diff --git a/data/ava2-itemshop/completion-168.json b/data/ava2-itemshop/completion-168.json index 88c0e628..31f62605 100644 --- a/data/ava2-itemshop/completion-168.json +++ b/data/ava2-itemshop/completion-168.json @@ -599,7 +599,17 @@ "original_price": 39, "source_type": "ITEM_USE", "source_subtype": "USE_CHANGE_ATTRIBUTE", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_product_costume_runtime.py", + "metin2-client/tests/wiki/test_costume_products.py" + ], + "remaining_acceptance": [ + "matching game/client/resource staging", + "actual item use and inventory consumption", + "relogin and channel change", + "Android device operation" + ] }, { "id": 74, @@ -607,7 +617,17 @@ "original_price": 69, "source_type": "ITEM_USE", "source_subtype": "USE_CHANGE_ATTRIBUTE", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_product_costume_runtime.py", + "metin2-client/tests/wiki/test_costume_products.py" + ], + "remaining_acceptance": [ + "matching game/client/resource staging", + "actual item use and inventory consumption", + "relogin and channel change", + "Android device operation" + ] }, { "id": 75, @@ -927,7 +947,17 @@ "original_price": 9, "source_type": "ITEM_USE", "source_subtype": "USE_TIME_CHARGE_PER", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_dragonsoul_alchemy.py", + "metin2-client/tools/server/ava2-items/tests/test_items.py" + ], + "remaining_acceptance": [ + "matching game/client/resource staging", + "actual item use and inventory consumption", + "relogin and channel change", + "Android device operation" + ] }, { "id": 145, @@ -935,7 +965,17 @@ "original_price": 17, "source_type": "ITEM_USE", "source_subtype": "USE_TIME_CHARGE_FIX", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_dragonsoul_alchemy.py", + "metin2-client/tools/server/ava2-items/tests/test_items.py" + ], + "remaining_acceptance": [ + "matching game/client/resource staging", + "actual item use and inventory consumption", + "relogin and channel change", + "Android device operation" + ] }, { "id": 146, @@ -1351,7 +1391,17 @@ "original_price": 19, "source_type": "ITEM_USE", "source_subtype": "USE_SPECIAL", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_economy.py", + "metin2-server/tests/features/test_gaya_runtime.py", + "metin2-client/tools/server/ava2-items/tests/test_items.py" + ], + "remaining_acceptance": [ + "actual item click and reconnect settlement", + "actual catalogue refresh/slot increase and count decrement", + "channel change and Android operation" + ] }, { "id": 234, @@ -1359,7 +1409,17 @@ "original_price": 19, "source_type": "ITEM_USE", "source_subtype": "USE_SPECIAL", - "status": "pending_implementation_and_live_acceptance" + "status": "implemented_pending_live_acceptance", + "evidence": [ + "metin2-server/tests/features/test_economy.py", + "metin2-server/tests/features/test_gaya_runtime.py", + "metin2-client/tools/server/ava2-items/tests/test_items.py" + ], + "remaining_acceptance": [ + "actual item click and reconnect settlement", + "actual catalogue refresh/slot increase and count decrement", + "channel change and Android operation" + ] }, { "id": 235, @@ -1409,5 +1469,13 @@ "source_subtype": "0", "status": "pending_implementation_and_live_acceptance" } - ] + ], + "platform_evidence": { + "android_resource_smoke": { + "status": "PASS", + "count": 168, + "evidence": "metin2-client/audit/evidence/ava2-products-device-20261021/device-icons.json", + "scope": "template/icon resource path load only; gameplay, actual purchase and item effects remain unverified" + } + } } diff --git a/data/ava2-itemshop/verified-products.json b/data/ava2-itemshop/verified-products.json index bdb95d46..d21ed66b 100644 --- a/data/ava2-itemshop/verified-products.json +++ b/data/ava2-itemshop/verified-products.json @@ -1,5 +1,5 @@ { - "count": 57, + "count": 49, "scope": "Existing implemented item systems only. Does not authorize production deployment.", "products": [ { @@ -182,24 +182,6 @@ "original_price": 60, "basis": "ported body/hair/mount-skin fixed enchants; game/src/port_costume_attr.cpp and make_items.ENCHANT_KEEP" }, - { - "id": 144, - "vnum": 100001, - "original_price": 9, - "basis": "dragon soul time charge (percent); game/src/char_item.cpp USE_TIME_CHARGE_PER and item.cpp GiveMoreTime_Per" - }, - { - "id": 145, - "vnum": 100002, - "original_price": 17, - "basis": "dragon soul time charge (fixed); game/src/char_item.cpp USE_TIME_CHARGE_FIX and item.cpp GiveMoreTime_Fix" - }, - { - "id": 149, - "vnum": 100500, - "original_price": 4, - "basis": "dragon soul strength refine material (holly bean); game/src/DragonSoul.cpp DSManager::DoRefineStrength" - }, { "id": 170, "vnum": 70002, @@ -313,36 +295,64 @@ "vnum": 54174, "original_price": 60, "basis": "ported body/hair/mount-skin fixed enchants; game/src/port_costume_attr.cpp and make_items.ENCHANT_KEEP" + } + ], + "candidates_pending_acceptance": [ + { + "id": 144, + "vnum": 100001, + "original_price": 9, + "basis": "dragon soul time charge (percent); game/src/char_item.cpp USE_TIME_CHARGE_PER and item.cpp GiveMoreTime_Per", + "status": "pending_real_behavior_and_platform_acceptance" + }, + { + "id": 145, + "vnum": 100002, + "original_price": 17, + "basis": "dragon soul time charge (fixed); game/src/char_item.cpp USE_TIME_CHARGE_FIX and item.cpp GiveMoreTime_Fix", + "status": "pending_real_behavior_and_platform_acceptance" + }, + { + "id": 149, + "vnum": 100500, + "original_price": 4, + "basis": "dragon soul strength refine material (holly bean); game/src/DragonSoul.cpp DSManager::DoRefineStrength", + "status": "pending_real_behavior_and_platform_acceptance" }, { "id": 233, "vnum": 39063, "original_price": 19, - "basis": "gaya market refresh item; game/src/port_gaya.cpp and char_item.cpp USE_RESET_GAYA_SHOP" + "basis": "gaya market refresh item; game/src/port_gaya.cpp and char_item.cpp USE_RESET_GAYA_SHOP", + "status": "pending_real_behavior_and_platform_acceptance" }, { "id": 234, "vnum": 39064, "original_price": 19, - "basis": "gaya market slot unlock item; game/src/port_gaya.cpp and char_item.cpp USE_EXPAND_GAYA_SHOP" + "basis": "gaya market slot unlock item; game/src/port_gaya.cpp and char_item.cpp USE_EXPAND_GAYA_SHOP", + "status": "pending_real_behavior_and_platform_acceptance" }, { "id": 240, "vnum": 77921, "original_price": 1, - "basis": "copper treasure key for box 77918; game/src/char_item.cpp single-count decrement" + "basis": "copper treasure key for box 77918; game/src/char_item.cpp single-count decrement", + "status": "pending_real_behavior_and_platform_acceptance" }, { "id": 241, "vnum": 77922, "original_price": 2, - "basis": "silver treasure key for box 77919; game/src/char_item.cpp single-count decrement" + "basis": "silver treasure key for box 77919; game/src/char_item.cpp single-count decrement", + "status": "pending_real_behavior_and_platform_acceptance" }, { "id": 242, "vnum": 77923, "original_price": 5, - "basis": "gold treasure key for box 77920; game/src/char_item.cpp single-count decrement" + "basis": "gold treasure key for box 77920; game/src/char_item.cpp single-count decrement", + "status": "pending_real_behavior_and_platform_acceptance" } ] } diff --git a/src/server/common/economy.h b/src/server/common/economy.h new file mode 100644 index 00000000..bd25960b --- /dev/null +++ b/src/server/common/economy.h @@ -0,0 +1,74 @@ +#pragma once +#include +#include +#include + +// Internal game/db protocol only. No client-supplied identity or price is trusted. +namespace PortEconomy { +constexpr uint8_t Header = 77; +enum Operation : uint8_t { List=1, Buy, Refund, Claim, Cancel, Withdraw, GayaBuy, GayaRefresh, GayaExpand, Status, GayaRetire, UiStatus }; +// Reserved terminal generation: preserve the catalogue as an audit tombstone. +constexpr uint64_t RetiredGeneration=INT64_MAX; +constexpr int64_t GoldLimit=2000000000000000LL; +#pragma pack(push,1) +struct Offer { uint32_t vnum=0,count=0;int32_t price=0;uint8_t bought=0; }; +#pragma pack(pop) +struct Reward { + uint32_t id=0,vnum=0,count=0; + int32_t sockets[3]={};uint8_t types[7]={};int16_t values[7]={};uint8_t extra[69]={}; +}; +struct Request { + uint32_t version=1,account=0,player=0; + uint8_t operation=0; + char token[33]={}; + alignas(8) uint64_t reference=0; + alignas(8) int64_t price=0; + alignas(8) int64_t expectedGold=0; + int32_t expectedGem=0,expectedOpen=0,deadline=0,nextDeadline=0; + uint32_t item=0,itemVnum=0,itemCount=0; + alignas(8) uint64_t generation=0; + uint8_t slot=0,rewardCount=0; + Offer offers[27],nextOffers[27]; + Reward rewards[10]; + Request() { std::memset(this,0,sizeof(*this));version=1; } +}; +struct Reply { uint32_t account,player;uint8_t ok;char message[240]; }; +static_assert(sizeof(Offer)==13 && sizeof(Reward)==116,"stable item/offer records"); +static_assert(sizeof(Request)==1976 && sizeof(Reply)==252,"stable internal request/reply layout"); +static_assert(sizeof(Request)<8192,"bounded durable request"); +inline bool Token(const char* s) { + if(s[32])return false; + for(unsigned i=0;i<32;++i)if(!((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f')))return false; + return true; +} +inline bool Offers(const Offer* offers) { + for(unsigned i=0;i<27;++i) { + const auto& o=offers[i]; + if(!o.vnum || !o.count || o.count>2000 || o.price<1 || o.price>1000000 || o.bought>1)return false; + } + return true; +} +inline bool Valid(const Request& r) { + if(r.version!=1 || !r.player || !r.account || !Token(r.token) || r.operationUiStatus || + r.expectedGold<0 || r.expectedGold>GoldLimit || r.expectedGem<0 || r.expectedGem>1000000 || + r.expectedOpen<0 || r.expectedOpen>18 || r.rewardCount>10)return false; + if(r.operation==UiStatus && (r.reference>1000000 || r.slot>2 || !r.generation || r.generation>UINT32_MAX))return false; + if(r.operation==Status && r.reference>1000000)return false; + if(r.operation!=GayaBuy && r.rewardCount)return false; + if(r.operation==List && (!r.item || !r.itemVnum || !r.itemCount || r.price<1 || r.price>GoldLimit))return false; + if((r.operation==Buy || r.operation==Refund || r.operation==Claim || r.operation==Cancel) && !r.reference)return false; + if(r.operation==GayaBuy && (r.slot>=27 || !Offers(r.offers) || !r.rewardCount))return false; + if(r.operation==GayaRefresh && (!Offers(r.nextOffers) || r.nextDeadline<=0 || (r.item && !r.itemCount)))return false; + if(r.operation==GayaExpand && (!r.item || !r.itemCount || r.expectedOpen>=18))return false; + for(unsigned i=0;i2000)return false; + for(unsigned j=0;j(data);static const char hex[]="0123456789abcdef"; + std::string out;out.reserve(size*2); + for(size_t i=0;i>4];out+=hex[p[i]&15];}return out; +} +} diff --git a/src/server/common/economy_mysql.h b/src/server/common/economy_mysql.h new file mode 100644 index 00000000..504957c3 --- /dev/null +++ b/src/server/common/economy_mysql.h @@ -0,0 +1,51 @@ +#pragma once +#include "economy_store.h" +#include +#include + +namespace PortEconomy { +// Use only on the DB main thread's direct connection. Automatic reconnection +// remains off for the entire lifetime, including ambiguous COMMIT recovery. +class Mysql { + MYSQL* connection; + bool active=false; + bool pinned=false; + unsigned previousTimeout=0; + unsigned long thread=0; +public: + uint64_t affected=0,inserted=0; + std::function afterStatement; + explicit Mysql(MYSQL* handle):connection(handle) { + // Reconnect only BEFORE entering the pinned transaction scope. Without + // this step a dead direct handle could keep pending orders retrying + // forever when no unrelated legacy query happens to reconnect it. + my_bool allowReconnect=true; + if(mysql_options(connection,MYSQL_OPT_RECONNECT,&allowReconnect)!=0 || mysql_ping(connection)!=0)return; + my_bool reconnect=false;pinned=mysql_options(connection,MYSQL_OPT_RECONNECT,&reconnect)==0; + thread=mysql_thread_id(connection); + Rows rows;uint64_t value=0; + if(Query("SELECT @@session.innodb_lock_wait_timeout",rows)&&rows.size()==1&&Number(rows[0][0],value,UINT32_MAX))previousTimeout=static_cast(value); + } + ~Mysql(){Rollback();if(previousTimeout){Rows rows;Query("SET SESSION innodb_lock_wait_timeout="+std::to_string(previousTimeout),rows);}my_bool reconnect=true;mysql_options(connection,MYSQL_OPT_RECONNECT,&reconnect);} + bool Query(const std::string& sql,Rows& rows) { + rows.clear();affected=0;inserted=0; + if(!pinned || mysql_thread_id(connection)!=thread || mysql_real_query(connection,sql.data(),static_cast(sql.size())))return false; + MYSQL_RES* result=mysql_store_result(connection); + if(result) { + MYSQL_ROW row;const unsigned fields=mysql_num_fields(result); + while((row=mysql_fetch_row(result))) { + const unsigned long* lengths=mysql_fetch_lengths(result);std::vector values; + for(unsigned i=0;i +#include +#include +#include + +namespace PortEconomy { +using Rows=std::vector>; +inline bool Number(const std::string& s,uint64_t& out,uint64_t max=UINT64_MAX) { + if(s.empty())return false;uint64_t n=0; + for(char c:s){if(c<'0'||c>'9'||uint64_t(c-'0')>max||n>(max-uint64_t(c-'0'))/10)return false;n=n*10+uint64_t(c-'0');} + out=n;return true; +} +// DB must supply Query(sql, rows), affected and inserted, plus Begin/Commit/Rollback. +// This store NEVER runs against an online character or an undrained cache. The +// DB coordinator owns that fence; game processes never execute these mutations. +template class Store { + DB& db; + std::function size; + std::string outcome; + uint64_t reference=0; + bool sqlOK=true; + static std::string N(uint64_t n){return std::to_string(n);} + bool Q(const std::string& sql,Rows& rows){if(!sqlOK)return false;sqlOK=db.Query(sql,rows);return sqlOK;} + bool Run(const std::string& sql){Rows rows;return Q(sql,rows);} + bool One(const std::string& sql,Rows& rows){return Q(sql,rows)&&rows.size()==1;} + bool Change(const std::string& sql){return Run(sql)&&db.affected==1;} + bool Reject(const char* why){outcome=why;return false;} + bool Quest(uint32_t pid,const char* state,uint64_t& value) { + Rows rows;if(!Q("SELECT lValue FROM quest WHERE dwPID="+N(pid)+" AND szName='gem' AND szState='"+state+"' FOR UPDATE",rows))return false; + value=0;return rows.empty()||(rows.size()==1&&Number(rows[0][0],value,INT32_MAX)); + } + bool SetQuest(uint32_t pid,const char* state,uint64_t value){ + return Run("INSERT INTO quest(dwPID,szName,szState,lValue) VALUES("+N(pid)+",'gem','"+state+"',"+N(value)+") ON DUPLICATE KEY UPDATE lValue=VALUES(lValue)"); + } + bool Catalog(const Request& r,Offer* offers,uint64_t& generation,int32_t& deadline) { + Rows rows;if(!Q("SELECT generation,deadline,offers FROM port_economy_gaya WHERE pid="+N(r.player)+" FOR UPDATE",rows))return false; + if(rows.empty()) { + if(r.generation || !Offers(r.offers) || r.deadline<0)return Reject("catalog_changed"); + std::memcpy(offers,r.offers,sizeof(r.offers));generation=0;deadline=r.deadline;return true; + } + uint64_t time=0; + if(rows.size()!=1 || !Number(rows[0][0],generation) || !Number(rows[0][1],time,INT32_MAX) || rows[0][2].size()!=sizeof(r.offers))return Reject("catalog_corrupt"); + std::memcpy(offers,rows[0][2].data(),sizeof(r.offers));deadline=static_cast(time); + if(!Offers(offers) || generation!=r.generation || deadline!=r.deadline || std::memcmp(offers,r.offers,sizeof(r.offers)))return Reject("catalog_changed"); + return true; + } + bool SaveCatalog(uint32_t pid,const Offer* offers,uint64_t generation,int32_t deadline) { + if(generation>=RetiredGeneration-1 || !Offers(offers) || deadline<0)return Reject("catalog_corrupt"); + return Run("INSERT INTO port_economy_gaya(pid,generation,deadline,offers) VALUES("+N(pid)+","+N(generation+1)+","+N(static_cast(deadline))+",X'"+Hex(offers,27*sizeof(Offer))+"') ON DUPLICATE KEY UPDATE generation=VALUES(generation),deadline=VALUES(deadline),offers=VALUES(offers)"); + } + // Mall uses a 5x9 grid per page, three pages. Retain original item IDs and + // every stored item column. Unknown sizes and malformed grids fail closed. + bool MallCell(uint32_t account,uint32_t vnum,unsigned& cell) { + const unsigned height=size(vnum);if(height<1 || height>3)return Reject("item_proto"); + std::array used={};Rows rows; + if(!Q("SELECT pos,vnum FROM item WHERE owner_id="+N(account)+" AND window='MALL' FOR UPDATE",rows))return false; + for(const auto& row:rows) { + uint64_t pos=0,id=0;if(!Number(row[0],pos,134)||!Number(row[1],id,UINT32_MAX))return Reject("mall_corrupt"); + const unsigned h=size(static_cast(id));if(h<1 || h>3 || (pos%45)/5+h>9)return Reject("mall_corrupt"); + for(unsigned j=0;j(pos)+5*j;if(used[at])return Reject("mall_corrupt");used[at]=true;} + } + for(unsigned pos=0;pos<135;++pos) { + if((pos%45)/5+height>9)continue;bool free=true; + for(unsigned j=0;j(r.price))+",'OPEN')"))return false; + reference=db.inserted;return reference!=0; + case Buy: + if(!One("SELECT owner,item,price,state FROM port_economy_listings WHERE id="+N(r.reference)+" FOR UPDATE",rows)|| + !Number(rows[0][0],a,UINT32_MAX)||!Number(rows[0][1],b,UINT32_MAX)||!Number(rows[0][2],c,GoldLimit)||rows[0][3]!="OPEN"||a==r.player||!c||c>gold||r.price!=static_cast(c))return Reject("listing_changed"); + if(!Change("UPDATE player SET gold=gold-"+N(c)+" WHERE id="+pid+" AND gold>="+N(c))|| + !Change("INSERT INTO port_economy_orders(request,listing,buyer,account,price,state) VALUES('"+std::string(r.token)+"',"+N(r.reference)+","+pid+","+aid+","+N(c)+",'READY')"))return false; + reference=db.inserted; + return Change("UPDATE port_economy_listings SET state='RESERVED',active_order="+N(reference)+" WHERE id="+N(r.reference)); + case Refund: case Claim: + if(!One("SELECT listing,price,state FROM port_economy_orders WHERE id="+N(r.reference)+" AND buyer="+pid+" AND account="+aid+" FOR UPDATE",rows)|| + !Number(rows[0][0],a)||!Number(rows[0][1],b,GoldLimit))return Reject("order_missing"); + if(rows[0][2]==(r.operation==Claim?"CLAIMED":"REFUNDED")){reference=r.reference;return true;} + if(rows[0][2]!="READY")return Reject("order_terminal"); + if(!One("SELECT owner,item,active_order FROM port_economy_listings WHERE id="+N(a)+" AND state='RESERVED' FOR UPDATE",rows)|| + !Number(rows[0][0],c,UINT32_MAX)||!Number(rows[0][1],d,UINT32_MAX)||rows[0][2]!=N(r.reference))return Reject("custody_changed"); + if(r.operation==Refund) { + if(gold>uint64_t(GoldLimit)-b)return Reject("gold_limit"); + if(!Change("UPDATE player SET gold=gold+"+N(b)+" WHERE id="+pid)||!Change("UPDATE port_economy_listings SET state='OPEN',active_order=0 WHERE id="+N(a)))return false; + } else { + if(!One("SELECT vnum FROM port_economy_custody WHERE id="+N(d)+" FOR UPDATE",rows))return Reject("custody_missing"); + uint64_t vnum=0;if(!Number(rows[0][0],vnum,UINT32_MAX)||!Deliver(static_cast(d),r.account,static_cast(vnum)))return false; + if(!Run("INSERT INTO port_economy_credit(pid,amount) VALUES("+N(c)+",0) ON DUPLICATE KEY UPDATE pid=VALUES(pid)")|| + !One("SELECT amount FROM port_economy_credit WHERE pid="+N(c)+" FOR UPDATE",rows)||!Number(rows[0][0],c,GoldLimit)||c>uint64_t(GoldLimit)-b)return Reject("seller_credit_limit"); + // Owner was decoded above; use the immutable listing relationship. + if(!Change("UPDATE port_economy_credit SET amount=amount+"+N(b)+" WHERE pid=(SELECT owner FROM port_economy_listings WHERE id="+N(a)+")")|| + !Change("UPDATE port_economy_listings SET state='SOLD' WHERE id="+N(a)))return false; + } + reference=r.reference; + return Change("UPDATE port_economy_orders SET state='"+std::string(r.operation==Claim?"CLAIMED":"REFUNDED")+"' WHERE id="+N(r.reference)); + case Cancel: + if(!One("SELECT item FROM port_economy_listings WHERE id="+N(r.reference)+" AND owner="+pid+" AND state='OPEN' FOR UPDATE",rows)||!Number(rows[0][0],a,UINT32_MAX))return Reject("listing_changed"); + if(!One("SELECT vnum FROM port_economy_custody WHERE id="+N(a)+" FOR UPDATE",rows)||!Number(rows[0][0],b,UINT32_MAX)||!Deliver(static_cast(a),r.account,static_cast(b)))return false; + reference=r.reference;return Change("UPDATE port_economy_listings SET state='CANCELLED' WHERE id="+N(r.reference)); + case Withdraw: + if(!One("SELECT amount FROM port_economy_credit WHERE pid="+pid+" FOR UPDATE",rows)||!Number(rows[0][0],a,GoldLimit)||!a)return Reject("no_credit"); + if(gold>uint64_t(GoldLimit)-a)return Reject("gold_limit"); + return Change("UPDATE player SET gold=gold+"+N(a)+" WHERE id="+pid)&&Change("UPDATE port_economy_credit SET amount=0 WHERE pid="+pid); + case GayaRetire: { + // Explicit retirement never destroys a positive wallet, custody, + // refundable order or seller credit. Keep offers/deadline for audit. + if(!Quest(r.player,"points",a)||!Quest(r.player,"open_slot",b)|| + a!=static_cast(r.expectedGem)||b!=static_cast(r.expectedOpen))return Reject("wallet_changed"); + if(a)return Reject("gaya_balance_remaining"); + if(!One("SELECT (EXISTS(SELECT 1 FROM port_economy_listings WHERE owner="+pid+" AND state IN('OPEN','RESERVED')))+(EXISTS(SELECT 1 FROM port_economy_orders WHERE buyer="+pid+" AND state='READY'))+(EXISTS(SELECT 1 FROM port_economy_credit WHERE pid="+pid+" AND amount<>0))",rows)||rows[0][0]!="0")return Reject("assets_remaining"); + if(!One("SELECT generation,deadline,offers FROM port_economy_gaya WHERE pid="+pid+" FOR UPDATE",rows)|| + !Number(rows[0][0],c,RetiredGeneration)||rows[0][2].size()!=sizeof(r.offers))return Reject("catalog_corrupt"); + Offer retained[27];std::memcpy(retained,rows[0][2].data(),sizeof(retained)); + if(!Offers(retained))return Reject("catalog_corrupt"); + reference=c; + if(c==RetiredGeneration)return true; + return Change("UPDATE port_economy_gaya SET generation="+N(RetiredGeneration)+" WHERE pid="+pid); + } + case GayaBuy: case GayaRefresh: case GayaExpand: { + if(!Q("SELECT generation FROM port_economy_gaya WHERE pid="+pid+" FOR UPDATE",rows))return false; + if(!rows.empty()&&(!Number(rows[0][0],a,RetiredGeneration)||a==RetiredGeneration))return Reject("gaya_retired"); + uint64_t gem=0,open=0,generation=0;int32_t deadline=0;Offer offers[27]; + if(!Quest(r.player,"points",gem)||!Quest(r.player,"open_slot",open)||gem!=static_cast(r.expectedGem)||open!=static_cast(r.expectedOpen))return Reject("wallet_changed"); + if(r.operation==GayaExpand) { + if(open>=18||!Consume(r,39064))return Reject("consumable_changed"); + return SetQuest(r.player,"open_slot",open+1); + } + if(!Catalog(r,offers,generation,deadline))return false; + if(r.operation==GayaRefresh) { + if(r.nextDeadlinea)return Reject("refresh_early");} + for(const auto& offer:r.nextOffers)if(offer.bought)return Reject("catalog_changed"); + return SaveCatalog(r.player,r.nextOffers,generation,r.nextDeadline)&&SetQuest(r.player,"left_time",static_cast(r.nextDeadline)); + } + auto& offer=offers[r.slot]; + if(offer.bought|| (r.slot>=9 && open(offer.price))return Reject("offer_unavailable"); + uint64_t total=0; + for(unsigned i=0;i(offer.price))&&SaveCatalog(r.player,offers,generation,deadline); + } + default:return Reject("invalid_operation"); + } + } +public: + Store(DB& database,std::function itemSize):db(database),size(itemSize){} + // Readiness is checked on every entry, so a missing/nontransactional table + // never silently downgrades a payment to autocommit. + bool Ready() { + Rows rows;sqlOK=true; + if(!One("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('player','item','quest','port_economy_custody','port_economy_requests','port_economy_pending','port_economy_listings','port_economy_orders','port_economy_credit','port_economy_gaya','port_economy_version','port_economy_account_lock','port_economy_item_reservations')",rows)||rows[0][0]!="13")return false; + if(!One("SELECT version FROM port_economy_version WHERE id=1",rows)||rows[0][0]!="1")return false; + Rows item,custody; + return Q("SHOW COLUMNS FROM item",item)&&Q("SHOW COLUMNS FROM port_economy_custody",custody)&&item==custody; + } + bool Enqueue(const Request& r) { + if(!Valid(r)||(r.operation==Status||r.operation==UiStatus)||!Ready()||!db.Begin())return false; + Rows rows;bool success=false; + const std::string token=r.token,body=Hex(&r,sizeof(r)); + if(Q("SELECT account,pid,body FROM port_economy_requests WHERE token='"+token+"' FOR UPDATE",rows)) { + if(!rows.empty())success=rows.size()==1&&rows[0][0]==N(r.account)&&rows[0][1]==N(r.player)&&rows[0][2].size()==sizeof(r)&&!std::memcmp(rows[0][2].data(),&r,sizeof(r)); + else { + success=true; + for(unsigned i=0;i(r.expectedGold))outcome="wallet_changed"; + else { + // Validation failures may happen after tentative writes (e.g. mall + // fills midway through a multi-stack reward). Roll back to savepoint. + if(!Run("SAVEPOINT economy_operation")){db.Rollback();return Retry;} + if(!Apply(r,gold)) { + if(!sqlOK){db.Rollback();return Retry;} + if(!Run("ROLLBACK TO SAVEPOINT economy_operation")){db.Rollback();return Retry;} + if(outcome=="ok")outcome="state_changed";reference=0; + } + } + if(!Change("UPDATE port_economy_requests SET state='DONE',result='"+outcome+"',reference="+N(reference)+" WHERE token='"+token+"'")|| + !Change("DELETE FROM port_economy_pending WHERE pid="+N(pid))||!db.Commit()){db.Rollback();return Retry;} + return Settled; + } + const std::string& Outcome()const{return outcome;} + uint64_t Reference()const{return reference;} +}; +} diff --git a/src/server/common/economy_view.h b/src/server/common/economy_view.h new file mode 100644 index 00000000..73f0163d --- /dev/null +++ b/src/server/common/economy_view.h @@ -0,0 +1,70 @@ +#pragma once +#include "economy_store.h" + +namespace PortEconomy { +// Bounded, ASCII-only presentation over the existing authenticated DB reply. +// Build the complete snapshot before emitting any frames. No UI read mutates +// wallets, item ownership or order state, and no display slot is an asset ID. +constexpr unsigned ViewPageSize=20; +inline bool SignedNumber(const std::string& text,int64_t& out,int64_t minimum,int64_t maximum) { + const bool negative=!text.empty()&&text[0]=='-';uint64_t value=0; + if(!Number(negative?text.substr(1):text,value,negative?static_cast(-minimum):static_cast(maximum)))return false; + out=negative?-static_cast(value):static_cast(value);return out>=minimum&&out<=maximum; +} +inline bool HexBytes(const std::string& text,size_t bytes) { + if(text.size()!=bytes*2)return false; + for(char c:text)if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false; + return true; +} +template bool View(DB& db,const Request& r,std::function height,std::vector& frames) { + frames.clear();Rows rows;if(!Valid(r)||r.operation!=UiStatus)return false; + // Transaction-scoped isolation applies to this read only, not later wallet + // settlements on the shared direct connection. + if(!db.Query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",rows)||!db.Begin())return false; + auto fail=[&](){db.Rollback();frames.clear();return false;}; + const auto pid=std::to_string(r.player),aid=std::to_string(r.account),seq=std::to_string(r.generation); + if(!db.Query("SELECT amount FROM port_economy_credit WHERE pid="+pid,rows)||rows.size()>1)return fail(); + uint64_t credit=0;if(!rows.empty()&&!Number(rows[0][0],credit,GoldLimit))return fail(); + std::string columns="c.vnum,c.count,"+std::string(r.slot==2?"o.state":"l.state")+",c.socket0,c.socket1,c.socket2"; + for(unsigned i=0;i<7;++i)columns+=",c.attrtype"+std::to_string(i)+",c.attrvalue"+std::to_string(i); + columns+=",HEX(c.port_extra)"; + std::string sql=r.slot==2 ? "SELECT o.id,o.price,l.owner,"+columns+" FROM port_economy_orders o JOIN port_economy_listings l ON l.id=o.listing LEFT JOIN port_economy_custody c ON c.id=l.item WHERE o.buyer="+pid+" AND o.account="+aid+" AND o.state='READY'" : + "SELECT l.id,l.price,l.owner,"+columns+" FROM port_economy_listings l LEFT JOIN port_economy_custody c ON c.id=l.item WHERE "+ + (r.slot==1?"l.owner="+pid+" AND l.state IN('OPEN','RESERVED')":std::string("l.state='OPEN'")+(r.item?" AND l.owner="+std::to_string(r.item):"")); + sql+=" ORDER BY "+std::string(r.slot==2?"o.id":"l.id")+" DESC LIMIT 21 OFFSET "+std::to_string(r.reference*ViewPageSize); + if(!db.Query(sql,rows)||rows.size()>ViewPageSize+1)return fail(); + const bool more=rows.size()>ViewPageSize;if(more)rows.pop_back(); + frames.push_back("MTECON1 begin "+seq+" "+std::to_string(r.slot)+" "+std::to_string(r.reference)+" "+std::to_string(rows.size())+" "+std::to_string(more)+" "+std::to_string(credit)); + for(size_t index=0;index(vnum));if(state==3||size<1||size>3)return fail(); + std::string item="MTECON1 row "+seq+" "+std::to_string(index)+" "+std::to_string(id)+" "+std::to_string(price)+" "+std::to_string(owner)+" "+std::to_string(state)+" "+std::to_string(vnum)+" "+std::to_string(count)+" "+std::to_string(size); + for(unsigned i=6;i<9;++i){int64_t socket=0;if(!SignedNumber(row[i],socket,INT32_MIN,INT32_MAX))return fail();item+=" "+std::to_string(socket);} + frames.push_back(item); + uint8_t attrs[21]={}; + for(unsigned i=0;i<7;++i){uint64_t type=0;int64_t value=0; + if(!Number(row[9+2*i],type,UINT8_MAX)||!SignedNumber(row[10+2*i],value,INT16_MIN,INT16_MAX))return fail(); + const auto bits=static_cast(value);attrs[3*i]=static_cast(type);attrs[3*i+1]=static_cast(bits&255);attrs[3*i+2]=static_cast(bits>>8); + } + std::string extra=row[23];if(extra.empty())extra=std::string(138,'0');if(!HexBytes(extra,69))return fail(); + frames.push_back("MTECON1 meta "+seq+" "+std::to_string(index)+" "+Hex(attrs,sizeof(attrs))+extra); + } + // A supplied receipt is scoped to the current account/player. On a fresh + // process the latest result is informational; actionable assets come from + // the authoritative orders/listings/credit views above. + if(!db.Query("SELECT state,result,reference FROM port_economy_requests WHERE pid="+pid+" AND account="+aid+ + (std::string(r.token)==std::string(32,'0')?" ORDER BY created_at DESC,token DESC LIMIT 1":" AND token='"+std::string(r.token)+"'"),rows)||rows.size()>1)return fail(); + if(!rows.empty()) { + uint64_t reference=0; + if(rows[0].size()!=3||!Number(rows[0][2],reference)||rows[0][1].size()>64||(rows[0][0]!="DONE"&&rows[0][0]!="PENDING"))return fail(); + frames.push_back("MTECON1 result "+seq+" "+rows[0][0]+" "+(rows[0][1].empty()?std::string("00"):Hex(rows[0][1].data(),rows[0][1].size()))+" "+std::to_string(reference)); + } + frames.push_back("MTECON1 end "+seq); + for(const auto& frame:frames)if(frame.size()>=sizeof(Reply::message))return fail(); + if(!db.Commit())return fail();return true; +} +} diff --git a/src/server/common/gaya_catalog.h b/src/server/common/gaya_catalog.h new file mode 100644 index 00000000..e96a7ad3 --- /dev/null +++ b/src/server/common/gaya_catalog.h @@ -0,0 +1,117 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A separate lifetime lock survives replacement of the catalogue inode. Wallet +// and item persistence are separate: this file is not an economic transaction. +class PortGayaCatalogFile { + int directory_=-1, lock_=-1; + bool healthy_=false; + std::string name_, error_; + bool Fail(const char* reason) { healthy_=false;error_=reason;return false; } + static uint32_t Hash(const std::string& s) { + uint32_t h=2166136261u;for(unsigned char c:s){h^=c;h*=16777619u;}return h; + } + static bool Number(const std::string& s,uint64_t maximum,uint64_t& out) { + if(s.empty())return false; + uint64_t n=0; + for(char c:s){if(c<'0'||c>'9'||uint64_t(c-'0')>maximum||n>(maximum-uint64_t(c-'0'))/10)return false;n=n*10+uint64_t(c-'0');} + out=n;return true; + } + template static bool Valid(unsigned slot,const Item& item) { + return slot<27 && item.itemVnum && item.itemCount>0 && item.itemCount<=2000 && item.itemPrice>0 && item.itemPrice<=1000000; + } +public: + enum Result { Error, Missing, Loaded }; + PortGayaCatalogFile()=default; + PortGayaCatalogFile(const PortGayaCatalogFile&)=delete; + PortGayaCatalogFile& operator=(const PortGayaCatalogFile&)=delete; + ~PortGayaCatalogFile(){if(lock_>=0)close(lock_);if(directory_>=0)close(directory_);} + bool Ready()const{return healthy_;} + const std::string& ErrorText()const{return error_;} + bool Open(const std::string& directory,uint32_t player) { + if(directory_>=0 || !player)return Fail("invalid or already opened catalogue"); + // Only the configured data directory is created. Parent directories must exist. + if(mkdir(directory.c_str(),0700)!=0 && errno!=EEXIST)return Fail("cannot create catalogue directory"); + directory_=open(directory.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW); + if(directory_<0)return Fail("cannot open catalogue directory"); + name_=std::to_string(player); + lock_=openat(directory_,(name_+".lock").c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600); + if(lock_<0)return Fail("cannot open catalogue lock"); + struct stat info={}; + if(fstat(lock_,&info)!=0 || !S_ISREG(info.st_mode) || flock(lock_,LOCK_EX|LOCK_NB)!=0) + return Fail("catalogue already owned or invalid lock file"); + healthy_=true;return true; + } + template Result Load(std::map& output,int& refresh) { + if(!healthy_)return Error; + int fd=openat(directory_,name_.c_str(),O_RDONLY|O_NOFOLLOW); + if(fd<0){if(errno==ENOENT){output.clear();refresh=0;return Missing;}Fail("cannot read catalogue");return Error;} + struct stat info={}; + if(fstat(fd,&info)!=0 || !S_ISREG(info.st_mode) || info.st_size<1 || info.st_size>16384){close(fd);Fail("invalid catalogue file");return Error;} + std::string bytes;char buf[1024];bool readOK=true; + for(;;){ssize_t n=read(fd,buf,sizeof(buf));if(n<0&&errno==EINTR)continue;if(n<0){readOK=false;break;}if(!n)break;bytes.append(buf,size_t(n));if(bytes.size()>16384){readOK=false;break;}} + close(fd); + if(!readOK || bytes.empty() || bytes.back()!='\n'){Fail("truncated catalogue");return Error;} + const auto newline=bytes.find('\n');std::string header=bytes.substr(0,newline),body=bytes.substr(newline+1); + int decodedRefresh=0; + if(header!="index-vnum-count-price-buyed") { + std::istringstream fields(header);std::string version,deadline,checksum,tail;uint64_t parsed=0; + if(!(fields>>version>>deadline>>checksum) || fields>>tail || version!="gaya-v2" || !Number(deadline,INT32_MAX,parsed) || checksum!=std::to_string(Hash(body))) { + Fail("invalid catalogue header or checksum");return Error; + } + decodedRefresh=static_cast(parsed); + } + std::map decoded;std::istringstream rows(body);std::string line; + while(std::getline(rows,line)) { + std::istringstream fields(line);std::string tokens[5],tail;uint64_t values[5]={}; + if(!(fields>>tokens[0]>>tokens[1]>>tokens[2]>>tokens[3]>>tokens[4]) || fields>>tail || + !Number(tokens[0],26,values[0]) || !Number(tokens[1],UINT32_MAX,values[1]) || + !Number(tokens[2],2000,values[2]) || !Number(tokens[3],1000000,values[3]) || !Number(tokens[4],1,values[4])) { + Fail("invalid catalogue row");return Error; + } + Item item={};item.itemVnum=static_cast(values[1]);item.itemCount=static_cast(values[2]);item.itemPrice=static_cast(values[3]);item.itemBuyed=values[4]!=0; + if(!Valid(unsigned(values[0]),item) || !decoded.emplace(uint8_t(values[0]),item).second){Fail("invalid or duplicate catalogue slot");return Error;} + } + if(decoded.empty()){Fail("empty catalogue");return Error;} + output.swap(decoded);refresh=decodedRefresh;return Loaded; + } + template bool Save(const std::map& items,int refresh) { + if(!healthy_)return false; + if(items.empty() || items.size()>27 || refresh<0)return Fail("invalid catalogue snapshot"); + std::ostringstream rows; + for(const auto& row:items){if(!Valid(row.first,row.second))return Fail("invalid catalogue snapshot row");const auto& i=row.second;rows<INT32_MAX-period || previous<0)return false; + int64_t result=now+period; + if(elapsedCadence && previous>0) { + if(previous>now)result=previous; + else result=int64_t(previous)+((now-previous)/period+1)*period; + } + if(result>INT32_MAX)return false; + next=static_cast(result);return true; +} diff --git a/src/server/common/gold_bounds.h b/src/server/common/gold_bounds.h new file mode 100644 index 00000000..58ea4b41 --- /dev/null +++ b/src/server/common/gold_bounds.h @@ -0,0 +1,10 @@ +#pragma once +#include +// Compare against bounded differences: never negate caller-supplied INT64_MIN. +inline bool PortGoldCanChange(int64_t balance,int64_t delta,int64_t maximum) { + return maximum>=0 && balance>=0 && balance<=maximum && delta>=-balance && delta<=maximum-balance; +} +inline bool PortGoldTotal(int64_t price,uint32_t count,int64_t maximum,int64_t& total) { + if(price<=0 || !count || maximum<0 || price>maximum/int64_t(count))return false; + total=price*int64_t(count);return true; +} diff --git a/src/server/common/item_length.h b/src/server/common/item_length.h index 93ff479d..0b9d07e4 100755 --- a/src/server/common/item_length.h +++ b/src/server/common/item_length.h @@ -81,7 +81,6 @@ enum EItemTypes ITEM_PET, // PORT: AVA2 growable pets, explicit item type 37. }; -enum EPetSubTypes { PET_LEVELABLE, PET_EGG, PET_TRANSPORTBOX, PET_PROTEIN, PET_CHANGE_NAME_ITEM, PET_DEW, PET_SKILL, PET_PRIMIUM_FEEDSTUFF, PET_ATTR_CHANGE, PET_ATTR_DETERMINE, PET_EXPFOOD_PER, PET_SKILL_DEL_BOOK, PET_SKILL_ALL_DEL_BOOK, PET_EXPFOOD, PET_FEEDSTUFF }; enum EShiningSubTypes { SHINING_WEAPON, SHINING_ARMOR, SHINING_SPECIAL }; enum EMetinSubTypes diff --git a/src/server/common/length.h b/src/server/common/length.h index ce758d84..d2ed0c79 100755 --- a/src/server/common/length.h +++ b/src/server/common/length.h @@ -1,6 +1,9 @@ #ifndef __INC_METIN_II_LENGTH_H__ #define __INC_METIN_II_LENGTH_H__ +// Feature-dependent wire layouts must not depend on a caller's include order. +#include "service.h" + #define WORD_MAX 0xffff enum EMisc { @@ -482,7 +485,9 @@ enum EApplyTypes // PORT AVA2 bonus numbering (AVA2 common/length.h): 92-138 are AVA2 applies not ported yet, // kept free so later ports and the client item_proto keep AVA2's numbers. // AVA2 ELEMENT_NEW_BONUSES: attack bonus % against monsters of the element (RACE_FLAG_ATT_*), on the talismans. - APPLY_ENCHANT_ELEC = 123, + APPLY_RESIST_MAGIC_REDUCTION = 98, // AVA2 ENABLE_MAGIC_REDUCTION_SYSTEM. + APPLY_RESIST_HUMAN = 99, // AVA2 growing-pet skill 17. + APPLY_ENCHANT_ELEC = 123, APPLY_ENCHANT_FIRE = 124, APPLY_ENCHANT_ICE = 125, APPLY_ENCHANT_WIND = 126, diff --git a/src/server/common/offline_shop_safety.h b/src/server/common/offline_shop_safety.h new file mode 100644 index 00000000..7426a7de --- /dev/null +++ b/src/server/common/offline_shop_safety.h @@ -0,0 +1,5 @@ +#pragma once +// The legacy offline shop has no durable, atomic custody/payment/delivery order. +// Keep ALL mutation and startup expiry cleanup closed until the replacement has +// passed cross-core DB-failure recovery acceptance. No event/GM flag can bypass it. +inline bool PortOfflineShopEconomyReady() { return false; } diff --git a/src/server/common/point_journal.h b/src/server/common/point_journal.h new file mode 100644 index 00000000..22fc79c0 --- /dev/null +++ b/src/server/common/point_journal.h @@ -0,0 +1,131 @@ +#pragma once +#include "ava2_itemshop.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A separate lifetime lock survives atomic compaction. The current data file is +// locked too, so an already-running legacy append-only writer excludes startup. +class PointJournal { + struct Entry { Ava2ShopRequest request; uint64_t created; }; + int fd_=-1, lock_=-1, directory_=-1; + bool healthy_=false; + uint64_t bytes_=0; + std::string name_, error_; + std::map pending_; + bool Fail(const char* reason){healthy_=false;error_=reason;return false;} + static uint32_t Hash(const std::string& data){uint32_t h=2166136261u;for(unsigned char c:data){h^=c;h*=16777619u;}return h;} + static bool Token(const std::string& s){if(s.size()!=32)return false;for(char c:s)if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false;return true;} + static bool Terminal(unsigned status){return status==0 || status==1 || status==2 || status==7;} + static bool Regular(int fd){struct stat info={};return fstat(fd,&info)==0 && S_ISREG(info.st_mode);} + static bool Unsigned(std::istringstream& in,uint64_t& value,uint64_t maximum){ + std::string text;if(!(in>>text)||text.empty())return false;value=0; + for(unsigned char c:text){if(c<'0'||c>'9')return false;const unsigned digit=c-'0';if(value>maximum/10 || (value==maximum/10 && digit>maximum%10))return false;value=value*10+digit;}return true; + } + static Ava2ShopRequest Canonical(const Ava2ShopRequest& r){ + Ava2ShopRequest result={};result.operation=3;result.account=r.account;result.player=r.player;result.product=r.product;result.count=r.count;result.expectedVnum=r.expectedVnum;memcpy(result.token,r.token,32);return result; + } + static std::string IntentPayload(const Entry& entry){ + const auto& r=entry.request;std::ostringstream out;out<<"INTENT v2 "<(n);}return true; + } + bool Append(const std::string& payload){ + if(!healthy_)return false;const auto line=Record(payload); + if(!WriteAll(fd_,line))return Fail("journal write failed; issuance paused; retain original journal for repair"); + if(fsync(fd_)!=0)return Fail("journal fsync failed; issuance paused; settlement may replay with same token"); + bytes_+=line.size();return true; + } +public: + PointJournal()=default; + PointJournal(const PointJournal&)=delete; + ~PointJournal(){if(fd_>=0)close(fd_);if(lock_>=0)close(lock_);if(directory_>=0)close(directory_);} + bool Ready()const{return healthy_;} + const std::string& Error()const{return error_;} + bool NeedsCompaction()const{return healthy_ && bytes_>=1024*1024 && (bytes_-4096)/512>pending_.size();} + bool Open(const std::string& path,std::map& pending){ + if(fd_>=0 || directory_>=0)return Fail("journal already open"); + const auto slash=path.rfind('/');const std::string dir=slash==std::string::npos?".":slash==0?"/":path.substr(0,slash); + name_=slash==std::string::npos?path:path.substr(slash+1); + if(name_.empty()||name_=="."||name_=="..")return Fail("invalid journal filename"); + if(mkdir(dir.c_str(),0700)!=0&&errno!=EEXIST)return Fail("cannot create journal directory"); + directory_=open(dir.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);if(directory_<0)return Fail("cannot open journal directory"); + const std::string lockName=name_+".lock"; + lock_=openat(directory_,lockName.c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600); + if(lock_<0||!Regular(lock_)||flock(lock_,LOCK_EX|LOCK_NB)!=0)return Fail("journal lock unavailable or already owned"); + fd_=openat(directory_,name_.c_str(),O_RDWR|O_CREAT|O_APPEND|O_NOFOLLOW,0600); + if(fd_<0||!Regular(fd_))return Fail("cannot open regular journal"); + if(flock(fd_,LOCK_EX|LOCK_NB)!=0)return Fail("journal already owned by another process"); + struct stat info={};if(fstat(fd_,&info)!=0||info.st_size<0)return Fail("cannot stat journal");bytes_=static_cast(info.st_size); + if(fsync(fd_)!=0||fsync(lock_)!=0||fsync(directory_)!=0)return Fail("cannot persist journal directory entry"); + const int reader=dup(fd_);if(reader<0)return Fail("cannot duplicate journal reader"); + FILE* input=fdopen(reader,"r");if(!input){close(reader);return Fail("cannot read journal");} + pending.clear();rewind(input);char line[512];bool valid=true; + while(fgets(line,sizeof(line),input)){ + const size_t size=strlen(line);if(!size||line[size-1]!='\n'){valid=false;break;} + std::string raw(line,size-1);std::istringstream fields(raw);std::string op,version,token,tail;fields>>op>>version>>token; + if(!Token(token)||(version!="v1"&&version!="v2")){valid=false;break;} + if(version=="v2"){ + const auto split=raw.rfind(' ');unsigned checksum=0;char extra=0; + if(split==std::string::npos||sscanf(raw.c_str()+split+1,"%8x%c",&checksum,&extra)!=1||checksum!=Hash(raw.substr(0,split))){valid=false;break;} + fields.clear();fields.str(raw.substr(0,split));fields>>op>>version>>token; + } + if(op=="INTENT"){ + Entry entry={};auto& r=entry.request;r.operation=3;uint64_t account=0,player=0,product=0,count=0,level=0; + if(!Unsigned(fields,account,UINT32_MAX)||!Unsigned(fields,player,UINT32_MAX)||!Unsigned(fields,product,UINT32_MAX)|| + !Unsigned(fields,count,1000000)||!Unsigned(fields,level,255)||!Unsigned(fields,entry.created,UINT64_MAX)||fields>>tail||!account||!player||!product||!count||!level){valid=false;break;} + r.account=static_cast(account);r.player=static_cast(player);r.product=static_cast(product);r.count=static_cast(count);r.expectedVnum=static_cast(level);memcpy(r.token,token.c_str(),32); + const auto found=pending_.find(token); + if(found!=pending_.end()&&memcmp(&found->second.request,&r,sizeof(r))!=0){valid=false;break;} + pending_[token]=entry;pending[token]=r; + }else if(op=="DONE"){ + uint64_t status=0,granted=0,balance=0,created=0; + if(!Unsigned(fields,status,255)||!Terminal(static_cast(status))||!Unsigned(fields,granted,1000000)||!Unsigned(fields,balance,INT64_MAX)||!Unsigned(fields,created,UINT64_MAX)||fields>>tail||(status!=0&&granted!=0)){valid=false;break;} + const auto found=pending_.find(token); + if(found!=pending_.end() && granted>found->second.request.count){valid=false;break;} + pending_.erase(token);pending.erase(token); + }else{valid=false;break;} + } + if(ferror(input))valid=false;fclose(input); + if(!valid)return Fail("corrupt journal: preserve bytes, pause issuance and repair tail before resuming"); + healthy_=true;return true; + } + bool Intent(const Ava2ShopRequest& r){ + if(r.operation!=3 || r.token[32] || !Token(std::string(r.token,32)) || !r.account || !r.player || !r.product || !r.count || r.count>1000000 || !r.expectedVnum || r.expectedVnum>255){error_="invalid reward intent";return false;} + Entry entry={Canonical(r),static_cast(time(0))};const auto found=pending_.find(r.token); + if(found!=pending_.end() && memcmp(&found->second.request,&entry.request,sizeof(r))!=0){error_="conflicting reward intent";return false;} + if(!Append(IntentPayload(entry)))return false;pending_[r.token]=entry;return true; + } + bool Done(const char* token,uint8_t status,uint32_t granted,int64_t balance){ + if(!token || strnlen(token,33)!=32 || !Token(std::string(token,32)) || balance<0 || !Terminal(status) || (status!=0 && granted!=0)){error_="invalid reward completion";return false;} + const auto found=pending_.find(token); + if(found==pending_.end() || granted>found->second.request.count){error_="unknown or excessive reward completion";return false;} + std::ostringstream out;out<<"DONE v2 "<='0' && c<='9'?c-'0':c>='A' && c<='F'?c-'A'+10:c>='a' && c<='f'?c-'a'+10:-1;}; - auto p=reinterpret_cast(&extra); - for(unsigned i=0;i(&decoded); + for(unsigned i=0;i((a<<4)|b);} + if(decoded.name[24]!=0)return false; + extra=decoded;return true; } diff --git a/src/server/common/shop_economy.h b/src/server/common/shop_economy.h new file mode 100644 index 00000000..21fc1aa5 --- /dev/null +++ b/src/server/common/shop_economy.h @@ -0,0 +1,16 @@ +#pragma once +#include "gold_bounds.h" +// Free NPC items are valid. Invalid or unrepresentable quotes never mutate output. +inline bool PortShopQuote(int64_t price, bool otherEmpire, int64_t maximum, int64_t& quote) { + const int multiplier = otherEmpire ? 3 : 1; + if (price < 0 || maximum < 0 || price > maximum / multiplier) return false; + quote = price * multiplier; + return true; +} +inline bool PortShopSettlement(int64_t price, int rate, int64_t maximum, int64_t& tax, int64_t& proceeds) { + if (price < 0 || price > maximum || rate < 0 || rate > 100) return false; + // Quotient/remainder also keeps this valid if the configured maximum grows. + tax = (price / 100) * rate + (price % 100) * rate / 100; + proceeds = price - tax; + return true; +} diff --git a/src/server/common/stl.h b/src/server/common/stl.h index eb85feff..8439f072 100755 --- a/src/server/common/stl.h +++ b/src/server/common/stl.h @@ -1,6 +1,7 @@ #ifndef __INC_METIN_II_STL_H__ #define __INC_METIN_II_STL_H__ +#include #include #include #include @@ -19,7 +20,7 @@ inline void stl_lowers(std::string& rstRet) { for (size_t i = 0; i < rstRet.length(); ++i) - rstRet[i] = tolower(rstRet[i]); + rstRet[i] = static_cast(std::tolower(static_cast(rstRet[i]))); } struct stringhash diff --git a/src/server/common/tables.h b/src/server/common/tables.h index 35a73c06..ed721353 100755 --- a/src/server/common/tables.h +++ b/src/server/common/tables.h @@ -624,9 +624,10 @@ typedef struct SShopItemTable BYTE count; TItemPos pos; // PC ìƒ�ì �ì—�ë§Œ ì�´ìš© - DWORD price; // PC, shop_table_ex.txt ìƒ�ì �ì—�ë§Œ ì�´ìš© + int64_t price; // PC, shop_table_ex.txt ìƒ�ì �ì—�ë§Œ ì�´ìš© BYTE display_pos; // PC, shop_table_ex.txt ìƒ�ì �ì—�ë§Œ ì�´ìš©, ë³´ì�¼ 위치. } TShopItemTable; +static_assert(sizeof(TShopItemTable)==17,"gold64 private shop wire size"); typedef struct SShopTable { @@ -1635,6 +1636,7 @@ typedef struct offline_shop_item DWORD transmutation; #endif char szOwnerName[CHARACTER_NAME_MAX_LEN+1]; + PortItemExtra extra; } OFFLINE_SHOP_ITEM; typedef struct ShopLog { diff --git a/src/server/common/utils.h b/src/server/common/utils.h index 414c53d8..6b5d48aa 100755 --- a/src/server/common/utils.h +++ b/src/server/common/utils.h @@ -1,3 +1,5 @@ +#include +#include /*----- atoi function -----*/ inline bool str_to_number (bool& out, const char *in) { @@ -73,18 +75,17 @@ inline bool str_to_number (unsigned long& out, const char *in) inline bool str_to_number (long long& out, const char *in) { - if (0==in || 0==in[0]) return false; - - out = (long long) strtoull(in, NULL, 10); - return true; + if(!in || !*in)return false; + errno=0;char* end=NULL;const long long value=strtoll(in,&end,10); + if(errno==ERANGE || end==in || *end)return false; + out=value;return true; } - inline bool str_to_number (unsigned long long& out, const char *in) { - if (0==in || 0==in[0]) return false; - - out = (unsigned long long) strtoull(in, NULL, 10); - return true; + if(!in || !*in || ((*in<'0'||*in>'9')&&*in!='+'))return false; + errno=0;char* end=NULL;const unsigned long long value=strtoull(in,&end,10); + if(errno==ERANGE || end==in || *end)return false; + out=value;return true; } inline bool str_to_number (float& out, const char *in) diff --git a/src/server/common/wire_bounds.h b/src/server/common/wire_bounds.h new file mode 100644 index 00000000..6e527754 --- /dev/null +++ b/src/server/common/wire_bounds.h @@ -0,0 +1,20 @@ +#pragma once +#include + +// The DB boot stream prefixes each table with two WORDs. Its transport accepts +// an int byte length, so validate every count/product before emitting any bytes. +class PortBootSizer { + uint64_t bytes_; + bool valid_; +public: + explicit PortBootSizer(uint64_t fixed):bytes_(fixed),valid_(fixed<=INT32_MAX){} + bool Add(uint64_t count,uint64_t stride) { + if(!valid_ || count>UINT16_MAX || stride>UINT16_MAX || + bytes_>INT32_MAX-4 || (count && stride>(INT32_MAX-4-bytes_)/count)) { + valid_=false;return false; + } + bytes_+=4+count*stride;return true; + } + bool Valid()const{return valid_;} + uint32_t Bytes()const{return valid_?static_cast(bytes_):0;} +}; diff --git a/src/server/db/src/Ava2ItemShop.cpp b/src/server/db/src/Ava2ItemShop.cpp index 6b254686..a988ae69 100644 --- a/src/server/db/src/Ava2ItemShop.cpp +++ b/src/server/db/src/Ava2ItemShop.cpp @@ -6,6 +6,7 @@ #include "ItemAwardManager.h" #include "../../common/ava2_itemshop.h" #include "../../common/point_drop.h" +#include #include #include #include @@ -57,8 +58,21 @@ void reply(CPeer* peer,DWORD handle,const Ava2ShopRequest& request,const std::ve Ava2ShopReply h={request.account,request.player,uint32_t(out.size())}; peer->EncodeHeader(76,handle,sizeof(h)+out.size());peer->Encode(&h,sizeof(h));peer->Encode(out.data(),out.size()); } +bool productNumber(const char* text,int64_t& value,int64_t minimum,int64_t maximum) { + if(!text || !*text)return false; + const char* digits=text;if(*digits=='-' && minimum<0)++digits; + if(!*digits)return false;for(const char* p=digits;*p;++p)if(*p<'0'||*p>'9')return false; + errno=0;char* end=nullptr;const long long parsed=strtoll(text,&end,10); + if(errno==ERANGE || *end || parsedmaximum)return false; + value=parsed;return true; +} Ava2ShopProduct product(MYSQL_ROW r) { - Ava2ShopProduct p={};p.id=strtoul(r[0],0,10);p.vnum=strtoul(r[1],0,10);p.price=strtoll(r[2],0,10);p.discount=atoi(r[3]);p.expiry=atoi(r[4]);p.added=atoi(r[5]);p.sold=strtoll(r[6],0,10);p.weekly=atoi(r[7]);p.monthly=atoi(r[8]);p.stock=atoi(r[9]);return p; + Ava2ShopProduct p={};int64_t n[10]={}; + const int64_t minimum[10]={1,1,0,0,0,0,0,0,0,-1}; + const int64_t maximum[10]={UINT32_MAX,UINT32_MAX,1000000000000LL,100,INT32_MAX,INT32_MAX,INT64_MAX,INT32_MAX,INT32_MAX,INT32_MAX}; + if(!r)return p; + for(unsigned i=0;i<10;++i)if(!productNumber(r[i],n[i],minimum[i],maximum[i]))return p; + p.id=static_cast(n[0]);p.vnum=static_cast(n[1]);p.price=n[2];p.discount=static_cast(n[3]);p.expiry=static_cast(n[4]);p.added=static_cast(n[5]);p.sold=n[6];p.weekly=static_cast(n[7]);p.monthly=static_cast(n[8]);p.stock=static_cast(n[9]);return p; } const char* fields="id,itemVnum,itemPrice,discount,IFNULL(UNIX_TIMESTAMP(offerTime),0),IFNULL(UNIX_TIMESTAMP(addedTime),0),sellCount,week_limit,month_limit,maxSellCount"; bool valid(const Ava2ShopProduct& p) {return p.id && p.vnum && p.price>=0 && p.price<=1000000000000LL && p.discount<=100 && p.weekly>=0 && p.monthly>=0 && p.stock>=-1;} @@ -76,31 +90,41 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR auto mob=std::find_if(m_vec_mobTable.begin(),m_vec_mobTable.end(),[&](const TMobTable& m){return m.dwVnum==r.product;}); const bool validMob=mob!=m_vec_mobTable.end() && (mob->bType==0 || mob->bType==2); const auto rule=PortPointRule([&](const std::string& key){auto it=m_map_lEventFlag.find(key);return it==m_map_lEventFlag.end()?0:int(it->second);},validMob && mob->bType==2); - auto engine=query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_point_rewards' AND ENGINE='InnoDB'"); - if(validMob && !adb.empty() && transactional(adb) && ok(engine) && engine->Get()->uiNumRows==1 && atoi(mysql_fetch_row(engine->Get()->pSQLResult)[0])==1) { + // Reward replay must remain available after catalogue/mob/rule changes. Only + // the two tables participating in this economic transaction are prerequisites. + auto engine=adb.empty()?Query():query("SELECT COUNT(*) FROM information_schema.tables WHERE ENGINE='InnoDB' AND ((TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_point_rewards') OR (TABLE_SCHEMA='"+adb.substr(1,adb.size()-2)+"' AND TABLE_NAME='account'))"); + if(!adb.empty() && ok(engine) && engine->Get()->uiNumRows==1 && atoi(mysql_fetch_row(engine->Get()->pSQLResult)[0])==2) { Transaction tx; if(tx.active) { - auto owner=query("SELECT account_id FROM player WHERE id="+decimal(r.player)); auto wallet=query("SELECT coins FROM "+adb+".account WHERE id="+aid+" FOR UPDATE"); - auto dateQ=query("SELECT CURDATE()"); - if(ok(owner) && owner->Get()->uiNumRows==1 && strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)==r.account && ok(wallet) && wallet->Get()->uiNumRows==1 && ok(dateQ) && dateQ->Get()->uiNumRows==1) { - const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0]; + if(ok(wallet) && wallet->Get()->uiNumRows==0)status=2; // Deleted account: terminal, never retry a new award. + else if(ok(wallet) && wallet->Get()->uiNumRows==1) { balance=strtoll(mysql_fetch_row(wallet->Get()->pSQLResult)[0],0,10); - auto previous=query("SELECT account_id,vnum,requested,amount FROM port_point_rewards WHERE token='"+std::string(r.token)+"'"); + auto previous=query("SELECT account_id,vnum,requested,amount,player_id FROM port_point_rewards WHERE token='"+std::string(r.token)+"'"); if(ok(previous) && previous->Get()->uiNumRows==1) { auto row=mysql_fetch_row(previous->Get()->pSQLResult); - if(strtoul(row[0],0,10)==r.account && strtoul(row[1],0,10)==r.product && strtoul(row[2],0,10)==r.count){granted=strtoul(row[3],0,10);status=0;}else status=7; + if(strtoul(row[0],0,10)==r.account && strtoul(row[1],0,10)==r.product && strtoul(row[2],0,10)==r.count && strtoul(row[4],0,10)==r.player){granted=strtoul(row[3],0,10);status=0;}else status=7; } else if(ok(previous)) { - if(!rule.eligible(mob->bLevel,r.expectedVnum) || r.countuint32_t(rule.maximum))status=1; - else { - auto earned=query("SELECT COALESCE(SUM(amount),0) FROM port_point_rewards WHERE account_id="+aid+" AND reward_day='"+rewardDay+"'"); - if(ok(earned) && earned->Get()->uiNumRows==1) { - granted=PortPointDropAmount(r.count,strtoull(mysql_fetch_row(earned->Get()->pSQLResult)[0],0,10),rule.dailyCap); - if(balance<0 || uint64_t(balance)>uint64_t(INT64_MAX)-granted){status=1;granted=0;} - else { - bool success=run("UPDATE "+adb+".account SET coins=coins+"+decimal(granted)+" WHERE id="+aid); - success=success && run("INSERT INTO port_point_rewards(token,account_id,player_id,vnum,requested,amount,reward_day) VALUES('"+std::string(r.token)+"',"+aid+","+decimal(r.player)+","+decimal(r.product)+","+decimal(r.count)+","+decimal(granted)+",'"+rewardDay+"')"); - if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;} + // Ownership/rules apply to new awards. They must not hide a committed token + // after a character deletion/transfer or a live configuration change. + auto owner=query("SELECT account_id FROM player WHERE id="+decimal(r.player)); + if(ok(owner) && (owner->Get()->uiNumRows!=1 || strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)!=r.account))status=2; + else if(ok(owner)) { + if(!validMob || !rule.eligible(mob->bLevel,r.expectedVnum) || r.countuint32_t(rule.maximum))status=1; + else { + auto dateQ=query("SELECT CURDATE()"); + if(ok(dateQ) && dateQ->Get()->uiNumRows==1) { + const std::string rewardDay = mysql_fetch_row(dateQ->Get()->pSQLResult)[0]; + auto earned=query("SELECT COALESCE(SUM(amount),0) FROM port_point_rewards WHERE account_id="+aid+" AND reward_day='"+rewardDay+"'"); + if(ok(earned) && earned->Get()->uiNumRows==1) { + granted=PortPointDropAmount(r.count,strtoull(mysql_fetch_row(earned->Get()->pSQLResult)[0],0,10),rule.dailyCap); + if(balance<0 || uint64_t(balance)>uint64_t(INT64_MAX)-granted){status=1;granted=0;} + else { + bool success=run("UPDATE "+adb+".account SET coins=coins+"+decimal(granted)+" WHERE id="+aid); + success=success && run("INSERT INTO port_point_rewards(token,account_id,player_id,vnum,requested,amount,reward_day) VALUES('"+std::string(r.token)+"',"+aid+","+decimal(r.player)+","+decimal(r.product)+","+decimal(r.count)+","+decimal(granted)+",'"+rewardDay+"')"); + if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;} + } + } } } } @@ -129,9 +153,10 @@ void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWOR std::map>> catalogue; MYSQL_ROW row; while((row=mysql_fetch_row(rows->Get()->pSQLResult))) { - auto p=product(row);int cat=atoi(row[10]),sub=atoi(row[11]); + auto p=product(row);int64_t cat=0,sub=0; + if(!productNumber(row[10],cat,0,7) || !productNumber(row[11],sub,0,9))continue; if(!valid(p) || cat<0 || cat>7 || sub<0 || sub>9 || (!m_map_itemTableByVnum.count(p.vnum) || m_map_itemTableByVnum.at(p.vnum)->bType==ITEM_NONE))continue; - catalogue[cat][sub].push_back(p); + catalogue[static_cast(cat)][static_cast(sub)].push_back(p); } std::vector ranked; for(auto& cat:catalogue)for(auto& sub:cat.second)for(auto& p:sub.second)ranked.push_back(&p); diff --git a/src/server/db/src/ClientManager.cpp b/src/server/db/src/ClientManager.cpp index 4e5bcf12..cb3902cb 100755 --- a/src/server/db/src/ClientManager.cpp +++ b/src/server/db/src/ClientManager.cpp @@ -1,5 +1,6 @@ #include "stdafx.h" +#include "../../common/wire_bounds.h" #include "../../common/billing.h" #include "../../common/building.h" @@ -259,44 +260,37 @@ void CClientManager::QUERY_BOOT(CPeer* peer, TPacketGDBoot * p) std::vector vAdmin; std::vector vHost; - __GetHostInfo(vHost); - __GetAdminInfo(p->szIP, vAdmin); + if (!__GetHostInfo(vHost) || !__GetAdminInfo(p->szIP, vAdmin)) { sys_err("BOOT: admin/host query failed or exceeded capacity"); return; } sys_log(0, "QUERY_BOOT : AdminInfo (Request ServerIp %s) ", p->szIP); - DWORD dwPacketSize = - sizeof(DWORD) + - sizeof(BYTE) + - sizeof(WORD) + sizeof(WORD) + sizeof(TMobTable) * m_vec_mobTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(TItemTable) * m_vec_itemTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(TShopTable) * m_iShopTableSize + - sizeof(WORD) + sizeof(WORD) + sizeof(TSkillTable) * m_vec_skillTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(TRefineTable) * m_iRefineTableSize + - sizeof(WORD) + sizeof(WORD) + sizeof(TItemAttrTable) * m_vec_itemAttrTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(TItemAttrTable) * m_vec_itemRareTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(TBanwordTable) * m_vec_banwordTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(building::TLand) * m_vec_kLandTable.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(building::TObjectProto) * m_vec_kObjectProto.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(building::TObject) * m_map_pkObjectTable.size() + + PortBootSizer boot(sizeof(DWORD)+sizeof(BYTE)+sizeof(time_t)+sizeof(WORD)); + bool valid = boot.Add(m_vec_mobTable.size(),sizeof(TMobTable)) && + boot.Add(m_vec_itemTable.size(),sizeof(TItemTable)) && boot.Add(m_iShopTableSize,sizeof(TShopTable)) && + boot.Add(m_vec_skillTable.size(),sizeof(TSkillTable)) && boot.Add(m_iRefineTableSize,sizeof(TRefineTable)) && + boot.Add(m_vec_itemAttrTable.size(),sizeof(TItemAttrTable)) && boot.Add(m_vec_itemRareTable.size(),sizeof(TItemAttrTable)) && + boot.Add(m_vec_banwordTable.size(),sizeof(TBanwordTable)) && boot.Add(m_vec_kLandTable.size(),sizeof(building::TLand)) && + boot.Add(m_vec_kObjectProto.size(),sizeof(building::TObjectProto)) && boot.Add(m_map_pkObjectTable.size(),sizeof(building::TObject)) && + boot.Add(2,sizeof(TItemIDRangeTable)) && boot.Add(vHost.size(),16) && boot.Add(vAdmin.size(),sizeof(tAdminInfo)) && + boot.Add(1,sizeof(TMonarchInfo)) && boot.Add(CMonarch::instance().MonarchCandidacySize(),sizeof(MonarchCandidacy)); #ifdef __AUCTION__ - sizeof(WORD) + sizeof(WORD) + sizeof(TPlayerItem) * AuctionManager::instance().GetAuctionItemSize() + - sizeof(WORD) + sizeof(WORD) + sizeof(TAuctionItemInfo) * AuctionManager::instance().GetAuctionSize() + - sizeof(WORD) + sizeof(WORD) + sizeof(TSaleItemInfo) * AuctionManager::instance().GetSaleSize() + - sizeof(WORD) + sizeof(WORD) + sizeof(TWishItemInfo) * AuctionManager::instance().GetWishSize() + - sizeof(WORD) + sizeof(WORD) + (sizeof(DWORD) + sizeof(DWORD) + sizeof(int)) * AuctionManager::instance().GetMyBidSize() + + valid = valid && boot.Add(AuctionManager::instance().GetAuctionItemSize(),sizeof(TPlayerItem)) && + boot.Add(AuctionManager::instance().GetAuctionSize(),sizeof(TAuctionItemInfo)) && + boot.Add(AuctionManager::instance().GetSaleSize(),sizeof(TSaleItemInfo)) && + boot.Add(AuctionManager::instance().GetWishSize(),sizeof(TWishItemInfo)) && + boot.Add(AuctionManager::instance().GetMyBidSize(),sizeof(DWORD)*2+sizeof(int)); #endif - sizeof(time_t) + - sizeof(WORD) + sizeof(WORD) + sizeof(TItemIDRangeTable)*2 + - //ADMIN_MANAGER - sizeof(WORD) + sizeof(WORD) + 16 * vHost.size() + - sizeof(WORD) + sizeof(WORD) + sizeof(tAdminInfo) * vAdmin.size() + - //END_ADMIN_MANAGER - sizeof(WORD) + sizeof(WORD) + sizeof(TMonarchInfo) + - sizeof(WORD) + sizeof(WORD) + sizeof(MonarchCandidacy)* CMonarch::instance().MonarchCandidacySize() + #ifdef ENABLE_OFFLINESHOP_SYSTEM - sizeof(WORD) + sizeof(WORD) + sizeof(TOfflineShop) * m_Offlineshop.size() + + valid = valid && boot.Add(m_Offlineshop.size(),sizeof(TOfflineShop)); #endif - sizeof(WORD); + if(!valid){sys_err("BOOT: table count or total stream length exceeds protocol capacity");return;} + if ((m_iShopTableSize && !m_pShopTable) || (m_iRefineTableSize && !m_pRefineTable)) return; + for (const auto& entry:m_map_pkObjectTable) if(!entry.second)return; +#ifdef ENABLE_OFFLINESHOP_SYSTEM + for (const auto& entry:m_Offlineshop) if(!entry.second)return; +#endif + for (const auto& host:vHost) if(host.size()>15){sys_err("BOOT: host exceeds fixed IPv4 field");return;} + const DWORD dwPacketSize=boot.Bytes(); peer->EncodeHeader(HEADER_DG_BOOT, 0, dwPacketSize); peer->Encode(&dwPacketSize, sizeof(DWORD)); @@ -305,64 +299,64 @@ void CClientManager::QUERY_BOOT(CPeer* peer, TPacketGDBoot * p) sys_log(0, "BOOT: PACKET: %d", dwPacketSize); sys_log(0, "BOOT: VERSION: %d", bPacketVersion); - sys_log(0, "sizeof(TMobTable) = %d", sizeof(TMobTable)); - sys_log(0, "sizeof(TItemTable) = %d", sizeof(TItemTable)); - sys_log(0, "sizeof(TShopTable) = %d", sizeof(TShopTable)); - sys_log(0, "sizeof(TSkillTable) = %d", sizeof(TSkillTable)); - sys_log(0, "sizeof(TRefineTable) = %d", sizeof(TRefineTable)); - sys_log(0, "sizeof(TItemAttrTable) = %d", sizeof(TItemAttrTable)); - sys_log(0, "sizeof(TItemRareTable) = %d", sizeof(TItemAttrTable)); - sys_log(0, "sizeof(TBanwordTable) = %d", sizeof(TBanwordTable)); - sys_log(0, "sizeof(TLand) = %d", sizeof(building::TLand)); - sys_log(0, "sizeof(TObjectProto) = %d", sizeof(building::TObjectProto)); - sys_log(0, "sizeof(TObject) = %d", sizeof(building::TObject)); + sys_log(0, "sizeof(TMobTable) = %zu", sizeof(TMobTable)); + sys_log(0, "sizeof(TItemTable) = %zu", sizeof(TItemTable)); + sys_log(0, "sizeof(TShopTable) = %zu", sizeof(TShopTable)); + sys_log(0, "sizeof(TSkillTable) = %zu", sizeof(TSkillTable)); + sys_log(0, "sizeof(TRefineTable) = %zu", sizeof(TRefineTable)); + sys_log(0, "sizeof(TItemAttrTable) = %zu", sizeof(TItemAttrTable)); + sys_log(0, "sizeof(TItemRareTable) = %zu", sizeof(TItemAttrTable)); + sys_log(0, "sizeof(TBanwordTable) = %zu", sizeof(TBanwordTable)); + sys_log(0, "sizeof(TLand) = %zu", sizeof(building::TLand)); + sys_log(0, "sizeof(TObjectProto) = %zu", sizeof(building::TObjectProto)); + sys_log(0, "sizeof(TObject) = %zu", sizeof(building::TObject)); //ADMIN_MANAGER - sys_log(0, "sizeof(tAdminInfo) = %d * %d ", sizeof(tAdminInfo) * vAdmin.size()); + sys_log(0, "sizeof(tAdminInfo) = %zu ", sizeof(tAdminInfo) * vAdmin.size()); //END_ADMIN_MANAGER - sys_log(0, "sizeof(TMonarchInfo) = %d * %d", sizeof(TMonarchInfo)); + sys_log(0, "sizeof(TMonarchInfo) = %zu", sizeof(TMonarchInfo)); peer->EncodeWORD(sizeof(TMobTable)); - peer->EncodeWORD(m_vec_mobTable.size()); - peer->Encode(&m_vec_mobTable[0], sizeof(TMobTable) * m_vec_mobTable.size()); + peer->EncodeWORD(static_cast(m_vec_mobTable.size())); + if (!m_vec_mobTable.empty()) peer->Encode(m_vec_mobTable.data(), sizeof(TMobTable) * m_vec_mobTable.size()); peer->EncodeWORD(sizeof(TItemTable)); - peer->EncodeWORD(m_vec_itemTable.size()); - peer->Encode(&m_vec_itemTable[0], sizeof(TItemTable) * m_vec_itemTable.size()); + peer->EncodeWORD(static_cast(m_vec_itemTable.size())); + if (!m_vec_itemTable.empty()) peer->Encode(m_vec_itemTable.data(), sizeof(TItemTable) * m_vec_itemTable.size()); peer->EncodeWORD(sizeof(TShopTable)); - peer->EncodeWORD(m_iShopTableSize); - peer->Encode(m_pShopTable, sizeof(TShopTable) * m_iShopTableSize); + peer->EncodeWORD(static_cast(m_iShopTableSize)); + if (m_iShopTableSize) peer->Encode(m_pShopTable, sizeof(TShopTable) * m_iShopTableSize); peer->EncodeWORD(sizeof(TSkillTable)); - peer->EncodeWORD(m_vec_skillTable.size()); - peer->Encode(&m_vec_skillTable[0], sizeof(TSkillTable) * m_vec_skillTable.size()); + peer->EncodeWORD(static_cast(m_vec_skillTable.size())); + if (!m_vec_skillTable.empty()) peer->Encode(m_vec_skillTable.data(), sizeof(TSkillTable) * m_vec_skillTable.size()); peer->EncodeWORD(sizeof(TRefineTable)); - peer->EncodeWORD(m_iRefineTableSize); - peer->Encode(m_pRefineTable, sizeof(TRefineTable) * m_iRefineTableSize); + peer->EncodeWORD(static_cast(m_iRefineTableSize)); + if (m_iRefineTableSize) peer->Encode(m_pRefineTable, sizeof(TRefineTable) * m_iRefineTableSize); peer->EncodeWORD(sizeof(TItemAttrTable)); - peer->EncodeWORD(m_vec_itemAttrTable.size()); - peer->Encode(&m_vec_itemAttrTable[0], sizeof(TItemAttrTable) * m_vec_itemAttrTable.size()); + peer->EncodeWORD(static_cast(m_vec_itemAttrTable.size())); + if (!m_vec_itemAttrTable.empty()) peer->Encode(m_vec_itemAttrTable.data(), sizeof(TItemAttrTable) * m_vec_itemAttrTable.size()); peer->EncodeWORD(sizeof(TItemAttrTable)); - peer->EncodeWORD(m_vec_itemRareTable.size()); - peer->Encode(&m_vec_itemRareTable[0], sizeof(TItemAttrTable) * m_vec_itemRareTable.size()); + peer->EncodeWORD(static_cast(m_vec_itemRareTable.size())); + if (!m_vec_itemRareTable.empty()) peer->Encode(m_vec_itemRareTable.data(), sizeof(TItemAttrTable) * m_vec_itemRareTable.size()); peer->EncodeWORD(sizeof(TBanwordTable)); - peer->EncodeWORD(m_vec_banwordTable.size()); - peer->Encode(&m_vec_banwordTable[0], sizeof(TBanwordTable) * m_vec_banwordTable.size()); + peer->EncodeWORD(static_cast(m_vec_banwordTable.size())); + if (!m_vec_banwordTable.empty()) peer->Encode(m_vec_banwordTable.data(), sizeof(TBanwordTable) * m_vec_banwordTable.size()); peer->EncodeWORD(sizeof(building::TLand)); - peer->EncodeWORD(m_vec_kLandTable.size()); - peer->Encode(&m_vec_kLandTable[0], sizeof(building::TLand) * m_vec_kLandTable.size()); + peer->EncodeWORD(static_cast(m_vec_kLandTable.size())); + if (!m_vec_kLandTable.empty()) peer->Encode(m_vec_kLandTable.data(), sizeof(building::TLand) * m_vec_kLandTable.size()); peer->EncodeWORD(sizeof(building::TObjectProto)); - peer->EncodeWORD(m_vec_kObjectProto.size()); - peer->Encode(&m_vec_kObjectProto[0], sizeof(building::TObjectProto) * m_vec_kObjectProto.size()); + peer->EncodeWORD(static_cast(m_vec_kObjectProto.size())); + if (!m_vec_kObjectProto.empty()) peer->Encode(m_vec_kObjectProto.data(), sizeof(building::TObjectProto) * m_vec_kObjectProto.size()); peer->EncodeWORD(sizeof(building::TObject)); - peer->EncodeWORD(m_map_pkObjectTable.size()); + peer->EncodeWORD(static_cast(m_map_pkObjectTable.size())); itertype(m_map_pkObjectTable) it = m_map_pkObjectTable.begin(); @@ -389,16 +383,18 @@ void CClientManager::QUERY_BOOT(CPeer* peer, TPacketGDBoot * p) //ADMIN_MANAGER peer->EncodeWORD(16); - peer->EncodeWORD(vHost.size()); + peer->EncodeWORD(static_cast(vHost.size())); for (size_t n = 0; n < vHost.size(); ++n) { - peer->Encode(vHost[n].c_str(), 16); + char address[16]={}; + strlcpy(address,vHost[n].c_str(),sizeof(address)); + peer->Encode(address,sizeof(address)); sys_log(0, "GMHosts %s", vHost[n].c_str()); } peer->EncodeWORD(sizeof(tAdminInfo)); - peer->EncodeWORD(vAdmin.size()); + peer->EncodeWORD(static_cast(vAdmin.size())); for (size_t n = 0; n < vAdmin.size(); ++n) { @@ -416,14 +412,14 @@ void CClientManager::QUERY_BOOT(CPeer* peer, TPacketGDBoot * p) size_t num_monarch_candidacy = CMonarch::instance().MonarchCandidacySize(); peer->EncodeWORD(sizeof(MonarchCandidacy)); - peer->EncodeWORD(num_monarch_candidacy); + peer->EncodeWORD(static_cast(num_monarch_candidacy)); if (num_monarch_candidacy != 0) { peer->Encode(&rVecMonarchCandidacy[0], sizeof(MonarchCandidacy) * num_monarch_candidacy); } //END_MONARCE if (g_test_server) - sys_log(0, "MONARCHCandidacy Size %d", CMonarch::instance().MonarchCandidacySize()); + sys_log(0, "MONARCHCandidacy Size %zu", CMonarch::instance().MonarchCandidacySize()); #ifdef ENABLE_OFFLINESHOP_SYSTEM peer->EncodeWORD(sizeof(TOfflineShop)); @@ -436,7 +432,7 @@ void CClientManager::QUERY_BOOT(CPeer* peer, TPacketGDBoot * p) memcpy(&p, it->second, sizeof(TOfflineShop)); offlineshop.push_back(p); } - peer->EncodeWORD(offlineshop.size()); + peer->EncodeWORD(static_cast(offlineshop.size())); if (offlineshop.size()) peer->Encode(&offlineshop[0], sizeof(TOfflineShop) * offlineshop.size()); #endif @@ -489,6 +485,7 @@ void CClientManager::QUERY_QUEST_SAVE(CPeer * pkPeer, TQuestTable * pTable, DWOR for (int i = 0; i < iSize; ++i, ++pTable) { + if(!EconomySaveAllowed(pkPeer,pTable->dwPID))continue; if (pTable->lValue == 0) { snprintf(szQuery, sizeof(szQuery), @@ -633,8 +630,15 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg) } static std::vector s_items; - CreateItemTableFromRes(msg->Get()->pSQLResult, &s_items, pi->account_id); + if (!CreateItemTableFromRes(msg->Get()->pSQLResult, &s_items, pi->account_id)) { + sys_err("SAFEBOX_EXTRA_QUARANTINE account=%u",pi->account_id); + delete pi;return; + } + if(s_items.size()>UINT16_MAX) { + sys_err("SAFEBOX item count exceeds wire limit: account=%u",pi->account_id); + delete pi;return; + } std::set * pSet = ItemAwardManager::instance().GetByLogin(pi->login); if (pSet && !m_vec_itemTable.empty()) @@ -667,7 +671,7 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg) char szQuery[512]; - while (it != pSet->end()) + while (it != pSet->end() && s_items.size()dwVnum; @@ -696,6 +700,9 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg) if ((iPos = grid.FindBlank(1, it->second->bSize)) == -1) break; + // Validate before INSERT/Taken: an unrepresentable cell + // must never become a paid award hidden from the response. + if(iPos<0 || iPos>UINT16_MAX)break; TPlayerItem item={}; memset(&item, 0, sizeof(TPlayerItem)); @@ -809,12 +816,12 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg) SQLResult * pRes = pmsg->Get(); sys_log(0, "SAFEBOX Query : [%s]", szQuery); - if (pRes->uiAffectedRows == 0 || pRes->uiInsertID == 0 || pRes->uiAffectedRows == (uint32_t)-1) + if (pRes->uiAffectedRows == 0 || (pRes->uiInsertID == 0 || pRes->uiInsertID > UINT32_MAX) || pRes->uiAffectedRows == UINT64_MAX) break; - item.id = pmsg->Get()->uiInsertID; + item.id = static_cast(pmsg->Get()->uiInsertID); item.window = pi->ip[0] == 0 ? SAFEBOX : MALL, - item.pos = iPos; + item.pos = static_cast(iPos); item.count = pItemAward->dwCount; item.vnum = pItemAward->dwVnum; item.alSockets[0] = pItemAward->dwSocket0; @@ -831,7 +838,7 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg) } } - pi->pSafebox->wItemCount = s_items.size(); + pi->pSafebox->wItemCount = static_cast(s_items.size()); pkPeer->EncodeHeader(pi->ip[0] == 0 ? HEADER_DG_SAFEBOX_LOAD : HEADER_DG_MALL_LOAD, dwHandle, sizeof(TSafeboxTable) + sizeof(TPlayerItem) * s_items.size()); @@ -1032,7 +1039,7 @@ void CClientManager::QUERY_EMPIRE_SELECT(CPeer * pkPeer, DWORD dwHandle, TEmpire if (pRes->uiNumRows) { - sys_log(0, "EMPIRE %lu", pRes->uiNumRows); + sys_log(0, "EMPIRE %llu", static_cast(pRes->uiNumRows)); MYSQL_ROW row = mysql_fetch_row(pRes->pSQLResult); DWORD pids[3]; @@ -1095,6 +1102,19 @@ void CClientManager::QUERY_SETUP(CPeer * peer, DWORD dwHandle, const char * c_pD return; } + size_t mapCount=1; + for(auto* candidate:m_peerList) { + const BYTE channel=candidate->GetChannel(); + if(candidate==peer || !channel)continue; + const bool include=p->bChannel==GUILD_WARP_WAR_CHANNEL ? + (channel==1 || channel==p->bChannel) : + (channel==GUILD_WARP_WAR_CHANNEL || channel==p->bChannel); + if(include && ++mapCount>UINT8_MAX) { + sys_err("SETUP map count exceeds wire limit: channel=%u",p->bChannel); + peer->Close(); + return; + } + } peer->SetPublicIP(p->szPublicIP); peer->SetChannel(p->bChannel); peer->SetListenPort(p->wListenPort); @@ -1204,7 +1224,7 @@ void CClientManager::QUERY_SETUP(CPeer * peer, DWORD dwHandle, const char * c_pD vec_kMapLocations.push_back(kMapLocations); peer->EncodeHeader(HEADER_DG_MAP_LOCATIONS, 0, sizeof(BYTE) + sizeof(TMapLocation) * vec_kMapLocations.size()); - bMapCount = vec_kMapLocations.size(); + bMapCount = static_cast(vec_kMapLocations.size()); peer->EncodeBYTE(bMapCount); peer->Encode(&vec_kMapLocations[0], sizeof(TMapLocation) * vec_kMapLocations.size()); @@ -1306,6 +1326,8 @@ void CClientManager::QUERY_ITEM_FLUSH(CPeer * pkPeer, const char * c_pData) void CClientManager::QUERY_ITEM_SAVE(CPeer * pkPeer, const char * c_pData) { TPlayerItem * p = (TPlayerItem *) c_pData; + if(!EconomyItemWritable(p->id))return; + if(p->window!=SAFEBOX && p->window!=MALL && !EconomySaveAllowed(pkPeer,p->owner))return; // 창고면 ìº�쉬하지 않고, ìº�쉬ì—� 있ë�˜ 것ë�„ 빼버려야 한다. // auctionì�€ ì�´ 루트를 타지 않아야 한다. EnrollInAuctionì�„ 타야한다. @@ -1616,6 +1638,7 @@ void CClientManager::QUERY_ITEM_DESTROY(CPeer * pkPeer, const char * c_pData) c_pData += sizeof(DWORD); DWORD dwPID = *(DWORD *) c_pData; + if(!EconomyItemWritable(dwID) || (dwPID && !EconomySaveAllowed(pkPeer,dwPID)))return; if (!DeleteItemCache(dwID)) { @@ -1674,6 +1697,10 @@ void CClientManager::QUERY_RELOAD_PROTO() return; } + if(m_vec_skillTable.size()>UINT16_MAX || m_vec_banwordTable.size()>UINT16_MAX || + m_vec_itemTable.size()>UINT16_MAX || m_vec_mobTable.size()>UINT16_MAX) { + sys_err("QUERY_RELOAD_PROTO: table count exceeds wire limit");return; + } for (TPeerList::iterator i = m_peerList.begin(); i != m_peerList.end(); ++i) { CPeer * tmp = *i; @@ -1687,17 +1714,17 @@ void CClientManager::QUERY_RELOAD_PROTO() sizeof(WORD) + sizeof(TItemTable) * m_vec_itemTable.size() + sizeof(WORD) + sizeof(TMobTable) * m_vec_mobTable.size()); - tmp->EncodeWORD(m_vec_skillTable.size()); - tmp->Encode(&m_vec_skillTable[0], sizeof(TSkillTable) * m_vec_skillTable.size()); + tmp->EncodeWORD(static_cast(m_vec_skillTable.size())); + tmp->Encode(m_vec_skillTable.data(), sizeof(TSkillTable) * m_vec_skillTable.size()); - tmp->EncodeWORD(m_vec_banwordTable.size()); - tmp->Encode(&m_vec_banwordTable[0], sizeof(TBanwordTable) * m_vec_banwordTable.size()); + tmp->EncodeWORD(static_cast(m_vec_banwordTable.size())); + tmp->Encode(m_vec_banwordTable.data(), sizeof(TBanwordTable) * m_vec_banwordTable.size()); - tmp->EncodeWORD(m_vec_itemTable.size()); - tmp->Encode(&m_vec_itemTable[0], sizeof(TItemTable) * m_vec_itemTable.size()); + tmp->EncodeWORD(static_cast(m_vec_itemTable.size())); + tmp->Encode(m_vec_itemTable.data(), sizeof(TItemTable) * m_vec_itemTable.size()); - tmp->EncodeWORD(m_vec_mobTable.size()); - tmp->Encode(&m_vec_mobTable[0], sizeof(TMobTable) * m_vec_mobTable.size()); + tmp->EncodeWORD(static_cast(m_vec_mobTable.size())); + tmp->Encode(m_vec_mobTable.data(), sizeof(TMobTable) * m_vec_mobTable.size()); } } @@ -2012,7 +2039,8 @@ void CClientManager::CreateObject(TPacketGDCreateObject * p) std::unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); - if (pmsg->Get()->uiInsertID == 0) + uint32_t objectID=0; + if (!pmsg->Get()->HasAffectedRows() || !pmsg->Get()->GetInsertID32(objectID)) { sys_err("cannot insert object"); return; @@ -2022,7 +2050,7 @@ void CClientManager::CreateObject(TPacketGDCreateObject * p) memset(pkObj, 0, sizeof(TObject)); - pkObj->dwID = pmsg->Get()->uiInsertID; + pkObj->dwID = objectID; pkObj->dwVnum = p->dwVnum; pkObj->dwLandID = p->dwLandID; pkObj->lMapIndex = p->lMapIndex; @@ -2046,7 +2074,7 @@ void CClientManager::DeleteObject(DWORD dwID) std::unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); - if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == UINT64_MAX) { sys_err("no object by id %u", dwID); return; @@ -2350,6 +2378,8 @@ void CClientManager::ProcessPackets(CPeer * peer) switch (header) { + case 77: + EconomyRequest(peer,dwHandle,data,dwLength);break; case 76: Ava2ItemShop(peer,dwHandle,data,dwLength);break; case HEADER_GD_BOOT: @@ -2893,6 +2923,7 @@ CPeer * CClientManager::GetAnyPeer() int CClientManager::AnalyzeQueryResult(SQLMsg * msg) { CQueryInfo * qi = (CQueryInfo *) msg->pvUserData; + if(qi->iType==QID_ECONOMY_FENCE) { EconomyMainFence(qi->dwIdent,msg->uiSQLErrno!=0);delete qi;return true; } CPeer * peer = GetPeer(qi->dwIdent); #ifdef _TEST @@ -3038,6 +3069,7 @@ int CClientManager::Process() while (pulses--) { ++thecore_heart->pulse; + EconomyTick(); /* //30분마다 변경 @@ -3393,7 +3425,7 @@ bool CClientManager::InitializeLocalization() return false; } - sys_log(0, "InitializeLocalization() - LoadLocaleTable(count:%d)", pMsg->Get()->uiNumRows); + sys_log(0, "InitializeLocalization() - LoadLocaleTable(count:%llu)", static_cast(pMsg->Get()->uiNumRows)); m_vec_Locale.clear(); @@ -3785,16 +3817,13 @@ bool CClientManager::__GetAdminInfo(const char *szIP, std::vector & szIP ? szIP : "ALL"); SQLMsg * pMsg = CDBManager::instance().DirectQuery(szQuery, SQL_COMMON); + if (!pMsg || pMsg->uiSQLErrno || !pMsg->Get()) { delete pMsg; return false; } - if (pMsg->Get()->uiNumRows == 0) - { - sys_err("__GetAdminInfo() ==> DirectQuery failed(%s)", szQuery); - delete pMsg; - return false; - } + if (pMsg->Get()->uiNumRows == 0) { delete pMsg; return true; } MYSQL_ROW row; - rAdminVec.reserve(pMsg->Get()->uiNumRows); + if (pMsg->Get()->uiNumRows > UINT16_MAX) { delete pMsg; return false; } + rAdminVec.reserve(static_cast(pMsg->Get()->uiNumRows)); while ((row = mysql_fetch_row(pMsg->Get()->pSQLResult))) { @@ -3837,15 +3866,12 @@ bool CClientManager::__GetHostInfo(std::vector & rIPVec) char szQuery[512]; snprintf(szQuery, sizeof(szQuery), "SELECT mIP FROM gmhost"); SQLMsg * pMsg = CDBManager::instance().DirectQuery(szQuery, SQL_COMMON); + if (!pMsg || pMsg->uiSQLErrno || !pMsg->Get()) { delete pMsg; return false; } - if (pMsg->Get()->uiNumRows == 0) - { - sys_err("__GetHostInfo() ==> DirectQuery failed(%s)", szQuery); - delete pMsg; - return false; - } + if (pMsg->Get()->uiNumRows == 0) { delete pMsg; return true; } - rIPVec.reserve(pMsg->Get()->uiNumRows); + if (pMsg->Get()->uiNumRows > UINT16_MAX) { delete pMsg; return false; } + rIPVec.reserve(static_cast(pMsg->Get()->uiNumRows)); MYSQL_ROW row; @@ -3868,11 +3894,11 @@ void CClientManager::ReloadAdmin(CPeer*, TPacketReloadAdmin* p) std::vector vAdmin; std::vector vHost; - __GetHostInfo(vHost); - __GetAdminInfo(p->szIP, vAdmin); - - DWORD dwPacketSize = sizeof(WORD) + sizeof (WORD) + sizeof(tAdminInfo) * vAdmin.size() + - sizeof(WORD) + sizeof(WORD) + 16 * vHost.size(); + if (!__GetHostInfo(vHost) || !__GetAdminInfo(p->szIP,vAdmin)) return; + PortBootSizer size(0); + if(!size.Add(vHost.size(),16) || !size.Add(vAdmin.size(),sizeof(tAdminInfo)))return; + for(const auto& host:vHost)if(host.size()>15)return; + const DWORD dwPacketSize=size.Bytes(); for (itertype(m_peerList) it = m_peerList.begin(); it != m_peerList.end(); ++it) { @@ -3884,13 +3910,14 @@ void CClientManager::ReloadAdmin(CPeer*, TPacketReloadAdmin* p) peer->EncodeHeader(HEADER_DG_RELOAD_ADMIN, 0, dwPacketSize); peer->EncodeWORD(16); - peer->EncodeWORD(vHost.size()); + peer->EncodeWORD(static_cast(vHost.size())); - for (size_t n = 0; n < vHost.size(); ++n) - peer->Encode(vHost[n].c_str(), 16); + for (size_t n = 0; n < vHost.size(); ++n) { + char address[16]={};strlcpy(address,vHost[n].c_str(),sizeof(address));peer->Encode(address,sizeof(address)); + } peer->EncodeWORD(sizeof(tAdminInfo)); - peer->EncodeWORD(vAdmin.size()); + peer->EncodeWORD(static_cast(vAdmin.size())); for (size_t n = 0; n < vAdmin.size(); ++n) peer->Encode(&vAdmin[n], sizeof(tAdminInfo)); @@ -4275,7 +4302,7 @@ void CClientManager::ChangeMonarchLord(CPeer * peer, DWORD dwHandle, TPacketChan snprintf(szQuery, sizeof(szQuery), "UPDATE monarch SET pid=%u, windate=NOW() WHERE empire=%d", ack.dwPID, ack.bEmpire); SQLMsg* pMsg2 = CDBManager::instance().DirectQuery(szQuery, SQL_PLAYER); - if (pMsg2->Get()->uiAffectedRows > 0) + if (pMsg2->Get()->HasAffectedRows()) { CMonarch::instance().LoadMonarch(); diff --git a/src/server/db/src/ClientManager.h b/src/server/db/src/ClientManager.h index b9a8413f..cf2f785d 100755 --- a/src/server/db/src/ClientManager.h +++ b/src/server/db/src/ClientManager.h @@ -30,7 +30,19 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p class CClientManager : public CNetBase, public singleton { + struct EconomyFence { DWORD account=0; bool primed=false,mainDone=false,asyncDone=false,failed=false; uint64_t mainFailures=0,asyncFailures=0; time_t nextAttempt=0; DWORD peer=0,handle=0; TPlayerLoadPacket load={}; }; + std::map> m_economyEnqueueEpoch; + std::map m_economyFences; + std::map m_economyOwners; + std::set m_economyClosed; public: + void EconomyRequest(CPeer*,DWORD,const char*,DWORD); + bool EconomyBeforeLoad(CPeer*,DWORD,TPlayerLoadPacket*); + void EconomyTick(); + void EconomyMainFence(DWORD,bool); + bool EconomySaveAllowed(CPeer*,DWORD); + bool EconomyItemWritable(DWORD); + bool EconomyCanDelete(DWORD); typedef std::list TPeerList; typedef std::unordered_map TPlayerTableCacheMap; typedef std::unordered_map TItemCacheMap; @@ -122,6 +134,7 @@ class CClientManager : public CNetBase, public singleton CItemCache * GetItemCache(DWORD id); void PutItemCache(TPlayerItem * pNew, bool bSkipQuery = false); + bool ValidateLoadedExtra(const TPlayerItem& item,const char* hex) const; bool DeleteItemCache(DWORD id); void UpdatePlayerCache(); diff --git a/src/server/db/src/ClientManagerBoot.cpp b/src/server/db/src/ClientManagerBoot.cpp index 9f52ee49..57ec6a34 100755 --- a/src/server/db/src/ClientManagerBoot.cpp +++ b/src/server/db/src/ClientManagerBoot.cpp @@ -118,6 +118,7 @@ bool CClientManager::InitializeRefineTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes->uiNumRows) return true; @@ -129,7 +130,7 @@ bool CClientManager::InitializeRefineTable() m_pRefineTable = NULL; } - m_iRefineTableSize = pRes->uiNumRows; + m_iRefineTableSize = static_cast(pRes->uiNumRows); m_pRefineTable = new TRefineTable[m_iRefineTableSize]; memset(m_pRefineTable, 0, sizeof(TRefineTable) * m_iRefineTableSize); @@ -457,6 +458,7 @@ bool CClientManager::InitializeShopTable() // shopì�˜ vnumì�€ 있는ë�° shop_item ì�´ ì—†ì�„경우... 실패로 처리ë�˜ë‹ˆ 주ì�˜ ìš”ë§�. // 고처야할부분 SQLResult * pRes2 = pkMsg2->Get(); + if (pkMsg2->uiSQLErrno || !pRes2 || pRes2->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes2->uiNumRows) { @@ -533,6 +535,7 @@ bool CClientManager::InitializeQuestItemTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes->uiNumRows) { @@ -870,6 +873,7 @@ bool CClientManager::InitializeSkillTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes->uiNumRows) { @@ -883,7 +887,7 @@ bool CClientManager::InitializeSkillTable() m_vec_skillTable.clear(); } - m_vec_skillTable.reserve(pRes->uiNumRows); + m_vec_skillTable.reserve(static_cast(pRes->uiNumRows)); MYSQL_ROW data; int col; @@ -952,6 +956,7 @@ bool CClientManager::InitializeBanwordTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery("SELECT word FROM banword")); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (pRes->uiNumRows == 0) return true; @@ -982,6 +987,7 @@ bool CClientManager::InitializeItemAttrTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes->uiNumRows) { @@ -995,7 +1001,7 @@ bool CClientManager::InitializeItemAttrTable() m_vec_itemAttrTable.clear(); } - m_vec_itemAttrTable.reserve(pRes->uiNumRows); + m_vec_itemAttrTable.reserve(static_cast(pRes->uiNumRows)); MYSQL_ROW data; @@ -1056,6 +1062,7 @@ bool CClientManager::InitializeItemRareTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!pRes->uiNumRows) { @@ -1069,7 +1076,7 @@ bool CClientManager::InitializeItemRareTable() m_vec_itemRareTable.clear(); } - m_vec_itemRareTable.reserve(pRes->uiNumRows); + m_vec_itemRareTable.reserve(static_cast(pRes->uiNumRows)); MYSQL_ROW data; @@ -1134,6 +1141,7 @@ bool CClientManager::InitializeLandTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!m_vec_kLandTable.empty()) { @@ -1141,7 +1149,7 @@ bool CClientManager::InitializeLandTable() m_vec_kLandTable.clear(); } - m_vec_kLandTable.reserve(pRes->uiNumRows); + m_vec_kLandTable.reserve(static_cast(pRes->uiNumRows)); MYSQL_ROW data; @@ -1237,6 +1245,7 @@ bool CClientManager::InitializeObjectProto() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!m_vec_kObjectProto.empty()) { @@ -1244,7 +1253,7 @@ bool CClientManager::InitializeObjectProto() m_vec_kObjectProto.clear(); } - m_vec_kObjectProto.reserve(MAX(0, pRes->uiNumRows)); + m_vec_kObjectProto.reserve(static_cast(pRes->uiNumRows)); MYSQL_ROW data; @@ -1306,6 +1315,7 @@ bool CClientManager::InitializeObjectTable() std::unique_ptr pkMsg(CDBManager::instance().DirectQuery(query)); SQLResult * pRes = pkMsg->Get(); + if (pkMsg->uiSQLErrno || !pRes || pRes->uiNumRows > UINT16_MAX) { sys_err("boot table query failed or exceeds 16-bit wire count"); return false; } if (!m_map_pkObjectTable.empty()) { diff --git a/src/server/db/src/ClientManagerLogin.cpp b/src/server/db/src/ClientManagerLogin.cpp index 4b8449a7..e75c488b 100755 --- a/src/server/db/src/ClientManagerLogin.cpp +++ b/src/server/db/src/ClientManagerLogin.cpp @@ -435,7 +435,7 @@ void CClientManager::RESULT_LOGIN(CPeer * peer, SQLMsg * msg) } else { - sys_log(0, "RESULT_LOGIN: login success %s rows: %lu", info->pAccountTable->login, msg->Get()->uiNumRows); + sys_log(0, "RESULT_LOGIN: login success %s rows: %llu", info->pAccountTable->login, static_cast(msg->Get()->uiNumRows)); if (msg->Get()->uiNumRows > 0) CreateAccountPlayerDataFromRes(msg->Get()->pSQLResult, info->pAccountTable); diff --git a/src/server/db/src/ClientManagerOfflineshop.cpp b/src/server/db/src/ClientManagerOfflineshop.cpp index 74d0fd51..cef3c097 100644 --- a/src/server/db/src/ClientManagerOfflineshop.cpp +++ b/src/server/db/src/ClientManagerOfflineshop.cpp @@ -1,6 +1,7 @@ #include "stdafx.h" #ifdef ENABLE_OFFLINESHOP_SYSTEM #include "ClientManager.h" +#include "../../common/offline_shop_safety.h" void InsertImportLog(const char* logReason, TOfflineShop* p, DWORD targetPID, const char* targetName, const OFFLINE_SHOP_ITEM* item) { @@ -14,6 +15,7 @@ void CClientManager::OfflineShopAssert(TOfflineShop* p){} bool CClientManager::InitializeOfflineShop() { + if(!PortOfflineShopEconomyReady())return true; // Do not run legacy expiry/delete cleanup on stored custody. MYSQL_ROW row; //for (size_t j = 1; j <= channelcount; j++) { @@ -57,7 +59,7 @@ bool CClientManager::InitializeOfflineShop() iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",socket%d",j); for (int j = 0; j < ITEM_ATTRIBUTE_MAX_NUM; j++) iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",attrtype%d,attrvalue%d",j,j); - iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",price,status,ownername,buyername"); + iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",price,status,ownername,buyername,HEX(port_extra)"); #ifdef ENABLE_CHANGELOOK_SYSTEM iLen+=snprintf(szQuery+iLen, sizeof(szQuery)-iLen, ",transmutation"); #endif @@ -71,7 +73,7 @@ bool CClientManager::InitializeOfflineShop() { cur = 0; str_to_number(pos, row_item[2]); - if (pos > OFFLINE_SHOP_HOST_ITEM_MAX_NUM) + if (pos >= OFFLINE_SHOP_HOST_ITEM_MAX_NUM) continue; OFFLINE_SHOP_ITEM& item = offlineshop->items[pos]; str_to_number(item.id, row_item[cur++]); @@ -90,6 +92,7 @@ bool CClientManager::InitializeOfflineShop() str_to_number(item.status, row_item[cur++]); strlcpy(item.szOwnerName, row_item[cur++], sizeof(item.szOwnerName)); strlcpy(item.szBuyerName, row_item[cur++], sizeof(item.szBuyerName)); + if(!PortItemExtraRead(row_item[cur++],item.extra)){sys_err("OFFLINE_EXTRA_QUARANTINE id=%u",item.id);return false;} #ifdef ENABLE_CHANGELOOK_SYSTEM str_to_number(item.transmutation, row_item[cur++]); #endif @@ -148,6 +151,7 @@ bool CClientManager::InitializeOfflineShop() void CClientManager::CreateOfflineShop(TOfflineShop* p) { + if(!PortOfflineShopEconomyReady())return; if (!p) return; auto it = m_Offlineshop.find(p->owner_id); @@ -202,8 +206,8 @@ void CClientManager::CreateOfflineShop(TOfflineShop* p) iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d", offlineshop->items[i].transmutation); #endif - iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername"); - iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s'", offlineshop->items[i].szOwnerName); + iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername,port_extra"); + iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s',UNHEX('%s')", offlineshop->items[i].szOwnerName,PortItemExtraHex(offlineshop->items[i].extra).c_str()); snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_item (%s) VALUES (%s)", szColumns, szValues); std::unique_ptr pMsg2(CDBManager::instance().DirectQuery(szQuery)); @@ -249,6 +253,7 @@ void CClientManager::CreateOfflineShop(TOfflineShop* p) void CClientManager::DeleteOfflineShop(DWORD ownerid) { + if(!PortOfflineShopEconomyReady())return; auto it = m_Offlineshop.find(ownerid); if (it == m_Offlineshop.end()) return; @@ -273,6 +278,8 @@ void CClientManager::DeleteOfflineShop(DWORD ownerid) void CClientManager::RemoveItem(OFFLINE_SHOP_ITEM* item) { + if(!PortOfflineShopEconomyReady())return; + if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!item) return; auto it = m_Offlineshop.find(item->owner_id); @@ -305,6 +312,8 @@ void CClientManager::RemoveItem(OFFLINE_SHOP_ITEM* item) void CClientManager::AddItem(OFFLINE_SHOP_ITEM* item) { + if(!PortOfflineShopEconomyReady())return; + if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!item) return; auto it = m_Offlineshop.find(item->owner_id); @@ -339,8 +348,8 @@ void CClientManager::AddItem(OFFLINE_SHOP_ITEM* item) iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",transmutation"); iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",%d", newitem.transmutation); #endif - iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername"); - iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s'", newitem.szOwnerName); + iLen += snprintf(szColumns + iLen, sizeof(szColumns) - iLen, ",ownername,port_extra"); + iUpdateLen += snprintf(szValues + iUpdateLen, sizeof(szValues) - iUpdateLen, ",'%s',UNHEX('%s')", newitem.szOwnerName,PortItemExtraHex(newitem.extra).c_str()); snprintf(szQuery, sizeof(szQuery), "INSERT INTO offline_shop_item (%s) VALUES (%s)", szColumns, szValues); std::unique_ptr pMsg2(CDBManager::instance().DirectQuery(szQuery)); @@ -355,6 +364,8 @@ void CClientManager::AddItem(OFFLINE_SHOP_ITEM* item) void CClientManager::BuyItem(TOfflineShopBuy* buyItem) { + if(!PortOfflineShopEconomyReady())return; + if(!buyItem || buyItem->item.pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!buyItem) return; auto it = m_Offlineshop.find(buyItem->item.owner_id); @@ -452,6 +463,7 @@ void CClientManager::BuyItem(TOfflineShopBuy* buyItem) void CClientManager::WithdrawMoney(DWORD ch) { + if(!PortOfflineShopEconomyReady())return; auto it = m_Offlineshop.find(ch); if (it == m_Offlineshop.end()) // todo player removes price... @@ -635,6 +647,7 @@ void CClientManager::AddTime(DWORD ch) void CClientManager::RecvPackets(const char* data) { + if(!PortOfflineShopEconomyReady())return; BYTE sub_header = (BYTE)*data; switch (sub_header) { diff --git a/src/server/db/src/ClientManagerPlayer.cpp b/src/server/db/src/ClientManagerPlayer.cpp index 0018d31d..fc35e0a0 100755 --- a/src/server/db/src/ClientManagerPlayer.cpp +++ b/src/server/db/src/ClientManagerPlayer.cpp @@ -22,6 +22,22 @@ extern int g_log; // // Check all SELECT syntax on item table before change this function!!! // +bool CClientManager::ValidateLoadedExtra(const TPlayerItem& item,const char* hex) const { + auto found=m_map_itemTableByVnum.find(item.vnum); + if(found==m_map_itemTableByVnum.end())return false; + const auto* proto=found->second; + if(proto->bType!=ITEM_PET || proto->bSubType!=PET_LEVELABLE)return true; + if(!hex || strlen(hex)!=138 || item.alSockets[1]<1 || item.alSockets[1]>120 || item.alSockets[2]<0 || + item.extra.sockets[0]<0 || item.extra.sockets[0]>3 || item.extra.sockets[1]<0 || item.extra.sockets[1]>15)return false; + for(unsigned i=2;i<5;++i)if(item.extra.sockets[i]<0 || item.extra.sockets[i]>20)return false; + for(unsigned i=0;i<15;++i){ + const unsigned type=i<7?item.aAttr[i].bType:item.extra.types[i-7]; + const int value=i<7?item.aAttr[i].sValue:item.extra.values[i-7]; + if((type>29 && type!=99) || value<0 || value>20 || ((type==0||type==99)&&value!=0))return false; + } + return true; +} + bool CreateItemTableFromRes(MYSQL_RES * res, std::vector * pVec, DWORD dwPID) { if (!res) @@ -65,7 +81,12 @@ bool CreateItemTableFromRes(MYSQL_RES * res, std::vector * pVec, DW str_to_number(item.aAttr[j].sValue, row[cur++]); } - PortItemExtraRead(mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL,item.extra); + if (!PortItemExtraRead(mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL,item.extra) || + !CClientManager::instance().ValidateLoadedExtra(item,mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL)) { + // Original bytes stay in SQL. Do not create caches or return partial inventory. + sys_err("ITEM_EXTRA_QUARANTINE owner=%u item=%u window=%u: invalid port_extra", dwPID,item.id,item.window); + pVec->clear();return false; + } item.owner = dwPID; } @@ -226,6 +247,7 @@ void CClientManager::PutPlayerCache(TPlayerTable * pNew) */ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoadPacket * packet) { + if(!EconomyBeforeLoad(peer,dwHandle,packet)){if(!m_economyFences.count(packet->player_id))peer->EncodeHeader(HEADER_DG_PLAYER_LOAD_FAILED,dwHandle,0);return;} CPlayerTableCache * c; TPlayerTable * pTab; @@ -722,7 +744,10 @@ void CClientManager::RESULT_ITEM_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dwHa { static std::vector s_items; //DBì—�서 ì•„ì�´í…œ 정보를 ì�½ì–´ì˜¨ë‹¤. - CreateItemTableFromRes(pRes, &s_items, dwPID); + if (!CreateItemTableFromRes(pRes, &s_items, dwPID)) { + peer->EncodeHeader(HEADER_DG_PLAYER_LOAD_FAILED, dwHandle, 0); + return; + } DWORD dwCount = s_items.size(); peer->EncodeHeader(HEADER_DG_ITEM_LOAD, dwHandle, sizeof(DWORD) + sizeof(TPlayerItem) * dwCount); @@ -827,6 +852,7 @@ void CClientManager::RESULT_QUEST_LOAD(CPeer * peer, MYSQL_RES * pRes, DWORD dwH */ void CClientManager::QUERY_PLAYER_SAVE(CPeer * peer, DWORD dwHandle, TPlayerTable * pkTab) { + if(!EconomySaveAllowed(peer,pkTab->id))return; if (g_test_server) sys_log(0, "PLAYER_SAVE: %s", pkTab->name); @@ -843,7 +869,7 @@ void CClientManager::__QUERY_PLAYER_CREATE(CPeer *peer, DWORD dwHandle, TPlayerC { char queryStr[QUERY_MAX_LEN]; int queryLen; - int player_id; + DWORD player_id = 0; // 한 계정ì—� Xì´ˆ 내로 ìº�릭터 ìƒ�성ì�„ í•  수 없다. time_by_id_map_t::iterator it = s_createTimeByAccountID.find(packet->account_id); @@ -958,24 +984,23 @@ void CClientManager::__QUERY_PLAYER_CREATE(CPeer *peer, DWORD dwHandle, TPlayerC if (g_test_server) sys_log(0, "Create_Player queryLen[%d] TEXT[%s]", queryLen, text); - if (pMsg2->Get()->uiAffectedRows <= 0) + if (!pMsg2->Get()->HasAffectedRows() || !pMsg2->Get()->GetInsertID32(player_id)) { peer->EncodeHeader(HEADER_DG_PLAYER_CREATE_ALREADY, dwHandle, 0); - sys_log(0, "ALREADY EXIST3 query: %s AffectedRows %lu", queryStr, pMsg2->Get()->uiAffectedRows); + sys_log(0, "ALREADY EXIST3 query: %s AffectedRows %llu", queryStr, static_cast(pMsg2->Get()->uiAffectedRows)); return; } - player_id = pMsg2->Get()->uiInsertID; - snprintf(queryStr, sizeof(queryStr), "UPDATE player_index%s SET pid%d=%d WHERE id=%d", + snprintf(queryStr, sizeof(queryStr), "UPDATE player_index%s SET pid%d=%u WHERE id=%u", GetTablePostfix(), packet->account_index + 1, player_id, packet->account_id); std::unique_ptr pMsg3(CDBManager::instance().DirectQuery(queryStr)); - if (pMsg3->Get()->uiAffectedRows <= 0) + if (!pMsg3->Get()->HasAffectedRows()) { sys_err("QUERY_ERROR: %s", queryStr); - snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%d", GetTablePostfix(), player_id); + snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%u", GetTablePostfix(), player_id); CDBManager::instance().DirectQuery(queryStr); peer->EncodeHeader(HEADER_DG_PLAYER_CREATE_FAILED, dwHandle, 0); @@ -1112,13 +1137,18 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg) return; } + if(!EconomyCanDelete(dwPID)) { + peer->EncodeHeader(HEADER_DG_PLAYER_DELETE_FAILED,pi->dwHandle,1); + peer->EncodeBYTE(pi->account_index); + delete pi;return; + } char queryStr[QUERY_MAX_LEN]; snprintf(queryStr, sizeof(queryStr), "INSERT INTO player%s_deleted SELECT * FROM player%s WHERE id=%d", GetTablePostfix(), GetTablePostfix(), pi->player_id); std::unique_ptr pIns(CDBManager::instance().DirectQuery(queryStr)); - if (pIns->Get()->uiAffectedRows == 0 || pIns->Get()->uiAffectedRows == (uint32_t)-1) + if (pIns->Get()->uiAffectedRows == 0 || pIns->Get()->uiAffectedRows == UINT64_MAX) { sys_log(0, "PLAYER_DELETE FAILED %u CANNOT INSERT TO player%s_deleted", dwPID, GetTablePostfix()); @@ -1170,7 +1200,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg) std::unique_ptr pMsg(CDBManager::instance().DirectQuery(queryStr)); - if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1) + if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX) { sys_log(0, "PLAYER_DELETE FAIL WHEN UPDATE account table"); peer->EncodeHeader(HEADER_DG_PLAYER_DELETE_FAILED, pi->dwHandle, 1); diff --git a/src/server/db/src/Config.cpp b/src/server/db/src/Config.cpp index d35633b9..5b314be1 100755 --- a/src/server/db/src/Config.cpp +++ b/src/server/db/src/Config.cpp @@ -26,72 +26,48 @@ void CConfig::NextLine(FILE *fp) } } -bool CConfig::GetWord(FILE *fp, char *tar) +bool CConfig::GetWord(FILE *fp, char *dest, size_t size) { - int i = 0; - int c; - - int semicolon_mode = 0; - - while ((c = fgetc(fp)) != EOF) - { - if (c == 13) - continue; - - if (semicolon_mode) - { - if (c == '"') - { - tar[i] = '\0'; - return true; - } - - tar[i++] = c; - continue; - } - else - { - if (i == 0) - { - if (c == '"') - { - semicolon_mode = 1; - continue; - } - - if (c == ' ' || c == '\t' || c == '\n') - { - continue; - } - } - - if ((c == ' ' || c == '\t' || c == '\n')) - { - // ÅÜ. - tar[i] = '\0'; - return true; - } - - tar[i] = c; - ++i; - } - } - - return (i != 0); + if (!fp || !dest || !size) { m_readError = true; return false; } + size_t used = 0; + bool quoted = false, started = false; + dest[0] = 0; + int c; + while ((c = fgetc(fp)) != EOF) + { + if (c == 0) { m_readError = true; return false; } + if (c == '\r') continue; + if (!started) + { + if (c == ' ' || c == '\t' || c == '\n') continue; + started = true; + if (c == '"') { quoted = true; continue; } + } + if ((quoted && c == '"') || (!quoted && (c == ' ' || c == '\t' || c == '\n'))) + return true; + if (used + 1 >= size) { m_readError = true; return false; } + dest[used++] = static_cast(c); // fgetc returned a byte, not EOF. + dest[used] = 0; + } + if (ferror(fp) || quoted) m_readError = true; + return started && !m_readError; } -bool CConfig::GetLine(FILE* fp, char*dest) +bool CConfig::GetLine(FILE *fp, char *dest, size_t size) { - int c; - int i = 0; - while ((c = fgetc(fp)) != EOF) - { - if (c == '\n') - return true; - dest[i] = c; - ++i; - } - return true; + if (!fp || !dest || !size) { m_readError = true; return false; } + size_t used = 0; + dest[0] = 0; + int c; + while ((c = fgetc(fp)) != EOF) + { + if (c == '\n') return true; + if (c == 0 || used + 1 >= size) { m_readError = true; return false; } + dest[used++] = static_cast(c); + dest[used] = 0; + } + if (ferror(fp)) m_readError = true; + return !m_readError; } bool CConfig::LoadFile(const char* filename) @@ -105,8 +81,10 @@ bool CConfig::LoadFile(const char* filename) return false; int mode = 0; + m_readError = false; + TValueMap staged = m_valueMap; - while (GetWord(fp, szTmp)) + while (GetWord(fp, szTmp, sizeof(szTmp))) { if (strcmp(szTmp, "//") == 0) { @@ -128,15 +106,15 @@ bool CConfig::LoadFile(const char* filename) case 2: mode = 0; - m_valueMap.insert(TValueMap::value_type(comment, szTmp)); + staged.insert(TValueMap::value_type(comment, szTmp)); break; } // ITEM_ID_RANGE if (mode == 2 && strcmp(comment, "ITEM_ID_RANGE") == 0) { - GetLine(fp, szTmp); - m_valueMap.insert(TValueMap::value_type(comment, szTmp)); + if (!GetLine(fp, szTmp, sizeof(szTmp))) break; + staged.insert(TValueMap::value_type(comment, szTmp)); mode = 0; } @@ -145,8 +123,10 @@ bool CConfig::LoadFile(const char* filename) // ÆÄÀÏ ´Ý´Â ºÎºÐ. + const bool valid = !m_readError && !ferror(fp) && mode == 0; fclose(fp); - return true; + if (valid) m_valueMap.swap(staged); + return valid; } std::string * CConfig::Search(const char* key) @@ -165,11 +145,14 @@ bool CConfig::GetParam(const char*key, int index, DWORD *Param) if (!pstStr) return false; - char szParam[5][32]; + if (!Param || index < 0 || index >= 5) return false; + char szParam[5][32] = {}; - sscanf(pstStr->c_str(), "%s %s %s %s %s", szParam[0],szParam[1],szParam[2],szParam[3],szParam[4]); + if (sscanf(pstStr->c_str(), "%31s %31s %31s %31s %31s", szParam[0],szParam[1],szParam[2],szParam[3],szParam[4]) <= index) return false; - str_to_number(*Param, szParam[index]); + unsigned long long value = 0; + if (!str_to_number(value, szParam[index]) || value > UINT32_MAX) return false; + *Param = static_cast(value); sys_log(0, "GetParam %d", *Param); return true; @@ -239,12 +222,15 @@ bool CConfig::GetValue(const char * key, char *dest, size_t destSize) bool CConfig::GetTwoValue(const char* key, DWORD * dest1, DWORD *dest2) { - if (!GetParam(key, 0, dest1)) + DWORD first=0, second=0; + if (!dest1 || !dest2) return false; + if (!GetParam(key, 0, &first)) return false; - if (!GetParam(key, 1, dest2)) + if (!GetParam(key, 1, &second)) return false; + *dest1=first; *dest2=second; return true; } diff --git a/src/server/db/src/Config.h b/src/server/db/src/Config.h index 45088321..15767b3c 100755 --- a/src/server/db/src/Config.h +++ b/src/server/db/src/Config.h @@ -15,8 +15,8 @@ class CConfig : public singleton bool GetValue(const char* key, DWORD* dest); bool GetValue(const char* key, BYTE* dest); bool GetValue(const char* key, char* dest, size_t destSize); - bool GetWord(FILE* fp, char* dest); - bool GetLine(FILE* fp, char* dest); + bool GetWord(FILE* fp, char* dest, size_t size); + bool GetLine(FILE* fp, char* dest, size_t size); bool GetTwoValue(const char* key, DWORD * dest1, DWORD *dest2); void NextLine(FILE* fp); @@ -29,6 +29,7 @@ class CConfig : public singleton private: TValueMap m_valueMap; + bool m_readError = false; }; #endif diff --git a/src/server/db/src/DBManager.h b/src/server/db/src/DBManager.h index 0788bd98..5a21c4ad 100755 --- a/src/server/db/src/DBManager.h +++ b/src/server/db/src/DBManager.h @@ -46,6 +46,9 @@ class CDBManager : public singleton void ReturnQuery(const char * c_pszQuery, int iType, DWORD dwIdent, void * pvData, int iSlot = SQL_PLAYER); void AsyncQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER); + void EconomyAsyncFence(DWORD pid) { m_asyncSQL[SQL_PLAYER]->ReturnQuery("SELECT 1",reinterpret_cast(static_cast(pid))); } + SQLMsg* PopEconomyAsyncFence() { SQLMsg* message=nullptr;return m_asyncSQL[SQL_PLAYER]->PopResult(&message)?message:nullptr; } + uint64_t EconomyFailures(bool async) { return (async?m_asyncSQL[SQL_PLAYER]:m_mainSQL[SQL_PLAYER])->FailureEpoch(); } MYSQL* DirectHandle(int slot=SQL_PLAYER) { return m_directSQL[slot]->GetSQLHandle(); } SQLMsg * DirectQuery(const char * c_pszQuery, int iSlot = SQL_PLAYER); diff --git a/src/server/db/src/Economy.cpp b/src/server/db/src/Economy.cpp new file mode 100644 index 00000000..49c6ae8f --- /dev/null +++ b/src/server/db/src/Economy.cpp @@ -0,0 +1,162 @@ +#include "stdafx.h" +#include "ClientManager.h" +#include "Cache.h" +#include "QID.h" +#include "Main.h" +#include "../../common/economy_mysql.h" +#include +#include "../../common/economy_view.h" + +namespace { +using namespace PortEconomy; +using Query=std::unique_ptr; +Query query(const std::string& sql){return Query(CDBManager::instance().DirectQuery(sql.c_str()));} +bool valid(const Query& q){return q&&!q->uiSQLErrno&&q->Get();} +// Schema installation/removal requires a coordinated restart. An absent schema +// is detected once without issuing failing SQL for every ordinary item save. +int schema() { + static int state=-1;if(state>=0)return state; + auto q=query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_economy_version'"); + if(!valid(q)||q->Get()->uiNumRows!=1)return -1; + MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);if(!row||!row[0])return -1; + state=std::string(row[0])=="1"?1:0;return state; +} +bool owns(CLoginData* login,CPeer* peer,DWORD pid,bool playing) { + if(!login || login->GetConnectedPeerHandle()!=peer->GetHandle() || login->IsPlay()!=playing)return false; + for(const auto& p:login->GetAccountRef().players)if(p.dwID==pid)return true; + return false; +} +} + +void CClientManager::EconomyRequest(CPeer* peer,DWORD handle,const char* data,DWORD length) { + if(length!=sizeof(PortEconomy::Request)||!peer->GetChannel())return; + PortEconomy::Request r;memcpy(&r,data,sizeof(r)); + if(!PortEconomy::Valid(r)||!owns(GetLoginDataByAID(r.account),peer,r.player,true))return; + PortEconomy::Reply reply={};reply.account=r.account;reply.player=r.player; + auto send=[&](const std::string& text,bool success){reply.ok=success;const std::string message=r.operation==PortEconomy::UiStatus&&text.find("MTECON1 ")!=0?"MTECON1 error "+std::to_string(r.generation)+" storage":text;strlcpy(reply.message,message.c_str(),sizeof(reply.message));peer->EncodeHeader(PortEconomy::Header,handle,sizeof(reply));peer->Encode(&reply,sizeof(reply));}; + if(*GetTablePostfix()||schema()!=1){send("Economy transactions require the unsuffixed player schema.",false);return;} + PortEconomy::Mysql mysql(CDBManager::instance().DirectHandle()); + PortEconomy::Store store(mysql,[&](uint32_t vnum){auto it=m_map_itemTableByVnum.find(vnum);return it==m_map_itemTableByVnum.end()?0u:unsigned(it->second->bSize);}); + if(!store.Ready()){send("Economy storage is unavailable; no payment was made.",false);return;} + if(r.operation==PortEconomy::UiStatus) { + std::vector frames; + if(!PortEconomy::View(mysql,r,[&](uint32_t vnum){auto it=m_map_itemTableByVnum.find(vnum);return it==m_map_itemTableByVnum.end()?0u:unsigned(it->second->bSize);},frames)) { + send("MTECON1 error "+std::to_string(r.generation)+" storage",false);return; + } + for(const auto& frame:frames)send(frame,true); + return; + } + if(r.operation==PortEconomy::Status) { + PortEconomy::Rows rows; + if(!mysql.Query("SELECT token,result,reference FROM port_economy_requests WHERE pid="+std::to_string(r.player)+" ORDER BY created_at DESC,token DESC LIMIT 3",rows)){send("Economy storage is unavailable.",false);return;} + std::string text="Recent transactions:"; + for(const auto& row:rows)text+=" "+row[1]+" #"+row[2];send(text,true); + if(mysql.Query("SELECT l.id,l.price,l.state,COALESCE(c.vnum,0),COALESCE(c.count,0) FROM port_economy_listings l LEFT JOIN port_economy_custody c ON c.id=l.item WHERE l.state='OPEN' OR l.owner="+std::to_string(r.player)+" ORDER BY l.id DESC LIMIT 5 OFFSET "+std::to_string(r.reference*5),rows))for(const auto& row:rows)send("Listing #"+row[0]+" vnum="+row[3]+" count="+row[4]+" price="+row[1]+" "+row[2],true); + if(mysql.Query("SELECT id,state FROM port_economy_orders WHERE buyer="+std::to_string(r.player)+" ORDER BY id DESC LIMIT 5 OFFSET "+std::to_string(r.reference*5),rows))for(const auto& row:rows)send("Order #"+row[0]+" "+row[1],true); + if(mysql.Query("SELECT amount FROM port_economy_credit WHERE pid="+std::to_string(r.player),rows))send("Unclaimed proceeds: "+(rows.empty()?std::string("0"):rows[0][0]),true); + return; + } + if(r.operation==PortEconomy::List) { + auto it=m_map_itemTableByVnum.find(r.itemVnum); + if(it==m_map_itemTableByVnum.end() || (it->second->dwAntiFlags&(ITEM_ANTIFLAG_GIVE|ITEM_ANTIFLAG_MYSHOP)) || it->second->bType==ITEM_QUEST) {send("This item cannot be listed.",false);return;} + } + // Materialized Gaya stacks are generated by game using the normal item + // factory. Validate proto stack limits before accepting their durable IDs. + for(unsigned i=0;i2000 || (!(it->second->dwFlags&ITEM_FLAG_STACKABLE)&&reward.count!=1)){send("Invalid reward stack.",false);return;} + } + if(store.Enqueue(r)) { + m_economyOwners[r.player]=r.account; + m_economyEnqueueEpoch.emplace(r.player,std::make_pair(CDBManager::instance().EconomyFailures(false),CDBManager::instance().EconomyFailures(true))); + send("Transaction queued. Reconnect and select the character to settle it; use /mt_economy status for the result.",true); + } else send("Transaction was not accepted, or another request is pending. Reconnect to recover it.",false); +} + +bool CClientManager::EconomyBeforeLoad(CPeer* peer,DWORD handle,TPlayerLoadPacket* packet) { + if(*GetTablePostfix())return true; + const int installed=schema();if(installed==0)return true;if(installed<0)return false; + // Existing ownership checks must run before evicting or fencing any cache. + auto* login=GetLoginDataByAID(packet->account_id); + if(!owns(login,peer,packet->player_id,false))return false; + for(const auto& running:m_economyFences)if(running.second.account==packet->account_id)return false; + auto pending=query("SELECT token FROM port_economy_pending WHERE pid="+std::to_string(packet->player_id)); + if(!valid(pending))return false; + if(!pending->Get()->uiNumRows){m_economyClosed.erase(packet->player_id);return true;} + m_economyOwners[packet->player_id]=packet->account_id; + m_economyClosed.insert(packet->player_id); + EconomyFence fence;fence.account=packet->account_id;fence.peer=peer->GetHandle();fence.handle=handle;fence.load=*packet; + auto& database=CDBManager::instance(); + auto epoch=m_economyEnqueueEpoch.find(packet->player_id); + fence.mainFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(false):epoch->second.first; + fence.asyncFailures=epoch==m_economyEnqueueEpoch.end()?database.EconomyFailures(true):epoch->second.second; + m_economyFences[packet->player_id]=fence; + // Eviction sends every dirty snapshot before the two FIFO barriers. Never + // settle on a cached player, including caches still awaiting logout timeout. + FlushItemCacheSet(packet->player_id);FlushPlayerCacheSet(packet->player_id); + DeleteLogoutPlayer(packet->player_id); + database.ReturnQuery("SELECT 1",QID_ECONOMY_FENCE,packet->player_id,nullptr); + return false; +} + +void CClientManager::EconomyMainFence(DWORD pid,bool failed) { + auto it=m_economyFences.find(pid);if(it==m_economyFences.end())return; + it->second.failed|=failed; + if(!it->second.primed) { + // Earlier load callbacks may themselves queue saves (e.g. mall awards). + // A second main barrier and an async barrier follow those callbacks. + it->second.primed=true; + CDBManager::instance().ReturnQuery("SELECT 1",QID_ECONOMY_FENCE,pid,nullptr); + CDBManager::instance().EconomyAsyncFence(pid); + } else it->second.mainDone=true; +} +void CClientManager::EconomyTick() { + auto& database=CDBManager::instance(); + while(SQLMsg* raw=database.PopEconomyAsyncFence()) { + Query q(raw);DWORD pid=static_cast(reinterpret_cast(q->pvUserData)); + auto it=m_economyFences.find(pid);if(it!=m_economyFences.end()){it->second.asyncDone=true;it->second.failed|=q->uiSQLErrno!=0;} + } + for(auto it=m_economyFences.begin();it!=m_economyFences.end();) { + auto& fence=it->second; + if(fence.nextAttempt>time(nullptr)){++it;continue;} + if(!fence.mainDone||!fence.asyncDone){++it;continue;} + auto* login=GetLoginDataByAID(fence.account); + if(login&&login->IsPlay()){++it;continue;} + PortEconomy::Mysql mysql(database.DirectHandle()); + PortEconomy::Store store(mysql,[&](uint32_t vnum){auto p=m_map_itemTableByVnum.find(vnum);return p==m_map_itemTableByVnum.end()?0u:unsigned(p->second->bSize);}); + const bool failed=fence.failed||database.EconomyFailures(false)!=fence.mainFailures||database.EconomyFailures(true)!=fence.asyncFailures; + bool done=failed?store.Abort(it->first,fence.account):store.Settle(it->first,fence.account)!=PortEconomy::Store::Retry; + if(done) { + m_economyEnqueueEpoch.erase(it->first); + sys_log(0,"ECONOMY_SETTLE pid=%u outcome=%s ref=%llu",it->first,failed?"save_failed":store.Outcome().c_str(),static_cast(store.Reference())); + EconomyFence completed=fence;it=m_economyFences.erase(it); + if(CPeer* peer=GetPeer(completed.peer))QUERY_PLAYER_LOAD(peer,completed.handle,&completed.load); + } else {fence.nextAttempt=time(nullptr)+5;++it;} + } +} + +bool CClientManager::EconomySaveAllowed(CPeer* peer,DWORD pid) { + if(m_economyClosed.count(pid))return false; + auto it=m_economyOwners.find(pid);if(it==m_economyOwners.end())return true; + return owns(GetLoginDataByAID(it->second),peer,pid,true); +} +bool CClientManager::EconomyItemWritable(DWORD id) { + if(*GetTablePostfix())return true; + const int installed=schema();if(installed==0)return true;if(installed<0)return false; + auto q=query("SELECT id FROM port_economy_custody WHERE id="+std::to_string(id)); + if(!valid(q))return false; + return q->Get()->uiNumRows==0; +} + +// Native character deletion must not strand escrow, pending refunds, proceeds +// or a migrated catalogue outside the tables that legacy deletion cleans up. +// Catalogue users need an explicit audited retirement, not an implicit reset. +bool CClientManager::EconomyCanDelete(DWORD pid) { + if(*GetTablePostfix())return true; + const int installed=schema();if(installed==0)return true;if(installed<0)return false; + if(m_economyFences.count(pid)||m_economyClosed.count(pid))return false; + const std::string id=std::to_string(pid); + auto q=query("SELECT (EXISTS(SELECT 1 FROM port_economy_pending WHERE pid="+id+"))+(EXISTS(SELECT 1 FROM port_economy_listings WHERE owner="+id+" AND state IN('OPEN','RESERVED')))+(EXISTS(SELECT 1 FROM port_economy_orders WHERE buyer="+id+" AND state='READY'))+(EXISTS(SELECT 1 FROM port_economy_credit WHERE pid="+id+" AND amount<>0))+(EXISTS(SELECT 1 FROM port_economy_gaya WHERE pid="+id+" AND generation<>"+std::to_string(PortEconomy::RetiredGeneration)+"))+(EXISTS(SELECT 1 FROM port_economy_gaya WHERE pid="+id+" AND generation="+std::to_string(PortEconomy::RetiredGeneration)+" AND EXISTS(SELECT 1 FROM quest WHERE dwPID="+id+" AND szName='gem' AND szState='points' AND lValue<>0)))"); + if(!valid(q)||q->Get()->uiNumRows!=1)return false; + MYSQL_ROW row=mysql_fetch_row(q->Get()->pSQLResult);return row&&row[0]&&std::string(row[0])=="0"; +} diff --git a/src/server/db/src/GuildManager.cpp b/src/server/db/src/GuildManager.cpp index f4d7d745..78db6deb 100755 --- a/src/server/db/src/GuildManager.cpp +++ b/src/server/db/src/GuildManager.cpp @@ -1067,13 +1067,12 @@ bool CGuildManager::ReserveWar(TPacketGuildWar * p) std::unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); - if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiInsertID == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg->Get()->uiAffectedRows == 0 || !pmsg->Get()->GetInsertID32(t.dwID) || pmsg->Get()->uiAffectedRows == UINT64_MAX) { sys_err("GuildWar: Cannot insert row"); return false; } - t.dwID = pmsg->Get()->uiInsertID; m_map_kWarReserve.insert(std::make_pair(t.dwID, new CGuildWarReserve(t))); @@ -1293,7 +1292,7 @@ bool CGuildWarReserve::Bet(const char * pszLogin, DWORD dwGold, DWORD dwGuild) std::unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); - if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == UINT64_MAX) { sys_log(0, "GuildWarReserve::Bet: failed. cannot insert row to guild_war_bet table"); return false; diff --git a/src/server/db/src/ItemAwardManager.cpp b/src/server/db/src/ItemAwardManager.cpp index 54f4b1a6..34e29a69 100755 --- a/src/server/db/src/ItemAwardManager.cpp +++ b/src/server/db/src/ItemAwardManager.cpp @@ -28,7 +28,7 @@ void ItemAwardManager::Load(SQLMsg * pMsg) { MYSQL_RES * pRes = pMsg->Get()->pSQLResult; - for (uint i = 0; i < pMsg->Get()->uiNumRows; ++i) + for (uint64_t i = 0; i < pMsg->Get()->uiNumRows; ++i) { MYSQL_ROW row = mysql_fetch_row(pRes); int col = 0; diff --git a/src/server/db/src/ItemIDRangeManager.cpp b/src/server/db/src/ItemIDRangeManager.cpp index 099765bd..377ecb69 100755 --- a/src/server/db/src/ItemIDRangeManager.cpp +++ b/src/server/db/src/ItemIDRangeManager.cpp @@ -93,20 +93,45 @@ bool CItemIDRangeManager::BuildRange(DWORD dwMin, DWORD dwMax, TItemIDRangeTable snprintf(szQuery, sizeof(szQuery), "SELECT MAX(id) FROM item%s WHERE id >= %u and id <= %u", GetTablePostfix(), dwMin, dwMax); + if(!*GetTablePostfix()) { + // Legacy escrow remains reserved until explicit reconciliation. Closing + // its UI must not make those original IDs available after a DB restart. + auto* legacy=CDBManager::instance().DirectQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='offline_shop_item'"); + if(!legacy || legacy->uiSQLErrno || !legacy->Get() || legacy->Get()->uiNumRows!=1 || !legacy->Get()->pSQLResult){delete legacy;return false;} + row=mysql_fetch_row(legacy->Get()->pSQLResult); + const bool hasLegacy=row && row[0] && !strcmp(row[0],"1"); + const bool noLegacy=row && row[0] && !strcmp(row[0],"0"); + delete legacy;if(!hasLegacy && !noLegacy)return false; + SQLMsg* version=CDBManager::instance().DirectQuery("SELECT version FROM port_economy_version WHERE id=1"); + if(!version)return false; + const bool absent=version->uiSQLErrno==ER_NO_SUCH_TABLE; + const bool valid=!version->uiSQLErrno && version->Get() && version->Get()->uiNumRows==1; + delete version; + if(!absent && !valid)return false; + const std::string bounds=" WHERE id BETWEEN "+std::to_string(dwMin)+" AND "+std::to_string(dwMax); + std::string sources="SELECT id FROM item"+bounds; + if(hasLegacy)sources+=" UNION ALL SELECT id FROM offline_shop_item"+bounds; + if(valid)sources+=" UNION ALL SELECT id FROM port_economy_custody"+bounds+" UNION ALL SELECT id FROM port_economy_item_reservations"+bounds; + snprintf(szQuery,sizeof(szQuery),"SELECT MAX(id) FROM (%s) AS allocated_ids",sources.c_str()); + } pMsg = CDBManager::instance().DirectQuery(szQuery); + if(!pMsg || pMsg->uiSQLErrno || !pMsg->Get() || pMsg->Get()->uiNumRows!=1 || !pMsg->Get()->pSQLResult){delete pMsg;return false;} if (pMsg != NULL) { - if (pMsg->Get()->uiNumRows > 0) + if (pMsg->Get()->uiNumRows == 1 && pMsg->Get()->pSQLResult) { row = mysql_fetch_row(pMsg->Get()->pSQLResult); - str_to_number(dwItemMaxID, row[0]); + unsigned long long maximum=0; + if(!row || (row[0] && (!str_to_number(maximum,row[0]) || maximum>UINT32_MAX))){delete pMsg;return false;} + dwItemMaxID=static_cast(maximum); } delete pMsg; } if (dwItemMaxID == 0) dwItemMaxID = dwMin; + else if(dwItemMaxID>=dwMax)return false; else dwItemMaxID++; @@ -126,28 +151,14 @@ bool CItemIDRangeManager::BuildRange(DWORD dwMin, DWORD dwMax, TItemIDRangeTable pMsg = CDBManager::instance().DirectQuery(szQuery); - if (pMsg != NULL) - { - if (pMsg->Get()->uiNumRows > 0) - { - DWORD count = 0; - row = mysql_fetch_row(pMsg->Get()->pSQLResult); - str_to_number(count, row[0]); - - if (count > 0) - { - sys_err("ItemIDRange: Build: %u ~ %u\thave a item", range.dwUsableItemIDMin, range.dwMax); - return false; - } - else - { - sys_log(0, "ItemIDRange: Build: %u ~ %u start:%u", range.dwMin, range.dwMax, range.dwUsableItemIDMin); - return true; - } - } - - delete pMsg; - } + if(!pMsg || pMsg->uiSQLErrno || !pMsg->Get() || pMsg->Get()->uiNumRows!=1 || !pMsg->Get()->pSQLResult){delete pMsg;return false;} + row=mysql_fetch_row(pMsg->Get()->pSQLResult); + unsigned long long count=0; + const bool empty=row && row[0] && str_to_number(count,row[0]) && count==0; + delete pMsg; + if(!empty)return false; + sys_log(0,"ItemIDRange: Build: %u ~ %u start:%u",range.dwMin,range.dwMax,range.dwUsableItemIDMin); + return true; } return false; diff --git a/src/server/db/src/Makefile b/src/server/db/src/Makefile index 22a8fa75..c32fdfee 100755 --- a/src/server/db/src/Makefile +++ b/src/server/db/src/Makefile @@ -39,7 +39,7 @@ SRCS = Config.cpp NetBase.cpp Peer.cpp PeerBase.cpp Main.cpp Lock.cpp DBManager. ClientManagerBoot.cpp ClientManagerParty.cpp ClientManagerGuild.cpp GuildManager.cpp HB.cpp \ PrivManager.cpp MoneyLog.cpp ItemAwardManager.cpp ClientManagerEventFlag.cpp Marriage.cpp \ Monarch.cpp BlockCountry.cpp ItemIDRangeManager.cpp ClientManagerHorseName.cpp ClientManagerOfflineshop.cpp version.cpp \ - AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp + AuctionManager.cpp ProtoReader.cpp CsvReader.cpp Ava2ItemShop.cpp Economy.cpp OBJS = $(SRCS:%.cpp=$(OBJDIR)/%.o) diff --git a/src/server/db/src/Marriage.cpp b/src/server/db/src/Marriage.cpp index d094ed2e..bbab6bba 100755 --- a/src/server/db/src/Marriage.cpp +++ b/src/server/db/src/Marriage.cpp @@ -44,11 +44,11 @@ namespace marriage unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult * pRes = pmsg->Get(); - sys_log(0, "MarriageList(size=%lu)", pRes->uiNumRows); + sys_log(0, "MarriageList(size=%llu)", static_cast(pRes->uiNumRows)); if (pRes->uiNumRows > 0) { - for (uint uiRow = 0; uiRow != pRes->uiNumRows; ++uiRow) + for (uint64_t uiRow = 0; uiRow != pRes->uiNumRows; ++uiRow) { MYSQL_ROW row = mysql_fetch_row(pRes->pSQLResult); @@ -104,7 +104,7 @@ namespace marriage unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult* res = pmsg->Get(); - if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1) + if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX) { sys_err("cannot insert marriage"); return; @@ -144,7 +144,7 @@ namespace marriage unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult* res = pmsg->Get(); - if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1) + if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX) { sys_err("cannot update marriage : PID:%u %u", dwPID1, dwPID2); return; @@ -190,7 +190,7 @@ namespace marriage unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult* res = pmsg->Get(); - if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1) + if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX) { sys_err("cannot delete marriage : PID:%u %u", dwPID1, dwPID2); return; @@ -234,7 +234,7 @@ namespace marriage unique_ptr pmsg(CDBManager::instance().DirectQuery(szQuery)); SQLResult* res = pmsg->Get(); - if (res->uiAffectedRows == 0 || res->uiAffectedRows == (uint32_t)-1) + if (res->uiAffectedRows == 0 || res->uiAffectedRows == UINT64_MAX) { sys_err("cannot change engage to marriage : PID:%u %u", dwPID1, dwPID2); return; diff --git a/src/server/db/src/ProtoReader.cpp b/src/server/db/src/ProtoReader.cpp index 21838c98..59098ed8 100755 --- a/src/server/db/src/ProtoReader.cpp +++ b/src/server/db/src/ProtoReader.cpp @@ -403,7 +403,7 @@ int get_Item_ApplyType_Value(string inputString) "APPLY_ENERGY", "APPLY_DEF_GRADE", "APPLY_COSTUME_ATTR_BONUS", "APPLY_MAGIC_ATTBONUS_PER", "APPLY_MELEE_MAGIC_ATTBONUS_PER", "APPLY_RESIST_ICE", "APPLY_RESIST_EARTH", "APPLY_RESIST_DARK", "APPLY_ANTI_CRITICAL_PCT", "APPLY_ANTI_PENETRATE_PCT", // PORT AVA2 numbering: 92-138 not ported yet (common/length.h) - "APPLY_RESERVED_92", "APPLY_RESERVED_93", "APPLY_RESERVED_94", "APPLY_RESERVED_95", "APPLY_RESERVED_96", "APPLY_RESERVED_97", "APPLY_RESERVED_98", "APPLY_RESERVED_99", + "APPLY_RESERVED_92", "APPLY_RESERVED_93", "APPLY_RESERVED_94", "APPLY_RESERVED_95", "APPLY_RESERVED_96", "APPLY_RESERVED_97", "APPLY_RESIST_MAGIC_REDUCTION", "APPLY_RESIST_HUMAN", "APPLY_RESERVED_100", "APPLY_RESERVED_101", "APPLY_RESERVED_102", "APPLY_RESERVED_103", "APPLY_RESERVED_104", "APPLY_RESERVED_105", "APPLY_RESERVED_106", "APPLY_RESERVED_107", "APPLY_RESERVED_108", "APPLY_RESERVED_109", "APPLY_RESERVED_110", "APPLY_RESERVED_111", "APPLY_RESERVED_112", "APPLY_RESERVED_113", "APPLY_RESERVED_114", "APPLY_RESERVED_115", "APPLY_RESERVED_116", "APPLY_RESERVED_117", "APPLY_RESERVED_118", "APPLY_RESERVED_119", "APPLY_RESERVED_120", "APPLY_RESERVED_121", "APPLY_RESERVED_122", "APPLY_ENCHANT_ELECT", diff --git a/src/server/db/src/QID.h b/src/server/db/src/QID.h index 230d2ef6..96fe1202 100755 --- a/src/server/db/src/QID.h +++ b/src/server/db/src/QID.h @@ -32,7 +32,8 @@ enum QID QID_ITEMPRICE_SAVE, ///< 21, ¾ÆÀÌÅÛ °¡°ÝÁ¤º¸ ÀúÀå Äõ¸® QID_ITEMPRICE_DESTROY, ///< 22, ¾ÆÀÌÅÛ °¡°ÝÁ¤º¸ »èÁ¦ Äõ¸® QID_ITEMPRICE_LOAD_FOR_UPDATE, ///< 23, °¡°ÝÁ¤º¸ ¾÷µ¥ÀÌÆ®¸¦ À§ÇÑ ¾ÆÀÌÅÛ °¡°ÝÁ¤º¸ ·Îµå Äõ¸® - QID_ITEMPRICE_LOAD, ///< 24, ¾ÆÀÌÅÛ °¡°ÝÁ¤º¸ ·Îµå Äõ¸® + QID_ECONOMY_FENCE = 100, + QID_ITEMPRICE_LOAD = 24, ///< 24, ¾ÆÀÌÅÛ °¡°ÝÁ¤º¸ ·Îµå Äõ¸® // END_OF_MYSHOP_PRICE_LIST }; diff --git a/src/server/game/src/BattleArena.cpp b/src/server/game/src/BattleArena.cpp index 4ec76b14..d4a94600 100755 --- a/src/server/game/src/BattleArena.cpp +++ b/src/server/game/src/BattleArena.cpp @@ -52,9 +52,9 @@ struct FWarpToHome if ( lpChar->GetGMLevel() != GM_PLAYER ) return; } - int nEmpire, nMapIndex, x, y; + const BYTE nEmpire = lpChar->GetEmpire(); + int nMapIndex, x, y; - nEmpire = lpChar->GetEmpire(); nMapIndex = EMPIRE_START_MAP(nEmpire); x = EMPIRE_START_X(nEmpire); y = EMPIRE_START_Y(nEmpire); @@ -243,7 +243,7 @@ bool CBattleArena::Start(int nEmpire) m_nEmpire = nEmpire; char szBuf[1024]; - snprintf(szBuf, sizeof(szBuf), LC_TEXT("%sÀÇ ¼ºÀ¸·Î ¸ó½ºÅ͵éÀÌ Áø±ºÇϰí ÀÖ½À´Ï´Ù."), EMPIRE_NAME(m_nEmpire)); + snprintf(szBuf, sizeof(szBuf), LC_TEXT("%sÀÇ ¼ºÀ¸·Î ¸ó½ºÅ͵éÀÌ Áø±ºÇϰí ÀÖ½À´Ï´Ù."), EMPIRE_NAME(static_cast(nEmpire))); BroadcastNotice(szBuf); BroadcastNotice(LC_TEXT("10ºÐ µÚ ¼ºÀ» °ø°ÝÇÒ ¿¹Á¤ÀÔ´Ï´Ù.")); diff --git a/src/server/game/src/Makefile b/src/server/game/src/Makefile index 3dc95e64..79ade9f3 100755 --- a/src/server/game/src/Makefile +++ b/src/server/game/src/Makefile @@ -61,7 +61,7 @@ CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp desc_client.cpp desc_manager.cpp desc_p2p.cpp dev_log.cpp dungeon.cpp empire_text_convert.cpp entity.cpp\ entity_view.cpp event.cpp event_queue.cpp exchange.cpp file_loader.cpp fishing.cpp gm.cpp guild.cpp\ guild_manager.cpp guild_war.cpp horse_rider.cpp horsename_manager.cpp input.cpp input_auth.cpp input_db.cpp\ - input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp ava2_channel.cpp new_mob_timer.cpp ava2_track.cpp ava2_ticket_shop.cpp ava2_itemshop.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.cpp port_special_storage.cpp offline_shop.cpp offlineshop_manager.cpp offlineshop_search_manager.cpp port_offlineshop.cpp port_ava2_dungeon.cpp port_gaya.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ + input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp ava2_channel.cpp new_mob_timer.cpp ava2_track.cpp ava2_ticket_shop.cpp ava2_itemshop.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.cpp port_special_storage.cpp offline_shop.cpp offlineshop_manager.cpp offlineshop_search_manager.cpp port_offlineshop.cpp port_ava2_dungeon.cpp port_gaya.cpp port_economy.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ item.cpp item_addon.cpp item_attribute.cpp item_manager.cpp item_manager_idrange.cpp locale.cpp\ locale_service.cpp log.cpp login_data.cpp lzo_manager.cpp marriage.cpp matrix_card.cpp\ messenger_manager.cpp mining.cpp mob_manager.cpp monarch.cpp motion.cpp over9refine.cpp p2p.cpp packet_info.cpp\ @@ -143,3 +143,6 @@ $(OBJDIR)/questlua_item.o: port_attr_lock.h $(OBJDIR)/ava2_channel.o: ava2_channel.h ava2_channel_registry.h $(OBJDIR)/char.o $(OBJDIR)/cmd_general.o $(OBJDIR)/input_p2p.o $(OBJDIR)/p2p.o $(OBJDIR)/input_login.o: ava2_channel.h + +$(OBJDIR)/cmd_general.o: port_features.h port_rank_runtime.h +$(OBJDIR)/char_battle.o $(OBJDIR)/char_skill.o: port_magic_reduction.h diff --git a/src/server/game/src/MarkManager.cpp b/src/server/game/src/MarkManager.cpp index 8979216f..1287af7f 100755 --- a/src/server/game/src/MarkManager.cpp +++ b/src/server/game/src/MarkManager.cpp @@ -2,6 +2,7 @@ #include "MarkManager.h" #include "crc32.h" +#include CGuildMarkImage * CGuildMarkManager::__NewImage() { @@ -47,29 +48,27 @@ void CGuildMarkManager::SetMarkPathPrefix(const char * prefix) // ¸¶Å© À妽º ºÒ·¯¿À±â (¼­¹ö¿¡¼­¸¸ »ç¿ë) bool CGuildMarkManager::LoadMarkIndex() { - char buf[64]; - snprintf(buf, sizeof(buf), "mark/%s_index", m_pathPrefix.c_str()); - FILE * fp = fopen(buf, "r"); - - if (!fp) - return false; - - DWORD guildID; - DWORD markID; - - char line[256]; - - while (fgets(line, sizeof(line)-1, fp)) - { - sscanf(line, "%u %u", &guildID, &markID); - line[0] = '\0'; - AddMarkIDByGuildID(guildID, markID); - } - - LoadMarkImages(); - - fclose(fp); - return true; + char filename[64];snprintf(filename,sizeof(filename),"mark/%s_index",m_pathPrefix.c_str()); + FILE* file=fopen(filename,"r");if(!file)return false; + std::map staged;std::set used;char line[256];bool valid=true; + while(true) { + const long begin=ftell(file);if(begin<0){valid=false;break;} + if(!fgets(line,sizeof(line),file))break; + const long end=ftell(file); + if(end=static_cast(sizeof(line))){valid=false;break;} + const size_t length=static_cast(end-begin); + if(memchr(line,0,length) || (length==sizeof(line)-1 && line[length-1]!='\n')){valid=false;break;} + std::istringstream fields(std::string(line,length));fields>>std::ws;if(fields.eof())continue; + uint64_t guild=0,mark=0;std::string tail; + if(!(fields>>guild>>mark)||fields>>tail || !guild || guild>UINT16_MAX || + mark>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT || staged.count(static_cast(guild)) || + !used.insert(static_cast(mark)).second){valid=false;break;} + staged.emplace(static_cast(guild),static_cast(mark)); + } + if(ferror(file))valid=false;fclose(file);if(!valid)return false; + std::set free; + for(DWORD id=0;id= MAX_IMAGE_COUNT * CGuildMarkImage::MARK_TOTAL_COUNT) - return false; - - //sys_log(0, "MarkManager: guild_id=%d mark_id=%d", guildID, markID); - m_mapGID_MarkID.insert(std::map::value_type(guildID, markID)); - m_setFreeMarkID.erase(markID); - return true; + if(!guildID || guildID>UINT16_MAX || markID>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT)return false; + const auto existing=m_mapGID_MarkID.find(guildID); + if(existing!=m_mapGID_MarkID.end())return existing->second==markID; + if(!m_setFreeMarkID.count(markID))return false; + m_mapGID_MarkID.emplace(guildID,markID);m_setFreeMarkID.erase(markID);return true; } DWORD CGuildMarkManager::GetMarkID(DWORD guildID) @@ -188,24 +185,24 @@ DWORD CGuildMarkManager::__AllocMarkID(DWORD guildID) DWORD CGuildMarkManager::GetMarkImageCount() const { - return m_mapIdx_Image.size(); + return static_cast(m_mapIdx_Image.size()); } DWORD CGuildMarkManager::GetMarkCount() const { - return m_mapGID_MarkID.size(); + return static_cast(m_mapGID_MarkID.size()); } // SERVER -void CGuildMarkManager::CopyMarkIdx(char * pcBuf) const +bool CGuildMarkManager::CopyMarkIdx(char* buffer, size_t capacity) const { - WORD * pwBuf = (WORD *) pcBuf; - - for (std::map::const_iterator it = m_mapGID_MarkID.begin(); it != m_mapGID_MarkID.end(); ++it) - { - *(pwBuf++) = it->first; // guild id - *(pwBuf++) = it->second; // mark id - } + if(m_mapGID_MarkID.size()>capacity/(sizeof(WORD)*2) || (!buffer && !m_mapGID_MarkID.empty()))return false; + for(const auto& entry:m_mapGID_MarkID)if(!entry.first || entry.first>UINT16_MAX || entry.second>=MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT)return false; + for(const auto& entry:m_mapGID_MarkID) { + const WORD guild=static_cast(entry.first), mark=static_cast(entry.second); + memcpy(buffer,&guild,sizeof(guild));memcpy(buffer+sizeof(guild),&mark,sizeof(mark));buffer+=sizeof(WORD)*2; + } + return true; } // SERVER @@ -218,7 +215,7 @@ DWORD CGuildMarkManager::SaveMark(DWORD guildID, BYTE * pbMarkImage) if ((idMark = __AllocMarkID(guildID)) == INVALID_MARK_ID) { sys_err("CGuildMarkManager: cannot alloc mark id %u", guildID); - return false; + return INVALID_MARK_ID; } else sys_log(0, "SaveMark: mark id alloc %u", idMark); diff --git a/src/server/game/src/MarkManager.h b/src/server/game/src/MarkManager.h index f8fa1427..b86df8fa 100755 --- a/src/server/game/src/MarkManager.h +++ b/src/server/game/src/MarkManager.h @@ -45,7 +45,7 @@ class CGuildMarkManager : public singleton DWORD GetMarkID(DWORD guildID); // SERVER - void CopyMarkIdx(char * pcBuf) const; + bool CopyMarkIdx(char* buffer, size_t capacity) const; DWORD SaveMark(DWORD guildID, BYTE * pbMarkImage); void DeleteMark(DWORD guildID); void GetDiffBlocks(DWORD imgIdx, const DWORD * crcList, std::map & mapDiffBlocks); diff --git a/src/server/game/src/OXEvent.cpp b/src/server/game/src/OXEvent.cpp index 02cb6e41..636f2029 100755 --- a/src/server/game/src/OXEvent.cpp +++ b/src/server/game/src/OXEvent.cpp @@ -10,6 +10,7 @@ #include "char_manager.h" #include "OXEvent.h" #include "desc.h" +#include bool COXEventManager::Initialize() { @@ -36,7 +37,7 @@ void COXEventManager::Destroy() OXEventStatus COXEventManager::GetStatus() { - BYTE ret = quest::CQuestManager::instance().GetEventFlag("oxevent_status"); + const int ret = quest::CQuestManager::instance().GetEventFlag("oxevent_status"); switch (ret) { @@ -240,15 +241,16 @@ EVENTFUNC(oxevent_timer) bool COXEventManager::Quiz(unsigned char level, int timelimit) { if (m_vec_quiz.size() == 0) return false; - if (level > m_vec_quiz.size()) level = m_vec_quiz.size() - 1; - if (m_vec_quiz[level].size() <= 0) return false; + const size_t selected = std::min(static_cast(level), m_vec_quiz.size() - 1); + const size_t count = m_vec_quiz[selected].size(); + if (!count || count > static_cast(std::numeric_limits::max())) return false; if (timelimit < 0) timelimit = 30; - int idx = number(0, m_vec_quiz[level].size()-1); + const int idx = number(0, static_cast(count) - 1); SendNoticeMap(LC_TEXT("¹®Á¦ ÀÔ´Ï´Ù."), OXEVENT_MAP_INDEX, true); - SendNoticeMap(m_vec_quiz[level][idx].Quiz, OXEVENT_MAP_INDEX, true); + SendNoticeMap(m_vec_quiz[selected][idx].Quiz, OXEVENT_MAP_INDEX, true); SendNoticeMap(LC_TEXT("¸ÂÀ¸¸é O, Ʋ¸®¸é X·Î À̵¿ÇØÁÖ¼¼¿ä"), OXEVENT_MAP_INDEX, true); if (m_timedEvent != NULL) { @@ -257,14 +259,14 @@ bool COXEventManager::Quiz(unsigned char level, int timelimit) OXEventInfoData* answer = AllocEventInfo(); - answer->answer = m_vec_quiz[level][idx].answer; + answer->answer = m_vec_quiz[selected][idx].answer; timelimit -= 15; m_timedEvent = event_create(oxevent_timer, answer, PASSES_PER_SEC(timelimit)); SetStatus(OXEVENT_QUIZ); - m_vec_quiz[level].erase(m_vec_quiz[level].begin()+idx); + m_vec_quiz[selected].erase(m_vec_quiz[selected].begin()+idx); return true; } @@ -327,7 +329,8 @@ bool COXEventManager::CheckAnswer(bool answer) TPacketGCChat pack_chat; pack_chat.header = HEADER_GC_CHAT; - pack_chat.size = sizeof(TPacketGCChat) + len; + static_assert(sizeof(TPacketGCChat) + sizeof(chatbuf) <= UINT16_MAX, "bounded OX chat packet"); + pack_chat.size = static_cast(sizeof(TPacketGCChat) + static_cast(len)); pack_chat.type = CHAT_TYPE_COMMAND; pack_chat.id = 0; diff --git a/src/server/game/src/affect.h b/src/server/game/src/affect.h index 3c080593..b75a1dac 100755 --- a/src/server/game/src/affect.h +++ b/src/server/game/src/affect.h @@ -18,6 +18,9 @@ class CAffect enum EAffectTypes { AFFECT_NONE, +#ifdef ENABLE_OFFLINESHOP_SYSTEM + AFFECT_DECORATION = 703, +#endif AFFECT_AUTO_PICK_UP = 705, AFFECT_MOV_SPEED = 200, diff --git a/src/server/game/src/ava2_itemshop.cpp b/src/server/game/src/ava2_itemshop.cpp index ba96d3af..7b90e52f 100644 --- a/src/server/game/src/ava2_itemshop.cpp +++ b/src/server/game/src/ava2_itemshop.cpp @@ -18,6 +18,7 @@ #include "questmanager.h" #include "config.h" #include "../../common/point_drop.h" +#include "../../common/point_journal.h" namespace { struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; }; @@ -25,77 +26,13 @@ std::map pendingPoints; LPEVENT pointRetryEvent = NULL; std::string s_pointLogPath = "log/point_rewards_pending.log"; -bool AppendDurableIntent(const Ava2ShopRequest& r) { - if (s_pointLogPath.empty()) return false; - size_t slash = s_pointLogPath.rfind('/'); - if (slash != std::string::npos) { - std::string dir = s_pointLogPath.substr(0, slash); - mkdir(dir.c_str(), 0755); - } - FILE* fp = fopen(s_pointLogPath.c_str(), "a"); - if (!fp) return false; - int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n", - r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0)); - if (res < 0) { fclose(fp); return false; } - if (fflush(fp) != 0) { fclose(fp); return false; } - if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } - fclose(fp); - return true; -} - -bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) { - if (s_pointLogPath.empty()) return false; - FILE* fp = fopen(s_pointLogPath.c_str(), "a"); - if (!fp) return false; - int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n", - token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0)); - if (res < 0) { fclose(fp); return false; } - if (fflush(fp) != 0) { fclose(fp); return false; } - if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } - fclose(fp); - return true; -} - -void CompactDurableLog() { - if (s_pointLogPath.empty()) return; - FILE* fp = fopen(s_pointLogPath.c_str(), "r"); - if (!fp) return; - std::map uncompleted; - char line[256]; - while (fgets(line, sizeof(line), fp)) { - char op[16] = {}, ver[16] = {}, token[64] = {}; - if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { - if (strcmp(op, "INTENT") == 0) { - Ava2ShopRequest r = {}; - r.operation = 3; - unsigned long long t = 0; - if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", - r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { - uncompleted[token] = r; - } - } else if (strcmp(op, "DONE") == 0) { - uncompleted.erase(token); - } - } - } - fclose(fp); - - std::string tmpPath = s_pointLogPath + ".tmp"; - FILE* out = fopen(tmpPath.c_str(), "w"); - if (!out) return; - for (const auto& kv : uncompleted) { - const auto& r = kv.second; - fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n", - r.token, r.account, r.player, r.product, r.count, r.expectedVnum); - } - fflush(out); - fsync(fileno(out)); - fclose(out); - rename(tmpPath.c_str(), s_pointLogPath.c_str()); -} +PointJournal pointJournal; +bool AppendDurableIntent(const Ava2ShopRequest& r){return pointJournal.Intent(r);} +bool AppendDurableDone(const char* token,uint8_t status,uint32_t granted,int64_t balance){return pointJournal.Done(token,status,granted,balance);} EVENTINFO(PointRetryInfo) {}; EVENTFUNC(RetryPoints) { + if(pointJournal.NeedsCompaction() && !pointJournal.Compact())sys_err("POINT_DROP: %s",pointJournal.Error().c_str()); for(auto it=pendingPoints.begin();it!=pendingPoints.end();) { auto& p=it->second; if(get_global_time()found->second.request.count || (status!=0 && amount!=0)) { + sys_err("POINT_DROP: malformed settlement result; keep durable token %s pending",token); + return true; + } + if(!AppendDurableDone(token,status,amount,balance)){sys_err("POINT_DROP: %s",pointJournal.Error().c_str());return true;} pendingPoints.erase(found); auto ch=CHARACTER_MANAGER::instance().FindByPID(reply.player); if(status || !amount || balance<0 || !ch || !ch->GetDesc() || ch->GetDesc()->GetAccountTable().id!=reply.account)return true; @@ -144,46 +86,11 @@ size_t Ava2PointPendingCount() { } void Ava2PointDropInit() { - if (s_pointLogPath.empty()) return; - FILE* fp = fopen(s_pointLogPath.c_str(), "r"); - if (!fp) return; - std::map uncompleted; - char line[256]; - int doneCount = 0; - while (fgets(line, sizeof(line), fp)) { - char op[16] = {}, ver[16] = {}, token[64] = {}; - if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { - if (strcmp(op, "INTENT") == 0) { - Ava2ShopRequest r = {}; - r.operation = 3; - unsigned long long t = 0; - if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", - r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { - uncompleted[token] = r; - } - } else if (strcmp(op, "DONE") == 0) { - uncompleted.erase(token); - ++doneCount; - } - } - } - fclose(fp); - - for (const auto& kv : uncompleted) { - const auto& r = kv.second; - if (pendingPoints.find(r.token) == pendingPoints.end()) { - PendingPoints pending = {r, 0, 1, get_global_time() + 2}; - pendingPoints.emplace(r.token, pending); - } - } - - if (doneCount > 500) { - CompactDurableLog(); - } - - if (!pendingPoints.empty() && !pointRetryEvent) { - pointRetryEvent = event_create(RetryPoints, AllocEventInfo(), PASSES_PER_SEC(1)); - } + std::map recovered; + if(!pointJournal.Open(s_pointLogPath,recovered))sys_err("POINT_DROP: %s",pointJournal.Error().c_str()); + if(pointJournal.NeedsCompaction() && !pointJournal.Compact())sys_err("POINT_DROP: %s",pointJournal.Error().c_str()); + for(const auto& record:recovered){PendingPoints pending={record.second,0,1,get_global_time()+2};pendingPoints.emplace(record.first,pending);} + if(!pendingPoints.empty()&&!pointRetryEvent)pointRetryEvent=event_create(RetryPoints,AllocEventInfo(),PASSES_PER_SEC(1)); } void Ava2PointDrop(CHARACTER* ch,CHARACTER* victim) { @@ -191,7 +98,7 @@ void Ava2PointDrop(CHARACTER* ch,CHARACTER* victim) { (!victim->IsMonster() && !victim->IsStone()))return; const auto rule=PortPointRule([](const std::string& key){return quest::CQuestManager::instance().GetEventFlag(key);},victim->IsStone()); if(!rule.eligible(victim->GetLevel(),ch->GetLevel()) || number(1,10000)>rule.chance)return; - if(pendingPoints.size()>=4096){sys_err("POINT_DROP: pending queue full, drop suppressed");return;} + if(!pointJournal.Ready()){sys_err("POINT_DROP: issuance paused: %s",pointJournal.Error().c_str());return;} Ava2ShopRequest p={};p.operation=3;p.account=ch->GetDesc()->GetAccountTable().id;p.player=ch->GetPlayerID(); p.product=victim->GetRaceNum();p.count=number(rule.minimum,rule.maximum);p.expectedVnum=ch->GetLevel(); static const uint64_t boot=[](){timeval t;gettimeofday(&t,NULL);return (uint64_t(t.tv_sec)*1000000+t.tv_usec) ^ (uint64_t(getpid())<<32);}(); diff --git a/src/server/game/src/ava2_ticket_shop.cpp b/src/server/game/src/ava2_ticket_shop.cpp index d3b610ee..a6837edd 100644 --- a/src/server/game/src/ava2_ticket_shop.cpp +++ b/src/server/game/src/ava2_ticket_shop.cpp @@ -20,7 +20,7 @@ static const Ava2TicketOffer kAva2Tickets[]={ struct Ava2ShopPrice { DWORD vnum,count; }; struct Ava2ShopStart { TPacketGCShopStart shop; Ava2ShopPrice prices[SHOP_HOST_ITEM_MAX_NUM]; }; #pragma pack(pop) -static_assert(sizeof(Ava2ShopStart)==2044,"native currency shop payload"); +static_assert(sizeof(Ava2ShopStart)==2204,"native currency shop payload"); static_assert(sizeof(Ava2ShopPrice)==8,"AVA2 item price layout"); class CAva2TicketShop : public CShop { public: diff --git a/src/server/game/src/char.cpp b/src/server/game/src/char.cpp index d30e56fa..090be6a4 100755 --- a/src/server/game/src/char.cpp +++ b/src/server/game/src/char.cpp @@ -4,6 +4,11 @@ #include "../../common/VnumHelper.h" #include "char.h" +#include "port_gaya.h" +#ifdef ENABLE_OFFLINESHOP_SYSTEM +#include "offline_shop.h" +#endif +#include "../../common/gold_bounds.h" #include "autohunt_pull_range.h" #include "config.h" @@ -385,6 +390,7 @@ void CHARACTER::Initialize() cannot_dead = false; #ifdef __PET_SYSTEM__ + m_petOwner.Reset(); m_petSystem = 0; m_bIsPet = false; #ifdef ENABLE_NEW_PET_SYSTEM @@ -421,6 +427,7 @@ void CHARACTER::Create(const char * c_pszName, DWORD vid, bool isPC) void CHARACTER::Destroy() { + PortGayaForgetPlayer(GetPlayerID()); CloseMyShop(); if (m_pkRegen) @@ -624,20 +631,17 @@ void CHARACTER::OpenMyShop(const char * c_pszSign, TShopItemTable * pTable, BYTE if (bItemCount == 0) return; - int64_t nTotalMoney = 0; - + int64_t nTotalMoney = GetGold(); + if (bItemCount > SHOP_HOST_ITEM_MAX_NUM) return; for (int n = 0; n < bItemCount; ++n) { - nTotalMoney += static_cast((pTable+n)->price); - } - - nTotalMoney += static_cast(GetGold()); - - if (GOLD_MAX_64 <= nTotalMoney) - { - sys_err("[OVERFLOW_GOLD] Overflow (GOLD_MAX_64) id %u name %s", GetPlayerID(), GetName()); - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("골드 한ë�„를 초과하여 ìƒ�ì �ì�„ 열수가 없습니다")); - return; + const int64_t price = pTable[n].price; + if (price <= 0 || !PortGoldCanChange(nTotalMoney, price, GOLD_MAX_64)) + { + ChatPacket(CHAT_TYPE_INFO, "Invalid shop price or gold limit exceeded."); + return; + } + nTotalMoney += price; } char szSign[SHOP_SIGN_MAX_LEN+1]; @@ -658,13 +662,15 @@ void CHARACTER::OpenMyShop(const char * c_pszSign, TShopItemTable * pTable, BYTE } // MYSHOP_PRICE_LIST - std::map itemkind; // ì•„ì�´í…œ 종류별 가격, first: vnum, second: 단ì�¼ 수량 가격 + std::map itemkind; // ì•„ì�´í…œ 종류별 가격, first: vnum, second: 단ì�¼ 수량 가격 // END_OF_MYSHOP_PRICE_LIST std::set cont; + std::set displayPositions; for (BYTE i = 0; i < bItemCount; ++i) { - if (cont.find((pTable + i)->pos) != cont.end()) + if ((pTable+i)->display_pos >= SHOP_HOST_ITEM_MAX_NUM || !displayPositions.insert((pTable+i)->display_pos).second || + cont.find((pTable + i)->pos) != cont.end()) { sys_err("MYSHOP: duplicate shop item detected! (name: %s)", GetName()); return; @@ -673,6 +679,7 @@ void CHARACTER::OpenMyShop(const char * c_pszSign, TShopItemTable * pTable, BYTE // ANTI_GIVE, ANTI_MYSHOP check LPITEM pkItem = GetItem((pTable + i)->pos); + if (!pkItem || !pkItem->GetCount()) return; if (pkItem) { const TItemTable * item_table = pkItem->GetProto(); @@ -1384,9 +1391,9 @@ void CHARACTER::Disconnect(const char * c_pszReason) p.bHeader = HEADER_GG_LOGOUT; strlcpy(p.szName, GetName(), sizeof(p.szName)); P2P_MANAGER::instance().Send(&p, sizeof(TPacketGGLogout)); - char buf[51]; - snprintf(buf, sizeof(buf), "%s %d %d %ld %d", - inet_ntoa(GetDesc()->GetAddr().sin_addr), GetGold(), g_bChannel, GetMapIndex(), GetAlignment()); + char buf[128]; + snprintf(buf, sizeof(buf), "%s %lld %d %ld %d", + inet_ntoa(GetDesc()->GetAddr().sin_addr), (long long)GetGold(), g_bChannel, GetMapIndex(), GetAlignment()); LogManager::instance().CharLog(this, 0, "LOGOUT", buf); @@ -2313,6 +2320,7 @@ void CHARACTER::ComputeBattlePoints() void CHARACTER::ComputePoints() { long lStat = GetPoint(POINT_STAT); + const int lGem=GetPoint(POINT_GEM); long lStatResetCount = GetPoint(POINT_STAT_RESET_COUNT); long lSkillActive = GetPoint(POINT_SKILL); long lSkillSub = GetPoint(POINT_SUB_SKILL); @@ -2334,6 +2342,7 @@ void CHARACTER::ComputePoints() m_SkillDamageBonus.clear(); SetPoint(POINT_STAT, lStat); + SetPoint(POINT_GEM,lGem); SetPoint(POINT_SKILL, lSkillActive); SetPoint(POINT_SUB_SKILL, lSkillSub); SetPoint(POINT_HORSE_SKILL, lSkillHorse); @@ -2484,11 +2493,13 @@ void CHARACTER::ComputePoints() ComputeSkillPoints(); RefreshAffect(); +#ifndef ENABLE_NEW_PET_SYSTEM CPetSystem* pPetSystem = GetPetSystem(); if (NULL != pPetSystem) { pPetSystem->RefreshBuff(); } +#endif for (TMapBuffOnAttrs::iterator it = m_map_buff_on_attrs.begin(); it != m_map_buff_on_attrs.end(); it++) { @@ -3433,22 +3444,18 @@ void CHARACTER::PointChange(BYTE type, int64_t amount, bool bAmount, bool bBroad val = GetMaxStamina(); break; + case POINT_GEM: + if(amount < -int64_t(GetPoint(type)) || amount > 1000000-int64_t(GetPoint(type)))return; + SetPoint(type,GetPoint(type)+amount); + val=GetPoint(type); + break; + case POINT_GOLD: { - if (amount > 0 && GetGold() > GOLD_MAX_64 - amount) - { - sys_err("[OVERFLOW_GOLD] OriGold %lld AddedGold %lld id %u Name %s ", (long long)GetGold(), (long long)amount, GetPlayerID(), GetName()); - LogManager::instance().CharLog(this, GetGold(), "OVERFLOW_GOLD", ""); - SetGold(GOLD_MAX_64); - val = (GetGold() > 2000000000LL) ? 2000000000 : (int)GetGold(); - break; - } - else if (amount < 0 && -amount > GetGold()) - { - SetGold(0); - val = 0; - break; - } + if (!PortGoldCanChange(GetGold(),amount,GOLD_MAX_64)) { + sys_err("GOLD_REJECT balance=%lld delta=%lld pid=%u",(long long)GetGold(),(long long)amount,GetPlayerID()); + return; + } // 청소년보호 if (LC_IsNewCIBN() && amount > 0) @@ -3564,6 +3571,7 @@ void CHARACTER::PointChange(BYTE type, int64_t amount, bool bAmount, bool bBroad case POINT_RESIST_FIRE: case POINT_RESIST_ELEC: case POINT_RESIST_MAGIC: + case POINT_RESIST_MAGIC_REDUCTION: case POINT_RESIST_WIND: case POINT_RESIST_ICE: case POINT_RESIST_EARTH: @@ -3767,8 +3775,8 @@ void CHARACTER::PointChange(BYTE type, int64_t amount, bool bAmount, bool bBroad pack.type = type; pack.value = val; - if (bAmount) - pack.amount = amount; + if (bAmount && amount>=INT32_MIN && amount<=INT32_MAX) + pack.amount = static_cast(amount); else pack.amount = 0; @@ -3874,6 +3882,7 @@ void CHARACTER::ApplyPoint(BYTE bApplyType, int iVal) case APPLY_RESIST_FIRE: case APPLY_RESIST_ELEC: case APPLY_RESIST_MAGIC: + case APPLY_RESIST_MAGIC_REDUCTION: case APPLY_RESIST_WIND: case APPLY_RESIST_ICE: case APPLY_RESIST_EARTH: @@ -7500,23 +7509,6 @@ void CHARACTER::Open67Attr() #include "offline_shop.h" #include "offlineshop_manager.h" -void CHARACTER::SetProtectTime(const std::string& flagname, int value) -{ - itertype(m_protection_Time) it = m_protection_Time.find(flagname); - if (it != m_protection_Time.end()) - it->second = value; - else - m_protection_Time.insert(std::make_pair(flagname, value)); -} - -int CHARACTER::GetProtectTime(const std::string& flagname) const -{ - itertype(m_protection_Time) it = m_protection_Time.find(flagname); - if (it != m_protection_Time.end()) - return it->second; - return 0; -} - bool CHARACTER::CheckWindows(bool bChat) { if (GetExchange() || GetShop() || GetSafebox() || GetOfflineShop() || GetOfflineShopPanel()) diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index 447acd66..b598d973 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -292,6 +292,7 @@ enum EPointTypes POINT_ENCHANT_DARK = 247, POINT_GEM = 248, POINT_RESIST_HUMAN = 220, + POINT_RESIST_MAGIC_REDUCTION = 144, // AVA2 attacker's magic resistance reduction. // 추가 ì†�성 저항 POINT_RESIST_ICE = 133, // 냉기 저항 : ì–¼ì�Œê³µê²©ì—� 대한 대미지 ê°�소 @@ -1197,7 +1198,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider int GetGem() const; void ChangeGem(int amount); bool OpenGemSlot(); - void RefreshGemALL(bool withRealTime = false); + bool RefreshGemALL(bool withRealTime = false); void RefreshGemPlayer(); void BuyGemItem(BYTE slotIndex); bool PickupItem(DWORD vid); @@ -1267,7 +1268,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider void SetGold(int64_t gold) { m_points.gold = gold; } bool DropGold(int64_t gold); int64_t GetAllowedGold() const; - void GiveGold(int64_t iAmount); // 파티가 있으면 파티 ë¶„ë°°, 로그 등ì�˜ 처리 + bool GiveGold(int64_t iAmount); // 파티가 있으면 파티 ë¶„ë°°, 로그 등ì�˜ 처리 // End of Money //////////////////////////////////////////////////////////////////////////////////////// @@ -1674,10 +1675,13 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider #ifdef __PET_SYSTEM__ public: + void SetOwner(LPCHARACTER owner) { m_petOwner = owner; } + LPCHARACTER GetOwner() const { return m_petOwner.Get(); } CPetSystem* GetPetSystem() { return m_petSystem; } protected: CPetSystem* m_petSystem; + DynamicCharacterPtr m_petOwner; #ifdef ENABLE_NEW_PET_SYSTEM bool m_bIsNewPet; #endif @@ -2236,8 +2240,6 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider unsigned long long GetOfflineShopFlag() { return m_pkOfflineShopFlag; } void SetOfflineShopFlag(unsigned long long ptr) { m_pkOfflineShopFlag = ptr; } - void SetProtectTime(const std::string& flagname, int value); - int GetProtectTime(const std::string& flagname) const; #ifdef ENABLE_SHOP_SEARCH_SYSTEM void SetLookingSearch(const std::vector& looking); @@ -2267,7 +2269,6 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider LPOFFLINESHOP m_pkOfflineShop; bool isOfflineShopPanelOpen; unsigned long long m_pkOfflineShopFlag; - std::map m_protection_Time; #ifdef ENABLE_SHOP_SEARCH_SYSTEM std::vector m_vecSearchLooking; #endif diff --git a/src/server/game/src/char_battle.cpp b/src/server/game/src/char_battle.cpp index cac10e2c..405eec0d 100755 --- a/src/server/game/src/char_battle.cpp +++ b/src/server/game/src/char_battle.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "port_magic_reduction.h" #include "PetSystem.h" #include "new_mob_timer.h" #include "utils.h" @@ -720,9 +721,9 @@ void CHARACTER::RewardGold(LPCHARACTER pkAttacker) for (int i = 0; i < iSplitCount; ++i) { - if (isAutoLoot) + if (isAutoLoot && pkAttacker->GiveGold(iGold / iSplitCount)) { - pkAttacker->GiveGold(iGold / iSplitCount); + // Successfully credited; otherwise keep the reward as a ground pile. } else if ((item = ITEM_MANAGER::instance().CreateItem(1, iGold / iSplitCount))) { @@ -3010,7 +3011,12 @@ class CFuncShoot NormalAttackAffect(m_me, pkVictim); // µ¥¹ÌÁö °è»ê - iDam = iDam * (100 - pkVictim->GetPoint(POINT_RESIST_MAGIC)) / 100; +#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM + iDam = PortMagicDamageAfterResistance(iDam, pkVictim->GetPoint(POINT_RESIST_MAGIC), + m_me->GetPoint(POINT_RESIST_MAGIC_REDUCTION), m_me->GetJob()==JOB_SURA); +#else + iDam = iDam * (100 - pkVictim->GetPoint(POINT_RESIST_MAGIC)) / 100; +#endif //sys_log(0, "%s arrow %s dam %d", m_me->GetName(), pkVictim->GetName(), iDam); diff --git a/src/server/game/src/char_change_empire.cpp b/src/server/game/src/char_change_empire.cpp index 59d25c1d..68bd3a13 100755 --- a/src/server/game/src/char_change_empire.cpp +++ b/src/server/game/src/char_change_empire.cpp @@ -107,7 +107,7 @@ int CHARACTER::ChangeEmpire(BYTE empire) std::unique_ptr msg(DBManager::instance().DirectQuery(szQuery)); - if (msg->Get()->uiAffectedRows > 0) + if (msg->Get()->HasAffectedRows()) { // 5. Á¦±¹ º¯°æ ÀÌ·ÂÀ» Ãß°¡ÇÑ´Ù. SetChangeEmpireCount(); diff --git a/src/server/game/src/char_item.cpp b/src/server/game/src/char_item.cpp index aa88981f..6a6da302 100755 --- a/src/server/game/src/char_item.cpp +++ b/src/server/game/src/char_item.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "../../common/gold_bounds.h" #include @@ -3140,7 +3141,9 @@ bool CHARACTER::UseItemEx(LPITEM item, TItemPos DestCell) case USE_TIME_CHARGE_PER: { LPITEM pDestItem = GetItem(DestCell); - if (NULL == pDestItem) + if (NULL == pDestItem || pDestItem == item || pDestItem->GetOwner() != this || + pDestItem->isLocked() || pDestItem->IsExchanging() || + item->GetValue(ITEM_VALUE_CHARGING_AMOUNT_IDX) <= 0) { return false; } @@ -3196,7 +3199,9 @@ bool CHARACTER::UseItemEx(LPITEM item, TItemPos DestCell) case USE_TIME_CHARGE_FIX: { LPITEM pDestItem = GetItem(DestCell); - if (NULL == pDestItem) + if (NULL == pDestItem || pDestItem == item || pDestItem->GetOwner() != this || + pDestItem->isLocked() || pDestItem->IsExchanging() || + item->GetValue(ITEM_VALUE_CHARGING_AMOUNT_IDX) <= 0) { return false; } @@ -3233,15 +3238,10 @@ bool CHARACTER::UseItemEx(LPITEM item, TItemPos DestCell) return true; } if(item->GetVnum()==39063) { - RefreshGemALL(); - item->SetCount(item->GetCount()-1); - return true; + return RefreshGemALL(); // Durable DB settlement consumes the item. } if(item->GetVnum()==39064) { - if(OpenGemSlot()) { - item->SetCount(item->GetCount()-1); - return true; - } + if(OpenGemSlot()) return true; // Durable DB settlement consumes the item. ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ë�” ì�´ìƒ� 슬롯ì�„ 확장할 수 없습니다.")); return false; } @@ -6364,7 +6364,7 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) bool CHARACTER::DropGold(int64_t gold) { - if (gold <= 0 || gold > GetGold()) + if (gold <= 0 || gold>INT_MAX || gold > GetGold()) return false; if (!CanHandleItem()) @@ -6684,9 +6684,9 @@ namespace NPartyPickupDistribute int total; LPCHARACTER c; int x, y; - int iMoney; + int64_t iMoney; - FMoneyDistributor(LPCHARACTER center, int iMoney) + FMoneyDistributor(LPCHARACTER center, int64_t iMoney) : total(0), c(center), x(center->GetX()), y(center->GetY()), iMoney(iMoney) { } @@ -6705,13 +6705,30 @@ namespace NPartyPickupDistribute }; } -void CHARACTER::GiveGold(int64_t iAmount) +bool CHARACTER::GiveGold(int64_t iAmount) { - if (iAmount <= 0) - return; + if (iAmount <= 0 || iAmount>GOLD_MAX_64) + return false; sys_log(0, "GIVE_GOLD: %s %lld", GetName(), (long long)iAmount); + // Preflight every recipient before distributing any part of a ground pile. + if(GetParty()){ + NPartyPickupDistribute::FCountNearMember count(this); + GetParty()->ForEachOnlineMember(count); + const int64_t share=count.total>1?iAmount/count.total:0; + const int64_t mine=iAmount-share*(count.total>1?count.total-1:0); + bool fits=PortGoldCanChange(GetGold(),mine,GOLD_MAX_64); + struct Check { + LPCHARACTER owner;int64_t share;bool* fits; + void operator()(LPCHARACTER member){ + if(member!=owner && DISTANCE_APPROX(member->GetX()-owner->GetX(),member->GetY()-owner->GetY())<=PARTY_DEFAULT_RANGE && !PortGoldCanChange(member->GetGold(),share,GOLD_MAX_64))*fits=false; + } + } check={this,share,&fits}; + GetParty()->ForEachOnlineMember(check); + if(!fits)return false; + }else if(!PortGoldCanChange(GetGold(),iAmount,GOLD_MAX_64))return false; + if (GetParty()) { LPPARTY pParty = GetParty(); @@ -6758,6 +6775,7 @@ void CHARACTER::GiveGold(int64_t iAmount) LogManager::instance().CharLog(this, iAmount, "GET_GOLD", ""); } } + return true; } bool CHARACTER::PickupItem(DWORD dwVID) @@ -6777,7 +6795,7 @@ bool CHARACTER::PickupItem(DWORD dwVID) // 만약 주으려 하는 ì•„ì�´í…œì�´ ì—˜í�¬ë�¼ë©´ if (item->GetType() == ITEM_ELK) { - GiveGold(item->GetCount()); + if(!GiveGold(item->GetCount()))return false; item->RemoveFromGround(); M2_DESTROY_ITEM(item); @@ -8193,6 +8211,14 @@ bool CHARACTER::GiveItemFromSpecialItemGroup(DWORD dwGroupNum, std::vector idxes; int n = pGroup->GetMultiIndex(idxes); + int64_t plannedGold=0; + for(int index:idxes)if(pGroup->GetVnum(index)==CSpecialItemGroup::GOLD){ + const int64_t amount=pGroup->GetCount(index); + if(!PortGoldCanChange(plannedGold,amount,GOLD_MAX_64))return false; + plannedGold+=amount; + } + if(!PortGoldCanChange(GetGold(),plannedGold,GOLD_MAX_64))return false; + bool bSuccess; for (int i = 0; i < n; i++) diff --git a/src/server/game/src/char_skill.cpp b/src/server/game/src/char_skill.cpp index ffe08f76..e75ca755 100755 --- a/src/server/game/src/char_skill.cpp +++ b/src/server/game/src/char_skill.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "port_magic_reduction.h" #include #include "utils.h" @@ -446,16 +447,16 @@ bool CHARACTER::LearnSkillByBook(DWORD dwSkillVnum, BYTE bProb) { if (GetSkillMasterType(dwSkillVnum) > SKILL_MASTER) { - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº Ã¥À¸·Î ´õÀÌ»ó ¼ö·ÃÇÒ ¼ö ¾ø½À´Ï´Ù."))); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº Ã¥À¸·Î ´õÀÌ»ó ¼ö·ÃÇÒ ¼ö ¾ø½À´Ï´Ù.")); return false; } } else if (GetSkillMasterType(dwSkillVnum) != SKILL_MASTER) { if (GetSkillMasterType(dwSkillVnum) > SKILL_MASTER) - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº Ã¥À¸·Î ´õÀÌ»ó ¼ö·ÃÇÒ ¼ö ¾ø½À´Ï´Ù."))); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº Ã¥À¸·Î ´õÀÌ»ó ¼ö·ÃÇÒ ¼ö ¾ø½À´Ï´Ù.")); else - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº ¾ÆÁ÷ Ã¥À¸·Î ¼ö·ÃÇÒ °æÁö¿¡ À̸£Áö ¾Ê¾Ò½À´Ï´Ù."))); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÀÌ ½ºÅ³Àº ¾ÆÁ÷ Ã¥À¸·Î ¼ö·ÃÇÒ °æÁö¿¡ À̸£Áö ¾Ê¾Ò½À´Ï´Ù.")); return false; } } @@ -1328,7 +1329,12 @@ struct FuncSplashDamage // À¸¾Æ¾Æ¾Æ¾Ç // ¿¹Àü¿¡ Àû¿ë¾ÈÇß´ø ¹ö±×°¡ À־ ¹æ¾î·Â °è»êÀ» ´Ù½ÃÇϸé À¯Àú°¡ ³­¸®³² //iDam -= pkChrVictim->GetPoint(POINT_MAGIC_DEF_GRADE); - iDam = iDam * (100 - pkChrVictim->GetPoint(POINT_RESIST_MAGIC)) / 100; +#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM + iDam = PortMagicDamageAfterResistance(iDam, pkChrVictim->GetPoint(POINT_RESIST_MAGIC), + m_pkChr->GetPoint(POINT_RESIST_MAGIC_REDUCTION), m_pkChr->GetJob()==JOB_SURA); +#else + iDam = iDam * (100 - pkChrVictim->GetPoint(POINT_RESIST_MAGIC)) / 100; +#endif break; default: diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index f1e40e4b..490ccf9d 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -305,6 +305,7 @@ ACMD (do_dragon_soul); ACMD (do_ds_list); ACMD (do_clear_affect); ACMD(do_gem); +ACMD(do_mt_economy); ACMD(do_ishop); struct command_info cmd_info[] = @@ -652,6 +653,7 @@ struct command_info cmd_info[] = { "pet_add_slot", do_pet_add_slot, 0, POS_DEAD, GM_PLAYER }, { "change_name", do_change_name, 0, POS_DEAD, GM_PLAYER }, #endif + { "mt_economy", do_mt_economy, 0, POS_DEAD, GM_PLAYER }, { "gem", do_gem, 0, POS_DEAD, GM_PLAYER }, { "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 ì�´ 것ì�´ 마지막ì�´ì–´ì•¼ 한다. */ }; diff --git a/src/server/game/src/cmd_general.cpp b/src/server/game/src/cmd_general.cpp index 976a225a..6d742c36 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -45,6 +45,8 @@ #include #include "port_calendar_runtime.h" #include "port_ava2_travel.h" +#include "db.h" +#include "port_rank_runtime.h" #include "port_features.h" #include "port_pickup.h" #include "ava2_pickup_commands.h" @@ -2757,94 +2759,111 @@ ACMD(do_channel_list) { #ifdef ENABLE_NEW_PET_SYSTEM #include "PetSystem.h" +static bool PortPetCommandReady(LPCHARACTER ch) +{ + if (!ch || !ch->IsPC() || !ch->GetDesc() || !ch->IsItemLoaded()) return false; + quest::PC* pc = quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID()); + return pc && pc->IsLoaded() && !pc->IsRunning() && ch->CanHandleItem() && !ch->IsDead() && !ch->IsStun() && + !ch->IsWarping() && !ch->GetExchange() && !ch->GetMyShop() && !ch->GetShop() && + !ch->IsOpenSafebox() && !ch->IsCubeOpen(); +} + +static std::vector PortPetCommandArguments(const char* argument) +{ + std::vector args(1, "pet"); + std::istringstream input(argument); + std::string word; + while (input >> word) args.push_back(word); + return args; +} + +static bool PortPetInventoryPosition(const std::string& text, WORD& position) +{ + unsigned long long value = 0; + if (!str_to_number(value, text.c_str()) || value >= INVENTORY_MAX_NUM) return false; + position = static_cast(value); + return true; +} + +static bool PortPetEditableItem(LPCHARACTER ch, LPITEM item) +{ + return item && item->GetOwner() == ch && item->GetCount() && !item->IsEquipped() && + !item->IsExchanging() && !item->isLocked(); +} + ACMD(do_change_name) { - if (!ch) - return; - - std::vector vecArgs; - split_argument(argument, vecArgs); - if (vecArgs.size() < 4) { return; } - int scrollPos = -1; - int petPos = -1; - str_to_number(scrollPos, vecArgs[1].c_str()); - str_to_number(petPos, vecArgs[2].c_str()); - if (scrollPos == -1 || petPos == -1 || vecArgs[3].empty() || vecArgs[3].size() < 3 || ch->GetGold() < 100000) - return; - LPITEM scroll = ch->GetInventoryItem(scrollPos); - if (scroll) - { - LPITEM pet = ch->GetInventoryItem(petPos); - if (pet) - { - if (pet->IsEquipped()) - return; - if (pet->GetType() == ITEM_PET && pet->GetSubType() == PET_LEVELABLE && scroll->GetVnum() == 55008) - { - if (!check_name(vecArgs[3].c_str())) - return; - ch->PointChange(POINT_GOLD, -100000); - scroll->SetCount(scroll->GetCount() - 1); - pet->SetNewName(vecArgs[3].c_str()); - pet->UpdatePacket(); - ch->ChatPacket(CHAT_TYPE_INFO, "559"); - } - } - } + if (!PortPetCommandReady(ch) || ch->GetGold() < 100000) return; + const auto vecArgs = PortPetCommandArguments(argument); + if (vecArgs.size() != 4) return; + WORD scrollPos = 0, petPos = 0; + if (!PortPetInventoryPosition(vecArgs[1], scrollPos) || !PortPetInventoryPosition(vecArgs[2], petPos) || + vecArgs[3].size() < 3 || vecArgs[3].size() > CHARACTER_NAME_MAX_LEN || !check_name(vecArgs[3].c_str())) return; + LPITEM scroll = ch->GetInventoryItem(scrollPos); + LPITEM pet = ch->GetInventoryItem(petPos); + if (!PortPetEditableItem(ch, scroll) || !PortPetEditableItem(ch, pet)) return; + if (pet->GetType() == ITEM_PET && pet->GetSubType() == PET_LEVELABLE && scroll->GetVnum() == 55008) + { + ch->PointChange(POINT_GOLD, -100000); + scroll->SetCount(scroll->GetCount() - 1); + pet->SetNewName(vecArgs[3].c_str()); + pet->UpdatePacket(); + ch->ChatPacket(CHAT_TYPE_INFO, "559"); + } } ACMD(do_pet_egg) { - if (!ch || ch->GetGold() < 100000) - return; + if (!PortPetCommandReady(ch) || ch->GetGold() < 100000) return; + const auto vecArgs = PortPetCommandArguments(argument); + if (vecArgs.size() != 3) return; + WORD petPos = 0; + if (!PortPetInventoryPosition(vecArgs[1], petPos) || vecArgs[2].size() < 3 || + vecArgs[2].size() > CHARACTER_NAME_MAX_LEN || !check_name(vecArgs[2].c_str())) return; + LPITEM item = ch->GetInventoryItem(petPos); + if (!PortPetEditableItem(ch, item) || !(item->GetType() == ITEM_PET && item->GetSubType() == PET_EGG)) return; + DWORD petVnum = item->GetValue(0); + const TItemTable* pPetTable = ITEM_MANAGER::instance().GetTable(petVnum); + if (!pPetTable || pPetTable->bType != ITEM_PET || pPetTable->bSubType != PET_LEVELABLE) return; + const int emptyCell = ch->GetEmptyInventory(pPetTable->bSize); + if (emptyCell < 0) return; + const int64_t expiresAt = int64_t(time(0)) + 60 * 60 * 24 * 30; + if (expiresAt < 0 || expiresAt > INT32_MAX) return; - std::vector vecArgs; - split_argument(argument, vecArgs); - if (vecArgs.size() < 3) { return; } - int petPos = -1; - str_to_number(petPos, vecArgs[1].c_str()); - - LPITEM item = ch->GetInventoryItem(petPos); - if (!item) - return; - else if (!(item->GetType() == ITEM_PET && item->GetSubType() == PET_EGG)) - return; - else if (vecArgs[2].empty() || vecArgs[2].size() < 3 || !check_name(vecArgs[2].c_str())) - return; - - DWORD petVnum = item->GetValue(0); - TItemTable* pPetTable = ITEM_MANAGER::instance().GetTable(petVnum); - if (!pPetTable) - return; - int emptyCell = ch->GetEmptyInventory(pPetTable->bSize); - if (emptyCell == -1) - { - ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ì�¸ë²¤í† ë¦¬ì—� 공간ì�´ 부족합니다.")); - return; - } - - ch->PointChange(POINT_GOLD, -100000); - item->SetCount(item->GetCount() - 1); - - LPITEM petItem = ch->AutoGiveItem(petVnum); - if (!petItem) - return; - - petItem->SetNewName(vecArgs[2].c_str()); - petItem->SetSocket(0, time(0) + 60 * 60 * 24 * 30); - petItem->SetSocket(1, 1); - for (BYTE j = 0; j < 15; ++j) - petItem->SetForceAttribute(j, 99, 0); - petItem->Save(); - petItem->UpdatePacket(); + LPITEM petItem = ITEM_MANAGER::instance().CreateItem(petVnum, 1); + if (!petItem) return; + petItem->SetSkipSave(true); + if (petItem->GetCount() != 1 || petItem->GetType() != ITEM_PET || petItem->GetSubType() != PET_LEVELABLE) + { + M2_DESTROY_ITEM(petItem); + return; + } + petItem->SetNewName(vecArgs[2].c_str()); + petItem->SetSocket(0, static_cast(expiresAt)); + petItem->SetSocket(1, 1); + for (BYTE j = 0; j < 15; ++j) + petItem->SetForceAttribute(j, 99, 0); + if (!petItem->AddToCharacter(ch, TItemPos(INVENTORY, emptyCell))) + { + M2_DESTROY_ITEM(petItem); + return; + } + // All operations below are synchronous on the game thread; creation and + // placement failures above leave both the egg and wallet untouched. + ch->PointChange(POINT_GOLD, -100000); + item->SetCount(item->GetCount() - 1); + petItem->SetSkipSave(false); + petItem->Save(); + ITEM_MANAGER::instance().FlushDelayedSave(petItem); + petItem->UpdatePacket(); } ACMD(do_pet_evolve) { - if (!ch) + if (!PortPetCommandReady(ch)) return; LPITEM item = ch->GetWear(WEAR_PET); - if (!item) + if (!item || item->GetOwner() != ch || item->IsExchanging() || item->isLocked()) return; long level = item->GetSocket(1); if (level != 40 && level != 75 && level != 100) @@ -2860,13 +2879,13 @@ ACMD(do_pet_evolve) ACMD(do_pet_add_slot) { - if (!ch) + if (!PortPetCommandReady(ch)) return; - std::vector vecArgs; - split_argument(argument, vecArgs); - if (vecArgs.size() < 2) { return; } - int skillSlot = -1; - str_to_number(skillSlot, vecArgs[1].c_str()); + const auto vecArgs = PortPetCommandArguments(argument); + if (vecArgs.size() != 2) return; + unsigned long long requestedSlot = 0; + if (!str_to_number(requestedSlot, vecArgs[1].c_str()) || requestedSlot >= 15) return; + int skillSlot = static_cast(requestedSlot); if (skillSlot >= 0 && skillSlot <= 14) { CPetSystem* pet = ch->GetPetSystem(); @@ -2876,7 +2895,7 @@ ACMD(do_pet_add_slot) if (!petActor) return; LPITEM item = petActor->GetSummonItem(); - if (!item) + if (!item || item->GetOwner() != ch || item->IsExchanging() || item->isLocked()) return; if (item->GetSocket(1) < 115) return; @@ -2912,10 +2931,10 @@ ACMD(do_pet_add_slot) return; } } + if (!petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0)) return; for (BYTE j = 0; j < _countof(slotItems); ++j) ch->RemoveSpecifyItem(slotItems[j][0], slotItems[j][1]); ch->ChatPacket(CHAT_TYPE_INFO, "561"); - petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0); } } #endif diff --git a/src/server/game/src/cmd_gm.cpp b/src/server/game/src/cmd_gm.cpp index e3ada84f..c4b16fb0 100755 --- a/src/server/game/src/cmd_gm.cpp +++ b/src/server/game/src/cmd_gm.cpp @@ -1449,12 +1449,13 @@ ACMD(do_set) { case 0: // gold { - int gold = 0; - str_to_number(gold, arg3); + long long gold = 0; + if(!str_to_number(gold,arg3))break; + if(gold < -tch->GetGold() || gold > GOLD_MAX_64-tch->GetGold())break; DBManager::instance().SendMoneyLog(MONEY_LOG_MISC, 3, gold); - int before_gold = tch->GetGold(); + int64_t before_gold = tch->GetGold(); tch->PointChange(POINT_GOLD, gold, true); - int after_gold = tch->GetGold(); + int64_t after_gold = tch->GetGold(); if (0 == after_gold && 0 != before_gold) { LogManager::instance().CharLog(tch, gold, "ZERO_GOLD", "GM"); @@ -2980,7 +2981,7 @@ ACMD(do_build) // °Ç¼³ Àç·á ¼Ò¸ðÇϱâ (Å×¼·¿¡¼­´Â GMµµ ¼Ò¸ð) { // °Ç¼³ ºñ¿ë ¼Ò¸ð - ch->PointChange(POINT_GOLD, -t->dwPrice); + ch->PointChange(POINT_GOLD, -static_cast(t->dwPrice)); // ¾ÆÀÌÅÛ ÀÚÀç »ç¿ëÇϱâ { diff --git a/src/server/game/src/constants.cpp b/src/server/game/src/constants.cpp index 4f92ee5c..14b54ea7 100755 --- a/src/server/game/src/constants.cpp +++ b/src/server/game/src/constants.cpp @@ -921,8 +921,8 @@ const TApplyInfo aApplyInfo[MAX_APPLY_NUM] = { POINT_NONE }, // 95 { POINT_NONE }, // 96 { POINT_NONE }, // 97 - { POINT_NONE }, // 98 - { POINT_NONE }, // 99 + { POINT_RESIST_MAGIC_REDUCTION }, // APPLY_RESIST_MAGIC_REDUCTION 98 + { POINT_RESIST_HUMAN }, // APPLY_RESIST_HUMAN 99 { POINT_NONE }, // 100 { POINT_NONE }, // 101 { POINT_NONE }, // 102 @@ -1331,6 +1331,8 @@ TValueName c_aApplyTypeNames[] = { "MAGIC_ATTBONUS_PER", APPLY_MAGIC_ATTBONUS_PER }, { "MELEE_MAGIC_ATTBONUS_PER", APPLY_MELEE_MAGIC_ATTBONUS_PER }, + { "RESIST_HUMAN", APPLY_RESIST_HUMAN }, + { "RESIST_MAGIC_REDUCTION", APPLY_RESIST_MAGIC_REDUCTION }, { "ATTBONUS_STONE", APPLY_ATTBONUS_STONE }, { "ATTBONUS_BOSS", APPLY_ATTBONUS_BOSS }, { "ENCHANT_ELEC", APPLY_ENCHANT_ELEC }, diff --git a/src/server/game/src/cube.cpp b/src/server/game/src/cube.cpp index 7a96f4bf..e0bc89da 100755 --- a/src/server/game/src/cube.cpp +++ b/src/server/game/src/cube.cpp @@ -554,7 +554,7 @@ bool Cube_make (LPCHARACTER ch) // Á¦Á¶½Ã ÇÊ¿äÇÑ °ñµå Â÷°¨ if (0 < cube_proto->gold) - ch->PointChange(POINT_GOLD, -(cube_proto->gold), false); + ch->PointChange(POINT_GOLD, -static_cast(cube_proto->gold), false); percent_number = number(1,100); if ( percent_number<=cube_proto->percent) diff --git a/src/server/game/src/db.cpp b/src/server/game/src/db.cpp index 0934c945..78c59491 100755 --- a/src/server/game/src/db.cpp +++ b/src/server/game/src/db.cpp @@ -1255,7 +1255,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg) m_map_dbstring.clear(); m_vec_GreetMessage.clear(); - for (uint i = 0; i < pMsg->Get()->uiNumRows; ++i) + for (uint64_t i = 0; i < pMsg->Get()->uiNumRows; ++i) { MYSQL_ROW row = mysql_fetch_row(pMsg->Get()->pSQLResult); //ch->SetSafeboxSize(SAFEBOX_PAGE_SIZE * atoi(row[0])); @@ -1285,7 +1285,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg) if (ch) { - if (pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1) + if (!pMsg->Get()->HasAffectedRows() || !pMsg->Get()->uiInsertID || pMsg->Get()->uiInsertID > INT32_MAX) { sys_log(0, "GIVE LOTTO FAIL TO pid %u", ch->GetPlayerID()); } @@ -1298,7 +1298,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg) sys_log(0, "GIVE LOTTO SUCCESS TO %s (pid %u)", ch->GetName(), qi->dwIdent); //ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¾ÆÀÌÅÛ È¹µæ: %s"), pkItem->GetName()); - pkItem->SetSocket(0, pMsg->Get()->uiInsertID); + pkItem->SetSocket(0, static_cast(pMsg->Get()->uiInsertID)); pkItem->SetSocket(1, pdw[2]); } else @@ -1440,7 +1440,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg) { TPacketCGLogin3 * pinfo = (TPacketCGLogin3 *) qi->pvData ; - if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1 ) + if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX ) { LPDESC d = DESC_MANAGER::instance().FindByLoginKey(qi->dwIdent) ; sys_log(0, "[AUTH_BRAZIL] NOID") ; @@ -1471,7 +1471,7 @@ void DBManager::AnalyzeReturnQuery(SQLMsg * pMsg) { TPacketCGLogin3 * pinfo = (TPacketCGLogin3 *) qi->pvData ; - if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1 ) + if( pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == UINT64_MAX ) { LPDESC d = DESC_MANAGER::instance().FindByLoginKey(qi->dwIdent) ; sys_log(0, "[AUTH_JAPAN] NOID") ; diff --git a/src/server/game/src/db.h b/src/server/game/src/db.h index 436b25cd..2ce15cab 100755 --- a/src/server/game/src/db.h +++ b/src/server/game/src/db.h @@ -1,6 +1,7 @@ #ifndef __INC_METIN_II_DB_MANAGER_H__ #define __INC_METIN_II_DB_MANAGER_H__ +#include "../../common/length.h" #include "../../libsql/AsyncSQL.h" #include "any_function.h" diff --git a/src/server/game/src/desc_manager.cpp b/src/server/game/src/desc_manager.cpp index 1cb1c00b..b589d091 100755 --- a/src/server/game/src/desc_manager.cpp +++ b/src/server/game/src/desc_manager.cpp @@ -539,7 +539,9 @@ void DESC_MANAGER::SendClientPackageCryptKey( LPDESC desc ) if( packet.KeyStreamLen > 0 ) { - desc->Packet( packet.GetStreamData(), packet.GetStreamSize() ); + const BYTE* stream = packet.GetStreamData(); + if (stream) desc->Packet(stream, static_cast(packet.GetStreamSize())); + else sys_err("invalid client package stream length"); } } @@ -559,7 +561,9 @@ void DESC_MANAGER::SendClientPackageSDBToLoadMap( LPDESC desc, const char* pMapN if( packet.iStreamLen > 0 ) { - desc->Packet( packet.GetStreamData(), packet.GetStreamSize()); + const BYTE* stream = packet.GetStreamData(); + if (stream) desc->Packet(stream, static_cast(packet.GetStreamSize())); + else sys_err("invalid client package stream length"); } } diff --git a/src/server/game/src/exchange.cpp b/src/server/game/src/exchange.cpp index da6b300b..eaba5e16 100755 --- a/src/server/game/src/exchange.cpp +++ b/src/server/game/src/exchange.cpp @@ -14,10 +14,10 @@ #include "exchange.h" #include "DragonSoul.h" -void exchange_packet(LPCHARACTER ch, BYTE sub_header, bool is_me, DWORD arg1, TItemPos arg2, DWORD arg3, void * pvData = NULL); +void exchange_packet(LPCHARACTER ch, BYTE sub_header, bool is_me, int64_t arg1, TItemPos arg2, DWORD arg3, void * pvData = NULL); // ±³È¯ ÆÐŶ -void exchange_packet(LPCHARACTER ch, BYTE sub_header, bool is_me, DWORD arg1, TItemPos arg2, DWORD arg3, void * pvData) +void exchange_packet(LPCHARACTER ch, BYTE sub_header, bool is_me, int64_t arg1, TItemPos arg2, DWORD arg3, void * pvData) { if (!ch->GetDesc()) return; @@ -269,7 +269,7 @@ bool CExchange::AddGold(int64_t gold) m_lGold = gold; - DWORD dwPacketGold = (m_lGold > 2000000000LL) ? 2000000000 : (DWORD)m_lGold; + int64_t dwPacketGold = m_lGold; exchange_packet(GetOwner(), EXCHANGE_SUBHEADER_GC_GOLD_ADD, true, dwPacketGold, NPOS, 0); exchange_packet(GetCompany()->GetOwner(), EXCHANGE_SUBHEADER_GC_GOLD_ADD, false, dwPacketGold, NPOS, 0); return true; diff --git a/src/server/game/src/guild.cpp b/src/server/game/src/guild.cpp index 82f996b0..745841b7 100755 --- a/src/server/game/src/guild.cpp +++ b/src/server/game/src/guild.cpp @@ -78,7 +78,11 @@ CGuild::CGuild(TGuildCreateParameter & cp) get_table_postfix(), m_data.name, m_data.master_pid)); // TODO if error occur? - m_data.guild_id = pmsg->Get()->uiInsertID; + if (pmsg->uiSQLErrno || !pmsg->Get() || !pmsg->Get()->HasAffectedRows() || !pmsg->Get()->GetInsertID32(m_data.guild_id)) + { + sys_err("guild create returned an invalid or unrepresentable ID"); + return; + } for (int i = 0; i < GUILD_GRADE_COUNT; ++i) { @@ -534,7 +538,7 @@ void CGuild::LoadGuildMemberData(SQLMsg* pmsg) m_member.clear(); - for (uint i = 0; i < pmsg->Get()->uiNumRows; ++i) + for (uint64_t i = 0; i < pmsg->Get()->uiNumRows; ++i) { MYSQL_ROW row = mysql_fetch_row(pmsg->Get()->pSQLResult); @@ -568,7 +572,7 @@ void CGuild::LoadGuildGradeData(SQLMsg* pmsg) return; } */ - for (uint i = 0; i < pmsg->Get()->uiNumRows; ++i) + for (uint64_t i = 0; i < pmsg->Get()->uiNumRows; ++i) { MYSQL_ROW row = mysql_fetch_row(pmsg->Get()->pSQLResult); BYTE grade = 0; @@ -897,7 +901,7 @@ void CGuild::SendGuildInfoPacket(LPCHARACTER ch) pack_sub.exp = m_data.exp; pack_sub.level = m_data.level; strlcpy(pack_sub.name, m_data.name, sizeof(pack_sub.name)); - pack_sub.gold = (m_data.gold > 2000000000LL) ? 2000000000 : (DWORD)m_data.gold; + pack_sub.gold = m_data.gold; pack_sub.has_land = HasLand(); sys_log(0, "GMC guild_name %s", m_data.name); @@ -1038,7 +1042,7 @@ void CGuild::DeleteComment(LPCHARACTER ch, DWORD comment_id) else pmsg = DBManager::instance().DirectQuery("DELETE FROM guild_comment%s WHERE id = %u AND guild_id = %u AND name = '%s'",get_table_postfix(), comment_id, m_data.guild_id, ch->GetName()); - if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg->Get()->uiAffectedRows == 0 || pmsg->Get()->uiAffectedRows == UINT64_MAX) ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("<±æµå> »èÁ¦ÇÒ ¼ö ¾ø´Â ±ÛÀÔ´Ï´Ù.")); else RefreshCommentForce(ch->GetPlayerID()); @@ -1065,7 +1069,8 @@ void CGuild::RefreshCommentForce(DWORD player_id) pack.size = sizeof(pack)+1; pack.subheader = GUILD_SUBHEADER_GC_COMMENTS; - BYTE count = pmsg->Get()->uiNumRows; + if (pmsg->Get()->uiNumRows > UINT8_MAX || pmsg->Get()->uiNumRows > GUILD_COMMENT_MAX_COUNT) return; + BYTE count = static_cast(pmsg->Get()->uiNumRows); LPDESC d = ch->GetDesc(); @@ -1080,7 +1085,7 @@ void CGuild::RefreshCommentForce(DWORD player_id) memset(szName, 0, sizeof(szName)); memset(szContent, 0, sizeof(szContent)); - for (uint i = 0; i < pmsg->Get()->uiNumRows; i++) + for (uint64_t i = 0; i < pmsg->Get()->uiNumRows; i++) { MYSQL_ROW row = mysql_fetch_row(pmsg->Get()->pSQLResult); DWORD id = strtoul(row[0], NULL, 10); @@ -1838,7 +1843,7 @@ void CGuild::RequestDepositMoney(LPCHARACTER ch, int64_t iGold) char buf[64+1]; snprintf(buf, sizeof(buf), "%u %s", GetID(), GetName()); - LogManager::instance().CharLog(ch, (DWORD)iGold, "GUILD_DEPOSIT", buf); + LogManager::instance().CharLog(ch, iGold, "GUILD_DEPOSIT", buf); ch->UpdateDepositPulse(); sys_log(0, "GUILD: DEPOSIT %s:%u player %s[%u] gold %lld", GetName(), GetID(), ch->GetName(), ch->GetPlayerID(), (long long)iGold); @@ -1887,17 +1892,17 @@ void CGuild::RecvMoneyChange(int64_t iGold) TPacketGCGuild p; p.header = HEADER_GC_GUILD; - p.size = sizeof(p) + sizeof(int); + p.size = sizeof(p) + sizeof(int64_t); p.subheader = GUILD_SUBHEADER_GC_MONEY_CHANGE; - int packet_gold = (iGold > 2000000000LL) ? 2000000000 : (int)iGold; + int64_t packet_gold = iGold; for (itertype(m_memberOnline) it = m_memberOnline.begin(); it != m_memberOnline.end(); ++it) { LPCHARACTER ch = *it; LPDESC d = ch->GetDesc(); d->BufferedPacket(&p, sizeof(p)); - d->Packet(&packet_gold, sizeof(int)); + d->Packet(&packet_gold, sizeof(packet_gold)); } } diff --git a/src/server/game/src/guild.h b/src/server/game/src/guild.h index 9bcb9fea..1dd560c3 100755 --- a/src/server/game/src/guild.h +++ b/src/server/game/src/guild.h @@ -66,7 +66,7 @@ typedef struct packet_guild_sub_info DWORD exp; BYTE level; char name[GUILD_NAME_MAX_LEN+1]; - DWORD gold; + int64_t gold; BYTE has_land; } TPacketGCGuildInfo; diff --git a/src/server/game/src/guild_manager.cpp b/src/server/game/src/guild_manager.cpp index 8980339a..c186802f 100755 --- a/src/server/game/src/guild_manager.cpp +++ b/src/server/game/src/guild_manager.cpp @@ -103,6 +103,7 @@ DWORD CGuildManager::CreateGuild(TGuildCreateParameter& gcp) // new CGuild(gcp) queries guild tables and tell dbcache to notice other game servers. // other game server calls CGuildManager::LoadGuild to load guild. CGuild * pg = M2_NEW CGuild(gcp); + if (!pg->GetID()) { M2_DELETE(pg); return 0; } m_mapGuild.insert(std::make_pair(pg->GetID(), pg)); return pg->GetID(); } @@ -208,9 +209,10 @@ void CGuildManager::Initialize() std::unique_ptr pmsg(DBManager::instance().DirectQuery("SELECT id FROM guild%s", get_table_postfix())); std::vector vecGuildID; - vecGuildID.reserve(pmsg->Get()->uiNumRows); + if (pmsg->Get()->uiNumRows > vecGuildID.max_size()) { sys_err("guild result exceeds container capacity"); return; } + vecGuildID.reserve(static_cast(pmsg->Get()->uiNumRows)); - for (uint i = 0; i < pmsg->Get()->uiNumRows; i++) + for (uint64_t i = 0; i < pmsg->Get()->uiNumRows; i++) { MYSQL_ROW row = mysql_fetch_row(pmsg->Get()->pSQLResult); DWORD guild_id = strtoul(row[0], (char**) NULL, 10); diff --git a/src/server/game/src/input_db.cpp b/src/server/game/src/input_db.cpp index 7a594a3c..5d5a0e45 100755 --- a/src/server/game/src/input_db.cpp +++ b/src/server/game/src/input_db.cpp @@ -1,5 +1,6 @@ #include "stdafx.h" #include "ava2_itemshop.h" +#include "port_economy.h" #include "../../common/ava2_itemshop.h" #include "new_mob_timer.h" #include "ava2_track.h" @@ -439,9 +440,9 @@ void CInputDB::PlayerLoad(LPDESC d, const char * data) P2P_MANAGER::instance().Send(&p, sizeof(TPacketGGLogin)); - char buf[51]; - snprintf(buf, sizeof(buf), "%s %d %d %ld %d", - inet_ntoa(ch->GetDesc()->GetAddr().sin_addr), ch->GetGold(), g_bChannel, ch->GetMapIndex(), ch->GetAlignment()); + char buf[128]; + snprintf(buf, sizeof(buf), "%s %lld %d %ld %d", + inet_ntoa(ch->GetDesc()->GetAddr().sin_addr), (long long)ch->GetGold(), g_bChannel, ch->GetMapIndex(), ch->GetAlignment()); LogManager::instance().CharLog(ch, 0, "LOGIN", buf); if (LC_IsYMIR() || LC_IsKorea() || LC_IsBrazil() || LC_IsJapan()) @@ -594,6 +595,9 @@ void CInputDB::Boot(const char* data) if (size) { ITEM_MANAGER::instance().Initialize((TItemTable *) data, size); +#if defined(ENABLE_OFFLINESHOP_SYSTEM) && defined(ENABLE_SHOP_SEARCH_SYSTEM) + COfflineShopManager::instance().LoadSearchLanguage(); +#endif data += size * sizeof(TItemTable); } @@ -1203,7 +1207,9 @@ void CInputDB::QuestLoad(LPDESC d, const char * c_pData) } pkPC->SetLoaded(); - pkPC->Build(); + pkPC->Build(); + ch->SetPoint(POINT_GEM, ch->GetQuestFlag("gem.points")); + ch->PointChange(POINT_GEM, 0); if (ch->GetDesc()->IsPhase(PHASE_GAME)) { @@ -1790,6 +1796,9 @@ void CInputDB::ReloadProto(const char * c_pData) if (wSize) { ITEM_MANAGER::instance().Initialize((TItemTable *) c_pData, wSize); +#if defined(ENABLE_OFFLINESHOP_SYSTEM) && defined(ENABLE_SHOP_SEARCH_SYSTEM) + COfflineShopManager::instance().LoadSearchLanguage(); +#endif c_pData += wSize * sizeof(TItemTable); } @@ -2112,7 +2121,7 @@ void CInputDB::VCard(const char * c_pData) std::unique_ptr pmsg1(DBManager::instance().DirectQuery("UPDATE GameTime SET LimitTime=LimitTime+%d WHERE UserID='%s'", time, p->szBuyAccount)); - if (pmsg1->Get()->uiAffectedRows == 0 || pmsg1->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg1->Get()->uiAffectedRows == 0 || pmsg1->Get()->uiAffectedRows == UINT64_MAX) { sys_log(0, "VCARD_FAIL: cannot modify GameTime table"); return; @@ -2120,7 +2129,7 @@ void CInputDB::VCard(const char * c_pData) std::unique_ptr pmsg2(DBManager::instance().DirectQuery("UPDATE vcard,GameTime SET sell_pid='%s', buy_pid='%s', buy_account='%s', sell_time=NOW(), new_time=GameTime.LimitTime WHERE vcard.id=%u AND GameTime.UserID='%s'", p->szSellCharacter, p->szBuyCharacter, p->szBuyAccount, p->dwID, p->szBuyAccount)); - if (pmsg2->Get()->uiAffectedRows == 0 || pmsg2->Get()->uiAffectedRows == (uint32_t)-1) + if (pmsg2->Get()->uiAffectedRows == 0 || pmsg2->Get()->uiAffectedRows == UINT64_MAX) { sys_log(0, "VCARD_FAIL: cannot modify vcard table"); return; @@ -2287,7 +2296,8 @@ int CInputDB::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) break; case HEADER_DG_PLAYER_LOAD_FAILED: - //sys_log(0, "PLAYER_LOAD_FAILED"); + if (LPDESC failed=DESC_MANAGER::instance().FindByHandle(m_dwHandle)) + failed->SetPhase(PHASE_CLOSE); break; case HEADER_DG_PLAYER_DELETE_FAILED: @@ -2323,6 +2333,8 @@ int CInputDB::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) SafeboxChangePasswordAnswer(DESC_MANAGER::instance().FindByHandle(m_dwHandle), c_pData); break; + case 77: + PortEconomyReply(m_dwHandle,c_pData);break; case 76: Ava2ItemShopReply(m_dwHandle,c_pData);break; case HEADER_DG_MALL_LOAD: @@ -2644,6 +2656,7 @@ bool CInputDB::Process(LPDESC d, const void * orig, int bytes, int & r_iBytesPro const char * pRealData = (c_pData + 9); + if(bHeader==77 && iSize!=int(sizeof(PortEconomy::Reply))){d->SetPhase(PHASE_CLOSE);return true;} if (bHeader==76 && (iSize32775 || reinterpret_cast(pRealData)->size!=iSize-sizeof(Ava2ShopReply))) { d->SetPhase(PHASE_CLOSE);return true; } if (Analyze(d, bHeader, pRealData) < 0) diff --git a/src/server/game/src/input_login.cpp b/src/server/game/src/input_login.cpp index c697d9cf..da960ad5 100755 --- a/src/server/game/src/input_login.cpp +++ b/src/server/game/src/input_login.cpp @@ -564,7 +564,7 @@ void CInputLogin::Entergame(LPDESC d, const char * data) { // PORT: wear40 moves dragon-soul/belt cells; older clients must not enter this world. const char* revision=strstr(d->GetClientVersion(),"mt"); - if(!revision || atoi(revision+2)<20261022) + if(!revision || atoi(revision+2)<20261024) { if(d->GetCharacter())d->GetCharacter()->ChatPacket(CHAT_TYPE_INFO,"Please update the client before entering the game."); d->DelayedDisconnect(1);return; @@ -969,7 +969,8 @@ void CInputLogin::GuildMarkUpload(LPDESC d, const char* c_pData) if (isEmpty) rkMarkMgr.DeleteMark(p->gid); else - rkMarkMgr.SaveMark(p->gid, p->image); + if (rkMarkMgr.SaveMark(p->gid, p->image) == CGuildMarkManager::INVALID_MARK_ID) + sys_err("mark upload rejected for unrepresentable guild/index %u",p->gid); } void CInputLogin::GuildMarkIDXList(LPDESC d, const char* c_pData) @@ -982,13 +983,14 @@ void CInputLogin::GuildMarkIDXList(LPDESC d, const char* c_pData) if (bufSize > 0) { buf = (char *) malloc(bufSize); - rkMarkMgr.CopyMarkIdx(buf); + if (!buf || !rkMarkMgr.CopyMarkIdx(buf, bufSize)) { free(buf); sys_err("invalid mark index stream"); return; } } TPacketGCMarkIDXList p; p.header = HEADER_GC_MARK_IDXLIST; p.bufSize = sizeof(p) + bufSize; - p.count = rkMarkMgr.GetMarkCount(); + if (rkMarkMgr.GetMarkCount() > UINT16_MAX) { free(buf); return; } + p.count = static_cast(rkMarkMgr.GetMarkCount()); if (buf) { diff --git a/src/server/game/src/input_main.cpp b/src/server/game/src/input_main.cpp index 9c74fca5..e8da7395 100755 --- a/src/server/game/src/input_main.cpp +++ b/src/server/game/src/input_main.cpp @@ -1109,6 +1109,9 @@ void CInputMain::OnClick(LPCHARACTER ch, const char * data) void CInputMain::Exchange(LPCHARACTER ch, const char * data) { struct command_exchange * pinfo = (struct command_exchange *) data; + if(pinfo->arg1<0 || pinfo->arg1>GOLD_MAX_64)return; + if(pinfo->sub_header!=EXCHANGE_SUBHEADER_CG_ELK_ADD && pinfo->arg1>UINT32_MAX)return; + LPCHARACTER to_ch = NULL; if (!ch->CanHandleItem()) @@ -1178,7 +1181,7 @@ void CInputMain::Exchange(LPCHARACTER ch, const char * data) { ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("액수가 20ì–µ 냥ì�„ 초과하여 거래를 할수가 없습니다..")); - sys_err("[OVERFLOG_GOLD] START (%u) id %u name %s ", ch->GetGold(), ch->GetPlayerID(), ch->GetName()); + sys_err("[OVERFLOG_GOLD] START (%lld) id %u name %s ", (long long)ch->GetGold(), ch->GetPlayerID(), ch->GetName()); return; } @@ -1222,9 +1225,8 @@ void CInputMain::Exchange(LPCHARACTER ch, const char * data) case EXCHANGE_SUBHEADER_CG_ELK_ADD: // arg1 == amount of gold if (ch->GetExchange()) { - const int64_t nTotalGold = static_cast(ch->GetExchange()->GetCompany()->GetOwner()->GetGold()) + static_cast(pinfo->arg1); - if (GOLD_MAX_64 <= nTotalGold) + if (pinfo->arg1<=0 || pinfo->arg1 > GOLD_MAX_64-ch->GetExchange()->GetCompany()->GetOwner()->GetGold()) { ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ìƒ�대방ì�˜ ì´�금액ì�´ 20ì–µ 냥ì�„ 초과하여 거래를 할수가 없습니다..")); @@ -2533,8 +2535,8 @@ size_t GetSubPacketSize(const GUILD_SUBHEADER_CG& header) { switch (header) { - case GUILD_SUBHEADER_CG_DEPOSIT_MONEY: return sizeof(int); - case GUILD_SUBHEADER_CG_WITHDRAW_MONEY: return sizeof(int); + case GUILD_SUBHEADER_CG_DEPOSIT_MONEY: return sizeof(int64_t); + case GUILD_SUBHEADER_CG_WITHDRAW_MONEY: return sizeof(int64_t); case GUILD_SUBHEADER_CG_ADD_MEMBER: return sizeof(DWORD); case GUILD_SUBHEADER_CG_REMOVE_MEMBER: return sizeof(DWORD); case GUILD_SUBHEADER_CG_CHANGE_GRADE_NAME: return 10; @@ -3779,7 +3781,11 @@ int CInputMain::ItemsPickup(LPCHARACTER ch,const char* data,size_t bytes) { if(packet.count>4096) { ch->GetDesc()->SetPhase(PHASE_CLOSE); return 0; } const size_t extra=size_t(packet.count)*sizeof(DWORD); if(bytesGetPickUPMode()&1) || ch->IsDead() || ch->IsStun() || ch->IsWarping() || ch->IsObserverMode()) return int(extra); + // PORT: CG235 is also used by autohunt; bit 0 controls the manual UI route only. + if(ch->IsDead() || ch->IsStun() || ch->IsWarping() || ch->IsObserverMode()) return int(extra); + const DWORD now=get_dword_time(); + if(ch->m_portPickupLastCommand && DWORD(now-ch->m_portPickupLastCommand)<500) return int(extra); + ch->m_portPickupLastCommand=now ? now : 1; for(DWORD i=0;i CItem::CItem(DWORD dwVnum) : m_dwVnum(dwVnum), m_bWindow(0), m_dwID(0), m_bEquipped(false), m_dwVID(0), m_wCell(0), m_dwCount(0), m_lFlag(0), m_dwLastOwnerPID(0), @@ -375,17 +376,17 @@ bool CItem::AddToCharacter(LPCHARACTER ch, TItemPos Cell) if (INVENTORY == window_type) { - if (m_wCell >= INVENTORY_MAX_NUM && BELT_INVENTORY_SLOT_START > m_wCell) + if (pos >= BELT_INVENTORY_SLOT_END || (pos >= INVENTORY_MAX_NUM && pos < BELT_INVENTORY_SLOT_START)) { - sys_err("CItem::AddToCharacter: cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), m_wCell); + sys_err("CItem::AddToCharacter: cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), pos); return false; } } else if (DRAGON_SOUL_INVENTORY == window_type) { - if (m_wCell >= DRAGON_SOUL_INVENTORY_MAX_NUM) + if (pos >= DRAGON_SOUL_INVENTORY_MAX_NUM) { - sys_err("CItem::AddToCharacter: cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), m_wCell); + sys_err("CItem::AddToCharacter: cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), pos); return false; } } @@ -1310,7 +1311,7 @@ int CItem::GetGold() return GetProto()->dwGold; } -int CItem::GetShopBuyPrice() +int64_t CItem::GetShopBuyPrice() { return GetProto()->dwShopBuyPrice; } @@ -2327,53 +2328,36 @@ bool CItem::IsDragonSoul() return GetType() == ITEM_DS; } +// PORT: retain AVA2/40250 capped recharge semantics without signed overflow or +// float-to-integer UB on corrupt durations, sockets and charge definitions. int CItem::GiveMoreTime_Per(float fPercent) { - if (IsDragonSoul()) - { - DWORD duration = DSManager::instance().GetDuration(this); - int remain_sec = GetSocket(ITEM_SOCKET_REMAIN_SEC); - int given_time = fPercent * duration / 100; - if (remain_sec == duration) - return false; - if ((given_time + remain_sec) >= duration) - { - SetSocket(ITEM_SOCKET_REMAIN_SEC, duration); - return duration - remain_sec; - } - else - { - SetSocket(ITEM_SOCKET_REMAIN_SEC, given_time + remain_sec); - return given_time; - } - } - // ìš°ì„  용혼ì„�ì—� 관해서만 하ë�„ë¡� 한다. - else + if (!IsDragonSoul() || !std::isfinite(fPercent) || fPercent <= 0) return 0; + const uint32_t duration = DSManager::instance().GetDuration(this); + const int64_t remaining = GetSocket(ITEM_SOCKET_REMAIN_SEC); + if (!duration || duration > INT32_MAX || remaining < 0 || remaining >= duration) + return 0; + const int64_t available = int64_t(duration) - remaining; + const double requested = double(fPercent) * duration / 100.0; + const int added = requested >= double(available) ? static_cast(available) : static_cast(requested); + if (added > 0) + SetSocket(ITEM_SOCKET_REMAIN_SEC, static_cast(remaining + added)); + return added; } int CItem::GiveMoreTime_Fix(DWORD dwTime) { - if (IsDragonSoul()) - { - DWORD duration = DSManager::instance().GetDuration(this); - int remain_sec = GetSocket(ITEM_SOCKET_REMAIN_SEC); - if (remain_sec == duration) - return false; - if ((dwTime + remain_sec) >= duration) - { - SetSocket(ITEM_SOCKET_REMAIN_SEC, duration); - return duration - remain_sec; - } - else - { - SetSocket(ITEM_SOCKET_REMAIN_SEC, dwTime + remain_sec); - return dwTime; - } - } - // ìš°ì„  용혼ì„�ì—� 관해서만 하ë�„ë¡� 한다. - else + if (!IsDragonSoul() || !dwTime) return 0; + const uint32_t duration = DSManager::instance().GetDuration(this); + const int64_t remaining = GetSocket(ITEM_SOCKET_REMAIN_SEC); + if (!duration || duration > INT32_MAX || remaining < 0 || remaining >= duration) + return 0; + const uint32_t available = duration - static_cast(remaining); + const uint32_t added = dwTime < available ? dwTime : available; + SetSocket(ITEM_SOCKET_REMAIN_SEC, static_cast(remaining + added)); + return static_cast(added); } diff --git a/src/server/game/src/item.h b/src/server/game/src/item.h index 45d811cd..0d045034 100755 --- a/src/server/game/src/item.h +++ b/src/server/game/src/item.h @@ -39,7 +39,7 @@ class CItem : public CEntity TItemTable const * GetProto() { return m_pProto; } int GetGold(); - int GetShopBuyPrice(); + int64_t GetShopBuyPrice(); const char * GetName() { return m_pProto ? m_pProto->szLocaleName : NULL; } const char * GetBaseName() { return m_pProto ? m_pProto->szName : NULL; } BYTE GetSize() { return m_pProto ? m_pProto->bSize : 0; } @@ -108,7 +108,7 @@ class CItem : public CEntity bool CreateSocket(BYTE bSlot, BYTE bGold); const long * GetSockets() { return &m_alSockets[0]; } - long GetSocket(int i) { return i>=0 && i<3 ? m_alSockets[i] : i>=3 && i<8 ? m_portExtra.sockets[i-3] : 0; } + long GetSocket(int i) const { return i>=0 && i<3 ? m_alSockets[i] : i>=3 && i<8 ? m_portExtra.sockets[i-3] : 0; } void SetSockets(const long * al); void SetSocket(int i, long v, bool bLog = true); diff --git a/src/server/game/src/log.cpp b/src/server/game/src/log.cpp index 8bc68dea..45eb5491 100755 --- a/src/server/game/src/log.cpp +++ b/src/server/game/src/log.cpp @@ -73,15 +73,15 @@ void LogManager::ItemLog(LPCHARACTER ch, int itemID, int itemVnum, const char * ItemLog(ch->GetPlayerID(), ch->GetX(), ch->GetY(), itemID, c_pszText, c_pszHint, ch->GetDesc() ? ch->GetDesc()->GetHostName() : "", itemVnum); } -void LogManager::CharLog(DWORD dwPID, DWORD x, DWORD y, DWORD dwValue, const char * c_pszText, const char * c_pszHint, const char * c_pszIP) +void LogManager::CharLog(DWORD dwPID, DWORD x, DWORD y, int64_t dwValue, const char * c_pszText, const char * c_pszHint, const char * c_pszIP) { m_sql.EscapeString(__escape_hint, sizeof(__escape_hint), c_pszHint, strlen(c_pszHint)); - Query("INSERT DELAYED INTO log%s (type, time, who, x, y, what, how, hint, ip) VALUES('CHARACTER', NOW(), %u, %u, %u, %u, '%s', '%s', '%s')", - get_table_postfix(), dwPID, x, y, dwValue, c_pszText, __escape_hint, c_pszIP); + Query("INSERT DELAYED INTO log%s (type, time, who, x, y, what, how, hint, ip) VALUES('CHARACTER', NOW(), %u, %u, %u, %lld, '%s', '%s', '%s')", + get_table_postfix(), dwPID, x, y, (long long)dwValue, c_pszText, __escape_hint, c_pszIP); } -void LogManager::CharLog(LPCHARACTER ch, DWORD dw, const char * c_pszText, const char * c_pszHint) +void LogManager::CharLog(LPCHARACTER ch, int64_t dw, const char * c_pszText, const char * c_pszHint) { if (ch) CharLog(ch->GetPlayerID(), ch->GetX(), ch->GetY(), dw, c_pszText, c_pszHint, ch->GetDesc() ? ch->GetDesc()->GetHostName() : ""); @@ -95,15 +95,15 @@ void LogManager::LoginLog(bool isLogin, DWORD dwAccountID, DWORD dwPID, BYTE bLe get_table_postfix(), isLogin ? "'LOGIN'" : "'LOGOUT'", g_bChannel, dwAccountID, dwPID, bLevel, bJob, dwPlayTime); } -void LogManager::MoneyLog(BYTE type, DWORD vnum, int gold) +void LogManager::MoneyLog(BYTE type, DWORD vnum, int64_t gold) { if (type == MONEY_LOG_RESERVED || type >= MONEY_LOG_TYPE_MAX_NUM) { - sys_err("TYPE ERROR: type %d vnum %u gold %d", type, vnum, gold); + sys_err("TYPE ERROR: type %d vnum %u gold %lld", type, vnum, (long long)gold); return; } - Query("INSERT DELAYED INTO money_log%s VALUES (NOW(), %d, %d, %d)", get_table_postfix(), type, vnum, gold); + Query("INSERT DELAYED INTO money_log%s VALUES (NOW(), %d, %d, %lld)", get_table_postfix(), type, vnum, (long long)gold); } void LogManager::HackLog(const char * c_pszHackName, const char * c_pszLogin, const char * c_pszName, const char * c_pszIP) diff --git a/src/server/game/src/log.h b/src/server/game/src/log.h index 471f8ffb..2e8ed61f 100755 --- a/src/server/game/src/log.h +++ b/src/server/game/src/log.h @@ -29,11 +29,11 @@ class LogManager : public singleton void ItemLog(LPCHARACTER ch, LPITEM item, const char * c_pszText, const char * c_pszHint); void ItemLog(LPCHARACTER ch, int itemID, int itemVnum, const char * c_pszText, const char * c_pszHint); - void CharLog(DWORD dwPID, DWORD x, DWORD y, DWORD dw, const char * c_pszText, const char * c_pszHint, const char * c_pszIP); - void CharLog(LPCHARACTER ch, DWORD dw, const char * c_pszText, const char * c_pszHint); + void CharLog(DWORD dwPID, DWORD x, DWORD y, int64_t dw, const char * c_pszText, const char * c_pszHint, const char * c_pszIP); + void CharLog(LPCHARACTER ch, int64_t dw, const char * c_pszText, const char * c_pszHint); void LoginLog(bool isLogin, DWORD dwAccountID, DWORD dwPID, BYTE bLevel, BYTE bJob, DWORD dwPlayTime); - void MoneyLog(BYTE type, DWORD vnum, int gold); + void MoneyLog(BYTE type, DWORD vnum, int64_t gold); void HackLog(const char * c_pszHackName, const char * c_pszLogin, const char * c_pszName, const char * c_pszIP); void HackLog(const char * c_pszHackName, LPCHARACTER ch); void HackCRCLog(const char * c_pszHackName, const char * c_pszLogin, const char * c_pszName, const char * c_pszIP, DWORD dwCRC); diff --git a/src/server/game/src/messenger_manager.cpp b/src/server/game/src/messenger_manager.cpp index b5b57f79..729100ea 100755 --- a/src/server/game/src/messenger_manager.cpp +++ b/src/server/game/src/messenger_manager.cpp @@ -64,7 +64,7 @@ void MessengerManager::LoadList(SQLMsg * msg) sys_log(1, "Messenger::LoadList"); - for (uint i = 0; i < msg->Get()->uiNumRows; ++i) + for (uint64_t i = 0; i < msg->Get()->uiNumRows; ++i) { MYSQL_ROW row = mysql_fetch_row(msg->Get()->pSQLResult); diff --git a/src/server/game/src/monarch.cpp b/src/server/game/src/monarch.cpp index 49e04e23..6e787a57 100755 --- a/src/server/game/src/monarch.cpp +++ b/src/server/game/src/monarch.cpp @@ -117,18 +117,17 @@ bool CMonarch::IsMoneyOk(int price, BYTE bEmpire) return (GetMoney(bEmpire) >= price); } -bool CMonarch::SendtoDBAddMoney(int Money, BYTE bEmpire, LPCHARACTER ch) +bool CMonarch::SendtoDBAddMoney(int64_t Money, BYTE bEmpire, LPCHARACTER ch) { - if (GetMoney(bEmpire) + Money > 2000000000) - return false; - - if (GetMoney(bEmpire) + Money < 0) + if (!ch || !ch->GetDesc() || bEmpire >= _countof(m_MonarchInfo.money) || + Money < 0 || Money > 2000000000LL - GetMoney(bEmpire)) return false; + const int wireMoney = static_cast(Money); int nEmpire = bEmpire; db_clientdesc->DBPacketHeader(HEADER_GD_ADD_MONARCH_MONEY, ch->GetDesc()->GetHandle(), sizeof(int) + sizeof(int)); db_clientdesc->Packet(&nEmpire, sizeof(int)); - db_clientdesc->Packet(&Money, sizeof(int)); + db_clientdesc->Packet(&wireMoney, sizeof(int)); return true; } diff --git a/src/server/game/src/monarch.h b/src/server/game/src/monarch.h index 5954339a..248a7916 100755 --- a/src/server/game/src/monarch.h +++ b/src/server/game/src/monarch.h @@ -16,7 +16,7 @@ class CMonarch : public singleton bool IsMonarch(DWORD pid, BYTE bEmpire); bool IsMoneyOk(int price, BYTE bEmpire); - bool SendtoDBAddMoney(int Money, BYTE bEmpire, LPCHARACTER ch); + bool SendtoDBAddMoney(int64_t Money, BYTE bEmpire, LPCHARACTER ch); bool SendtoDBDecMoney(int Money, BYTE bEmpire, LPCHARACTER ch); bool AddMoney(int Money, BYTE bEmpire); diff --git a/src/server/game/src/offlineshop_manager.cpp b/src/server/game/src/offlineshop_manager.cpp index 2e2efd82..339e2821 100644 --- a/src/server/game/src/offlineshop_manager.cpp +++ b/src/server/game/src/offlineshop_manager.cpp @@ -22,6 +22,7 @@ //#include #include #include "offlineshop_manager.h" +#include "../../common/offline_shop_safety.h" #include "p2p.h" #include "entity.h" #include "sectree_manager.h" @@ -31,12 +32,9 @@ #include "offline_shop_search.h" #endif -COfflineShopManager::COfflineShopManager() +COfflineShopManager::COfflineShopManager() : m_pShopTimeEvent(NULL) { Initialize(); -#ifdef ENABLE_SHOP_SEARCH_SYSTEM - LoadSearchLanguage(); -#endif } COfflineShopManager::~COfflineShopManager(){Initialize();} @@ -264,6 +262,11 @@ void COfflineShopManager::DestroyOfflineShopReal(DWORD ch) void COfflineShopManager::DestroyOfflineShop(LPCHARACTER ch) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch) return; if (ch->CanDestroyShop()) @@ -289,6 +292,7 @@ void COfflineShopManager::DestroyOfflineShop(LPCHARACTER ch) void COfflineShopManager::AddItemReal(OFFLINE_SHOP_ITEM* item) { + if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!item) { sys_err("COfflineShopManager::AddItemReal item data is null!!!!!!!!!"); return; @@ -305,7 +309,12 @@ void COfflineShopManager::AddItemReal(OFFLINE_SHOP_ITEM* item) void COfflineShopManager::AddItem(LPCHARACTER ch, BYTE bDisplayPos, TItemPos bPos, long long iPrice) { - if (!ch || bDisplayPos >= OFFLINE_SHOP_HOST_ITEM_MAX_NUM) + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + + if (!ch || bDisplayPos >= OFFLINE_SHOP_HOST_ITEM_MAX_NUM || iPrice<=0 || iPrice>GOLD_MAX_64) return; if (bDisplayPos >= 40) @@ -370,6 +379,7 @@ void COfflineShopManager::AddItem(LPCHARACTER ch, BYTE bDisplayPos, TItemPos bPo item.status = 0; thecore_memcpy(item.alSockets, pkItem->GetSockets(), sizeof(item.alSockets)); thecore_memcpy(item.aAttr, pkItem->GetAttributes(), sizeof(item.aAttr)); + item.extra=pkItem->GetPortExtra(); #ifdef ENABLE_CHANGELOOK_SYSTEM item.transmutation = pkItem->GetTransmutation(); #endif @@ -386,6 +396,7 @@ void COfflineShopManager::AddItem(LPCHARACTER ch, BYTE bDisplayPos, TItemPos bPo void COfflineShopManager::RemoveItemReal(OFFLINE_SHOP_ITEM* item) { + if(!item || item->pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!item) return; LPOFFLINESHOP pkOfflineShop = FindOfflineShopPID(item->owner_id); @@ -401,15 +412,17 @@ void COfflineShopManager::RemoveItemReal(OFFLINE_SHOP_ITEM* item) LPCHARACTER ch = CHARACTER_MANAGER::Instance().FindByPID(item->owner_id); if (ch != NULL) { - LPITEM pItem = ch->AutoGiveItem(item->vnum, item->count,0,true); + LPITEM pItem = ITEM_MANAGER::instance().CreateItem(item->vnum,item->count); if (pItem) { pItem->SetAttributes(item->aAttr); pItem->SetSockets(item->alSockets); + pItem->SetPortExtra(item->extra); #ifdef ENABLE_CHANGELOOK_SYSTEM pItem->SetTransmutation(item->transmutation); #endif - pItem->UpdatePacket(); + ch->AutoGiveItem(pItem); + pItem->UpdatePacket(); //int iEmptyPos = -1; //iEmptyPos = ch->CalculateItemPos(pItem); //if (iEmptyPos < 0) @@ -430,6 +443,12 @@ void COfflineShopManager::RemoveItemReal(OFFLINE_SHOP_ITEM* item) void COfflineShopManager::RemoveItem(LPCHARACTER ch, BYTE bPos) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + + if(!ch || bPos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM)return; if (!ch || bPos >= OFFLINE_SHOP_HOST_ITEM_MAX_NUM) return; if (ch->CanRemoveItemShop()) @@ -512,6 +531,7 @@ void SendReturnPacket(LPCHARACTER ch, BYTE ret) void COfflineShopManager::BuyItemReal(TOfflineShopBuy* item) { + if(!item || item->item.pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM || item->item.price<=0 || item->item.price>GOLD_MAX_64)return; LPOFFLINESHOP pkOfflineShop = FindOfflineShopPID(item->item.owner_id); if (!pkOfflineShop) return; @@ -531,15 +551,17 @@ void COfflineShopManager::BuyItemReal(TOfflineShopBuy* item) LPCHARACTER ch = CHARACTER_MANAGER::Instance().FindByPID(item->customer_id); if (ch != NULL) { - LPITEM pItem = ch->AutoGiveItem(item->item.vnum, item->item.count,0,true); + LPITEM pItem = ITEM_MANAGER::instance().CreateItem(item->item.vnum,item->item.count); if (pItem != NULL) { pItem->SetAttributes(item->item.aAttr); pItem->SetSockets(item->item.alSockets); + pItem->SetPortExtra(item->item.extra); #ifdef ENABLE_CHANGELOOK_SYSTEM pItem->SetTransmutation(item->item.transmutation); #endif - pItem->UpdatePacket(); + ch->AutoGiveItem(pItem); + pItem->UpdatePacket(); //int iEmptyPos = -1; //iEmptyPos = ch->CalculateItemPos(pItem); //if (iEmptyPos < 0) @@ -561,7 +583,12 @@ void COfflineShopManager::BuyItemReal(TOfflineShopBuy* item) void COfflineShopManager::Buy(LPCHARACTER ch, DWORD vid, BYTE pos) { - if(!ch) + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + + if(!ch || pos>=OFFLINE_SHOP_HOST_ITEM_MAX_NUM) return; if (ch->CanBuyItemOfflineShop()) return; @@ -580,6 +607,7 @@ void COfflineShopManager::Buy(LPCHARACTER ch, DWORD vid, BYTE pos) } OFFLINE_SHOP_ITEM& item = pkOfflineShop->m_data.items[pos]; + if(!item.vnum || item.price<=0 || item.price>GOLD_MAX_64)return; if (item.owner_id == ch->GetPlayerID()){ //ch->ChatPacket(CHAT_TYPE_INFO, "You can't buy your own shop!"); return; @@ -734,6 +762,11 @@ void COfflineShopManager::WithdrawMoneyReal(DWORD ch) void COfflineShopManager::WithdrawMoney(LPCHARACTER ch) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch) return; if (ch->CanWithdrawMoney()) @@ -793,6 +826,11 @@ void COfflineShopManager::ShopLogRemoveReal(DWORD ch) void COfflineShopManager::ChangeDecoration(LPCHARACTER ch, TShopDecoration* data) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch || !data) return; if (ch->CanChangeDecoration()) @@ -898,9 +936,24 @@ bool HasNearOfflineShop(LPCHARACTER ch, long newX, long newY) void COfflineShopManager::OpenMyOfflineShop(LPCHARACTER ch, const char* c_pszSign, TOfflineShopItemTable* pTable, BYTE bItemCount, DWORD shopVnum, BYTE titleType) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + - if (bItemCount == 0) + if (!ch || !pTable || bItemCount == 0 || bItemCount>OFFLINE_SHOP_HOST_ITEM_MAX_NUM) return; + bool slots[OFFLINE_SHOP_HOST_ITEM_MAX_NUM]={}; + std::set itemIDs; + for(unsigned i=0;i=OFFLINE_SHOP_HOST_ITEM_MAX_NUM || slots[pTable[i].display_pos] || + pTable[i].price<=0 || pTable[i].price>GOLD_MAX_64)return; + slots[pTable[i].display_pos]=true; + LPITEM item=ch->GetItem(pTable[i].pos); + if(!item || !itemIDs.insert(item->GetID()).second)return; + } + if (ch->CanCreateShop()) return; @@ -1010,6 +1063,7 @@ void COfflineShopManager::OpenMyOfflineShop(LPCHARACTER ch, const char* c_pszSig item.status = 0; thecore_memcpy(item.alSockets, pkItem->GetSockets(), sizeof(item.alSockets)); thecore_memcpy(item.aAttr, pkItem->GetAttributes(), sizeof(item.aAttr)); + item.extra=pkItem->GetPortExtra(); #ifdef ENABLE_CHANGELOOK_SYSTEM item.transmutation = pkItem->GetTransmutation(); #endif @@ -1044,6 +1098,11 @@ void COfflineShopManager::OpenSlotReal(TOfflineShopOpenSlot* ch) void COfflineShopManager::OpenSlot(LPCHARACTER ch, BYTE bPos) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch) return; unsigned long long myFlag = ch->GetOfflineShopFlag(); @@ -1136,6 +1195,11 @@ void COfflineShopManager::CloseOfflineShopForTime(LPOFFLINESHOP offlineshop) void COfflineShopManager::GetBackItem(LPCHARACTER ch) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch) return; if (ch->CanGetBackItems()) @@ -1165,15 +1229,17 @@ void COfflineShopManager::GetBackItemReal(TOfflineShopBackItem* ch) { if (ch->items[i].vnum == 0 || ch->items[i].status == 1) continue; - LPITEM pItem = t->AutoGiveItem(ch->items[i].vnum, ch->items[i].count,0,true); + LPITEM pItem = ITEM_MANAGER::instance().CreateItem(ch->items[i].vnum,ch->items[i].count); if (pItem != NULL) { pItem->SetAttributes(ch->items[i].aAttr); pItem->SetSockets(ch->items[i].alSockets); + pItem->SetPortExtra(ch->items[i].extra); #ifdef ENABLE_CHANGELOOK_SYSTEM pItem->SetTransmutation(ch->items[i].transmutation); #endif - pItem->UpdatePacket(); + t->AutoGiveItem(pItem); + pItem->UpdatePacket(); //int iEmptyPos = -1; //iEmptyPos = t->CalculateItemPos(pItem); //if (iEmptyPos < 0) @@ -1216,6 +1282,11 @@ void COfflineShopManager::GetBackItemReal(TOfflineShopBackItem* ch) void COfflineShopManager::ShopAddTime(LPCHARACTER ch) { + if(!PortOfflineShopEconomyReady()) { + if(ch)ch->ChatPacket(CHAT_TYPE_INFO,"Offline shop is unavailable while durable-order recovery is being upgraded."); + return; + } + if (!ch) return; if (ch->CanAddTimeShop()) diff --git a/src/server/game/src/offlineshop_search_manager.cpp b/src/server/game/src/offlineshop_search_manager.cpp index 45b5fb69..875f8bd8 100644 --- a/src/server/game/src/offlineshop_search_manager.cpp +++ b/src/server/game/src/offlineshop_search_manager.cpp @@ -15,11 +15,14 @@ bool COfflineShopManager::CheckItemNames(LPCHARACTER ch, const char* searchInput, std::vector& m_vecItemVnums) { - const std::string searchedFileName(searchInput); + if (!ch || !searchInput) return false; + std::string searchedFileName(searchInput); + std::transform(searchedFileName.begin(), searchedFileName.end(), searchedFileName.begin(), + [](unsigned char c) { return std::tolower(c); }); const size_t searchTextLength = searchedFileName.length(); if (searchTextLength < 1) return false; - const auto it = m_mapItemNames.find(ch->GetCharacterLanguage()); + const auto it = m_mapItemNames.find(0); if (it != m_mapItemNames.end()) { for (DWORD j = 0; j < it->second.size(); ++j) @@ -34,47 +37,21 @@ bool COfflineShopManager::CheckItemNames(LPCHARACTER ch, const char* searchInput } return m_vecItemVnums.size() > 0 ? true : false; } -//agregar lenguajes offline search +// The port uses the active server item proto's localized names. Native AVA2's +// per-character language handshake is not implemented here. void COfflineShopManager::LoadSearchLanguage() { - const std::map m_vecLang = { - {LOCALE_EN, "en"}, - {LOCALE_TR, "tr"}, - {LOCALE_ES, "es"}, - {LOCALE_PL, "pl"}, - {LOCALE_PT, "pt"}, - {LOCALE_RO, "ro"}, - }; - m_mapItemNames.clear(); - for (auto it = m_vecLang.begin(); it != m_vecLang.end(); ++it) - { - char filename[40]; - snprintf(filename, sizeof(filename), "locale/multi_lang/%s_item_names.txt", it->second.c_str()); - char one_line[256]; - FILE* fp = fopen(filename, "r"); - if (fp != NULL) - { - std::vector> m_ItemNames; - while (fgets(one_line, 256, fp)) - { - std::vector m_vec; - split_argument_special(one_line, m_vec, "\t"); - if (m_vec.size() < 2) - continue; - else if (m_vec[0].length() < 1 || m_vec[1].length() < 1) - continue; - DWORD itemvnum; - str_to_number(itemvnum, m_vec[0].c_str()); - if (!itemvnum) - continue; - std::transform(m_vec[1].begin(), m_vec[1].end(), m_vec[1].begin(), [](unsigned char c) { return std::tolower(c); }); - m_ItemNames.emplace_back(std::make_pair(m_vec[1], itemvnum)); - } - fclose(fp); - if (m_ItemNames.size()) - m_mapItemNames.emplace(it->first, m_ItemNames); - } - } + m_mapItemNames.clear(); + auto& names = m_mapItemNames[0]; + for (const auto& item : ITEM_MANAGER::instance().GetTable()) + { + std::string name(item.szLocaleName, + strnlen(item.szLocaleName, sizeof(item.szLocaleName))); + if (name.empty()) continue; + std::transform(name.begin(), name.end(), name.begin(), + [](unsigned char c) { return std::tolower(c); }); + names.emplace_back(name, item.dwVnum); + } } void COfflineShopManager::SaveInMemory(OFFLINE_SHOP_ITEM* item) @@ -165,7 +142,7 @@ void COfflineShopManager::RemoveInMemory(OFFLINE_SHOP_ITEM* item) LPCHARACTER ch = desc->GetCharacter(); if (ch) { - if (ch->IsLookingSearchItem(item->id)) + if (ch->IsLookingSearch(item->id)) ch->ChatPacket(CHAT_TYPE_COMMAND, "OfflineShopBuyed %u", item->id); } } diff --git a/src/server/game/src/packet.h b/src/server/game/src/packet.h index 341c5396..a0285e22 100755 --- a/src/server/game/src/packet.h +++ b/src/server/game/src/packet.h @@ -1,4 +1,7 @@ #ifndef __INC_PACKET_H__ + +#include +#include #define __INC_PACKET_H__ enum @@ -841,10 +844,11 @@ typedef struct command_exchange { BYTE header; BYTE sub_header; - DWORD arg1; + int64_t arg1; BYTE arg2; TItemPos Pos; } TPacketCGExchange; +static_assert(sizeof(TPacketCGExchange)==14,"gold64 CG exchange size"); typedef struct command_position { @@ -1385,12 +1389,13 @@ enum EPacketShopSubHeaders struct packet_shop_item { DWORD vnum; - DWORD price; + int64_t price; BYTE count; BYTE display_pos; - long alSockets[ITEM_SOCKET_MAX_NUM]; + int32_t alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; }; +static_assert(sizeof(packet_shop_item)==47,"gold64 shop item wire size"); typedef struct packet_shop_start { @@ -1418,7 +1423,7 @@ typedef struct packet_shop_update_item typedef struct packet_shop_update_price { - int iPrice; + int64_t iPrice; } TPacketGCShopUpdatePrice; typedef struct packet_shop // 가변 패킷 @@ -1433,12 +1438,13 @@ struct packet_exchange BYTE header; BYTE sub_header; BYTE is_me; - DWORD arg1; // vnum + int64_t arg1; // vnum TItemPos arg2; // cell DWORD arg3; // count - long alSockets[ITEM_SOCKET_MAX_NUM]; + int32_t alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; }; +static_assert(sizeof(packet_exchange)==51,"gold64 GC exchange size"); enum EPacketTradeSubHeaders { @@ -1840,13 +1846,13 @@ typedef struct command_safebox_money { BYTE bHeader; BYTE bState; - long lMoney; + int64_t lMoney; } TPacketCGSafeboxMoney; typedef struct packet_safebox_money_change { BYTE bHeader; - long lMoney; + int64_t lMoney; } TPacketGCSafeboxMoneyChange; // Guild @@ -2082,10 +2088,10 @@ typedef struct packet_offline_shop_item { DWORD id; DWORD vnum; - long long price; - int count; + int64_t price; + int32_t count; BYTE display_pos; - long alSockets[ITEM_SOCKET_MAX_NUM]; + int32_t alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; BYTE status; char szBuyerName[CHARACTER_NAME_MAX_LEN+1]; @@ -2094,6 +2100,11 @@ typedef struct packet_offline_shop_item #endif DWORD owner_id; } TOfflineShopItem; +#ifndef ENABLE_CHANGELOOK_SYSTEM +static_assert(sizeof(TOfflineShopItem)==84,"offline item wire size"); +static_assert(offsetof(TOfflineShopItem,aAttr)==33,"offline item attribute offset"); +#endif + typedef struct SPacketCGMyOfflineShop { @@ -2132,6 +2143,11 @@ typedef struct packet_offline_shop_update_item int time; DWORD type; } TPacketGCOfflineShopUpdateItem; +#ifndef ENABLE_CHANGELOOK_SYSTEM +static_assert(sizeof(TPacketGCOfflineShopStart)==12083,"offline start wire size"); +static_assert(sizeof(TPacketGCOfflineShopUpdateItem)==229,"offline update wire size"); +#endif + #endif #ifdef ENABLE_SHOP_SEARCH_SYSTEM @@ -2437,7 +2453,7 @@ typedef struct SPacketGCPanamaPack //TODO : ì•„ìš° 짱나..가변패킷 사ì�´ì¦ˆ 받아들ì�¼ìˆ˜ 있게 패킷 핸들러 Refactoring 하ìž�. typedef struct SPacketGCHybridCryptKeys { - SPacketGCHybridCryptKeys() : m_pStream(NULL) {} + SPacketGCHybridCryptKeys() : bHeader(0), uDynamicPacketSize(0), KeyStreamLen(0), pDataKeyStream(NULL), m_pStream(NULL) {} ~SPacketGCHybridCryptKeys() { //GCC ì—�ì„  NULL delete í•´ë�„ 괜찮나? ì�¼ë‹¨ 안전하게 NULL ì²´í�¬ 하ìž�. ( ê·¼ë�° ì�´ê±° C++ 표준아니었나 --a ) @@ -2450,15 +2466,19 @@ typedef struct SPacketGCHybridCryptKeys DWORD GetStreamSize() { - return sizeof(bHeader) + sizeof(WORD) + sizeof(int) + KeyStreamLen; + if (KeyStreamLen < 0 || KeyStreamLen > 65535 - 7 || (KeyStreamLen > 0 && !pDataKeyStream)) return 0; + return 7u + static_cast(KeyStreamLen); } BYTE* GetStreamData() { - if( m_pStream ) - delete[] m_pStream; + delete[] m_pStream; + m_pStream = NULL; + uDynamicPacketSize = 0; + const DWORD size = GetStreamSize(); + if (!size) return NULL; - uDynamicPacketSize = (WORD)GetStreamSize(); + uDynamicPacketSize = static_cast(size); m_pStream = new BYTE[ uDynamicPacketSize ]; @@ -2486,7 +2506,7 @@ private: typedef struct SPacketGCPackageSDB { - SPacketGCPackageSDB() : m_pDataSDBStream(NULL), m_pStream(NULL) {} + SPacketGCPackageSDB() : bHeader(0), uDynamicPacketSize(0), iStreamLen(0), m_pDataSDBStream(NULL), m_pStream(NULL) {} ~SPacketGCPackageSDB() { if( m_pStream ) @@ -2498,15 +2518,19 @@ typedef struct SPacketGCPackageSDB DWORD GetStreamSize() { - return sizeof(bHeader) + sizeof(WORD) + sizeof(int) + iStreamLen; + if (iStreamLen < 0 || iStreamLen > 65535 - 7 || (iStreamLen > 0 && !m_pDataSDBStream)) return 0; + return 7u + static_cast(iStreamLen); } BYTE* GetStreamData() { - if( m_pStream ) - delete[] m_pStream; + delete[] m_pStream; + m_pStream = NULL; + uDynamicPacketSize = 0; + const DWORD size = GetStreamSize(); + if (!size) return NULL; - uDynamicPacketSize = GetStreamSize(); + uDynamicPacketSize = static_cast(size); m_pStream = new BYTE[ uDynamicPacketSize ]; diff --git a/src/server/game/src/port_battlepass_runtime.h b/src/server/game/src/port_battlepass_runtime.h index 10432c57..105cfc21 100644 --- a/src/server/game/src/port_battlepass_runtime.h +++ b/src/server/game/src/port_battlepass_runtime.h @@ -103,7 +103,7 @@ inline void PortBpLoad(DWORD pid,PortBpState& state) { PortBpState& state=it->second; if(!msg || msg->uiSQLErrno || !msg->Get()){sys_err("PORT_BP: load failed pid %u season %u",pid,season);return;} unsigned long long stored[kPortBpSlots+1]={}; - for(unsigned i=0;iGet()->uiNumRows;++i) { + for (uint64_t i=0;iGet()->uiNumRows;++i) { MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult); if(!row || !row[0] || !row[1] || !row[2])continue; const unsigned slot=unsigned(strtoul(row[1],nullptr,10)); diff --git a/src/server/game/src/port_costume_attr.cpp b/src/server/game/src/port_costume_attr.cpp index 19b0accf..9771036b 100644 --- a/src/server/game/src/port_costume_attr.cpp +++ b/src/server/game/src/port_costume_attr.cpp @@ -3,13 +3,14 @@ // value2 = target mask (1 << bonus flag). Dragged onto a costume they add that one fixed attribute, // at most three per costume; they never reroll anything, and gear is refused (they would otherwise be // free 40250 switchers, so the switchbot skips them too). -// Only the costume kinds 40250 has are mapped: body (flag 1), hair (2) and mount skin (4). AVA2's -// weapon costume (3), sash skin (5) and shining (6) items stay locked in tools/server/ava2-items. +// AVA2 bonus flags include body/hair/weapon/mount-skin/sash-skin/shining. +// 53998 removes the last normal attribute; 53999 removes all normal attributes. // Messages go to the client as "MTCATTR " commands (rendered by the client's mt_costume_attr // script) instead of AVA2's locale strings 1056 / 1057 / 1061 / 1062 / 1063. #include "stdafx.h" #include "char.h" #include "item.h" +#include "item_manager.h" #include "log.h" enum @@ -21,8 +22,9 @@ enum bool CItem::IsCostumeEnchant() { - return GetType() == ITEM_USE && GetSubType() == USE_CHANGE_ATTRIBUTE && GetValue(2) != 0 && - GetVnum() >= COSTUME_ENCHANT_VNUM_MIN && GetVnum() <= COSTUME_ENCHANT_VNUM_MAX; + return GetType() == ITEM_USE && GetSubType() == USE_CHANGE_ATTRIBUTE && + (GetVnum() == 53998 || GetVnum() == 53999 || + (GetValue(2) != 0 && GetVnum() >= COSTUME_ENCHANT_VNUM_MIN && GetVnum() <= COSTUME_ENCHANT_VNUM_MAX)); } // AVA2 CItem::GetBonusFlag for the costume kinds that exist here; 0 = cannot be enchanted. @@ -60,25 +62,20 @@ static int CostumeEnchantFlag(LPITEM item) bool CHARACTER::CostumeEnchantUse(LPITEM item, LPITEM item2) { - if (item2->IsExchanging()) + if (!item || !item2 || item == item2 || !item->IsCostumeEnchant() || !item->GetCount() || + item->GetOwner() != this || item2->GetOwner() != this || + item->IsExchanging() || item2->IsExchanging() || item->isLocked() || item2->isLocked()) return false; const int flag = CostumeEnchantFlag(item2); - const BYTE applyType = static_cast(item->GetValue(0)); - const short applyValue = static_cast(item->GetValue(1)); + const bool removal = item->GetVnum() == 53998 || item->GetVnum() == 53999; - if (!flag || !(item->GetValue(2) & (1 << flag))) + if (!flag || (!removal && !(item->GetValue(2) & (1 << flag)))) { ChatPacket(CHAT_TYPE_COMMAND, "MTCATTR target"); return false; } - if (applyType == APPLY_NONE || applyValue == 0) - { - ChatPacket(CHAT_TYPE_COMMAND, "MTCATTR none"); - return false; - } - // 40250 equipped items are never touched by attribute items (the "Fix" in the switcher path): // the new attribute would not be applied to the character until the next re-equip. if (item2->IsEquipped()) @@ -87,6 +84,40 @@ bool CHARACTER::CostumeEnchantUse(LPITEM item, LPITEM item2) return false; } + if (removal) + { + bool changed = false; + // Match AVA2: reverse order for one, every normal slot for all. + // Rare slots 5/6 and the extended lock records are retained. + for (int index = ITEM_MANAGER::MAX_NORM_ATTR_NUM - 1; index >= 0; --index) + { + if (item2->GetAttributeType(index) == APPLY_NONE) + continue; + item2->SetForceAttribute(index, APPLY_NONE, 0); + changed = true; + if (item->GetVnum() == 53998) + break; + } + if (changed) + { + LogManager::instance().ItemLog(this, item2, "COSTUME_REMOVE_ATTRIBUTE", item->GetVnum() == 53998 ? "last" : "all"); + item->SetCount(item->GetCount() - 1); + } + ChatPacket(CHAT_TYPE_COMMAND, changed ? "MTCATTR removed" : "MTCATTR empty"); + return true; + } + + // Reject corrupt proto values before their serialized widths can truncate. + const int type = item->GetValue(0), value = item->GetValue(1); + if (type <= APPLY_NONE || type >= MAX_APPLY_NUM || type > UINT8_MAX || + value <= 0 || value > INT16_MAX) + { + ChatPacket(CHAT_TYPE_COMMAND, "MTCATTR none"); + return false; + } + const BYTE applyType = static_cast(type); + const short applyValue = static_cast(value); + if (item2->GetAttributeCount() >= COSTUME_ENCHANT_MAX_ATTR) { ChatPacket(CHAT_TYPE_COMMAND, "MTCATTR full"); diff --git a/src/server/game/src/port_economy.cpp b/src/server/game/src/port_economy.cpp new file mode 100644 index 00000000..8236a764 --- /dev/null +++ b/src/server/game/src/port_economy.cpp @@ -0,0 +1,95 @@ +#include "stdafx.h" +#include "port_economy.h" +#include "char.h" +#include "char_manager.h" +#include "item.h" +#include "desc.h" +#include "desc_client.h" +#include "desc_manager.h" +#include "questmanager.h" +#include "questpc.h" +#include "cmd.h" +#include "config.h" +#include +#include +#include +#include +#include +#include +#include + +bool PortEconomySubmit(CHARACTER* ch,PortEconomy::Request& r) { + if(*get_table_postfix())return false; + if(!ch||!ch->IsPC()||!ch->GetDesc()||!db_clientdesc||!ch->IsItemLoaded())return false; + auto* pc=quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID()); + if(!pc||!pc->IsLoaded()||pc->IsRunning()||!ch->CanHandleItem()||ch->IsWarping()||ch->IsDead()||ch->IsStun()|| + ch->GetExchange()||ch->GetMyShop()||ch->GetShop()||ch->IsOpenSafebox()||ch->GetMall()||ch->IsCubeOpen())return false; + r.account=ch->GetDesc()->GetAccountTable().id;r.player=ch->GetPlayerID(); + r.expectedGold=ch->GetGold();r.expectedGem=ch->GetQuestFlag("gem.points");r.expectedOpen=ch->GetQuestFlag("gem.open_slot"); + if(r.operation==PortEconomy::UiStatus) { + static std::map next;const auto now=time(nullptr);const auto handle=ch->GetDesc()->GetHandle(); + if(next[handle]>now)return false; + if(next.size()>4096){for(auto it=next.begin();it!=next.end();)if(it->second<=now)it=next.erase(it);else ++it;if(next.size()>4096)return false;} + next[handle]=now+1; + } + if(!PortEconomy::Token(r.token)) { + unsigned char random[16];int fd=open("/dev/urandom",O_RDONLY);if(fd<0)return false;size_t offset=0; + while(offset(n);}close(fd); + const std::string token=PortEconomy::Hex(random,sizeof(random));memcpy(r.token,token.c_str(),sizeof(r.token)); + } + if(!PortEconomy::Valid(r))return false; + db_clientdesc->DBPacket(PortEconomy::Header,ch->GetDesc()->GetHandle(),&r,sizeof(r)); + if(r.operation!=PortEconomy::Status && r.operation!=PortEconomy::UiStatus) { + // No money, item, flag or catalogue mutation occurs in game. Closing + // runs normal final saves + logout after this durable intent request. + ch->ChatPacket(CHAT_TYPE_INFO,"Transaction requested. Reconnect, select this character, then use /mt_economy status to check the result."); + ch->GetDesc()->SetPhase(PHASE_CLOSE); + } + return true; +} + +void PortEconomyReply(unsigned handle,const char* data) { + PortEconomy::Reply reply;memcpy(&reply,data,sizeof(reply)); + if(reply.message[sizeof(reply.message)-1]||reply.ok>1)return; + LPDESC d=DESC_MANAGER::instance().FindByHandle(handle); + if(!d||!d->GetCharacter()||d->GetAccountTable().id!=reply.account||d->GetCharacter()->GetPlayerID()!=reply.player)return; + d->GetCharacter()->ChatPacket(strncmp(reply.message,"MTECON1 ",8)==0?CHAT_TYPE_COMMAND:CHAT_TYPE_INFO,"%s",reply.message); +} + +ACMD(do_mt_economy) { + if(!ch)return; + std::istringstream input(argument);std::string op,receipt;input>>op; + const bool action=op=="act"; + if(action){input>>receipt>>op;if(receipt.size()!=32||receipt==std::string(32,'0'))return;} + std::vector args;std::string value;while(input>>value){args.push_back(value);if(args.size()>6)return;} + PortEconomy::Request r; + if(action){memcpy(r.token,receipt.c_str(),33);if(!PortEconomy::Token(r.token))return;} + auto fail=[&](){if(action)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTECON1 action_error %s rejected",receipt.c_str());else ch->ChatPacket(CHAT_TYPE_INFO,"Economy request unavailable or invalid.");}; + auto parse=[](const std::string& text,uint64_t maximum,uint64_t& out)->bool{ + if(text.empty())return false;uint64_t n=0; + for(char c:text){if(c<'0'||c>'9'||uint64_t(c-'0')>maximum||n>(maximum-uint64_t(c-'0'))/10)return false;n=n*10+uint64_t(c-'0');}out=n;return true; + }; + uint64_t first=0,second=0; + if(op=="ui"&&!action&&args.size()==5) { + uint64_t mode=0,sequence=0,owner=0; + if(!parse(args[0],2,mode)||!parse(args[1],1000000,first)||!parse(args[2],UINT32_MAX,sequence)||!sequence|| + !parse(args[3],UINT32_MAX,owner)||args[4].size()!=32)return; + memcpy(r.token,args[4].c_str(),33);if(!PortEconomy::Token(r.token))return; + r.operation=PortEconomy::UiStatus;r.slot=static_cast(mode);r.reference=first;r.generation=sequence;r.item=static_cast(owner); + if(!PortEconomySubmit(ch,r))ch->ChatPacket(CHAT_TYPE_COMMAND,"MTECON1 error %llu busy",static_cast(sequence));return; + } + if(op=="status"&&!action&&args.size()<=1&&(args.empty()||parse(args[0],1000000,first))){r.operation=PortEconomy::Status;r.reference=first;} + else if(op=="gaya_retire"&&!action&&args.empty())r.operation=PortEconomy::GayaRetire; + else if(op=="withdraw"&&args.empty())r.operation=PortEconomy::Withdraw; + else if(op=="list"&&args.size()==(action?4u:2u)&&parse(args[0],224,first)&&parse(args[1],PortEconomy::GoldLimit,second)&&second) { + LPITEM item=ch->GetInventoryItem(static_cast(first));uint64_t vnum=0,count=0; + if(!item||item->IsEquipped()||item->isLocked()||item->IsExchanging()||IS_SET(item->GetAntiFlag(),ITEM_ANTIFLAG_GIVE|ITEM_ANTIFLAG_MYSHOP)||item->GetType()==ITEM_QUEST){fail();return;} + if(action&&(!parse(args[2],UINT32_MAX,vnum)||!parse(args[3],2000,count)||vnum!=item->GetOriginalVnum()||count!=item->GetCount())){fail();return;} + r.operation=PortEconomy::List;r.item=item->GetID();r.itemVnum=item->GetOriginalVnum();r.itemCount=item->GetCount();r.price=static_cast(second); + } else if(op=="buy"&&args.size()==2&&parse(args[0],UINT64_MAX,first)&&parse(args[1],PortEconomy::GoldLimit,second)&&first&&second) { + r.operation=PortEconomy::Buy;r.reference=first;r.price=static_cast(second); + } else if(args.size()==1&&parse(args[0],UINT64_MAX,first)&&first&&(op=="refund"||op=="claim"||op=="cancel")) { + r.operation=op=="refund"?PortEconomy::Refund:op=="claim"?PortEconomy::Claim:PortEconomy::Cancel;r.reference=first; + } else {fail();return;} + if(!PortEconomySubmit(ch,r))fail(); +} diff --git a/src/server/game/src/port_economy.h b/src/server/game/src/port_economy.h new file mode 100644 index 00000000..83fb261a --- /dev/null +++ b/src/server/game/src/port_economy.h @@ -0,0 +1,5 @@ +#pragma once +#include "../../common/economy.h" +class CHARACTER; +bool PortEconomySubmit(CHARACTER*,PortEconomy::Request&); +void PortEconomyReply(unsigned,const char*); diff --git a/src/server/game/src/port_features.h b/src/server/game/src/port_features.h index 08aec4ad..6ede47fa 100644 --- a/src/server/game/src/port_features.h +++ b/src/server/game/src/port_features.h @@ -7,6 +7,7 @@ static void PortTrackTravel(LPCHARACTER ch,unsigned request,unsigned boss); // Own-player read-only protocol v1. Capability bits: drops, chests, stats, reverse sources, dungeon snapshots; 256 = world bosses. void PortBossQuery(LPCHARACTER ch,unsigned request); +static void PortRankQuery(LPCHARACTER ch,unsigned request,unsigned index); static bool PortFeatureNumber(const std::string& text,unsigned& value) { if (text.empty() || text.size()>10) return false; unsigned long long result=0; @@ -27,6 +28,7 @@ static const PortStat kPortStats[]={ {"resist_warrior",POINT_RESIST_WARRIOR},{"resist_assassin",POINT_RESIST_ASSASSIN},{"resist_sura",POINT_RESIST_SURA},{"resist_shaman",POINT_RESIST_SHAMAN}, {"sword",POINT_RESIST_SWORD},{"twohand",POINT_RESIST_TWOHAND},{"dagger",POINT_RESIST_DAGGER},{"bell",POINT_RESIST_BELL},{"fan",POINT_RESIST_FAN},{"bow",POINT_RESIST_BOW}, {"magic",POINT_RESIST_MAGIC},{"fire",POINT_RESIST_FIRE},{"electric",POINT_RESIST_ELEC},{"wind",POINT_RESIST_WIND},{"poison_reduce",POINT_POISON_REDUCE}, + {"magic_resist_reduction",POINT_RESIST_MAGIC_REDUCTION}, {"hp_regen",POINT_HP_REGEN},{"sp_regen",POINT_SP_REGEN},{"steal_hp",POINT_STEAL_HP},{"steal_sp",POINT_STEAL_SP}, {"exp_bonus",POINT_EXP_DOUBLE_BONUS},{"gold_bonus",POINT_GOLD_DOUBLE_BONUS},{"item_bonus",POINT_ITEM_DROP_BONUS}, {"skill_damage",POINT_SKILL_DAMAGE_BONUS},{"normal_damage",POINT_NORMAL_HIT_DAMAGE_BONUS}, @@ -45,7 +47,7 @@ ACMD(do_port_features) { ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return; } ch->m_portFeatureLastQuery=get_dword_time(); - if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 959 %lld",request,(long long)get_global_time());return;} + if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 1983 %lld",request,(long long)get_global_time());return;} if(kind=="dungeons" && args.size()==3) {PortDungeonQuery(ch,request);return;} if(kind=="bosses" && args.size()==3) {PortBossQuery(ch,request);return;} if(kind=="stats" && args.size()==3) { @@ -58,9 +60,13 @@ ACMD(do_port_features) { } ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,unsigned(sizeof(kPortStats)/sizeof(kPortStats[0])));return; } - if(args.size()!=5 || !PortFeatureNumber(args[3],subject) || !subject || !PortFeatureNumber(args[4],offset) || offset>4096) { + if(args.size()!=5 || !PortFeatureNumber(args[3],subject) || (!subject && kind!="rank") || !PortFeatureNumber(args[4],offset) || offset>4096) { ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u invalid",request);return; } + if(kind=="rank") { + if(subject>=10 || offset){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u invalid",request);return;} + PortRankQuery(ch,request,subject);return; + } if(kind=="calendar" && subject==1) {PortCalendarQuery(ch,request,offset);return;} if(kind=="travel" && !offset) {PortTrackTravel(ch,request,subject);return;} std::vector rows; diff --git a/src/server/game/src/port_gaya.cpp b/src/server/game/src/port_gaya.cpp index d8b0195b..8ca5c6ac 100644 --- a/src/server/game/src/port_gaya.cpp +++ b/src/server/game/src/port_gaya.cpp @@ -1,17 +1,27 @@ #include "stdafx.h" #include "port_gaya.h" #include "char.h" +#include "item.h" +#include "item_manager.h" +#include "questmanager.h" +#include "questpc.h" #include "utils.h" #include "cmd.h" +#include "db.h" +#include "port_economy.h" #include #include #include #include #include +#include +#include "../../common/gaya_catalog.h" namespace { std::string s_gayaDir = "locale/germany/gem"; std::map> s_playerGayaItems; +std::map> s_catalogFiles; +std::map s_databaseGeneration; struct GemCatalogEntry { uint32_t vnum; @@ -88,6 +98,9 @@ static const GemCatalogEntry s_gemCatalog[] = { } void PortGayaSetDirectory(const std::string& dir) { + s_databaseGeneration.clear(); + s_catalogFiles.clear(); + s_playerGayaItems.clear(); s_gayaDir = dir; } @@ -101,90 +114,124 @@ int PortGayaGet(const CHARACTER* ch) { } void PortGayaChange(CHARACTER* ch, int amount) { - if (!ch) return; + if (!ch || !PortGayaLoadItems(ch)) return; int current = PortGayaGet(ch); - int updated = std::max(0, std::min(GEM_MAX, current + amount)); + const int64_t candidate=int64_t(current)+amount; + if(candidate<0 || candidate>GEM_MAX)return; + int updated = static_cast(candidate); ch->SetQuestFlag("gem.points", updated); ch->SetPoint(POINT_GEM, updated); ch->PointChange(POINT_GEM, 0); } +static bool PortGayaCanMutate(CHARACTER* ch) { + if (!ch || !ch->IsPC() || !ch->GetDesc() || !ch->IsItemLoaded()) return false; + quest::PC* pc = quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID()); + const int slots = ch->GetQuestFlag("gem.open_slot"), balance = PortGayaGet(ch); + return pc && pc->IsLoaded() && !pc->IsRunning() && slots >= 0 && slots <= 18 && balance >= 0 && balance <= GEM_MAX && + ch->CanHandleItem() && !ch->IsDead() && !ch->IsStun() && !ch->IsWarping() && !ch->GetExchange() && + !ch->GetMyShop() && !ch->GetShop() && !ch->IsOpenSafebox() && !ch->IsCubeOpen(); +} + bool PortGayaOpenSlot(CHARACTER* ch) { - if (!ch) return false; - const int openSlotFlag = ch->GetQuestFlag("gem.open_slot"); - if (openSlotFlag < 18) { - ch->SetQuestFlag("gem.open_slot", openSlotFlag + 1); - ch->ChatPacket(CHAT_TYPE_COMMAND, "GemUpdateSlotCount %d", openSlotFlag + 1); + if (!PortGayaCanMutate(ch) || !PortGayaLoadItems(ch) || ch->GetQuestFlag("gem.open_slot")>=18) return false; + LPITEM consumable=ch->FindSpecifyItem(OPEN_GEM_SLOT_ITEM); + if(!consumable || consumable->isLocked() || consumable->IsExchanging())return false; + PortEconomy::Request r;r.operation=PortEconomy::GayaExpand;r.item=consumable->GetID();r.itemCount=consumable->GetCount(); + return PortEconomySubmit(ch,r); +} + +void PortGayaForgetPlayer(uint32_t player) { + s_databaseGeneration.erase(player); + s_playerGayaItems.erase(player); + s_catalogFiles.erase(player); +} + +bool PortGayaLoadItems(CHARACTER* ch) { + if (!ch || !ch->IsPC() || !ch->GetDesc() || !ch->GetPlayerID() || !ch->IsItemLoaded()) return false; + quest::PC* pc = quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID()); + if (!pc || !pc->IsLoaded()) return false; + const uint32_t pid = ch->GetPlayerID(); + auto committed=s_databaseGeneration.find(pid); + if(committed!=s_databaseGeneration.end() && committed->second)return committed->secondsecond->Ready(); + std::map loaded; + int refresh = 0; + // A committed SQL catalogue supersedes the old local file. No file write + // participates in a purchase, refresh-consumable or expansion transaction. + std::unique_ptr schema(DBManager::instance().DirectQuery("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_economy_gaya'")); + if(!schema || schema->uiSQLErrno || !schema->Get() || schema->Get()->uiNumRows!=1 || !schema->Get()->pSQLResult)return false; + MYSQL_ROW present=mysql_fetch_row(schema->Get()->pSQLResult);if(!present || !present[0])return false; + std::unique_ptr sql; + if(std::string(present[0])=="1")sql.reset(DBManager::instance().DirectQuery("SELECT generation,deadline,offers FROM port_economy_gaya WHERE pid=%u",pid)); + else if(std::string(present[0])!="0")return false; + if(sql && (sql->uiSQLErrno || !sql->Get()))return false; + auto result=PortGayaCatalogFile::Missing; + uint64_t generation=0; + if(sql && sql->Get()->uiNumRows) { + if(sql->Get()->uiNumRows!=1 || !sql->Get()->pSQLResult)return false; + MYSQL_ROW row=mysql_fetch_row(sql->Get()->pSQLResult);const unsigned long* lengths=mysql_fetch_lengths(sql->Get()->pSQLResult); + PortEconomy::Offer offers[27]; + if(!row || !row[0] || !row[1] || !row[2] || lengths[2]!=sizeof(offers) || + !str_to_number(generation,row[0]) || !generation || !str_to_number(refresh,row[1]) || refresh<0)return false; + if(generation>=PortEconomy::RetiredGeneration) { + s_databaseGeneration[pid]=PortEconomy::RetiredGeneration; + ch->ChatPacket(CHAT_TYPE_INFO,"This Gaya catalogue is retired. Character deletion is available after all other assets are settled."); + return false; + } + memcpy(offers,row[2],sizeof(offers));if(!PortEconomy::Offers(offers))return false; + for(uint8_t i=0;i<27;++i)loaded[i]={offers[i].vnum,offers[i].count,offers[i].price,offers[i].bought!=0}; + s_databaseGeneration[pid]=generation;s_playerGayaItems[pid].swap(loaded); + ch->SetQuestFlag("gem.left_time",refresh); return true; } - return false; + std::unique_ptr store(new PortGayaCatalogFile); + if (!store->Open(s_gayaDir, pid)) { + sys_err("GAYA: player %u catalogue unavailable: %s", pid, store->ErrorText().c_str()); + return false; + } + result=store->Load(loaded,refresh); + s_databaseGeneration[pid]=0; + s_catalogFiles[pid] = std::move(store); + if (result == PortGayaCatalogFile::Error) { + sys_err("GAYA: player %u corrupt catalogue retained: %s", pid, s_catalogFiles[pid]->ErrorText().c_str()); + return false; + } + s_playerGayaItems[pid].swap(loaded); + if (result == PortGayaCatalogFile::Loaded && refresh > 0) + ch->SetQuestFlag("gem.left_time", refresh); + return true; } -void PortGayaLoadItems(CHARACTER* ch) { - if (!ch) return; - uint32_t pid = ch->GetPlayerID(); - auto& items = s_playerGayaItems[pid]; - items.clear(); - - char filename[256]; - snprintf(filename, sizeof(filename), "%s/%u", s_gayaDir.c_str(), pid); - FILE* fp = fopen(filename, "r"); - if (fp) { - char line[256]; - while (fgets(line, sizeof(line), fp)) { - unsigned slot = 0, vnum = 0, count = 0, buyed = 0; - int price = 0; - if (sscanf(line, "%u %u %u %d %u", &slot, &vnum, &count, &price, &buyed) == 5) { - TGemItem item; - item.itemVnum = vnum; - item.itemCount = count; - item.itemPrice = price; - item.itemBuyed = (buyed != 0); - items[(uint8_t)slot] = item; - } - } - fclose(fp); +bool PortGayaSaveItems(CHARACTER* ch) { + if (!ch) return false; + const uint32_t pid = ch->GetPlayerID(); + if(s_databaseGeneration[pid])return false; // SQL catalogue is the authority after migration. + auto store = s_catalogFiles.find(pid); + if (store == s_catalogFiles.end() || !store->second->Save(s_playerGayaItems[pid], ch->GetQuestFlag("gem.left_time"))) { + sys_err("GAYA: player %u catalogue save failed; pause market and reconcile item/balance before resuming", pid); + return false; } + return true; } -void PortGayaSaveItems(CHARACTER* ch) { - if (!ch) return; +static bool PortGayaGenerateItems(CHARACTER* ch, int nextRefresh, uint32_t consumable=0, uint32_t consumableCount=0) { + if (!PortGayaLoadItems(ch)) return false; uint32_t pid = ch->GetPlayerID(); - const auto& items = s_playerGayaItems[pid]; - - // Ensure directory exists - size_t slash = s_gayaDir.rfind('/'); - if (slash != std::string::npos) { - std::string parent = s_gayaDir.substr(0, slash); - mkdir(parent.c_str(), 0755); - } - mkdir(s_gayaDir.c_str(), 0755); - - char filename[256]; - snprintf(filename, sizeof(filename), "%s/%u", s_gayaDir.c_str(), pid); - FILE* fp = fopen(filename, "w+"); - if (fp) { - fprintf(fp, "index-vnum-count-price-buyed\n"); - for (const auto& kv : items) { - fprintf(fp, "%u %u %u %d %u\n", kv.first, kv.second.itemVnum, kv.second.itemCount, kv.second.itemPrice, kv.second.itemBuyed ? 1 : 0); - } - fflush(fp); - fsync(fileno(fp)); - fclose(fp); - } -} - -static void PortGayaGenerateItems(CHARACTER* ch) { - if (!ch) return; - uint32_t pid = ch->GetPlayerID(); - auto& items = s_playerGayaItems[pid]; - items.clear(); + std::map items; const size_t catalogSize = sizeof(s_gemCatalog) / sizeof(s_gemCatalog[0]); std::vector chosenIndices; + unsigned draws = 0; while (chosenIndices.size() < 27 && chosenIndices.size() < catalogSize) { for (size_t i = 0; i < catalogSize; ++i) { - if (number(1, 100) > s_gemCatalog[i].lucky) continue; + if (++draws > 100000) { + sys_err("GAYA: item selection exhausted; refresh refused without consumption"); + return false; + } + // AVA2's field is a rejection threshold: 100 admits a roll of 100. + if (number(1, 100) < s_gemCatalog[i].lucky) continue; if (std::find(chosenIndices.begin(), chosenIndices.end(), (uint8_t)i) != chosenIndices.end()) continue; chosenIndices.push_back((uint8_t)i); if (chosenIndices.size() >= 27) break; @@ -199,23 +246,36 @@ static void PortGayaGenerateItems(CHARACTER* ch) { it.itemPrice = entry.price; items[(uint8_t)i] = it; } - PortGayaSaveItems(ch); + if(s_databaseGeneration[pid] || consumable) { + PortEconomy::Request r;r.operation=PortEconomy::GayaRefresh;r.item=consumable;r.itemCount=consumableCount; + r.generation=s_databaseGeneration[pid];r.deadline=ch->GetQuestFlag("gem.left_time");r.nextDeadline=nextRefresh; + if(s_playerGayaItems[pid].size()!=27 || items.size()!=27)return false; + for(const auto& kv:s_playerGayaItems[pid]){const auto& i=kv.second;r.offers[kv.first]={i.itemVnum,i.itemCount,i.itemPrice,uint8_t(i.itemBuyed)};} + for(const auto& kv:items){const auto& i=kv.second;r.nextOffers[kv.first]={i.itemVnum,i.itemCount,i.itemPrice,0};} + return PortEconomySubmit(ch,r); + } + if (!s_catalogFiles[pid]->Save(items, nextRefresh)) { + sys_err("GAYA: player %u refresh not committed: %s", pid, s_catalogFiles[pid]->ErrorText().c_str()); + return false; + } + s_playerGayaItems[pid].swap(items); + ch->SetQuestFlag("gem.left_time", nextRefresh); + return true; } void PortGayaRefreshPlayer(CHARACTER* ch) { if (!ch) return; uint32_t pid = ch->GetPlayerID(); - auto it = s_playerGayaItems.find(pid); - if (it == s_playerGayaItems.end() || it->second.empty()) { - PortGayaLoadItems(ch); - if (s_playerGayaItems[pid].empty()) - PortGayaGenerateItems(ch); + if (!PortGayaLoadItems(ch)) return; + if (s_playerGayaItems[pid].empty()) { + int next = 0; + if (!PortGayaNextRefresh(time(0), 0, false, next) || !PortGayaGenerateItems(ch, next)) return; } ch->ChatPacket(CHAT_TYPE_COMMAND, "GemClear"); ch->ChatPacket(CHAT_TYPE_COMMAND, "GemUpdateSlotCount %d", ch->GetQuestFlag("gem.open_slot")); - int left = ch->GetQuestFlag("gem.left_time") - time(0); - ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetRefreshLeftTime %d", left > 0 ? left : 0); + const int64_t left = int64_t(ch->GetQuestFlag("gem.left_time")) - int64_t(time(0)); + ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetRefreshLeftTime %d", left > 0 ? static_cast(left) : 0); const auto& items = s_playerGayaItems[pid]; std::string cmdString = ""; @@ -242,25 +302,31 @@ void PortGayaRefreshPlayer(CHARACTER* ch) { } } -void PortGayaRefreshAll(CHARACTER* ch, bool withRealTime) { - if (!ch) return; - int leftTime = 0; - if (withRealTime && ch->GetQuestFlag("gem.left_time") != 0) { - leftTime = time(0) - ch->GetQuestFlag("gem.left_time"); - if (leftTime < 1) leftTime = 0; +bool PortGayaRefreshAll(CHARACTER* ch, bool withRealTime) { + if (!PortGayaCanMutate(ch) || !PortGayaLoadItems(ch)) return false; + int next = 0; + const int previous = ch->GetQuestFlag("gem.left_time"); + if (!PortGayaNextRefresh(time(0), previous, withRealTime, next)) return false; + if (withRealTime && previous > time(0)) { PortGayaRefreshPlayer(ch); return true; } + uint32_t consumable=0,consumableCount=0; + if(!withRealTime) { + LPITEM item=ch->FindSpecifyItem(OPEN_GEM_REFRESH_ITEM); + if(!item || item->isLocked() || item->IsExchanging())return false; + consumable=item->GetID();consumableCount=item->GetCount(); + // Initial offers are non-economic. Establish a snapshot before staging + // a paid refresh; no consumable is removed here. + if(s_playerGayaItems[ch->GetPlayerID()].empty()) {PortGayaRefreshPlayer(ch);if(s_playerGayaItems[ch->GetPlayerID()].empty())return false;} } - ch->SetQuestFlag("gem.left_time", (time(0) + REFRESH_TIME) - leftTime); - PortGayaGenerateItems(ch); + if (!PortGayaGenerateItems(ch, next,consumable,consumableCount)) return false; PortGayaRefreshPlayer(ch); + return true; } void PortGayaBuyItem(CHARACTER* ch, uint8_t slotIndex) { - if (!ch) return; + if (!PortGayaCanMutate(ch) || slotIndex >= 27) return; uint32_t pid = ch->GetPlayerID(); + if (!PortGayaLoadItems(ch)) return; auto& items = s_playerGayaItems[pid]; - if (items.empty()) { - PortGayaLoadItems(ch); - } auto it = items.find(slotIndex); if (it != items.end()) { if (slotIndex >= 9) { @@ -270,15 +336,33 @@ void PortGayaBuyItem(CHARACTER* ch, uint8_t slotIndex) { if (it->second.itemBuyed) return; int price = it->second.itemPrice; - if (price > PortGayaGet(ch)) { + if (price <= 0 || price > GEM_MAX || !it->second.itemVnum || !it->second.itemCount || it->second.itemCount > 2000 || + PortGayaGet(ch) > GEM_MAX || price > PortGayaGet(ch)) { ch->ChatPacket(CHAT_TYPE_INFO, "Not enough Gaya."); return; } - it->second.itemBuyed = true; - PortGayaChange(ch, -price); - ch->AutoGiveItem(it->second.itemVnum, it->second.itemCount); - ch->ChatPacket(CHAT_TYPE_COMMAND, "GemSetBuyedSlot %d 1", slotIndex); - PortGayaSaveItems(ch); + if(items.size()!=27)return; + PortEconomy::Request request;request.operation=PortEconomy::GayaBuy; + request.generation=s_databaseGeneration[pid];request.deadline=ch->GetQuestFlag("gem.left_time");request.slot=slotIndex; + for(const auto& kv:items){const auto& i=kv.second;request.offers[kv.first]={i.itemVnum,i.itemCount,i.itemPrice,uint8_t(i.itemBuyed)};} + // Allocate stable item IDs and the normal factory's sockets/attributes, + // but publish no item to inventory and schedule no save in game. + uint32_t left=it->second.itemCount; + while(left) { + if(request.rewardCount>=10)return; + LPITEM reward=ITEM_MANAGER::instance().CreateItem(it->second.itemVnum,left); + if(!reward)return; + reward->SetSkipSave(true); + const uint32_t count=reward->GetCount(); + if(!count || count>left){M2_DESTROY_ITEM(reward);return;} + auto& out=request.rewards[request.rewardCount++];out.id=reward->GetID();out.vnum=reward->GetOriginalVnum();out.count=count; + for(unsigned j=0;j<3;++j)out.sockets[j]=reward->GetSocket(j); + for(unsigned j=0;j<7;++j){out.types[j]=reward->GetAttributes()[j].bType;out.values[j]=reward->GetAttributes()[j].sValue;} + static_assert(sizeof(out.extra)==sizeof(PortItemExtra),"complete durable reward extras"); + memcpy(out.extra,&reward->GetPortExtra(),sizeof(out.extra)); + M2_DESTROY_ITEM(reward);left-=count; + } + PortEconomySubmit(ch,request); } } @@ -295,8 +379,8 @@ bool CHARACTER::OpenGemSlot() { return PortGayaOpenSlot(this); } -void CHARACTER::RefreshGemALL(bool withRealTime) { - PortGayaRefreshAll(this, withRealTime); +bool CHARACTER::RefreshGemALL(bool withRealTime) { + return PortGayaRefreshAll(this, withRealTime); } void CHARACTER::RefreshGemPlayer() { @@ -309,9 +393,11 @@ void CHARACTER::BuyGemItem(BYTE slotIndex) { ACMD(do_gem) { if (!ch || !ch->IsPC() || !ch->GetDesc() || ch->IsWarping() || ch->IsDead()) return; - std::vector vecArgs; - split_argument(argument, vecArgs); - if (vecArgs.size() < 2) return; + std::vector vecArgs(1, "gem"); + std::istringstream input(argument); + std::string word; + while (input >> word) vecArgs.push_back(word); + if (vecArgs.size() < 2 || (vecArgs[1] != "buy" && vecArgs.size() != 2)) return; if (vecArgs[1] == "load") { if (time(0) >= ch->GetQuestFlag("gem.left_time")) { ch->RefreshGemALL(true); @@ -327,20 +413,17 @@ ACMD(do_gem) { ch->ChatPacket(CHAT_TYPE_INFO, "You don't have enough Gaya slot expansion items."); return; } - if (ch->OpenGemSlot()) { - ch->RemoveSpecifyItem(OPEN_GEM_SLOT_ITEM, 1); - } + ch->OpenGemSlot(); // DB transaction consumes the item after logout. } else if (vecArgs[1] == "refresh") { if (ch->CountSpecifyItem(OPEN_GEM_REFRESH_ITEM) < 1) { ch->ChatPacket(CHAT_TYPE_INFO, "You don't have enough refresh Gaya market items."); return; } - ch->RemoveSpecifyItem(OPEN_GEM_REFRESH_ITEM, 1); - ch->RefreshGemALL(); + ch->RefreshGemALL(); // DB transaction consumes the item after logout. } else if (vecArgs[1] == "buy") { if (vecArgs.size() < 3) return; - BYTE slotIndex = 0; - if (!str_to_number(slotIndex, vecArgs[2].c_str())) return; - ch->BuyGemItem(slotIndex); + unsigned long long slotIndex = 0; + if (vecArgs.size() != 3 || !str_to_number(slotIndex, vecArgs[2].c_str()) || slotIndex >= 27) return; + ch->BuyGemItem(static_cast(slotIndex)); } } diff --git a/src/server/game/src/port_gaya.h b/src/server/game/src/port_gaya.h index 0fa72ea9..e44f9916 100644 --- a/src/server/game/src/port_gaya.h +++ b/src/server/game/src/port_gaya.h @@ -25,10 +25,12 @@ class CHARACTER; int PortGayaGet(const CHARACTER* ch); void PortGayaChange(CHARACTER* ch, int amount); bool PortGayaOpenSlot(CHARACTER* ch); -void PortGayaRefreshAll(CHARACTER* ch, bool withRealTime = false); +bool PortGayaRefreshAll(CHARACTER* ch, bool withRealTime = false); void PortGayaRefreshPlayer(CHARACTER* ch); void PortGayaBuyItem(CHARACTER* ch, uint8_t slotIndex); -void PortGayaSaveItems(CHARACTER* ch); -void PortGayaLoadItems(CHARACTER* ch); +bool PortGayaSaveItems(CHARACTER* ch); +bool PortGayaLoadItems(CHARACTER* ch); void PortGayaSetDirectory(const std::string& dir); const std::string& PortGayaGetDirectory(); + +void PortGayaForgetPlayer(uint32_t player); diff --git a/src/server/game/src/port_magic_reduction.h b/src/server/game/src/port_magic_reduction.h new file mode 100644 index 00000000..ffa2e291 --- /dev/null +++ b/src/server/game/src/port_magic_reduction.h @@ -0,0 +1,17 @@ +#ifndef METIN2_PORT_MAGIC_REDUCTION_H +#define METIN2_PORT_MAGIC_REDUCTION_H +#include +#include + +// Candidate AVA2 ENABLE_MAGIC_REDUCTION_SYSTEM branch (disabled in the archive). +// Activation requires an explicit rules decision; default combat is unchanged. +// This is the attacker's reduction of the victim's magic resistance. +inline int PortMagicDamageAfterResistance(int damage, int64_t resistance, + int64_t reduction, bool sura) { + resistance=std::max(0,std::min(100,resistance)); + if(sura)reduction/=2; + reduction=std::max(0,std::min(50,reduction)); + const int64_t effective=std::max(0,std::min(100,resistance-reduction)); + return static_cast(static_cast(damage)*(100-effective)/100); +} +#endif diff --git a/src/server/game/src/port_offlineshop.cpp b/src/server/game/src/port_offlineshop.cpp index d10b710e..9884f4c2 100644 --- a/src/server/game/src/port_offlineshop.cpp +++ b/src/server/game/src/port_offlineshop.cpp @@ -1,10 +1,12 @@ #include "stdafx.h" #include "port_offlineshop.h" +#include "../../common/offline_shop_safety.h" #include "db.h" #include void PortOfflineShopBoot() { + if(!PortOfflineShopEconomyReady())return; // 1. Create offline_shop_npc table { std::unique_ptr msg(DBManager::instance().DirectQuery( @@ -58,7 +60,8 @@ void PortOfflineShopBoot() "attrvalue5 INT NOT NULL DEFAULT 0," "attrtype6 TINYINT NOT NULL DEFAULT 0," "attrvalue6 INT NOT NULL DEFAULT 0," - "status TINYINT NOT NULL DEFAULT 0," + "port_extra VARBINARY(69) NOT NULL DEFAULT ''," + "status TINYINT NOT NULL DEFAULT 0," "ownername VARCHAR(24) NOT NULL DEFAULT ''," "buyername VARCHAR(24) NOT NULL DEFAULT ''," "INDEX idx_owner (owner_id)" diff --git a/src/server/game/src/port_rank_runtime.h b/src/server/game/src/port_rank_runtime.h new file mode 100644 index 00000000..8ba9a31a --- /dev/null +++ b/src/server/game/src/port_rank_runtime.h @@ -0,0 +1,98 @@ +#ifndef METIN2_PORT_RANK_RUNTIME_H +#define METIN2_PORT_RANK_RUNTIME_H +#include +#include +#include +#include +#include +#include + +// CH5 board order: level, stone, monster, boss, dungeon, playtime, gold, +// Gaya, fish, chest. Only columns with an established authority are exposed. +namespace PortRank { +struct Row { std::string name; unsigned empire; uint64_t value; }; +struct Waiter { unsigned handle, handshake, account, player, request; }; +struct Board { + bool loading=false, valid=false; + uint32_t expires=0; + long long asOf=0; + std::vector rows; + std::vector waiters; +}; +static Board boards[10]; +static const char* Column(unsigned board) { + switch(board) { case 0:return "level";case 5:return "playtime";case 6:return "gold";default:return nullptr; } +} +static bool Number(const char* text,uint64_t maximum,uint64_t& result) { + if(!text || !*text)return false; + result=0; + for(const unsigned char* p=(const unsigned char*)text;*p;++p) { + if(*p<'0'||*p>'9'||uint64_t(*p-'0')>maximum || result>(maximum-(*p-'0'))/10)return false; + result=result*10+(*p-'0'); + } + return true; +} +static std::string NameHex(const std::string& name) { + const char* digits="0123456789abcdef";std::string out; + for(unsigned char c:name){out+=digits[c>>4];out+=digits[c&15];} + return out; +} +static LPCHARACTER Resolve(const Waiter& w) { + auto* d=DESC_MANAGER::instance().FindByHandle(w.handle); + if(!d || d->GetHandshake()!=w.handshake || d->GetAccountTable().id!=w.account)return nullptr; + auto* ch=d->GetCharacter(); + return ch && ch->GetPlayerID()==w.player ? ch : nullptr; +} +static void Reply(const Waiter& w,unsigned index,const char* error=nullptr) { + auto* ch=Resolve(w);if(!ch)return; + if(error){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u %s",w.request,error);return;} + const Board& board=boards[index]; + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u rank %u 0 %u 0 %lld",w.request,index,unsigned(board.rows.size()),board.asOf); + for(unsigned i=0;iChatPacket(CHAT_TYPE_COMMAND,"MTF1 rank %u %u %s %u %llu",w.request,i,NameHex(r.name).c_str(),r.empire,(unsigned long long)r.value); + } + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",w.request,unsigned(board.rows.size())); +} +static void Loaded(unsigned index,long long asOf,SQLMsg* msg) { + Board& board=boards[index];board.loading=false;board.valid=false; + std::vector rows; + bool ok=msg && !msg->uiSQLErrno && msg->Get() && msg->Get()->pSQLResult && msg->Get()->uiNumRows<=10; + if(ok){ + MYSQL_ROW row; + while((row=mysql_fetch_row(msg->Get()->pSQLResult))){ + uint64_t empire=0,value=0; + if(!row[0] || !*row[0] || strlen(row[0])>24 || !Number(row[1],3,empire) || empire<1 || + !Number(row[2],uint64_t(std::numeric_limits::max()),value) || rows.size()>=10){ok=false;break;} + for(const unsigned char* p=(const unsigned char*)row[0];*p;++p)if(*p<32 || *p==127){ok=false;break;} + if(!ok)break; + rows.push_back({row[0],unsigned(empire),value}); + } + if(rows.size()!=msg->Get()->uiNumRows)ok=false; + } + if(ok){board.rows.swap(rows);board.asOf=asOf;board.expires=get_dword_time()+60000;board.valid=true;} + std::vector waiters;waiters.swap(board.waiters); + for(const auto& w:waiters)Reply(w,index,ok?nullptr:"storage"); +} +} + +static void PortRankQuery(LPCHARACTER ch,unsigned request,unsigned index) { + if(index>=10 || !PortRank::Column(index)){ + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u unsupported",request);return; + } + auto* d=ch->GetDesc();if(!d)return; + PortRank::Waiter w={d->GetHandle(),d->GetHandshake(),d->GetAccountTable().id,ch->GetPlayerID(),request}; + auto& board=PortRank::boards[index]; + if(board.valid && int32_t(board.expires-get_dword_time())>0){PortRank::Reply(w,index);return;} + if(board.waiters.size()>=32){PortRank::Reply(w,index,"busy");return;} + board.waiters.push_back(w); + if(board.loading)return; + board.loading=true; + const long long asOf=get_global_time(); + // No user-supplied identifier enters SQL. Read persisted values asynchronously; + // ties use character id, and the empire comes from the account's player index. + DBManager::instance().FuncQuery([index,asOf](SQLMsg* msg){PortRank::Loaded(index,asOf,msg);}, + "SELECT p.name, i.empire, p.%s FROM player%s p JOIN player_index%s i ON i.id=p.account_id " + "WHERE p.%s>0 ORDER BY p.%s DESC, p.id ASC LIMIT 10", + PortRank::Column(index),get_table_postfix(),get_table_postfix(),PortRank::Column(index),PortRank::Column(index)); +} +#endif diff --git a/src/server/game/src/questlua_pc.cpp b/src/server/game/src/questlua_pc.cpp index 36fcf4a4..b53c6963 100755 --- a/src/server/game/src/questlua_pc.cpp +++ b/src/server/game/src/questlua_pc.cpp @@ -1,3 +1,5 @@ +#include +#include "../../common/gold_bounds.h" #include "stdafx.h" @@ -961,21 +963,17 @@ namespace quest } int pc_change_money(lua_State * L) - { - int gold = (int)lua_tonumber(L, -1); - - LPCHARACTER ch = CQuestManager::instance().GetCurrentCharacterPtr(); - - if (gold + ch->GetGold() < 0) - sys_err("QUEST wrong ChangeGold %d (now %d)", gold, ch->GetGold()); - else - { - DBManager::instance().SendMoneyLog(MONEY_LOG_QUEST, ch->GetPlayerID(), gold); - ch->PointChange(POINT_GOLD, gold, true); - } - - return 0; - } + { + const double input=lua_tonumber(L,-1); + if(!lua_isnumber(L,-1) || !std::isfinite(input) || std::floor(input)!=input || input < -double(GOLD_MAX_64) || input > double(GOLD_MAX_64))return 0; + const int64_t gold=static_cast(input); + LPCHARACTER ch=CQuestManager::instance().GetCurrentCharacterPtr(); + if(!ch || !PortGoldCanChange(ch->GetGold(),gold,GOLD_MAX_64))return 0; + const int64_t before=ch->GetGold(); + ch->PointChange(POINT_GOLD,gold,true); + DBManager::instance().SendMoneyLog(MONEY_LOG_QUEST,ch->GetPlayerID(),ch->GetGold()-before); + return 0; + } int pc_set_another_quest_flag(lua_State* L) { diff --git a/src/server/game/src/shop.cpp b/src/server/game/src/shop.cpp index 36ab7c10..8bba8913 100755 --- a/src/server/game/src/shop.cpp +++ b/src/server/game/src/shop.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "../../common/shop_economy.h" #include "../../libgame/include/grid.h" #include "constants.h" #include "utils.h" @@ -23,9 +24,9 @@ // MT: the sockets ITEM_MANAGER::CreateItem gives a new item of this vnum (its remaining time), sent // with an NPC shop's items so the client tooltip shows how long a bought one lasts instead of 0. -void MT_GetNewItemSockets(DWORD dwVnum, long* alSockets) +void MT_GetNewItemSockets(DWORD dwVnum, int32_t* alSockets) { - memset(alSockets, 0, sizeof(long) * ITEM_SOCKET_MAX_NUM); + memset(alSockets, 0, sizeof(int32_t) * ITEM_SOCKET_MAX_NUM); const TItemTable* table = ITEM_MANAGER::instance().GetTable(dwVnum); if (!table) @@ -138,7 +139,7 @@ void CShop::SetShopItems(TShopItemTable * pTable, BYTE bItemCount) m_itemVector.resize(SHOP_HOST_ITEM_MAX_NUM); memset(&m_itemVector[0], 0, sizeof(SHOP_ITEM) * m_itemVector.size()); - for (int i = 0; i < bItemCount; ++i) + for (int i = 0; i < bItemCount; ++i, ++pTable) { LPITEM pkItem = NULL; const TItemTable * item_table; @@ -225,14 +226,13 @@ void CShop::SetShopItems(TShopItemTable * pTable, BYTE bItemCount) item.price = item.count / item_table->dwGold; } else - item.price = item_table->dwGold * item.count; + item.price = int64_t(item_table->dwGold) * item.count; } char name[36]; snprintf(name, sizeof(name), "%-20s(#%-5d) (x %d)", item_table->szName, (int) item.vnum, item.count); - sys_log(0, "SHOP_ITEM: %-36s PRICE %-5d", name, item.price); - ++pTable; + sys_log(0, "SHOP_ITEM: %-36s PRICE %lld", name, (long long)item.price); } } @@ -264,13 +264,13 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) if (IsPCShop()) { - if (!pkSelectedItem) + if (!pkSelectedItem || pkSelectedItem != r_item.pkItem || pkSelectedItem->GetVnum() != r_item.vnum || !pkSelectedItem->GetCount()) { sys_log(0, "Shop::Buy : Critical: This user seems to be a hacker : invalid pcshop item : BuyerPID:%d SellerPID:%d", ch->GetPlayerID(), m_pkPC->GetPlayerID()); - return false; + return SHOP_SUBHEADER_GC_SOLD_OUT; } if ((pkSelectedItem->GetOwner() != m_pkPC)) @@ -279,18 +279,17 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) ch->GetPlayerID(), m_pkPC->GetPlayerID()); - return false; + return SHOP_SUBHEADER_GC_SOLD_OUT; } } - DWORD dwPrice = r_item.price; + int64_t dwPrice = 0; + if (!PortShopQuote(r_item.price, !IsPCShop() && it->second, GOLD_MAX_64, dwPrice)) + return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; - if (it->second) // if other empire, price is triple - dwPrice *= 3; - - if (ch->GetGold() < (int) dwPrice) + if (ch->GetGold() < dwPrice) { - sys_log(1, "Shop::Buy : Not enough money : %s has %d, price %d", ch->GetName(), ch->GetGold(), dwPrice); + sys_log(1, "Shop::Buy : Not enough money : %s has %lld, price %lld", ch->GetName(), (long long)ch->GetGold(), (long long)dwPrice); return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; } @@ -311,6 +310,7 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) //ÃູÀÇ ±¸½½ && ¸¸³âÇÑö À̺¥Æ® if (item->GetVnum() == 70024 || item->GetVnum() == 70035) { + M2_DESTROY_ITEM(item); return SHOP_SUBHEADER_GC_END; } } @@ -341,51 +341,26 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) } } + int iVal = quest::CQuestManager::instance().GetEventFlag( + (LC_IsYMIR() || LC_IsKorea()) ? "trade_tax" : "personal_shop"); + if (iVal <= 0) iVal = (LC_IsYMIR() || LC_IsKorea()) ? 3 : 0; + if (iVal > 100) iVal = 100; + int64_t dwTax = 0, proceeds = 0; + if (!PortShopSettlement(dwPrice, iVal, GOLD_MAX_64, dwTax, proceeds) || + (m_pkPC && (m_pkPC == ch || !PortGoldCanChange(m_pkPC->GetGold(), proceeds, GOLD_MAX_64)))) + { + if (!m_pkPC) M2_DESTROY_ITEM(item); + return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; + } + ch->PointChange(POINT_GOLD, -dwPrice, false); if (!m_pkPC) PortBpCount(ch, PORT_BP_NPC_SPEND, 0, dwPrice); // PORT: battle pass, NPC shops only - //¼¼±Ý °è»ê - DWORD dwTax = 0; - int iVal = 0; - if (LC_IsYMIR() || LC_IsKorea()) - { - if (0 < (iVal = quest::CQuestManager::instance().GetEventFlag("trade_tax"))) - { - if (iVal > 100) - iVal = 100; + const int64_t chargedPrice = dwPrice; + dwPrice = proceeds; - dwTax = dwPrice * iVal / 100; - dwPrice = dwPrice - dwTax; - } - else - { - iVal = 3; - dwTax = dwPrice * iVal / 100; - dwPrice = dwPrice - dwTax; - } - } - else - { - iVal = quest::CQuestManager::instance().GetEventFlag("personal_shop"); - - if (0 < iVal) - { - if (iVal > 100) - iVal = 100; - - dwTax = dwPrice * iVal / 100; - dwPrice = dwPrice - dwTax; - } - else - { - iVal = 0; - dwTax = 0; - } - } - - // »óÁ¡¿¡¼­ »ì‹š ¼¼±Ý 5% if (!m_pkPC) { CMonarch::instance().SendtoDBAddMoney(dwTax, ch->GetEmpire(), ch); @@ -407,7 +382,7 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) if (item->GetVnum() >= 80003 && item->GetVnum() <= 80007) { - snprintf(buf, sizeof(buf), "%s FROM: %u TO: %u PRICE: %u", item->GetName(), ch->GetPlayerID(), m_pkPC->GetPlayerID(), dwPrice); + snprintf(buf, sizeof(buf), "%s FROM: %u TO: %u PRICE: %lld", item->GetName(), ch->GetPlayerID(), m_pkPC->GetPlayerID(), (long long)dwPrice); LogManager::instance().GoldBarLog(ch->GetPlayerID(), item->GetID(), SHOP_BUY, buf); LogManager::instance().GoldBarLog(m_pkPC->GetPlayerID(), item->GetID(), SHOP_SELL, buf); } @@ -420,10 +395,10 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) ITEM_MANAGER::instance().FlushDelayedSave(item); - snprintf(buf, sizeof(buf), "%s %u(%s) %u %u", item->GetName(), m_pkPC->GetPlayerID(), m_pkPC->GetName(), dwPrice, item->GetCount()); + snprintf(buf, sizeof(buf), "%s %u(%s) %lld %u", item->GetName(), m_pkPC->GetPlayerID(), m_pkPC->GetName(), (long long)dwPrice, item->GetCount()); LogManager::instance().ItemLog(ch, item, "SHOP_BUY", buf); - snprintf(buf, sizeof(buf), "%s %u(%s) %u %u", item->GetName(), ch->GetPlayerID(), ch->GetName(), dwPrice, item->GetCount()); + snprintf(buf, sizeof(buf), "%s %u(%s) %lld %u", item->GetName(), ch->GetPlayerID(), ch->GetName(), (long long)dwPrice, item->GetCount()); LogManager::instance().ItemLog(m_pkPC, item, "SHOP_SELL", buf); } @@ -451,11 +426,11 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos) LogManager::instance().GoldBarLog(ch->GetPlayerID(), item->GetID(), PERSONAL_SHOP_BUY, ""); } - DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), -dwPrice); + DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), -chargedPrice); } if (item) - sys_log(0, "SHOP: BUY: name %s %s(x %d):%u price %u", ch->GetName(), item->GetName(), item->GetCount(), item->GetID(), dwPrice); + sys_log(0, "SHOP: BUY: name %s %s(x %d):%u price %lld", ch->GetName(), item->GetName(), item->GetCount(), item->GetID(), (long long)dwPrice); ch->Save(); @@ -520,10 +495,11 @@ bool CShop::AddGuest(LPCHARACTER ch, DWORD owner_vid, bool bOtherEmpire) pack2.items[i].vnum = item.vnum; - if (bOtherEmpire) // no empire price penalty for pc shop - pack2.items[i].price = item.price * 3; - else - pack2.items[i].price = item.price; + if (!PortShopQuote(item.price, !IsPCShop() && bOtherEmpire, GOLD_MAX_64, pack2.items[i].price)) + { + memset(&pack2.items[i], 0, sizeof(pack2.items[i])); + continue; + } pack2.items[i].count = item.count; diff --git a/src/server/game/src/shop.h b/src/server/game/src/shop.h index 3568949b..08ed94e2 100755 --- a/src/server/game/src/shop.h +++ b/src/server/game/src/shop.h @@ -15,7 +15,7 @@ class CShop typedef struct shop_item { DWORD vnum; // ¾ÆÀÌÅÛ ¹øÈ£ - long price; // °¡°Ý + int64_t price; // °¡°Ý BYTE count; // ¾ÆÀÌÅÛ °³¼ö LPITEM pkItem; diff --git a/src/server/game/src/shopEx.cpp b/src/server/game/src/shopEx.cpp index 983d6134..349b8bb9 100755 --- a/src/server/game/src/shopEx.cpp +++ b/src/server/game/src/shopEx.cpp @@ -1,4 +1,6 @@ #include "stdafx.h" +#include "../../common/shop_economy.h" +#include #include "../../libgame/include/grid.h" #include "constants.h" #include "utils.h" @@ -19,7 +21,7 @@ #include "mob_manager.h" #include "locale_service.h" -void MT_GetNewItemSockets(DWORD dwVnum, long* alSockets); +void MT_GetNewItemSockets(DWORD dwVnum, int32_t* alSockets); #include "desc_client.h" #include "shopEx.h" #include "group_text_parse_tree.h" @@ -77,9 +79,9 @@ bool CShopEx::AddGuest(LPCHARACTER ch,DWORD owner_vid, bool bOtherEmpire) for (itertype(m_vec_shopTabs) it = m_vec_shopTabs.begin(); it != m_vec_shopTabs.end(); it++) { const TShopTableEx& shop_tab = *it; - TPacketGCShopStartEx::TSubPacketShopTab pack_tab; + TPacketGCShopStartEx::TSubPacketShopTab pack_tab = {}; pack_tab.coin_type = shop_tab.coinType; - memcpy(pack_tab.name, shop_tab.name.c_str(), SHOP_TAB_NAME_MAX); + strlcpy(pack_tab.name, shop_tab.name.c_str(), sizeof(pack_tab.name)); for (BYTE i = 0; i < SHOP_HOST_ITEM_MAX_NUM; i++) { @@ -88,10 +90,8 @@ bool CShopEx::AddGuest(LPCHARACTER ch,DWORD owner_vid, bool bOtherEmpire) switch(shop_tab.coinType) { case SHOP_COIN_TYPE_GOLD: - if (bOtherEmpire) // no empire price penalty for pc shop - pack_tab.items[i].price = shop_tab.items[i].price * 3; - else - pack_tab.items[i].price = shop_tab.items[i].price; + if (!PortShopQuote(shop_tab.items[i].price, bOtherEmpire, GOLD_MAX_64, pack_tab.items[i].price)) + memset(&pack_tab.items[i], 0, sizeof(pack_tab.items[i])); break; case SHOP_COIN_TYPE_SECONDARY_COIN: pack_tab.items[i].price = shop_tab.items[i].price; @@ -142,30 +142,32 @@ int CShopEx::Buy(LPCHARACTER ch, BYTE pos) return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; } - DWORD dwPrice = r_item.price; + int64_t dwPrice = r_item.price; switch (shopTab.coinType) { case SHOP_COIN_TYPE_GOLD: - if (it->second) // if other empire, price is triple - dwPrice *= 3; + if (!PortShopQuote(r_item.price, it->second, GOLD_MAX_64, dwPrice)) + return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; - if (ch->GetGold() < (int) dwPrice) + if (ch->GetGold() < dwPrice) { - sys_log(1, "ShopEx::Buy : Not enough money : %s has %d, price %d", ch->GetName(), ch->GetGold(), dwPrice); + sys_log(1, "ShopEx::Buy : Not enough money : %s has %lld, price %lld", ch->GetName(), (long long)ch->GetGold(), (long long)dwPrice); return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY; } break; case SHOP_COIN_TYPE_SECONDARY_COIN: { int count = ch->CountSpecifyTypeItem(ITEM_SECONDARY_COIN); - if (count < dwPrice) + if (dwPrice > INT_MAX || count < dwPrice) { - sys_log(1, "ShopEx::Buy : Not enough myeongdojun : %s has %d, price %d", ch->GetName(), count, dwPrice); + sys_log(1, "ShopEx::Buy : Not enough myeongdojun : %s has %d, price %lld", ch->GetName(), count, (long long)dwPrice); return SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX; } } break; + default: + return SHOP_SUBHEADER_GC_END; } LPITEM item; @@ -198,7 +200,7 @@ int CShopEx::Buy(LPCHARACTER ch, BYTE pos) ch->PointChange(POINT_GOLD, -dwPrice, false); break; case SHOP_COIN_TYPE_SECONDARY_COIN: - ch->RemoveSpecifyTypeItem(ITEM_SECONDARY_COIN, dwPrice); + ch->RemoveSpecifyTypeItem(ITEM_SECONDARY_COIN, static_cast(dwPrice)); break; } @@ -216,10 +218,11 @@ int CShopEx::Buy(LPCHARACTER ch, BYTE pos) LogManager::instance().GoldBarLog(ch->GetPlayerID(), item->GetID(), PERSONAL_SHOP_BUY, ""); } - DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), -dwPrice); + if (shopTab.coinType == SHOP_COIN_TYPE_GOLD) + DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), -dwPrice); if (item) - sys_log(0, "ShopEx: BUY: name %s %s(x %d):%u price %u", ch->GetName(), item->GetName(), item->GetCount(), item->GetID(), dwPrice); + sys_log(0, "ShopEx: BUY: name %s %s(x %d):%u price %lld", ch->GetName(), item->GetName(), item->GetCount(), item->GetID(), (long long)dwPrice); if (LC_IsBrazil()) { diff --git a/src/server/game/src/shop_manager.cpp b/src/server/game/src/shop_manager.cpp index 75637099..4a2346b2 100755 --- a/src/server/game/src/shop_manager.cpp +++ b/src/server/game/src/shop_manager.cpp @@ -1,4 +1,6 @@ #include "stdafx.h" +#include "../../common/shop_economy.h" +#include #include "ava2_ticket_shop.h" #include "../../libgame/include/grid.h" #include "constants.h" @@ -298,7 +300,7 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) if (IS_SET(item->GetAntiFlag(), ITEM_ANTIFLAG_SELL)) return; - DWORD dwPrice; + int64_t dwPrice; if (bCount == 0 || bCount > item->GetCount()) bCount = item->GetCount(); @@ -318,7 +320,7 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) dwPrice /= 5; //¼¼±Ý °è»ê - DWORD dwTax = 0; + int64_t dwTax = 0; int iVal = 3; if (LC_IsYMIR() || LC_IsKorea()) @@ -335,17 +337,15 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) if (test_server) sys_log(0, "Sell Item price id %d %s itemid %d", ch->GetPlayerID(), ch->GetName(), item->GetID()); - const int64_t nTotalMoney = static_cast(ch->GetGold()) + static_cast(dwPrice); - - if (GOLD_MAX_64 <= nTotalMoney) + if (!PortGoldCanChange(ch->GetGold(), dwPrice, GOLD_MAX_64)) { - sys_err("[OVERFLOW_GOLD] id %u name %s gold %u", ch->GetPlayerID(), ch->GetName(), ch->GetGold()); + sys_err("[OVERFLOW_GOLD] id %u name %s gold %lld", ch->GetPlayerID(), ch->GetName(), (long long)ch->GetGold()); ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("20¾ï³ÉÀÌ ÃʰúÇÏ¿© ¹°Ç°À» ÆÈ¼ö ¾ø½À´Ï´Ù.")); return; } // 20050802.myevan.»óÁ¡ ÆÇ¸Å ·Î±×¿¡ ¾ÆÀÌÅÛ ID Ãß°¡ - sys_log(0, "SHOP: SELL: %s item name: %s(x%d):%u price: %u", ch->GetName(), item->GetName(), bCount, item->GetID(), dwPrice); + sys_log(0, "SHOP: SELL: %s item name: %s(x%d):%u price: %lld", ch->GetName(), item->GetName(), bCount, item->GetID(), (long long)dwPrice); if (iVal > 0) ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("ÆÇ¸Å±Ý¾×ÀÇ %d %% °¡ ¼¼±ÝÀ¸·Î ³ª°¡°ÔµË´Ï´Ù"), iVal); @@ -449,7 +449,8 @@ bool ConvertToShopItemTable(IN CGroupNode* pNode, OUT TShopTableEx& shopTable) sys_err("row(%d) of group items of group %s does not have count column", i, pNode->GetNodeName().c_str()); return false; } - if (!pItemGroup->GetValue(i, "price", shopItems[i].price)) + if (!pItemGroup->GetValue(i, "price", shopItems[i].price) || shopItems[i].price < 0 || shopItems[i].price > GOLD_MAX_64 || + (shopTable.coinType == SHOP_COIN_TYPE_SECONDARY_COIN && shopItems[i].price > INT_MAX)) { sys_err("row(%d) of group items of group %s does not have price column", i, pNode->GetNodeName().c_str()); return false; diff --git a/src/server/game/src/utils.cpp b/src/server/game/src/utils.cpp index 169402a4..5923530f 100755 --- a/src/server/game/src/utils.cpp +++ b/src/server/game/src/utils.cpp @@ -1,5 +1,44 @@ #include "stdafx.h" +// AVA2 search files use tab token compression and preserve embedded spaces. +#ifdef ENABLE_SHOP_SEARCH_SYSTEM +void split_argument_special(const char* argument, std::vector& vecArgs, const char* delimiters) +{ + // Match boost::split(..., token_compress_on), including empty edge fields, + // without introducing the archived Boost headers into the C++23 utility unit. + const std::string text = argument ? argument : ""; + const std::string separators = delimiters ? delimiters : ""; + vecArgs.clear(); + size_t begin = 0; + while (begin < text.size()) + { + const size_t end = text.find_first_of(separators, begin); + if (end == std::string::npos) break; + vecArgs.push_back(text.substr(begin, end - begin)); + begin = text.find_first_not_of(separators, end); + if (begin == std::string::npos) { begin = text.size(); break; } + } + vecArgs.push_back(text.substr(begin)); +} +#endif + +#ifdef ENABLE_OFFLINESHOP_SYSTEM +// Reject SQL string delimiters and control bytes in legacy shop labels. +// This is input validation, not a substitute for parameterized SQL. +bool getInjectText(const char* text) +{ + if (!text) return true; + for (size_t i = 0; i < 256; ++i) + { + const unsigned char c = static_cast(text[i]); + if (c == 0) return false; + if (c < 32 || c == 127 || c == 39 || c == 34 || c == 92 || c == 59) + return true; + } + return true; +} +#endif + static int global_time_gap = 0; time_t get_global_time() diff --git a/src/server/game/src/utils.h b/src/server/game/src/utils.h index 707107ff..b5e54a80 100755 --- a/src/server/game/src/utils.h +++ b/src/server/game/src/utils.h @@ -3,6 +3,16 @@ #define __INC_METIN_II_UTILS_H__ #include +#include +#include + +#ifdef ENABLE_OFFLINESHOP_SYSTEM +bool getInjectText(const char* text); +#endif + +#ifdef ENABLE_SHOP_SEARCH_SYSTEM +void split_argument_special(const char* argument, std::vector& vecArgs, const char* delimiters); +#endif #define IS_SET(flag, bit) ((flag) & (bit)) #define SET_BIT(var, bit) ((var) |= (bit)) @@ -43,7 +53,7 @@ inline int DISTANCE_APPROX(int dx, int dy) #ifndef __WIN32__ inline WORD MAKEWORD(BYTE a, BYTE b) { - return static_cast(a) | (static_cast(b) << 8); + return static_cast(static_cast(a) | (static_cast(b) << 8)); } #endif diff --git a/src/server/libsql/AsyncSQL.cpp b/src/server/libsql/AsyncSQL.cpp index 4fa7706a..358b4341 100755 --- a/src/server/libsql/AsyncSQL.cpp +++ b/src/server/libsql/AsyncSQL.cpp @@ -271,6 +271,7 @@ SQLMsg * CAsyncSQL::DirectQuery(const char * c_pszQuery) sys_err(buf); p->uiSQLErrno = mysql_errno(&m_hDB); + ++m_failureEpoch; } p->Store(); @@ -562,6 +563,7 @@ void CAsyncSQL::ChildLoop() if (mysql_real_query(&m_hDB, p->stQuery.c_str(), p->stQuery.length())) { p->uiSQLErrno = mysql_errno(&m_hDB); + ++m_failureEpoch; sys_err("AsyncSQL: query failed: %s (query: %s errno: %d)", mysql_error(&m_hDB), p->stQuery.c_str(), p->uiSQLErrno); @@ -624,6 +626,7 @@ void CAsyncSQL::ChildLoop() if (mysql_real_query(&m_hDB, p->stQuery.c_str(), p->stQuery.length())) { p->uiSQLErrno = mysql_errno(&m_hDB); + ++m_failureEpoch; sys_err("AsyncSQL::ChildLoop : mysql_query error: %s:\nquery: %s", mysql_error(&m_hDB), p->stQuery.c_str()); diff --git a/src/server/libsql/AsyncSQL.h b/src/server/libsql/AsyncSQL.h index 733b467a..36ccbe3e 100755 --- a/src/server/libsql/AsyncSQL.h +++ b/src/server/libsql/AsyncSQL.h @@ -4,6 +4,7 @@ #include "../libthecore/include/stdafx.h" #include "../libthecore/include/log.h" +#include #include #include #include @@ -32,10 +33,20 @@ typedef struct _SQLResult } } + // mysql_affected_rows uses all 64 bits for its error sentinel. + static constexpr uint64_t AFFECTED_ROWS_ERROR = UINT64_MAX; + bool GetInsertID32(uint32_t& destination) const + { + if (!uiInsertID || uiInsertID > UINT32_MAX) return false; + destination = static_cast(uiInsertID); + return true; + } + bool HasAffectedRows() const { return uiAffectedRows != 0 && uiAffectedRows != AFFECTED_ROWS_ERROR; } + MYSQL_RES * pSQLResult; - uint32_t uiNumRows; - uint32_t uiAffectedRows; - uint32_t uiInsertID; + uint64_t uiNumRows; + uint64_t uiAffectedRows; + uint64_t uiInsertID; } SQLResult; typedef struct _SQLMsg @@ -135,6 +146,7 @@ class CAsyncSQL bool PopResult(SQLMsg ** pp); void ChildLoop(); + uint64_t FailureEpoch()const { return m_failureEpoch.load(); } MYSQL * GetSQLHandle(); @@ -162,6 +174,7 @@ class CAsyncSQL //private: protected: + std::atomic m_failureEpoch{0}; MYSQL m_hDB; std::string m_stHost; diff --git a/tests/features/fixtures/economy_probe.cpp b/tests/features/fixtures/economy_probe.cpp new file mode 100644 index 00000000..08d6b326 --- /dev/null +++ b/tests/features/fixtures/economy_probe.cpp @@ -0,0 +1,255 @@ +#include "src/server/common/economy_store.h" +#include +#include +#include +#include +#include +#include +#ifdef PORT_ECONOMY_MYSQL +#include "src/server/common/economy_mysql.h" +#else +#include +#endif +using namespace PortEconomy; +static std::string address; +struct TestDB { +#ifdef PORT_ECONOMY_MYSQL + MYSQL handle;Mysql* db; + TestDB(){mysql_init(&handle);assert(mysql_real_connect(&handle,"localhost","root","","economy_test",0,address.c_str(),0));db=new Mysql(&handle);} + ~TestDB(){delete db;mysql_close(&handle);} + bool Query(const std::string& sql,Rows& rows){bool ok=db->Query(sql,rows);affected=db->affected;inserted=db->inserted;if(ok&&after)after(sql);return ok;} + bool Begin(){return db->Begin();}bool Commit(){bool ok=db->Commit();if(ok&&after)after("COMMIT");return ok;}void Rollback(){db->Rollback();} +#else + sqlite3* db=nullptr; + TestDB(){assert(sqlite3_open(address.c_str(),&db)==SQLITE_OK);sqlite3_busy_timeout(db,5000);} + ~TestDB(){sqlite3_close(db);} + static void replace(std::string& s,const std::string& from,const std::string& to){size_t pos;while((pos=s.find(from))!=std::string::npos)s.replace(pos,from.size(),to);} + bool Query(std::string sql,Rows& rows){ + rows.clear();affected=0;inserted=0; + if(sql.find("information_schema.tables")!=std::string::npos){rows={{"13"}};return true;} + if(sql=="SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")return true; + if(sql.find("SHOW COLUMNS")!=std::string::npos){rows={{"fixture-schema"}};return true;} + replace(sql," FOR UPDATE","");replace(sql,"UNIX_TIMESTAMP()","strftime('%s','now')"); + replace(sql,"ON DUPLICATE KEY UPDATE account=VALUES(account)","ON CONFLICT(account) DO NOTHING"); + replace(sql,"ON DUPLICATE KEY UPDATE pid=VALUES(pid)","ON CONFLICT(pid) DO NOTHING"); + replace(sql,"ON DUPLICATE KEY UPDATE lValue=VALUES(lValue)","ON CONFLICT(dwPID,szName,szState) DO UPDATE SET lValue=excluded.lValue"); + replace(sql,"ON DUPLICATE KEY UPDATE generation=VALUES(generation),deadline=VALUES(deadline),offers=VALUES(offers)","ON CONFLICT(pid) DO UPDATE SET generation=excluded.generation,deadline=excluded.deadline,offers=excluded.offers"); + sqlite3_stmt* statement=nullptr; + if(sqlite3_prepare_v2(db,sql.c_str(),-1,&statement,nullptr)!=SQLITE_OK){std::cerr< row;for(int i=0;i(sqlite3_column_blob(statement,i));row.emplace_back(p?std::string(p,sqlite3_column_bytes(statement,i)):std::string());}rows.push_back(row);} + sqlite3_finalize(statement);if(rc!=SQLITE_DONE)return false; + affected=static_cast(sqlite3_changes(db));inserted=static_cast(sqlite3_last_insert_rowid(db));if(after)after(sql);return true; + } + bool Begin(){Rows rows;return Query("BEGIN IMMEDIATE",rows);}bool Commit(){Rows rows;return Query("COMMIT",rows);}void Rollback(){Rows rows;Query("ROLLBACK",rows);} +#endif + uint64_t affected=0,inserted=0;std::function after; +}; +static unsigned itemSize(uint32_t vnum){return vnum==999?0u:vnum==333?3u:1u;} +static void sql(TestDB& db,const std::string& q){Rows rows;if(!db.Query(q,rows)){std::cerr<<"FAILED "<(operation);r.player=pid;r.account=account;r.expectedGold=gold; + char text[33];snprintf(text,sizeof(text),"%032llx",static_cast(token++));memcpy(r.token,text,33);return r; +} +static void reset(TestDB& db){ + for(const char* t:{"port_economy_pending","port_economy_requests","port_economy_listings","port_economy_orders","port_economy_credit","port_economy_gaya","port_economy_account_lock","port_economy_item_reservations","port_economy_custody","item","quest","player"})sql(db,std::string("DELETE FROM ")+t); + sql(db,"INSERT INTO player(id,account_id,gold) VALUES(1,1,100),(2,2,1000),(3,3,1000)"); + sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum,socket0,attrtype0,attrvalue0,port_extra) VALUES(10,1,'INVENTORY',0,5,100,123456,99,17,X'010203')"); +} +static uint64_t settle(TestDB& db,Request r,const char* expected="ok"){ + Store store(db,itemSize);if(!store.Enqueue(r)){std::cerr<<"enqueue operation "<::Settled); + if(store.Outcome()!=expected){std::cerr<<"EXPECTED "<::None); + assert(store.Enqueue(r));assert(store.Settle(r.player,r.account)==Store::None);return store.Reference(); +} +static uint64_t listing(TestDB& db){auto r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;return settle(db,r);} +static uint64_t buy(TestDB& db,uint64_t listing){auto r=req(Buy);r.reference=listing;r.price=750;return settle(db,r);} +static Request gaya(TestDB& db){ + sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(2,'gem','points',500),(2,'gem','open_slot',18)"); + Request r=req(GayaBuy);r.expectedGem=500;r.expectedOpen=18;r.deadline=100;r.slot=0;r.rewardCount=10; + for(auto& o:r.offers)o={200,2000,50,0}; + for(unsigned i=0;i<10;++i)r.rewards[i]={1000+i,200,200}; + return r; +} +static void basic(TestDB& db){ + reset(db);Store store(db,itemSize);assert(store.Ready()); + Request invalid=req(List);invalid.item=1;assert(!store.Enqueue(invalid)); +#ifdef PORT_ECONOMY_MYSQL + sql(db,"ALTER TABLE item ENGINE=MyISAM");assert(!store.Ready());assert(!store.Enqueue(req(Withdraw,1,1,100)));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);sql(db,"ALTER TABLE item ENGINE=InnoDB");assert(store.Ready()); + sql(db,"ALTER TABLE port_economy_custody ADD COLUMN unexpected INT DEFAULT 0");assert(!store.Ready());sql(db,"ALTER TABLE port_economy_custody DROP COLUMN unexpected");assert(store.Ready()); + sql(db,"UPDATE port_economy_version SET version=2 WHERE id=1");assert(!store.Ready());sql(db,"UPDATE port_economy_version SET version=1 WHERE id=1");assert(store.Ready()); + puts("PASS readiness refuses MyISAM, partial custody migration and incompatible schema version"); +#endif + Request immutable=req(List,1,1,100);immutable.item=10;immutable.itemVnum=100;immutable.itemCount=5;immutable.price=750; + assert(store.Enqueue(immutable));auto conflict=immutable;conflict.price=751;assert(!store.Enqueue(conflict));conflict=req(Withdraw,1,1,100);assert(!store.Enqueue(conflict));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1);assert(store.Settle(1,1)==Store::Settled);reset(db); + uint64_t l=listing(db);assert(l);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1); + uint64_t o=buy(db,l);assert(o);assert(integer(db,"SELECT gold FROM player WHERE id=2")==250); + auto collision=req(Buy,3,3);collision.reference=l;collision.price=750;settle(db,collision,"listing_changed");assert(integer(db,"SELECT gold FROM player WHERE id=3")==1000); + auto refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund);assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000); + refund=req(Refund);refund.reference=o;settle(db,refund);assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000); + o=buy(db,l);auto claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim); + assert(value(db,"SELECT window FROM item WHERE id=10")=="MALL");assert(integer(db,"SELECT owner_id FROM item WHERE id=10")==2);assert(integer(db,"SELECT socket0 FROM item WHERE id=10")==123456);assert(integer(db,"SELECT attrvalue0 FROM item WHERE id=10")==17);assert(value(db,"SELECT hex(port_extra) FROM item WHERE id=10")=="010203"); + assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750); + claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim);assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750); + refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund,"order_terminal"); + auto withdraw=req(Withdraw,1,1,100);settle(db,withdraw);assert(integer(db,"SELECT gold FROM player WHERE id=1")==850);settle(db,req(Withdraw,1,1,850),"no_credit"); + reset(db);l=listing(db);auto cancel=req(Cancel,1,1,100);cancel.reference=l;settle(db,cancel);assert(value(db,"SELECT window FROM item WHERE id=10")=="MALL"); + // Wallet snapshot mismatch never mutates a listing or debits persisted funds. + reset(db);l=listing(db);auto stale=req(Buy,2,2,5000);stale.reference=l;stale.price=750;settle(db,stale,"wallet_changed");assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000); + // Full mall after payment leaves a READY order refundable and its item in custody. + reset(db);l=listing(db);o=buy(db,l); + for(unsigned i=0;i<135;++i)sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES("+std::to_string(2000+i)+",2,'MALL',"+std::to_string(i)+",1,200)"); + claim=req(Claim,2,2,250);claim.reference=o;settle(db,claim,"mall_full");assert(value(db,"SELECT state FROM port_economy_orders WHERE id="+std::to_string(o))=="READY");refund=req(Refund,2,2,250);refund.reference=o;settle(db,refund); + // Gaya wallet, offer and ten stable item IDs commit together. + reset(db);auto r=gaya(db);settle(db,r);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==1); + auto duplicate=r;memcpy(duplicate.token,req(GayaBuy).token,33);duplicate.expectedGem=450;assert(!store.Enqueue(duplicate));assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000); + // Paid refresh consumes exactly one item in the same commit as the new catalogue. + sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39063),(51,2,'INVENTORY',6,1,39064)"); + Request refresh=req(GayaRefresh);refresh.expectedGem=450;refresh.expectedOpen=18;refresh.generation=1;refresh.deadline=100;refresh.nextDeadline=200;refresh.item=50;refresh.itemCount=2; + memcpy(refresh.offers,r.offers,sizeof(r.offers));refresh.offers[0].bought=1;memcpy(refresh.nextOffers,r.offers,sizeof(r.offers));settle(db,refresh);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);assert(integer(db,"SELECT deadline FROM port_economy_gaya WHERE pid=2")==200); + sql(db,"UPDATE quest SET lValue=17 WHERE dwPID=2 AND szState='open_slot'");Request expand=req(GayaExpand);expand.expectedGem=450;expand.expectedOpen=17;expand.item=51;expand.itemCount=1;settle(db,expand);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=51")==0);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18); + // A multi-stack delivery that runs out of space rolls back earlier stacks too. + reset(db);r=gaya(db);for(unsigned i=0;i<130;++i)sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES("+std::to_string(2000+i)+",2,'MALL',"+std::to_string(i)+",1,200)");settle(db,r,"mall_full");assert(integer(db,"SELECT COUNT(*) FROM item WHERE id>=1000 AND id<1010")==0);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500);assert(integer(db,"SELECT COUNT(*) FROM port_economy_gaya")==0); + // SQL failure after five tentative inserts rolls back all of them; the same + // durable request remains pending and succeeds once the fault is removed. + reset(db);r=gaya(db);assert(store.Enqueue(r));sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(1005,3,'INVENTORY',1,1,200)"); + assert(store.Settle(2,2)==Store::Retry);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id>=1000 AND id<1010")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1); + sql(db,"DELETE FROM item WHERE id=1005");assert(store.Settle(2,2)==Store::Settled);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000); + // A reservation participates in the restart high-water mark even before a + // reward row exists, and survives an aborted economic request. + reset(db);r=gaya(db);assert(store.Enqueue(r));assert(integer(db,"SELECT MAX(id) FROM (SELECT id FROM item UNION ALL SELECT id FROM port_economy_custody UNION ALL SELECT id FROM port_economy_item_reservations) AS allocated_ids")==1009); + assert(store.Abort(2,2));assert(integer(db,"SELECT MAX(id) FROM port_economy_item_reservations")==1009); + // Abort after a failed save preserves every economic store. + reset(db);l=listing(db);r=req(Buy);r.reference=l;r.price=750;assert(store.Enqueue(r));assert(store.Abort(2,2));assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(value(db,"SELECT result FROM port_economy_requests WHERE token='"+std::string(r.token)+"'")=="save_failed"); +#ifdef PORT_ECONOMY_MYSQL + // Kill the pinned connection after the first reward statement. It must never + // auto-reconnect and continue the remaining statements in autocommit mode. + reset(db);r=gaya(db);assert(store.Enqueue(r));bool killed=false;TestDB killer; + db.after=[&](const std::string& sql){if(!killed&&sql.find("INSERT INTO item(")==0){killed=true;assert(mysql_kill(&killer.handle,mysql_thread_id(&db.handle))==0);}}; + assert(store.Settle(2,2)==Store::Retry);db.after={};assert(killed); + delete db.db;db.db=new Mysql(&db.handle); // new coordinator attempt, same direct handle + assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==500); + assert(integer(db,"SELECT COUNT(*) FROM item WHERE owner_id=2 AND window='MALL'")==0); + assert(store.Settle(2,2)==Store::Settled);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000); + puts("PASS pinned connection loss: rollback; reconnect before next transaction; one debit/delivery"); +#endif + // Explicit retirement keeps paid offers/slots, refuses residual assets and + // positive balance, and prevents every later Gaya mutation including expand. + reset(db);r=gaya(db);settle(db,r); + auto retire=req(GayaRetire);retire.expectedGem=450;retire.expectedOpen=18; + settle(db,retire,"gaya_balance_remaining"); + sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=2 AND szState='points'"); + sql(db,"INSERT INTO port_economy_credit(pid,amount) VALUES(2,1)"); + retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire,"assets_remaining"); + sql(db,"DELETE FROM port_economy_credit WHERE pid=2"); + auto snapshot=value(db,"SELECT hex(offers) FROM port_economy_gaya WHERE pid=2"); + retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire); + assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==RetiredGeneration); + assert(value(db,"SELECT hex(offers) FROM port_economy_gaya WHERE pid=2")==snapshot); + assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18); + retire=req(GayaRetire);retire.expectedOpen=18;settle(db,retire); + sql(db,"UPDATE quest SET lValue=17 WHERE dwPID=2 AND szState='open_slot'"); + sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39064)"); + auto blocked=req(GayaExpand);blocked.expectedOpen=17;blocked.item=50;blocked.itemCount=2; + settle(db,blocked,"gaya_retired");assert(integer(db,"SELECT count FROM item WHERE id=50")==2); + puts("PASS Gaya retirement: zero balance/assets, retained catalogue/paid slots, idempotent, no reactivation"); + puts("PASS economy orders/refunds/claim/cancel/withdraw/Gaya/rollback/idempotency"); +} +static Request prepareCrash(TestDB& db,unsigned mode) { + reset(db); + if(mode==0){auto r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750;return r;} + if(mode==1){auto l=listing(db);auto r=req(Buy);r.reference=l;r.price=750;return r;} + if(mode==2||mode==3){auto l=listing(db);auto o=buy(db,l);auto r=req(mode==2?Refund:Claim,2,2,250);r.reference=o;return r;} + if(mode==4){auto r=req(Cancel,1,1,100);r.reference=listing(db);return r;} + if(mode==5){auto l=listing(db);auto o=buy(db,l);auto c=req(Claim,2,2,250);c.reference=o;settle(db,c);return req(Withdraw,1,1,100);} + if(mode==6)return gaya(db); + if(mode==7){ + auto original=gaya(db);settle(db,original); + sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39063)"); + auto r=req(GayaRefresh);r.expectedGem=450;r.expectedOpen=18;r.generation=1;r.deadline=100;r.nextDeadline=200;r.item=50;r.itemCount=2; + memcpy(r.offers,original.offers,sizeof(r.offers));r.offers[0].bought=1;memcpy(r.nextOffers,original.offers,sizeof(r.offers));return r; + } + if(mode==9){auto original=gaya(db);settle(db,original);sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=2 AND szState='points'");auto r=req(GayaRetire);r.expectedOpen=18;return r;} + assert(mode==8);sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(2,'gem','points',500),(2,'gem','open_slot',17)");sql(db,"INSERT INTO item(id,owner_id,window,pos,count,vnum) VALUES(50,2,'INVENTORY',5,2,39064)");auto r=req(GayaExpand);r.expectedGem=500;r.expectedOpen=17;r.item=50;r.itemCount=2;return r; +} +static void checkCrash(TestDB& db,unsigned mode) { + assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0); + if(mode==0){assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(integer(db,"SELECT COUNT(*) FROM port_economy_listings WHERE state='OPEN'")==1);} + if(mode==1){assert(integer(db,"SELECT gold FROM player WHERE id=2")==250);assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='READY'")==1);assert(integer(db,"SELECT SUM(price) FROM port_economy_orders WHERE state='READY'")==750);} + if(mode==2){assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(integer(db,"SELECT COUNT(*) FROM port_economy_orders WHERE state='REFUNDED'")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);} + if(mode==3){assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);assert(integer(db,"SELECT gold FROM player WHERE id=2")==250);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=2 AND window='MALL'")==1);} + if(mode==4)assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=1 AND window='MALL'")==1); + if(mode==5){assert(integer(db,"SELECT gold FROM player WHERE id=1")==850);assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==0);} + if(mode==6||mode==7){assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")== (mode==6?1:2));} + if(mode==7){assert(integer(db,"SELECT deadline FROM port_economy_gaya WHERE pid=2")==200);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);} + if(mode==9){assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==RetiredGeneration);assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==0);assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000);} + if(mode==8){assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='open_slot'")==18);assert(integer(db,"SELECT count FROM item WHERE id=50")==1);} +} +static void crashes(TestDB& db){ + const char* names[]={"list","buy","refund","claim","cancel","withdraw","Gaya buy","Gaya refresh","Gaya expand","Gaya retire"}; + unsigned total=0;Store store(db,itemSize); + for(unsigned mode=0;mode<10;++mode) { + auto r=prepareCrash(db,mode);assert(store.Enqueue(r));unsigned boundaries=0;db.after=[&](const std::string&){++boundaries;};assert(store.Settle(r.player,r.account)==Store::Settled);db.after={};checkCrash(db,mode); + for(unsigned boundary=1;boundary<=boundaries;++boundary){ + r=prepareCrash(db,mode);assert(store.Enqueue(r)); + pid_t child=fork();assert(child>=0); + if(!child){TestDB worker;Store s(worker,itemSize);unsigned count=0;worker.after=[&](const std::string&){if(++count==boundary)_exit(70);};s.Settle(r.player,r.account);_exit(71);} + int status=0;const auto waited=waitpid(child,&status,0); + if(waited!=child||!WIFEXITED(status)||WEXITSTATUS(status)!=70){std::cerr<<"crash probe mode="<::Settled||result==Store::None);checkCrash(db,mode); + } + total+=boundaries;printf("PASS %s process exit/replay at %u SQL boundaries\n",names[mode],boundaries); + } + printf("PASS economy whole-process exit/replay: %u SQL boundaries across ten operations (including COMMIT)\n",total); +} +static void races(TestDB& db){ + reset(db);uint64_t l=listing(db);Request a=req(Buy,2,2),b=req(Buy,3,3);a.reference=b.reference=l;a.price=b.price=750; + pid_t children[2];unsigned i=0;for(const auto& r:{a,b}){children[i]=fork();assert(children[i]>=0);if(!children[i++]){TestDB worker;Store s(worker,itemSize);bool queued=false;for(unsigned retry=0;retry<20&&!queued;++retry){queued=s.Enqueue(r);if(!queued)usleep(10000);}if(!queued)_exit(80);for(unsigned retry=0;retry<20;++retry){auto result=s.Settle(r.player,r.account);if(result!=Store::Retry)_exit(0);usleep(10000);}_exit(81);}} + for(auto child:children){int status;assert(waitpid(child,&status,0)==child);if(!WIFEXITED(status)||WEXITSTATUS(status)!=0)std::cerr<<"race child status="< store(db,itemSize);assert(store.Enqueue(delivery)); + for(unsigned i=0;i<2;++i){children[i]=fork();assert(children[i]>=0);if(!children[i]){TestDB worker;Store s(worker,itemSize);for(unsigned retry=0;retry<20;++retry){if(s.Settle(2,2)!=Store::Retry)_exit(0);usleep(10000);}_exit(82);}} + for(auto child:children){int status;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&WEXITSTATUS(status)==0);} + assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0); + if(refund){assert(integer(db,"SELECT gold FROM player WHERE id=2")==1000);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody WHERE id=10")==1);} + else {assert(integer(db,"SELECT amount FROM port_economy_credit WHERE pid=1")==750);assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10 AND owner_id=2 AND window='MALL'")==1);} + } + puts("PASS concurrent settlement of the same claim/refund: one delivery or one refund"); +} +int main(int argc,char** argv){assert(argc==2||argc==3);address=argv[1];TestDB db; +#ifndef PORT_ECONOMY_MYSQL + std::string item="id INTEGER PRIMARY KEY,owner_id INTEGER NOT NULL,window TEXT NOT NULL,pos INTEGER NOT NULL,count INTEGER NOT NULL,vnum INTEGER NOT NULL"; + for(unsigned i=0;i<3;++i)item+=",socket"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0"; + for(unsigned i=0;i<7;++i)item+=",attrtype"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0,attrvalue"+std::to_string(i)+" INTEGER NOT NULL DEFAULT 0"; + item+=",port_extra BLOB NOT NULL DEFAULT X''"; + sql(db,"CREATE TABLE item("+item+")");sql(db,"CREATE TABLE port_economy_custody("+item+")"); + for(const auto& definition:{"player(id INTEGER PRIMARY KEY,account_id INTEGER,gold INTEGER)","quest(dwPID INTEGER,szName TEXT,szState TEXT,lValue INTEGER,PRIMARY KEY(dwPID,szName,szState))","port_economy_version(id INTEGER PRIMARY KEY,version INTEGER)","port_economy_requests(token TEXT PRIMARY KEY,account INTEGER,pid INTEGER,body BLOB,state TEXT,result TEXT,reference INTEGER,created_at TEXT DEFAULT CURRENT_TIMESTAMP)","port_economy_pending(pid INTEGER PRIMARY KEY,token TEXT UNIQUE)","port_economy_item_reservations(id INTEGER PRIMARY KEY,request TEXT)","port_economy_account_lock(account INTEGER PRIMARY KEY)","port_economy_listings(id INTEGER PRIMARY KEY AUTOINCREMENT,owner INTEGER,account INTEGER,item INTEGER,price INTEGER,state TEXT,active_order INTEGER DEFAULT 0)","port_economy_orders(id INTEGER PRIMARY KEY AUTOINCREMENT,request TEXT UNIQUE,listing INTEGER,buyer INTEGER,account INTEGER,price INTEGER,state TEXT)","port_economy_credit(pid INTEGER PRIMARY KEY,amount INTEGER)","port_economy_gaya(pid INTEGER PRIMARY KEY,generation INTEGER,deadline INTEGER,offers BLOB)"})sql(db,std::string("CREATE TABLE ")+definition); + sql(db,"INSERT INTO port_economy_version VALUES(1,1)"); +#endif + + if(argc==3) { + const std::string mode=argv[2];Store store(db,itemSize); + if(mode=="recover") { + const auto result=store.Settle(2,2);assert(result==Store::Settled||result==Store::None); + assert(integer(db,"SELECT lValue FROM quest WHERE dwPID=2 AND szState='points'")==450); + assert(integer(db,"SELECT SUM(count) FROM item WHERE owner_id=2 AND window='MALL'")==2000); + assert(integer(db,"SELECT generation FROM port_economy_gaya WHERE pid=2")==1); + assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0);puts("PASS real MySQL crash/restart: one debit, ten item IDs, one catalogue generation");return 0; + } + assert(mode=="before"||mode=="after");reset(db);auto r=gaya(db);assert(store.Enqueue(r)); + db.after=[&](const std::string& sql){ + if((mode=="before"&&sql.find("UPDATE port_economy_requests SET state='DONE'")==0)||(mode=="after"&&sql=="COMMIT")) { + puts("READY_FOR_ISOLATED_MYSQL_CRASH");fflush(stdout);for(;;)pause(); + } + }; + store.Settle(2,2);return 90; + } + basic(db); +#ifndef PORT_ECONOMY_NO_FORK + crashes(db);races(db); +#endif + return 0; +} diff --git a/tests/features/fixtures/economy_view_probe.cpp b/tests/features/fixtures/economy_view_probe.cpp new file mode 100644 index 00000000..1f3ce316 --- /dev/null +++ b/tests/features/fixtures/economy_view_probe.cpp @@ -0,0 +1,53 @@ +#define main economy_base_main +#include "economy_probe.cpp" +#undef main +#include "src/server/common/economy_view.h" +#include +struct ViewDB:TestDB { + std::string failing;bool failed=false; + bool Query(const std::string& sql,Rows& rows) { + if(!failing.empty()&&sql.find(failing)!=std::string::npos){failed=true;rows.clear();return false;} +#ifndef PORT_ECONOMY_MYSQL + if(sql=="SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"){rows.clear();return true;} +#endif + return TestDB::Query(sql,rows); + } + bool Begin(){return TestDB::Begin();} + bool Commit(){if(failing=="COMMIT"){failed=true;return false;}return TestDB::Commit();} +}; +int main(int argc,char** argv) { + assert(argc==2||argc==3);economy_base_main(2,argv);address=argv[1];ViewDB db;reset(db); + sql(db,"UPDATE item SET port_extra=X'"+std::string(138,'0')+"' WHERE id=10"); + uint64_t id=listing(db);Request r=req(UiStatus);r.generation=123;r.reference=0;r.slot=0;memset(r.token,'0',32);r.token[32]=0; + Store store(db,itemSize);assert(Valid(r)&&!store.Enqueue(r)); + std::vector frames; + assert(View(db,r,itemSize,frames));assert(frames.front()=="MTECON1 begin 123 0 0 1 0 0");assert(frames.back()=="MTECON1 end 123"); + assert(frames[1].find("MTECON1 row 123 0 "+std::to_string(id)+" 750 1 0 100 5 1 123456 0 0")==0); + assert(frames[2].find("MTECON1 meta 123 0 631100")==0); + for(const auto& frame:frames)assert(frame.size()<240); + if(argc==3){std::ofstream output(argv[2]);for(const auto& frame:frames)output< POINT_ENCHANT_* 242-247 assert rows[123:129]==['POINT_ENCHANT_'+e for e in ELEM],rows[123:129] @@ -32,6 +36,7 @@ char=source('game/src/char.cpp') apply=char[char.index('void CHARACTER::ApplyPoint('):char.index('void CHARACTER::MotionPacketEncode(')] assert all('case APPLY_ENCHANT_%s:'%e in apply for e in ELEM) assert 'case APPLY_ATTBONUS_STONE:' in apply and 'case APPLY_ATTBONUS_BOSS:' in apply +assert 'case APPLY_RESIST_MAGIC_REDUCTION:' in apply points=source('game/src/char.h') assert all('POINT_ENCHANT_%s = %d,'%(e,242+i) in points for i,e in enumerate(ELEM)),'enchant points' assert 'POINT_ATTBONUS_STONE = 240,' in points and 'POINT_ATTBONUS_BOSS = 241,' in points diff --git a/tests/features/test_ava2_argument_split.py b/tests/features/test_ava2_argument_split.py new file mode 100644 index 00000000..30e18119 --- /dev/null +++ b/tests/features/test_ava2_argument_split.py @@ -0,0 +1,41 @@ +"""Compile AVA2 text utilities and the legacy shop-label input guard.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class Arguments(unittest.TestCase): + def test_tab_compression_preserves_spaces_and_empty_edges(self): + source=(ROOT/'src/server/game/src/utils.cpp').read_text(encoding='latin1') + body=source[source.index('// AVA2 search files'):source.index('static int global_time_gap')] + code=r''' +#include +#include +#include +using WORD=uint16_t;using BYTE=uint8_t; +#define ENABLE_SHOP_SEARCH_SYSTEM +#define ENABLE_OFFLINESHOP_SYSTEM +#include "src/server/game/src/utils.h" +'''+body+r''' +int main(){ + assert(getInjectText(nullptr)); + assert(!getInjectText("SELECT dragon") && !getInjectText("\xe9\xbe\x99")); + assert(getInjectText("a'b") && getInjectText("a\\b") && getInjectText("a; DROP")); + assert(getInjectText("a\n") && getInjectText("a\x7f")); + std::string longLabel(256,'a');assert(getInjectText(longLabel.c_str())); + std::vector args; + split_argument_special("1\t\tpet\t20",args,"\t");assert((args==std::vector{"1","pet","20"})); + split_argument_special("\tlong pet name\t",args,"\t");assert((args==std::vector{"","long pet name",""})); + split_argument_special(nullptr,args,"\t");assert(args.size()==1 && args[0].empty()); + split_argument_special("\t\t",args,"\t");assert(args.size()==2 && args[0].empty() && args[1].empty()); + split_argument_special("a|b||c;",args,"|;");assert((args==std::vector{"a","b","c",""})); + split_argument_special("a b",args,"");assert(args.size()==1 && args[0]=="a b"); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(code) + subprocess.run(['c++','-std=c++23','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_ava2_pickup.py b/tests/features/test_ava2_pickup.py index f2a8ce43..6b71f5e8 100644 --- a/tests/features/test_ava2_pickup.py +++ b/tests/features/test_ava2_pickup.py @@ -14,6 +14,7 @@ harness=r''' #include #include using BYTE=uint8_t;using DWORD=uint32_t; +DWORD clockNow=1000;DWORD get_dword_time(){return clockNow;} #define IS_SET(v,b) ((v)&(b)) enum {ITEM_WEAPON=1,ITEM_ARMOR,ITEM_NEW_RINGS,ITEM_COSTUME,ITEM_SKILLBOOK,ITEM_METIN,ITEM_GIFTBOX,ITEM_BELT}; enum {ARMOR_BODY=0,ARMOR_HEAD,ARMOR_SHIELD,ARMOR_WRIST,ARMOR_NECK,ARMOR_EAR,ARMOR_FOOTS,ARMOR_PENDANT}; @@ -25,7 +26,7 @@ struct Item {unsigned type=ITEM_GIFTBOX,sub=0,vnum=50100;bool ground=true,distan bool GetSectree(){return ground;}bool DistanceValid(CHARACTER*){return distance;}bool IsOwnership(CHARACTER*){return owned;} };using LPITEM=Item*; struct Desc{bool closed=false;void SetPhase(int){closed=true;}}; -struct CHARACTER {unsigned mode=1;bool dead=false,stun=false,warp=false,observer=false;Desc desc;std::vector picked; +struct CHARACTER {DWORD m_portPickupLastCommand=0;unsigned mode=1;bool dead=false,stun=false,warp=false,observer=false;Desc desc;std::vector picked; unsigned GetPickUPMode(){return mode;}bool IsDead(){return dead;}bool IsStun(){return stun;}bool IsWarping(){return warp;}bool IsObserverMode(){return observer;} Desc* GetDesc(){return &desc;}void PickupItem(unsigned v){picked.push_back(v);}bool CheckItemCanGet(LPITEM); };using LPCHARACTER=CHARACTER*; @@ -44,10 +45,13 @@ int main(){ char data[17];TPacketCGItemsPickUp p{235,3};memcpy(data,&p,5);unsigned vids[]={10,11,12};memcpy(data+5,vids,12); assert(input.ItemsPickup(&ch,data,16)==-1&&ch.picked.empty()); assert(input.ItemsPickup(&ch,data,17)==12);assert((ch.picked==std::vector{10,11})); - ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_CHESTS;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{11})); - ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_STONES;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{10})); - ch.picked.clear();ch.mode=0;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty()); - ch.mode=1;ch.dead=true;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());ch.dead=false; + clockNow+=500;ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_CHESTS;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{11})); + clockNow+=500;ch.picked.clear();ch.mode=1|AUTOMATIC_PICK_UP_STONES;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{10})); + clockNow+=500;ch.picked.clear();ch.mode=0;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{10,11})); + ch.picked.clear();input.ItemsPickup(&ch,data,17);assert(ch.picked.empty()); + clockNow+=499;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty()); + clockNow+=1;input.ItemsPickup(&ch,data,17);assert((ch.picked==std::vector{10,11}));ch.picked.clear(); + ch.mode=1;ch.dead=true;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty());ch.dead=false;clockNow+=500; box.distance=false;stone.ground=false;input.ItemsPickup(&ch,data,17);assert(ch.picked.empty()); p.count=0xffffffff;memcpy(data,&p,5);assert(input.ItemsPickup(&ch,data,5)==0&&ch.desc.closed); } @@ -55,4 +59,4 @@ int main(){ with tempfile.TemporaryDirectory() as d: p=Path(d)/'pickup.cpp';exe=Path(d)/'pickup';p.write_text(harness+enums+filters+handler+main) subprocess.run(['c++','-std=c++11',str(p),'-o',str(exe)],check=True);subprocess.run([str(exe)],check=True) -print('AVA2 CG235: framing, count overflow, mode, ownership/distance, distinct chest/stone filters: PASS') +print('AVA2 CG235: framing, count overflow, UI-disabled autohunt, 500ms rate limit, ownership/distance, distinct chest/stone filters: PASS') diff --git a/tests/features/test_ava2_ticket_shop.py b/tests/features/test_ava2_ticket_shop.py index 25e15a36..50360d24 100644 --- a/tests/features/test_ava2_ticket_shop.py +++ b/tests/features/test_ava2_ticket_shop.py @@ -16,11 +16,11 @@ using DWORD=uint32_t;using BYTE=uint8_t;using WORD=uint16_t; const int SHOP_HOST_ITEM_MAX_NUM=40,HEADER_GC_SHOP=38,CHAT_TYPE_COMMAND=1; enum {SHOP_SUBHEADER_GC_START,SHOP_SUBHEADER_GC_END,SHOP_SUBHEADER_GC_UPDATE_ITEM,SHOP_SUBHEADER_GC_UPDATE_PRICE,SHOP_SUBHEADER_GC_OK,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY,SHOP_SUBHEADER_GC_SOLDOUT,SHOP_SUBHEADER_GC_INVENTORY_FULL,SHOP_SUBHEADER_GC_INVALID_POS,SHOP_SUBHEADER_GC_SOLD_OUT,SHOP_SUBHEADER_GC_START_EX,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX,SHOP_SUBHEADER_GC_START_ITEM_CURRENCY,SHOP_SUBHEADER_GC_NOT_ENOUGH_ITEM}; #pragma pack(push,1) -struct WireItem { DWORD vnum,price;BYTE count,display_pos;char rest[33]; }; +struct WireItem { DWORD vnum;int64_t price;BYTE count,display_pos;char rest[33]; }; struct TPacketGCShopStart { DWORD owner_vid;WireItem items[40]; }; struct TPacketGCShop { BYTE header;WORD size;BYTE subheader; }; #pragma pack(pop) -static_assert(sizeof(WireItem)==43,"baseline item"); +static_assert(sizeof(WireItem)==47,"baseline item"); struct TShopItemTable { DWORD vnum;BYTE count; }; struct Desc { std::string frame;void BufferedPacket(const void* p,size_t n){frame.assign((const char*)p,n);}void Packet(const void* p,size_t n){frame.append((const char*)p,n);} }; class CShop; @@ -56,7 +56,7 @@ main=r''' int main(){ Character c;c.items[90011]=30; assert(Ava2OpenTicketShop(&c));assert(Ava2IsTicketShop(c.GetShop()));assert(c.GetShopOwner()==&c); - assert(c.desc.frame.size()==2048); + assert(c.desc.frame.size()==2208); Ava2ShopStart start;memcpy(&start,c.desc.frame.data()+sizeof(TPacketGCShop),sizeof(start)); assert(start.shop.owner_vid==0 && start.shop.items[7].vnum==25170 && start.prices[0].vnum==90011 && start.prices[7].count==30); assert(c.GetShop()->Buy(&c,0)==SHOP_SUBHEADER_GC_OK);assert(c.items[25163]==1 && c.items[90011]==20 && c.gold==123456); diff --git a/tests/features/test_cube_gold_debit.py b/tests/features/test_cube_gold_debit.py new file mode 100644 index 00000000..9bd0ceaa --- /dev/null +++ b/tests/features/test_cube_gold_debit.py @@ -0,0 +1,48 @@ +"""Execute actual Cube_make with wide balances and unsigned proto fees.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + + +class CubeGold(unittest.TestCase): + def test_unsigned_fee_debits_exactly_once_and_insufficient_balance_is_unchanged(self): + text=(ROOT/'src/server/game/src/cube.cpp').read_text(encoding='latin1') + actual='bool Cube_make'+text.split('bool Cube_make',1)[1].split('void Cube_show_list',1)[0] + harness=r''' +#include +#include +#include +struct Item{unsigned GetID(){return 1;}};using LPITEM=Item*; +struct Character;using LPCHARACTER=Character*; +struct CUBE_VALUE{unsigned vnum=19,count=1;}; +struct CUBE_DATA{uint32_t gold=50;int percent=100;unsigned removed=0;CUBE_VALUE value; + CUBE_VALUE* reward_value(){return &value;}void remove_material(LPCHARACTER){++removed;}} proto; +struct Character {int64_t balance=1000,delta=0;unsigned charges=0,rewards=0;Item item; + bool IsCubeOpen(){return true;}Character* GetQuestNPC(){return this;}LPITEM* GetCubeItem(){return nullptr;} + unsigned GetRaceNum(){return 1;}int64_t GetGold(){return balance;} + void ChatPacket(int,const char*,...){}void PointChange(int,int64_t n,bool){delta=n;balance+=n;++charges;} + Item* AutoGiveItem(unsigned,unsigned){++rewards;return &item;} + unsigned GetPlayerID(){return 1;}int GetX(){return 0;}int GetY(){return 0;}}; +CUBE_DATA* FN_find_cube(LPITEM*,unsigned){return &proto;} +constexpr int POINT_GOLD=11,CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=2; +#define LC_TEXT(s) "notice" +int roll=1;int number(int,int){return roll;} +struct LogManager{static LogManager& instance(){static LogManager m;return m;}void CubeLog(unsigned,int,int,unsigned,unsigned,unsigned,int){}}; +''' + main=r''' +int main(){ + for(uint32_t fee:{uint32_t(50),uint32_t(INT32_MAX)+1u,UINT32_MAX}) { + proto.gold=fee;proto.removed=0;Character ch;ch.balance=int64_t(fee)+123; + assert(Cube_make(&ch));assert(ch.balance==123 && ch.delta==-int64_t(fee) && ch.charges==1 && proto.removed==1 && ch.rewards==1); + ch={};ch.balance=int64_t(fee)-1;proto.removed=0;assert(!Cube_make(&ch));assert(ch.balance==int64_t(fee)-1 && ch.charges==0 && proto.removed==0 && ch.rewards==0); + } + proto.gold=50;proto.removed=0;roll=100;proto.percent=0;Character ch; + assert(!Cube_make(&ch));assert(ch.balance==950 && ch.charges==1 && proto.removed==1 && ch.rewards==0); +} +''' + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);(p/'probe.cpp').write_text('#include \n'+harness+actual+main) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(p/'probe.cpp'),'-o',str(p/'probe')],check=True) + subprocess.run([str(p/'probe')],check=True) diff --git a/tests/features/test_db_config_runtime.py b/tests/features/test_db_config_runtime.py new file mode 100644 index 00000000..6eba10f5 --- /dev/null +++ b/tests/features/test_db_config_runtime.py @@ -0,0 +1,58 @@ +"""Run the actual DB config parser with bounded buffers and atomic rejection.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] +class ConfigRuntime(unittest.TestCase): + def test_tokens_lines_and_malformed_reload_preserve_active_config(self): + source=(ROOT/'src/server/db/src/Config.cpp').read_text(encoding='latin1') + source='\n'.join(line for line in source.splitlines() if not line.startswith('#include')) + stl=(ROOT/'src/server/common/stl.h').read_text(encoding='latin1') + lower=stl[stl.index('inline void stl_lowers'):stl.index('struct stringhash')] + code=r''' +#include +#include +#include +#include +#include +#include +#include +#include +using DWORD=uint32_t;using WORD=uint16_t;using BYTE=uint8_t; +#include +#include +#define itertype(v) decltype((v).begin()) +// Singleton lifetime is outside the parser boundary exercised here. +template struct singleton {}; +#include "src/server/common/utils.h" +#include "src/server/db/src/Config.h" +#define sys_log(...) ((void)0) +'''+lower+source+r''' +FILE* input(const std::string& s){FILE* f=tmpfile();assert(f);assert(fwrite(s.data(),1,s.size(),f)==s.size());rewind(f);return f;} +void file(const char* path,const std::string& text){std::ofstream out(path);out<GiveMoreTime_Fix', fix_block) self.assertIn('item->SetCount(item->GetCount() - 1);', fix_block) - def test_item_give_more_time_implementation(self): - """Verify CItem::GiveMoreTime_Per and CItem::GiveMoreTime_Fix logic in item.cpp.""" - source = (ROOT / 'src/server/game/src/item.cpp').read_text(encoding='latin1') - - # Verify GiveMoreTime_Per - self.assertIn('int CItem::GiveMoreTime_Per(float fPercent)', source) - per_code = source.split('int CItem::GiveMoreTime_Per(float fPercent)', 1)[1].split('int CItem::GiveMoreTime_Fix', 1)[0] - self.assertIn('DWORD duration = DSManager::instance().GetDuration(this);', per_code) - self.assertIn('int remain_sec = GetSocket(ITEM_SOCKET_REMAIN_SEC);', per_code) - self.assertIn('int given_time = fPercent * duration / 100;', per_code) - self.assertIn('if (remain_sec == duration)', per_code) - self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', per_code) - - # Verify GiveMoreTime_Fix - self.assertIn('int CItem::GiveMoreTime_Fix(DWORD dwTime)', source) - fix_code = source.split('int CItem::GiveMoreTime_Fix(DWORD dwTime)', 1)[1].split('int\tCItem::GetDuration()', 1)[0] - self.assertIn('if (remain_sec == duration)', fix_code) - self.assertIn('SetSocket(ITEM_SOCKET_REMAIN_SEC, duration);', fix_code) - - def test_time_charge_simulation(self): - """Simulate GiveMoreTime_Per and GiveMoreTime_Fix numerical bounds.""" - duration = 86400 # 24 hours - - # Simulated GiveMoreTime_Per (50%) - def give_more_time_per(remain_sec, percent=50.0): - given = int(percent * duration / 100) - if remain_sec == duration: - return 0, remain_sec - if given + remain_sec >= duration: - return duration - remain_sec, duration - return given, remain_sec + given - - # 1. 50% charge when remaining is 0: gives 43200s, total 43200s - added, new_remain = give_more_time_per(0, 50.0) - self.assertEqual(added, 43200) - self.assertEqual(new_remain, 43200) - - # 2. 50% charge when remaining is 60000s: capped at 86400, gives 26400s - added, new_remain = give_more_time_per(60000, 50.0) - self.assertEqual(added, 26400) - self.assertEqual(new_remain, 86400) - - # 3. Charge when already full: gives 0 - added, new_remain = give_more_time_per(86400, 50.0) - self.assertEqual(added, 0) - self.assertEqual(new_remain, 86400) - - # Simulated GiveMoreTime_Fix (86400s) - def give_more_time_fix(remain_sec, fix_time=86400): - if remain_sec == duration: - return 0, remain_sec - if fix_time + remain_sec >= duration: - return duration - remain_sec, duration - return fix_time, remain_sec + fix_time - - # 1. Fixed charge 86400s when remaining is 1000s: capped at 86400, gives 85400s - added, new_remain = give_more_time_fix(1000, 86400) - self.assertEqual(added, 85400) - self.assertEqual(new_remain, 86400) + def test_actual_time_charge_methods_reject_corruption_and_cap_before_conversion(self): + import subprocess, tempfile + source=(ROOT/'src/server/game/src/item.cpp').read_bytes().decode('latin1') + body=source[source.index('int CItem::GiveMoreTime_Per('):source.index('int\tCItem::GetDuration()')] + harness=r""" +#include +#include +#include +#include +using DWORD=uint32_t; +constexpr int ITEM_SOCKET_REMAIN_SEC=0; +struct CItem {bool dragon=true;int64_t remaining=0;unsigned writes=0; + bool IsDragonSoul(){return dragon;}int64_t GetSocket(int){return remaining;} + void SetSocket(int,int value){remaining=value;++writes;} + int GiveMoreTime_Per(float);int GiveMoreTime_Fix(DWORD); +}; +struct DSManager {uint32_t duration=86400;static DSManager& instance(){static DSManager m;return m;}uint32_t GetDuration(CItem*){return duration;}}; +""" + main=r""" +int main(){ + CItem i;auto& d=DSManager::instance(); + assert(i.GiveMoreTime_Per(50)==43200&&i.remaining==43200);i.remaining=60000;assert(i.GiveMoreTime_Per(50)==26400&&i.remaining==86400); + unsigned writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0&&i.writes==writes); + i.remaining=1000;assert(i.GiveMoreTime_Fix(86400)==85400&&i.remaining==86400); + i.remaining=0;writes=i.writes; + for(float f:{-1.f,0.f,std::numeric_limits::infinity(),std::numeric_limits::quiet_NaN()})assert(i.GiveMoreTime_Per(f)==0&&i.writes==writes); + assert(i.GiveMoreTime_Per(.00001f)==0&&i.writes==writes); + assert(i.GiveMoreTime_Per(std::numeric_limits::max())==86400&&i.remaining==86400); + for(int64_t remaining:{int64_t(-1),int64_t(INT32_MIN),int64_t(86401),int64_t(INT32_MAX)}){i.remaining=remaining;writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(UINT32_MAX)==0&&i.remaining==remaining&&i.writes==writes);} + d.duration=INT32_MAX;i.remaining=INT32_MAX-10;assert(i.GiveMoreTime_Fix(UINT32_MAX)==10&&i.remaining==INT32_MAX); + for(uint32_t duration:{0u,UINT32_MAX}){d.duration=duration;i.remaining=0;writes=i.writes;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0&&i.writes==writes);} + d.duration=86400;i.dragon=false;assert(i.GiveMoreTime_Per(50)==0&&i.GiveMoreTime_Fix(86400)==0); +} +""" + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);(p/'test.cpp').write_text(harness+body+main) + subprocess.run(['c++','-std=c++17','-include','initializer_list','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(p/'test.cpp'),'-o',str(p/'probe')],check=True) + subprocess.run([str(p/'probe')],check=True) def test_dragon_bean_100500_refine_strength_mechanics(self): """Verify 100500 MATERIAL_DS_REFINE_HOLLY in DSManager::DoRefineStrength.""" diff --git a/tests/features/test_economy.py b/tests/features/test_economy.py new file mode 100644 index 00000000..b9d625c7 --- /dev/null +++ b/tests/features/test_economy.py @@ -0,0 +1,17 @@ +"""Execute the production transaction store against SQLite (SQL dialect boundary). +The same C++ scenarios are separately run against isolated real MySQL/InnoDB. +""" +import subprocess +import tempfile +import unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] + +class EconomyTransactions(unittest.TestCase): + def test_orders_gaya_crash_replay_and_competing_buyers(self): + with tempfile.TemporaryDirectory() as tmp: + exe=Path(tmp)/'economy' + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(ROOT/'tests/features/fixtures/economy_probe.cpp'),'-lsqlite3','-o',str(exe)],check=True) + subprocess.run([str(exe),str(Path(tmp)/'economy.db')],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_economy_coordinator.py b/tests/features/test_economy_coordinator.py new file mode 100644 index 00000000..0e97fc27 --- /dev/null +++ b/tests/features/test_economy_coordinator.py @@ -0,0 +1,100 @@ +"""Execute DB coordinator functions with explicit peer/cache/FIFO SQL boundaries.""" +import re +import subprocess +import tempfile +import unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] + +class EconomyCoordinator(unittest.TestCase): + def test_ownership_logout_cache_eviction_two_barriers_and_stale_write_fences(self): + fixture=(ROOT/'tests/features/fixtures/economy_probe.cpp').read_text() + prefix,main=fixture.split('int main(int argc,char** argv)',1) + prefix=prefix.replace('rows={{"13"}};return true;', 'rows={{sql.find("AND TABLE_NAME=\'port_economy_version\'")!=std::string::npos?"1":"13"}};return true;') + init=main.split(' basic(db);',1)[0] + assert len(init) values;size_t next=0;};using MYSQL_ROW=char**; +MYSQL_ROW mysql_fetch_row(MYSQL_RES* res){if(res->next>=res->rows.size())return nullptr;res->values.clear();for(auto& s:res->rows[res->next++])res->values.push_back(s.data());return res->values.data();} +struct SQLResult {uint64_t uiNumRows=0;MYSQL_RES* pSQLResult=nullptr;}; +struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;void* pvUserData=nullptr;SQLResult* Get(){return &result;}}; +struct CPeer {unsigned id=1;std::vector replies;unsigned GetHandle(){return id;}unsigned GetChannel(){return 1;}void EncodeHeader(unsigned,unsigned,size_t){}void Encode(const void* data,size_t n){assert(n==sizeof(Reply));replies.push_back(*static_cast(data));}}; +struct Player {unsigned dwID=0;};struct Account {Player players[4];}; +struct CLoginData {bool playing=true;unsigned peer=1;Account account;unsigned GetConnectedPeerHandle(){return peer;}bool IsPlay(){return playing;}Account& GetAccountRef(){return account;}}; +struct TPlayerLoadPacket{unsigned account_id,player_id;}; +struct Proto{unsigned bSize=1,dwAntiFlags=0,bType=0,dwFlags=1;}; +constexpr unsigned ITEM_ANTIFLAG_GIVE=1,ITEM_ANTIFLAG_MYSHOP=2,ITEM_QUEST=18,ITEM_FLAG_STACKABLE=1,QID_ECONOMY_FENCE=100; +TestDB* activeDB=nullptr; +struct CDBManager { + std::vector mainQueue,asyncQueue;std::vector completed;uint64_t failures[2]={}; + static CDBManager& instance(){static CDBManager m;return m;} + TestDB* DirectHandle(){return activeDB;} + SQLMsg* DirectQuery(const char* sql){auto* msg=new SQLMsg;if(!activeDB->Query(sql,msg->res.rows))msg->uiSQLErrno=1;msg->result.uiNumRows=msg->res.rows.size();msg->result.pSQLResult=&msg->res;return msg;} + uint64_t EconomyFailures(bool async){return failures[async?1:0];} + void ReturnQuery(const char*,unsigned,unsigned pid,void*){mainQueue.push_back(pid);} + void EconomyAsyncFence(unsigned pid){asyncQueue.push_back(pid);} + SQLMsg* PopEconomyAsyncFence(){if(completed.empty())return nullptr;auto* p=completed.back();completed.pop_back();return p;} + void asyncDone(unsigned pid){assert(!asyncQueue.empty());asyncQueue.pop_back();auto* p=new SQLMsg;p->pvUserData=reinterpret_cast(static_cast(pid));completed.push_back(p);} +}; +namespace PortEconomy {struct Mysql { + TestDB& ref;uint64_t affected=0,inserted=0; + explicit Mysql(TestDB* db):ref(*db){} + bool Query(const std::string& q,Rows& rows){bool ok=ref.Query(q,rows);affected=ref.affected;inserted=ref.inserted;return ok;} + bool Begin(){return ref.Begin();}bool Commit(){return ref.Commit();}void Rollback(){ref.Rollback();} +};} +const char* GetTablePostfix(){return "";} +static size_t TestCopyString(char* out,const char* text,size_t n){size_t length=strlen(text);if(n){size_t k=std::min(n-1,length);memcpy(out,text,k);out[k]=0;}return length;} +#define strlcpy TestCopyString +#define sys_log(...) ((void)0) +struct CClientManager { + struct EconomyFence {DWORD account=0;bool primed=false,mainDone=false,asyncDone=false,failed=false;uint64_t mainFailures=0,asyncFailures=0;time_t nextAttempt=0;DWORD peer=0,handle=0;TPlayerLoadPacket load={};}; + std::map> m_economyEnqueueEpoch; + std::map m_economyFences;std::map m_economyOwners;std::set m_economyClosed; + std::map m_map_itemTableByVnum;CLoginData login;unsigned itemFlushes=0,playerFlushes=0,logoutDeletes=0; + CPeer* connected=nullptr;unsigned resumed=0;CPeer* GetPeer(unsigned id){return connected&&connected->id==id?connected:nullptr;}void QUERY_PLAYER_LOAD(CPeer* peer,unsigned handle,TPlayerLoadPacket* p){assert(EconomyBeforeLoad(peer,handle,p));++resumed;} + CLoginData* GetLoginDataByAID(unsigned account){return account==1?&login:nullptr;} + void FlushItemCacheSet(unsigned){++itemFlushes;}void FlushPlayerCacheSet(unsigned){++playerFlushes;}void DeleteLogoutPlayer(unsigned){++logoutDeletes;} + void EconomyRequest(CPeer*,DWORD,const char*,DWORD);bool EconomyBeforeLoad(CPeer*,DWORD,TPlayerLoadPacket*);void EconomyTick();void EconomyMainFence(DWORD,bool);bool EconomySaveAllowed(CPeer*,DWORD);bool EconomyItemWritable(DWORD);bool EconomyCanDelete(DWORD); +}; +''' + # Extra headers are boundaries used by the real coordinator. + prefix='#include "src/server/common/economy_view.h"\n#include \n#include \n#include \n#include \n'+prefix + tests=r''' + activeDB=&db;reset(db);CClientManager manager;CPeer peer,wrong;manager.connected=&peer;wrong.id=99;manager.login.account.players[0].dwID=1; + Proto proto;manager.m_map_itemTableByVnum[100]=&proto; + Request r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750; + manager.EconomyRequest(&wrong,1,reinterpret_cast(&r),sizeof(r));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0); + manager.EconomyRequest(&peer,1,reinterpret_cast(&r),sizeof(r));assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==1);assert(!manager.EconomyCanDelete(1));assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1); + TPlayerLoadPacket load{1,1};assert(!manager.EconomyBeforeLoad(&peer,7,&load));assert(manager.itemFlushes==0); // still playing + manager.login.playing=false;assert(!manager.EconomyBeforeLoad(&wrong,7,&load));assert(manager.itemFlushes==0); + assert(!manager.EconomyBeforeLoad(&peer,7,&load));assert(manager.itemFlushes==1 && manager.playerFlushes==1 && manager.logoutDeletes==1);assert(!manager.EconomySaveAllowed(&peer,1)); + auto& queues=CDBManager::instance();assert(queues.mainQueue.size()==1 && queues.asyncQueue.empty());manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1); + manager.EconomyMainFence(1,false);assert(queues.mainQueue.size()==2 && queues.asyncQueue.size()==1);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1); + queues.asyncDone(1);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1); // second main fence not done + manager.EconomyMainFence(1,false);manager.EconomyTick();assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==0);assert(!manager.EconomyItemWritable(10));assert(!manager.EconomyCanDelete(1));assert(manager.resumed==1);assert(!manager.EconomySaveAllowed(&peer,1)); + assert(manager.EconomyBeforeLoad(&peer,7,&load));assert(!manager.EconomySaveAllowed(&peer,1));manager.login.playing=true;assert(manager.EconomySaveAllowed(&peer,1));assert(!manager.EconomySaveAllowed(&wrong,1)); + // A failed final async write aborts the durable intent instead of settling it. + reset(db);queues.mainQueue.clear();queues.asyncQueue.clear();r=req(List,1,1,100);r.item=10;r.itemVnum=100;r.itemCount=5;r.price=750; + manager.EconomyRequest(&peer,1,reinterpret_cast(&r),sizeof(r));++queues.failures[1];manager.login.playing=false;assert(!manager.EconomyBeforeLoad(&peer,7,&load));manager.EconomyMainFence(1,false);queues.asyncDone(1);manager.EconomyMainFence(1,false);manager.EconomyTick(); + assert(integer(db,"SELECT COUNT(*) FROM item WHERE id=10")==1);assert(integer(db,"SELECT COUNT(*) FROM port_economy_custody")==0);assert(value(db,"SELECT result FROM port_economy_requests WHERE token='"+std::string(r.token)+"'")=="save_failed"); + assert(manager.EconomyCanDelete(1));sql(db,"INSERT INTO port_economy_gaya(pid,generation,deadline,offers) VALUES(1,1,100,X'')");assert(!manager.EconomyCanDelete(1)); + sql(db,"UPDATE port_economy_gaya SET generation="+std::to_string(RetiredGeneration)+" WHERE pid=1");assert(manager.EconomyCanDelete(1)); + sql(db,"INSERT INTO quest(dwPID,szName,szState,lValue) VALUES(1,'gem','points',1)");assert(!manager.EconomyCanDelete(1)); + sql(db,"UPDATE quest SET lValue=0 WHERE dwPID=1");assert(manager.EconomyCanDelete(1)); + // UI reads return correlated command frames and never queue a mutation. + manager.login.playing=true;r=req(UiStatus,1,1,100);r.generation=17;r.slot=0;memset(r.token,'0',32);r.token[32]=0; + peer.replies.clear();manager.EconomyRequest(&peer,1,reinterpret_cast(&r),sizeof(r)); + assert(!peer.replies.empty() && std::string(peer.replies.front().message).find("MTECON1 begin 17 ")==0); + assert(std::string(peer.replies.back().message)=="MTECON1 end 17");assert(integer(db,"SELECT COUNT(*) FROM port_economy_pending")==0); + puts("PASS actual DB coordinator: ownership/logout/eviction/two FIFO barriers/stale saves/failure abort"); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe' + src.write_text(prefix+harness+body+'int main(int argc,char** argv)'+init+tests) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-lsqlite3','-o',str(exe)],check=True) + subprocess.run([str(exe),str(Path(tmp)/'economy.db')],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_economy_game_ui.py b/tests/features/test_economy_game_ui.py new file mode 100644 index 00000000..6fd7b7b8 --- /dev/null +++ b/tests/features/test_economy_game_ui.py @@ -0,0 +1,59 @@ +"""Run actual game command/submission/reply functions, with session/socket boundaries.""" +import pathlib,re,subprocess,tempfile,unittest +ROOT=pathlib.Path(__file__).resolve().parents[2] +class GameEconomyUI(unittest.TestCase): + def test_read_only_frames_receipts_and_mutation_handoff(self): + body=re.sub(r'^#include[^\n]*\n','',(ROOT/'src/server/game/src/port_economy.cpp').read_text(),flags=re.M) + harness=r''' +#include "src/server/common/economy.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +constexpr int PHASE_CLOSE=0,CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=2,ITEM_QUEST=18; +constexpr unsigned ITEM_ANTIFLAG_GIVE=1,ITEM_ANTIFLAG_MYSHOP=2; +#define IS_SET(v,bits) ((v)&(bits)) +struct Item {unsigned id=10,vnum=100,count=5;bool locked=false; + bool IsEquipped(){return false;}bool isLocked(){return locked;}bool IsExchanging(){return false;}unsigned GetAntiFlag(){return 0;}unsigned GetType(){return 0;} + unsigned GetID(){return id;}unsigned GetOriginalVnum(){return vnum;}unsigned GetCount(){return count;}};using LPITEM=Item*;using WORD=uint16_t; +struct CHARACTER; +struct Desc {unsigned handle=1,closed=0;struct Account{unsigned id=1;} account;CHARACTER* ch=nullptr; + unsigned GetHandle(){return handle;}Account& GetAccountTable(){return account;}void SetPhase(int){++closed;}CHARACTER* GetCharacter(){return ch;}}; +struct CHARACTER {Desc desc;Item item;bool busy=false;std::vector> messages; + CHARACTER(){desc.ch=this;}bool IsPC(){return true;}Desc* GetDesc(){return &desc;}bool IsItemLoaded(){return true;}unsigned GetPlayerID(){return 1;} + int GetQuestFlag(const char*){return 0;}int64_t GetGold(){return 1000;}bool CanHandleItem(){return !busy;}bool IsWarping(){return false;}bool IsDead(){return false;}bool IsStun(){return false;} + bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool GetMall(){return false;}bool IsCubeOpen(){return false;} + LPITEM GetInventoryItem(WORD cell){return cell==0?&item:nullptr;} + void ChatPacket(int type,const char* fmt,...){char out[1024];va_list ap;va_start(ap,fmt);vsnprintf(out,sizeof(out),fmt,ap);va_end(ap);messages.emplace_back(type,out);} +};using LPDESC=Desc*; +namespace quest {struct PC{bool IsLoaded(){return true;}bool IsRunning(){return false;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};} +struct Database {std::vector requests;void DBPacket(unsigned header,unsigned,const void* data,size_t n){assert(header==77&&n==sizeof(PortEconomy::Request));requests.push_back(*static_cast(data));}} database; +Database* db_clientdesc=&database; +const char* get_table_postfix(){return "";} +Desc* live=nullptr; +struct DESC_MANAGER {static DESC_MANAGER& instance(){static DESC_MANAGER m;return m;}Desc* FindByHandle(unsigned handle){return live&&live->handle==handle?live:nullptr;}}; +#define ACMD(name) void name(CHARACTER* ch,const char* argument,int cmd=0,int subcmd=0) +''' + main=r''' +int main(){CHARACTER ch;live=&ch.desc; + do_mt_economy(&ch,"ui 0 0 1 0 00000000000000000000000000000000");assert(database.requests.size()==1 && database.requests.back().operation==PortEconomy::UiStatus && !ch.desc.closed); + do_mt_economy(&ch,"ui 0 0 2 0 00000000000000000000000000000000");assert(database.requests.size()==1 && ch.messages.back().first==CHAT_TYPE_COMMAND); + do_mt_economy(&ch,"act aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa buy 4294967297 750");assert(database.requests.size()==2 && ch.desc.closed==1); + const auto request=database.requests.back();assert(request.reference==4294967297ULL && request.price==750 && request.expectedGold==1000 && request.player==1 && request.account==1 && std::string(request.token)==std::string(32,'a')); + do_mt_economy(&ch,"act bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb list 0 750 101 5");assert(database.requests.size()==2); + do_mt_economy(&ch,"act bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb list 0 750 100 5");assert(database.requests.size()==3 && database.requests.back().item==10); + do_mt_economy(&ch,"act zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz withdraw");assert(database.requests.size()==3); + ch.busy=true;do_mt_economy(&ch,"act cccccccccccccccccccccccccccccccc withdraw");assert(database.requests.size()==3);ch.busy=false; + PortEconomy::Reply reply={};reply.account=1;reply.player=1;reply.ok=1;strcpy(reply.message,"MTECON1 end 1");PortEconomyReply(1,reinterpret_cast(&reply));assert(ch.messages.back().first==CHAT_TYPE_COMMAND); + auto count=ch.messages.size();reply.account=2;PortEconomyReply(1,reinterpret_cast(&reply));assert(ch.messages.size()==count); +} +''' + with tempfile.TemporaryDirectory() as tmp: + p=pathlib.Path(tmp);(p/'probe.cpp').write_text(harness+body+main) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32','-I'+str(ROOT),str(p/'probe.cpp'),'-o',str(p/'probe')],check=True) + subprocess.run([str(p/'probe')],check=True) diff --git a/tests/features/test_economy_reconcile.py b/tests/features/test_economy_reconcile.py new file mode 100644 index 00000000..cafa24ba --- /dev/null +++ b/tests/features/test_economy_reconcile.py @@ -0,0 +1,48 @@ +"""Legacy evidence is inventoried without manufacturing assets or refunds.""" +import importlib.util +from pathlib import Path +import unittest +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('reconcile', ROOT/'tools/economy/reconcile.py') +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) + + +def snapshot(tables): + encoded={t:[{k:v.encode('utf-8', 'surrogateescape').hex() if v is not None else None + for k,v in row.items()} for row in rows] for t,rows in tables.items()} + result={'format':1,'encoding':'mysql-hex-all-columns','tables':encoded} + result['sha256']=m.digest(result) + return result + + +class Reconcile(unittest.TestCase): + def test_conflicts_balances_history_and_unproven_refunds(self): + item={'id':'10','owner_id':'1','count':'5','vnum':'100','price':'750','status':'0','port_extra':'\0'*69} + tables={t:[] for t in m.REQUIRED} + tables['player']=[{'id':'1','shop_money':'750'},{'id':'2','shop_money':'-1'}] + tables['offline_shop_item']=[item,dict(item,id='11',status='1'),dict(item,id='12',owner_id='99'),dict(item,id='13',port_extra=None)] + tables['item']=[{'id':'10'}] + tables['offline_shop_log_important']=[{'reason':'BUY','itemid':'11','price':'750'}] + report=m.audit(snapshot(tables));assets={a['key']:a for a in report['assets']} + self.assertIn('item_id_exists_elsewhere',assets['legacy-item:10']['reasons']) + self.assertIn('historical_order_requires_delivery_payment_evidence',assets['legacy-item:11']['reasons']) + self.assertIn('owner_missing_or_duplicate',assets['legacy-item:12']['reasons']) + self.assertIn('missing_or_invalid_full_item_metadata',assets['legacy-item:13']['reasons']) + self.assertEqual(assets['legacy-proceeds:1']['classification'],'proceeds_review') + self.assertEqual(assets['legacy-proceeds:2']['classification'],'quarantine') + self.assertEqual(report['automatic_refunds'],[]);self.assertEqual(report['automatic_writes'],[]) + self.assertEqual(report['history_rows']['offline_shop_log_important'],1) + + def test_valid_candidate_remains_review_only_and_snapshot_tamper_refused(self): + tables={t:[] for t in m.REQUIRED};tables['player']=[{'id':'1','shop_money':'0'}] + tables['offline_shop_item']=[{'id':'10','owner_id':'1','count':'5','vnum':'100','price':'750','status':'0','port_extra':'\0'*69}] + data=snapshot(tables);report=m.audit(data) + self.assertEqual(report['assets'][0]['classification'],'custody_review') + self.assertEqual(report['release_gate'],'BLOCKED_PENDING_RECONCILIATION') + data['tables']['item'].append({'id':'3130'}) + with self.assertRaises(ValueError):m.audit(data) + + def test_mysql_xml_null_binary_multiple_results(self): + text='00FF' + self.assertEqual(m.xml_rows(text),[[{'x':'00FF','y':None,'z':''}],[]]) diff --git a/tests/features/test_economy_view.py b/tests/features/test_economy_view.py new file mode 100644 index 00000000..9809cd06 --- /dev/null +++ b/tests/features/test_economy_view.py @@ -0,0 +1,12 @@ +"""Actual production UI snapshot encoder plus transaction store with SQL adapter.""" +import subprocess +import tempfile +import unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] +class EconomyView(unittest.TestCase): + def test_atomic_bounded_snapshots_and_authoritative_receipts(self): + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);exe=p/'view' + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(ROOT/'tests/features/fixtures/economy_view_probe.cpp'),'-lsqlite3','-o',str(exe)],check=True) + subprocess.run([str(exe),str(p/'view.db'),str(p/'frames')],check=True) diff --git a/tests/features/test_extended_items.py b/tests/features/test_extended_items.py index 29068510..a1c18704 100644 --- a/tests/features/test_extended_items.py +++ b/tests/features/test_extended_items.py @@ -49,14 +49,14 @@ int main() { assert(!PortItemExtraRead("00",decoded)); hex[137]='g';assert(!PortItemExtraRead(hex.c_str(),decoded)); assert(!std::memcmp(&zero,&decoded,sizeof(zero))); - hex=std::string(138,'f');assert(PortItemExtraRead(hex.c_str(),decoded)); + hex=std::string(138,'f');assert(!PortItemExtraRead(hex.c_str(),decoded)); assert(decoded.name[24]==0); } ''' with tempfile.TemporaryDirectory() as tmp: cpp, exe = Path(tmp)/'extra.cpp', Path(tmp)/'extra' cpp.write_text(source) - subprocess.run(['c++', '-std=c++17', '-I'+str(ROOT), str(cpp), '-o', str(exe)], check=True) + subprocess.run(['c++', '-std=c++17', '-Werror=implicit-int-conversion', '-I'+str(ROOT), str(cpp), '-o', str(exe)], check=True) subprocess.run([str(exe)], check=True) diff --git a/tests/features/test_gaya_catalog.py b/tests/features/test_gaya_catalog.py new file mode 100644 index 00000000..e2349f31 --- /dev/null +++ b/tests/features/test_gaya_catalog.py @@ -0,0 +1,81 @@ +"""Execute catalogue I/O, corruption, writer exclusion and crash boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class GayaCatalogue(unittest.TestCase): + def test_atomic_snapshots_and_failures(self): + code=r''' +#include +#include +#include +#include +#include +static bool failWrite=false,failRename=false;static int syncs=0,failSyncAt=0,crashAt=0; +static ssize_t Write(int fd,const void* p,size_t n){if(failWrite){errno=ENOSPC;return -1;}return ::write(fd,p,n);} +static int Sync(int fd){++syncs;if(syncs==failSyncAt){errno=EIO;return -1;}int r=::fsync(fd);if(crashAt==1 && syncs==1)_exit(0);return r;} +static int Rename(int a,const char* b,int c,const char* d){if(failRename){errno=EIO;return -1;}int r=::renameat(a,b,c,d);if(crashAt==2 && r==0)_exit(0);return r;} +#define write Write +#define fsync Sync +#define renameat Rename +#include "src/server/common/gaya_catalog.h" +#undef write +#undef fsync +#undef renameat +#include +#include +#include +struct Item{uint32_t itemVnum,itemCount;int itemPrice;bool itemBuyed;}; +using Items=std::map; +std::string readFile(const std::string& path){std::ifstream f(path);return std::string((std::istreambuf_iterator(f)),{});} +void writeFile(const std::string& path,const std::string& bytes){std::ofstream out(path);out<=0); + if(child==0){PortGayaCatalogFile file;assert(file.Open(dir,1));syncs=0;crashAt=boundary;auto next=original;next[0].itemBuyed=true;file.Save(next,300000);_exit(9);} + int status=0;waitpid(child,&status,0);assert(WIFEXITED(status) && WEXITSTATUS(status)==0); + PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Loaded);assert(loaded[0].itemBuyed==(boundary==2)); + } + unlink(path.c_str());symlink("/does/not/exist",path.c_str()); + {PortGayaCatalogFile file;assert(file.Open(dir,1));assert(file.Load(loaded,refresh)==PortGayaCatalogFile::Error);} + int next=123; + assert(PortGayaNextRefresh(100000,0,true,next) && next==118000); + assert(PortGayaNextRefresh(100000,90000,true,next) && next==108000); + assert(PortGayaNextRefresh(200000,90000,true,next) && next==216000); // many elapsed windows, still future. + assert(PortGayaNextRefresh(100000,110000,true,next) && next==110000); + assert(!PortGayaNextRefresh(INT32_MAX,1,true,next));assert(!PortGayaNextRefresh(1,-1,true,next)); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe),str(Path(tmp)/'gem')],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_gaya_market.py b/tests/features/test_gaya_market.py index 70c18776..db2b2a6c 100644 --- a/tests/features/test_gaya_market.py +++ b/tests/features/test_gaya_market.py @@ -1,8 +1,6 @@ #!/usr/bin/env python3 """Verify Gaya market, items 39063/39064, and /gem command suite.""" from pathlib import Path -import subprocess -import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] @@ -15,194 +13,13 @@ class GayaMarketTest(unittest.TestCase): # 39063: Refresh Gaya Market self.assertIn('if(item->GetVnum()==39063)', special_block) - self.assertIn('RefreshGemALL();', special_block) - self.assertIn('item->SetCount(item->GetCount()-1);', special_block) + self.assertIn('return RefreshGemALL();', special_block) + self.assertNotIn('item->SetCount', special_block.split('if(item->GetVnum()==39063)',1)[1]) # 39064: Gaya Market Expansion self.assertIn('if(item->GetVnum()==39064)', special_block) self.assertIn('if(OpenGemSlot())', special_block) - def test_gaya_engine_harness(self): - harness = r''' -#include "src/server/game/src/port_gaya.h" -#include -#include -#include -#include -#include -#include -#include -#include - -struct DummyItem { - uint32_t vnum; - uint32_t count; -}; - -struct DummyChar { - uint32_t pid; - std::map questFlags; - std::vector commands; - std::vector bag; - - uint32_t GetPlayerID() const { return pid; } - int GetQuestFlag(const std::string& key) const { - auto it = questFlags.find(key); - return it == questFlags.end() ? 0 : it->second; - } - void SetQuestFlag(const std::string& key, int val) { - questFlags[key] = val; - } - void SetPoint(int, int) {} - void PointChange(int, int) {} - void ChatPacket(int, const char* fmt, ...) { - char buf[512]; - va_list ap; - va_start(ap, fmt); - vsnprintf(buf, sizeof(buf), fmt, ap); - va_end(ap); - commands.push_back(buf); - } - void AutoGiveItem(uint32_t vnum, uint32_t count) { - bag.push_back({vnum, count}); - } -}; - -// Implement standalone port_gaya harness -namespace { -std::string s_dir = ""; -std::map> s_items; -} - -void SetDir(const std::string& d) { s_dir = d; } - -bool TestOpenSlot(DummyChar* ch) { - int open = ch->GetQuestFlag("gem.open_slot"); - if (open < 18) { - ch->SetQuestFlag("gem.open_slot", open + 1); - ch->ChatPacket(0, "GemUpdateSlotCount %d", open + 1); - return true; - } - return false; -} - -void TestSaveItems(DummyChar* ch) { - mkdir(s_dir.c_str(), 0755); - char path[256]; - snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID()); - FILE* fp = fopen(path, "w+"); - assert(fp != NULL); - fprintf(fp, "index-vnum-count-price-buyed\n"); - for (const auto& kv : s_items[ch->GetPlayerID()]) { - fprintf(fp, "%u %u %u %d %u\n", kv.first, kv.second.itemVnum, kv.second.itemCount, kv.second.itemPrice, kv.second.itemBuyed ? 1 : 0); - } - fclose(fp); -} - -void TestLoadItems(DummyChar* ch) { - char path[256]; - snprintf(path, sizeof(path), "%s/%u", s_dir.c_str(), ch->GetPlayerID()); - FILE* fp = fopen(path, "r"); - if (!fp) return; - s_items[ch->GetPlayerID()].clear(); - char line[256]; - while (fgets(line, sizeof(line), fp)) { - unsigned slot = 0, vnum = 0, count = 0, buyed = 0; - int price = 0; - if (sscanf(line, "%u %u %u %d %u", &slot, &vnum, &count, &price, &buyed) == 5) { - TGemItem it; - it.itemVnum = vnum; - it.itemCount = count; - it.itemPrice = price; - it.itemBuyed = (buyed != 0); - s_items[ch->GetPlayerID()][(uint8_t)slot] = it; - } - } - fclose(fp); -} - -void TestBuyItem(DummyChar* ch, uint8_t slot) { - auto& map = s_items[ch->GetPlayerID()]; - auto it = map.find(slot); - if (it == map.end()) return; - if (slot >= 9) { - if (ch->GetQuestFlag("gem.open_slot") < (slot - 9) + 1) - return; - } - if (it->second.itemBuyed) return; - int points = ch->GetQuestFlag("gem.points"); - if (points < it->second.itemPrice) return; - ch->SetQuestFlag("gem.points", points - it->second.itemPrice); - it->second.itemBuyed = true; - ch->AutoGiveItem(it->second.itemVnum, it->second.itemCount); - ch->ChatPacket(0, "GemSetBuyedSlot %d 1", slot); - TestSaveItems(ch); -} - -int main(int argc, char** argv) { - assert(argc > 1); - SetDir(argv[1]); - - DummyChar ch; - ch.pid = 42; - ch.SetQuestFlag("gem.points", 500); - - // 1. Initial slot expansion - assert(ch.GetQuestFlag("gem.open_slot") == 0); - assert(TestOpenSlot(&ch)); - assert(ch.GetQuestFlag("gem.open_slot") == 1); - - // Max 18 additional slots (up to 18) - for (int i = 2; i <= 18; ++i) { - assert(TestOpenSlot(&ch)); - assert(ch.GetQuestFlag("gem.open_slot") == i); - } - // Slot 19 should fail - assert(!TestOpenSlot(&ch)); - assert(ch.GetQuestFlag("gem.open_slot") == 18); - - // 2. Set up store items (slot 0 default, slot 9 locked without open_slot >= 1) - s_items[42][0] = {71084, 100, 50, false}; - s_items[42][9] = {72319, 1, 20, false}; - s_items[42][10] = {72320, 1, 20, false}; - TestSaveItems(&ch); - - // 3. Buy item from slot 0 - TestBuyItem(&ch, 0); - assert(ch.GetQuestFlag("gem.points") == 450); - assert(s_items[42][0].itemBuyed == true); - assert(ch.bag.size() == 1 && ch.bag[0].vnum == 71084 && ch.bag[0].count == 100); - - // Cannot buy already bought item - TestBuyItem(&ch, 0); - assert(ch.GetQuestFlag("gem.points") == 450); - assert(ch.bag.size() == 1); - - // 4. Persistence round-trip: reload from disk - s_items[42].clear(); - TestLoadItems(&ch); - assert(s_items[42].size() == 3); - assert(s_items[42][0].itemBuyed == true); - assert(s_items[42][9].itemVnum == 72319); - - // 5. Unlocked slot 9 can be purchased - TestBuyItem(&ch, 9); - assert(ch.GetQuestFlag("gem.points") == 430); - assert(s_items[42][9].itemBuyed == true); - assert(ch.bag.size() == 2 && ch.bag[1].vnum == 72319); - - puts("PASS: gaya slot expansion limit, purchase validation, persistence file io, balance deduction"); - return 0; -} -''' - with tempfile.TemporaryDirectory() as tmp: - src = Path(tmp) / 'test_gaya.cpp' - exe = Path(tmp) / 'test_gaya' - gemdir = Path(tmp) / 'gem' - src.write_text(harness) - subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True) - res = subprocess.run([str(exe), str(gemdir)], capture_output=True, text=True, check=True) - self.assertIn('PASS', res.stdout) if __name__ == '__main__': diff --git a/tests/features/test_gaya_runtime.py b/tests/features/test_gaya_runtime.py new file mode 100644 index 00000000..bf266fed --- /dev/null +++ b/tests/features/test_gaya_runtime.py @@ -0,0 +1,109 @@ +"""Execute the production Gaya unit; SQL, item factory and DB submission are boundaries.""" +import re +import subprocess +import tempfile +import unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] + +class GayaRuntime(unittest.TestCase): + def test_durable_requests_never_mutate_wallet_items_or_paid_catalogue_in_game(self): + body=re.sub(r'^#include[^\n]*\n','',(ROOT/'src/server/game/src/port_gaya.cpp').read_text(),flags=re.M) + harness=r''' +#include "src/server/game/src/port_gaya.h" +#include "src/server/common/gaya_catalog.h" +#include "src/server/common/economy.h" +#include "src/server/common/utils.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +using BYTE=uint8_t; +constexpr int POINT_GEM=248,CHAT_TYPE_COMMAND=1,CHAT_TYPE_INFO=2,DRAGON_SOUL_INVENTORY=2,INVENTORY=1,ER_NO_SUCH_TABLE=1146; +bool questLoaded=true,questRunning=false; +namespace quest {struct PC{bool IsLoaded(){return questLoaded;}bool IsRunning(){return questRunning;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};} +struct PortItemExtra{uint8_t bytes[69]={};}; +struct Attr{uint8_t bType=0;int16_t sValue=0;}; +struct Item {unsigned id=0,vnum=0,count=1;bool skip=false,locked=false;PortItemExtra extra;Attr attrs[7]; + unsigned GetID(){return id;}unsigned GetOriginalVnum(){return vnum;}unsigned GetCount(){return count;} + void SetSkipSave(bool v){skip=v;}bool isLocked(){return locked;}bool IsExchanging(){return false;} + int32_t GetSocket(unsigned i){return static_cast(i+10);}const Attr* GetAttributes(){return attrs;} + const PortItemExtra& GetPortExtra(){return extra;} +};using LPITEM=Item*; +struct CHARACTER { + unsigned pid=1;int balance=500,open=0,points=500,left=0,refreshItems=2;bool itemLoaded=true,busy=false; + Item consumable;std::vector messages; + int GetQuestFlag(const char* k){return std::string(k)=="gem.points"?balance:std::string(k)=="gem.left_time"?left:open;} + void SetQuestFlag(const char* k,int n){if(std::string(k)=="gem.points")balance=n;else if(std::string(k)=="gem.left_time")left=n;else open=n;} + void SetPoint(int,int n){points=n;}void PointChange(int,int){}unsigned GetPlayerID(){return pid;} + void ChatPacket(int,const char* fmt,...){char out[1024];va_list ap;va_start(ap,fmt);vsnprintf(out,sizeof(out),fmt,ap);va_end(ap);messages.emplace_back(out);} + bool CanHandleItem(){return !busy;}bool IsDead(){return false;}bool IsStun(){return false;}bool IsWarping(){return false;} + bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;} + bool IsItemLoaded(){return itemLoaded;}bool IsPC(){return true;}bool GetDesc(){return true;} + int CountSpecifyItem(int){return refreshItems;}Item* FindSpecifyItem(unsigned vnum){consumable.id=vnum;return refreshItems?&consumable:nullptr;} + int GetGem()const;void ChangeGem(int);bool OpenGemSlot();bool RefreshGemALL(bool=false);void RefreshGemPlayer();void BuyGemItem(BYTE); +}; +struct ITEM_MANAGER {bool failCreate=false;unsigned next=1000,created=0,destroyed=0; + static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + Item* CreateItem(unsigned vnum,unsigned count){if(failCreate)return nullptr;Item* i=new Item;i->id=next++;i->vnum=vnum;i->count=std::min(count,200u);++created;return i;} + void Destroy(Item* i){assert(i->skip);++destroyed;delete i;} +}; +#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i) +#define sys_err(...) ((void)0) +#define ACMD(name) void name(CHARACTER* ch,const char* argument,int cmd=0,int subcmd=0) +bool failRng=false;unsigned draws=0;int number(int low,int high){return !failRng && (++draws%101==0)?high:low;} +std::vector requests;bool queueReady=true; +bool PortEconomySubmit(CHARACTER*,PortEconomy::Request& r){if(!queueReady)return false;requests.push_back(r);return true;} +using MYSQL_ROW=char**; +struct MYSQL_RES {char* row[3];unsigned long lengths[3];}; +MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){return r->row;}const unsigned long* mysql_fetch_lengths(MYSQL_RES* r){return r->lengths;} +std::string sqlGeneration="9";bool sqlCatalogue=false;unsigned sqlError=0;PortEconomy::Offer sqlOffers[27]; +struct SQLResult {uint64_t uiNumRows=0;MYSQL_RES* pSQLResult=nullptr;}; +struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;std::string generation=sqlGeneration,deadline="2000000000"; + SQLResult* Get(){return &result;} + SQLMsg(){if(sqlError){uiSQLErrno=sqlError;return;}if(!sqlCatalogue){uiSQLErrno=ER_NO_SUCH_TABLE;return;}result.uiNumRows=1;result.pSQLResult=&res;res.row[0]=&generation[0];res.row[1]=&deadline[0];res.row[2]=reinterpret_cast(sqlOffers);res.lengths[0]=1;res.lengths[1]=10;res.lengths[2]=sizeof(sqlOffers);} +}; +struct DBManager {static DBManager& instance(){static DBManager m;return m;}SQLMsg* DirectQuery(const char* q,...){auto* msg=new SQLMsg;if(std::string(q).find("information_schema")!=std::string::npos&&!sqlError){msg->uiSQLErrno=0;msg->generation=sqlCatalogue?"1":"0";msg->result.uiNumRows=1;msg->result.pSQLResult=&msg->res;msg->res.row[0]=msg->generation.data();}return msg;}}; +''' + main=r''' +int main(int argc,char** argv){ + std::string dir=argv[1];PortGayaSetDirectory(dir);CHARACTER ch; + assert(ch.RefreshGemALL(true));assert(s_playerGayaItems[1].size()==27 && requests.empty()); + auto& offers=s_playerGayaItems[1];offers[0]={19,2000,50,false};assert(PortGayaSaveItems(&ch));int original=ch.left; + auto unchanged=[&](){assert(ch.balance==500 && ch.points==500 && !s_playerGayaItems[1][0].itemBuyed && ch.left==original);}; + ch.itemLoaded=false;ch.BuyGemItem(0);assert(requests.empty());ch.itemLoaded=true;questLoaded=false;ch.BuyGemItem(0);assert(requests.empty());questLoaded=true; + questRunning=true;ch.BuyGemItem(0);assert(requests.empty());questRunning=false;ch.busy=true;ch.BuyGemItem(0);assert(requests.empty());ch.busy=false; + ITEM_MANAGER::instance().failCreate=true;ch.BuyGemItem(0);assert(requests.empty());ITEM_MANAGER::instance().failCreate=false; + do_gem(&ch,"buy 256");do_gem(&ch,"buy -1");do_gem(&ch,"buy 0 junk");ch.BuyGemItem(9);assert(requests.empty()); + ch.BuyGemItem(0);unchanged();assert(requests.size()==1);const auto buy=requests.back();assert(buy.operation==PortEconomy::GayaBuy && buy.rewardCount==10 && buy.generation==0); + unsigned count=0;for(unsigned i=0;i 0 && GetGold() > GOLD_MAX_64 - amount)", char_cpp) - self.assertIn("else if (amount < 0 && -amount > GetGold())", char_cpp) - self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", char_cpp) + self.assertTrue("PortGoldCanChange(GetGold(),amount,GOLD_MAX_64)" in char_cpp) + self.assertNotIn("else if (amount < 0 && -amount > GetGold())", char_cpp) + self.assertIn("!PortGoldCanChange(nTotalMoney, price, GOLD_MAX_64)", char_cpp) exchange_cpp = read_server_file("src/server/game/src/exchange.cpp") self.assertIn("if (m_lGold > 0 && victim->GetGold() > GOLD_MAX_64 - m_lGold)", exchange_cpp) - self.assertIn("DWORD dwPacketGold = (m_lGold > 2000000000LL) ? 2000000000 : (DWORD)m_lGold;", exchange_cpp) + self.assertTrue("int64_t dwPacketGold = m_lGold;" in exchange_cpp) shop_cpp = read_server_file("src/server/game/src/shop_manager.cpp") - self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", shop_cpp) + self.assertIn("!PortGoldCanChange(ch->GetGold(), dwPrice, GOLD_MAX_64)", shop_cpp) offlineshop_cpp = read_server_file("src/server/game/src/offlineshop_manager.cpp") self.assertIn("if (GOLD_MAX_64 <= nTotalMoney)", offlineshop_cpp) input_main_cpp = read_server_file("src/server/game/src/input_main.cpp") self.assertIn("if (ch->GetGold() >= GOLD_MAX_64)", input_main_cpp) - self.assertIn("if (GOLD_MAX_64 <= nTotalGold)", input_main_cpp) + self.assertTrue("pinfo->arg1 > GOLD_MAX_64-" in input_main_cpp) guild_cpp = read_server_file("src/server/game/src/guild.cpp") self.assertIn("if (m_data.gold > GOLD_MAX_64 - iGold)", guild_cpp) self.assertIn("if (ch->GetGold() > GOLD_MAX_64 - iGold)", guild_cpp) - self.assertIn("pack_sub.gold\t= (m_data.gold > 2000000000LL) ? 2000000000 : (DWORD)m_data.gold;", guild_cpp) - self.assertIn("int packet_gold = (iGold > 2000000000LL) ? 2000000000 : (int)iGold;", guild_cpp) + self.assertTrue("pack_sub.gold\t= m_data.gold;" in guild_cpp) + self.assertTrue("int64_t packet_gold = iGold;" in guild_cpp) def test_database_persistence_and_queries(self): cmp_cpp = read_server_file("src/server/db/src/ClientManagerPlayer.cpp") @@ -129,17 +129,15 @@ class TestGold64System(unittest.TestCase): def test_sql_migration_and_rollback_scripts(self): migrate_sql = read_server_file("tools/gold64/migrate_gold64.sql") - self.assertIn("ALTER TABLE `player` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql) - self.assertIn("ALTER TABLE `safebox` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql) - self.assertIn("ALTER TABLE `guild` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;", migrate_sql) + self.assertIn("SIGNAL SQLSTATE", migrate_sql) + planner=read_server_file("tools/gold64/migrate_gold64.py") + self.assertIn("'player_deleted'", planner) + self.assertIn("'money_log'", planner) + self.assertNotIn("UPDATE `player` SET `gold`", planner) rollback_sql = read_server_file("tools/gold64/rollback_gold64.sql") - self.assertIn("UPDATE `player` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql) - self.assertIn("UPDATE `safebox` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql) - self.assertIn("UPDATE `guild` SET `gold` = 2000000000 WHERE `gold` > 2000000000;", rollback_sql) - self.assertIn("ALTER TABLE `player` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql) - self.assertIn("ALTER TABLE `safebox` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql) - self.assertIn("ALTER TABLE `guild` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;", rollback_sql) + self.assertNotRegex(rollback_sql, r'(?im)^\s*(UPDATE|ALTER|DELETE|TRUNCATE)\b') + self.assertIn("compatible", rollback_sql) def test_client_python_64bit_bridging(self): if os.path.exists(CLIENT_ROOT): @@ -172,26 +170,12 @@ class TestGold64System(unittest.TestCase): static const int64_t GOLD_MAX_64 = 2000000000000000LL; static const int64_t LEGACY_GOLD_MAX = 2000000000LL; +#include "src/server/common/gold_bounds.h" struct MockCharacter { int64_t gold; - - MockCharacter(int64_t initial_gold = 0) : gold(initial_gold) {} - - bool PointChange(int64_t amount) { - if (amount > 0 && gold > GOLD_MAX_64 - amount) { - gold = GOLD_MAX_64; - return false; - } else if (amount < 0 && -amount > gold) { - gold = 0; - return false; - } - gold += amount; - return true; - } - - int32_t GetLegacyClampedGold() const { - return (gold > LEGACY_GOLD_MAX) ? (int32_t)LEGACY_GOLD_MAX : (int32_t)gold; - } + MockCharacter(int64_t value=0):gold(value){} + bool PointChange(int64_t delta){if(!PortGoldCanChange(gold,delta,GOLD_MAX_64))return false;gold+=delta;return true;} + int32_t GetLegacyClampedGold(){return gold>LEGACY_GOLD_MAX?LEGACY_GOLD_MAX:gold;} }; int main() { @@ -225,13 +209,13 @@ int main() { MockCharacter richPlayer(GOLD_MAX_64 - 1000LL); bool overflowBlocked = richPlayer.PointChange(2000LL); assert(!overflowBlocked); - assert(richPlayer.gold == GOLD_MAX_64); + assert(richPlayer.gold == GOLD_MAX_64 - 1000LL); // 4. Underflow protection MockCharacter poorPlayer(500LL); bool underflowBlocked = poorPlayer.PointChange(-1000LL); assert(!underflowBlocked); - assert(poorPlayer.gold == 0); + assert(poorPlayer.gold == 500); // 5. Cold restart persistence (100 billion gold) int64_t originalGold = 100000000000LL; // 100B @@ -264,7 +248,7 @@ int main() { with open(src_file, "w") as f: f.write(cxx_code) - compile_cmd = ["clang++", "-std=c++17", "-O2", src_file, "-o", bin_file] + compile_cmd = ["clang++", "-std=c++17", "-I"+SERVER_ROOT, "-O2", src_file, "-o", bin_file] res = subprocess.run(compile_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) self.assertEqual(res.returncode, 0, f"Compilation failed: {res.stderr}") diff --git a/tests/features/test_itemshop_durable.py b/tests/features/test_itemshop_durable.py index b96ec3cb..eb8a041e 100644 --- a/tests/features/test_itemshop_durable.py +++ b/tests/features/test_itemshop_durable.py @@ -29,229 +29,63 @@ class ItemShopDurableTest(unittest.TestCase): def test_game_durable_log_and_recovery(self): harness = r''' -#include "src/server/common/ava2_itemshop.h" -#include -#include -#include -#include -#include -#include #include -#include - -static std::string s_pointLogPath = ""; -struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; }; -static std::map pendingPoints; -static std::vector dispatchedPackets; - -void Ava2PointDropSetLogPath(const std::string& path) { s_pointLogPath = path; } -const std::string& Ava2PointDropGetLogPath() { return s_pointLogPath; } -size_t Ava2PointPendingCount() { return pendingPoints.size(); } - -bool AppendDurableIntent(const Ava2ShopRequest& r) { - if (s_pointLogPath.empty()) return false; - size_t slash = s_pointLogPath.rfind('/'); - if (slash != std::string::npos) { - std::string dir = s_pointLogPath.substr(0, slash); - mkdir(dir.c_str(), 0755); - } - FILE* fp = fopen(s_pointLogPath.c_str(), "a"); - if (!fp) return false; - int res = fprintf(fp, "INTENT v1 %s %u %u %u %u %u %lld\n", - r.token, r.account, r.player, r.product, r.count, r.expectedVnum, (long long)time(0)); - if (res < 0) { fclose(fp); return false; } - if (fflush(fp) != 0) { fclose(fp); return false; } - if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } - fclose(fp); - return true; -} - -bool AppendDurableDone(const char* token, uint8_t status, uint32_t granted, int64_t balance) { - if (s_pointLogPath.empty()) return false; - FILE* fp = fopen(s_pointLogPath.c_str(), "a"); - if (!fp) return false; - int res = fprintf(fp, "DONE v1 %s %u %u %lld %lld\n", - token, (unsigned)status, (unsigned)granted, (long long)balance, (long long)time(0)); - if (res < 0) { fclose(fp); return false; } - if (fflush(fp) != 0) { fclose(fp); return false; } - if (fsync(fileno(fp)) != 0) { fclose(fp); return false; } - fclose(fp); - return true; -} - -void CompactDurableLog() { - if (s_pointLogPath.empty()) return; - FILE* fp = fopen(s_pointLogPath.c_str(), "r"); - if (!fp) return; - std::map uncompleted; - char line[256]; - while (fgets(line, sizeof(line), fp)) { - char op[16] = {}, ver[16] = {}, token[64] = {}; - if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { - if (strcmp(op, "INTENT") == 0) { - Ava2ShopRequest r = {}; - r.operation = 3; - unsigned long long t = 0; - if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", - r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { - uncompleted[token] = r; - } - } else if (strcmp(op, "DONE") == 0) { - uncompleted.erase(token); - } - } - } - fclose(fp); - - std::string tmpPath = s_pointLogPath + ".tmp"; - FILE* out = fopen(tmpPath.c_str(), "w"); - if (!out) return; - for (const auto& kv : uncompleted) { - const auto& r = kv.second; - fprintf(out, "INTENT v1 %s %u %u %u %u %u 0\n", - r.token, r.account, r.player, r.product, r.count, r.expectedVnum); - } - fflush(out); - fsync(fileno(out)); - fclose(out); - rename(tmpPath.c_str(), s_pointLogPath.c_str()); -} - -void Ava2PointDropInit() { - if (s_pointLogPath.empty()) return; - FILE* fp = fopen(s_pointLogPath.c_str(), "r"); - if (!fp) return; - std::map uncompleted; - char line[256]; - while (fgets(line, sizeof(line), fp)) { - char op[16] = {}, ver[16] = {}, token[64] = {}; - if (sscanf(line, "%15s %15s %63s", op, ver, token) >= 3) { - if (strcmp(op, "INTENT") == 0) { - Ava2ShopRequest r = {}; - r.operation = 3; - unsigned long long t = 0; - if (sscanf(line, "%*s %*s %32s %u %u %u %u %u %llu", - r.token, &r.account, &r.player, &r.product, &r.count, &r.expectedVnum, &t) >= 6) { - uncompleted[token] = r; - } - } else if (strcmp(op, "DONE") == 0) { - uncompleted.erase(token); - } - } - } - fclose(fp); - - for (const auto& kv : uncompleted) { - const auto& r = kv.second; - if (pendingPoints.find(r.token) == pendingPoints.end()) { - PendingPoints pending = {r, 0, 1, time(0) + 2}; - pendingPoints.emplace(r.token, pending); - dispatchedPackets.push_back(r); - } - } -} - -bool HandlePointReply(const char* token, uint8_t status, uint32_t amount, int64_t balance) { - auto found = pendingPoints.find(token); - if (found == pendingPoints.end()) return false; - if (status == 6 || status == 8) return true; // Transient, retry - AppendDurableDone(token, status, amount, balance); - pendingPoints.erase(found); - return true; -} - -void SimulateRetryTick(time_t now) { - for (auto it = pendingPoints.begin(); it != pendingPoints.end();) { - auto& p = it->second; - if (now < p.next) { ++it; continue; } - if (p.attempts >= 12) { - // Throttled retry: reschedule, NEVER erase - p.next = now + 60; - dispatchedPackets.push_back(p.request); - ++p.attempts; - ++it; - continue; - } - dispatchedPackets.push_back(p.request); - ++p.attempts; - p.next = now + 10; - ++it; - } -} - -int main(int argc, char** argv) { - assert(argc > 1); - std::string logFile = argv[1]; - Ava2PointDropSetLogPath(logFile); - - // 1. Record two intents and ensure both sync to disk - Ava2ShopRequest r1 = {}; - r1.operation = 3; r1.account = 100; r1.player = 1001; r1.product = 101; r1.count = 5; r1.expectedVnum = 120; - strcpy(r1.token, "11111111111111111111111111111111"); - - Ava2ShopRequest r2 = {}; - r2.operation = 3; r2.account = 200; r2.player = 2001; r2.product = 8001; r2.count = 8; r2.expectedVnum = 120; - strcpy(r2.token, "22222222222222222222222222222222"); - - assert(AppendDurableIntent(r1)); - assert(AppendDurableIntent(r2)); - pendingPoints[r1.token] = {r1, 1, 1, 0}; - pendingPoints[r2.token] = {r2, 2, 1, 0}; - - // 2. Complete r1 successfully - assert(HandlePointReply(r1.token, 0, 5, 50)); - assert(pendingPoints.find(r1.token) == pendingPoints.end()); - assert(pendingPoints.find(r2.token) != pendingPoints.end()); - - // 3. Transient error for r2 - should remain pending - assert(HandlePointReply(r2.token, 6, 0, 0)); - assert(pendingPoints.find(r2.token) != pendingPoints.end()); - - // 4. Retry throttling after 12 attempts - never erase! - pendingPoints[r2.token].attempts = 12; - pendingPoints[r2.token].next = 0; - SimulateRetryTick(100); - assert(pendingPoints.find(r2.token) != pendingPoints.end()); - assert(pendingPoints[r2.token].next == 160); // 60s throttle interval - - // 5. Simulate cold reboot / crash recovery - pendingPoints.clear(); - dispatchedPackets.clear(); - assert(Ava2PointPendingCount() == 0); - - Ava2PointDropInit(); - // r1 was DONE, r2 was NOT DONE -> r2 must be recovered with exact token! - assert(Ava2PointPendingCount() == 1); - assert(pendingPoints.find(r2.token) != pendingPoints.end()); - assert(pendingPoints[r2.token].request.account == 200); - assert(pendingPoints[r2.token].request.product == 8001); - assert(pendingPoints[r2.token].request.count == 8); - assert(dispatchedPackets.size() == 1); - assert(strcmp(dispatchedPackets[0].token, r2.token) == 0); - - // 6. Compact durable log - CompactDurableLog(); - FILE* fp = fopen(logFile.c_str(), "r"); - assert(fp != NULL); - char buf[1024]; - size_t lines = 0; - while (fgets(buf, sizeof(buf), fp)) lines++; - fclose(fp); - assert(lines == 1); // Only r2 uncompleted line remains in compacted log - - puts("PASS: durable point queue, atomic disk commit, throttle retention, crash recovery, compaction"); - return 0; +#include +static bool failWrite=false,failSync=false; +static ssize_t TestWrite(int fd,const void* data,size_t n){if(failWrite){errno=ENOSPC;return -1;}return ::write(fd,data,n);} +static int TestSync(int fd){if(failSync){errno=EIO;return -1;}return ::fsync(fd);} +#define write TestWrite +#define fsync TestSync +#include "src/server/common/point_journal.h" +#undef write +#undef fsync +#include +#include +#include +int main(int argc,char** argv){ + std::string path=argv[1];Ava2ShopRequest request={};request.operation=3;request.account=1;request.player=2;request.product=101;request.count=1;request.expectedVnum=10;strcpy(request.token,"0123456789abcdef0123456789abcdef"); + { + PointJournal journal;std::map pending;assert(journal.Open(path,pending));assert(pending.empty()); + auto invalid=request;invalid.count=0;assert(!journal.Intent(invalid) && journal.Ready()); + invalid=request;memset(invalid.token,'z',32);assert(!journal.Intent(invalid) && journal.Ready()); + assert(!journal.Done(request.token,0,1,-1) && journal.Ready()); + assert(!journal.Done(request.token,255,0,100) && journal.Ready()); + assert(!journal.Done(request.token,2,1,100) && journal.Ready()); + assert(journal.Intent(request)); + PointJournal competitor;assert(!competitor.Open(path,pending)); + failWrite=true;assert(!journal.Done(request.token,0,1,10));assert(!journal.Ready());failWrite=false; + assert(!journal.Intent(request)); // I/O failure latches until repaired/reopened. + } + { + PointJournal journal;std::map pending;assert(journal.Open(path,pending));assert(pending.size()==1);assert(pending.begin()->second.count==1); + assert(journal.Done(request.token,0,1,10)); + } + { + PointJournal journal;std::map pending;assert(journal.Open(path,pending));assert(pending.empty()); + failSync=true;assert(!journal.Intent(request));failSync=false;assert(!journal.Ready()); + } + { + PointJournal journal;std::map pending;assert(journal.Open(path,pending));assert(pending.size()==1); // same durable token, never reroll. + } + {std::ofstream out(path,std::ios::app);out<<"INTENT v2 broken tail";} + { + PointJournal journal;std::map pending;assert(!journal.Open(path,pending));assert(pending.size()==1);assert(!journal.Intent(request)); + } + // A process death after fsync but before sending the request must be recoverable. + const std::string crash=path+".crash";pid_t child=fork();assert(child>=0); + if(child==0){PointJournal j;std::map p;assert(j.Open(crash,p));assert(j.Intent(request));_exit(0);} + int status=0;waitpid(child,&status,0);assert(WIFEXITED(status)&&WEXITSTATUS(status)==0); + {PointJournal j;std::map p;assert(j.Open(crash,p));assert(p.size()==1);assert(j.Done(request.token,0,1,10));} + // Checksums reject a syntactically valid but changed amount; original bytes remain on disk. + {std::fstream out(crash,std::ios::in|std::ios::out);out.seekp(10);out.put('f');} + {PointJournal j;std::map p;assert(!j.Open(crash,p));} + puts("PASS actual point journal: replay, exclusive recovery, ENOSPC/EIO, corrupt tail/checksum, abrupt exit"); } ''' with tempfile.TemporaryDirectory() as tmp: - src = Path(tmp) / 'test_durable.cpp' - exe = Path(tmp) / 'test_durable' - log = Path(tmp) / 'pending.log' - src.write_text(harness) - subprocess.run(['c++', '-std=c++17', '-I' + str(ROOT), str(src), '-o', str(exe)], check=True) - res = subprocess.run([str(exe), str(log)], capture_output=True, text=True, check=True) - self.assertIn('PASS', res.stdout) + src=Path(tmp)/'journal.cpp';exe=Path(tmp)/'journal';src.write_text(harness) + subprocess.run(['c++','-std=c++17','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe),str(Path(tmp)/'pending.log')],check=True) -if __name__ == '__main__': - unittest.main() +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_legacy_item_ids.py b/tests/features/test_legacy_item_ids.py new file mode 100644 index 00000000..1b3b5b9b --- /dev/null +++ b/tests/features/test_legacy_item_ids.py @@ -0,0 +1,60 @@ +"""Actual restart range allocation reserves unmigrated legacy escrow IDs.""" +import subprocess +import tempfile +import unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] + + +class LegacyIDs(unittest.TestCase): + def test_legacy_new_custody_errors_and_overflow(self): + text=(ROOT/'src/server/db/src/ItemIDRangeManager.cpp').read_text(encoding='latin1') + actual=text.split('bool CItemIDRangeManager::BuildRange',1)[1].split('void CItemIDRangeManager::UpdateRange',1)[0] + actual='bool CItemIDRangeManager::BuildRange'+actual + harness=r''' +#include "src/server/common/utils.h" +#include +#include +#include +#include +#include +using DWORD=uint32_t; +using MYSQL_ROW=char**; +struct MYSQL_RES {std::string value;char* fields[1];}; +MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){r->fields[0]=r->value.empty()?nullptr:r->value.data();return r->fields;} +struct SQLResult {unsigned uiNumRows=1;MYSQL_RES* pSQLResult=nullptr;}; +struct SQLMsg {unsigned uiSQLErrno=0;SQLResult result;MYSQL_RES res;SQLMsg(){result.pSQLResult=&res;}SQLResult* Get(){return &result;}}; +constexpr unsigned ER_NO_SUCH_TABLE=1146; +bool legacy=true,economy=true,failed=false;std::string maximum="900",count="0"; +std::string maxQuery; +struct CDBManager {static CDBManager& instance(){static CDBManager m;return m;} + SQLMsg* DirectQuery(const char* q){auto* m=new SQLMsg;std::string sql=q; + if(failed){m->uiSQLErrno=2006;return m;} + if(sql.find("information_schema")!=std::string::npos)m->res.value=legacy?"1":"0"; + else if(sql.find("SELECT version")!=std::string::npos){m->res.value="1";if(!economy)m->uiSQLErrno=ER_NO_SUCH_TABLE;} + else if(sql.find("SELECT MAX")!=std::string::npos){m->res.value=maximum;maxQuery=sql;} + else m->res.value=count; + return m;}}; +const char* GetTablePostfix(){return "";} +#define sys_log(...) ((void)0) +struct TItemIDRangeTable {DWORD dwMin=0,dwMax=0,dwUsableItemIDMin=0;}; +struct CItemIDRangeManager {static constexpr DWORD cs_dwMinimumRemainCount=10000;bool BuildRange(DWORD,DWORD,TItemIDRangeTable&);}; +''' + main=r''' +int main(){CItemIDRangeManager manager;TItemIDRangeTable range; + assert(manager.BuildRange(1,100000,range)&&range.dwUsableItemIDMin==901); + assert(maxQuery.find("offline_shop_item")!=std::string::npos && maxQuery.find("port_economy_custody")!=std::string::npos && maxQuery.find("port_economy_item_reservations")!=std::string::npos); + economy=false;assert(manager.BuildRange(1,100000,range));assert(maxQuery.find("offline_shop_item")!=std::string::npos && maxQuery.find("port_economy_custody")==std::string::npos); + legacy=false;assert(manager.BuildRange(1,100000,range));assert(maxQuery.find("offline_shop_item")==std::string::npos); + maximum="";assert(manager.BuildRange(1,100000,range)&&range.dwUsableItemIDMin==1); + maximum="4294967295";assert(!manager.BuildRange(1,UINT32_MAX,range)); + maximum="4294967296";assert(!manager.BuildRange(1,UINT32_MAX,range)); + maximum="100";count="1";assert(!manager.BuildRange(1,100000,range)); + count="bad";assert(!manager.BuildRange(1,100000,range)); + failed=true;assert(!manager.BuildRange(1,100000,range)); +} +''' + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);(p/'probe.cpp').write_text(harness+actual+main) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-I'+str(ROOT),str(p/'probe.cpp'),'-o',str(p/'probe')],check=True) + subprocess.run([str(p/'probe')],check=True) diff --git a/tests/features/test_magic_reduction.py b/tests/features/test_magic_reduction.py new file mode 100644 index 00000000..3215ded0 --- /dev/null +++ b/tests/features/test_magic_reduction.py @@ -0,0 +1,66 @@ +"""Verify the disabled candidate formula and preserve default combat dispatch.""" +from pathlib import Path +import re +import subprocess +import tempfile +import unittest + +SRC=Path(__file__).resolve().parents[2]/'src/server/game/src' + + +class MagicReductionTests(unittest.TestCase): + def test_source_formula_boundaries_and_production_dispatch(self): + wrappers=[] + for filename,name in (('char_skill.cpp','skill'),('char_battle.cpp','magic_attack')): + text=(SRC/filename).read_bytes().decode('latin1') + branch=re.search(r'#ifdef ENABLE_MAGIC_REDUCTION_SYSTEM\s+(iDam = PortMagicDamageAfterResistance\(.*?\);)\s+#else\s+(iDam = iDam \* \(100 - .*?;)\s+#endif',text,re.S) + self.assertIsNotNone(branch, filename+' must preserve default resistance formula') + statement=branch.group(1) + wrappers.append('int '+name+'(int iDam, Actor* attacker, Actor* victim) {' + 'Actor *m_pkChr=attacker,*m_me=attacker,*pkChrVictim=victim,*pkVictim=victim;' + +statement+' return iDam;}') + wrappers.append('int default_'+name+'(int iDam, Actor* pkChrVictim, Actor* pkVictim) {' + +branch.group(2)+' return iDam;}') + for path in (SRC.parent.parent/'common').glob('*.h'): + self.assertIsNone(re.search(rb'^\s*#\s*define\s+ENABLE_MAGIC_REDUCTION_SYSTEM\b',path.read_bytes(),re.M),str(path)) + code=r''' +#include +#include +#include +#include "port_magic_reduction.h" +enum{POINT_RESIST_MAGIC=77,POINT_RESIST_MAGIC_REDUCTION=144,JOB_SURA=2}; +struct Actor {int job=0;int64_t resistance=0,reduction=0; + int GetJob(){return job;}int64_t GetPoint(int type){return type==POINT_RESIST_MAGIC?resistance:reduction;}}; +'''+ '\n'.join(wrappers)+r''' +int main(){ + struct Case {int damage;int64_t resist,reduction;bool sura;int expected;}; + const Case cases[]={ + {1000,80,30,false,500},{1000,80,30,true,350}, + {1000,100,0,false,0},{1000,-1,0,false,1000}, + {1000,200,200,false,500},{1000,80,-3,true,200}, + {1000,80,1,true,200},{999,80,3,true,209}, + {1000,10,50,false,1000},{0,80,30,false,0}, + {INT_MAX,0,0,false,INT_MAX},{INT_MIN,0,0,false,INT_MIN}, + {1000,INT64_MAX,INT64_MAX,true,500} + }; + for(const auto& c:cases){ + Actor attacker,victim;attacker.job=c.sura?JOB_SURA:0; + attacker.reduction=c.reduction;victim.resistance=c.resist; + assert(PortMagicDamageAfterResistance(c.damage,c.resist,c.reduction,c.sura)==c.expected); + assert(skill(c.damage,&attacker,&victim)==c.expected); + assert(magic_attack(c.damage,&attacker,&victim)==c.expected); + } + Actor victim;victim.resistance=80; + assert(default_skill(1000,&victim,&victim)==200); + assert(default_magic_attack(1000,&victim,&victim)==200); +} +''' + with tempfile.TemporaryDirectory(prefix='ch5-magic-') as folder: + root=Path(folder);(root/'probe.cpp').write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined', + '-fno-sanitize-recover=all','-I'+str(SRC),str(root/'probe.cpp'), + '-o',str(root/'probe')],check=True) + subprocess.run([str(root/'probe')],check=True) + + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_offline_search_names.py b/tests/features/test_offline_search_names.py new file mode 100644 index 00000000..94439864 --- /dev/null +++ b/tests/features/test_offline_search_names.py @@ -0,0 +1,48 @@ +"""Run the production localized-proto search, without a language handshake stub.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] +class SearchNames(unittest.TestCase): + def test_localized_names_reload_and_bounded_strings(self): + text=(ROOT/'src/server/game/src/offlineshop_search_manager.cpp').read_text() + methods=text[text.index('bool COfflineShopManager::CheckItemNames'):text.index('void COfflineShopManager::SaveInMemory')] + code=r''' +#include +#include +#include +#include +#include +#include +#include +#include +using BYTE=uint8_t;using DWORD=uint32_t;using LPCHARACTER=void*; +struct TItemTable {char szLocaleName[32];DWORD dwVnum;}; +struct ITEM_MANAGER {std::vector tables;static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}const auto& GetTable(){return tables;}}; +struct COfflineShopManager { + std::map>> m_mapItemNames; + bool CheckItemNames(LPCHARACTER,const char*,std::vector&); + void LoadSearchLanguage(); +}; +'''+methods+r''' +int main(){ + COfflineShopManager shop;auto& tables=ITEM_MANAGER::instance().tables; + tables={{{"Dragon Sword"},10},{{"Dragon Sword"},10},{{"é¾�牙"},20},{{""},30}}; + TItemTable full={};memset(full.szLocaleName,'x',sizeof(full.szLocaleName));full.dwVnum=40;tables.push_back(full); + shop.LoadSearchLanguage();std::vector found; + assert(shop.CheckItemNames(&shop,"DRAGON",found) && found==std::vector{10}); + found.clear();assert(shop.CheckItemNames(&shop,"é¾�",found) && found==std::vector{20}); + found.clear();assert(shop.CheckItemNames(&shop,"xxxx",found) && found==std::vector{40}); + assert(!shop.CheckItemNames(nullptr,"Dragon",found));assert(!shop.CheckItemNames(&shop,nullptr,found));assert(!shop.CheckItemNames(&shop,"",found)); + tables={{{"Replacement"},50}};shop.LoadSearchLanguage();found.clear(); + assert(!shop.CheckItemNames(&shop,"Dragon",found));assert(shop.CheckItemNames(&shop,"replace",found) && found==std::vector{50}); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code) + subprocess.run(['c++','-std=c++23','-fsanitize=address,undefined','-fno-sanitize-recover=all',str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + entry=(ROOT/'src/server/game/src/input_db.cpp').read_text(encoding='latin1') + self.assertEqual(entry.count('COfflineShopManager::instance().LoadSearchLanguage();'),2) +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_oxevent_bounds.py b/tests/features/test_oxevent_bounds.py new file mode 100644 index 00000000..2d246c19 --- /dev/null +++ b/tests/features/test_oxevent_bounds.py @@ -0,0 +1,63 @@ +"""Exercise actual OX status/quiz functions with timer/notice boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT = Path(__file__).resolve().parents[2] + + +def function(text, signature): + start = text.index(signature) + brace = text.index('{', start) + depth = 1 + end = brace + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +class OXBounds(unittest.TestCase): + def test_equal_and_excess_level_and_untruncated_status(self): + source = (ROOT/'src/server/game/src/OXEvent.cpp').read_bytes().decode('latin1') + actual = '\n'.join(function(source, s) for s in + ('OXEventStatus COXEventManager::GetStatus()', + 'bool COXEventManager::Quiz(')) + fixture = r''' +#include +#include +#include +#include +#include +enum OXEventStatus {OXEVENT_FINISH,OXEVENT_OPEN,OXEVENT_CLOSE,OXEVENT_QUIZ,OXEVENT_ERR}; +int flag=0; +namespace quest {struct CQuestManager {static CQuestManager& instance(){static CQuestManager m;return m;}int GetEventFlag(const char*){return flag;}};} +struct OXEventInfoData {bool answer=false;}; +struct Question {const char* Quiz="test";bool answer=true;}; +struct COXEventManager {std::vector> m_vec_quiz;void* m_timedEvent=nullptr;OXEventStatus status=OXEVENT_FINISH; + OXEventStatus GetStatus();bool Quiz(unsigned char,int);void SetStatus(OXEventStatus s){status=s;}}; +int number(int lo,int hi){assert(lo==0 && hi>=0);return hi;} +void SendNoticeMap(const char*,int,bool){} +constexpr int OXEVENT_MAP_INDEX=113; +void event_cancel(void** p){*p=nullptr;} +templateT* AllocEventInfo(){static T data;return &data;} +void* event_create(int,OXEventInfoData*,int){static int event;return &event;} +constexpr int oxevent_timer=1; +#define LC_TEXT(s) "notice" +#define PASSES_PER_SEC(t) (t) +''' + main = r''' +int main(){COXEventManager m;assert(!m.Quiz(0,30)); + for(int value:{-1,4,256,257}){flag=value;assert(m.GetStatus()==OXEVENT_ERR);} + for(int value=0;value<4;++value){flag=value;assert(m.GetStatus()==static_cast(value));} + m.m_vec_quiz={{{"first",true}}};assert(m.Quiz(1,30));assert(m.m_vec_quiz[0].empty()); + m.m_vec_quiz={{{"first",true}},{{"last",false}}};assert(m.Quiz(255,-1)); + assert(m.m_vec_quiz[0].size()==1 && m.m_vec_quiz[1].empty());assert(!m.Quiz(2,30)); + assert(m.Quiz(0,30));assert(m.status==OXEVENT_QUIZ); +} +''' + with tempfile.TemporaryDirectory() as tmp: + path=Path(tmp);(path/'probe.cpp').write_text(fixture+actual+main) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined', + '-fno-sanitize-recover=all',str(path/'probe.cpp'),'-o',str(path/'probe')],check=True) + subprocess.run([str(path/'probe')],check=True) diff --git a/tests/features/test_packet_catalog_bounds.py b/tests/features/test_packet_catalog_bounds.py new file mode 100644 index 00000000..d1eb50f7 --- /dev/null +++ b/tests/features/test_packet_catalog_bounds.py @@ -0,0 +1,88 @@ +"""Exercise the actual dynamic packet builders and SQL catalogue numeric parser.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] +class Bounds(unittest.TestCase): + def native(self,code): + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + def test_dynamic_package_lengths_and_repeated_serialization(self): + text=(ROOT/'src/server/game/src/packet.h').read_text() + bodies=text[text.index('typedef struct SPacketGCHybridCryptKeys'):text.index('#ifdef _IMPROVED_PACKET_ENCRYPTION_',text.index('typedef struct SPacketGCPackageSDB'))] + self.native(r''' +#include +#include +#include +#include +#include +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t; +'''+bodies+r''' +int main(){ + TPacketGCHybridCryptKeys keys;TPacketGCPackageSDB sdb; + assert(keys.KeyStreamLen==0 && !keys.pDataKeyStream && sdb.iStreamLen==0 && !sdb.m_pDataSDBStream); + std::vector data(65528,0xa5);keys.bHeader=0x98;sdb.bHeader=0x99; + for(int count:{-1,INT_MIN,65529,65536,INT_MAX}){ + keys.KeyStreamLen=count;keys.pDataKeyStream=data.data();sdb.iStreamLen=count;sdb.m_pDataSDBStream=data.data(); + assert(!keys.GetStreamSize()&&!sdb.GetStreamSize());assert(!keys.GetStreamData()&&!sdb.GetStreamData());assert(!keys.uDynamicPacketSize&&!sdb.uDynamicPacketSize); + } + for(int count:{0,1,65528}){ + keys.KeyStreamLen=count;keys.pDataKeyStream=data.data();sdb.iStreamLen=count;sdb.m_pDataSDBStream=data.data(); + BYTE* a=keys.GetStreamData();BYTE* b=sdb.GetStreamData();assert(a&&b); + WORD size=0;memcpy(&size,a+1,2);assert(size==7+count && keys.GetStreamSize()==size);memcpy(&size,b+1,2);assert(size==7+count && sdb.GetStreamSize()==size); + assert(a[0]==0x98&&b[0]==0x99);if(count){assert(!memcmp(a+7,data.data(),count)&&!memcmp(b+7,data.data(),count));} + } + keys.pDataKeyStream=nullptr;sdb.m_pDataSDBStream=nullptr;assert(!keys.GetStreamData()&&!sdb.GetStreamData()); +} +''') + def test_discount_and_product_fields_reject_before_narrowing(self): + text=(ROOT/'src/server/db/src/Ava2ItemShop.cpp').read_text();a=text.index('bool productNumber(');b=text.index('const char* fields=',a) + self.native(r''' +#include "src/server/common/ava2_itemshop.h" +#include +#include +#include +#include +#include +using MYSQL_ROW=char**; +'''+text[a:b]+r''' +int main(){ + std::vector fields={"1","19","1000000000000","100","0","2147483647","9223372036854775807","2147483647","0","-1"};std::vector row; + auto parse=[&](){row.clear();for(auto& field:fields)row.push_back(&field[0]);return product(row.data());}; + auto p=parse();assert(p.id==1&&p.vnum==19&&p.discount==100&&p.price==1000000000000LL&&p.sold==INT64_MAX&&p.stock==-1); + for(const char* discount:{"-1","101","256","356","512","junk","100junk","","999999999999999999999999"}){fields[3]=discount;assert(!parse().id);}fields[3]="3"; + for(unsigned i=0;iGetDesc())',a) + actual=text[a:b]+'\nreturn true;\n}\n' + self.native(r''' +#include +#include +#include +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t; +#include "src/server/common/length.h" +using LPCHARACTER=void*; +#define sys_err(...) ((void)0) +struct CItem { WORD m_wCell=0;void* m_pOwner=nullptr;void* GetSectree(){return nullptr;}bool AddToCharacter(LPCHARACTER,TItemPos);}; +'''+actual+r''' +int main(){ + CItem item; + for(WORD cell:{WORD(INVENTORY_MAX_NUM),WORD(BELT_INVENTORY_SLOT_START-1),WORD(BELT_INVENTORY_SLOT_END),WORD(UINT16_MAX)})assert(!item.AddToCharacter(nullptr,TItemPos(INVENTORY,cell))); + assert(!item.AddToCharacter(nullptr,TItemPos(DRAGON_SOUL_INVENTORY,DRAGON_SOUL_INVENTORY_MAX_NUM))); + item.m_wCell=UINT16_MAX;assert(item.AddToCharacter(nullptr,TItemPos(INVENTORY,0))); + assert(item.AddToCharacter(nullptr,TItemPos(INVENTORY,BELT_INVENTORY_SLOT_START))); + assert(item.AddToCharacter(nullptr,TItemPos(DRAGON_SOUL_INVENTORY,DRAGON_SOUL_INVENTORY_MAX_NUM-1))); +} +''') + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_pet_commands_runtime.py b/tests/features/test_pet_commands_runtime.py new file mode 100644 index 00000000..c005f301 --- /dev/null +++ b/tests/features/test_pet_commands_runtime.py @@ -0,0 +1,99 @@ +"""Execute real growing-pet commands with failing creation/placement/actor boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class PetCommands(unittest.TestCase): + def test_consumption_only_after_successful_hatch_or_unlock(self): + source=(ROOT/'src/server/game/src/cmd_general.cpp').read_text(encoding='latin1') + a=source.index('static bool PortPetCommandReady');b=source.index('\n#endif',a);body=source[a:b] + harness=r''' +#include "src/server/common/utils.h" +#include "src/server/common/port_item_extra.h" +#include +#include +#include +#include +#include +#include +#include +bool questLoaded=true,questRunning=false; +namespace quest {struct PC{bool IsLoaded(){return questLoaded;}bool IsRunning(){return questRunning;}};struct CQuestManager{PC pc;static CQuestManager& instance(){static CQuestManager m;return m;}PC* GetPCForce(unsigned){return &pc;}};} +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t; +constexpr int INVENTORY_MAX_NUM=225,CHARACTER_NAME_MAX_LEN=24,ITEM_PET=28,PET_LEVELABLE=1,PET_EGG=0,POINT_GOLD=11,CHAT_TYPE_INFO=1,INVENTORY=1,WEAR_PET=30,POINT_PET_SKILL_INDEX_1=20; +#define _countof(a) (sizeof(a)/sizeof(a[0])) +struct CHARACTER;struct Item;using LPITEM=Item*;using LPCHARACTER=CHARACTER*; +struct TItemPos{int cell;TItemPos(int,int c):cell(c){}}; +struct TItemTable{int bType=ITEM_PET,bSubType=PET_LEVELABLE,bSize=1;}; +struct Item{CHARACTER* owner=nullptr;unsigned vnum=1,count=2;int type=ITEM_PET,sub=PET_EGG;bool locked=false,exchanged=false,equipped=false,skip=false;long sockets[3]={};BYTE attr[7]={};PortItemExtra extra={}; + CHARACTER* GetOwner(){return owner;}unsigned GetCount(){return count;}unsigned GetVnum(){return vnum;}int GetType(){return type;}int GetSubType(){return sub;} + bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanged;}bool isLocked(){return locked;}int GetValue(int){return 53000;} + void SetCount(unsigned n){count=n;}void SetSkipSave(bool b){skip=b;}void SetNewName(const char* s){strncpy(extra.name,s,sizeof(extra.name)-1);} + void SetSocket(unsigned i,long n){if(i<3)sockets[i]=n;else extra.sockets[i-3]=n;}long GetSocket(int i){return sockets[i];} + void SetForceAttribute(unsigned i,BYTE n,int){if(i<7)attr[i]=n;else extra.types[i-7]=n;}int GetAttributeType(int i){return i<7?attr[i]:extra.types[i-7];} + void Save(){}void UpdatePacket(){}bool AddToCharacter(CHARACTER*,TItemPos); +}; +struct CPetActor{Item* summon=nullptr;bool accept=true;int changes=0,evolved=0; + Item* GetSummonItem(){return summon;}void IncreaseEvolve(){++evolved;} + bool PointChange(int point,int){if(!accept)return false;++changes;summon->SetForceAttribute(point-POINT_PET_SKILL_INDEX_1,0,0);return true;} +};using LPPET=CPetActor*; +struct CPetSystem{CPetActor actor;CPetActor* GetNewPet(){return &actor;}BYTE PetItemSocketMax(DWORD){return 14;}}; +struct CHARACTER{int64_t gold=500000;bool itemLoaded=true,busy=false,full=false,failAdd=false;int material=1;std::map items;Item* wear=nullptr;CPetSystem system; + unsigned GetPlayerID(){return 1;}bool IsItemLoaded(){return itemLoaded;}bool IsPC(){return true;}bool GetDesc(){return true;}bool CanHandleItem(){return !busy;}bool IsDead(){return false;}bool IsStun(){return false;}bool IsWarping(){return false;} + bool GetExchange(){return false;}bool GetMyShop(){return false;}bool GetShop(){return false;}bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;} + int64_t GetGold(){return gold;}void PointChange(int,int64_t n){assert(gold+n>=0);gold+=n;} + Item* GetInventoryItem(int p){return items.count(p)?items[p]:nullptr;}int GetEmptyInventory(int){return full?-1:2;} + templatevoid ChatPacket(T...){}Item* GetWear(int){return wear;}CPetSystem* GetPetSystem(){return &system;} + int CountSpecifyItem(unsigned){return material;}void RemoveSpecifyItem(unsigned,unsigned n){assert(material>=int(n));material-=n;} +}; +bool Item::AddToCharacter(CHARACTER* ch,TItemPos pos){if(ch->failAdd)return false;assert(skip && extra.name[0] && sockets[1]==1);for(int j=0;j<15;++j)assert(GetAttributeType(j)==99);owner=ch;ch->items[pos.cell]=this;return true;} +struct ITEM_MANAGER{bool fail=false,validProto=true;TItemTable table;std::vector rewards;int flushed=0; + static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + TItemTable* GetTable(unsigned){return validProto?&table:nullptr;} + Item* CreateItem(unsigned vnum,unsigned count){if(fail)return nullptr;Item* i=new Item;i->vnum=vnum;i->count=count;i->sub=PET_LEVELABLE;rewards.push_back(i);return i;} + void Destroy(Item* i){assert(i->skip && !i->owner);for(auto& p:rewards)if(p==i){p=nullptr;break;}delete i;} + void FlushDelayedSave(Item* i){assert(!i->skip);++flushed;} + ~ITEM_MANAGER(){for(auto* i:rewards)delete i;} +}; +#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i) +#define ACMD(name) void name(LPCHARACTER ch,const char* argument) +bool check_name(const char* name){return strchr(name,'!')==nullptr;} +''' + main=r''' +int main(){ + CHARACTER ch;Item egg,scroll;egg.owner=&ch;scroll.owner=&ch;scroll.vnum=55008;ch.items[0]=&egg;ch.items[1]=&scroll; + auto unchanged=[&](){assert(ch.gold==500000 && egg.count==2 && ch.items.size()==2 && ITEM_MANAGER::instance().flushed==0);}; + for(const char* arg:{"0","0 abc extra","-1 abc","225 abc","4294967296 abc","9223372036854775808 abc","0 !bad","0 aa","0 abcdefghijklmnopqrstuvwxyz"}){do_pet_egg(&ch,arg);unchanged();} + ch.itemLoaded=false;do_pet_egg(&ch,"0 abc");unchanged();ch.itemLoaded=true;questLoaded=false;do_pet_egg(&ch,"0 abc");unchanged();questLoaded=true;questRunning=true;do_pet_egg(&ch,"0 abc");unchanged();questRunning=false; + ch.busy=true;do_pet_egg(&ch,"0 abc");unchanged();ch.busy=false; + egg.exchanged=true;do_pet_egg(&ch,"0 abc");unchanged();egg.exchanged=false; + egg.locked=true;do_pet_egg(&ch,"0 abc");unchanged();egg.locked=false; + ch.full=true;do_pet_egg(&ch,"0 abc");unchanged();ch.full=false; + auto& manager=ITEM_MANAGER::instance();manager.validProto=false;do_pet_egg(&ch,"0 abc");unchanged();manager.validProto=true; + manager.table.bSubType=PET_EGG;do_pet_egg(&ch,"0 abc");unchanged();manager.table.bSubType=PET_LEVELABLE; + manager.fail=true;do_pet_egg(&ch,"0 abc");unchanged();manager.fail=false; + ch.failAdd=true;do_pet_egg(&ch,"0 abc");unchanged();ch.failAdd=false; + do_pet_egg(&ch,"0 abc");assert(ch.gold==400000 && egg.count==1 && ch.items.size()==3 && manager.flushed==1); + Item* pet=ch.items[2];assert(!strcmp(pet->extra.name,"abc") && pet->sockets[1]==1 && pet->sockets[0]>time(0));for(unsigned j=0;j<15;++j)assert(pet->GetAttributeType(j)==99); + pet->locked=true;do_change_name(&ch,"1 2 renamed");assert(ch.gold==400000 && scroll.count==2);pet->locked=false; + for(const char* arg:{"1 2 renamed extra","-1 2 renamed","1 4294967296 renamed"})do_change_name(&ch,arg); + assert(ch.gold==400000 && scroll.count==2 && !strcmp(pet->extra.name,"abc")); + do_change_name(&ch,"1 2 renamed");assert(ch.gold==300000 && scroll.count==1 && !strcmp(pet->extra.name,"renamed")); + ch.wear=pet;pet->equipped=true;pet->sockets[1]=115;ch.system.actor.summon=pet; + ch.system.actor.accept=false;do_pet_add_slot(&ch,"3");assert(ch.material==1 && ch.system.actor.changes==0); + ch.system.actor.accept=true;for(const char* arg:{"3 extra","-1","4294967299","15"})do_pet_add_slot(&ch,arg); + assert(ch.material==1 && ch.system.actor.changes==0); + pet->locked=true;do_pet_add_slot(&ch,"3");assert(ch.material==1);pet->locked=false; + do_pet_add_slot(&ch,"3");assert(ch.material==0 && ch.system.actor.changes==1 && pet->GetAttributeType(3)==0); + pet->sockets[1]=40;ch.busy=true;do_pet_evolve(&ch,"");assert(ch.system.actor.evolved==0);ch.busy=false; + do_pet_evolve(&ch,"");assert(ch.system.actor.evolved==1); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+body+main) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_pet_system.py b/tests/features/test_pet_system.py index dce60d7d..b0647e51 100644 --- a/tests/features/test_pet_system.py +++ b/tests/features/test_pet_system.py @@ -104,17 +104,17 @@ class TestPetSystem(unittest.TestCase): # do_change_name self.assertIn('ACMD(do_change_name)', cg) - self.assertIn('vecArgs.size() < 4', cg) # Out-of-bounds guard + self.assertIn('vecArgs.size() != 4', cg) # Out-of-bounds guard self.assertIn('ch->PointChange(POINT_GOLD, -100000);', cg) self.assertIn('scroll->GetVnum() == 55008', cg) self.assertIn('pet->SetNewName(vecArgs[3].c_str());', cg) # do_pet_egg self.assertIn('ACMD(do_pet_egg)', cg) - self.assertIn('vecArgs.size() < 3', cg) # Out-of-bounds guard + self.assertIn('vecArgs.size() != 3', cg) # Out-of-bounds guard self.assertIn('ch->GetEmptyInventory(pPetTable->bSize)', cg) # Inventory space guard self.assertIn('item->GetType() == ITEM_PET && item->GetSubType() == PET_EGG', cg) - self.assertIn('petItem->SetSocket(0, time(0) + 60 * 60 * 24 * 30);', cg) # 30 days + self.assertIn('petItem->SetSocket(0, static_cast(expiresAt));', cg) # 30 days self.assertIn('petItem->SetSocket(1, 1);', cg) # Level 1 self.assertIn('for (BYTE j = 0; j < 15; ++j)', cg) self.assertIn('petItem->SetForceAttribute(j, 99, 0);', cg) @@ -129,7 +129,7 @@ class TestPetSystem(unittest.TestCase): self.assertIn('ACMD(do_pet_add_slot)', cg) self.assertIn('item->GetSocket(1) < 115', cg) # 115 level requirement self.assertIn('55036', cg) # item requirement - self.assertIn('petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0);', cg) + self.assertIn('if (!petActor->PointChange(POINT_PET_SKILL_INDEX_1 + nextIndex, 0)) return;', cg) def test_legacy_pet_quest_lua_isolated(self): ql_h = source('game/src/questlua.h') diff --git a/tests/features/test_planb_safety.py b/tests/features/test_planb_safety.py new file mode 100644 index 00000000..8188c53e --- /dev/null +++ b/tests/features/test_planb_safety.py @@ -0,0 +1,249 @@ +"""Regression checks execute the helpers and loader used by production code.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT=Path(__file__).resolve().parents[2] + +def module(name,file): + spec=importlib.util.spec_from_file_location(name,ROOT/file) + result=importlib.util.module_from_spec(spec);spec.loader.exec_module(result);return result + +MIG=module('planb_migration','tools/ava2-itemshop/migrate_extended_items.py') +BUILD=module('planb_build','tools/ava2-itemshop/build_isolated.py') + +class PlanBSafety(unittest.TestCase): + def native(self,source): + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(source) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + + def test_gold_extremes_reject_without_mutation(self): + self.native(r''' +#include "src/server/common/gold_bounds.h" +#include +#include +int main(){ + const int64_t limit=2000000000000000LL; + assert(!PortGoldCanChange(500,-1000,limit)); + assert(!PortGoldCanChange(500,INT64_MIN,limit)); + assert(!PortGoldCanChange(500,INT64_MAX,limit)); + assert(PortGoldCanChange(500,-500,limit)); + assert(PortGoldCanChange(limit-1,1,limit)); + assert(!PortGoldCanChange(limit,1,limit)); + int64_t total=123;assert(!PortGoldTotal(INT64_MAX,UINT32_MAX,limit,total));assert(total==123); + assert(PortGoldTotal(5000000000LL,20,limit,total));assert(total==100000000000LL); +} +''') + + def test_shop_quote_and_settlement_preserve_64bit_values(self): + self.native(r''' +#include "src/server/common/shop_economy.h" +#include +#include +int main(){ + const int64_t cap=2000000000000000LL; + int64_t quote=123,tax=0,proceeds=0; + assert(PortShopQuote(100000000000LL,true,cap,quote));assert(quote==300000000000LL); + assert(PortShopSettlement(quote,3,cap,tax,proceeds)); + assert(tax==9000000000LL && proceeds==291000000000LL && tax+proceeds==quote); + assert(PortGoldCanChange(cap-proceeds,proceeds,cap));assert(!PortGoldCanChange(cap-proceeds+1,proceeds,cap)); + assert(PortShopQuote(0,true,cap,quote) && quote==0); + quote=123;assert(!PortShopQuote(INT64_MIN,true,cap,quote) && quote==123); + assert(!PortShopQuote(INT64_MAX,true,cap,quote) && quote==123); + assert(!PortShopQuote(cap/3+1,true,cap,quote) && quote==123); + assert(PortShopSettlement(INT64_MAX,100,INT64_MAX,tax,proceeds));assert(tax==INT64_MAX && proceeds==0); + assert(PortShopSettlement(101,3,cap,tax,proceeds));assert(tax==3 && proceeds==98); + assert(!PortShopSettlement(100,-1,cap,tax,proceeds));assert(!PortShopSettlement(100,101,cap,tax,proceeds)); +} +''') + + def test_actual_item_loader_rejects_corruption_atomically(self): + source=(ROOT/'src/server/db/src/ClientManagerPlayer.cpp').read_text(encoding='latin1') + start=source.index('bool CreateItemTableFromRes(');end=source.index('\nsize_t CreatePlayerSaveQuery',start) + actual=source[start:end] + self.native(r''' +#include "src/server/common/port_item_extra.h" +#include +#include +#include +#include +using DWORD=uint32_t; +struct Attr{uint8_t bType;int16_t sValue;}; +struct TPlayerItem{uint32_t id,window,pos,count,vnum;int32_t alSockets[3];Attr aAttr[7];PortItemExtra extra;uint32_t owner;}; +constexpr int ITEM_ATTRIBUTE_MAX_NUM=7; +struct CClientManager{static CClientManager& instance(){static CClientManager c;return c;}bool ValidateLoadedExtra(const TPlayerItem&,const char*){return true;}}; +struct MYSQL_RES{std::vector> rows;unsigned index=0;std::vector row;}; +using MYSQL_ROW=char**; +int mysql_num_rows(MYSQL_RES* r){return r->rows.size();} +unsigned mysql_num_fields(MYSQL_RES* r){return r->rows[0].size();} +MYSQL_ROW mysql_fetch_row(MYSQL_RES* r){r->row.clear();for(auto& s:r->rows[r->index++])r->row.push_back(&s[0]);return r->row.data();} +templatevoid str_to_number(T& v,const char* s){v=static_cast(strtoll(s,nullptr,10));} +#define sys_err(...) ((void)0) +'''+actual+r''' +int main(){ + MYSQL_RES res;res.rows.resize(2,std::vector(23,"0")); + PortItemExtra extra={};strcpy(extra.name,"pet"); + for(auto& row:res.rows)row[22]=PortItemExtraHex(extra); + res.rows[1][22]="00"; + std::vector output;assert(!CreateItemTableFromRes(&res,&output,7));assert(output.empty()); + res.index=0;res.rows[1][22]=PortItemExtraHex(extra);assert(CreateItemTableFromRes(&res,&output,7));assert(output.size()==2);assert(!strcmp(output[1].extra.name,"pet")); + PortItemExtra before=extra;assert(!PortItemExtraRead("00",extra));assert(!memcmp(&extra,&before,sizeof(extra))); +} +''') + + def test_actual_party_gold_distribution_is_all_or_nothing_at_cap(self): + source=(ROOT/'src/server/game/src/char_item.cpp').read_text(encoding='latin1') + start=source.index('\tstruct FCountNearMember') + method=source.index('bool CHARACTER::GiveGold(int64_t iAmount)') + end=source.index('\nbool CHARACTER::PickupItem',method) + helpers='namespace NPartyPickupDistribute {\n'+source[start:method] + self.native(r''' +#include "src/server/common/gold_bounds.h" +#include +#include +#include +constexpr int64_t GOLD_MAX_64=2000000000000000LL; +constexpr int POINT_GOLD=11,PARTY_DEFAULT_RANGE=5000; +struct Party; +struct CHARACTER{int64_t balance=0;Party* party=nullptr;int64_t GetGold(){return balance;}Party* GetParty(){return party;}int GetX(){return 0;}int GetY(){return 0;}const char* GetName(){return "test";}void PointChange(int,int64_t n,bool){assert(PortGoldCanChange(balance,n,GOLD_MAX_64));balance+=n;}bool GiveGold(int64_t);}; +using LPCHARACTER=CHARACTER*;using LPPARTY=Party*; +struct Party{std::vector members;templatevoid ForEachOnlineMember(F& f){for(auto* c:members)f(c);}}; +inline int DISTANCE_APPROX(int x,int y){return abs(x)+abs(y);} +inline bool LC_IsBrazil(){return false;} +struct LogManager{static LogManager& instance(){static LogManager m;return m;}templatevoid CharLog(T...){};}; +#define sys_log(...) ((void)0) +'''+helpers+source[method:end]+r''' +int main(){ + CHARACTER a,b;Party p;p.members={&a,&b};a.party=&p;b.party=&p; + b.balance=GOLD_MAX_64; + assert(!a.GiveGold(100));assert(a.balance==0&&b.balance==GOLD_MAX_64); + b.balance=0;assert(a.GiveGold(10000000000LL));assert(a.balance==5000000000LL&&b.balance==5000000000LL); + a.party=nullptr;a.balance=GOLD_MAX_64;assert(!a.GiveGold(1));assert(a.balance==GOLD_MAX_64); +} +''') + + def test_real_64bit_integer_parser(self): + self.native(r''' +#include "src/server/common/utils.h" +#include +#include +int main(){long long v=7;unsigned long long u=7; + assert(str_to_number(v,"-9223372036854775808")&&v==LLONG_MIN); + assert(str_to_number(v,"5000000000")&&v==5000000000LL); + assert(!str_to_number(v,"9223372036854775808")&&v==5000000000LL); + assert(!str_to_number(v,"123oops")); + assert(!str_to_number(u,"-1")&&u==7); + assert(!str_to_number(u," -1")&&u==7); + assert(!str_to_number(u,"18446744073709551616")&&u==7); +} +''') + + def test_migration_identity_checksum_and_column_definition(self): + identity=['player_sb','host','3306','1','uuid'] + plan={'version':2,'target':identity,'items':[[1,'EQUIPMENT',32,40,123,10,1,'']],'quickslots':[],'item_state':{'1':'0'*64}} + plan['sha256']=MIG.plan_digest(plan);MIG.validate_plan(plan,identity) + with self.assertRaises(RuntimeError):MIG.validate_plan(plan,identity[:-1]+['different']) + plan['items'][0][6]=2 + with self.assertRaises(RuntimeError):MIG.validate_plan(plan,identity) + good=[['port_extra','varbinary(69)','NO','','','']] + self.assertTrue(MIG.validate_extra_schema(good)) + for name in ('blob','varchar(69)','varbinary(68)'): + with self.assertRaises(RuntimeError):MIG.validate_extra_schema([['port_extra',name,'NO','','','']]) + with tempfile.TemporaryDirectory() as tmp: + path=Path(tmp)/'plan.json';MIG.atomic_json(path,plan) + self.assertEqual(json.loads(path.read_text()),plan) + self.assertEqual(path.stat().st_mode & 0o777,0o600) + + def test_real_migration_control_flow_recovers_without_double_shift(self): + # This exercises main/SQL ordering, not MySQL's own transaction or DDL behavior. + from unittest.mock import patch + from types import SimpleNamespace + backend={'pos':32,'done':False,'crash':True,'updates':0,'owner':10} + def execute(command,**kwargs): + q=kwargs['input'] + rows=[] + if q.startswith('SELECT DATABASE()'):rows=[['player_sb','host','3306','1','uuid']] + elif q.startswith('SHOW COLUMNS'):rows=[['port_extra','varbinary(69)','NO','','','']] + elif q.startswith('SELECT name FROM mt_migration'): + rows=[['ava2-shop-wear-40']] if backend['done'] else [] + elif q.startswith('SELECT id,window,pos,vnum'):rows=[['1','EQUIPMENT',str(backend['pos']),'123',str(backend['owner']),'1','','0'*64]] + elif q.startswith('SELECT window,pos,vnum'):rows=[['EQUIPMENT',str(backend['pos']),'123',str(backend['owner']),'1','','0'*64]] + elif q.startswith('SELECT pos FROM item'):rows=[[str(backend['pos'])]] + elif q.startswith('UPDATE item SET'): + backend['updates']+=1;backend['pos']=40 + if backend['crash']: + backend['crash']=False + raise subprocess.CalledProcessError(1,command) + elif q.startswith('INSERT IGNORE INTO mt_migration(name'):backend['done']=True + elif q.startswith(('CREATE TABLE','INSERT IGNORE INTO mt_migration_target','SELECT i.id','SELECT id FROM item WHERE','SELECT id,HEX(quickslot)')):pass + else:raise AssertionError('Unexpected SQL: '+q) + return SimpleNamespace(stdout=''.join('\t'.join(r)+'\n' for r in rows)) + with tempfile.TemporaryDirectory() as tmp: + plan=Path(tmp)/'plan.json';args=['migrate','--player','player_sb','--plan',str(plan),'--apply','--offline','--backup-id','backup-1'] + with patch.object(MIG.subprocess,'run',side_effect=execute),patch('sys.argv',args): + with self.assertRaises(subprocess.CalledProcessError):MIG.main() + self.assertTrue(plan.exists());self.assertFalse(backend['done']);self.assertEqual(backend['pos'],40) + MIG.main();self.assertTrue(backend['done']);self.assertEqual(backend['pos'],40) + backend['owner']=99;before=backend['updates'] + with self.assertRaises(RuntimeError):MIG.main() + self.assertEqual(backend['updates'],before) + + def test_fresh_build_binding_dependencies_and_warnings(self): + with tempfile.TemporaryDirectory() as tmp: + base=Path(tmp);source=base/'source';out=base/'output' + for part in ('game','db'): + d=source/'server'/part/'src';d.mkdir(parents=True);(d/'Makefile').write_text('CFLAGS = -w -m32\nDepend: .obj/a.o OBJDIR/b.o\n') + (source/'extern').mkdir();archive=source/'extern/libfixture.a';archive.write_bytes(b'fixture') + manifest={'source_sha256':BUILD.source_digest(source),'archives':{'extern/libfixture.a':BUILD.digest(archive)}} + run,snapshot,rev=BUILD.prepare(source,out,'game',manifest,True) + flags=(snapshot/'server/game/src/Makefile').read_text() + self.assertNotIn(' -w ',flags);self.assertIn('-Wformat=2',flags);self.assertIn('-Werror=shorten-64-to-32',flags);self.assertIn('$(OBJDIR)/a.o',flags) + with self.assertRaises(FileExistsError):BUILD.prepare(source,out,'game',manifest,True) + BUILD.prepare(source,out,'db',manifest) + system=base/'system.a';system.write_bytes(b'system archive') + manifest['system_archives']={str(system):BUILD.digest(system)} + BUILD.validate_dependencies(source,manifest,BUILD.source_digest(source)) + system.write_bytes(b'foreign archive') + with self.assertRaises(ValueError):BUILD.validate_dependencies(source,manifest,BUILD.source_digest(source)) + manifest.pop('system_archives') + archive.write_bytes(b'changed') + with self.assertRaises(ValueError):BUILD.prepare(source,base/'other','game',manifest) + + def test_build_records_binary_after_make_moves_it_to_bin(self): + from unittest.mock import patch + with tempfile.TemporaryDirectory() as tmp: + base=Path(tmp);source=base/'source';out=base/'output' + for part in ('game','db'): + d=source/'server'/part/'src';d.mkdir(parents=True);(d/'Makefile').write_text('CFLAGS = -w -m32\n') + (source/'extern').mkdir();archive=source/'extern/libfixture.a';archive.write_bytes(b'fixture') + manifest=base/'dependencies.json' + manifest.write_text(json.dumps({'source_sha256':BUILD.source_digest(source),'archives':{'extern/libfixture.a':BUILD.digest(archive)}})) + for target in ('game','db'): + def make(cmd,**kwargs): + values=dict(arg.split('=',1) for arg in cmd if '=' in arg) + destination=Path(values['GAMEDIR' if target=='game' else 'DBDIR'])/target + self.assertEqual(destination.parent.parent,out.resolve()/(target+'-release')) + destination.write_bytes(b'candidate') + return subprocess.CompletedProcess(cmd,0) + argv=['build','--source',str(source),'--output',str(out),'--target',target,'--dependency-manifest',str(manifest)] + with patch('sys.argv',argv),patch.object(BUILD.platform,'system',return_value='FreeBSD'),patch.object(BUILD.subprocess,'run',side_effect=make),patch.object(BUILD.subprocess,'check_output',return_value='test compiler'): + BUILD.main() + result=json.loads((out/(target+'-release')/'result.json').read_text()) + self.assertEqual(result['status'],'PASS') + self.assertEqual(Path(result['binary']),out.resolve()/(target+'-release')/'bin'/target) + + def test_gold_migration_rejects_unexpected_column_kinds(self): + planner=module('gold_plan','tools/gold64/migrate_gold64.py') + for kind in ('int(11)','bigint(20) unsigned','bigint'): + planner.validate_column(kind) + for kind in ('varchar(32)','decimal(20,2)','int(11); DROP TABLE player','float'): + with self.assertRaises(ValueError):planner.validate_column(kind) + + def test_offline_unverified_economy_cannot_be_enabled_by_runtime_flag(self): + self.native('#include "src/server/common/offline_shop_safety.h"\n#include \nint main(){assert(!PortOfflineShopEconomyReady());}') diff --git a/tests/features/test_point_journal_compaction.py b/tests/features/test_point_journal_compaction.py new file mode 100644 index 00000000..c32aa4c0 --- /dev/null +++ b/tests/features/test_point_journal_compaction.py @@ -0,0 +1,93 @@ +"""Execute production journal compaction, including fault and crash boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class PointJournalCompaction(unittest.TestCase): + def test_atomic_compaction_never_loses_unsettled_intents(self): + code=r''' +#include +#include +#include +#include +static int syncCount=0,failSync=0,crash=0;static bool writeFailure=false,renameFailure=false,interruptOnce=false;static size_t allowance=0; +static ssize_t Write(int fd,const void* bytes,size_t count){ + if(interruptOnce){interruptOnce=false;errno=EINTR;return -1;} + if(writeFailure){if(!allowance){errno=ENOSPC;return -1;}if(count>allowance)count=allowance;allowance-=count;} + return ::write(fd,bytes,count); +} +static int Sync(int fd){++syncCount;if(syncCount==failSync){errno=EIO;return -1;}int result=::fsync(fd);if(crash==1 && syncCount==1)_exit(0);return result;} +static int Rename(int a,const char* b,int c,const char* d){if(renameFailure){errno=EIO;return -1;}int result=::renameat(a,b,c,d);if(crash==2 && result==0)_exit(0);return result;} +#define write Write +#define fsync Sync +#define renameat Rename +#include "src/server/common/point_journal.h" +#undef write +#undef fsync +#undef renameat +#include +#include +#include +std::string read(const std::string& path){std::ifstream in(path);return std::string((std::istreambuf_iterator(in)),{});} +void write(const std::string& path,const std::string& text){std::ofstream out(path);out< pending;assert(journal.Open(path,pending));assert(pending.size()==1 && !journal.NeedsCompaction()); + auto invalid=pending.begin()->second;invalid.count=9;assert(!journal.Intent(invalid) && journal.Ready());assert(read(path)==history); + assert(!journal.Done(other.c_str(),0,9,100) && journal.Ready());assert(read(path)==history); + interruptOnce=true;assert(journal.Compact() && journal.Ready()); + assert(read(path).find("INTENT v2 "+other+" 1 2 3 8 10 123 ")==0 && read(path).find("DONE")==std::string::npos); + PointJournal competitor;assert(!competitor.Open(path,pending)); + int direct=open(path.c_str(),O_RDWR);assert(direct>=0 && flock(direct,LOCK_EX|LOCK_NB)!=0);close(direct); + assert(journal.Done(other.c_str(),0,8,100));assert(journal.Compact() && read(path).empty()); + } + for(int fault=0;fault<5;++fault){ + write(path,history);{PointJournal journal;std::map p;assert(journal.Open(path,p)); + syncCount=0;failSync=fault==1?1:fault==3?2:0;writeFailure=fault==0;allowance=7;renameFailure=fault==2; + const std::string temporary=path+".compact."+std::to_string(getpid()); + if(fault==4)write(temporary,"do not replace a pre-existing file"); + assert(!journal.Compact() && !journal.Ready()); + failSync=0;writeFailure=false;renameFailure=false; + if(fault!=3)assert(read(path)==history);else assert(read(path).find("DONE")==std::string::npos); + if(fault==4){assert(read(temporary)=="do not replace a pre-existing file");unlink(temporary.c_str());} + } + PointJournal recovery;std::map p;assert(recovery.Open(path,p));assert(p.size()==1 && p.begin()->first==other && p.begin()->second.count==8); + } + for(int boundary=1;boundary<=2;++boundary){ + write(path,history);pid_t child=fork();assert(child>=0); + if(child==0){PointJournal journal;std::map p;assert(journal.Open(path,p));syncCount=0;crash=boundary;journal.Compact();_exit(9);} + int status=0;waitpid(child,&status,0);assert(WIFEXITED(status)&&WEXITSTATUS(status)==0); + PointJournal recovery;std::map p;assert(recovery.Open(path,p));assert(p.size()==1&&p.begin()->first==other);assert(recovery.Compact()); + } + // A large active queue must not be truncated to 4096 during replacement. + {std::ofstream out(path);for(unsigned i=1;i<=5000;++i){char t[33];snprintf(t,sizeof(t),"%032x",i);out< p;assert(journal.Open(path,p)&&p.size()==5000);assert(journal.Compact());} + {PointJournal journal;std::map p;assert(journal.Open(path,p)&&p.size()==5000);} + {std::ofstream out(path);for(unsigned i=0;i<12000;++i)out< p;assert(journal.Open(path,p)&&p.size()==1&&journal.NeedsCompaction());assert(journal.Compact()&&!journal.NeedsCompaction());} + // Reject invalid legacy numeric/status records too; compaction cannot sanitize corruption. + for(const auto& invalid:{"INTENT v1 "+token+" -1 2 3 8 10 123\n",intent(other)+"DONE v1 "+other+" 6 0 100 124\n",intent(other)+"DONE v1 "+other+" 0 9 100 124\n"}){ + write(path,invalid);PointJournal journal;std::map p;assert(!journal.Open(path,p));assert(!journal.Compact() && read(path)==invalid); + } + unlink((path+".lock").c_str());symlink("/does/not/exist",(path+".lock").c_str()); + {PointJournal journal;std::map p;assert(!journal.Open(path,p));} +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe),str(Path(tmp)/'pending.log')],check=True) + + def test_maintenance_is_wired_to_startup_and_retry(self): + text=(ROOT/'src/server/game/src/ava2_itemshop.cpp').read_text() + self.assertIn('pointJournal.NeedsCompaction()',text[text.index('EVENTFUNC(RetryPoints)'):text.index('bool PointReply(')]) + self.assertIn('pointJournal.NeedsCompaction()',text[text.index('void Ava2PointDropInit()'):text.index('void Ava2PointDrop(CHARACTER*')]) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_point_reply_runtime.py b/tests/features/test_point_reply_runtime.py new file mode 100644 index 00000000..de393543 --- /dev/null +++ b/tests/features/test_point_reply_runtime.py @@ -0,0 +1,53 @@ +"""Run the game completion handler: malformed or unpersisted results stay pending.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class PointReply(unittest.TestCase): + def test_only_valid_durable_completion_removes_the_original_token(self): + source=(ROOT/'src/server/game/src/ava2_itemshop.cpp').read_text() + a=source.index('bool PointReply(');b=source.index('\n}\n}',a)+2;body=source[a:b] + harness=r''' +#include "src/server/common/ava2_itemshop.h" +#include +#include +#include +#include +#include +using DWORD=uint32_t; +struct Pending{Ava2ShopRequest request;};std::map pendingPoints; +bool allowDone=true;int done=0; +bool AppendDurableDone(const char*,uint8_t,uint32_t,int64_t){if(!allowDone)return false;++done;return true;} +struct Journal{std::string Error(){return "injected EIO";}}pointJournal; +#define sys_err(...) ((void)0) +struct Desc{struct Account{unsigned id=1;}account;Account GetAccountTable(){return account;}const char* GetClientVersion(){return "mt20261024";}}; +struct Character{Desc desc;int notified=0;Desc* GetDesc(){return &desc;}templatevoid ChatPacket(T...){++notified;}}character; +struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}Character* FindByPID(unsigned){return &character;}}; +constexpr int CHAT_TYPE_COMMAND=1; +''' + main=r''' +int main(){ + Ava2ShopReply reply={1,2,46};Ava2ShopRequest request={};request.account=1;request.player=2;request.count=8; + const std::string token="0123456789abcdef0123456789abcdef";char data[46]={};data[0]=9;memcpy(data+2,token.data(),32); + auto reset=[&](){pendingPoints.clear();pendingPoints[token]={request};}; + auto response=[&](unsigned status,uint32_t amount,int64_t balance){data[1]=char(status);memcpy(data+34,&amount,4);memcpy(data+38,&balance,8);return PointReply(reply,data);}; + for(unsigned status:{6u,8u,255u,3u}){reset();assert(response(status,0,100) && pendingPoints.size()==1 && !done);} + reset();assert(response(0,9,100) && pendingPoints.size()==1 && !done); + assert(response(0,1,-1) && pendingPoints.size()==1 && !done); + assert(response(2,1,100) && pendingPoints.size()==1 && !done); + allowDone=false;assert(response(0,8,100) && pendingPoints.size()==1 && !done);allowDone=true; + reply.account=99;assert(response(0,8,100) && pendingPoints.size()==1 && !done);reply.account=1; + assert(response(0,8,100) && pendingPoints.empty() && done==1 && character.notified==1); + assert(response(0,8,100) && done==1 && character.notified==1); // Duplicate completion is ignored. + reset();assert(response(2,0,100) && pendingPoints.empty() && done==2 && character.notified==1); + reset();reply.size=45;assert(!response(0,8,100) && pendingPoints.size()==1);reply.size=46; +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+body+main) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_point_settlement_runtime.py b/tests/features/test_point_settlement_runtime.py new file mode 100644 index 00000000..9c6dfbf8 --- /dev/null +++ b/tests/features/test_point_settlement_runtime.py @@ -0,0 +1,118 @@ +"""Execute DB reward handler control flow with transactional SQL fault boundaries. +This is not a real MySQL or a full db-process crash acceptance test. +""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class PointSettlement(unittest.TestCase): + def test_commit_uncertainty_replay_and_configuration_changes(self): + source=(ROOT/'src/server/db/src/Ava2ItemShop.cpp').read_text() + body=source[source.index(' if(r.operation==3) {'):source.index(' auto login=GetLoginDataByAID')] + harness=r''' +#include "src/server/common/ava2_itemshop.h" +#include "src/server/common/point_drop.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +using DWORD=uint32_t; +struct TMobTable{DWORD dwVnum;int bType,bLevel;}; +struct CPeer{int GetChannel(){return 1;}}; +struct Reward{unsigned account,player,vnum,requested,amount;}; +struct State{int64_t coins=100;std::map rewards;}; +State durable,working; +Ava2ShopRequest current={};bool ownerPresent=true,walletPresent=true;unsigned ownerAccount=1;int ownershipQueries=0;bool active=false,commitLost=false,commitRefused=false,failInsert=false,engineOK=true; +std::string queryFailure;int writes=0,quotas=0; +struct Rows{std::vector> values;std::vector output;}; +struct Result{unsigned uiNumRows=0;Rows rows;Rows* pSQLResult=&rows;}; +struct SQL{unsigned uiSQLErrno=0;Result result;Result* Get(){return &result;}}; +using Query=std::unique_ptr; +Query result(std::vector> rows){Query q(new SQL);q->result.uiNumRows=rows.size();q->result.rows.values=std::move(rows);return q;} +char** mysql_fetch_row(Rows* rows){assert(!rows->values.empty());rows->output.clear();for(auto& v:rows->values[0])rows->output.push_back(v.data());return rows->output.data();} +bool ok(const Query& q){return q && !q->uiSQLErrno;} +std::string decimal(uint64_t v){return std::to_string(v);}std::string accountDB(){return "`account`";} +Query query(const std::string& sql){ + if(!queryFailure.empty() && sql.find(queryFailure)!=std::string::npos){Query q(new SQL);q->uiSQLErrno=1;return q;} + if(sql.find("information_schema.tables")!=std::string::npos){assert(sql.find("ishop")==std::string::npos && sql.find("port_point_rewards")!=std::string::npos && sql.find("account")!=std::string::npos);return result({{engineOK?"2":"1"}});} + assert(active); + if(sql.find("SELECT account_id FROM player")==0){++ownershipQueries;return result(ownerPresent?std::vector>{{decimal(ownerAccount)}}:std::vector>{});} + if(sql.find("SELECT coins FROM")==0){assert(sql.find("FOR UPDATE")!=std::string::npos);return result(walletPresent?std::vector>{{std::to_string(working.coins)}}:std::vector>{});} + if(sql=="SELECT CURDATE()")return result({{"2026-10-20"}}); + if(sql.find("SELECT account_id,vnum,requested,amount,player_id FROM port_point_rewards")==0){ + auto it=working.rewards.find(current.token);if(it==working.rewards.end())return result({});const auto& r=it->second; + return result({{decimal(r.account),decimal(r.vnum),decimal(r.requested),decimal(r.amount),decimal(r.player)}}); + } + if(sql.find("SELECT COALESCE(SUM(amount),0)")==0){++quotas;assert(sql.find("reward_day='2026-10-20'")!=std::string::npos);unsigned n=0;for(auto& row:working.rewards)if(row.second.account==current.account)n+=row.second.amount;return result({{decimal(n)}});} + assert(false);return {}; +} +bool run(const std::string& sql){ + assert(active);++writes; + if(sql.find("UPDATE `account`.account SET coins=coins+")==0){auto a=sql.find("coins+")+6;auto b=sql.find(" WHERE",a);working.coins+=std::stoll(sql.substr(a,b-a));return true;} + if(sql.find("INSERT INTO port_point_rewards")==0){ + if(failInsert)return false; + auto before=durable.coins;unsigned amount=unsigned(working.coins-before); + assert(sql.find(","+decimal(current.count)+","+decimal(amount)+",'2026-10-20')")!=std::string::npos); + working.rewards[current.token]={current.account,current.player,current.product,current.count,amount};return true; + } + assert(false);return false; +} +struct Transaction{bool active=true;Transaction(){assert(!::active);::active=true;working=durable;} + bool commit(){if(commitRefused)return false;durable=working;if(commitLost)return false;active=false;return true;} + ~Transaction(){::active=false;} +}; +templatevoid append(std::vector& out,const T& v){auto p=reinterpret_cast(&v);out.insert(out.end(),p,p+sizeof(v));} +std::vector response; +void reply(CPeer*,DWORD,const Ava2ShopRequest&,const std::vector& out){response=out;} +struct Handler{ + std::vector m_vec_mobTable={{8021,2,100}}; + std::map m_map_lEventFlag={{"points_stone_chance",10000},{"points_stone_min",3},{"points_stone_max",8},{"points_max_overlevel",15},{"points_daily_cap",500}}; + void Handle(CPeer* peer,DWORD handle,const Ava2ShopRequest& r){ BODY } +}; +uint8_t settle(Handler& handler,Ava2ShopRequest r){current=r;response.clear();CPeer peer;handler.Handle(&peer,0,r);assert(response.size()==46);return uint8_t(response[1]);} +unsigned granted(){unsigned n=0;memcpy(&n,response.data()+34,4);return n;} +'''.replace('BODY',body) + main=r''' +int main(){ + Ava2ShopRequest r={};r.operation=3;r.account=1;r.player=2;r.product=8021;r.count=8;r.expectedVnum=110;strcpy(r.token,"0123456789abcdef0123456789abcdef"); + Handler handler;durable.rewards["older"]={1,3,8021,498,498}; + commitLost=true;assert(settle(handler,r)==8);assert(durable.coins==102 && durable.rewards[r.token].amount==2);int quotaCalls=quotas; + commitLost=false;ownerPresent=false;int ownershipBefore=ownershipQueries;handler.m_vec_mobTable.clear();handler.m_map_lEventFlag.clear(); + assert(settle(handler,r)==0 && granted()==2 && durable.coins==102 && quotas==quotaCalls); // original committed result survives source changes. + assert(ownershipQueries==ownershipBefore);ownerPresent=true; + r.player=3;assert(settle(handler,r)==7 && durable.coins==102);r.player=2; + r.count=7;assert(settle(handler,r)==7 && durable.coins==102);r.count=8; + r.product=999;assert(settle(handler,r)==7 && durable.coins==102);r.product=8021; + // A new token with a removed mob is terminally refused, never dereferenced. + strcpy(r.token,"1123456789abcdef0123456789abcdef");assert(settle(handler,r)==1 && durable.coins==102); + handler=Handler();durable=State();failInsert=true; + assert(settle(handler,r)==6 && durable.coins==100 && durable.rewards.empty());failInsert=false; + assert(settle(handler,r)==0 && granted()==8 && durable.coins==108 && durable.rewards.size()==1); + assert(settle(handler,r)==0 && durable.coins==108); + strcpy(r.token,"2123456789abcdef0123456789abcdef");commitRefused=true; + assert(settle(handler,r)==8 && durable.coins==108 && durable.rewards.size()==1);commitRefused=false; + assert(settle(handler,r)==0 && durable.coins==116 && durable.rewards.size()==2); + strcpy(r.token,"3123456789abcdef0123456789abcdef");queryFailure="SELECT COALESCE"; + assert(settle(handler,r)==6 && durable.coins==116);queryFailure.clear(); + engineOK=false;assert(settle(handler,r)==6 && durable.coins==116);engineOK=true; + ownerPresent=false;assert(settle(handler,r)==2 && durable.coins==116);ownerPresent=true; + ownerAccount=99;assert(settle(handler,r)==2 && durable.coins==116);ownerAccount=1; + walletPresent=false;assert(settle(handler,r)==2 && durable.coins==116);walletPresent=true; + // Zero grants are durable results; later replay does not recalculate the cap. + handler.m_map_lEventFlag["points_daily_cap"]=16;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116); + handler.m_map_lEventFlag["points_daily_cap"]=500;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116); +} +''' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe';src.write_text(harness+main) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_product_costume_runtime.py b/tests/features/test_product_costume_runtime.py new file mode 100644 index 00000000..e3392be9 --- /dev/null +++ b/tests/features/test_product_costume_runtime.py @@ -0,0 +1,63 @@ +"""Execute actual costume enchant/removal functions, including all AVA2 target masks.""" +from pathlib import Path +import subprocess,tempfile,unittest +ROOT=Path(__file__).resolve().parents[2] +class CostumeProducts(unittest.TestCase): + def test_real_use_preserves_rare_state_and_consumes_only_after_success(self): + body=(ROOT/'src/server/game/src/port_costume_attr.cpp').read_text() + body='\n'.join(line for line in body.splitlines() if not line.startswith('#include')) + harness=r''' +#include +#include +#include +#include +#include +using BYTE=uint8_t; +enum {ITEM_USE=3,ITEM_COSTUME=28,ITEM_SHINING=35,USE_CHANGE_ATTRIBUTE=18,COSTUME_BODY=0,COSTUME_HAIR=1,COSTUME_WEAPON=5,COSTUME_MOUNT_SKIN=4,COSTUME_NEW_SASH=6,SHINING_WEAPON=0,SHINING_ARMOR=1,SHINING_SPECIAL=2,APPLY_NONE=0,MAX_APPLY_NUM=141,MAX_NORM_ATTR_NUM=5,CHAT_TYPE_COMMAND=1}; +struct ITEM_MANAGER{enum {MAX_NORM_ATTR_NUM=5};}; +struct CHARACTER; +struct CItem {int type=ITEM_USE,sub=USE_CHANGE_ATTRIBUTE;unsigned vnum=54001,count=2;int values[3]={23,10,2};CHARACTER* owner=nullptr;bool equipped=false,locked=false,exchanged=false;std::array attrs{},amounts{}; + int GetType(){return type;}int GetSubType(){return sub;}int GetValue(int i){return values[i];}unsigned GetVnum(){return vnum;}unsigned GetCount(){return count;}void SetCount(unsigned n){count=n;}unsigned GetID(){return 42;} + CHARACTER* GetOwner(){return owner;}bool IsEquipped(){return equipped;}bool isLocked(){return locked;}bool IsExchanging(){return exchanged;} + int GetAttributeType(int i){return attrs.at(i);}int GetAttributeCount(){int i=0;while(i<5&&attrs[i])++i;return i;}bool HasAttr(BYTE n){for(int i=0;i<5;++i)if(attrs[i]==n)return true;return false;} + void AddAttribute(BYTE n,short v){int i=GetAttributeCount();attrs.at(i)=n;amounts.at(i)=v;}void SetForceAttribute(int i,BYTE n,short v){attrs.at(i)=n;amounts.at(i)=v;}bool IsCostumeEnchant(); +};using LPITEM=CItem*; +struct CHARACTER {char message[80]={};bool CostumeEnchantUse(LPITEM,LPITEM);void ChatPacket(int,const char* text){snprintf(message,sizeof(message),"%s",text);}}; +struct LogManager{static LogManager& instance(){static LogManager m;return m;}templatevoid ItemLog(T...) {}}; +''' + main=r''' +int main(){ + CHARACTER ch,other;CItem scroll,target;scroll.owner=target.owner=&ch;target.type=ITEM_COSTUME;target.sub=COSTUME_BODY; + assert(!ch.CostumeEnchantUse(nullptr,&target));assert(!ch.CostumeEnchantUse(&scroll,nullptr));assert(!ch.CostumeEnchantUse(&scroll,&scroll)); + for(int flag=1;flag<=6;++flag){ + target.attrs.fill(0);target.amounts.fill(0);target.type=flag==6?ITEM_SHINING:ITEM_COSTUME; + const int subs[]={0,COSTUME_BODY,COSTUME_HAIR,COSTUME_WEAPON,COSTUME_MOUNT_SKIN,COSTUME_NEW_SASH,SHINING_SPECIAL};target.sub=subs[flag]; + scroll.count=3;scroll.vnum=54001;scroll.values[2]=1< +#include +#include +using WORD=uint16_t; +struct TSkillTable{char data[2];};struct TBanwordTable{char data[3];};struct TItemTable{char data[4];};struct TMobTable{char data[5];}; +constexpr int HEADER_DG_RELOAD_PROTO=1; +#define sys_err(...) ((void)0) +struct CPeer {unsigned headers=0;size_t announced=0,bytes=0;std::vector counts; + unsigned GetChannel(){return 1;}void EncodeHeader(int,int,size_t n){++headers;announced=n;} + void EncodeWORD(WORD n){counts.push_back(n);bytes+=sizeof(n);}void Encode(const void* ptr,size_t n){assert(!n||ptr);bytes+=n;}}; +struct CClientManager {using TPeerList=std::vector;TPeerList m_peerList; + std::vector m_vec_skillTable;std::vector m_vec_banwordTable; + std::vector m_vec_itemTable;std::vector m_vec_mobTable; + bool InitializeTables(){return true;}void QUERY_RELOAD_PROTO();}; +''' + main=r''' +int main(){CClientManager manager;CPeer peer;manager.m_peerList.push_back(&peer); + manager.QUERY_RELOAD_PROTO();assert(peer.headers==1 && peer.announced==8 && peer.bytes==8); + assert(peer.counts==std::vector({0,0,0,0}));peer={}; + manager.m_vec_skillTable.resize(UINT16_MAX);manager.QUERY_RELOAD_PROTO();assert(peer.headers==1 && peer.counts[0]==UINT16_MAX && peer.bytes==peer.announced);peer={}; + manager.m_vec_skillTable.resize(UINT16_MAX+1u);manager.QUERY_RELOAD_PROTO();assert(peer.headers==0 && peer.bytes==0); + manager.m_vec_skillTable.clear();manager.m_vec_itemTable.resize(UINT16_MAX+1u);manager.QUERY_RELOAD_PROTO();assert(peer.headers==0 && peer.bytes==0); +} +''' + with tempfile.TemporaryDirectory() as tmp: + p=Path(tmp);(p/'probe.cpp').write_text(harness+actual+main) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32',str(p/'probe.cpp'),'-o',str(p/'probe')],check=True) + subprocess.run([str(p/'probe')],check=True) diff --git a/tests/features/test_queries.py b/tests/features/test_queries.py index 2b904557..113acfaa 100644 --- a/tests/features/test_queries.py +++ b/tests/features/test_queries.py @@ -74,6 +74,7 @@ static void PortCalendarQuery(LPCHARACTER,unsigned,unsigned){} static bool PortDungeonQuery(LPCHARACTER,unsigned){return true;} static unsigned travelBoss=0;static void PortTrackTravel(LPCHARACTER,unsigned,unsigned boss){travelBoss=boss;} static unsigned bossQueries=0;void PortBossQuery(LPCHARACTER,unsigned request){bossQueries=request;} +static unsigned rankQuery=99;static void PortRankQuery(LPCHARACTER,unsigned,unsigned index){rankQuery=index;} #include "port_features.h" #include "port_dungeon_rules.h" static void query(Character& ch,const char* text){clockms+=300;do_port_features(&ch,text);} @@ -117,7 +118,10 @@ int main(){ assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE); rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100); assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty()); - Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 959 1700000000"); + Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 1983 1700000000"); + query(ch,"1 90 rank 0 0");assert(rankQuery==0); + query(ch,"1 91 rank 10 0");assert(ch.messages.back()=="MTF1 error 91 invalid" && rankQuery==0); + query(ch,"1 92 rank 6 1");assert(ch.messages.back()=="MTF1 error 92 invalid" && rankQuery==0); ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8"); query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset"); query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing"); diff --git a/tests/features/test_rank_runtime.py b/tests/features/test_rank_runtime.py new file mode 100644 index 00000000..fe8463df --- /dev/null +++ b/tests/features/test_rank_runtime.py @@ -0,0 +1,116 @@ +"""Execute the production async rank/cache/session handler with explicit SQL/peer substitutes.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +SRC = Path(__file__).resolve().parents[2] / 'src/server/game/src' +CODE = r''' +#include +#include +#include +#include +#include +#include +#include +#include +static unsigned tick=1000; +unsigned get_dword_time(){return tick;} +long long get_global_time(){return 1700000000;} +const char* get_table_postfix(){return "_sb";} +enum{CHAT_TYPE_COMMAND=5}; +struct Character; +struct Desc{ + unsigned handle=7,handshake=40;struct Account{unsigned id=3;} account; + Character* ch=nullptr; + unsigned GetHandle(){return handle;}unsigned GetHandshake(){return handshake;} + Account& GetAccountTable(){return account;}Character* GetCharacter(){return ch;} +}; +struct Character{ + unsigned pid=9;Desc* d;std::vector lines; + Desc* GetDesc(){return d;}unsigned GetPlayerID(){return pid;} + void ChatPacket(int,const char* format,...){ + char out[512];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args); + lines.emplace_back(out); + } +}; +using LPCHARACTER=Character*; +struct DESC_MANAGER{ + std::map peers; + static DESC_MANAGER& instance(){static DESC_MANAGER m;return m;} + Desc* FindByHandle(unsigned h){auto i=peers.find(h);return i==peers.end()?nullptr:i->second;} +}; +struct Result{ + std::vector> rows; + size_t cursor=0;char* fields[3]; +}; +using MYSQL_ROW=char**; +MYSQL_ROW mysql_fetch_row(Result* r){ + if(r->cursor>=r->rows.size())return nullptr; + auto& row=r->rows[r->cursor++];for(int i=0;i<3;++i)r->fields[i]=&row[i][0];return r->fields; +} +struct SQLMsg{ + unsigned uiSQLErrno=0; + struct Data{Result* pSQLResult;unsigned uiNumRows;} data; + Data* Get(){return &data;} +}; +struct DBManager{ + std::vector> callbacks;std::vector queries; + static DBManager& instance(){static DBManager m;return m;} + templatevoid FuncQuery(F f,const char* format,...){ + char out[4096];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args); + queries.emplace_back(out);callbacks.emplace_back(f); + } + void Complete(std::vector> rows,unsigned error=0){ + Result r;r.rows=rows;SQLMsg msg;msg.uiSQLErrno=error;msg.data={&r,unsigned(rows.size())}; + auto f=callbacks.front();callbacks.erase(callbacks.begin());f(&msg); + } +}; +#include "port_rank_runtime.h" +int main(){ + Desc d;Character c;c.d=&d;d.ch=&c;DESC_MANAGER::instance().peers[d.handle]=&d; + auto& db=DBManager::instance(); + PortRankQuery(&c,1,0);PortRankQuery(&c,2,0); + assert(db.queries.size()==1 && c.lines.empty()); + assert(db.queries[0].find("p.level")!=std::string::npos); + assert(db.queries[0].find("player_sb p JOIN player_index_sb")!=std::string::npos); + assert(db.queries[0].find("ORDER BY p.level DESC, p.id ASC LIMIT 10")!=std::string::npos); + db.Complete({{"hero","1","120"},{"second","2","119"}}); + assert(c.lines.size()==8 && c.lines.front()=="MTF1 begin 1 rank 0 0 2 0 1700000000"); + assert(c.lines[1]=="MTF1 rank 1 0 6865726f 1 120"); + PortRankQuery(&c,3,0);assert(db.queries.size()==1 && c.lines.back()=="MTF1 end 3 2"); + PortRankQuery(&c,4,1);assert(c.lines.back()=="MTF1 error 4 unsupported"); + PortRankQuery(&c,5,10);assert(c.lines.back()=="MTF1 error 5 unsupported"); + PortRankQuery(&c,6,6);db.Complete({{"rich","3","5000000000"}}); + assert(c.lines[c.lines.size()-2]=="MTF1 rank 6 0 72696368 3 5000000000"); + PortRankQuery(&c,7,5);db.Complete({});assert(c.lines.back()=="MTF1 end 7 0"); + tick+=60001;PortRankQuery(&c,8,0);db.Complete({{"valid","1","5"},{"bad","9","1"}}); + assert(c.lines.back()=="MTF1 error 8 storage"); + PortRankQuery(&c,9,0);db.Complete({},1);assert(c.lines.back()=="MTF1 error 9 storage"); + PortRankQuery(&c,10,0);size_t before=c.lines.size();d.handshake++; + db.Complete({{"hero","1","120"}});assert(c.lines.size()==before); + tick+=60001;PortRankQuery(&c,11,0);before=c.lines.size();c.pid++; + db.Complete({{"hero","1","120"}});assert(c.lines.size()==before); + tick+=60001;PortRankQuery(&c,12,0);before=c.lines.size();d.account.id++; + db.Complete({{"hero","1","120"}});assert(c.lines.size()==before); + uint64_t n;assert(!PortRank::Number("-1",10,n));assert(!PortRank::Number("11",10,n)); + assert(PortRank::Number("18446744073709551615",UINT64_MAX,n)); + assert(!PortRank::Number("18446744073709551616",UINT64_MAX,n)); + puts("PASS: production rank query, async coalescing, persisted top10, 64bit, cache expiry, atomic failure, stale session/player/account"); +} +''' + + +class RankRuntimeTests(unittest.TestCase): + def test_actual_rank_handler(self): + with tempfile.TemporaryDirectory(prefix='ch5-rank-') as folder: + root = Path(folder) + (root / 'probe.cpp').write_text(CODE) + subprocess.run(['c++', '-std=c++17', '-Wall', '-Wextra', + '-I' + str(SRC), str(root / 'probe.cpp'), + '-o', str(root / 'probe')], check=True) + subprocess.run([str(root / 'probe')], check=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/features/test_shared_wire_headers.py b/tests/features/test_shared_wire_headers.py new file mode 100644 index 00000000..c93b9d1f --- /dev/null +++ b/tests/features/test_shared_wire_headers.py @@ -0,0 +1,36 @@ +"""Compile common protocol headers without relying on a game-only include order.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +class SharedWireHeaders(unittest.TestCase): + def test_game_and_db_include_order_share_enabled_fields(self): + body=r''' +#include +#include +#include +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;using LONG=int32_t;using INT=int32_t; +SERVICE +#include "src/server/common/tables.h" +static_assert(OFFLINE_SHOP_HOST_ITEM_MAX_NUM==80); +static_assert(SHOP_SIGN_MAX_LEN==45); +static_assert(PET_LEVELABLE==0 && PET_FEEDSTUFF==14); +static_assert(APPLY_RESIST_HUMAN==99); +static_assert(sizeof(TShopItemTable)==17); +int main(){ + TPlayerTable player={};player.shopFlag=1;player.inventory_unlock[0]=1; + TOfflineShop shop={};OFFLINE_SHOP_ITEM item={}; + std::cout< +#include +#include +#include +#include +#include +#include +using DWORD=uint32_t;using BYTE=uint8_t; +constexpr int64_t GOLD_MAX_64=2000000000000000LL; +enum {SHOP_SUBHEADER_GC_OK=4,SHOP_SUBHEADER_GC_INVALID_POS=8,SHOP_SUBHEADER_GC_END=1,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY=5,SHOP_SUBHEADER_GC_SOLD_OUT=9,SHOP_SUBHEADER_GC_INVENTORY_FULL=7}; +enum {POINT_GOLD,PORT_BP_NPC_SPEND,QUICKSLOT_TYPE_ITEM,DRAGON_SOUL_INVENTORY,INVENTORY,SHOP_BUY,SHOP_SELL,PERSONAL_SHOP_BUY,MONEY_LOG_SHOP,CHAT_TYPE_INFO}; +#define sys_log(...) ((void)0) +#define LC_TEXT(x) (x) +bool LC_IsYMIR(){return false;}bool LC_IsKorea(){return false;} +struct Character;using LPCHARACTER=Character*; +struct TItemPos{TItemPos(int,int){}}; +struct Item {DWORD vnum=19,id=1;BYTE count=1;Character* owner=nullptr; + DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}BYTE GetCount(){return count;} + Character* GetOwner(){return owner;}int GetSize(){return 1;}bool IsDragonSoul(){return false;} + const char* GetName(){return "item";}int GetCell(){return 0;} + void RemoveFromCharacter(){owner=nullptr;}void AddToCharacter(Character* c,TItemPos){owner=c;} +};using LPITEM=Item*; +struct Character {int64_t gold=0;bool full=false;int writes=0,saves=0; + int64_t GetGold(){return gold;}const char* GetName(){return "test";}DWORD GetPlayerID(){return 1;} + int GetEmptyInventory(int){return full?-1:0;}int GetEmptyDragonSoulInventory(Item*){return full?-1:0;} + void PointChange(int,int64_t delta,bool){assert(PortGoldCanChange(gold,delta,GOLD_MAX_64));gold+=delta;++writes;} + void SyncQuickslot(int,int,int){}int GetEmpire(){return 1;}void Save(){++saves;} + templatevoid ChatPacket(T...){} +}; +struct ITEM_MANAGER {std::map items;int created=0,destroyed=0; + static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + Item* Find(int id){return items.count(id)?items[id]:nullptr;} + Item* CreateItem(DWORD vnum,BYTE count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;} + void Destroy(Item* item){++destroyed;for(auto it=items.begin();it!=items.end();)if(it->second==item)it=items.erase(it);else ++it;delete item;} + void FlushDelayedSave(Item*){} + ~ITEM_MANAGER(){for(auto& it:items)if(it.first!=1)delete it.second;} +}; +#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i) +struct LogManager {static LogManager& instance(){static LogManager m;return m;}templatevoid HackLog(T...){}templatevoid GoldBarLog(T...){}templatevoid ItemLog(T...){} }; +namespace quest {struct CQuestManager {int tax=3;static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char* key){return std::string(key)=="personal_shop"?tax:1;} };} +struct CMonarch {int64_t total=0;static CMonarch& instance(){static CMonarch m;return m;}void SendtoDBAddMoney(int64_t money,int,Character*){total+=money;} }; +struct DBManager {int64_t logged=0;static DBManager& instance(){static DBManager m;return m;}void SendMoneyLog(int,DWORD,int64_t gold){logged+=gold;} }; +void PortBpCount(Character*,int,int,int64_t){}void VCardUse(Character*,Character*,Item*){} +struct CShop {struct SHOP_ITEM{DWORD vnum=19;int64_t price=0;BYTE count=1;Item* pkItem=nullptr;int itemid=1;}; + using GuestMapType=std::map;GuestMapType m_map_guest;std::vector m_itemVector; + Character* m_pkPC=nullptr;bool IsPCShop(){return m_pkPC!=nullptr;}void BroadcastUpdateItem(BYTE){}int Buy(Character*,BYTE); +}; +''' + extra_source=(ROOT/'src/server/game/src/shopEx.cpp').read_bytes().decode('latin1') + extra_body=extra_source[extra_source.index('int CShopEx::Buy('):] + harness=harness.replace('int64_t gold=0;', 'int secondary=100;int64_t gold=0;').replace('void SyncQuickslot(int,int,int){}', 'int CountSpecifyTypeItem(int){return secondary;}void RemoveSpecifyTypeItem(int,int n){assert(n>=0 && n<=secondary);secondary-=n;}void SaveReal(){Save();}void SyncQuickslot(int,int,int){}') + harness+=r''' +constexpr int SHOP_HOST_ITEM_MAX_NUM=40,SHOP_COIN_TYPE_GOLD=0,SHOP_COIN_TYPE_SECONDARY_COIN=1; +constexpr int ITEM_SECONDARY_COIN=1,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX=11,HEADER_GD_FLUSH_CACHE=0; +bool LC_IsBrazil(){return false;} +struct DbDesc{templatevoid DBPacketHeader(T...){}templatevoid Packet(T...){};} dbDesc; +auto* db_clientdesc=&dbDesc; +using TShopItemTable=CShop::SHOP_ITEM; +struct TShopTableEx{int coinType=SHOP_COIN_TYPE_GOLD;TShopItemTable items[SHOP_HOST_ITEM_MAX_NUM];}; +struct CShopEx:CShop {std::vector m_vec_shopTabs;int GetTabCount(){return m_vec_shopTabs.size();}int Buy(Character*,BYTE);}; +''' + main = r''' +int main(){ + Character buyer,seller;Item item;item.owner=&seller;ITEM_MANAGER::instance().items[1]=&item; + CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item; + shop.m_map_guest[&buyer]=true; // PC shop never charges an empire multiplier. + buyer.gold=400000000000LL;seller.gold=GOLD_MAX_64-291000000000LL+1; + assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY); + assert(buyer.gold==400000000000LL && buyer.writes==0 && seller.writes==0 && item.owner==&seller && row.pkItem==&item); + --seller.gold;assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK); + assert(buyer.gold==100000000000LL && seller.gold==GOLD_MAX_64 && item.owner==&buyer && !row.pkItem); + assert(CMonarch::instance().total==9000000000LL); + assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_SOLD_OUT && buyer.gold==100000000000LL); + assert(shop.Buy(&buyer,255)==SHOP_SUBHEADER_GC_INVALID_POS); + CShop npc;npc.m_itemVector.resize(1);npc.m_itemVector[0].price=100000000000LL;npc.m_map_guest[&buyer]=true; + buyer.gold=400000000000LL;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK); + assert(buyer.gold==100000000000LL && DBManager::instance().logged==-300000000000LL); + npc.m_itemVector[0].price=INT64_MAX;int writes=buyer.writes; + assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY && buyer.writes==writes); + npc.m_itemVector[0].price=-1;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY && buyer.writes==writes); + npc.m_itemVector[0].price=0;assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.gold==100000000000LL); + buyer.full=true;int created=ITEM_MANAGER::instance().created; + assert(npc.Buy(&buyer,0)==SHOP_SUBHEADER_GC_INVENTORY_FULL); + assert(ITEM_MANAGER::instance().created==created+1 && ITEM_MANAGER::instance().destroyed==1); +} +''' + exmain=r''' + CShopEx ex;ex.m_vec_shopTabs.resize(1);ex.m_map_guest[&buyer]=true; + auto& tab=ex.m_vec_shopTabs[0];tab.items[0].price=100000000000LL; + buyer.gold=400000000000LL;buyer.full=false; + assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.gold==100000000000LL); + tab.coinType=SHOP_COIN_TYPE_SECONDARY_COIN;tab.items[0].price=int64_t(INT_MAX)+1; + assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX && buyer.secondary==100); + tab.items[0].price=20;int64_t logged=DBManager::instance().logged; + assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_OK && buyer.secondary==80 && DBManager::instance().logged==logged); + tab.coinType=99;assert(ex.Buy(&buyer,0)==SHOP_SUBHEADER_GC_END && buyer.secondary==80); +''' + main=main[:main.rfind('}')]+exmain+'}\n' + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=Path(tmp)/'probe' + src.write_text(harness+body+extra_body+main) + subprocess.run(['c++','-std=c++17','-fsanitize=undefined,address','-fno-sanitize-recover=all','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) + +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_sql_mark_bounds.py b/tests/features/test_sql_mark_bounds.py new file mode 100644 index 00000000..673a43bc --- /dev/null +++ b/tests/features/test_sql_mark_bounds.py @@ -0,0 +1,153 @@ +"""Run the production SQL metadata, mark index and boot encoder boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT=Path(__file__).resolve().parents[2] + +def function(text,signature): + start=text.index(signature);a=text.index('{',start);depth=1;b=a+1 + while depth: + if text[b]=='{':depth+=1 + elif text[b]=='}':depth-=1 + b+=1 + return text[start:b]+'\n' + +class SQLMarkBounds(unittest.TestCase): + def native(self,code): + with tempfile.TemporaryDirectory() as tmp: + src=Path(tmp)/'probe.cpp';exe=src.with_suffix('');src.write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-fno-sanitize-recover=all','-Werror=implicit-int-conversion','-Werror=shorten-64-to-32','-I'+str(ROOT),str(src),'-o',str(exe)],check=True) + subprocess.run([str(exe)],cwd=tmp,check=True) + def test_sql_store_preserves_mysql_width_and_error_sentinel(self): + text=(ROOT/'src/server/libsql/AsyncSQL.h').read_text(encoding='latin1');a=text.index('typedef struct _SQLResult');b=text.index('class CAsyncSQL') + self.native(r''' +#include +#include +#include +#include +#include +using my_ulonglong=unsigned long long; +struct MYSQL_RES {my_ulonglong rows;}; +struct Fake {MYSQL_RES* rows;my_ulonglong id,affected;}; +struct MYSQL {std::vector results;size_t index=0;}; +unsigned frees=0; +MYSQL_RES* mysql_store_result(MYSQL* m){return m->results[m->index].rows;} +my_ulonglong mysql_insert_id(MYSQL* m){return m->results[m->index].id;} +my_ulonglong mysql_affected_rows(MYSQL* m){return m->results[m->index].affected;} +my_ulonglong mysql_num_rows(MYSQL_RES* r){return r->rows;} +int mysql_next_result(MYSQL* m){return ++m->indexresults.size()?0:-1;} +void mysql_free_result(MYSQL_RES*){++frees;} +'''+text[a:b]+r''' +int main(){ + static_assert(sizeof(SQLResult::uiNumRows)==8 && sizeof(SQLResult::uiAffectedRows)==8 && sizeof(SQLResult::uiInsertID)==8); + MYSQL_RES rows={uint64_t(UINT32_MAX)+17};MYSQL db={{{&rows,uint64_t(UINT32_MAX)+1,UINT64_MAX},{nullptr,UINT32_MAX,UINT32_MAX},{nullptr,0,0}}}; + { + SQLMsg msg;msg.m_pkSQL=&db;msg.Store();assert(msg.vec_pkResult.size()==3); + SQLResult* result=msg.Get();assert(result->uiNumRows==uint64_t(UINT32_MAX)+17&&result->uiInsertID==uint64_t(UINT32_MAX)+1&&result->uiAffectedRows==UINT64_MAX&&!result->HasAffectedRows()); + uint32_t id=123;assert(!result->GetInsertID32(id)&&id==123); + assert(msg.Next());result=msg.Get();assert(result->HasAffectedRows());assert(result->GetInsertID32(id)&&id==UINT32_MAX); // 2^32-1 is a valid count/ID, not the 64-bit error. + assert(msg.Next());assert(!msg.Get()->HasAffectedRows());id=7;assert(!msg.Get()->GetInsertID32(id)&&id==7);assert(!msg.Next()); + } + assert(frees==1); +} +''') + def test_mark_index_validation_atomic_load_and_unaligned_output(self): + text=(ROOT/'src/server/game/src/MarkManager.cpp').read_text(encoding='latin1') + methods=''.join(function(text,s) for s in ['CGuildMarkManager::CGuildMarkManager()','bool CGuildMarkManager::LoadMarkIndex()','bool CGuildMarkManager::AddMarkIDByGuildID','DWORD CGuildMarkManager::GetMarkCount()','bool CGuildMarkManager::CopyMarkIdx','DWORD CGuildMarkManager::GetMarkID','DWORD CGuildMarkManager::__AllocMarkID','DWORD CGuildMarkManager::SaveMark']) + self.native(r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t; +struct CGuildMarkImage {static constexpr unsigned MARK_TOTAL_COUNT=1280;void SaveMark(DWORD,BYTE*){}}; +#define sys_log(...) ((void)0) +#define sys_err(...) ((void)0) +struct CGuildMarkManager { + static constexpr unsigned MAX_IMAGE_COUNT=5;static constexpr DWORD INVALID_MARK_ID=UINT32_MAX;CGuildMarkImage image; + std::map m_mapGID_MarkID;std::set m_setFreeMarkID;std::string m_pathPrefix="probe";int imageLoads=0; + DWORD GetMarkID(DWORD);DWORD __AllocMarkID(DWORD);DWORD SaveMark(DWORD,BYTE*);CGuildMarkImage* __GetImage(DWORD){return ℑ}void SaveMarkImage(DWORD){}bool SaveMarkIndex(){return true;} + CGuildMarkManager();bool LoadMarkIndex();bool AddMarkIDByGuildID(DWORD,DWORD);DWORD GetMarkCount()const;bool CopyMarkIdx(char*,size_t)const;void LoadMarkImages(){++imageLoads;} +}; +'''+methods+r''' +void file(const std::string& text){std::ofstream out("mark/probe_index");out< bytes;bytes.fill('Z');assert(!marks.CopyMarkIdx(bytes.data()+1,7));for(char c:bytes)assert(c=='Z'); + assert(marks.CopyMarkIdx(bytes.data()+1,8));assert(bytes[0]=='Z'&&bytes[9]=='Z');WORD pair[4];memcpy(pair,bytes.data()+1,8);assert(pair[0]==1&&pair[1]==0&&pair[2]==65535&&pair[3]==6399); + for(const char* bad:{"1 0\n1 1\n","1 0\n2 0\n","65536 1\n","-1 1\n","1 6400\n","1 nope\n","1 2 junk\n"}){ + file(bad);auto map=marks.m_mapGID_MarkID;auto free=marks.m_setFreeMarkID;assert(!marks.LoadMarkIndex());assert(marks.m_mapGID_MarkID==map&&marks.m_setFreeMarkID==free&&marks.imageLoads==1); + } + file(std::string("1 0\0junk\n",9));assert(!marks.LoadMarkIndex()&&marks.GetMarkCount()==2&&marks.imageLoads==1); + file("2 1\n");assert(marks.LoadMarkIndex()&&marks.GetMarkCount()==1&&!marks.m_mapGID_MarkID.count(1)); + file("");assert(marks.LoadMarkIndex()&&marks.GetMarkCount()==0&&marks.m_setFreeMarkID.size()==6400&&marks.CopyMarkIdx(nullptr,0)); +} +''') + def test_boot_table_counts_and_total_match_encoded_stream(self): + text=(ROOT/'src/server/db/src/ClientManager.cpp').read_text(encoding='latin1');actual=function(text,'void CClientManager::QUERY_BOOT')+function(text,'void CClientManager::ReloadAdmin(') + self.native(r''' +#include +#include +#include +#include +#include +#include +#include +using BYTE=uint8_t;using WORD=uint16_t;using DWORD=uint32_t;using LONG=int32_t;using INT=int32_t; +#include "src/server/common/tables.h" +#include "src/server/common/building.h" +#include "src/server/common/wire_bounds.h" +#define sys_log(...) ((void)0) +#define sys_err(...) ((void)0) +#define itertype(v) decltype((v).begin()) +bool g_test_server=false; +struct CPeer { + std::vector bytes;DWORD announced=0;int headers=0; + void EncodeHeader(int,int,DWORD size){announced=size;++headers;} + void Encode(const void* p,size_t n){if(!n)return;assert(p);const char* b=static_cast(p);bytes.insert(bytes.end(),b,b+n);} + void EncodeWORD(WORD value){Encode(&value,2);}int GetChannel(){return 1;} + void SetItemIDRange(TItemIDRangeTable){}void SetSpareItemIDRange(TItemIDRangeTable){} +}; +struct CMonarch { + using VEC_MONARCHCANDIDACY=std::vector;VEC_MONARCHCANDIDACY candidates;TMonarchInfo info={}; + static CMonarch& instance(){static CMonarch m;return m;}size_t MonarchCandidacySize(){return candidates.size();}VEC_MONARCHCANDIDACY& GetVecMonarchCandidacy(){return candidates;}TMonarchInfo* GetMonarch(){return &info;} +}; +struct CItemIDRangeManager {static CItemIDRangeManager& instance(){static CItemIDRangeManager m;return m;}TItemIDRangeTable GetRange(){return {};}}; +struct CClientManager { + std::vector m_vec_mobTable;std::vector m_vec_itemTable;std::vector m_vec_skillTable; + int m_iShopTableSize=0,m_iRefineTableSize=0;TShopTable* m_pShopTable=nullptr;TRefineTable* m_pRefineTable=nullptr; + std::vector m_vec_itemAttrTable,m_vec_itemRareTable;std::vector m_vec_banwordTable; + std::vector m_vec_kLandTable;std::vector m_vec_kObjectProto;std::map m_map_pkObjectTable; + std::vector m_peerList; + std::map m_Offlineshop;std::vector hosts;std::vector admins;bool queryOK=true; + bool __GetHostInfo(std::vector& out){out=hosts;return queryOK;}bool __GetAdminInfo(const char*,std::vector& out){out=admins;return queryOK;} + void QUERY_BOOT(CPeer*,TPacketGDBoot*);void ReloadAdmin(CPeer*,TPacketReloadAdmin*); +}; +'''+actual+r''' +int main(){ + PortBootSizer huge(0);assert(!huge.Add(UINT16_MAX,UINT16_MAX)&&!huge.Valid()&&!huge.Bytes()); + PortBootSizer invalid(UINT64_MAX);assert(!invalid.Add(0,0)&&!invalid.Bytes()); + CClientManager manager;TPacketGDBoot request={};CPeer peer;manager.QUERY_BOOT(&peer,&request);assert(peer.headers==1&&peer.announced==peer.bytes.size()); + manager.hosts={"1.2.3.4"};manager.m_vec_banwordTable.resize(2);CPeer normal;manager.QUERY_BOOT(&normal,&request);assert(normal.headers==1&&normal.announced==normal.bytes.size()); + DWORD declared=0;memcpy(&declared,normal.bytes.data(),4);assert(declared==normal.bytes.size()&&normal.bytes[4]==6); + manager.m_vec_banwordTable.resize(65536);CPeer overflow;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers&&overflow.bytes.empty());manager.m_vec_banwordTable.clear(); + manager.m_iShopTableSize=-1;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.m_iShopTableSize=1;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.m_iShopTableSize=0; + CPeer adminPeer;manager.m_peerList={&adminPeer};TPacketReloadAdmin adminRequest={};manager.ReloadAdmin(nullptr,&adminRequest);assert(adminPeer.headers==1&&adminPeer.announced==adminPeer.bytes.size()); + adminPeer={};manager.admins.resize(65536);manager.ReloadAdmin(nullptr,&adminRequest);assert(!adminPeer.headers&&adminPeer.bytes.empty());manager.admins.clear(); + manager.hosts={std::string(16,'x')};manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers);manager.hosts.clear();manager.queryOK=false;manager.QUERY_BOOT(&overflow,&request);assert(!overflow.headers); +} +''') +if __name__=='__main__':unittest.main() diff --git a/tools/ava2-itemshop/README.md b/tools/ava2-itemshop/README.md index 05d7aa5a..9bc9008c 100644 --- a/tools/ava2-itemshop/README.md +++ b/tools/ava2-itemshop/README.md @@ -67,3 +67,19 @@ coins, orders, awards and items were removed; its one test sale was subtracted w resetting other sales. Existing players received no test currency. db/auth/13 cores remained healthy after cleanup. macOS release bundle and connected Android client's APK/resources were updated; Android in-game purchase acceptance is not claimed by this release. + +## 2026-10-20 safety fixes (not deployed) + +`build_isolated.py` now requires a reviewed `--dependency-manifest`: JSON with `source_sha256` from `source_digest(source)` and `archives` mapping every source-relative `.a` path to SHA-256. The manifest binds reviewed dependency provenance to the exact server/extern sources; generating hashes alone does not certify provenance. FreeBSD is required. A fresh `game-release`, `db-release`, `game-warnings` or `db-warnings` directory is created beneath `--output`; reusing a target/mode directory fails. Source/dependency mismatches also fail. `--warnings` removes `-w`, enables format/conversion diagnostics and makes format/narrowing warnings errors. Build evidence and binary hashes are written to the new directory. FreeBSD validation remains required. + +The wear40 planner now binds database/server identity, a persistent target UUID, item identity/state, quickslots and a plan checksum. `--apply` requires `--offline --backup-id ID`. Reuse the exact saved v2 plan for interrupted runs; old unbound plans are rejected. A completed marker is rechecked against actual data and schema; corrupt extra is rejected before mutation. Backups and stopping writers remain operational prerequisites, not facts inferred from command success. + +Offline shop mutation and startup expiry cleanup are explicitly closed in game/db until durable custody/payment/delivery orders and crash recovery are implemented and accepted. Stored assets are preserved. This closure is a containment measure, not completion of offline trading. + +### Pending-reward journal maintenance + +`PointJournal` keeps its own durable pending set. Startup recovery and the retry event compact a log above 1 MiB when enough completed history can be removed. Compaction retains every pending token/request/time, writes a new file exclusively, fsyncs it, atomically renames it and fsyncs the directory. It does not cap the queue at 4096 entries. Do not pass a subset of runtime requests to replace the journal; there is deliberately no such API. + +Keep the `.lock` sidecar in place for the writer's lifetime. Stop old binaries before upgrading a process that uses the same journal path; mixed old/new concurrent writers are unsupported. An I/O error pauses issuance, retaining a complete recovery source; fix the storage problem and preserve journal evidence before restarting. A corrupt log is not automatically truncated or compacted. These changes have standalone fault tests, including ELF32 probes, and do not replace real database/process-crash acceptance. + +Strict builds also promote `-Wshorten-64-to-32` to an error. The broader strict warning gate is still failing on legacy code; see the maintenance evidence for the exact blockers. diff --git a/tools/ava2-itemshop/audit_completion.py b/tools/ava2-itemshop/audit_completion.py new file mode 100644 index 00000000..80c281fe --- /dev/null +++ b/tools/ava2-itemshop/audit_completion.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Check the exact remaining original offers and their staged dependencies. Never enables offers.""" +import argparse,collections,hashlib,json +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] +CLIENT=ROOT.parent/'metin2-client' +def feature(row): + v=row['vnum'];t=row['source_type'];sub=row['source_subtype'] + if v in (53998,53999):return 'costume_attribute_removal' + if v in (100001,100002):return 'dragon_soul_charge' + if v in (39063,39064):return 'gaya_consumables' + if v==71097:return 'dragon_soul_attribute_change' + if v==85009:return 'sash_detachment' + if v==6884:return 'rarity_conversion' + if v==72319:return 'offline_shop_key' + if v==72320:return 'storage_unlock' + if v==25159:return 'monthly_battlepass_ticket' + if v in (72067,72068):return 'rare_attribute_support' + if v in range(25163,25170):return 'dungeon_tickets' + if v==20059:return 'appearance_exchange_ticket' + if t=='ITEM_COSTUME':return sub.lower() + if t=='ITEM_PET':return 'growing_pet_'+sub.removeprefix('PET_').lower() + if t=='ITEM_GIFTBOX':return 'giftbox_reward_chain' + if t=='ITEM_TREASURE_KEY':return 'treasure_key_reward_chain' + if t=='ITEM_MATERIAL':return 'dragon_soul_refine_material' + if t=='ITEM_USE' and sub=='USE_CHANGE_ATTRIBUTE':return 'costume_fixed_attribute' + if t=='ITEM_UNIQUE':return 'unique_item_'+str(v) + if t=='ITEM_USE' and sub=='USE_AFFECT':return 'affect_consumable' + return 'quest_item_'+str(v) +def audit(staged=None,assets=None): + data=ROOT/'data/ava2-itemshop' + ledger=json.loads((data/'completion-168.json').read_text());remaining=ledger['products'] + baseline=json.loads((data/'verified-products.json').read_text())['products'] + originals={} + for line in (data/'original-products.tsv').read_text().splitlines(): + c=line.split('\t');key=int(c[0]);assert key not in originals,'duplicate original id';originals[key]=(int(c[3]),int(c[4])) + ids=[r['id'] for r in remaining];assert len(ids)==len(set(ids))==ledger['count']==168,'remaining identity/count changed' + baseids={r['id'] for r in baseline};assert len(baseids)==49 and not baseids.intersection(ids) + assert baseids.union(ids)==set(originals),'original catalogue not partitioned exactly' + rows={} + if staged: + for line in Path(staged).read_bytes().splitlines(): + c=line.split(b'\t') + if c[0].isdigit(): + v=int(c[0]);assert v not in rows,'duplicate staged vnum';rows[v]=[x.decode('gbk') for x in c] + # Resolve the exact original icon/model mapping; a missing explicit mapping is + # shown as missing rather than guessed to be a working model. + items={} + for line in (ROOT.parent/'AVA2/1. Client DEV/pack_maker/locale/locale/es/item_list.txt').read_text(encoding='latin1').splitlines(): + c=[x.strip().lower().replace('\\','/') for x in line.split('\t') if x.strip()] + if c and c[0].isdigit():items[int(c[0])]=c + result=[] + for r in remaining: + assert (r['vnum'],r['original_price'])==originals[r['id']],'offer identity or original price changed' + evidence=r.get('evidence',[]) + for name in evidence: + p=Path(name);p=p if p.is_absolute() else ROOT.parent/p + assert p.is_file(),'missing evidence source: '+name + v=r['vnum'];proto=rows.get(v);entry=items.get(v,[str(v),'etc','icon/item/%05d.tga'%v]);paths=entry[2:4] + ready=bool(proto and proto[2]!='ITEM_NONE' and proto[2:4]==[r['source_type'],r['source_subtype']]) + # QUEST_NONE/NONE are aliases for the zero subtype, not distinct handlers. + if proto and r['source_type']=='ITEM_QUEST':ready=proto[2]=='ITEM_QUEST' and proto[3] in ('0','NONE','QUEST_NONE') + result.append({'id':r['id'],'vnum':v,'original_price':r['original_price'],'feature':feature(r),'status':r['status'],'prototype_staged':ready if staged else None,'staged_type':proto[2:4] if proto else None,'direct_asset_paths':paths,'missing_direct_assets':[p for p in paths if not (Path(assets)/p).is_file()] if assets else None,'live_acceptance':'NOT_VERIFIED','evidence_sources':evidence}) + return {'count':168,'baseline_count':49,'original_count':len(originals),'scope':'dependency inventory; source paths and direct assets do not prove working gameplay, full resource closure or live acceptance','ledger_sha256':hashlib.sha256((data/'completion-168.json').read_bytes()).hexdigest(),'groups':dict(sorted(collections.Counter(r['feature'] for r in result).items())),'statuses':dict(collections.Counter(r['status'] for r in result)),'prototype_staged_count':sum(r['prototype_staged'] is True for r in result) if staged else None,'products':result} +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--staged-server-tsv',type=Path);p.add_argument('--assets',type=Path);p.add_argument('--output',type=Path,required=True);a=p.parse_args() + report=audit(a.staged_server_tsv,a.assets);a.output.parent.mkdir(parents=True,exist_ok=True);a.output.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(json.dumps({k:report[k] for k in ('count','groups','statuses','prototype_staged_count')},ensure_ascii=False)) +if __name__=='__main__':main() diff --git a/tools/ava2-itemshop/build_isolated.py b/tools/ava2-itemshop/build_isolated.py index 6c847b3a..97d8a3ef 100644 --- a/tools/ava2-itemshop/build_isolated.py +++ b/tools/ava2-itemshop/build_isolated.py @@ -1,29 +1,96 @@ #!/usr/bin/env python3 -"""Build game/db without either Makefile's production installation default.""" +"""Build a bound source snapshot in fresh per-target directories; never install it.""" import argparse +import hashlib +import json from pathlib import Path +import platform +import re +import shutil import subprocess +import sys + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def source_digest(source): + h=hashlib.sha256() + for part in ('server','extern'): + for path in sorted((source/part).rglob('*')): + if not path.is_file() or any(p in ('.obj','OBJDIR','obj','.git') for p in path.parts):continue + if path.suffix in ('.o','.a','.so','.d'):continue + h.update(str(path.relative_to(source)).encode()+b'\0'+path.read_bytes()+b'\0') + return h.hexdigest() + + +def validate_dependencies(source, manifest, revision): + if manifest.get('source_sha256')!=revision:raise ValueError('dependency manifest source mismatch') + archives=manifest.get('archives',{}) + actual={str(p.relative_to(source)):digest(p) for p in source.rglob('*.a')} + if not actual or archives!=actual:raise ValueError('all dependency archives must match the reviewed source-bound manifest') + for name, expected in manifest.get('system_archives',{}).items(): + dependency=Path(name) + if not dependency.is_absolute() or not dependency.is_file() or digest(dependency)!=expected: + raise ValueError('system dependency archive mismatch: '+name) + + +def prepare(source, output, target, dependency_manifest, warnings=False): + production=Path('/usr/metin2/server') + if output==production or production in output.parents or source==output or source in output.parents: + raise ValueError('output must be outside source and production trees') + revision=source_digest(source) + validate_dependencies(source,dependency_manifest,revision) + output.mkdir(parents=True,exist_ok=True) + state=output/'source-binding.json' + binding={'source':str(source),'sha256':revision,'dependencies':dependency_manifest} + if state.exists(): + if json.loads(state.read_text())!=binding:raise ValueError('output belongs to another source/dependency set') + elif any(output.iterdir()):raise ValueError('unbound output must be empty') + else:state.write_text(json.dumps(binding,indent=2)+'\n') + run=output/(target+('-warnings' if warnings else '-release')) + run.mkdir() # Never silently reuse objects, even after a failed build. + snapshot=run/'source' + snapshot.mkdir() + for name in ('server','extern'): + shutil.copytree(source/name,snapshot/name,ignore=shutil.ignore_patterns('*.o','.obj','OBJDIR','*.d')) + for target_dir in (snapshot/'server/game/src',snapshot/'server/db/src'): + makefile=target_dir/'Makefile' + text=makefile.read_bytes().decode('latin1') + # Depend paths must follow this target's OBJDIR, not the original checkout. + text=re.sub(r'(?X'00');") + if bad:raise RuntimeError('Corrupt extra: quarantine original rows before migration: '+repr(bad[:20])) sql('CREATE TABLE IF NOT EXISTS mt_migration(name VARCHAR(64) PRIMARY KEY,done DATETIME);') - if sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME): - print(NAME + ': already applied') - return + markers=sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME) + if markers and not has_extra:raise RuntimeError('Completed marker has missing extra schema') if args.plan.exists(): - plan = json.loads(args.plan.read_text()) - if plan['schema'] != args.player: - raise RuntimeError('Plan belongs to another database') + plan=json.loads(args.plan.read_text());validate_plan(plan,identity[0]) else: - # Equipped DS cells are relative; belt cells in INVENTORY are absolute. - bad = sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum " - "WHERE i.window='EQUIPMENT' AND i.pos>=32 AND " - "(i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));") - if bad: - raise RuntimeError('Unexpected occupied extended equipment cells; inspect before migration') - items = sql("SELECT id,pos FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) " - "OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;") - plan = {'schema': args.player, 'items': [[int(i), int(p), int(p)+8] for i, p in items], - 'quickslots': []} - for table in ('player', 'player_deleted'): - for pid, value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table): - old = bytes.fromhex(value) - new = quickslots(old) - if old != new: - plan['quickslots'].append([table, int(pid), old.hex(), new.hex()]) - args.plan.parent.mkdir(parents=True, exist_ok=True) - args.plan.write_text(json.dumps(plan, indent=2)+'\n') - args.plan.chmod(0o600) + if markers:raise RuntimeError('Completed marker has no bound plan; inspect instead of trusting marker') + bad=sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum WHERE i.window='EQUIPMENT' AND i.pos>=32 AND (i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));") + if bad:raise RuntimeError('Unexpected equipment cells; inspect before migration') + rows=sql("SELECT id,window,pos,vnum,owner_id,count,%s,%s FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL)) + plan={'version':2,'schema':args.player,'target':identity[0], 'items':[], 'quickslots':[], 'item_state':{}} + for item,window,pos,vnum,owner,count,extra,state in rows: + plan['item_state'][item]=state + plan['items'].append([int(item),window,int(pos),int(pos)+8,int(vnum),int(owner),int(count),extra]) + for table in ('player','player_deleted'): + for pid,value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table): + old=bytes.fromhex(value);new=quickslots(old) + if old!=new:plan['quickslots'].append([table,int(pid),old.hex(),new.hex()]) + plan['sha256']=plan_digest(plan);args.plan.parent.mkdir(parents=True,exist_ok=True);atomic_json(args.plan,plan) + validate_plan(plan,identity[0]) print('planned items=%d quickslots=%d' % (len(plan['items']), len(plan['quickslots']))) - if not args.apply: - return - # Every update is conditional on its original value, allowing safe saved-plan replay. - for item, old, new in plan['items']: - row = sql('SELECT pos FROM item WHERE id=%d;' % item) - if row not in ([[str(old)]], [[str(new)]]): - raise RuntimeError('Item changed since planning; cores/db must stay stopped') - sql('UPDATE item SET pos=%d WHERE id=%d AND pos=%d;' % (new, item, old)) + # Validate ALL rows before mutating any of them. Resume permits only each bound old/new state. + for item,window,old,new,vnum,owner,count,extra in plan['items']: + row=sql("SELECT window,pos,vnum,owner_id,count,%s,%s FROM item WHERE id=%d;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL,item)) + expected=[window,str(new if markers else old),str(vnum),str(owner),str(count),extra,plan['item_state'][str(item)]] + alternative=list(expected);alternative[1]=str(new) + if len(row)!=1 or row[0] not in (expected,alternative):raise RuntimeError('Item identity/state differs from bound plan: '+str(item)) for table, pid, old, new in plan['quickslots']: row = sql('SELECT HEX(quickslot) FROM `%s` WHERE id=%d;' % (table, pid)) - if not row or row[0][0].lower() not in (old, new): + if not row or row[0][0].lower() not in ((new,) if markers else (old,new)): raise RuntimeError('Quickslot changed since planning') + if not args.apply:return + if not has_extra: + sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ") + for item,window,old,new,vnum,owner,count,extra in plan['items']: + if markers:continue + sql("UPDATE item SET pos=%d WHERE id=%d AND window='%s' AND pos=%d AND vnum=%d AND owner_id=%d AND count=%d;" % (new,item,window,old,vnum,owner,count)) + for table,pid,old,new in plan['quickslots']: sql("UPDATE `%s` SET quickslot=X'%s' WHERE id=%d AND HEX(quickslot)='%s';" % (table, new, pid, old.upper())) - columns = sql("SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() " - "AND TABLE_NAME='item' AND COLUMN_NAME='port_extra';") - if not columns: - sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ") - sql("INSERT INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME) - print(NAME + ': applied; retain the saved plan for recovery') + # A completion marker is accepted only after re-reading every migrated target value. + for item,window,old,new,vnum,owner,count,extra in plan['items']: + if sql('SELECT pos FROM item WHERE id=%d;' % item)!=[[str(new)]]:raise RuntimeError('Item post-validation failed') + for table,pid,old,new in plan['quickslots']: + if sql('SELECT LOWER(HEX(quickslot)) FROM `%s` WHERE id=%d;' % (table,pid))!=[[new]]:raise RuntimeError('Quickslot post-validation failed') + validate_extra_schema(sql('SHOW COLUMNS FROM item;')) + sql("INSERT IGNORE INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME) + atomic_json(args.plan.with_name(args.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'target':identity[0],'backup_id':args.backup_id,'verified':True}) + print(NAME+': post-validated; preserve plan, receipt and backup') if __name__ == '__main__': diff --git a/tools/economy/README.md b/tools/economy/README.md new file mode 100644 index 00000000..2b47f0b8 --- /dev/null +++ b/tools/economy/README.md @@ -0,0 +1,157 @@ +# Durable economy transactions + +This is the replacement DB transaction path for offline sales and Gaya. It is +implemented separately from the unsafe legacy offline-shop protocol. Do not +change `PortOfflineShopEconomyReady()` to enable that old protocol. + +## Current entry points + +- `/mt_economy status [PAGE]` lists recent results, public/owned listings, + buyer orders and available proceeds. Pages start at zero. +- `/mt_economy list CELL PRICE` places the complete inventory stack in custody. +- `/mt_economy buy LISTING PRICE` reserves that listing and holds the price in + its order. An outdated price or another buyer's reservation is rejected. +- `/mt_economy refund ORDER` returns the held price and reopens the listing. +- `/mt_economy claim ORDER` moves the original item ID into the buyer account's + mall storage and credits the seller's proceeds in the same transaction. +- `/mt_economy cancel LISTING` returns an OPEN listing to its owner's mall. +- `/mt_economy withdraw` transfers available proceeds into character gold. +- `/mt_economy gaya_retire` retires a migrated catalogue after its Gaya + balance reaches zero and active listings, refundable orders and proceeds are + settled. It permanently disables this character's Gaya catalogue so the native + character deletion flow can proceed. It uses the same logout/save fences. + Positive balances are refused, never silently discarded or refunded. +- Existing `/gem buy`, refresh and expansion commands/items submit DB intents. + Gaya purchases deliver stable item IDs to account mall storage. Paid refresh + and expansion consume their item in the same transaction as their effect. + +All mutating requests close the game connection through the normal logout +path. Reconnect and select the same character: DB evicts its caches, completes +the queued SQL writes, settles the durable intent, and resumes character load. +No in-game gold, Gaya, inventory or paid catalogue change happens before this +handoff. `status` and the new `ui` query do not disconnect. The native client now +loads the original AVA2 offline window through its inventory button/F8 and routes +confirmed actions to this backend. Buying reserves an order; claiming is a +separate action that delivers to mall and credits the seller. Real connected +cross-channel/mobile acceptance is still pending. World NPC creation and legacy +NPC-to-new-seller mapping are not implemented by this window adapter. + +The window uses `/mt_economy ui MODE PAGE SEQ OWNER TOKEN` (mode 0 public, +1 owned, 2 READY orders; zero-based pages of 20). A consistent read transaction +builds and validates complete `MTECON1 begin/row/meta/result/end` command frames +before sending any. Read failures return `MTECON1 error SEQ storage`. +`/mt_economy act TOKEN OP ...` preserves a nonzero random 32-hex receipt for +list/buy/claim/refund/cancel/withdraw. List additionally carries expected vnum +and count. Account, character and wallet fields always come from the session; +exact-token receipt queries are account/character scoped. Immediate rejection +returns `MTECON1 action_error TOKEN rejected`. UiStatus=12 cannot be enqueued +as a mutation; schema version and internal record sizes are unchanged. + +An order remains READY until claimed or refunded; there is no automatic order +expiry. A full mall or gold/proceeds limit leaves the order/custody intact and +allows a later request. Seller proceeds become available after successful +delivery, rather than while the buyer can still refund the reservation. + +## Storage and ownership + +| Storage | Authority | +| --- | --- | +| `item` | Normal inventory, equipment, safebox and mall item rows | +| `port_economy_custody` | Exact original item row while a listing is OPEN/RESERVED | +| `port_economy_listings` | Seller, immutable price and current listing/order state | +| `port_economy_orders` | Held buyer payment and READY/CLAIMED/REFUNDED result | +| `port_economy_credit` | Seller proceeds awaiting withdrawal | +| `port_economy_requests` / `pending` | Immutable token/body, result and one pending intent per character | +| `port_economy_item_reservations` | Durable high-water marks for allocated Gaya reward IDs, including aborted intents | +| `port_economy_gaya` | Catalogue generation, deadline and all 27 offers | +| `player.gold` / `quest` gem flags | Character wallet and unlocked slots, changed only after logout/fencing | + +The old `offline_shop_npc`, `offline_shop_item`, `offline_shop_log` and +`player.shop_money` are preserved. They are **not imported or treated as new +orders**. Their old writes did not record enough evidence to infer missing +buyer refunds or delivery safely. Existing production custody and balances +must be reconciled against actual item IDs, owners, statuses and logs before +any live migration. This batch has not modified or inspected production assets. + +Custody uses an exact `CREATE TABLE ... LIKE item` layout; transactions copy all +stored columns, retaining sockets, attributes, extra state and the original ID. +Game item saves/destruction cannot write a custodial ID. ID range startup reads +the maximum across normal items, custody and durable reward reservations, so a +restart cannot reissue an escrowed or pending reward ID. Unmigrated legacy +`offline_shop_item` IDs are also reserved when that table exists, even before +the new economy schema is installed; lookup errors refuse range allocation. Reservation tombstones +must not be casually deleted during cleanup or rollback. + +Gaya imports an existing validated local catalogue on its first economic +transaction. Its committed SQL catalogue then supersedes the local file and +does not depend on that file/directory being writable. Balance, reward rows and +offer/generation commit together; refresh/expansion effects and consumables do +likewise. The normal quest-save path remains a wallet mirror during play and is +fully drained before settlement. Wallet snapshots that do not match persisted +values are rejected, rather than spending an older balance. + +Native character deletion is refused while there is pending work, active +custody, a refundable order, unclaimed proceeds or an active migrated Gaya +catalogue. Explicit `gaya_retire` preserves all offers, deadline and paid slots; +the reserved generation `9223372036854775807` marks the retained SQL row retired. +The immutable request records the original generation in its result reference. +Repeated retirement is harmless. Buy, refresh, expansion and local-file fallback +cannot reactivate the retired catalogue. Deletion remains blocked if a quest +writer later adds a nonzero Gaya balance. Spend Gaya and settle external assets +before retiring; this is not a balance forfeiture or currency conversion feature. +Use coordinated game/DB binaries that understand operation 11 and the terminal +generation. Existing table version 1 and request record sizes stay unchanged; +old pending requests remain readable. No additional startup DDL is required. + +## Installation and recovery boundaries + +`schema.sql` is an explicit, reviewable migration, never startup DDL. It supports +the unsuffixed player schema only. `player`, `item` and `quest`, plus every new +participant, must use InnoDB; readiness refuses missing/nontransactional tables +and differing custody/item column layouts. This script does not convert those +three existing tables or overwrite existing balances/history. Install and +change schemas only while all writers are stopped, with verified backups and +asset reconciliation. Schema presence is cached until process restart. + +Deploy matching game, DB and all internal libraries together: internal packet +77 and the AsyncSQL fence ABI require coordinated binaries. The classic client +wire version stays `mt20261024`; deploy the matching native window client and +its offline layout/image resources with this integration. +Do not downgrade to a version that ignores custody and ID reservations after +new transactions have been accepted. Disabling the old offline-shop gate is +not a recovery mechanism for the new path. + +SQL failures retain the same pending token for retry. An ambiguous COMMIT is +resolved from the committed request/order state. Connections can reconnect +before a new attempt, but automatic reconnect is disabled throughout a pinned +transaction. Failed final saves abort the intent without economic mutations. +Result/history and reservation rows are retained; no automatic log truncation +or destructive compensation is performed. + +## Verification + +`tests/features/test_economy.py` runs the actual C++ store with an explicit +SQLite SQL-dialect adapter and ASan/UBSan. The same C++ scenarios in +`fixtures/economy_probe.cpp` also run against isolated real MySQL 5.6/InnoDB on +FreeBSD i386. They cover all nine mutation types, each settlement statement/COMMIT exit +boundary after durable enqueue, competing buyers, duplicate claim/refund settlement, partial reward +SQL failure, full mall rollback, wallet changes and stable-ID replay. + +`test_economy_coordinator.py` executes the production DB coordinator with peer, +cache and FIFO completion boundaries replaced. `test_gaya_runtime.py` executes +the production Gaya unit with SQL/item-factory/submission boundaries replaced, +verifying it does not charge, grant or consume paid items in game. + +Evidence and real MySQL connection-loss/server-SIGKILL recovery results are in +the client repository's `audit/evidence/planb-economy-20261020/`. These tests do +not constitute a connected multi-core game/client or mobile-device acceptance. +No production installation or migration was performed. + +## Current acceptance scope + +The user excluded historical asset migration/compensation from the current +repair scope. Existing legacy rows remain preserved; no legacy import or refund +is implied by accepting new transactions. The optional read-only `reconcile.py` +utility is available for a future review and is not a current release gate. +Native NPC/window routing, complete connected acceptance, actual mall checkout, +mobile interaction and remaining Plan B product checks still require evidence. diff --git a/tools/economy/reconcile.py b/tools/economy/reconcile.py new file mode 100644 index 00000000..9481e373 --- /dev/null +++ b/tools/economy/reconcile.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Read-only legacy asset inventory. Never guesses refunds or writes game tables.""" +import argparse +from collections import Counter +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import xml.etree.ElementTree as ET + +TABLES = ('player', 'item', 'offline_shop_npc', 'offline_shop_item', + 'offline_shop_log', 'offline_shop_log_important', 'port_economy_custody', + 'port_economy_listings', 'port_economy_orders', 'port_economy_credit') +REQUIRED = {'player', 'item', 'offline_shop_item', 'offline_shop_npc', + 'offline_shop_log', 'offline_shop_log_important'} + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode() + + +def digest(value): + return hashlib.sha256(canonical(value)).hexdigest() + + +def xml_rows(output): + text = re.sub(r'<\?xml[^?]*\?>', '', output) + root = ET.fromstring('' + text + '') + return [[{f.attrib['name']: None if f.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}nil') == 'true' else (f.text or '') for f in row} for row in result.findall('row')] + for result in root.findall('resultset')] + + +def snapshot(defaults, database): + if not re.fullmatch(r'[A-Za-z0-9_]+', database): + raise ValueError('invalid database name') + def query(sql): + # Credentials remain in the supplied protected MySQL defaults file. + result = subprocess.run(['mysql', '--defaults-extra-file=' + str(defaults.resolve()), + '--xml', '--database=' + database, '--execute=' + sql], + check=True, capture_output=True) + return xml_rows(result.stdout.decode('utf-8')) + metadata = query("SELECT TABLE_NAME,COLUMN_NAME FROM information_schema.columns " + "WHERE TABLE_SCHEMA=DATABASE() ORDER BY TABLE_NAME,ORDINAL_POSITION")[0] + columns = {} + for row in metadata: + if row['TABLE_NAME'] in TABLES: + columns.setdefault(row['TABLE_NAME'], []).append(row['COLUMN_NAME']) + if not REQUIRED <= columns.keys(): + raise ValueError('required legacy tables missing: ' + ','.join(sorted(REQUIRED - columns.keys()))) + engines = query("SELECT TABLE_NAME,ENGINE FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE()")[0] + nontransactional = [r['TABLE_NAME'] for r in engines if r['TABLE_NAME'] in columns and r['ENGINE'] != 'InnoDB'] + if nontransactional: + raise ValueError('consistent snapshot requires InnoDB: ' + ','.join(nontransactional)) + sql = ['SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ', + 'START TRANSACTION WITH CONSISTENT SNAPSHOT'] + for table, names in columns.items(): + # Hex every value, including arbitrary binary metadata and names. NULL + # stays NULL; all original columns survive the review snapshot. + def ident(name): + return '`' + name.replace('`', '``') + '`' + sql.append('SELECT ' + ','.join('HEX(CAST(' + ident(n) + ' AS BINARY)) AS ' + ident(n) for n in names) + + ' FROM ' + ident(table)) + sql.append('COMMIT') + results = query(';'.join(sql)) + if len(results) != len(columns): + raise ValueError('incomplete snapshot') + tables = dict(zip(columns, results)) + # SELECT order is unspecified. Stable snapshots sort by complete row bytes. + for rows in tables.values(): + rows.sort(key=canonical) + payload = {'format': 1, 'encoding': 'mysql-hex-all-columns', 'tables': tables} + return dict(payload, sha256=digest(payload)) + + +def audit(snap): + payload = {k: v for k, v in snap.items() if k != 'sha256'} + if snap.get('format') != 1 or snap.get('encoding') != 'mysql-hex-all-columns' or digest(payload) != snap.get('sha256'): + raise ValueError('snapshot format or checksum mismatch') + if not REQUIRED <= snap['tables'].keys(): + raise ValueError('incomplete legacy snapshot') + def rows(table): + return [{k: bytes.fromhex(v).decode('utf-8', 'surrogateescape') if v is not None else None + for k, v in row.items()} for row in snap['tables'].get(table, [])] + def number(row, key, maximum=2**32-1): + value = row.get(key) + if value is None or not re.fullmatch(r'[0-9]+', value) or int(value) > maximum: + raise ValueError('invalid ' + key) + return int(value) + players = rows('player') + ids = Counter(r.get('id') for r in players) + owners = {r.get('id') for r in players if ids[r.get('id')] == 1} + normal = Counter(r.get('id') for r in rows('item')) + custody = Counter(r.get('id') for r in rows('port_economy_custody')) + legacy = rows('offline_shop_item') + duplicates = Counter(r.get('id') for r in legacy) + assets = [] + for row in legacy: + reasons = [] + try: + item = number(row, 'id'); owner = number(row, 'owner_id') + if not item or not owner or not number(row, 'count', 2000) or not number(row, 'vnum'): + reasons.append('invalid_item') + if number(row, 'price', 2_000_000_000_000_000) == 0: + reasons.append('invalid_price') + except ValueError: + reasons.append('invalid_numeric_fields') + if duplicates[row.get('id')] != 1: + reasons.append('duplicate_legacy_id') + if normal[row.get('id')] or custody[row.get('id')]: + reasons.append('item_id_exists_elsewhere') + if row.get('owner_id') not in owners: + reasons.append('owner_missing_or_duplicate') + extra = row.get('port_extra') + if extra is None or len(extra.encode('utf-8', 'surrogateescape')) != 69: + reasons.append('missing_or_invalid_full_item_metadata') + if row.get('status') != '0': + reasons.append('historical_order_requires_delivery_payment_evidence') + # A structurally valid row is only a candidate. It is never an approved + # migration: legacy statuses cannot prove ownership or refund liability. + assets.append({'key': 'legacy-item:' + str(row.get('id')), 'row_sha256': digest(row), + 'classification': 'quarantine' if reasons else 'custody_review', + 'reasons': reasons, 'action': 'manual_evidence_review'}) + for row in players: + if row.get('shop_money') not in (None, '0'): + reasons = [] + try: + number(row, 'shop_money', 2_000_000_000_000_000) + except ValueError: + reasons.append('invalid_balance') + assets.append({'key': 'legacy-proceeds:' + str(row.get('id')), 'row_sha256': digest(row), + 'classification': 'quarantine' if reasons else 'proceeds_review', + 'reasons': reasons, 'action': 'reconcile_logs_before_transfer'}) + history = {t: len(snap['tables'].get(t, [])) for t in ('offline_shop_log', 'offline_shop_log_important')} + return {'format': 1, 'snapshot_sha256': snap['sha256'], 'assets': assets, + 'history_rows': history, 'automatic_refunds': [], 'automatic_writes': [], + 'release_gate': 'BLOCKED_PENDING_RECONCILIATION', + 'required_review': 'Resolve every asset against original item metadata, owners, payments, deliveries and logs; missing evidence stays quarantined.'} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='command', required=True) + export = sub.add_parser('snapshot') + export.add_argument('--defaults-file', type=Path, required=True) + export.add_argument('--database', required=True) + export.add_argument('--output', type=Path, required=True) + inspect = sub.add_parser('audit') + inspect.add_argument('--snapshot', type=Path, required=True) + inspect.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + result = snapshot(args.defaults_file, args.database) if args.command == 'snapshot' else audit(json.loads(args.snapshot.read_text())) + # Refuse replacement of prior evidence; owner-only permissions for asset data. + with os.fdopen(os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as out: + out.write(json.dumps(result, indent=2, ensure_ascii=True) + '\n') + print(args.command + ' complete; no game tables modified') + + +if __name__ == '__main__': + main() diff --git a/tools/economy/schema.sql b/tools/economy/schema.sql new file mode 100644 index 00000000..83c8771d --- /dev/null +++ b/tools/economy/schema.sql @@ -0,0 +1,53 @@ +-- Explicit migration, never run at game startup. Select the player database. +-- player, item and quest MUST already use InnoDB. Back up before any production +-- engine conversion; this script intentionally does not convert those tables. +CREATE TABLE IF NOT EXISTS port_economy_version ( + id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_requests ( + token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY, + account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL, + body VARBINARY(8192) NOT NULL, + state ENUM('PENDING','DONE') NOT NULL, + result VARCHAR(64) NOT NULL, reference BIGINT UNSIGNED NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX player_history(pid,created_at) +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_pending ( + pid INT UNSIGNED PRIMARY KEY, token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_item_reservations ( + id INT UNSIGNED PRIMARY KEY, request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_account_lock ( + account INT UNSIGNED PRIMARY KEY +) ENGINE=InnoDB; +-- Exact column layout is checked before every transaction. All sockets, +-- attributes and port_extra bytes survive custody without reinterpretation. +CREATE TABLE IF NOT EXISTS port_economy_custody LIKE item; +ALTER TABLE port_economy_custody ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_listings ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + owner INT UNSIGNED NOT NULL, account INT UNSIGNED NOT NULL, + item INT UNSIGNED NOT NULL, INDEX custody_item(item), price BIGINT NOT NULL, + state ENUM('OPEN','RESERVED','SOLD','CANCELLED') NOT NULL, + active_order BIGINT UNSIGNED NOT NULL DEFAULT 0, + INDEX public_list(state,id), INDEX owner_list(owner,id) +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_orders ( + id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE, + listing BIGINT UNSIGNED NOT NULL, buyer INT UNSIGNED NOT NULL, + account INT UNSIGNED NOT NULL, price BIGINT NOT NULL, + state ENUM('READY','CLAIMED','REFUNDED') NOT NULL, + INDEX buyer_orders(buyer,id) +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_credit ( + pid INT UNSIGNED PRIMARY KEY, amount BIGINT NOT NULL DEFAULT 0 +) ENGINE=InnoDB; +CREATE TABLE IF NOT EXISTS port_economy_gaya ( + pid INT UNSIGNED PRIMARY KEY, generation BIGINT UNSIGNED NOT NULL, + deadline INT UNSIGNED NOT NULL, offers VARBINARY(351) NOT NULL +) ENGINE=InnoDB; +INSERT INTO port_economy_version(id,version) VALUES(1,1) + ON DUPLICATE KEY UPDATE version=version; diff --git a/tools/gold64/migrate_gold64.py b/tools/gold64/migrate_gold64.py new file mode 100644 index 00000000..42b7bff1 --- /dev/null +++ b/tools/gold64/migrate_gold64.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Plan/apply gold columns from the actual selected schemas; never truncate balances.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess + +MAXIMUM=2000000000000000 + + +def validate_column(kind): + if not re.fullmatch(r'(tinyint|smallint|mediumint|int|bigint)(\(\d+\))?( unsigned)?',kind.lower()): + raise ValueError('Unexpected money column definition: '+kind) + + +def fingerprint(value): + return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest() + + +def save(path,value): + temporary=path.with_name(path.name+'.new') + with temporary.open('x') as out: + os.chmod(temporary,0o600);json.dump(value,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno()) + os.replace(temporary,path) + fd=os.open(path.parent,os.O_RDONLY) + try:os.fsync(fd) + finally:os.close(fd) + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--player',required=True);p.add_argument('--log',required=True) + p.add_argument('--plan',type=Path,required=True);p.add_argument('--apply',action='store_true') + p.add_argument('--offline',action='store_true');p.add_argument('--backup-id') + a=p.parse_args() + if not all(re.fullmatch(r'[A-Za-z0-9_]+',s) for s in (a.player,a.log)):p.error('Invalid schema name') + if a.apply and (not a.offline or not a.backup_id):p.error('Apply requires --offline --backup-id') + def sql(query): + r=subprocess.run(['mysql','-N','-B'],input=query,text=True,capture_output=True,check=True) + return [line.split('\t') for line in r.stdout.splitlines()] + identity=sql('SELECT @@hostname,@@port,@@server_id,@@version;') + if len(identity)!=1:raise RuntimeError('Unknown server identity') + required=[(a.player,t,'gold',True) for t in ('player','player_deleted','safebox','guild')]+[(a.log,'money_log','gold',False)] + optional=[(a.log,'log','what',False)]+[(a.player,t,c,False) for t,c in [('player','shop_money'),('offline_shop_item','price'),('offline_shop_log','price'),('offline_shop_log_important','price')]] + rows=[];ddl={} + for schema,table,column,unsigned in required+optional: + definition=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(schema,table,column)) + if len(definition)!=1: + if (schema,table,column,unsigned) in optional:continue + raise RuntimeError('Missing required column: '+'.'.join((schema,table,column))) + validate_column(definition[0][0]) + if definition[0][3]:raise RuntimeError('Generated/automatic money columns require explicit review') + target='bigint(20)'+(' unsigned' if unsigned else '') + upper=(2**63-1) if schema==a.log else MAXIMUM + lower=-(2**63) if schema==a.log else 0 + invalid=sql('SELECT COUNT(*) FROM `%s`.`%s` WHERE `%s` IS NULL OR `%s`>%d OR `%s`<%d;'%(schema,table,column,column,upper,column,lower)) + if invalid!=[['0']]:raise RuntimeError('Out of range/null money data: '+schema+'.'+table+'.'+column) + key=schema+'.'+table + if key not in ddl:ddl[key]=sql('SHOW CREATE TABLE `%s`.`%s`;'%(schema,table)) + rows.append({'schema':schema,'table':table,'column':column,'before':definition[0],'target':target}) + if a.plan.exists(): + plan=json.loads(a.plan.read_text());checksum=plan.get('sha256');base={k:v for k,v in plan.items() if k!='sha256'} + if plan.get('version')!=1 or plan.get('identity')!=identity[0] or checksum!=fingerprint(base):raise RuntimeError('Foreign/stale/corrupt plan') + if [(r['schema'],r['table'],r['column']) for r in rows]!=[(r['schema'],r['table'],r['column']) for r in plan['columns']]:raise RuntimeError('Column inventory differs from plan') + for current,bound in zip(rows,plan['columns']): + if current['before']!=bound['before'] and current['before'][:2]!=[bound['target'],'NO']:raise RuntimeError('Column changed since planning') + else: + plan={'version':1,'identity':identity[0],'columns':rows,'show_create':ddl};plan['sha256']=fingerprint(plan) + a.plan.parent.mkdir(parents=True,exist_ok=True);save(a.plan,plan) + if not a.apply: + print('PLAN ONLY: review '+str(a.plan));return + for row in plan['columns']: + sql('ALTER TABLE `%s`.`%s` MODIFY COLUMN `%s` %s NOT NULL DEFAULT 0;'%(row['schema'],row['table'],row['column'],row['target'])) + actual=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(row['schema'],row['table'],row['column'])) + if actual!=[[row['target'],'NO','0']]:raise RuntimeError('Money column post-validation failed') + save(a.plan.with_name(a.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'backup_id':a.backup_id,'verified':True}) + print('PASS: columns verified; balances preserved. Runtime release acceptance is separate.') + + +if __name__=='__main__':main() diff --git a/tools/gold64/migrate_gold64.sql b/tools/gold64/migrate_gold64.sql index d33da2f1..6e9ad8e8 100644 --- a/tools/gold64/migrate_gold64.sql +++ b/tools/gold64/migrate_gold64.sql @@ -1,14 +1,4 @@ --- Metin2 64-bit Gold Migration Script --- Target: player database (player, safebox, guild) --- GOLD_MAX_64 = 2,000,000,000,000,000 (2 quadrillion / 2000万亿) - -USE `player`; - --- 1. Upgrade player.gold to BIGINT(20) UNSIGNED -ALTER TABLE `player` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0; - --- 2. Upgrade safebox.gold to BIGINT(20) UNSIGNED -ALTER TABLE `safebox` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0; - --- 3. Upgrade guild.gold to BIGINT(20) UNSIGNED -ALTER TABLE `guild` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0; +-- Blind DDL cannot verify schema identity, player_deleted, or the actual money_log. +-- Use migrate_gold64.py --player SCHEMA --log LOG_SCHEMA --plan PATH. +-- Apply the reviewed plan with --apply --offline --backup-id BACKUP. +SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Use the source-bound gold migration planner; blind DDL is disabled'; diff --git a/tools/gold64/rollback_gold64.sql b/tools/gold64/rollback_gold64.sql index 3e890cec..fa5f14e4 100644 --- a/tools/gold64/rollback_gold64.sql +++ b/tools/gold64/rollback_gold64.sql @@ -1,19 +1,4 @@ --- Metin2 64-bit Gold Rollback Script --- Target: player database (player, safebox, guild) --- Restores gold column to INT(11) with clamp to 2,000,000,000 to prevent data truncation errors - -USE `player`; - --- 1. Clamp values exceeding 2,000,000,000 before downcasting -UPDATE `player` SET `gold` = 2000000000 WHERE `gold` > 2000000000; -UPDATE `safebox` SET `gold` = 2000000000 WHERE `gold` > 2000000000; -UPDATE `guild` SET `gold` = 2000000000 WHERE `gold` > 2000000000; - --- 2. Restore player.gold to INT(11) NOT NULL DEFAULT 0 -ALTER TABLE `player` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0; - --- 3. Restore safebox.gold to INT(11) NOT NULL DEFAULT 0 -ALTER TABLE `safebox` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0; - --- 4. Restore guild.gold to INT(11) NOT NULL DEFAULT 0 -ALTER TABLE `guild` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0; +-- Asset-preserving rollback: keep the expanded schema and every balance. +-- Deploy a compatible binary that reads/writes BIGINT while disabling new features. +-- An automatic downgrade to INT is intentionally prohibited. +SELECT 'Keep BIGINT balances; use the compatible rollback binary' AS rollback_policy;