Cleanup on some database-related files: merge some DB-related files, add some consistency to callhandles in sourcetree (M

+ combine MySQL-specific files into main database-files (click)
+ fix vcproj-files, adjust handler-function names for consistency (Machiavelli)

--HG--
branch : trunk
This commit is contained in:
click
2010-05-08 05:03:32 +02:00
parent d6df19cd99
commit f60d534b73
32 changed files with 600 additions and 796 deletions
+20 -20
View File
@@ -27,7 +27,7 @@
#include "Util.h" #include "Util.h"
#include "Auth/Sha1.h" #include "Auth/Sha1.h"
extern DatabaseType loginDatabase; extern DatabaseType LoginDatabase;
INSTANTIATE_SINGLETON_1(AccountMgr); INSTANTIATE_SINGLETON_1(AccountMgr);
@@ -50,16 +50,16 @@ AccountOpResult AccountMgr::CreateAccount(std::string username, std::string pass
return AOR_NAME_ALREDY_EXIST; // username does already exist return AOR_NAME_ALREDY_EXIST; // username does already exist
} }
if (!loginDatabase.PExecute("INSERT INTO account(username,sha_pass_hash,joindate) VALUES('%s','%s',NOW())", username.c_str(), CalculateShaPassHash(username, password).c_str())) if (!LoginDatabase.PExecute("INSERT INTO account(username,sha_pass_hash,joindate) VALUES('%s','%s',NOW())", username.c_str(), CalculateShaPassHash(username, password).c_str()))
return AOR_DB_INTERNAL_ERROR; // unexpected error return AOR_DB_INTERNAL_ERROR; // unexpected error
loginDatabase.Execute("INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist,account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL"); LoginDatabase.Execute("INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist,account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL");
return AOR_OK; // everything's fine return AOR_OK; // everything's fine
} }
AccountOpResult AccountMgr::DeleteAccount(uint32 accid) AccountOpResult AccountMgr::DeleteAccount(uint32 accid)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d'", accid); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d'", accid);
if (!result) if (!result)
return AOR_NAME_NOT_EXIST; // account doesn't exist return AOR_NAME_NOT_EXIST; // account doesn't exist
@@ -88,14 +88,14 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid)
CharacterDatabase.PExecute("DELETE FROM character_tutorial WHERE account = '%u'",accid); CharacterDatabase.PExecute("DELETE FROM character_tutorial WHERE account = '%u'",accid);
CharacterDatabase.PExecute("DELETE FROM account_data WHERE account = '%u'",accid); CharacterDatabase.PExecute("DELETE FROM account_data WHERE account = '%u'",accid);
loginDatabase.BeginTransaction(); LoginDatabase.BeginTransaction();
bool res = bool res =
loginDatabase.PExecute("DELETE FROM account WHERE id='%d'", accid) && LoginDatabase.PExecute("DELETE FROM account WHERE id='%d'", accid) &&
loginDatabase.PExecute("DELETE FROM account_access WHERE id ='%d'", accid) && LoginDatabase.PExecute("DELETE FROM account_access WHERE id ='%d'", accid) &&
loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid='%d'", accid); LoginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid='%d'", accid);
loginDatabase.CommitTransaction(); LoginDatabase.CommitTransaction();
if (!res) if (!res)
return AOR_DB_INTERNAL_ERROR; // unexpected error; return AOR_DB_INTERNAL_ERROR; // unexpected error;
@@ -105,7 +105,7 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid)
AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname, std::string new_passwd) AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname, std::string new_passwd)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d'", accid); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d'", accid);
if (!result) if (!result)
return AOR_NAME_NOT_EXIST; // account doesn't exist return AOR_NAME_NOT_EXIST; // account doesn't exist
@@ -119,9 +119,9 @@ AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname,
normalizeString(new_passwd); normalizeString(new_passwd);
std::string safe_new_uname = new_uname; std::string safe_new_uname = new_uname;
loginDatabase.escape_string(safe_new_uname); LoginDatabase.escape_string(safe_new_uname);
if (!loginDatabase.PExecute("UPDATE account SET v='0',s='0',username='%s',sha_pass_hash='%s' WHERE id='%d'", safe_new_uname.c_str(), if (!LoginDatabase.PExecute("UPDATE account SET v='0',s='0',username='%s',sha_pass_hash='%s' WHERE id='%d'", safe_new_uname.c_str(),
CalculateShaPassHash(new_uname, new_passwd).c_str(), accid)) CalculateShaPassHash(new_uname, new_passwd).c_str(), accid))
return AOR_DB_INTERNAL_ERROR; // unexpected error return AOR_DB_INTERNAL_ERROR; // unexpected error
@@ -142,7 +142,7 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accid, std::string new_passwd)
normalizeString(new_passwd); normalizeString(new_passwd);
// also reset s and v to force update at next realmd login // also reset s and v to force update at next realmd login
if (!loginDatabase.PExecute("UPDATE account SET v='0', s='0', sha_pass_hash='%s' WHERE id='%d'", if (!LoginDatabase.PExecute("UPDATE account SET v='0', s='0', sha_pass_hash='%s' WHERE id='%d'",
CalculateShaPassHash(username, new_passwd).c_str(), accid)) CalculateShaPassHash(username, new_passwd).c_str(), accid))
return AOR_DB_INTERNAL_ERROR; // unexpected error return AOR_DB_INTERNAL_ERROR; // unexpected error
@@ -151,8 +151,8 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accid, std::string new_passwd)
uint32 AccountMgr::GetId(std::string username) uint32 AccountMgr::GetId(std::string username)
{ {
loginDatabase.escape_string(username); LoginDatabase.escape_string(username);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", username.c_str()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", username.c_str());
if (!result) if (!result)
return 0; return 0;
else else
@@ -164,7 +164,7 @@ uint32 AccountMgr::GetId(std::string username)
uint32 AccountMgr::GetSecurity(uint32 acc_id) uint32 AccountMgr::GetSecurity(uint32 acc_id)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u'", acc_id); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u'", acc_id);
if (result) if (result)
{ {
uint32 sec = (*result)[0].GetUInt32(); uint32 sec = (*result)[0].GetUInt32();
@@ -177,8 +177,8 @@ uint32 AccountMgr::GetSecurity(uint32 acc_id)
uint32 AccountMgr::GetSecurity(uint32 acc_id, int32 realm_id) uint32 AccountMgr::GetSecurity(uint32 acc_id, int32 realm_id)
{ {
QueryResult_AutoPtr result = (realm_id == -1) QueryResult_AutoPtr result = (realm_id == -1)
? loginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u' AND RealmID = '%d'", acc_id, realm_id) ? LoginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u' AND RealmID = '%d'", acc_id, realm_id)
: loginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u' AND (RealmID = '%d' OR RealmID = '-1')", acc_id, realm_id); : LoginDatabase.PQuery("SELECT gmlevel FROM account_access WHERE id = '%u' AND (RealmID = '%d' OR RealmID = '-1')", acc_id, realm_id);
if (result) if (result)
{ {
uint32 sec = (*result)[0].GetUInt32(); uint32 sec = (*result)[0].GetUInt32();
@@ -190,7 +190,7 @@ uint32 AccountMgr::GetSecurity(uint32 acc_id, int32 realm_id)
bool AccountMgr::GetName(uint32 acc_id, std::string &name) bool AccountMgr::GetName(uint32 acc_id, std::string &name)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id);
if (result) if (result)
{ {
name = (*result)[0].GetCppString(); name = (*result)[0].GetCppString();
@@ -209,7 +209,7 @@ bool AccountMgr::CheckPassword(uint32 accid, std::string passwd)
normalizeString(username); normalizeString(username);
normalizeString(passwd); normalizeString(passwd);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d' AND sha_pass_hash='%s'", accid, CalculateShaPassHash(username, passwd).c_str()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%d' AND sha_pass_hash='%s'", accid, CalculateShaPassHash(username, passwd).c_str());
if (result) if (result)
return true; return true;
+1 -1
View File
@@ -28,7 +28,7 @@
#include "Auth/Sha1.h" #include "Auth/Sha1.h"
#include "ProgressBar.h" #include "ProgressBar.h"
extern DatabaseType loginDatabase; extern DatabaseType LoginDatabase;
INSTANTIATE_SINGLETON_1(AddonMgr); INSTANTIATE_SINGLETON_1(AddonMgr);
+4 -4
View File
@@ -279,7 +279,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket & recv_data)
return; return;
} }
QueryResult_AutoPtr resultacct = loginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%d'", GetAccountId()); QueryResult_AutoPtr resultacct = LoginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%d'", GetAccountId());
if (resultacct) if (resultacct)
{ {
Field *fields=resultacct->Fetch(); Field *fields=resultacct->Fetch();
@@ -466,8 +466,8 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket & recv_data)
pNewChar->SaveToDB(); pNewChar->SaveToDB();
charcount+=1; charcount+=1;
loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", GetAccountId(), realmID); LoginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", GetAccountId(), realmID);
loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charcount, GetAccountId(), realmID); LoginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charcount, GetAccountId(), realmID);
pNewChar->CleanupsBeforeDelete(); pNewChar->CleanupsBeforeDelete();
delete pNewChar; // created only to call SaveToDB() delete pNewChar; // created only to call SaveToDB()
@@ -723,7 +723,7 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder * holder)
pCurrChar->SendInitialPacketsAfterAddToMap(); pCurrChar->SendInitialPacketsAfterAddToMap();
CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow()); CharacterDatabase.PExecute("UPDATE characters SET online = 1 WHERE guid = '%u'", pCurrChar->GetGUIDLow());
loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId()); LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = '%u'", GetAccountId());
pCurrChar->SetInGameTime(getMSTime()); pCurrChar->SetInGameTime(getMSTime());
// announce group about member online (must be after add to player list to receive announce to self) // announce group about member online (must be after add to player list to receive announce to self)
+3 -3
View File
@@ -254,7 +254,7 @@ bool ChatHandler::HandleAccountAddonCommand(const char* args)
return false; return false;
// No SQL injection // No SQL injection
loginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'", expansion, account_id); LoginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'", expansion, account_id);
PSendSysMessage(LANG_ACCOUNT_ADDON, expansion); PSendSysMessage(LANG_ACCOUNT_ADDON, expansion);
return true; return true;
} }
@@ -270,14 +270,14 @@ bool ChatHandler::HandleAccountLockCommand(const char* args)
std::string argstr = (char*)args; std::string argstr = (char*)args;
if (argstr == "on") if (argstr == "on")
{ {
loginDatabase.PExecute("UPDATE account SET locked = '1' WHERE id = '%d'",m_session->GetAccountId()); LoginDatabase.PExecute("UPDATE account SET locked = '1' WHERE id = '%d'",m_session->GetAccountId());
PSendSysMessage(LANG_COMMAND_ACCLOCKLOCKED); PSendSysMessage(LANG_COMMAND_ACCLOCKLOCKED);
return true; return true;
} }
if (argstr == "off") if (argstr == "off")
{ {
loginDatabase.PExecute("UPDATE account SET locked = '0' WHERE id = '%d'",m_session->GetAccountId()); LoginDatabase.PExecute("UPDATE account SET locked = '0' WHERE id = '%d'",m_session->GetAccountId());
PSendSysMessage(LANG_COMMAND_ACCLOCKUNLOCKED); PSendSysMessage(LANG_COMMAND_ACCLOCKUNLOCKED);
return true; return true;
} }
+9 -9
View File
@@ -84,7 +84,7 @@ bool ChatHandler::HandleMuteCommand(const char* args)
if (target) if (target)
target->GetSession()->m_muteTime = mutetime; target->GetSession()->m_muteTime = mutetime;
loginDatabase.PExecute("UPDATE account SET mutetime = " UI64FMTD " WHERE id = '%u'",uint64(mutetime), account_id); LoginDatabase.PExecute("UPDATE account SET mutetime = " UI64FMTD " WHERE id = '%u'",uint64(mutetime), account_id);
if (target) if (target)
ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_DISABLED, notspeaktime, mutereasonstr.c_str()); ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_DISABLED, notspeaktime, mutereasonstr.c_str());
@@ -128,7 +128,7 @@ bool ChatHandler::HandleUnmuteCommand(const char* args)
target->GetSession()->m_muteTime = 0; target->GetSession()->m_muteTime = 0;
} }
loginDatabase.PExecute("UPDATE account SET mutetime = '0' WHERE id = '%u'", account_id); LoginDatabase.PExecute("UPDATE account SET mutetime = '0' WHERE id = '%u'", account_id);
if (target) if (target)
ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_ENABLED); ChatHandler(target).PSendSysMessage(LANG_YOUR_CHAT_ENABLED);
@@ -2215,7 +2215,7 @@ bool ChatHandler::HandlePInfoCommand(const char* args)
uint32 security = 0; uint32 security = 0;
std::string last_login = GetTrinityString(LANG_ERROR); std::string last_login = GetTrinityString(LANG_ERROR);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT a.username,aa.gmlevel,a.email,a.last_ip,a.last_login " QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT a.username,aa.gmlevel,a.email,a.last_ip,a.last_login "
"FROM account a " "FROM account a "
"LEFT JOIN account_access aa " "LEFT JOIN account_access aa "
"ON (a.id = aa.id) " "ON (a.id = aa.id) "
@@ -3741,9 +3741,9 @@ bool ChatHandler::HandleLookupPlayerIpCommand(const char* args)
char* limit_str = strtok (NULL, " "); char* limit_str = strtok (NULL, " ");
int32 limit = limit_str ? atoi (limit_str) : -1; int32 limit = limit_str ? atoi (limit_str) : -1;
loginDatabase.escape_string (ip); LoginDatabase.escape_string (ip);
QueryResult_AutoPtr result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE last_ip = '%s'", ip.c_str ()); QueryResult_AutoPtr result = LoginDatabase.PQuery ("SELECT id,username FROM account WHERE last_ip = '%s'", ip.c_str ());
return LookupPlayerSearchCommand (result,limit); return LookupPlayerSearchCommand (result,limit);
} }
@@ -3760,9 +3760,9 @@ bool ChatHandler::HandleLookupPlayerAccountCommand(const char* args)
if (!AccountMgr::normalizeString (account)) if (!AccountMgr::normalizeString (account))
return false; return false;
loginDatabase.escape_string (account); LoginDatabase.escape_string (account);
QueryResult_AutoPtr result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE username = '%s'", account.c_str ()); QueryResult_AutoPtr result = LoginDatabase.PQuery ("SELECT id,username FROM account WHERE username = '%s'", account.c_str ());
return LookupPlayerSearchCommand (result,limit); return LookupPlayerSearchCommand (result,limit);
} }
@@ -3777,9 +3777,9 @@ bool ChatHandler::HandleLookupPlayerEmailCommand(const char* args)
char* limit_str = strtok (NULL, " "); char* limit_str = strtok (NULL, " ");
int32 limit = limit_str ? atoi (limit_str) : -1; int32 limit = limit_str ? atoi (limit_str) : -1;
loginDatabase.escape_string (email); LoginDatabase.escape_string (email);
QueryResult_AutoPtr result = loginDatabase.PQuery ("SELECT id,username FROM account WHERE email = '%s'", email.c_str ()); QueryResult_AutoPtr result = LoginDatabase.PQuery ("SELECT id,username FROM account WHERE email = '%s'", email.c_str ());
return LookupPlayerSearchCommand (result,limit); return LookupPlayerSearchCommand (result,limit);
} }
+21 -21
View File
@@ -1465,7 +1465,7 @@ bool ChatHandler::HandleAccountSetGmLevelCommand(const char *args)
// Check and abort if the target gm has a higher rank on one of the realms and the new realm is -1 // Check and abort if the target gm has a higher rank on one of the realms and the new realm is -1
if (gmRealmID == -1) if (gmRealmID == -1)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT * FROM account_access WHERE id = '%u' AND gmlevel > '%d'", targetAccountId, gm); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT * FROM account_access WHERE id = '%u' AND gmlevel > '%d'", targetAccountId, gm);
if (result) if (result)
{ {
SendSysMessage(LANG_YOURS_SECURITY_IS_LOW); SendSysMessage(LANG_YOURS_SECURITY_IS_LOW);
@@ -1484,12 +1484,12 @@ bool ChatHandler::HandleAccountSetGmLevelCommand(const char *args)
// If gmRealmID is -1, delete all values for the account id, else, insert values for the specific realmID // If gmRealmID is -1, delete all values for the account id, else, insert values for the specific realmID
if (gmRealmID == -1) if (gmRealmID == -1)
loginDatabase.PExecute("DELETE FROM account_access WHERE id = '%u'", targetAccountId); LoginDatabase.PExecute("DELETE FROM account_access WHERE id = '%u'", targetAccountId);
else else
loginDatabase.PExecute("DELETE FROM account_access WHERE id = '%u' AND (RealmID = '%d' OR RealmID = '-1')", targetAccountId, realmID); LoginDatabase.PExecute("DELETE FROM account_access WHERE id = '%u' AND (RealmID = '%d' OR RealmID = '-1')", targetAccountId, realmID);
if (gm != 0) if (gm != 0)
loginDatabase.PExecute("INSERT INTO account_access VALUES ('%u','%d','%d')", targetAccountId, gm, realmID); LoginDatabase.PExecute("INSERT INTO account_access VALUES ('%u','%d','%d')", targetAccountId, gm, realmID);
PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm); PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm);
return true; return true;
} }
@@ -5914,7 +5914,7 @@ bool ChatHandler::HandleBanInfoCharacterCommand(const char *args)
bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname)
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate,banreason,bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC",accountid); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(bandate), unbandate-bandate, active, unbandate,banreason,bannedby FROM account_banned WHERE id = '%u' ORDER BY bandate ASC",accountid);
if (!result) if (!result)
{ {
PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname); PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname);
@@ -5953,8 +5953,8 @@ bool ChatHandler::HandleBanInfoIPCommand(const char *args)
std::string IP = cIP; std::string IP = cIP;
loginDatabase.escape_string(IP); LoginDatabase.escape_string(IP);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason,bannedby,unbandate-bandate FROM ip_banned WHERE ip = '%s'",IP.c_str()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(bandate), FROM_UNIXTIME(unbandate), unbandate-UNIX_TIMESTAMP(), banreason,bannedby,unbandate-bandate FROM ip_banned WHERE ip = '%s'",IP.c_str());
if (!result) if (!result)
{ {
PSendSysMessage(LANG_BANINFO_NOIP); PSendSysMessage(LANG_BANINFO_NOIP);
@@ -5972,14 +5972,14 @@ bool ChatHandler::HandleBanInfoIPCommand(const char *args)
bool ChatHandler::HandleBanListCharacterCommand(const char *args) bool ChatHandler::HandleBanListCharacterCommand(const char *args)
{ {
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate");
char* cFilter = strtok ((char*)args, " "); char* cFilter = strtok ((char*)args, " ");
if (!cFilter) if (!cFilter)
return false; return false;
std::string filter = cFilter; std::string filter = cFilter;
loginDatabase.escape_string(filter); LoginDatabase.escape_string(filter);
QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'"),filter.c_str()); QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'"),filter.c_str());
if (!result) if (!result)
{ {
@@ -5992,22 +5992,22 @@ bool ChatHandler::HandleBanListCharacterCommand(const char *args)
bool ChatHandler::HandleBanListAccountCommand(const char *args) bool ChatHandler::HandleBanListAccountCommand(const char *args)
{ {
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate");
char* cFilter = strtok((char*)args, " "); char* cFilter = strtok((char*)args, " ");
std::string filter = cFilter ? cFilter : ""; std::string filter = cFilter ? cFilter : "";
loginDatabase.escape_string(filter); LoginDatabase.escape_string(filter);
QueryResult_AutoPtr result; QueryResult_AutoPtr result;
if (filter.empty()) if (filter.empty())
{ {
result = loginDatabase.Query("SELECT account.id, username FROM account, account_banned" result = LoginDatabase.Query("SELECT account.id, username FROM account, account_banned"
" WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id"); " WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id");
} }
else else
{ {
result = loginDatabase.PQuery("SELECT account.id, username FROM account, account_banned" result = LoginDatabase.PQuery("SELECT account.id, username FROM account, account_banned"
" WHERE account.id = account_banned.id AND active = 1 AND username "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" GROUP BY account.id", " WHERE account.id = account_banned.id AND active = 1 AND username "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")" GROUP BY account.id",
filter.c_str()); filter.c_str());
} }
@@ -6033,7 +6033,7 @@ bool ChatHandler::HandleBanListHelper(QueryResult_AutoPtr result)
Field* fields = result->Fetch(); Field* fields = result->Fetch();
uint32 accountid = fields[0].GetUInt32(); uint32 accountid = fields[0].GetUInt32();
QueryResult_AutoPtr banresult = loginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id",accountid); QueryResult_AutoPtr banresult = LoginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.id='%u' AND account_banned.id=account.id",accountid);
if (banresult) if (banresult)
{ {
Field* fields2 = banresult->Fetch(); Field* fields2 = banresult->Fetch();
@@ -6063,7 +6063,7 @@ bool ChatHandler::HandleBanListHelper(QueryResult_AutoPtr result)
accmgr.GetName (account_id,account_name); accmgr.GetName (account_id,account_name);
// No SQL injection. id is uint32. // No SQL injection. id is uint32.
QueryResult_AutoPtr banInfo = loginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id); QueryResult_AutoPtr banInfo = LoginDatabase.PQuery("SELECT bandate,unbandate,bannedby,banreason FROM account_banned WHERE id = %u ORDER BY unbandate", account_id);
if (banInfo) if (banInfo)
{ {
Field *fields2 = banInfo->Fetch(); Field *fields2 = banInfo->Fetch();
@@ -6097,23 +6097,23 @@ bool ChatHandler::HandleBanListHelper(QueryResult_AutoPtr result)
bool ChatHandler::HandleBanListIPCommand(const char *args) bool ChatHandler::HandleBanListIPCommand(const char *args)
{ {
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate");
char* cFilter = strtok((char*)args, " "); char* cFilter = strtok((char*)args, " ");
std::string filter = cFilter ? cFilter : ""; std::string filter = cFilter ? cFilter : "";
loginDatabase.escape_string(filter); LoginDatabase.escape_string(filter);
QueryResult_AutoPtr result; QueryResult_AutoPtr result;
if (filter.empty()) if (filter.empty())
{ {
result = loginDatabase.Query ("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" result = LoginDatabase.Query ("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
" WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())" " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP())"
" ORDER BY unbandate"); " ORDER BY unbandate");
} }
else else
{ {
result = loginDatabase.PQuery("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned" result = LoginDatabase.PQuery("SELECT ip,bandate,unbandate,bannedby,banreason FROM ip_banned"
" WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'") " WHERE (bandate=unbandate OR unbandate>UNIX_TIMESTAMP()) AND ip "_LIKE_" "_CONCAT3_("'%%'","'%s'","'%%'")
" ORDER BY unbandate",filter.c_str()); " ORDER BY unbandate",filter.c_str());
} }
@@ -6868,7 +6868,7 @@ bool ChatHandler::HandleInstanceSaveDataCommand(const char * /*args*/)
bool ChatHandler::HandleGMListFullCommand(const char* /*args*/) bool ChatHandler::HandleGMListFullCommand(const char* /*args*/)
{ {
///- Get the accounts with GM Level >0 ///- Get the accounts with GM Level >0
QueryResult_AutoPtr result = loginDatabase.Query("SELECT a.username,aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel > 0"); QueryResult_AutoPtr result = LoginDatabase.Query("SELECT a.username,aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel > 0");
if (result) if (result)
{ {
SendSysMessage(LANG_GMLIST); SendSysMessage(LANG_GMLIST);
@@ -6976,7 +6976,7 @@ bool ChatHandler::HandleAccountSetAddonCommand(const char *args)
return false; return false;
// No SQL injection // No SQL injection
loginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'",expansion,account_id); LoginDatabase.PExecute("UPDATE account SET expansion = '%d' WHERE id = '%u'",expansion,account_id);
PSendSysMessage(LANG_ACCOUNT_SETADDON,account_name.c_str(),account_id,expansion); PSendSysMessage(LANG_ACCOUNT_SETADDON,account_name.c_str(),account_id,expansion);
return true; return true;
} }
+1 -1
View File
@@ -1310,7 +1310,7 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data)
uint32 accid = plr->GetSession()->GetAccountId(); uint32 accid = plr->GetSession()->GetAccountId();
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT username,email,last_ip FROM account WHERE id=%u", accid); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT username,email,last_ip FROM account WHERE id=%u", accid);
if (!result) if (!result)
{ {
SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str()); SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str());
+1 -1
View File
@@ -4354,7 +4354,7 @@ void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmC
CharacterDatabase.CommitTransaction(); CharacterDatabase.CommitTransaction();
//loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID); //LoginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
if (updateRealmChars) sWorld.UpdateRealmCharCount(accountId); if (updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
} }
+18 -18
View File
@@ -1275,7 +1275,7 @@ void World::SetInitialWorldSettings()
// not send custom type REALM_FFA_PVP to realm list // not send custom type REALM_FFA_PVP to realm list
uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE); uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
uint32 realm_zone = getConfig(CONFIG_REALM_ZONE); uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID); LoginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
///- Remove the bones after a restart ///- Remove the bones after a restart
CharacterDatabase.Execute("DELETE FROM corpse WHERE corpse_type = '0'"); CharacterDatabase.Execute("DELETE FROM corpse WHERE corpse_type = '0'");
@@ -1619,7 +1619,7 @@ void World::SetInitialWorldSettings()
sprintf(isoDate, "%04d-%02d-%02d %02d:%02d:%02d", sprintf(isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec); local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime, revision) VALUES('%u', " UI64FMTD ", '%s', 0, '%s')", LoginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime, revision) VALUES('%u', " UI64FMTD ", '%s', 0, '%s')",
realmID, uint64(m_startTime), isoDate, _FULLVERSION); realmID, uint64(m_startTime), isoDate, _FULLVERSION);
static uint32 abtimer = 0; static uint32 abtimer = 0;
@@ -1679,7 +1679,7 @@ void World::SetInitialWorldSettings()
objmgr.LoadTransportEvents(); objmgr.LoadTransportEvents();
sLog.outString("Deleting expired bans..."); sLog.outString("Deleting expired bans...");
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate<>bandate");
sLog.outString("Calculate next daily quest reset time..."); sLog.outString("Calculate next daily quest reset time...");
InitDailyQuestResetTime(); InitDailyQuestResetTime();
@@ -1905,7 +1905,7 @@ void World::Update(uint32 diff)
uint32 maxClientsNum = GetMaxActiveSessionCount(); uint32 maxClientsNum = GetMaxActiveSessionCount();
m_timers[WUPDATE_UPTIME].Reset(); m_timers[WUPDATE_UPTIME].Reset();
loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime)); LoginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
} }
/// <li> Clean logs table /// <li> Clean logs table
@@ -1917,7 +1917,7 @@ void World::Update(uint32 diff)
//uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount(); //uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
m_timers[WUPDATE_CLEANDB].Reset(); m_timers[WUPDATE_CLEANDB].Reset();
loginDatabase.PExecute("DELETE FROM logs WHERE (time + %u) < "UI64FMTD";", LoginDatabase.PExecute("DELETE FROM logs WHERE (time + %u) < "UI64FMTD";",
sWorld.getConfig(CONFIG_LOGDB_CLEARTIME), uint64(time(0))); sWorld.getConfig(CONFIG_LOGDB_CLEARTIME), uint64(time(0)));
} }
} }
@@ -2184,10 +2184,10 @@ void World::KickAllLess(AccountTypes sec)
/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author) BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
{ {
loginDatabase.escape_string(nameOrIP); LoginDatabase.escape_string(nameOrIP);
loginDatabase.escape_string(reason); LoginDatabase.escape_string(reason);
std::string safe_author=author; std::string safe_author=author;
loginDatabase.escape_string(safe_author); LoginDatabase.escape_string(safe_author);
uint32 duration_secs = TimeStringToSecs(duration); uint32 duration_secs = TimeStringToSecs(duration);
QueryResult_AutoPtr resultAccounts = QueryResult_AutoPtr(NULL); //used for kicking QueryResult_AutoPtr resultAccounts = QueryResult_AutoPtr(NULL); //used for kicking
@@ -2197,12 +2197,12 @@ BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string dura
{ {
case BAN_IP: case BAN_IP:
//No SQL injection as strings are escaped //No SQL injection as strings are escaped
resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str()); resultAccounts = LoginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
loginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+%u,'%s','%s')",nameOrIP.c_str(),duration_secs,safe_author.c_str(),reason.c_str()); LoginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+%u,'%s','%s')",nameOrIP.c_str(),duration_secs,safe_author.c_str(),reason.c_str());
break; break;
case BAN_ACCOUNT: case BAN_ACCOUNT:
//No SQL injection as string is escaped //No SQL injection as string is escaped
resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str()); resultAccounts = LoginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
break; break;
case BAN_CHARACTER: case BAN_CHARACTER:
//No SQL injection as string is escaped //No SQL injection as string is escaped
@@ -2229,7 +2229,7 @@ BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string dura
if (mode != BAN_IP) if (mode != BAN_IP)
{ {
//No SQL injection as strings are escaped //No SQL injection as strings are escaped
loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')", LoginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
account,duration_secs,safe_author.c_str(),reason.c_str()); account,duration_secs,safe_author.c_str(),reason.c_str());
} }
@@ -2247,8 +2247,8 @@ bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
{ {
if (mode == BAN_IP) if (mode == BAN_IP)
{ {
loginDatabase.escape_string(nameOrIP); LoginDatabase.escape_string(nameOrIP);
loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str()); LoginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
} }
else else
{ {
@@ -2262,7 +2262,7 @@ bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
return false; return false;
//NO SQL injection as account is uint32 //NO SQL injection as account is uint32
loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account); LoginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
} }
return true; return true;
} }
@@ -2491,8 +2491,8 @@ void World::_UpdateRealmCharCount(QueryResult_AutoPtr resultCharCount, uint32 ac
Field *fields = resultCharCount->Fetch(); Field *fields = resultCharCount->Fetch();
uint32 charCount = fields[0].GetUInt32(); uint32 charCount = fields[0].GetUInt32();
loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID); LoginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID); LoginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
} }
} }
@@ -2552,7 +2552,7 @@ void World::ResetDailyQuests()
void World::UpdateAllowedSecurity() void World::UpdateAllowedSecurity()
{ {
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT allowedSecurityLevel from realmlist WHERE id = '%d'", realmID); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT allowedSecurityLevel from realmlist WHERE id = '%d'", realmID);
if (result) if (result)
{ {
m_allowedSecurityLevel = AccountTypes(result->Fetch()->GetUInt16()); m_allowedSecurityLevel = AccountTypes(result->Fetch()->GetUInt16());
+2 -2
View File
@@ -55,7 +55,7 @@ m_latency(0), m_TutorialsChanged(false), m_timeOutTime(0)
{ {
m_Address = sock->GetRemoteAddress (); m_Address = sock->GetRemoteAddress ();
sock->AddReference (); sock->AddReference ();
loginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId()); LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId());
} }
} }
@@ -79,7 +79,7 @@ WorldSession::~WorldSession()
while (_recvQueue.next(packet)) while (_recvQueue.next(packet))
delete packet; delete packet;
loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId()); LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId());
CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = %u;", GetAccountId()); CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = %u;", GetAccountId());
} }
+6 -6
View File
@@ -753,11 +753,11 @@ int WorldSocket::HandleAuthSession (WorldPacket& recvPacket)
// Get the account information from the realmd database // Get the account information from the realmd database
std::string safe_account = account; // Duplicate, else will screw the SHA hash verification below std::string safe_account = account; // Duplicate, else will screw the SHA hash verification below
loginDatabase.escape_string (safe_account); LoginDatabase.escape_string (safe_account);
// No SQL injection, username escaped. // No SQL injection, username escaped.
QueryResult_AutoPtr result = QueryResult_AutoPtr result =
loginDatabase.PQuery ("SELECT " LoginDatabase.PQuery ("SELECT "
"id, " //0 "id, " //0
"sessionkey, " //1 "sessionkey, " //1
"last_ip, " //2 "last_ip, " //2
@@ -837,7 +837,7 @@ int WorldSocket::HandleAuthSession (WorldPacket& recvPacket)
// Checks gmlevel per Realm // Checks gmlevel per Realm
result = result =
loginDatabase.PQuery ("SELECT " LoginDatabase.PQuery ("SELECT "
"RealmID, " //0 "RealmID, " //0
"gmlevel " //1 "gmlevel " //1
"FROM account_access " "FROM account_access "
@@ -855,7 +855,7 @@ int WorldSocket::HandleAuthSession (WorldPacket& recvPacket)
// Re-check account ban (same check as in realmd) // Re-check account ban (same check as in realmd)
QueryResult_AutoPtr banresult = QueryResult_AutoPtr banresult =
loginDatabase.PQuery ("SELECT 1 FROM account_banned WHERE id = %u AND active = 1 " LoginDatabase.PQuery ("SELECT 1 FROM account_banned WHERE id = %u AND active = 1 "
"UNION " "UNION "
"SELECT 1 FROM ip_banned WHERE ip = '%s'", "SELECT 1 FROM ip_banned WHERE ip = '%s'",
id, GetRemoteAddress().c_str()); id, GetRemoteAddress().c_str());
@@ -917,9 +917,9 @@ int WorldSocket::HandleAuthSession (WorldPacket& recvPacket)
// Update the last_ip in the database // Update the last_ip in the database
// No SQL injection, username escaped. // No SQL injection, username escaped.
loginDatabase.escape_string (address); LoginDatabase.escape_string (address);
loginDatabase.PExecute ("UPDATE account " LoginDatabase.PExecute ("UPDATE account "
"SET last_ip = '%s' " "SET last_ip = '%s' "
"WHERE username = '%s'", "WHERE username = '%s'",
address.c_str (), address.c_str (),
+1 -5
View File
@@ -6,14 +6,10 @@ SET(trinitydatabase_STAT_SRCS
Database.h Database.h
DatabaseEnv.h DatabaseEnv.h
DatabaseImpl.h DatabaseImpl.h
DatabaseMysql.cpp
DatabaseMysql.h
Field.cpp Field.cpp
Field.h Field.h
MySQLDelayThread.h QueryResult.cpp
QueryResult.h QueryResult.h
QueryResultMysql.cpp
QueryResultMysql.h
SQLStorage.cpp SQLStorage.cpp
SQLStorage.h SQLStorage.h
SqlDelayThread.cpp SqlDelayThread.cpp
+399 -2
View File
@@ -24,15 +24,51 @@
#include "Common.h" #include "Common.h"
#include "../../game/UpdateFields.h" #include "../../game/UpdateFields.h"
#include "Util.h"
#include "Policies/SingletonImp.h"
#include "Platform/Define.h"
#include "Threading.h"
#include "Database/SqlDelayThread.h"
#include "Database/SqlOperations.h"
#include "Timer.h"
#include <ctime> #include <ctime>
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
Database::~Database() size_t Database::db_count = 0;
Database::Database()
{ {
// before first connection
if (db_count++ == 0)
{
// Mysql Library Init
mysql_library_init(-1, NULL, NULL);
if (!mysql_thread_safe())
{
sLog.outError("FATAL ERROR: Used MySQL library isn't thread-safe.");
exit(1);
}
}
} }
bool Database::Initialize(const char *) Database::~Database()
{
if (m_delayThread)
HaltDelayThread();
if (mMysql)
mysql_close(mMysql);
// Free Mysql library pointers for last ~DB
if (--db_count == 0)
mysql_library_end();
}
bool Database::Initialize(const char *infoString)
{ {
// Enable logging of SQL commands (usally only GM commands) // Enable logging of SQL commands (usally only GM commands)
// (See method: PExecuteLog) // (See method: PExecuteLog)
@@ -44,15 +80,114 @@ bool Database::Initialize(const char *)
m_logsDir.append("/"); m_logsDir.append("/");
} }
tranThread = NULL;
MYSQL *mysqlInit;
mysqlInit = mysql_init(NULL);
if (!mysqlInit)
{
sLog.outError("Could not initialize Mysql connection");
return false;
}
InitDelayThread();
Tokens tokens = StrSplit(infoString, ";");
Tokens::iterator iter;
std::string host, port_or_socket, user, password, database;
int port;
char const* unix_socket;
iter = tokens.begin();
if (iter != tokens.end())
host = *iter++;
if (iter != tokens.end())
port_or_socket = *iter++;
if (iter != tokens.end())
user = *iter++;
if (iter != tokens.end())
password = *iter++;
if (iter != tokens.end())
database = *iter++;
mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
#ifdef WIN32
if (host==".") // named pipe use option (Windows)
{
unsigned int opt = MYSQL_PROTOCOL_PIPE;
mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
port = 0;
unix_socket = 0;
}
else // generic case
{
port = atoi(port_or_socket.c_str());
unix_socket = 0;
}
#else
if (host==".") // socket use option (Unix/Linux)
{
unsigned int opt = MYSQL_PROTOCOL_SOCKET;
mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
host = "localhost";
port = 0;
unix_socket = port_or_socket.c_str();
}
else // generic case
{
port = atoi(port_or_socket.c_str());
unix_socket = 0;
}
#endif
mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
password.c_str(), database.c_str(), port, unix_socket, 0);
if (mMysql)
{
sLog.outDetail("Connected to MySQL database at %s", host.c_str());
sLog.outString("MySQL client library: %s", mysql_get_client_info());
sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql));
if (!mysql_autocommit(mMysql, 1))
sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1");
else
sLog.outDetail("AUTOCOMMIT NOT SET TO 1");
// set connection properties to UTF8 to properly handle locales for different
// server configs - core sends data in UTF8, so MySQL must expect UTF8 too
PExecute("SET NAMES `utf8`");
PExecute("SET CHARACTER SET `utf8`");
#if MYSQL_VERSION_ID >= 50003
my_bool my_true = (my_bool)1;
if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
else
sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT.");
#else
#warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem."
#endif
return true; return true;
}
else
{
sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(),mysql_error(mysqlInit));
mysql_close(mysqlInit);
return false;
}
} }
void Database::ThreadStart() void Database::ThreadStart()
{ {
mysql_thread_init();
} }
void Database::ThreadEnd() void Database::ThreadEnd()
{ {
mysql_thread_end();
} }
void Database::escape_string(std::string& str) void Database::escape_string(std::string& str)
@@ -66,6 +201,15 @@ void Database::escape_string(std::string& str)
delete[] buf; delete[] buf;
} }
unsigned long Database::escape_string(char *to, const char *from, unsigned long length)
{
if (!mMysql || !to || !from || !length)
return 0;
return(mysql_real_escape_string(mMysql, to, from, length));
}
bool Database::PExecuteLog(const char * format,...) bool Database::PExecuteLog(const char * format,...)
{ {
if (!format) if (!format)
@@ -115,6 +259,65 @@ void Database::SetResultQueue(SqlResultQueue * queue)
m_queryQueues[ACE_Based::Thread::current()] = queue; m_queryQueues[ACE_Based::Thread::current()] = queue;
} }
bool Database::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
if (!mMysql)
return 0;
{
// guarded block for thread-safe mySQL request
ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
#ifdef TRINITY_DEBUG
uint32 _s = getMSTime();
#endif
if (mysql_query(mMysql, sql))
{
sLog.outErrorDb("SQL: %s", sql);
sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
return false;
}
else
{
#ifdef TRINITY_DEBUG
sLog.outDebug("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql );
#endif
}
*pResult = mysql_store_result(mMysql);
*pRowCount = mysql_affected_rows(mMysql);
*pFieldCount = mysql_field_count(mMysql);
}
if (!*pResult )
return false;
if (!*pRowCount)
{
mysql_free_result(*pResult);
return false;
}
*pFields = mysql_fetch_fields(*pResult);
return true;
}
QueryResult_AutoPtr Database::Query(const char *sql)
{
MYSQL_RES *result = NULL;
MYSQL_FIELD *fields = NULL;
uint64 rowCount = 0;
uint32 fieldCount = 0;
if (!_Query(sql, &result, &fields, &rowCount, &fieldCount))
return QueryResult_AutoPtr(NULL);
QueryResult *queryResult = new QueryResult(result, fields, rowCount, fieldCount);
queryResult->NextRow();
return QueryResult_AutoPtr(queryResult);
}
QueryResult_AutoPtr Database::PQuery(const char *format,...) QueryResult_AutoPtr Database::PQuery(const char *format,...)
{ {
if (!format) if (!format)
@@ -135,6 +338,27 @@ QueryResult_AutoPtr Database::PQuery(const char *format,...)
return Query(szQuery); return Query(szQuery);
} }
QueryNamedResult* Database::QueryNamed(const char *sql)
{
MYSQL_RES *result = NULL;
MYSQL_FIELD *fields = NULL;
uint64 rowCount = 0;
uint32 fieldCount = 0;
if (!_Query(sql, &result, &fields, &rowCount, &fieldCount))
return NULL;
QueryFieldNames names(fieldCount);
for (uint32 i = 0; i < fieldCount; i++)
names[i] = fields[i].name;
QueryResult *queryResult = new QueryResult(result, fields, rowCount, fieldCount);
queryResult->NextRow();
return new QueryNamedResult(queryResult, names);
}
QueryNamedResult* Database::PQueryNamed(const char *format,...) QueryNamedResult* Database::PQueryNamed(const char *format,...)
{ {
if (!format) if (!format)
@@ -155,6 +379,25 @@ QueryNamedResult* Database::PQueryNamed(const char *format,...)
return QueryNamed(szQuery); return QueryNamed(szQuery);
} }
bool Database::Execute(const char *sql)
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
return DirectExecute(sql);
tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
i->second->DelayExecute(sql); // Statement for transaction
else
m_threadBody->Delay(new SqlStatement(sql)); // Simple sql statement
return true;
}
bool Database::PExecute(const char * format,...) bool Database::PExecute(const char * format,...)
{ {
if (!format) if (!format)
@@ -194,6 +437,35 @@ bool Database::_SetDataBlobValue(const uint32 guid, const uint32 field, const ui
field, value, -int32(PLAYER_END-field), guid); field, value, -int32(PLAYER_END-field), guid);
} }
bool Database::DirectExecute(const char* sql)
{
if (!mMysql)
return false;
{
// guarded block for thread-safe mySQL request
ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
#ifdef TRINITY_DEBUG
uint32 _s = getMSTime();
#endif
if (mysql_query(mMysql, sql))
{
sLog.outErrorDb("SQL: %s", sql);
sLog.outErrorDb("SQL ERROR: %s", mysql_error(mMysql));
return false;
}
else
{
#ifdef TRINITY_DEBUG
sLog.outDebug("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql);
#endif
}
}
return true;
}
bool Database::DirectPExecute(const char * format,...) bool Database::DirectPExecute(const char * format,...)
{ {
if (!format) if (!format)
@@ -250,3 +522,128 @@ bool Database::CheckRequiredField(char const* table_name, char const* required_n
return false; return false;
} }
bool Database::_TransactionCmd(const char *sql)
{
if (mysql_query(mMysql, sql))
{
sLog.outError("SQL: %s", sql);
sLog.outError("SQL ERROR: %s", mysql_error(mMysql));
return false;
}
else
DEBUG_LOG("SQL: %s", sql);
return true;
}
bool Database::BeginTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread == ACE_Based::Thread::current())
return false; // huh? this thread already started transaction
mMutex.acquire();
if (!_TransactionCmd("START TRANSACTION"))
{
mMutex.release(); // can't start transaction
return false;
}
return true; // transaction started
}
tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
// If for thread exists queue and also contains transaction
// delete that transaction (not allow trans in trans)
delete i->second;
m_tranQueues[tranThread] = new SqlTransaction();
return true;
}
bool Database::CommitTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("COMMIT");
tranThread = NULL;
mMutex.release();
return _res;
}
tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
m_threadBody->Delay(i->second);
i->second = NULL;
return true;
}
else
return false;
}
bool Database::RollbackTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("ROLLBACK");
tranThread = NULL;
mMutex.release();
return _res;
}
tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
delete i->second;
i->second = NULL;
}
return true;
}
void Database::InitDelayThread()
{
assert(!m_delayThread);
//New delay thread for delay execute
m_threadBody = new SqlDelayThread(this); // will deleted at m_delayThread delete
m_delayThread = new ACE_Based::Thread(m_threadBody);
}
void Database::HaltDelayThread()
{
if (!m_threadBody || !m_delayThread)
return;
m_threadBody->Stop(); //Stop event
m_delayThread->wait(); //Wait for flush to DB
delete m_delayThread; //This also deletes m_threadBody
m_delayThread = NULL;
m_threadBody = NULL;
}
+40 -29
View File
@@ -24,6 +24,17 @@
#include "Threading.h" #include "Threading.h"
#include "Utilities/UnorderedMap.h" #include "Utilities/UnorderedMap.h"
#include "Database/SqlDelayThread.h" #include "Database/SqlDelayThread.h"
#include "Policies/Singleton.h"
#include "ace/Thread_Mutex.h"
#include "ace/Guard_T.h"
#ifdef WIN32
#define FD_SETSIZE 1024
#include <winsock2.h>
#include <mysql/mysql.h>
#else
#include <mysql.h>
#endif
class SqlTransaction; class SqlTransaction;
class SqlResultQueue; class SqlResultQueue;
@@ -37,8 +48,6 @@ typedef UNORDERED_MAP<ACE_Based::Thread* , SqlResultQueue*> QueryQueues;
class Database class Database
{ {
protected: protected:
Database() : m_threadBody(NULL), m_delayThread(NULL) {};
TransactionQueues m_tranQueues; ///< Transaction queues from diff. threads TransactionQueues m_tranQueues; ///< Transaction queues from diff. threads
QueryQueues m_queryQueues; ///< Query queues from diff threads QueryQueues m_queryQueues; ///< Query queues from diff threads
SqlDelayThread* m_threadBody; ///< Pointer to delay sql executer (owned by m_delayThread) SqlDelayThread* m_threadBody; ///< Pointer to delay sql executer (owned by m_delayThread)
@@ -46,15 +55,18 @@ class Database
public: public:
virtual ~Database(); Database();
~Database();
virtual bool Initialize(const char *infoString); /*! infoString should be formated like hostname;username;password;database. */
virtual void InitDelayThread() = 0; bool Initialize(const char *infoString);
virtual void HaltDelayThread() = 0;
virtual QueryResult_AutoPtr Query(const char *sql) = 0; void InitDelayThread();
void HaltDelayThread();
QueryResult_AutoPtr Query(const char *sql);
QueryResult_AutoPtr PQuery(const char *format,...) ATTR_PRINTF(2,3); QueryResult_AutoPtr PQuery(const char *format,...) ATTR_PRINTF(2,3);
virtual QueryNamedResult* QueryNamed(const char *sql) = 0; QueryNamedResult* QueryNamed(const char *sql);
QueryNamedResult* PQueryNamed(const char *format,...) ATTR_PRINTF(2,3); QueryNamedResult* PQueryNamed(const char *format,...) ATTR_PRINTF(2,3);
/// Async queries and query holders, implemented in DatabaseImpl.h /// Async queries and query holders, implemented in DatabaseImpl.h
@@ -97,9 +109,9 @@ class Database
template<class Class, typename ParamType1> template<class Class, typename ParamType1>
bool DelayQueryHolder(Class *object, void (Class::*method)(QueryResult_AutoPtr, SqlQueryHolder*, ParamType1), SqlQueryHolder *holder, ParamType1 param1); bool DelayQueryHolder(Class *object, void (Class::*method)(QueryResult_AutoPtr, SqlQueryHolder*, ParamType1), SqlQueryHolder *holder, ParamType1 param1);
virtual bool Execute(const char *sql) = 0; bool Execute(const char *sql);
bool PExecute(const char *format,...) ATTR_PRINTF(2,3); bool PExecute(const char *format,...) ATTR_PRINTF(2,3);
virtual bool DirectExecute(const char* sql) = 0; bool DirectExecute(const char* sql);
bool DirectPExecute(const char *format,...) ATTR_PRINTF(2,3); bool DirectPExecute(const char *format,...) ATTR_PRINTF(2,3);
bool _UpdateDataBlobValue(const uint32 guid, const uint32 field, const int32 value); bool _UpdateDataBlobValue(const uint32 guid, const uint32 field, const int32 value);
@@ -108,36 +120,35 @@ class Database
// Writes SQL commands to a LOG file (see Trinityd.conf "LogSQL") // Writes SQL commands to a LOG file (see Trinityd.conf "LogSQL")
bool PExecuteLog(const char *format,...) ATTR_PRINTF(2,3); bool PExecuteLog(const char *format,...) ATTR_PRINTF(2,3);
virtual bool BeginTransaction() // nothing do if DB not support transactions bool BeginTransaction();
{ bool CommitTransaction();
return true; bool RollbackTransaction();
}
virtual bool CommitTransaction() // nothing do if DB not support transactions
{
return true;
}
virtual bool RollbackTransaction() // can't rollback without transaction support
{
return false;
}
virtual operator bool () const = 0; operator bool () const { return mMysql != NULL; }
unsigned long escape_string(char *to, const char *from, unsigned long length);
virtual unsigned long escape_string(char *to, const char *from, unsigned long length) { strncpy(to,from,length); return length; }
void escape_string(std::string& str); void escape_string(std::string& str);
// must be called before first query in thread (one time for thread using one from existed Database objects) void ThreadStart();
virtual void ThreadStart(); void ThreadEnd();
// must be called before finish thread run (one time for thread using one from existed Database objects)
virtual void ThreadEnd();
// sets the result queue of the current thread, be careful what thread you call this from // sets the result queue of the current thread, be careful what thread you call this from
void SetResultQueue(SqlResultQueue * queue); void SetResultQueue(SqlResultQueue * queue);
bool CheckRequiredField(char const* table_name, char const* required_name); bool CheckRequiredField(char const* table_name, char const* required_name);
private: private:
bool m_logSQL; bool m_logSQL;
std::string m_logsDir; std::string m_logsDir;
ACE_Thread_Mutex mMutex;
ACE_Based::Thread * tranThread;
MYSQL *mMysql;
static size_t db_count;
bool _TransactionCmd(const char *sql);
bool _Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount);
}; };
#endif #endif
+2 -4
View File
@@ -28,10 +28,8 @@
#include "Database/Field.h" #include "Database/Field.h"
#include "Database/QueryResult.h" #include "Database/QueryResult.h"
#include "Database/QueryResultMysql.h"
#include "Database/Database.h" #include "Database/Database.h"
#include "Database/DatabaseMysql.h" typedef Database DatabaseType;
typedef DatabaseMysql DatabaseType;
#define _LIKE_ "LIKE" #define _LIKE_ "LIKE"
#define _TABLE_SIM_ "`" #define _TABLE_SIM_ "`"
#define _CONCAT3_(A,B,C) "CONCAT( " A " , " B " , " C " )" #define _CONCAT3_(A,B,C) "CONCAT( " A " , " B " , " C " )"
@@ -39,7 +37,7 @@ typedef DatabaseMysql DatabaseType;
extern DatabaseType WorldDatabase; extern DatabaseType WorldDatabase;
extern DatabaseType CharacterDatabase; extern DatabaseType CharacterDatabase;
extern DatabaseType loginDatabase; extern DatabaseType LoginDatabase;
#endif #endif
-435
View File
@@ -1,435 +0,0 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Util.h"
#include "Policies/SingletonImp.h"
#include "Platform/Define.h"
#include "Threading.h"
#include "DatabaseEnv.h"
#include "Database/MySQLDelayThread.h"
#include "Database/SqlOperations.h"
#include "Timer.h"
void DatabaseMysql::ThreadStart()
{
mysql_thread_init();
}
void DatabaseMysql::ThreadEnd()
{
mysql_thread_end();
}
size_t DatabaseMysql::db_count = 0;
DatabaseMysql::DatabaseMysql() : Database(), mMysql(0)
{
// before first connection
if (db_count++ == 0)
{
// Mysql Library Init
mysql_library_init(-1, NULL, NULL);
if (!mysql_thread_safe())
{
sLog.outError("FATAL ERROR: Used MySQL library isn't thread-safe.");
exit(1);
}
}
}
DatabaseMysql::~DatabaseMysql()
{
if (m_delayThread)
HaltDelayThread();
if (mMysql)
mysql_close(mMysql);
// Free Mysql library pointers for last ~DB
if (--db_count == 0)
mysql_library_end();
}
bool DatabaseMysql::Initialize(const char *infoString)
{
if (!Database::Initialize(infoString))
return false;
tranThread = NULL;
MYSQL *mysqlInit;
mysqlInit = mysql_init(NULL);
if (!mysqlInit)
{
sLog.outError("Could not initialize Mysql connection");
return false;
}
InitDelayThread();
Tokens tokens = StrSplit(infoString, ";");
Tokens::iterator iter;
std::string host, port_or_socket, user, password, database;
int port;
char const* unix_socket;
iter = tokens.begin();
if (iter != tokens.end())
host = *iter++;
if (iter != tokens.end())
port_or_socket = *iter++;
if (iter != tokens.end())
user = *iter++;
if (iter != tokens.end())
password = *iter++;
if (iter != tokens.end())
database = *iter++;
mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8");
#ifdef WIN32
if (host==".") // named pipe use option (Windows)
{
unsigned int opt = MYSQL_PROTOCOL_PIPE;
mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
port = 0;
unix_socket = 0;
}
else // generic case
{
port = atoi(port_or_socket.c_str());
unix_socket = 0;
}
#else
if (host==".") // socket use option (Unix/Linux)
{
unsigned int opt = MYSQL_PROTOCOL_SOCKET;
mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt);
host = "localhost";
port = 0;
unix_socket = port_or_socket.c_str();
}
else // generic case
{
port = atoi(port_or_socket.c_str());
unix_socket = 0;
}
#endif
mMysql = mysql_real_connect(mysqlInit, host.c_str(), user.c_str(),
password.c_str(), database.c_str(), port, unix_socket, 0);
if (mMysql)
{
sLog.outDetail("Connected to MySQL database at %s", host.c_str());
sLog.outString("MySQL client library: %s", mysql_get_client_info());
sLog.outString("MySQL server ver: %s ", mysql_get_server_info( mMysql));
if (!mysql_autocommit(mMysql, 1))
sLog.outDetail("AUTOCOMMIT SUCCESSFULLY SET TO 1");
else
sLog.outDetail("AUTOCOMMIT NOT SET TO 1");
// set connection properties to UTF8 to properly handle locales for different
// server configs - core sends data in UTF8, so MySQL must expect UTF8 too
PExecute("SET NAMES `utf8`");
PExecute("SET CHARACTER SET `utf8`");
#if MYSQL_VERSION_ID >= 50003
my_bool my_true = (my_bool)1;
if (mysql_options(mMysql, MYSQL_OPT_RECONNECT, &my_true))
sLog.outDetail("Failed to turn on MYSQL_OPT_RECONNECT.");
else
sLog.outDetail("Successfully turned on MYSQL_OPT_RECONNECT.");
#else
#warning "Your mySQL client lib version does not support reconnecting after a timeout.\nIf this causes you any trouble we advice you to upgrade your mySQL client libs to at least mySQL 5.0.13 to resolve this problem."
#endif
return true;
}
else
{
sLog.outError("Could not connect to MySQL database at %s: %s\n", host.c_str(),mysql_error(mysqlInit));
mysql_close(mysqlInit);
return false;
}
}
bool DatabaseMysql::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
if (!mMysql)
return 0;
{
// guarded block for thread-safe mySQL request
ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
#ifdef TRINITY_DEBUG
uint32 _s = getMSTime();
#endif
if (mysql_query(mMysql, sql))
{
sLog.outErrorDb("SQL: %s", sql);
sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
return false;
}
else
{
#ifdef TRINITY_DEBUG
sLog.outDebug("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql );
#endif
}
*pResult = mysql_store_result(mMysql);
*pRowCount = mysql_affected_rows(mMysql);
*pFieldCount = mysql_field_count(mMysql);
}
if (!*pResult )
return false;
if (!*pRowCount)
{
mysql_free_result(*pResult);
return false;
}
*pFields = mysql_fetch_fields(*pResult);
return true;
}
QueryResult_AutoPtr DatabaseMysql::Query(const char *sql)
{
MYSQL_RES *result = NULL;
MYSQL_FIELD *fields = NULL;
uint64 rowCount = 0;
uint32 fieldCount = 0;
if (!_Query(sql, &result, &fields, &rowCount, &fieldCount))
return QueryResult_AutoPtr(NULL);
QueryResultMysql *queryResult = new QueryResultMysql(result, fields, rowCount, fieldCount);
queryResult->NextRow();
return QueryResult_AutoPtr(queryResult);
}
QueryNamedResult* DatabaseMysql::QueryNamed(const char *sql)
{
MYSQL_RES *result = NULL;
MYSQL_FIELD *fields = NULL;
uint64 rowCount = 0;
uint32 fieldCount = 0;
if (!_Query(sql, &result, &fields, &rowCount, &fieldCount))
return NULL;
QueryFieldNames names(fieldCount);
for (uint32 i = 0; i < fieldCount; i++)
names[i] = fields[i].name;
QueryResultMysql *queryResult = new QueryResultMysql(result, fields, rowCount, fieldCount);
queryResult->NextRow();
return new QueryNamedResult(queryResult, names);
}
bool DatabaseMysql::Execute(const char *sql)
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
return DirectExecute(sql);
tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
i->second->DelayExecute(sql); // Statement for transaction
else
m_threadBody->Delay(new SqlStatement(sql)); // Simple sql statement
return true;
}
bool DatabaseMysql::DirectExecute(const char* sql)
{
if (!mMysql)
return false;
{
// guarded block for thread-safe mySQL request
ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
#ifdef TRINITY_DEBUG
uint32 _s = getMSTime();
#endif
if (mysql_query(mMysql, sql))
{
sLog.outErrorDb("SQL: %s", sql);
sLog.outErrorDb("SQL ERROR: %s", mysql_error(mMysql));
return false;
}
else
{
#ifdef TRINITY_DEBUG
sLog.outDebug("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql);
#endif
}
}
return true;
}
bool DatabaseMysql::_TransactionCmd(const char *sql)
{
if (mysql_query(mMysql, sql))
{
sLog.outError("SQL: %s", sql);
sLog.outError("SQL ERROR: %s", mysql_error(mMysql));
return false;
}
else
DEBUG_LOG("SQL: %s", sql);
return true;
}
bool DatabaseMysql::BeginTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread == ACE_Based::Thread::current())
return false; // huh? this thread already started transaction
mMutex.acquire();
if (!_TransactionCmd("START TRANSACTION"))
{
mMutex.release(); // can't start transaction
return false;
}
return true; // transaction started
}
tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
// If for thread exists queue and also contains transaction
// delete that transaction (not allow trans in trans)
delete i->second;
m_tranQueues[tranThread] = new SqlTransaction();
return true;
}
bool DatabaseMysql::CommitTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("COMMIT");
tranThread = NULL;
mMutex.release();
return _res;
}
tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
m_threadBody->Delay(i->second);
i->second = NULL;
return true;
}
else
return false;
}
bool DatabaseMysql::RollbackTransaction()
{
if (!mMysql)
return false;
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("ROLLBACK");
tranThread = NULL;
mMutex.release();
return _res;
}
tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
delete i->second;
i->second = NULL;
}
return true;
}
unsigned long DatabaseMysql::escape_string(char *to, const char *from, unsigned long length)
{
if (!mMysql || !to || !from || !length)
return 0;
return(mysql_real_escape_string(mMysql, to, from, length));
}
void DatabaseMysql::InitDelayThread()
{
assert(!m_delayThread);
//New delay thread for delay execute
m_threadBody = new MySQLDelayThread(this); // will deleted at m_delayThread delete
m_delayThread = new ACE_Based::Thread(m_threadBody);
}
void DatabaseMysql::HaltDelayThread()
{
if (!m_threadBody || !m_delayThread)
return;
m_threadBody->Stop(); //Stop event
m_delayThread->wait(); //Wait for flush to DB
delete m_delayThread; //This also deletes m_threadBody
m_delayThread = NULL;
m_threadBody = NULL;
}
-80
View File
@@ -1,80 +0,0 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _DATABASEMYSQL_H
#define _DATABASEMYSQL_H
#include "Database.h"
#include "Policies/Singleton.h"
#include "ace/Thread_Mutex.h"
#include "ace/Guard_T.h"
#ifdef WIN32
#define FD_SETSIZE 1024
#include <winsock2.h>
#include <mysql/mysql.h>
#else
#include <mysql.h>
#endif
class DatabaseMysql : public Database
{
friend class Trinity::OperatorNew<DatabaseMysql>;
public:
DatabaseMysql();
~DatabaseMysql();
//! Initializes Mysql and connects to a server.
/*! infoString should be formated like hostname;username;password;database. */
bool Initialize(const char *infoString);
void InitDelayThread();
void HaltDelayThread();
QueryResult_AutoPtr Query(const char *sql);
QueryNamedResult* QueryNamed(const char *sql);
bool Execute(const char *sql);
bool DirectExecute(const char* sql);
bool BeginTransaction();
bool CommitTransaction();
bool RollbackTransaction();
operator bool () const { return mMysql != NULL; }
unsigned long escape_string(char *to, const char *from, unsigned long length);
using Database::escape_string;
// must be call before first query in thread
void ThreadStart();
// must be call before finish thread run
void ThreadEnd();
private:
ACE_Thread_Mutex mMutex;
ACE_Based::Thread * tranThread;
MYSQL *mMysql;
static size_t db_count;
bool _TransactionCmd(const char *sql);
bool _Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount);
};
#endif
-33
View File
@@ -1,33 +0,0 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __MYSQLDELAYTHREAD_H
#define __MYSQLDELAYTHREAD_H
#include "Database/SqlDelayThread.h"
class MySQLDelayThread : public SqlDelayThread
{
public:
MySQLDelayThread(Database* db) : SqlDelayThread(db) {}
void Stop() { SqlDelayThread::Stop(); }
};
#endif //__MYSQLDELAYTHREAD_H
@@ -20,10 +20,11 @@
#include "DatabaseEnv.h" #include "DatabaseEnv.h"
QueryResultMysql::QueryResultMysql(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) : QueryResult::QueryResult(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount)
QueryResult(rowCount, fieldCount), mResult(result) : mResult(result)
, mFieldCount(fieldCount)
, mRowCount(rowCount)
{ {
mCurrentRow = new Field[mFieldCount]; mCurrentRow = new Field[mFieldCount];
ASSERT(mCurrentRow); ASSERT(mCurrentRow);
@@ -31,12 +32,12 @@ QueryResultMysql::QueryResultMysql(MYSQL_RES *result, MYSQL_FIELD *fields, uint6
mCurrentRow[i].SetType(ConvertNativeType(fields[i].type)); mCurrentRow[i].SetType(ConvertNativeType(fields[i].type));
} }
QueryResultMysql::~QueryResultMysql() QueryResult::~QueryResult()
{ {
EndQuery(); EndQuery();
} }
bool QueryResultMysql::NextRow() bool QueryResult::NextRow()
{ {
MYSQL_ROW row; MYSQL_ROW row;
@@ -56,7 +57,7 @@ bool QueryResultMysql::NextRow()
return true; return true;
} }
void QueryResultMysql::EndQuery() void QueryResult::EndQuery()
{ {
if (mCurrentRow) if (mCurrentRow)
{ {
@@ -71,7 +72,7 @@ void QueryResultMysql::EndQuery()
} }
} }
enum Field::DataTypes QueryResultMysql::ConvertNativeType(enum_field_types mysqlType) const enum Field::DataTypes QueryResult::ConvertNativeType(enum_field_types mysqlType) const
{ {
switch (mysqlType) switch (mysqlType)
{ {
+17 -5
View File
@@ -26,15 +26,21 @@
#include "Field.h" #include "Field.h"
#ifdef WIN32
#define FD_SETSIZE 1024
#include <winsock2.h>
#include <mysql/mysql.h>
#else
#include <mysql.h>
#endif
class QueryResult class QueryResult
{ {
public: public:
QueryResult(uint64 rowCount, uint32 fieldCount) QueryResult(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount);
: mFieldCount(fieldCount), mRowCount(rowCount) {} ~QueryResult();
virtual ~QueryResult() {} bool NextRow();
virtual bool NextRow() = 0;
Field *Fetch() const { return mCurrentRow; } Field *Fetch() const { return mCurrentRow; }
@@ -47,6 +53,12 @@ class QueryResult
Field *mCurrentRow; Field *mCurrentRow;
uint32 mFieldCount; uint32 mFieldCount;
uint64 mRowCount; uint64 mRowCount;
private:
enum Field::DataTypes ConvertNativeType(enum_field_types mysqlType) const;
void EndQuery();
MYSQL_RES *mResult;
}; };
typedef ACE_Refcounted_Auto_Ptr<QueryResult, ACE_Null_Mutex> QueryResult_AutoPtr; typedef ACE_Refcounted_Auto_Ptr<QueryResult, ACE_Null_Mutex> QueryResult_AutoPtr;
-47
View File
@@ -1,47 +0,0 @@
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if !defined(QUERYRESULTMYSQL_H)
#define QUERYRESULTMYSQL_H
#ifdef WIN32
#define FD_SETSIZE 1024
#include <winsock2.h>
#include <mysql/mysql.h>
#else
#include <mysql.h>
#endif
class QueryResultMysql : public QueryResult
{
public:
QueryResultMysql(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount);
~QueryResultMysql();
bool NextRow();
private:
enum Field::DataTypes ConvertNativeType(enum_field_types mysqlType) const;
void EndQuery();
MYSQL_RES *mResult;
};
#endif
+1 -1
View File
@@ -21,7 +21,7 @@
#include "SQLStorage.h" #include "SQLStorage.h"
#include "SQLStorageImpl.h" #include "SQLStorageImpl.h"
extern DatabaseMysql WorldDatabase; extern Database WorldDatabase;
const char CreatureInfosrcfmt[]="iiiiiiiiiisssiiiiiiifffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiifffliiiiiiiliiisi"; const char CreatureInfosrcfmt[]="iiiiiiiiiisssiiiiiiifffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiifffliiiiiiiliiisi";
const char CreatureInfodstfmt[]="iiiiiiiiiisssibbiiiifffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiifffliiiiiiiliiiii"; const char CreatureInfodstfmt[]="iiiiiiiiiisssibbiiiifffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiifffliiiiiiiliiiii";
+1 -1
View File
@@ -44,7 +44,7 @@ class SqlDelayThread : public ACE_Based::Runnable
///< Put sql statement to delay queue ///< Put sql statement to delay queue
bool Delay(SqlOperation* sql); bool Delay(SqlOperation* sql);
virtual void Stop(); ///< Stop event void Stop(); ///< Stop event
virtual void run(); ///< Main Thread loop virtual void run(); ///< Main Thread loop
}; };
#endif //__SQLDELAYTHREAD_H #endif //__SQLDELAYTHREAD_H
+2 -2
View File
@@ -364,9 +364,9 @@ void Log::outDB(LogTypes type, const char * str)
std::string new_str(str); std::string new_str(str);
if (new_str.empty()) if (new_str.empty())
return; return;
loginDatabase.escape_string(new_str); LoginDatabase.escape_string(new_str);
loginDatabase.PExecute("INSERT INTO logs (time, realm, type, string) " LoginDatabase.PExecute("INSERT INTO logs (time, realm, type, string) "
"VALUES (" UI64FMTD ", %u, %u, '%s');", uint64(time(0)), realm, type, new_str.c_str()); "VALUES (" UI64FMTD ", %u, %u, '%s');", uint64(time(0)), realm, type, new_str.c_str());
} }
+1 -1
View File
@@ -241,7 +241,7 @@ bool ChatHandler::HandleAccountOnlineListCommand(const char* /*args*/)
///- Get the username, last IP and GM level of each account ///- Get the username, last IP and GM level of each account
// No SQL injection. account is uint32. // No SQL injection. account is uint32.
QueryResult_AutoPtr resultLogin = QueryResult_AutoPtr resultLogin =
loginDatabase.PQuery("SELECT a.username, a.last_ip, aa.gmlevel, a.expansion " LoginDatabase.PQuery("SELECT a.username, a.last_ip, aa.gmlevel, a.expansion "
"FROM account a " "FROM account a "
"LEFT JOIN account_access aa " "LEFT JOIN account_access aa "
"ON (a.id = aa.id) " "ON (a.id = aa.id) "
+1 -1
View File
@@ -53,7 +53,7 @@ int m_ServiceStatus = -1;
DatabaseType WorldDatabase; ///< Accessor to the world database DatabaseType WorldDatabase; ///< Accessor to the world database
DatabaseType CharacterDatabase; ///< Accessor to the character database DatabaseType CharacterDatabase; ///< Accessor to the character database
DatabaseType loginDatabase; ///< Accessor to the realm/login database DatabaseType LoginDatabase; ///< Accessor to the realm/login database
uint32 realmID; ///< Id of the realm uint32 realmID; ///< Id of the realm
+7 -7
View File
@@ -135,7 +135,7 @@ public:
loopCounter = 0; loopCounter = 0;
sLog.outDetail ("Ping MySQL to keep connection alive"); sLog.outDetail ("Ping MySQL to keep connection alive");
WorldDatabase.Query ("SELECT 1 FROM command LIMIT 1"); WorldDatabase.Query ("SELECT 1 FROM command LIMIT 1");
loginDatabase.Query ("SELECT 1 FROM realmlist LIMIT 1"); LoginDatabase.Query ("SELECT 1 FROM realmlist LIMIT 1");
CharacterDatabase.Query ("SELECT 1 FROM bugreport LIMIT 1"); CharacterDatabase.Query ("SELECT 1 FROM bugreport LIMIT 1");
} }
} }
@@ -241,7 +241,7 @@ int Master::Run()
world_thread.setPriority(ACE_Based::Highest); world_thread.setPriority(ACE_Based::Highest);
// set server online // set server online
loginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID); LoginDatabase.PExecute("UPDATE realmlist SET color = 0, population = 0 WHERE id = '%d'",realmID);
ACE_Based::Thread* cliThread = NULL; ACE_Based::Thread* cliThread = NULL;
@@ -329,7 +329,7 @@ int Master::Run()
sWorldSocketMgr->Wait (); sWorldSocketMgr->Wait ();
// set server offline // set server offline
loginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID); LoginDatabase.PExecute("UPDATE realmlist SET color = 2 WHERE id = '%d'",realmID);
///- Remove signal handling before leaving ///- Remove signal handling before leaving
_UnhookSignals(); _UnhookSignals();
@@ -345,7 +345,7 @@ int Master::Run()
///- Wait for delay threads to end ///- Wait for delay threads to end
CharacterDatabase.HaltDelayThread(); CharacterDatabase.HaltDelayThread();
WorldDatabase.HaltDelayThread(); WorldDatabase.HaltDelayThread();
loginDatabase.HaltDelayThread(); LoginDatabase.HaltDelayThread();
sLog.outString( "Halting process..." ); sLog.outString( "Halting process..." );
@@ -444,7 +444,7 @@ bool Master::_StartDB()
} }
///- Get login database info from configuration file ///- Get login database info from configuration file
dbstring = sConfig.GetStringDefault("loginDatabaseInfo", ""); dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if(dbstring.empty()) if(dbstring.empty())
{ {
sLog.outError("Login database not specified in configuration file"); sLog.outError("Login database not specified in configuration file");
@@ -452,7 +452,7 @@ bool Master::_StartDB()
} }
///- Initialise the login database ///- Initialise the login database
if(!loginDatabase.Initialize(dbstring.c_str())) if(!LoginDatabase.Initialize(dbstring.c_str()))
{ {
sLog.outError("Cannot connect to login database %s",dbstring.c_str()); sLog.outError("Cannot connect to login database %s",dbstring.c_str());
return false; return false;
@@ -500,7 +500,7 @@ void Master::clearOnlineAccounts()
{ {
// Cleanup online status for characters hosted at current realm // Cleanup online status for characters hosted at current realm
/// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'? /// \todo Only accounts with characters logged on *this* realm should have online status reset. Move the online column from 'account' to 'realmcharacters'?
loginDatabase.PExecute( LoginDatabase.PExecute(
"UPDATE account SET online = 0 WHERE online > 0 " "UPDATE account SET online = 0 WHERE online > 0 "
"AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID); "AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = '%d')",realmID);
+5 -5
View File
@@ -152,9 +152,9 @@ void RASocket::OnRead()
AccountMgr::normalizeString(login); AccountMgr::normalizeString(login);
///- Escape the Login to allow quotes in names ///- Escape the Login to allow quotes in names
loginDatabase.escape_string(login); LoginDatabase.escape_string(login);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = '%s'",login.c_str ()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = '%s'",login.c_str ());
///- If the user is not found, deny access ///- If the user is not found, deny access
if(!result) if(!result)
@@ -200,10 +200,10 @@ void RASocket::OnRead()
AccountMgr::normalizeString(login); AccountMgr::normalizeString(login);
AccountMgr::normalizeString(pw); AccountMgr::normalizeString(pw);
loginDatabase.escape_string(login); LoginDatabase.escape_string(login);
loginDatabase.escape_string(pw); LoginDatabase.escape_string(pw);
QueryResult_AutoPtr check = loginDatabase.PQuery( QueryResult_AutoPtr check = LoginDatabase.PQuery(
"SELECT 1 FROM account WHERE username = '%s' AND sha_pass_hash=SHA1(CONCAT('%s',':','%s'))", "SELECT 1 FROM account WHERE username = '%s' AND sha_pass_hash=SHA1(CONCAT('%s',':','%s'))",
login.c_str(), login.c_str(), pw.c_str()); login.c_str(), login.c_str(), pw.c_str());
+18 -18
View File
@@ -34,7 +34,7 @@
#include "Auth/Sha1.h" #include "Auth/Sha1.h"
//#include "Util.h" -- for commented utf8ToUpperOnlyLatin //#include "Util.h" -- for commented utf8ToUpperOnlyLatin
extern DatabaseType loginDatabase; extern DatabaseType LoginDatabase;
#define ChunkSize 2048 #define ChunkSize 2048
@@ -296,7 +296,7 @@ void AuthSocket::_SetVSFields(const std::string& rI)
const char *v_hex, *s_hex; const char *v_hex, *s_hex;
v_hex = v.AsHexStr(); v_hex = v.AsHexStr();
s_hex = s.AsHexStr(); s_hex = s.AsHexStr();
loginDatabase.PExecute("UPDATE account SET v = '%s', s = '%s' WHERE username = '%s'", v_hex, s_hex, _safelogin.c_str()); LoginDatabase.PExecute("UPDATE account SET v = '%s', s = '%s' WHERE username = '%s'", v_hex, s_hex, _safelogin.c_str());
OPENSSL_free((void*)v_hex); OPENSSL_free((void*)v_hex);
OPENSSL_free((void*)s_hex); OPENSSL_free((void*)s_hex);
} }
@@ -353,7 +353,7 @@ bool AuthSocket::_HandleLogonChallenge()
//Escape the user login to avoid further SQL injection //Escape the user login to avoid further SQL injection
//Memory will be freed on AuthSocket object destruction //Memory will be freed on AuthSocket object destruction
_safelogin = _login; _safelogin = _login;
loginDatabase.escape_string(_safelogin); LoginDatabase.escape_string(_safelogin);
_build = ch->build; _build = ch->build;
@@ -362,11 +362,11 @@ bool AuthSocket::_HandleLogonChallenge()
///- Verify that this IP is not in the ip_banned table ///- Verify that this IP is not in the ip_banned table
// No SQL injection possible (paste the IP address as passed by the socket) // No SQL injection possible (paste the IP address as passed by the socket)
loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
std::string address(socket().get_remote_address().c_str()); std::string address(socket().get_remote_address().c_str());
loginDatabase.escape_string(address); LoginDatabase.escape_string(address);
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT * FROM ip_banned WHERE ip = '%s'",address.c_str()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT * FROM ip_banned WHERE ip = '%s'",address.c_str());
if (result) if (result)
{ {
pkt << (uint8)WOW_FAIL_BANNED; pkt << (uint8)WOW_FAIL_BANNED;
@@ -377,7 +377,7 @@ bool AuthSocket::_HandleLogonChallenge()
///- Get the account details from the account table ///- Get the account details from the account table
// No SQL injection (escaped user name) // No SQL injection (escaped user name)
result = loginDatabase.PQuery("SELECT a.sha_pass_hash,a.id,a.locked,a.last_ip,aa.gmlevel,a.v,a.s " result = LoginDatabase.PQuery("SELECT a.sha_pass_hash,a.id,a.locked,a.last_ip,aa.gmlevel,a.v,a.s "
"FROM account a " "FROM account a "
"LEFT JOIN account_access aa " "LEFT JOIN account_access aa "
"ON (a.id = aa.id) " "ON (a.id = aa.id) "
@@ -405,9 +405,9 @@ bool AuthSocket::_HandleLogonChallenge()
if (!locked) if (!locked)
{ {
//set expired bans to inactive //set expired bans to inactive
loginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate"); LoginDatabase.Execute("UPDATE account_banned SET active = 0 WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
///- If the account is banned, reject the logon attempt ///- If the account is banned, reject the logon attempt
QueryResult_AutoPtr banresult = loginDatabase.PQuery("SELECT bandate,unbandate FROM account_banned WHERE id = %u AND active = 1", (*result)[1].GetUInt32()); QueryResult_AutoPtr banresult = LoginDatabase.PQuery("SELECT bandate,unbandate FROM account_banned WHERE id = %u AND active = 1", (*result)[1].GetUInt32());
if (banresult) if (banresult)
{ {
if ((*banresult)[0].GetUInt64() == (*banresult)[1].GetUInt64()) if ((*banresult)[0].GetUInt64() == (*banresult)[1].GetUInt64())
@@ -609,7 +609,7 @@ bool AuthSocket::_HandleLogonProof()
///- Update the sessionkey, last_ip, last login time and reset number of failed logins in the account table for this account ///- Update the sessionkey, last_ip, last login time and reset number of failed logins in the account table for this account
// No SQL injection (escaped user name) and IP address as received by socket // No SQL injection (escaped user name) and IP address as received by socket
const char* K_hex = K.AsHexStr(); const char* K_hex = K.AsHexStr();
loginDatabase.PExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = '%u', failed_logins = 0 WHERE username = '%s'", K_hex, socket().get_remote_address().c_str(), GetLocaleByName(_localizationName), _safelogin.c_str()); LoginDatabase.PExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = '%u', failed_logins = 0 WHERE username = '%s'", K_hex, socket().get_remote_address().c_str(), GetLocaleByName(_localizationName), _safelogin.c_str());
OPENSSL_free((void*)K_hex); OPENSSL_free((void*)K_hex);
///- Finish SRP6 and send the final result to the client ///- Finish SRP6 and send the final result to the client
@@ -653,9 +653,9 @@ bool AuthSocket::_HandleLogonProof()
if (MaxWrongPassCount > 0) if (MaxWrongPassCount > 0)
{ {
//Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP //Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP
loginDatabase.PExecute("UPDATE account SET failed_logins = failed_logins + 1 WHERE username = '%s'",_safelogin.c_str()); LoginDatabase.PExecute("UPDATE account SET failed_logins = failed_logins + 1 WHERE username = '%s'",_safelogin.c_str());
if (QueryResult_AutoPtr loginfail = loginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '%s'", _safelogin.c_str())) if (QueryResult_AutoPtr loginfail = LoginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '%s'", _safelogin.c_str()))
{ {
Field* fields = loginfail->Fetch(); Field* fields = loginfail->Fetch();
uint32 failed_logins = fields[1].GetUInt32(); uint32 failed_logins = fields[1].GetUInt32();
@@ -668,7 +668,7 @@ bool AuthSocket::_HandleLogonProof()
if (WrongPassBanType) if (WrongPassBanType)
{ {
uint32 acc_id = fields[0].GetUInt32(); uint32 acc_id = fields[0].GetUInt32();
loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Trinity realmd','Failed login autoban',1)", LoginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Trinity realmd','Failed login autoban',1)",
acc_id, WrongPassBanTime); acc_id, WrongPassBanTime);
sLog.outBasic("[AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times", sLog.outBasic("[AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times",
_login.c_str(), WrongPassBanTime, failed_logins); _login.c_str(), WrongPassBanTime, failed_logins);
@@ -676,8 +676,8 @@ bool AuthSocket::_HandleLogonProof()
else else
{ {
std::string current_ip(socket().get_remote_address().c_str()); std::string current_ip(socket().get_remote_address().c_str());
loginDatabase.escape_string(current_ip); LoginDatabase.escape_string(current_ip);
loginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Trinity realmd','Failed login autoban')", LoginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Trinity realmd','Failed login autoban')",
current_ip.c_str(), WrongPassBanTime); current_ip.c_str(), WrongPassBanTime);
sLog.outBasic("[AuthChallenge] IP %s got banned for '%u' seconds because account %s failed to authenticate '%u' times", sLog.outBasic("[AuthChallenge] IP %s got banned for '%u' seconds because account %s failed to authenticate '%u' times",
current_ip.c_str(), WrongPassBanTime, _login.c_str(), failed_logins); current_ip.c_str(), WrongPassBanTime, _login.c_str(), failed_logins);
@@ -723,7 +723,7 @@ bool AuthSocket::_HandleReconnectChallenge()
_login = (const char*)ch->I; _login = (const char*)ch->I;
_safelogin = _login; _safelogin = _login;
QueryResult_AutoPtr result = loginDatabase.PQuery ("SELECT sessionkey FROM account WHERE username = '%s'", _safelogin.c_str ()); QueryResult_AutoPtr result = LoginDatabase.PQuery ("SELECT sessionkey FROM account WHERE username = '%s'", _safelogin.c_str ());
// Stop if the account is not found // Stop if the account is not found
if (!result) if (!result)
@@ -802,7 +802,7 @@ bool AuthSocket::_HandleRealmList()
///- Get the user id (else close the connection) ///- Get the user id (else close the connection)
// No SQL injection (escaped user name) // No SQL injection (escaped user name)
QueryResult_AutoPtr result = loginDatabase.PQuery("SELECT id,sha_pass_hash FROM account WHERE username = '%s'",_safelogin.c_str()); QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT id,sha_pass_hash FROM account WHERE username = '%s'",_safelogin.c_str());
if (!result) if (!result)
{ {
sLog.outError("[ERROR] user %s tried to login and we cannot find him in the database.",_login.c_str()); sLog.outError("[ERROR] user %s tried to login and we cannot find him in the database.",_login.c_str());
@@ -846,7 +846,7 @@ bool AuthSocket::_HandleRealmList()
uint8 AmountOfCharacters; uint8 AmountOfCharacters;
// No SQL injection. id of realm is controlled by the database. // No SQL injection. id of realm is controlled by the database.
result = loginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'",i->second.m_ID,id); result = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'",i->second.m_ID,id);
if (result) if (result)
{ {
Field *fields = result->Fetch(); Field *fields = result->Fetch();
+7 -7
View File
@@ -62,7 +62,7 @@ void HookSignals();
bool stopEvent = false; ///< Setting it to true stops the server bool stopEvent = false; ///< Setting it to true stops the server
DatabaseType loginDatabase; ///< Accessor to the realm server database DatabaseType LoginDatabase; ///< Accessor to the realm server database
/// Print out the usage string for this program on the console. /// Print out the usage string for this program on the console.
void usage(const char *prog) void usage(const char *prog)
@@ -291,7 +291,7 @@ extern int main(int argc, char **argv)
{ {
loopCounter = 0; loopCounter = 0;
sLog.outDetail("Ping MySQL to keep connection alive"); sLog.outDetail("Ping MySQL to keep connection alive");
loginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1"); LoginDatabase.Query("SELECT 1 FROM realmlist LIMIT 1");
} }
#ifdef WIN32 #ifdef WIN32
if (m_ServiceStatus == 0) stopEvent = true; if (m_ServiceStatus == 0) stopEvent = true;
@@ -300,8 +300,8 @@ extern int main(int argc, char **argv)
} }
///- Wait for the delay thread to exit ///- Wait for the delay thread to exit
loginDatabase.ThreadEnd(); LoginDatabase.ThreadEnd();
loginDatabase.HaltDelayThread(); LoginDatabase.HaltDelayThread();
///- Remove signal handling before leaving ///- Remove signal handling before leaving
UnhookSignals(); UnhookSignals();
@@ -334,19 +334,19 @@ void OnSignal(int s)
/// Initialize connection to the database /// Initialize connection to the database
bool StartDB() bool StartDB()
{ {
std::string dbstring = sConfig.GetStringDefault("loginDatabaseInfo", ""); std::string dbstring = sConfig.GetStringDefault("LoginDatabaseInfo", "");
if (dbstring.empty()) if (dbstring.empty())
{ {
sLog.outError("Database not specified"); sLog.outError("Database not specified");
return false; return false;
} }
if (!loginDatabase.Initialize(dbstring.c_str())) if (!LoginDatabase.Initialize(dbstring.c_str()))
{ {
sLog.outError("Cannot connect to database"); sLog.outError("Cannot connect to database");
return false; return false;
} }
loginDatabase.ThreadStart(); LoginDatabase.ThreadStart();
return true; return true;
} }
+2 -2
View File
@@ -27,7 +27,7 @@
#include "Database/DatabaseEnv.h" #include "Database/DatabaseEnv.h"
extern DatabaseType loginDatabase; extern DatabaseType LoginDatabase;
RealmList::RealmList() : m_UpdateInterval(0), m_NextUpdateTime(time(NULL)) RealmList::RealmList() : m_UpdateInterval(0), m_NextUpdateTime(time(NULL))
{ {
@@ -81,7 +81,7 @@ void RealmList::UpdateRealms(bool init)
{ {
sLog.outDetail("Updating Realm List..."); sLog.outDetail("Updating Realm List...");
QueryResult_AutoPtr result = loginDatabase.Query("SELECT id, name, address, port, icon, color, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE color <> 3 ORDER BY name"); QueryResult_AutoPtr result = LoginDatabase.Query("SELECT id, name, address, port, icon, color, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE color <> 3 ORDER BY name");
///- Circle through results and add them to the realm map ///- Circle through results and add them to the realm map
if (result) if (result)
+1 -17
View File
@@ -368,14 +368,6 @@
RelativePath="..\..\src\shared\Database\DatabaseImpl.h" RelativePath="..\..\src\shared\Database\DatabaseImpl.h"
> >
</File> </File>
<File
RelativePath="..\..\src\shared\Database\DatabaseMysql.cpp"
>
</File>
<File
RelativePath="..\..\src\shared\Database\DatabaseMysql.h"
>
</File>
<File <File
RelativePath="..\..\src\shared\Database\Field.cpp" RelativePath="..\..\src\shared\Database\Field.cpp"
> >
@@ -385,21 +377,13 @@
> >
</File> </File>
<File <File
RelativePath="..\..\src\shared\Database\MySQLDelayThread.h" RelativePath="..\..\src\shared\Database\QueryResult.cpp"
> >
</File> </File>
<File <File
RelativePath="..\..\src\shared\Database\QueryResult.h" RelativePath="..\..\src\shared\Database\QueryResult.h"
> >
</File> </File>
<File
RelativePath="..\..\src\shared\Database\QueryResultMysql.cpp"
>
</File>
<File
RelativePath="..\..\src\shared\Database\QueryResultMysql.h"
>
</File>
<File <File
RelativePath="..\..\src\shared\Database\SqlDelayThread.cpp" RelativePath="..\..\src\shared\Database\SqlDelayThread.cpp"
> >