feat(server): save economy hardening and CH5 continuation work
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
// 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.operation<List || r.operation>UiStatus ||
|
||||
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;i<r.rewardCount;++i) {
|
||||
if(!r.rewards[i].id || !r.rewards[i].vnum || !r.rewards[i].count || r.rewards[i].count>2000)return false;
|
||||
for(unsigned j=0;j<i;++j)if(r.rewards[j].id==r.rewards[i].id)return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
inline std::string Hex(const void* data,size_t size) {
|
||||
const auto* p=static_cast<const unsigned char*>(data);static const char hex[]="0123456789abcdef";
|
||||
std::string out;out.reserve(size*2);
|
||||
for(size_t i=0;i<size;++i){out+=hex[p[i]>>4];out+=hex[p[i]&15];}return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
#include "economy_store.h"
|
||||
#include <mysql/mysql.h>
|
||||
#include <mysql/errmsg.h>
|
||||
|
||||
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<void(const std::string&)> 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<unsigned>(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<unsigned long>(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<std::string> values;
|
||||
for(unsigned i=0;i<fields;++i)values.emplace_back(row[i]?std::string(row[i],lengths[i]):std::string());
|
||||
rows.push_back(std::move(values));
|
||||
}
|
||||
const bool ok=mysql_errno(connection)==0;mysql_free_result(result);if(!ok)return false;
|
||||
} else if(mysql_field_count(connection))return false;
|
||||
affected=mysql_affected_rows(connection);inserted=mysql_insert_id(connection);
|
||||
if(afterStatement)afterStatement(sql);
|
||||
return mysql_thread_id(connection)==thread;
|
||||
}
|
||||
bool Begin(){Rows rows;if(active||!previousTimeout||!Query("SET SESSION innodb_lock_wait_timeout=3",rows)||!Query("START TRANSACTION",rows))return false;active=true;return true;}
|
||||
bool Commit(){Rows rows;if(!active||!Query("COMMIT",rows))return false;active=false;return true;}
|
||||
void Rollback(){if(active){Rows rows;Query("ROLLBACK",rows);active=false;}}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
#pragma once
|
||||
#include "economy.h"
|
||||
#include <array>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace PortEconomy {
|
||||
using Rows=std::vector<std::vector<std::string>>;
|
||||
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 DB> class Store {
|
||||
DB& db;
|
||||
std::function<unsigned(uint32_t)> 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<int32_t>(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<uint32_t>(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<bool,135> 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<uint32_t>(id));if(h<1 || h>3 || (pos%45)/5+h>9)return Reject("mall_corrupt");
|
||||
for(unsigned j=0;j<h;++j){const size_t at=static_cast<size_t>(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<height;++j)if(used[pos+5*j])free=false;
|
||||
if(free){cell=pos;return true;}
|
||||
}
|
||||
return Reject("mall_full");
|
||||
}
|
||||
bool Deliver(uint32_t item,uint32_t account,uint32_t vnum) {
|
||||
unsigned cell=0;if(!MallCell(account,vnum,cell))return false;
|
||||
// Copy all columns by ordinal: readiness checks exact custody/item schema.
|
||||
if(!Change("INSERT INTO item SELECT * FROM port_economy_custody WHERE id="+N(item)))return false;
|
||||
return Change("UPDATE item SET owner_id="+N(account)+",window='MALL',pos="+N(cell)+" WHERE id="+N(item))&&
|
||||
Change("DELETE FROM port_economy_custody WHERE id="+N(item));
|
||||
}
|
||||
bool Consume(const Request& r,uint32_t vnum) {
|
||||
Rows rows;uint64_t count=0;
|
||||
if(!One("SELECT count FROM item WHERE id="+N(r.item)+" AND owner_id="+N(r.player)+" AND window='INVENTORY' AND pos<225 AND vnum="+N(vnum)+" FOR UPDATE",rows)||!Number(rows[0][0],count,2000)||!count||count!=r.itemCount)return Reject("consumable_changed");
|
||||
if(count==1)return Change("DELETE FROM item WHERE id="+N(r.item));
|
||||
return Change("UPDATE item SET count=count-1 WHERE id="+N(r.item));
|
||||
}
|
||||
bool Apply(const Request& r,uint64_t gold) {
|
||||
const std::string pid=N(r.player),aid=N(r.account);
|
||||
Rows rows;uint64_t a=0,b=0,c=0,d=0;
|
||||
switch(r.operation) {
|
||||
case List:
|
||||
if(!One("SELECT id FROM item WHERE id="+N(r.item)+" AND owner_id="+pid+" AND window='INVENTORY' AND vnum="+N(r.itemVnum)+" AND count="+N(r.itemCount)+" AND pos<225 FOR UPDATE",rows))return Reject("item_changed");
|
||||
if(!Change("INSERT INTO port_economy_custody SELECT * FROM item WHERE id="+N(r.item))||!Change("DELETE FROM item WHERE id="+N(r.item)))return false;
|
||||
if(!Change("INSERT INTO port_economy_listings(owner,account,item,price,state) VALUES("+pid+","+aid+","+N(r.item)+","+N(static_cast<uint64_t>(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<int64_t>(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<uint32_t>(d),r.account,static_cast<uint32_t>(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<uint32_t>(a),r.account,static_cast<uint32_t>(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<uint64_t>(r.expectedGem)||b!=static_cast<uint64_t>(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<uint64_t>(r.expectedGem)||open!=static_cast<uint64_t>(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.nextDeadline<deadline || (!r.item && r.nextDeadline==deadline))return Reject("refresh_changed");
|
||||
if(r.item) {if(!Consume(r,39063))return false;}
|
||||
else {if(!One("SELECT UNIX_TIMESTAMP()",rows)||!Number(rows[0][0],a)||uint64_t(deadline)>a)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<uint32_t>(r.nextDeadline));
|
||||
}
|
||||
auto& offer=offers[r.slot];
|
||||
if(offer.bought|| (r.slot>=9 && open<uint64_t(r.slot-8)) || gem<static_cast<uint32_t>(offer.price))return Reject("offer_unavailable");
|
||||
uint64_t total=0;
|
||||
for(unsigned i=0;i<r.rewardCount;++i) {
|
||||
const auto& reward=r.rewards[i];if(reward.vnum!=offer.vnum)return Reject("reward_changed");total+=reward.count;
|
||||
unsigned cell=0;if(!MallCell(r.account,reward.vnum,cell))return false;
|
||||
std::string columns="id,owner_id,window,pos,count,vnum",values=N(reward.id)+","+aid+",'MALL',"+N(cell)+","+N(reward.count)+","+N(reward.vnum);
|
||||
for(unsigned j=0;j<3;++j){columns+=",socket"+N(j);values+=","+std::to_string(reward.sockets[j]);}
|
||||
for(unsigned j=0;j<7;++j){columns+=",attrtype"+N(j)+",attrvalue"+N(j);values+=","+N(reward.types[j])+","+std::to_string(reward.values[j]);}
|
||||
columns+=",port_extra";values+=",X'"+Hex(reward.extra,sizeof(reward.extra))+"'";
|
||||
if(!Change("INSERT INTO item("+columns+") VALUES("+values+")"))return false;
|
||||
}
|
||||
if(total!=offer.count)return Reject("reward_changed");
|
||||
offer.bought=1;
|
||||
return SetQuest(r.player,"points",gem-static_cast<uint32_t>(offer.price))&&SaveCatalog(r.player,offers,generation,deadline);
|
||||
}
|
||||
default:return Reject("invalid_operation");
|
||||
}
|
||||
}
|
||||
public:
|
||||
Store(DB& database,std::function<unsigned(uint32_t)> 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.rewardCount && success;++i) {
|
||||
Rows existing;
|
||||
success=Q("SELECT id FROM item WHERE id="+N(r.rewards[i].id)+" UNION ALL SELECT id FROM port_economy_custody WHERE id="+N(r.rewards[i].id),existing)&&existing.empty()&&
|
||||
Change("INSERT INTO port_economy_item_reservations(id,request) VALUES("+N(r.rewards[i].id)+",'"+token+"')");
|
||||
}
|
||||
success=success&&Change("INSERT INTO port_economy_pending(pid,token) VALUES("+N(r.player)+",'"+token+"')")&&
|
||||
Change("INSERT INTO port_economy_requests(token,account,pid,body,state,result,reference) VALUES('"+token+"',"+N(r.account)+","+N(r.player)+",X'"+body+"','PENDING','queued',0)");
|
||||
}
|
||||
}
|
||||
if(success&&db.Commit())return true;db.Rollback();return false;
|
||||
}
|
||||
enum Result { Retry, None, Settled };
|
||||
bool Abort(uint32_t pid,uint32_t account) {
|
||||
if(!Ready()||!db.Begin())return false;
|
||||
Rows rows;
|
||||
bool done=One("SELECT r.token FROM port_economy_pending p JOIN port_economy_requests r ON r.token=p.token WHERE p.pid="+N(pid)+" AND r.pid="+N(pid)+" AND r.account="+N(account)+" AND r.state='PENDING' FOR UPDATE",rows)&&
|
||||
Change("UPDATE port_economy_requests SET state='DONE',result='save_failed' WHERE pid="+N(pid)+" AND account="+N(account)+" AND state='PENDING'")&&
|
||||
Run("DELETE FROM port_economy_pending WHERE pid="+N(pid));
|
||||
if(done&&db.Commit())return true;db.Rollback();return false;
|
||||
}
|
||||
Result Settle(uint32_t pid,uint32_t account) {
|
||||
if(!Ready()||!db.Begin())return Retry;
|
||||
Rows rows;Request r;uint64_t gold=0;
|
||||
if(!Q("SELECT token FROM port_economy_pending WHERE pid="+N(pid)+" FOR UPDATE",rows)){db.Rollback();return Retry;}
|
||||
if(rows.empty()){db.Rollback();return None;}
|
||||
const std::string token=rows[0][0];
|
||||
if(!One("SELECT body FROM port_economy_requests WHERE token='"+token+"' AND account="+N(account)+" AND pid="+N(pid)+" AND state='PENDING' FOR UPDATE",rows)||rows[0][0].size()!=sizeof(r)){db.Rollback();return Retry;}
|
||||
std::memcpy(&r,rows[0][0].data(),sizeof(r));
|
||||
if(!Valid(r)||r.player!=pid||r.account!=account||std::string(r.token)!=token){db.Rollback();return Retry;}
|
||||
if(!Run("INSERT INTO port_economy_account_lock(account) VALUES("+N(account)+") ON DUPLICATE KEY UPDATE account=VALUES(account)")||!One("SELECT account FROM port_economy_account_lock WHERE account="+N(account)+" FOR UPDATE",rows)){db.Rollback();return Retry;}
|
||||
if(!One("SELECT gold FROM player WHERE id="+N(pid)+" AND account_id="+N(account)+" FOR UPDATE",rows)||!Number(rows[0][0],gold,GoldLimit)){db.Rollback();return Retry;}
|
||||
// A save lost before logout cannot authorize spending an older snapshot.
|
||||
outcome="ok";reference=0;
|
||||
if(gold!=static_cast<uint64_t>(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;}
|
||||
};
|
||||
}
|
||||
@@ -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<uint64_t>(-minimum):static_cast<uint64_t>(maximum)))return false;
|
||||
out=negative?-static_cast<int64_t>(value):static_cast<int64_t>(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<class DB> bool View(DB& db,const Request& r,std::function<unsigned(uint32_t)> height,std::vector<std::string>& 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<rows.size();++index) {
|
||||
const auto& row=rows[index];if(row.size()!=24)return fail();
|
||||
uint64_t id=0,price=0,owner=0,vnum=0,count=0;
|
||||
if(!Number(row[0],id)||!id||!Number(row[1],price,GoldLimit)||!price||!Number(row[2],owner,UINT32_MAX)||!owner||
|
||||
!Number(row[3],vnum,UINT32_MAX)||!vnum||!Number(row[4],count,2000)||!count)return fail();
|
||||
unsigned state=row[5]=="OPEN"?0:row[5]=="RESERVED"?1:row[5]=="READY"?2:3;
|
||||
const unsigned size=height(static_cast<uint32_t>(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<uint16_t>(value);attrs[3*i]=static_cast<uint8_t>(type);attrs[3*i+1]=static_cast<uint8_t>(bits&255);attrs[3*i+2]=static_cast<uint8_t>(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <fcntl.h>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// 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<class Item> 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<class Item> Result Load(std::map<uint8_t,Item>& 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<int>(parsed);
|
||||
}
|
||||
std::map<uint8_t,Item> 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<uint32_t>(values[1]);item.itemCount=static_cast<uint32_t>(values[2]);item.itemPrice=static_cast<int>(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<class Item> bool Save(const std::map<uint8_t,Item>& 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<<unsigned(row.first)<<' '<<i.itemVnum<<' '<<i.itemCount<<' '<<i.itemPrice<<' '<<(i.itemBuyed?1:0)<<'\n';}
|
||||
const std::string body=rows.str(),bytes="gaya-v2 "+std::to_string(refresh)+" "+std::to_string(Hash(body))+"\n"+body;
|
||||
const std::string temporary=name_+".tmp."+std::to_string(getpid());
|
||||
int fd=openat(directory_,temporary.c_str(),O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW,0600);
|
||||
if(fd<0)return Fail("cannot create catalogue snapshot");
|
||||
bool written=true;size_t offset=0;
|
||||
while(offset<bytes.size()){ssize_t n=write(fd,bytes.data()+offset,bytes.size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0){written=false;break;}offset+=size_t(n);}
|
||||
if(written && fsync(fd)!=0)written=false;
|
||||
if(close(fd)!=0)written=false;
|
||||
if(!written){unlinkat(directory_,temporary.c_str(),0);return Fail("catalogue write/fsync failed; old snapshot retained");}
|
||||
if(renameat(directory_,temporary.c_str(),directory_,name_.c_str())!=0){unlinkat(directory_,temporary.c_str(),0);return Fail("catalogue replace failed; old snapshot retained");}
|
||||
if(fsync(directory_)!=0)return Fail("catalogue directory fsync failed; snapshot outcome requires reload");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
inline bool PortGayaNextRefresh(int64_t now,int previous,bool elapsedCadence,int& next) {
|
||||
const int64_t period=5*60*60;
|
||||
if(now<0 || now>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<int>(result);return true;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
// 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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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; }
|
||||
@@ -0,0 +1,131 @@
|
||||
#pragma once
|
||||
#include "ava2_itemshop.h"
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// 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<std::string,Entry> 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 "<<r.token<<' '<<r.account<<' '<<r.player<<' '<<r.product<<' '<<r.count<<' '<<r.expectedVnum<<' '<<entry.created;return out.str();
|
||||
}
|
||||
static std::string Record(const std::string& payload){char checksum[16];snprintf(checksum,sizeof(checksum)," %08x\n",Hash(payload));return payload+checksum;}
|
||||
static bool WriteAll(int fd,const std::string& line){
|
||||
size_t offset=0;while(offset<line.size()){const ssize_t n=write(fd,line.data()+offset,line.size()-offset);if(n<0&&errno==EINTR)continue;if(n<=0)return false;offset+=static_cast<size_t>(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<std::string,Ava2ShopRequest>& 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<uint64_t>(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<uint32_t>(account);r.player=static_cast<uint32_t>(player);r.product=static_cast<uint32_t>(product);r.count=static_cast<uint32_t>(count);r.expectedVnum=static_cast<uint32_t>(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<unsigned>(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<uint64_t>(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 "<<token<<' '<<unsigned(status)<<' '<<granted<<' '<<balance<<' '<<uint64_t(time(0));
|
||||
if(!Append(out.str()))return false;pending_.erase(found);return true;
|
||||
}
|
||||
bool Compact(){
|
||||
if(!healthy_)return false;
|
||||
const std::string temporary=name_+".compact."+std::to_string(getpid());
|
||||
const int next=openat(directory_,temporary.c_str(),O_RDWR|O_CREAT|O_EXCL|O_APPEND|O_NOFOLLOW,0600);
|
||||
if(next<0)return Fail("cannot create journal compact snapshot; original retained");
|
||||
uint64_t size=0;bool valid=flock(next,LOCK_EX|LOCK_NB)==0;
|
||||
for(const auto& entry:pending_){if(!valid)break;const auto line=Record(IntentPayload(entry.second));valid=WriteAll(next,line);size+=line.size();}
|
||||
if(valid)valid=fsync(next)==0;
|
||||
if(!valid){close(next);unlinkat(directory_,temporary.c_str(),0);return Fail("cannot persist journal compact snapshot; original retained");}
|
||||
if(renameat(directory_,temporary.c_str(),directory_,name_.c_str())!=0){close(next);unlinkat(directory_,temporary.c_str(),0);return Fail("cannot publish journal compact snapshot; original retained");}
|
||||
const int previous=fd_;fd_=next;bytes_=size;
|
||||
const bool synced=fsync(directory_)==0;close(previous);
|
||||
if(!synced)return Fail("journal compact directory sync failed; issuance paused; both snapshots retain pending intentions");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
@@ -22,11 +22,13 @@ inline std::string PortItemExtraHex(const PortItemExtra& extra) {
|
||||
return result;
|
||||
}
|
||||
inline bool PortItemExtraRead(const char* hex,PortItemExtra& extra) {
|
||||
std::memset(&extra,0,sizeof(extra));
|
||||
if(!hex || !*hex)return true;
|
||||
if(std::strlen(hex)!=sizeof(extra)*2)return false;
|
||||
PortItemExtra decoded = {};
|
||||
if(!hex)return false;
|
||||
if(!*hex){extra=decoded;return true;}
|
||||
if(std::strlen(hex)!=sizeof(decoded)*2)return false;
|
||||
auto nibble=[](char c){return c>='0' && c<='9'?c-'0':c>='A' && c<='F'?c-'A'+10:c>='a' && c<='f'?c-'a'+10:-1;};
|
||||
auto p=reinterpret_cast<unsigned char*>(&extra);
|
||||
for(unsigned i=0;i<sizeof(extra);++i){int a=nibble(hex[2*i]),b=nibble(hex[2*i+1]);if(a<0 || b<0){std::memset(&extra,0,sizeof(extra));return false;}p[i]=(a<<4)|b;}
|
||||
extra.name[24]=0;return true;
|
||||
auto p=reinterpret_cast<unsigned char*>(&decoded);
|
||||
for(unsigned i=0;i<sizeof(decoded);++i){int a=nibble(hex[2*i]),b=nibble(hex[2*i+1]);if(a<0 || b<0)return false;p[i]=static_cast<unsigned char>((a<<4)|b);}
|
||||
if(decoded.name[24]!=0)return false;
|
||||
extra=decoded;return true;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef __INC_METIN_II_STL_H__
|
||||
#define __INC_METIN_II_STL_H__
|
||||
|
||||
#include <cctype>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <map>
|
||||
@@ -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<char>(std::tolower(static_cast<unsigned char>(rstRet[i])));
|
||||
}
|
||||
|
||||
struct stringhash
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
/*----- 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)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// 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<uint32_t>(bytes_):0;}
|
||||
};
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "ItemAwardManager.h"
|
||||
#include "../../common/ava2_itemshop.h"
|
||||
#include "../../common/point_drop.h"
|
||||
#include <cerrno>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <cctype>
|
||||
@@ -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 || parsed<minimum || parsed>maximum)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<uint32_t>(n[0]);p.vnum=static_cast<uint32_t>(n[1]);p.price=n[2];p.discount=static_cast<uint8_t>(n[3]);p.expiry=static_cast<int32_t>(n[4]);p.added=static_cast<int32_t>(n[5]);p.sold=n[6];p.weekly=static_cast<int32_t>(n[7]);p.monthly=static_cast<int32_t>(n[8]);p.stock=static_cast<int32_t>(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.count<uint32_t(rule.minimum) || r.count>uint32_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.count<uint32_t(rule.minimum) || r.count>uint32_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<uint8_t,std::map<uint8_t,std::vector<Ava2ShopProduct>>> 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<uint8_t>(cat)][static_cast<uint8_t>(sub)].push_back(p);
|
||||
}
|
||||
std::vector<Ava2ShopProduct*> ranked;
|
||||
for(auto& cat:catalogue)for(auto& sub:cat.second)for(auto& p:sub.second)ranked.push_back(&p);
|
||||
|
||||
+142
-115
@@ -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<tAdminInfo> vAdmin;
|
||||
std::vector<std::string> 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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<TPlayerItem> 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<TItemAward *> * 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()<UINT16_MAX)
|
||||
{
|
||||
TItemAward * pItemAward = *(it++);
|
||||
const DWORD& dwItemVnum = pItemAward->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<uint32_t>(pmsg->Get()->uiInsertID);
|
||||
item.window = pi->ip[0] == 0 ? SAFEBOX : MALL,
|
||||
item.pos = iPos;
|
||||
item.pos = static_cast<WORD>(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<WORD>(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<unsigned long long>(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<BYTE>(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<WORD>(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<WORD>(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<WORD>(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<WORD>(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<SQLMsg> 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<SQLMsg> 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<unsigned long long>(pMsg->Get()->uiNumRows));
|
||||
|
||||
m_vec_Locale.clear();
|
||||
|
||||
@@ -3785,16 +3817,13 @@ bool CClientManager::__GetAdminInfo(const char *szIP, std::vector<tAdminInfo> &
|
||||
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<size_t>(pMsg->Get()->uiNumRows));
|
||||
|
||||
while ((row = mysql_fetch_row(pMsg->Get()->pSQLResult)))
|
||||
{
|
||||
@@ -3837,15 +3866,12 @@ bool CClientManager::__GetHostInfo(std::vector<std::string> & 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<size_t>(pMsg->Get()->uiNumRows));
|
||||
|
||||
MYSQL_ROW row;
|
||||
|
||||
@@ -3868,11 +3894,11 @@ void CClientManager::ReloadAdmin(CPeer*, TPacketReloadAdmin* p)
|
||||
std::vector<tAdminInfo> vAdmin;
|
||||
std::vector<std::string> 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<WORD>(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<WORD>(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();
|
||||
|
||||
|
||||
@@ -30,7 +30,19 @@ size_t CreatePlayerSaveQuery(char * pszQuery, size_t querySize, TPlayerTable * p
|
||||
|
||||
class CClientManager : public CNetBase, public singleton<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<DWORD,std::pair<uint64_t,uint64_t>> m_economyEnqueueEpoch;
|
||||
std::map<DWORD,EconomyFence> m_economyFences;
|
||||
std::map<DWORD,DWORD> m_economyOwners;
|
||||
std::set<DWORD> 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<CPeer *> TPeerList;
|
||||
typedef std::unordered_map<DWORD, CPlayerTableCache *> TPlayerTableCacheMap;
|
||||
typedef std::unordered_map<DWORD, CItemCache *> TItemCacheMap;
|
||||
@@ -122,6 +134,7 @@ class CClientManager : public CNetBase, public singleton<CClientManager>
|
||||
|
||||
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();
|
||||
|
||||
@@ -118,6 +118,7 @@ bool CClientManager::InitializeRefineTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> 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<int>(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<SQLMsg> 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<SQLMsg> 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<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
int col;
|
||||
@@ -952,6 +956,7 @@ bool CClientManager::InitializeBanwordTable()
|
||||
std::unique_ptr<SQLMsg> 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<SQLMsg> 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<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1056,6 +1062,7 @@ bool CClientManager::InitializeItemRareTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> 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<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1134,6 +1141,7 @@ bool CClientManager::InitializeLandTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> 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<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1237,6 +1245,7 @@ bool CClientManager::InitializeObjectProto()
|
||||
|
||||
std::unique_ptr<SQLMsg> 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<size_t>(pRes->uiNumRows));
|
||||
|
||||
MYSQL_ROW data;
|
||||
|
||||
@@ -1306,6 +1315,7 @@ bool CClientManager::InitializeObjectTable()
|
||||
|
||||
std::unique_ptr<SQLMsg> 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())
|
||||
{
|
||||
|
||||
@@ -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<unsigned long long>(msg->Get()->uiNumRows));
|
||||
|
||||
if (msg->Get()->uiNumRows > 0)
|
||||
CreateAccountPlayerDataFromRes(msg->Get()->pSQLResult, info->pAccountTable);
|
||||
|
||||
@@ -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<SQLMsg> 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<SQLMsg> 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)
|
||||
{
|
||||
|
||||
@@ -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<TPlayerItem> * pVec, DWORD dwPID)
|
||||
{
|
||||
if (!res)
|
||||
@@ -65,7 +81,12 @@ bool CreateItemTableFromRes(MYSQL_RES * res, std::vector<TPlayerItem> * 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<TPlayerItem> 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<unsigned long long>(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<SQLMsg> 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<SQLMsg> 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<SQLMsg> 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);
|
||||
|
||||
@@ -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<char>(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<char>(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<DWORD>(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;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ class CConfig : public singleton<CConfig>
|
||||
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<CConfig>
|
||||
|
||||
private:
|
||||
TValueMap m_valueMap;
|
||||
bool m_readError = false;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -46,6 +46,9 @@ class CDBManager : public singleton<CDBManager>
|
||||
|
||||
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<void*>(static_cast<uintptr_t>(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);
|
||||
|
||||
|
||||
@@ -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 <memory>
|
||||
#include "../../common/economy_view.h"
|
||||
|
||||
namespace {
|
||||
using namespace PortEconomy;
|
||||
using Query=std::unique_ptr<SQLMsg>;
|
||||
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<PortEconomy::Mysql> 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<std::string> 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;i<r.rewardCount;++i) {
|
||||
const auto& reward=r.rewards[i];auto it=m_map_itemTableByVnum.find(reward.vnum);
|
||||
if(it==m_map_itemTableByVnum.end() || reward.count>2000 || (!(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<DWORD>(reinterpret_cast<uintptr_t>(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<PortEconomy::Mysql> 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<PortEconomy::Mysql>::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<unsigned long long>(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";
|
||||
}
|
||||
@@ -1067,13 +1067,12 @@ bool CGuildManager::ReserveWar(TPacketGuildWar * p)
|
||||
|
||||
std::unique_ptr<SQLMsg> 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<SQLMsg> 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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<DWORD>(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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -44,11 +44,11 @@ namespace marriage
|
||||
unique_ptr<SQLMsg> 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<unsigned long long>(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<SQLMsg> 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<SQLMsg> 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<SQLMsg> 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<SQLMsg> 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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
|
||||
@@ -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<BYTE>(nEmpire)));
|
||||
BroadcastNotice(szBuf);
|
||||
BroadcastNotice(LC_TEXT("10분 뒤 성을 공격할 예정입니다."));
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "MarkManager.h"
|
||||
|
||||
#include "crc32.h"
|
||||
#include <sstream>
|
||||
|
||||
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<DWORD,DWORD> staged;std::set<DWORD> 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<begin || end-begin>=static_cast<long>(sizeof(line))){valid=false;break;}
|
||||
const size_t length=static_cast<size_t>(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<DWORD>(guild)) ||
|
||||
!used.insert(static_cast<DWORD>(mark)).second){valid=false;break;}
|
||||
staged.emplace(static_cast<DWORD>(guild),static_cast<DWORD>(mark));
|
||||
}
|
||||
if(ferror(file))valid=false;fclose(file);if(!valid)return false;
|
||||
std::set<DWORD> free;
|
||||
for(DWORD id=0;id<MAX_IMAGE_COUNT*CGuildMarkImage::MARK_TOTAL_COUNT;++id)if(!used.count(id))free.insert(id);
|
||||
m_mapGID_MarkID.swap(staged);m_setFreeMarkID.swap(free);LoadMarkImages();return true;
|
||||
}
|
||||
|
||||
bool CGuildMarkManager::SaveMarkIndex()
|
||||
@@ -149,13 +148,11 @@ CGuildMarkImage * CGuildMarkManager::__GetImage(DWORD imgIdx)
|
||||
|
||||
bool CGuildMarkManager::AddMarkIDByGuildID(DWORD guildID, DWORD markID)
|
||||
{
|
||||
if (markID >= 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<DWORD, DWORD>::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<DWORD>(m_mapIdx_Image.size());
|
||||
}
|
||||
|
||||
DWORD CGuildMarkManager::GetMarkCount() const
|
||||
{
|
||||
return m_mapGID_MarkID.size();
|
||||
return static_cast<DWORD>(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<DWORD, DWORD>::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<WORD>(entry.first), mark=static_cast<WORD>(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);
|
||||
|
||||
@@ -45,7 +45,7 @@ class CGuildMarkManager : public singleton<CGuildMarkManager>
|
||||
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<BYTE, const SGuildMarkBlock *> & mapDiffBlocks);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "char_manager.h"
|
||||
#include "OXEvent.h"
|
||||
#include "desc.h"
|
||||
#include <limits>
|
||||
|
||||
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<size_t>(level), m_vec_quiz.size() - 1);
|
||||
const size_t count = m_vec_quiz[selected].size();
|
||||
if (!count || count > static_cast<size_t>(std::numeric_limits<int>::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<int>(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<OXEventInfoData>();
|
||||
|
||||
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<WORD>(sizeof(TPacketGCChat) + static_cast<size_t>(len));
|
||||
pack_chat.type = CHAT_TYPE_COMMAND;
|
||||
pack_chat.id = 0;
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<std::string, PendingPoints> 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<std::string, Ava2ShopRequest> 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()<p.next){++it;continue;}
|
||||
@@ -120,7 +57,12 @@ bool PointReply(const Ava2ShopReply& reply,const char* data) {
|
||||
const uint8_t status=uint8_t(data[1]);
|
||||
if(status==6 || status==8)return true; // Same durable token retries transaction/commit uncertainty.
|
||||
uint32_t amount=0;int64_t balance=0;memcpy(&amount,data+34,4);memcpy(&balance,data+38,8);
|
||||
AppendDurableDone(token, status, amount, balance);
|
||||
if((status!=0 && status!=1 && status!=2 && status!=7) || balance<0 ||
|
||||
amount>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<std::string, Ava2ShopRequest> 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<PointRetryInfo>(), PASSES_PER_SEC(1));
|
||||
}
|
||||
std::map<std::string,Ava2ShopRequest> 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<PointRetryInfo>(),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);}();
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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<int64_t>((pTable+n)->price);
|
||||
}
|
||||
|
||||
nTotalMoney += static_cast<int64_t>(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<DWORD, DWORD> itemkind; // 아이템 종류별 가격, first: vnum, second: 단일 수량 가격
|
||||
std::map<DWORD, int64_t> itemkind; // 아이템 종류별 가격, first: vnum, second: 단일 수량 가격
|
||||
// END_OF_MYSHOP_PRICE_LIST
|
||||
|
||||
std::set<TItemPos> cont;
|
||||
std::set<BYTE> 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<int32_t>(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())
|
||||
|
||||
@@ -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<const OFFLINE_SHOP_ITEM*>& 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<std::string, int> m_protection_Time;
|
||||
#ifdef ENABLE_SHOP_SEARCH_SYSTEM
|
||||
std::vector<DWORD> m_vecSearchLooking;
|
||||
#endif
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ int CHARACTER::ChangeEmpire(BYTE empire)
|
||||
|
||||
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery(szQuery));
|
||||
|
||||
if (msg->Get()->uiAffectedRows > 0)
|
||||
if (msg->Get()->HasAffectedRows())
|
||||
{
|
||||
// 5. 제국 변경 이력을 추가한다.
|
||||
SetChangeEmpireCount();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "stdafx.h"
|
||||
#include "../../common/gold_bounds.h"
|
||||
|
||||
#include <stack>
|
||||
|
||||
@@ -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<DWORD
|
||||
std::vector <int> 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++)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "stdafx.h"
|
||||
#include "port_magic_reduction.h"
|
||||
#include <sstream>
|
||||
|
||||
#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:
|
||||
|
||||
@@ -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 } /* 반드시 이 것이 마지막이어야 한다. */
|
||||
};
|
||||
|
||||
@@ -45,6 +45,8 @@
|
||||
#include <sstream>
|
||||
#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<std::string> PortPetCommandArguments(const char* argument)
|
||||
{
|
||||
std::vector<std::string> 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<WORD>(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<std::string> 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<std::string> 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<long>(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<std::string> 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<int>(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
|
||||
|
||||
@@ -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<int64_t>(t->dwPrice));
|
||||
|
||||
// 아이템 자재 사용하기
|
||||
{
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<int64_t>(cube_proto->gold), false);
|
||||
|
||||
percent_number = number(1,100);
|
||||
if ( percent_number<=cube_proto->percent)
|
||||
|
||||
@@ -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<int32_t>(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") ;
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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<int>(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<int>(packet.GetStreamSize()));
|
||||
else sys_err("invalid client package stream length");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<BYTE>(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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<SQLMsg> pmsg(DBManager::instance().DirectQuery("SELECT id FROM guild%s", get_table_postfix()));
|
||||
|
||||
std::vector<DWORD> 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<size_t>(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);
|
||||
|
||||
@@ -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<SQLMsg> 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<SQLMsg> 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 && (iSize<int(sizeof(Ava2ShopReply))+1 || iSize>32775 || reinterpret_cast<const Ava2ShopReply*>(pRealData)->size!=iSize-sizeof(Ava2ShopReply))) { d->SetPhase(PHASE_CLOSE);return true; }
|
||||
|
||||
if (Analyze(d, bHeader, pRealData) < 0)
|
||||
|
||||
@@ -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<WORD>(rkMarkMgr.GetMarkCount());
|
||||
|
||||
if (buf)
|
||||
{
|
||||
|
||||
@@ -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<int64_t>(ch->GetExchange()->GetCompany()->GetOwner()->GetGold()) + static_cast<int64_t>(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(bytes<sizeof(packet)+extra) return -1;
|
||||
if(!(ch->GetPickUPMode()&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<packet.count;++i) {
|
||||
DWORD vid;memcpy(&vid,data+sizeof(packet)+i*4,4);
|
||||
LPITEM item=ITEM_MANAGER::instance().FindByVID(vid);
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "belt_inventory_helper.h"
|
||||
#include "../../common/VnumHelper.h"
|
||||
#include "PetSystem.h"
|
||||
#include <cmath>
|
||||
|
||||
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<int>(available) : static_cast<int>(requested);
|
||||
if (added > 0)
|
||||
SetSocket(ITEM_SOCKET_REMAIN_SEC, static_cast<int>(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<uint32_t>(remaining);
|
||||
const uint32_t added = dwTime < available ? dwTime : available;
|
||||
SetSocket(ITEM_SOCKET_REMAIN_SEC, static_cast<int>(remaining + added));
|
||||
return static_cast<int>(added);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -29,11 +29,11 @@ class LogManager : public singleton<LogManager>
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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<int>(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;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ class CMonarch : public singleton<CMonarch>
|
||||
|
||||
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);
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//#include <boost/algorithm/string/predicate.hpp>
|
||||
#include <cctype>
|
||||
#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<DWORD> itemIDs;
|
||||
for(unsigned i=0;i<bItemCount;++i){
|
||||
if(pTable[i].display_pos>=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())
|
||||
|
||||
@@ -15,11 +15,14 @@
|
||||
|
||||
bool COfflineShopManager::CheckItemNames(LPCHARACTER ch, const char* searchInput, std::vector<DWORD>& 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<BYTE, std::string> 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<std::pair<std::string, DWORD>> m_ItemNames;
|
||||
while (fgets(one_line, 256, fp))
|
||||
{
|
||||
std::vector<std::string> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#ifndef __INC_PACKET_H__
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#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<DWORD>(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<WORD>(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<DWORD>(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<WORD>(size);
|
||||
|
||||
m_pStream = new BYTE[ uDynamicPacketSize ];
|
||||
|
||||
|
||||
@@ -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;i<msg->Get()->uiNumRows;++i) {
|
||||
for (uint64_t i=0;i<msg->Get()->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));
|
||||
|
||||
@@ -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 <code>" 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<BYTE>(item->GetValue(0));
|
||||
const short applyValue = static_cast<short>(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<BYTE>(type);
|
||||
const short applyValue = static_cast<short>(value);
|
||||
|
||||
if (item2->GetAttributeCount() >= COSTUME_ENCHANT_MAX_ATTR)
|
||||
{
|
||||
ChatPacket(CHAT_TYPE_COMMAND, "MTCATTR full");
|
||||
|
||||
@@ -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 <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <cerrno>
|
||||
#include <sstream>
|
||||
#include <map>
|
||||
#include <ctime>
|
||||
#include <vector>
|
||||
|
||||
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<unsigned,time_t> 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<sizeof(random)){ssize_t n=read(fd,random+offset,sizeof(random)-offset);if(n<0&&errno==EINTR)continue;if(n<=0){close(fd);return false;}offset+=static_cast<size_t>(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<std::string> 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<uint8_t>(mode);r.reference=first;r.generation=sequence;r.item=static_cast<uint32_t>(owner);
|
||||
if(!PortEconomySubmit(ch,r))ch->ChatPacket(CHAT_TYPE_COMMAND,"MTECON1 error %llu busy",static_cast<unsigned long long>(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<WORD>(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<int64_t>(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<int64_t>(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();
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
#include "../../common/economy.h"
|
||||
class CHARACTER;
|
||||
bool PortEconomySubmit(CHARACTER*,PortEconomy::Request&);
|
||||
void PortEconomyReply(unsigned,const char*);
|
||||
@@ -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<PortWikiRow> rows;
|
||||
|
||||
+186
-103
@@ -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 <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "../../common/gaya_catalog.h"
|
||||
|
||||
namespace {
|
||||
std::string s_gayaDir = "locale/germany/gem";
|
||||
std::map<uint32_t, std::map<uint8_t, TGemItem>> s_playerGayaItems;
|
||||
std::map<uint32_t, std::unique_ptr<PortGayaCatalogFile>> s_catalogFiles;
|
||||
std::map<uint32_t,uint64_t> 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<int>(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->second<PortEconomy::RetiredGeneration;
|
||||
auto found = s_catalogFiles.find(pid);
|
||||
if (found != s_catalogFiles.end()) return found->second->Ready();
|
||||
std::map<uint8_t,TGemItem> 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<SQLMsg> 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<SQLMsg> 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<PortGayaCatalogFile> 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<uint8_t,TGemItem> items;
|
||||
|
||||
const size_t catalogSize = sizeof(s_gemCatalog) / sizeof(s_gemCatalog[0]);
|
||||
std::vector<uint8_t> 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<int>(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<std::string> vecArgs;
|
||||
split_argument(argument, vecArgs);
|
||||
if (vecArgs.size() < 2) return;
|
||||
std::vector<std::string> 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<BYTE>(slotIndex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef METIN2_PORT_MAGIC_REDUCTION_H
|
||||
#define METIN2_PORT_MAGIC_REDUCTION_H
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
|
||||
// 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<int64_t>(0,std::min<int64_t>(100,resistance));
|
||||
if(sura)reduction/=2;
|
||||
reduction=std::max<int64_t>(0,std::min<int64_t>(50,reduction));
|
||||
const int64_t effective=std::max<int64_t>(0,std::min<int64_t>(100,resistance-reduction));
|
||||
return static_cast<int>(static_cast<int64_t>(damage)*(100-effective)/100);
|
||||
}
|
||||
#endif
|
||||
@@ -1,10 +1,12 @@
|
||||
#include "stdafx.h"
|
||||
#include "port_offlineshop.h"
|
||||
#include "../../common/offline_shop_safety.h"
|
||||
#include "db.h"
|
||||
#include <memory>
|
||||
|
||||
void PortOfflineShopBoot()
|
||||
{
|
||||
if(!PortOfflineShopEconomyReady())return;
|
||||
// 1. Create offline_shop_npc table
|
||||
{
|
||||
std::unique_ptr<SQLMsg> 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)"
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
#ifndef METIN2_PORT_RANK_RUNTIME_H
|
||||
#define METIN2_PORT_RANK_RUNTIME_H
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 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<Row> rows;
|
||||
std::vector<Waiter> 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;i<board.rows.size();++i){const Row& r=board.rows[i];
|
||||
ch->ChatPacket(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<Row> 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<int64_t>::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<Waiter> 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
|
||||
@@ -1,3 +1,5 @@
|
||||
#include <cmath>
|
||||
#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<int64_t>(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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ class CShop
|
||||
typedef struct shop_item
|
||||
{
|
||||
DWORD vnum; // 아이템 번호
|
||||
long price; // 가격
|
||||
int64_t price; // 가격
|
||||
BYTE count; // 아이템 개수
|
||||
|
||||
LPITEM pkItem;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "stdafx.h"
|
||||
#include "../../common/shop_economy.h"
|
||||
#include <climits>
|
||||
#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<int>(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())
|
||||
{
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#include "stdafx.h"
|
||||
#include "../../common/shop_economy.h"
|
||||
#include <climits>
|
||||
#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<int64_t>(ch->GetGold()) + static_cast<int64_t>(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;
|
||||
|
||||
@@ -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<std::string>& 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<unsigned char>(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()
|
||||
|
||||
@@ -3,6 +3,16 @@
|
||||
#define __INC_METIN_II_UTILS_H__
|
||||
|
||||
#include <math.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifdef ENABLE_OFFLINESHOP_SYSTEM
|
||||
bool getInjectText(const char* text);
|
||||
#endif
|
||||
|
||||
#ifdef ENABLE_SHOP_SEARCH_SYSTEM
|
||||
void split_argument_special(const char* argument, std::vector<std::string>& 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<WORD>(a) | (static_cast<WORD>(b) << 8);
|
||||
return static_cast<WORD>(static_cast<unsigned>(a) | (static_cast<unsigned>(b) << 8));
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "../libthecore/include/stdafx.h"
|
||||
#include "../libthecore/include/log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
@@ -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<uint32_t>(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<uint64_t> m_failureEpoch{0};
|
||||
MYSQL m_hDB;
|
||||
|
||||
std::string m_stHost;
|
||||
|
||||
Reference in New Issue
Block a user