database.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. int32 port=0;
  80. bool compression = false;
  81. bool items[6] = {false, false, false, false, false, false};
  82. if(!ReadDBINI(host, user, passwd, database, port, compression, items)) {
  83. //exit(1);
  84. return false;
  85. }
  86. if (!items[0] || !items[1] || !items[2] || !items[3])
  87. {
  88. LogWrite(DATABASE__ERROR, 0, "DB", "Incomplete DB.INI file.");
  89. LogWrite(DATABASE__ERROR, 0, "DB", "Read README.TXT!");
  90. //exit (1);
  91. return false;
  92. }
  93. int32 errnum = 0;
  94. char errbuf[MYSQL_ERRMSG_SIZE];
  95. if (!Open(host, user, passwd, database,port, &errnum, errbuf))
  96. {
  97. LogWrite(DATABASE__ERROR, 0, "DB", "Failed to connect to database: Error: %s", errbuf);
  98. HandleMysqlError(errnum);
  99. //exit(1);
  100. return false;
  101. }
  102. else
  103. {
  104. if (!silentLoad)
  105. LogWrite(DATABASE__INFO, 0, "DB", "Using database '%s' at %s", database, host);
  106. }
  107. return true;
  108. }
  109. map<int16, int16> Database::GetVersions(){
  110. map<int16, int16> opcodes;
  111. Query query;
  112. MYSQL_ROW row;
  113. MYSQL_RES* result = query.RunQuery2(Q_SELECT, "select distinct version_range1, version_range2 from opcodes");
  114. while(result && (row = mysql_fetch_row(result))){
  115. if(row[0] && row[1])
  116. opcodes[atoi(row[0])] = atoi(row[1]);
  117. }
  118. return opcodes;
  119. }
  120. map<string, uint16> Database::GetOpcodes(int16 version){
  121. map<string, uint16> opcodes;
  122. Query query;
  123. MYSQL_ROW row;
  124. 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);
  125. while(result && (row = mysql_fetch_row(result))){
  126. opcodes[row[0]] = atoi(row[1]);
  127. }
  128. return opcodes;
  129. }
  130. void Database::HandleMysqlError(int32 errnum) {
  131. switch(errnum) {
  132. case 0:
  133. break;
  134. case 1045: // Access Denied
  135. case 2001: {
  136. AddEQEMuError(EQEMuError_Mysql_1405, true);
  137. break;
  138. }
  139. case 2003: { // Unable to connect
  140. AddEQEMuError(EQEMuError_Mysql_2003, true);
  141. break;
  142. }
  143. case 2005: { // Unable to connect
  144. AddEQEMuError(EQEMuError_Mysql_2005, true);
  145. break;
  146. }
  147. case 2007: { // Unable to connect
  148. AddEQEMuError(EQEMuError_Mysql_2007, true);
  149. break;
  150. }
  151. }
  152. }
  153. void Database::InitVars() {
  154. }
  155. Database::~Database()
  156. {
  157. #ifdef WORLD
  158. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  159. activeQuerySessions.clear();
  160. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  161. DBAsyncMutex.writelock();
  162. continueAsync = false;
  163. map<int32, deque<Query*>>::iterator itr;
  164. for (itr = asyncQueries.begin(); itr != asyncQueries.end(); itr++)
  165. {
  166. asyncQueriesMutex[itr->first]->writelock();
  167. deque<Query*> queries = itr->second;
  168. while (queries.size() > 0)
  169. {
  170. Query* cur = queries.front();
  171. queries.pop_front();
  172. safe_delete(cur);
  173. }
  174. asyncQueriesMutex[itr->first]->releasewritelock();
  175. Mutex* mutex = asyncQueriesMutex[itr->first];
  176. asyncQueriesMutex.erase(itr->first);
  177. safe_delete(mutex);
  178. }
  179. asyncQueries.clear();
  180. asyncQueriesMutex.clear();
  181. DBAsyncMutex.releasewritelock();
  182. PurgeDBInstances();
  183. #endif
  184. }
  185. #ifdef WORLD
  186. void Query::AddQueryAsync(int32 queryID, Database* db, QUERY_TYPE type, const char* format, ...) {
  187. in_type = type;
  188. va_list args;
  189. va_start(args, format);
  190. #ifdef WIN32
  191. char* buffer;
  192. int buf_len = _vscprintf(format, args) + 1;
  193. buffer = new char[buf_len];
  194. vsprintf(buffer, format, args);
  195. #else
  196. char* buffer;
  197. int buf_len;
  198. va_list argcopy;
  199. va_copy(argcopy, args);
  200. buf_len = vsnprintf(NULL, 0, format, argcopy) + 1;
  201. va_end(argcopy);
  202. buffer = new char[buf_len];
  203. vsnprintf(buffer, buf_len, format, args);
  204. #endif
  205. va_end(args);
  206. query = string(buffer);
  207. Query* asyncQuery = new Query(this, queryID);
  208. safe_delete_array(buffer);
  209. db->AddAsyncQuery(asyncQuery);
  210. }
  211. void Query::RunQueryAsync(Database* db) {
  212. db->RunQuery(query.c_str(), query.length(), errbuf, &result, affected_rows, last_insert_id, &errnum, retry);
  213. }
  214. #endif
  215. MYSQL_RES* Query::RunQuery2(QUERY_TYPE type, const char* format, ...){
  216. va_list args;
  217. va_start( args, format );
  218. #ifdef WIN32
  219. char * buffer;
  220. int buf_len = _vscprintf( format, args ) + 1;
  221. buffer = new char[buf_len];
  222. vsprintf( buffer, format, args );
  223. #else
  224. char* buffer;
  225. int buf_len;
  226. va_list argcopy;
  227. va_copy(argcopy, args);
  228. buf_len = vsnprintf(NULL, 0, format, argcopy) + 1;
  229. va_end(argcopy);
  230. buffer = new char[buf_len];
  231. vsnprintf(buffer, buf_len, format, args);
  232. #endif
  233. va_end(args);
  234. query = string(buffer);
  235. safe_delete_array( buffer );
  236. return RunQuery2(query.c_str(), type);
  237. }
  238. MYSQL_RES* Query::RunQuery2(string in_query, QUERY_TYPE type){
  239. switch(type){
  240. case Q_SELECT:
  241. break;
  242. case Q_DBMS:
  243. case Q_REPLACE:
  244. case Q_DELETE:
  245. case Q_UPDATE:
  246. safe_delete(affected_rows);
  247. affected_rows = new int32;
  248. break;
  249. case Q_INSERT:
  250. safe_delete(last_insert_id);
  251. last_insert_id = new int32;
  252. }
  253. if(result){
  254. if(!multiple_results)
  255. multiple_results = new vector<MYSQL_RES*>();
  256. multiple_results->push_back(result);
  257. }
  258. query = in_query;
  259. #if defined WORLD && defined _DEBUG
  260. if (type == Q_UPDATE || type == Q_INSERT || type == Q_DELETE || type == Q_REPLACE)
  261. {
  262. char* filteredTables[] = { " characters", " character_", " `character_", " statistics", " variables", " char_colors", " `guild", " bugs" };
  263. bool match = false;
  264. for (int i = 0; i < sizeof(filteredTables) / sizeof(filteredTables[0]); i++)
  265. {
  266. if (query.find(filteredTables[i]) != std::string::npos) {
  267. match = true;
  268. }
  269. }
  270. try
  271. {
  272. if (!match)
  273. {
  274. FILE* pFile;
  275. pFile = fopen("sql_updates.sql", "a+");
  276. fwrite(query.c_str(), 1, query.length(), pFile);
  277. fwrite(";", sizeof(char), 1, pFile);
  278. fwrite("\n", sizeof(char), 1, pFile);
  279. fclose(pFile);
  280. }
  281. }
  282. catch (...) {}
  283. }
  284. #endif
  285. database.RunQuery(query.c_str(), query.length(), errbuf, &result, affected_rows, last_insert_id, &errnum, retry);
  286. return result;
  287. }
  288. #ifdef WORLD
  289. void Database::RunAsyncQueries(int32 queryid)
  290. {
  291. Database* asyncdb = FindFreeInstance();
  292. DBAsyncMutex.writelock();
  293. map<int32, deque<Query*>>::iterator itr = asyncQueries.find(queryid);
  294. if (itr == asyncQueries.end())
  295. {
  296. DBAsyncMutex.releasewritelock();
  297. return;
  298. }
  299. asyncQueriesMutex[queryid]->writelock();
  300. deque<Query*> queries;
  301. while (itr->second.size())
  302. {
  303. Query* cur = itr->second.front();
  304. queries.push_back(cur);
  305. itr->second.pop_front();
  306. }
  307. itr->second.clear();
  308. asyncQueries.erase(itr);
  309. DBAsyncMutex.releasewritelock();
  310. int32 count = 0;
  311. while (queries.size() > 0)
  312. {
  313. Query* cur = queries.front();
  314. cur->RunQueryAsync(asyncdb);
  315. this->RemoveActiveQuery(cur);
  316. queries.pop_front();
  317. safe_delete(cur);
  318. }
  319. FreeDBInstance(asyncdb);
  320. asyncQueriesMutex[queryid]->releasewritelock();
  321. }
  322. void Database::AddAsyncQuery(Query* query)
  323. {
  324. DBAsyncMutex.writelock();
  325. map<int32, Mutex*>::iterator mutexItr = asyncQueriesMutex.find(query->GetQueryID());
  326. if (mutexItr == asyncQueriesMutex.end())
  327. {
  328. Mutex* queryMutex = new Mutex();
  329. queryMutex->SetName("AsyncQuery" + query->GetQueryID());
  330. asyncQueriesMutex.insert(make_pair(query->GetQueryID(), queryMutex));
  331. }
  332. map<int32, deque<Query*>>::iterator itr = asyncQueries.find(query->GetQueryID());
  333. asyncQueriesMutex[query->GetQueryID()]->writelock();
  334. if ( itr != asyncQueries.end())
  335. itr->second.push_back(query);
  336. else
  337. {
  338. deque<Query*> queue;
  339. queue.push_back(query);
  340. asyncQueries.insert(make_pair(query->GetQueryID(), queue));
  341. }
  342. AddActiveQuery(query);
  343. asyncQueriesMutex[query->GetQueryID()]->releasewritelock();
  344. DBAsyncMutex.releasewritelock();
  345. bool isActive = IsActiveQuery(query->GetQueryID(), query);
  346. if (!isActive)
  347. {
  348. continueAsync = true;
  349. DBStruct* tmp = new DBStruct;
  350. tmp->queryid = query->GetQueryID();
  351. #ifdef WIN32
  352. _beginthread(DBAsyncQueries, 0, (void*)tmp);
  353. #else
  354. pthread_create(&t1, NULL, DBAsyncQueries, (void*)tmp);
  355. pthread_detach(t1);
  356. #endif
  357. }
  358. }
  359. Database* Database::FindFreeInstance()
  360. {
  361. Database* db_inst = 0;
  362. map<Database*, bool>::iterator itr;
  363. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  364. for (itr = dbInstances.begin(); itr != dbInstances.end(); itr++) {
  365. if (!itr->second)
  366. {
  367. db_inst = itr->first;
  368. itr->second = true;
  369. break;
  370. }
  371. }
  372. if (!db_inst)
  373. {
  374. WorldDatabase* tmp = new WorldDatabase();
  375. db_inst = (Database*)tmp;
  376. tmp->Init();
  377. tmp->ConnectNewDatabase();
  378. dbInstances.insert(make_pair(db_inst, true));
  379. }
  380. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  381. return db_inst;
  382. }
  383. void Database::PurgeDBInstances()
  384. {
  385. map<Database*, bool>::iterator itr;
  386. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  387. for (itr = dbInstances.begin(); itr != dbInstances.end(); itr++) {
  388. Database* tmpInst = itr->first;
  389. safe_delete(tmpInst);
  390. }
  391. dbInstances.clear();
  392. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  393. }
  394. void Database::FreeDBInstance(Database* cur)
  395. {
  396. DBInstanceMutex.writelock(__FUNCTION__, __LINE__);
  397. dbInstances[cur] = false;
  398. DBInstanceMutex.releasewritelock(__FUNCTION__, __LINE__);
  399. }
  400. void Database::RemoveActiveQuery(Query* query)
  401. {
  402. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  403. vector<Query*>::iterator itr;
  404. for (itr = activeQuerySessions.begin(); itr != activeQuerySessions.end(); itr++)
  405. {
  406. Query* curQuery = *itr;
  407. if (query == curQuery)
  408. {
  409. activeQuerySessions.erase(itr);
  410. break;
  411. }
  412. }
  413. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  414. }
  415. void Database::AddActiveQuery(Query* query)
  416. {
  417. DBQueryMutex.writelock(__FUNCTION__, __LINE__);
  418. activeQuerySessions.push_back(query);
  419. DBQueryMutex.releasewritelock(__FUNCTION__, __LINE__);
  420. }
  421. bool Database::IsActiveQuery(int32 id, Query* skip)
  422. {
  423. bool isActive = false;
  424. DBQueryMutex.readlock(__FUNCTION__, __LINE__);
  425. vector<Query*>::iterator itr;
  426. for (itr = activeQuerySessions.begin(); itr != activeQuerySessions.end(); itr++)
  427. {
  428. Query* query = *itr;
  429. if (query == skip)
  430. continue;
  431. if (query->GetQueryID() == id)
  432. {
  433. isActive = true;
  434. break;
  435. }
  436. }
  437. DBQueryMutex.releasereadlock(__FUNCTION__, __LINE__);
  438. return isActive;
  439. }
  440. #endif