database.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "../common/debug.h"
  17. #include <iostream>
  18. using namespace std;
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <errmsg.h>
  23. //#include <mysqld_error.h>
  24. #include <limits.h>
  25. #include <ctype.h>
  26. #include <assert.h>
  27. #include <map>
  28. // Disgrace: for windows compile
  29. #ifdef WIN32
  30. #include <WinSock2.h>
  31. #include <windows.h>
  32. #define snprintf _snprintf
  33. #define strncasecmp _strnicmp
  34. #define strcasecmp _stricmp
  35. #else
  36. #include "unix.h"
  37. #include <netinet/in.h>
  38. #endif
  39. #include "database.h"
  40. #include "EQStream.h"
  41. #include "packet_functions.h"
  42. #include "emu_opcodes.h"
  43. #ifdef WORLD
  44. #include "../WorldServer/WorldDatabase.h"
  45. extern WorldDatabase database;
  46. #endif
  47. #ifdef LOGIN
  48. #include "../LoginServer/LoginDatabase.h"
  49. extern LoginDatabase database;
  50. #endif
  51. #ifdef PARSER
  52. #include "../PacketParser/ParserDatabase.h"
  53. extern ParserDatabase database;
  54. #endif
  55. #ifdef PATCHER
  56. #include "../PatchServer/PatcherDatabase.h"
  57. extern PatcherDatabase database;
  58. #endif
  59. #include "../common/EQEMuError.h"
  60. #include "../common/packet_dump.h"
  61. #include "../common/Log.h"
  62. #ifdef WORLD
  63. ThreadReturnType DBAsyncQueries(void* str)
  64. {
  65. // allow some buffer for multiple queries to collect
  66. Sleep(10);
  67. DBStruct* data = (DBStruct*)str;
  68. database.RunAsyncQueries(data->queryid);
  69. delete data;
  70. THREAD_RETURN(NULL);
  71. }
  72. #endif
  73. Database::Database()
  74. {
  75. InitVars();
  76. }
  77. bool Database::Init(bool silentLoad) {
  78. char host[200], user[200], passwd[200], database[200];
  79. unsigned int port=0;
  80. bool compression = false;
  81. bool items[6] = {false, false, false, false, false, false};
  82. const char* exampleIni[] = { "[Database]", "host = localhost", "user = root", "password = pass", "database = dbname", "### --- Assure each parameter is on a new line!" };
  83. if(!ReadDBINI(host, user, passwd, database, &port, &compression, items)) {
  84. //exit(1);
  85. return false;
  86. }
  87. if (!items[0] || !items[1] || !items[2] || !items[3])
  88. {
  89. LogWrite(DATABASE__ERROR, 0, "DB", "Database file %s is incomplete.", DB_INI_FILE);
  90. int i;
  91. for (i = 0; i < 4; i++)
  92. {
  93. if ( !items[i] )
  94. LogWrite(DATABASE__ERROR, 0, "DB", "Could not find parameter %s", exampleIni[i+1]); // offset by 1 because the [Database] entry
  95. }
  96. LogWrite(DATABASE__ERROR, 0, "DB", "Example File:");
  97. int length = sizeof exampleIni / sizeof exampleIni[0];
  98. for(i=0;i<length;i++)
  99. LogWrite(DATABASE__ERROR, 0, "DB", "%s", exampleIni[i]);
  100. //exit (1);
  101. return false;
  102. }
  103. int32 errnum = 0;
  104. char errbuf[MYSQL_ERRMSG_SIZE];
  105. if (!Open(host, user, passwd, database,port, &errnum, errbuf))
  106. {
  107. LogWrite(DATABASE__ERROR, 0, "DB", "Failed to connect to database: Error: %s", errbuf);
  108. HandleMysqlError(errnum);
  109. //exit(1);
  110. return false;
  111. }
  112. else
  113. {
  114. if (!silentLoad)
  115. LogWrite(DATABASE__INFO, 0, "DB", "Using database '%s' at %s", database, host);
  116. }
  117. return true;
  118. }
  119. map<int16, int16> Database::GetVersions(){
  120. map<int16, int16> opcodes;
  121. Query query;
  122. MYSQL_ROW row;
  123. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "select distinct version_range1, version_range2 from opcodes");
  124. while(result && (row = mysql_fetch_row(result))){
  125. if(row[0] && row[1])
  126. opcodes[atoi(row[0])] = atoi(row[1]);
  127. }
  128. return opcodes;
  129. }
  130. map<string, uint16> Database::GetOpcodes(int16 version){
  131. map<string, uint16> opcodes;
  132. Query query;
  133. MYSQL_ROW row;
  134. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "select name, opcode from opcodes where %i between version_range1 and version_range2 order by version_range1, id", version);
  135. while(result && (row = mysql_fetch_row(result))){
  136. opcodes[row[0]] = atoi(row[1]);
  137. }
  138. return opcodes;
  139. }
  140. int32 Database::AuthenticateWebUser(char* userName, char* passwd, int32* status){
  141. if(status) {
  142. *status = 0;
  143. }
  144. Query query;
  145. MYSQL_ROW row;
  146. int32 id = 0;
  147. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "select id, status from web_users where username='%s' and passwd = sha2('%s', 512)", getSafeEscapeString(userName).c_str(), getSafeEscapeString(passwd).c_str());
  148. if(result && (row = mysql_fetch_row(result))){
  149. id = atoul(row[0]);
  150. if(status) {
  151. *status = atoul(row[1]);
  152. }
  153. }
  154. return id;
  155. }
  156. int32 Database::NoAuthRoute(char* route){
  157. Query query;
  158. MYSQL_ROW row;
  159. int32 status = 0xFFFFFFFF;
  160. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "select status from web_routes where route='%s'", getSafeEscapeString(route).c_str());
  161. if(result && (row = mysql_fetch_row(result))){
  162. status = atoul(row[0]);
  163. }
  164. return status;
  165. }
  166. void Database::HandleMysqlError(int32 errnum) {
  167. switch(errnum) {
  168. case 0:
  169. break;
  170. case 1045: // Access Denied
  171. case 2001: {
  172. AddEQEMuError(EQEMuError_Mysql_1405, true);
  173. break;
  174. }
  175. case 2003: { // Unable to connect
  176. AddEQEMuError(EQEMuError_Mysql_2003, true);
  177. break;
  178. }
  179. case 2005: { // Unable to connect
  180. AddEQEMuError(EQEMuError_Mysql_2005, true);
  181. break;
  182. }
  183. case 2007: { // Unable to connect
  184. AddEQEMuError(EQEMuError_Mysql_2007, true);
  185. break;
  186. }
  187. }
  188. }
  189. void Database::InitVars() {
  190. }
  191. Database::~Database()
  192. {
  193. #ifdef WORLD
  194. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  195. activeQuerySessions.clear();
  196. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  197. DBAsyncMutex.writelock();
  198. continueAsync = false;
  199. map<int32, deque<Query*>>::iterator itr;
  200. for (itr = asyncQueries.begin(); itr != asyncQueries.end(); itr++)
  201. {
  202. asyncQueriesMutex[itr->first]->writelock();
  203. deque<Query*> queries = itr->second;
  204. while (queries.size() > 0)
  205. {
  206. Query* cur = queries.front();
  207. queries.pop_front();
  208. safe_delete(cur);
  209. }
  210. asyncQueriesMutex[itr->first]->releasewritelock();
  211. Mutex* mutex = asyncQueriesMutex[itr->first];
  212. asyncQueriesMutex.erase(itr->first);
  213. safe_delete(mutex);
  214. }
  215. asyncQueries.clear();
  216. asyncQueriesMutex.clear();
  217. DBAsyncMutex.releasewritelock();
  218. PurgeDBInstances();
  219. #endif
  220. }
  221. #ifdef WORLD
  222. void Query::AddQueryAsync(int32 queryID, Database* db, QUERY_TYPE type, const char* format, ...) {
  223. in_type = type;
  224. va_list args;
  225. va_start(args, format);
  226. #ifdef WIN32
  227. char* buffer;
  228. int buf_len = _vscprintf(format, args) + 1;
  229. buffer = new char[buf_len];
  230. vsprintf(buffer, format, args);
  231. #else
  232. char* buffer;
  233. int buf_len;
  234. va_list argcopy;
  235. va_copy(argcopy, args);
  236. buf_len = vsnprintf(NULL, 0, format, argcopy) + 1;
  237. va_end(argcopy);
  238. buffer = new char[buf_len];
  239. vsnprintf(buffer, buf_len, format, args);
  240. #endif
  241. va_end(args);
  242. query = string(buffer);
  243. Query* asyncQuery = new Query(this, queryID);
  244. safe_delete_array(buffer);
  245. db->AddAsyncQuery(asyncQuery);
  246. }
  247. void Query::RunQueryAsync(Database* db) {
  248. db->RunQuery(query.c_str(), query.length(), errbuf, &result, affected_rows, last_insert_id, &errnum, retry);
  249. }
  250. #endif
  251. MYSQL_RES* Query::RunQuery2(QUERY_TYPE type, const char* format, ...){
  252. va_list args;
  253. va_start( args, format );
  254. #ifdef WIN32
  255. char * buffer;
  256. int buf_len = _vscprintf( format, args ) + 1;
  257. buffer = new char[buf_len];
  258. vsprintf( buffer, format, args );
  259. #else
  260. char* buffer;
  261. int buf_len;
  262. va_list argcopy;
  263. va_copy(argcopy, args);
  264. buf_len = vsnprintf(NULL, 0, format, argcopy) + 1;
  265. va_end(argcopy);
  266. buffer = new char[buf_len];
  267. vsnprintf(buffer, buf_len, format, args);
  268. #endif
  269. va_end(args);
  270. query = string(buffer);
  271. safe_delete_array( buffer );
  272. return RunQuery2(query.c_str(), type);
  273. }
  274. MYSQL_RES* Query::RunQuery2(string in_query, QUERY_TYPE type){
  275. switch(type){
  276. case Q_SELECT:
  277. break;
  278. case Q_DBMS:
  279. case Q_REPLACE:
  280. case Q_DELETE:
  281. case Q_UPDATE:
  282. safe_delete(affected_rows);
  283. affected_rows = new int32;
  284. break;
  285. case Q_INSERT:
  286. safe_delete(last_insert_id);
  287. last_insert_id = new int32;
  288. }
  289. if(result){
  290. if(!multiple_results)
  291. multiple_results = new vector<MYSQL_RES*>();
  292. multiple_results->push_back(result);
  293. }
  294. query = in_query;
  295. #if defined WORLD && defined _DEBUG
  296. if (type == Q_UPDATE || type == Q_INSERT || type == Q_DELETE || type == Q_REPLACE)
  297. {
  298. char* filteredTables[] = { " characters", " character_", " `character_", " statistics", " variables", " char_colors", " `guild", " bugs" };
  299. bool match = false;
  300. for (int i = 0; i < sizeof(filteredTables) / sizeof(filteredTables[0]); i++)
  301. {
  302. if (query.find(filteredTables[i]) != std::string::npos) {
  303. match = true;
  304. break;
  305. }
  306. }
  307. try
  308. {
  309. if (!match)
  310. {
  311. FILE* pFile;
  312. pFile = fopen("sql_updates.sql", "a+");
  313. fwrite(query.c_str(), 1, query.length(), pFile);
  314. fwrite(";", sizeof(char), 1, pFile);
  315. fwrite("\n", sizeof(char), 1, pFile);
  316. fclose(pFile);
  317. }
  318. }
  319. catch (...) {}
  320. }
  321. #endif
  322. database.RunQuery(query.c_str(), query.length(), errbuf, &result, affected_rows, last_insert_id, &errnum, retry);
  323. return result;
  324. }
  325. #ifdef WORLD
  326. void Database::RunAsyncQueries(int32 queryid)
  327. {
  328. Database* asyncdb = FindFreeInstance();
  329. DBAsyncMutex.writelock();
  330. map<int32, deque<Query*>>::iterator itr = asyncQueries.find(queryid);
  331. if (itr == asyncQueries.end())
  332. {
  333. DBAsyncMutex.releasewritelock();
  334. return;
  335. }
  336. asyncQueriesMutex[queryid]->writelock();
  337. deque<Query*> queries;
  338. while (itr->second.size())
  339. {
  340. Query* cur = itr->second.front();
  341. queries.push_back(cur);
  342. itr->second.pop_front();
  343. }
  344. itr->second.clear();
  345. asyncQueries.erase(itr);
  346. DBAsyncMutex.releasewritelock();
  347. asyncQueriesMutex[queryid]->releasewritelock();
  348. int32 count = 0;
  349. while (queries.size() > 0)
  350. {
  351. Query* cur = queries.front();
  352. cur->RunQueryAsync(asyncdb);
  353. this->RemoveActiveQuery(cur);
  354. queries.pop_front();
  355. safe_delete(cur);
  356. }
  357. FreeDBInstance(asyncdb);
  358. bool isActive = IsActiveQuery(queryid);
  359. if (isActive)
  360. {
  361. continueAsync = true;
  362. DBStruct* tmp = new DBStruct;
  363. tmp->queryid = queryid;
  364. #ifdef WIN32
  365. _beginthread(DBAsyncQueries, 0, (void*)tmp);
  366. #else
  367. pthread_t t1;
  368. pthread_create(&t1, NULL, DBAsyncQueries, (void*)tmp);
  369. pthread_detach(t1);
  370. #endif
  371. }
  372. }
  373. void Database::AddAsyncQuery(Query* query)
  374. {
  375. DBAsyncMutex.writelock();
  376. map<int32, Mutex*>::iterator mutexItr = asyncQueriesMutex.find(query->GetQueryID());
  377. if (mutexItr == asyncQueriesMutex.end())
  378. {
  379. Mutex* queryMutex = new Mutex();
  380. queryMutex->SetName("AsyncQuery" + query->GetQueryID());
  381. asyncQueriesMutex.insert(make_pair(query->GetQueryID(), queryMutex));
  382. }
  383. map<int32, deque<Query*>>::iterator itr = asyncQueries.find(query->GetQueryID());
  384. asyncQueriesMutex[query->GetQueryID()]->writelock();
  385. if ( itr != asyncQueries.end())
  386. itr->second.push_back(query);
  387. else
  388. {
  389. deque<Query*> queue;
  390. queue.push_back(query);
  391. asyncQueries.insert(make_pair(query->GetQueryID(), queue));
  392. }
  393. AddActiveQuery(query);
  394. asyncQueriesMutex[query->GetQueryID()]->releasewritelock();
  395. DBAsyncMutex.releasewritelock();
  396. bool isActive = IsActiveQuery(query->GetQueryID(), query);
  397. if (!isActive)
  398. {
  399. continueAsync = true;
  400. DBStruct* tmp = new DBStruct;
  401. tmp->queryid = query->GetQueryID();
  402. #ifdef WIN32
  403. _beginthread(DBAsyncQueries, 0, (void*)tmp);
  404. #else
  405. pthread_t t1;
  406. pthread_create(&t1, NULL, DBAsyncQueries, (void*)tmp);
  407. pthread_detach(t1);
  408. #endif
  409. }
  410. }
  411. Database* Database::FindFreeInstance()
  412. {
  413. Database* db_inst = 0;
  414. map<Database*, bool>::iterator itr;
  415. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  416. for (itr = dbInstances.begin(); itr != dbInstances.end(); itr++) {
  417. if (!itr->second)
  418. {
  419. db_inst = itr->first;
  420. itr->second = true;
  421. break;
  422. }
  423. }
  424. if (!db_inst)
  425. {
  426. WorldDatabase* tmp = new WorldDatabase();
  427. db_inst = (Database*)tmp;
  428. tmp->Init();
  429. tmp->ConnectNewDatabase();
  430. dbInstances.insert(make_pair(db_inst, true));
  431. }
  432. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  433. return db_inst;
  434. }
  435. void Database::PurgeDBInstances()
  436. {
  437. map<Database*, bool>::iterator itr;
  438. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  439. for (itr = dbInstances.begin(); itr != dbInstances.end(); itr++) {
  440. WorldDatabase* tmpInst = (WorldDatabase*)itr->first;
  441. safe_delete(tmpInst);
  442. }
  443. dbInstances.clear();
  444. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  445. }
  446. void Database::PingAsyncDatabase()
  447. {
  448. map<Database*, bool>::iterator itr;
  449. DBInstanceMutex.readlock(__FUNCTION__, __LINE__);
  450. for (itr = dbInstances.begin(); itr != dbInstances.end(); itr++) {
  451. Database* tmpInst = itr->first;
  452. tmpInst->ping();
  453. }
  454. DBInstanceMutex.releasereadlock(__FUNCTION__, __LINE__);
  455. }
  456. void Database::FreeDBInstance(Database* cur)
  457. {
  458. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  459. dbInstances[cur] = false;
  460. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  461. }
  462. void Database::RemoveActiveQuery(Query* query)
  463. {
  464. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  465. vector<Query*>::iterator itr;
  466. for (itr = activeQuerySessions.begin(); itr != activeQuerySessions.end(); itr++)
  467. {
  468. Query* curQuery = *itr;
  469. if (query == curQuery)
  470. {
  471. activeQuerySessions.erase(itr);
  472. break;
  473. }
  474. }
  475. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  476. }
  477. void Database::AddActiveQuery(Query* query)
  478. {
  479. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  480. activeQuerySessions.push_back(query);
  481. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  482. }
  483. bool Database::IsActiveQuery(int32 id, Query* skip)
  484. {
  485. bool isActive = false;
  486. DBQueryMutex.readlock(__FUNCTION__, __LINE__);
  487. vector<Query*>::iterator itr;
  488. for (itr = activeQuerySessions.begin(); itr != activeQuerySessions.end(); itr++)
  489. {
  490. Query* query = *itr;
  491. if (query == skip)
  492. continue;
  493. if (query->GetQueryID() == id)
  494. {
  495. isActive = true;
  496. break;
  497. }
  498. }
  499. DBQueryMutex.releasereadlock(__FUNCTION__, __LINE__);
  500. return isActive;
  501. }
  502. #endif