9
3

LoginServer.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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 "../common/Log.h"
  18. #include <iostream>
  19. using namespace std;
  20. #include <string.h>
  21. #include <stdio.h>
  22. #include <iomanip>
  23. using namespace std;
  24. #include <stdlib.h>
  25. #include "../common/version.h"
  26. #include "../common/GlobalHeaders.h"
  27. #include "../common/sha512.h"
  28. #ifdef WIN32
  29. #include <process.h>
  30. #include <WinSock2.h>
  31. #include <Ws2tcpip.h>
  32. #include <windows.h>
  33. #define strncasecmp _strnicmp
  34. #define strcasecmp _stricmp
  35. #else // Pyro: fix for linux
  36. #include <sys/socket.h>
  37. #ifdef FREEBSD //Timothy Whitman - January 7, 2003
  38. #include <sys/types.h>
  39. #endif
  40. #include <netinet/in.h>
  41. #include <arpa/inet.h>
  42. #include <pthread.h>
  43. #include <unistd.h>
  44. #include <errno.h>
  45. #include "../common/unix.h"
  46. #define SOCKET_ERROR -1
  47. #define INVALID_SOCKET -1
  48. extern int errno;
  49. #endif
  50. #include "../common/servertalk.h"
  51. #include "LoginServer.h"
  52. #include "../common/packet_dump.h"
  53. #include "net.h"
  54. #include "zoneserver.h"
  55. #include "WorldDatabase.h"
  56. #include "Variables.h"
  57. #include "World.h"
  58. #include "../common/ConfigReader.h"
  59. #include "Rules/Rules.h"
  60. extern sint32 numzones;
  61. extern sint32 numclients;
  62. extern NetConnection net;
  63. extern LoginServer loginserver;
  64. extern WorldDatabase database;
  65. extern ZoneAuth zone_auth;
  66. extern Variables variables;
  67. extern ZoneList zone_list;
  68. extern ClientList client_list;
  69. extern volatile bool RunLoops;
  70. volatile bool LoginLoopRunning = false;
  71. extern ConfigReader configReader;
  72. extern RuleManager rule_manager;
  73. bool AttemptingConnect = false;
  74. LoginServer::LoginServer(const char* iAddress, int16 iPort) {
  75. LoginServerIP = ResolveIP(iAddress);
  76. LoginServerPort = iPort;
  77. statusupdate_timer = new Timer(LoginServer_StatusUpdateInterval);
  78. tcpc = new TCPConnection(false);
  79. pTryReconnect = true;
  80. try_auto_update = true;
  81. updates_always = false;
  82. updates_verbose = false;
  83. updates_auto_data = false;
  84. updates_ask = false;
  85. minLockedStatus = 100;
  86. maxPlayers = -1;
  87. minGameFullStatus = 100;
  88. update_server_verified = false;
  89. last_checked_time = 0;
  90. UpdateServerPort = 0;
  91. UpdateServerIP = 0;
  92. update_server_completed = false;
  93. data_waiting = 0;
  94. zone_updates = 0;
  95. loginEquip_updates = 0;
  96. }
  97. LoginServer::~LoginServer() {
  98. delete statusupdate_timer;
  99. delete tcpc;
  100. }
  101. void LoginServer::SendImmediateEquipmentUpdatesForChar(int32 char_id) {
  102. LogWrite(WORLD__DEBUG, 5, "World", "Sending login equipment updates for char_id: %u", char_id);
  103. int16 count = 0;
  104. if(!loginEquip_updates)
  105. loginEquip_updates = database.GetEquipmentUpdates(char_id);
  106. if(loginEquip_updates && loginEquip_updates->size() > 0)
  107. {
  108. map<int32, LoginEquipmentUpdate> send_map;
  109. int32 size = 0;
  110. MutexMap<int32, LoginEquipmentUpdate>::iterator itr = loginEquip_updates->begin();
  111. while(itr.Next())
  112. {
  113. send_map[itr->first] = itr->second;
  114. size += sizeof(EquipmentUpdate_Struct);
  115. loginEquip_updates->erase(itr->first);
  116. count++;
  117. }
  118. ServerPacket* outpack = new ServerPacket(ServerOP_LoginEquipment, size + sizeof(EquipmentUpdateList_Struct)+5);
  119. EquipmentUpdateList_Struct* updates = (EquipmentUpdateList_Struct*)outpack->pBuffer;
  120. updates->total_updates = count;
  121. int32 pos = sizeof(EquipmentUpdateList_Struct);
  122. map<int32, LoginEquipmentUpdate>::iterator send_itr;
  123. for(send_itr = send_map.begin(); send_itr != send_map.end(); send_itr++)
  124. {
  125. EquipmentUpdate_Struct* update = (EquipmentUpdate_Struct*)(outpack->pBuffer + pos);
  126. update->id = send_itr->first;
  127. update->world_char_id = send_itr->second.world_char_id;
  128. update->equip_type = send_itr->second.equip_type;
  129. update->red = send_itr->second.red;
  130. update->green = send_itr->second.green;
  131. update->blue = send_itr->second.blue;
  132. update->highlight_red = send_itr->second.red;
  133. update->highlight_green = send_itr->second.green;
  134. update->highlight_blue = send_itr->second.blue;
  135. update->slot = send_itr->second.slot;
  136. pos += sizeof(EquipmentUpdate_Struct);
  137. }
  138. SendPacket(outpack);
  139. outpack->Deflate();
  140. safe_delete(outpack);
  141. }
  142. if(loginEquip_updates && count)
  143. loginEquip_updates->clear();
  144. if(loginEquip_updates && loginEquip_updates->size() == 0)
  145. {
  146. database.UpdateLoginEquipment();
  147. safe_delete(loginEquip_updates);
  148. }
  149. }
  150. bool LoginServer::Process() {
  151. if(last_checked_time > Timer::GetCurrentTime2())
  152. return true;
  153. last_checked_time = Timer::GetCurrentTime2() + 50;
  154. bool ret = true;
  155. if (statusupdate_timer->Check()) {
  156. this->SendStatus();
  157. }
  158. /************ Get all packets from packet manager out queue and process them ************/
  159. ServerPacket *pack = 0;
  160. while((pack = tcpc->PopPacket()))
  161. {
  162. switch(pack->opcode)
  163. {
  164. case ServerOP_LSFatalError:
  165. {
  166. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_LSFatalError", pack->opcode, pack->opcode);
  167. LogWrite(WORLD__ERROR, 0, "World", "Login Server returned a fatal error: %s\n", pack->pBuffer);
  168. tcpc->Disconnect();
  169. ret = false;
  170. net.ReadLoginINI();
  171. break;
  172. }
  173. case ServerOP_CharTimeStamp:
  174. {
  175. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_CharTimeStamp", pack->opcode, pack->opcode);
  176. if(pack->size != sizeof(CharacterTimeStamp_Struct))
  177. break;
  178. CharacterTimeStamp_Struct* cts = (CharacterTimeStamp_Struct*) pack->pBuffer;
  179. // determine if the character exists and retrieve its latest timestamp from the world server
  180. bool char_exist = false;
  181. //int32 character_timestamp = database.GetCharacterTimeStamp(cts->char_id,cts->account_id,&char_exist);
  182. if(!char_exist)
  183. {
  184. //Character doesn't exist, get rid of it
  185. SendDeleteCharacter ( cts );
  186. break;
  187. }
  188. break;
  189. }
  190. case ServerOP_GetTableData:{
  191. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_GetTableData", pack->opcode, pack->opcode);
  192. uchar* tmp = new uchar[pack->size];
  193. memcpy(tmp, pack->pBuffer, pack->size);
  194. data_updates_waiting.push_back(tmp);
  195. break;
  196. }
  197. case ServerOP_GetTableQuery:{
  198. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_GetTableQuery", pack->opcode, pack->opcode);
  199. uchar* tmp = new uchar[pack->size];
  200. memcpy(tmp, pack->pBuffer, pack->size);
  201. table_updates_waiting.push_back(tmp);
  202. break;
  203. }
  204. case ServerOP_GetLatestTables:{
  205. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_GetLatestTables", pack->opcode, pack->opcode);
  206. data_waiting = new uchar[pack->size];
  207. memcpy(data_waiting, pack->pBuffer, pack->size);
  208. break;
  209. }
  210. // Push Character Select "item appearances" to login_equipment table
  211. case ServerOP_LoginEquipment:{
  212. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_LoginEquipment", pack->opcode, pack->opcode);
  213. LogWrite(MISC__TODO, 0, "TODO", "Implement map<character id <map<slot id, updatestruct> > method to update Login.\n%s, %s, %i", __FILE__, __FUNCTION__, __LINE__);
  214. if( pack->size == sizeof(EquipmentUpdateRequest_Struct) )
  215. {
  216. int16 max = ((EquipmentUpdateRequest_Struct*)pack->pBuffer)->max_per_batch;
  217. int16 count = 0;
  218. if(!loginEquip_updates)
  219. loginEquip_updates = database.GetEquipmentUpdates();
  220. if(loginEquip_updates && loginEquip_updates->size() > 0)
  221. {
  222. map<int32, LoginEquipmentUpdate> send_map;
  223. int32 size = 0;
  224. MutexMap<int32, LoginEquipmentUpdate>::iterator itr = loginEquip_updates->begin();
  225. while(itr.Next() && count < max)
  226. {
  227. send_map[itr->first] = itr->second;
  228. size += sizeof(EquipmentUpdate_Struct);
  229. loginEquip_updates->erase(itr->first);
  230. count++;
  231. }
  232. ServerPacket* outpack = new ServerPacket(ServerOP_LoginEquipment, size + sizeof(EquipmentUpdateList_Struct)+5);
  233. EquipmentUpdateList_Struct* updates = (EquipmentUpdateList_Struct*)outpack->pBuffer;
  234. updates->total_updates = count;
  235. int32 pos = sizeof(EquipmentUpdateList_Struct);
  236. map<int32, LoginEquipmentUpdate>::iterator send_itr;
  237. for(send_itr = send_map.begin(); send_itr != send_map.end(); send_itr++)
  238. {
  239. EquipmentUpdate_Struct* update = (EquipmentUpdate_Struct*)(outpack->pBuffer + pos);
  240. update->id = send_itr->first;
  241. update->world_char_id = send_itr->second.world_char_id;
  242. update->equip_type = send_itr->second.equip_type;
  243. update->red = send_itr->second.red;
  244. update->green = send_itr->second.green;
  245. update->blue = send_itr->second.blue;
  246. update->highlight_red = send_itr->second.red;
  247. update->highlight_green = send_itr->second.green;
  248. update->highlight_blue = send_itr->second.blue;
  249. update->slot = send_itr->second.slot;
  250. pos += sizeof(EquipmentUpdate_Struct);
  251. }
  252. SendPacket(outpack);
  253. outpack->Deflate();
  254. safe_delete(outpack);
  255. }
  256. if(loginEquip_updates && count < max)
  257. loginEquip_updates->clear();
  258. if(loginEquip_updates && loginEquip_updates->size() == 0)
  259. {
  260. database.UpdateLoginEquipment();
  261. safe_delete(loginEquip_updates);
  262. }
  263. }
  264. break;
  265. }
  266. case ServerOP_ZoneUpdates:{
  267. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_ZoneUpdates", pack->opcode, pack->opcode);
  268. if(pack->size == sizeof(ZoneUpdateRequest_Struct)){
  269. int16 max = ((ZoneUpdateRequest_Struct*)pack->pBuffer)->max_per_batch;
  270. int16 count = 0;
  271. if(!zone_updates)
  272. zone_updates = database.GetZoneUpdates();
  273. if(zone_updates && zone_updates->size() > 0){
  274. map<int32, LoginZoneUpdate> send_map;
  275. int32 size = 0;
  276. MutexMap<int32, LoginZoneUpdate>::iterator itr = zone_updates->begin();
  277. while(itr.Next() && count < max){
  278. send_map[itr->first] = itr->second;
  279. size += sizeof(ZoneUpdate_Struct) + itr->second.name.length() + itr->second.description.length();
  280. zone_updates->erase(itr->first);
  281. count++;
  282. }
  283. ServerPacket* outpack = new ServerPacket(ServerOP_ZoneUpdates, size + sizeof(ZoneUpdateList_Struct)+5);
  284. ZoneUpdateList_Struct* updates = (ZoneUpdateList_Struct*)outpack->pBuffer;
  285. updates->total_updates = count;
  286. int32 pos = sizeof(ZoneUpdateList_Struct);
  287. map<int32, LoginZoneUpdate>::iterator send_itr;
  288. for(send_itr = send_map.begin(); send_itr != send_map.end(); send_itr++){
  289. ZoneUpdate_Struct* update = (ZoneUpdate_Struct*)(outpack->pBuffer + pos);
  290. update->zone_id = send_itr->first;
  291. update->zone_name_length = send_itr->second.name.length();
  292. update->zone_desc_length = send_itr->second.description.length();
  293. strcpy(update->data, send_itr->second.name.c_str());
  294. strcpy(update->data + send_itr->second.name.length(), send_itr->second.description.c_str());
  295. pos += sizeof(ZoneUpdate_Struct) + send_itr->second.name.length() + send_itr->second.description.length();
  296. }
  297. SendPacket(outpack);
  298. outpack->Deflate();
  299. safe_delete(outpack);
  300. }
  301. if(zone_updates && count < max)
  302. zone_updates->clear();
  303. if(zone_updates && zone_updates->size() == 0){
  304. database.UpdateLoginZones();
  305. safe_delete(zone_updates);
  306. }
  307. }
  308. break;
  309. }
  310. case ServerOP_CharacterCreate:{
  311. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_CharacterCreate", pack->opcode, pack->opcode);
  312. int16 version = 1;
  313. if(pack->pBuffer[0] > 0)
  314. memcpy(&version, pack->pBuffer, sizeof(int16));
  315. //DumpPacket(pack->pBuffer,pack->size);
  316. PacketStruct* packet = configReader.getStruct("CreateCharacter", version);
  317. int8 resp = 0;
  318. int32 acct_id = 0;
  319. int32 char_id = 0;
  320. if(packet && packet->LoadPacketData(pack->pBuffer+sizeof(int16),pack->size - sizeof(int16))){
  321. EQ2_16BitString name = packet->getType_EQ2_16BitString_ByName("name");
  322. resp = database.CheckNameFilter(name.data.c_str());
  323. acct_id = packet->getType_int32_ByName("account_id");
  324. LogWrite(WORLD__DEBUG, 0, "World", "Response: %i", (int)resp);
  325. sint16 lowestStatus = database.GetLowestCharacterAdminStatus(acct_id);
  326. if(lowestStatus == -2)
  327. resp = UNKNOWNERROR_REPLY2;
  328. else if(resp == CREATESUCCESS_REPLY)
  329. char_id = database.SaveCharacter(packet, acct_id);
  330. }
  331. else{
  332. LogWrite(WORLD__ERROR, 0, "World", "Invalid creation request!");
  333. resp = UNKNOWNERROR_REPLY;
  334. }
  335. // send name filter response data back to the login server
  336. SendFilterNameResponse ( resp , acct_id , char_id );
  337. safe_delete(packet);
  338. break;
  339. }
  340. case ServerOP_BasicCharUpdate: {
  341. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_BasicCharUpdate", pack->opcode, pack->opcode);
  342. if(pack->size != sizeof(CharDataUpdate_Struct))
  343. break;
  344. CharDataUpdate_Struct* cdu = (CharDataUpdate_Struct*) pack->pBuffer;
  345. switch(cdu->update_field)
  346. {
  347. case DELETE_UPDATE_FLAG:
  348. {
  349. LogWrite(WORLD__DEBUG, 0, "World", "Delete character request: %i %i",cdu->account_id,cdu->char_id );
  350. database.DeleteCharacter(cdu->account_id,cdu->char_id);
  351. break;
  352. }
  353. }
  354. break;
  355. }
  356. case ServerOP_UsertoWorldReq:{
  357. LogWrite(OPCODE__DEBUG, 0, "Opcode", "Opcode 0x%X (%i): ServerOP_UsertoWorldReq", pack->opcode, pack->opcode);
  358. UsertoWorldRequest_Struct* utwr = (UsertoWorldRequest_Struct*) pack->pBuffer;
  359. /*int32 id = database.GetAccountIDFromLSID(utwr->lsaccountid);
  360. sint16 status = database.CheckStatus(id);
  361. */
  362. int32 access_key = 0;
  363. // if it is a accepted login, we add the zone auth request
  364. access_key = DetermineCharacterLoginRequest ( utwr );
  365. if ( access_key != 0 )
  366. {
  367. zone_auth.PurgeInactiveAuth();
  368. char* characterName = database.GetCharacterName( utwr->char_id );
  369. if(characterName != 0){
  370. ZoneAuthRequest* zar = new ZoneAuthRequest(utwr->lsaccountid,characterName,access_key);
  371. zar->setFirstLogin ( true );
  372. zone_auth.AddAuth(zar);
  373. safe_delete_array(characterName);
  374. }
  375. }
  376. break;
  377. }
  378. case ServerOP_ResetDatabase:{
  379. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): ServerOP_ResetDatabase", pack->opcode, pack->opcode);
  380. database.ResetDatabase();
  381. break;
  382. }
  383. case UpdateServerOP_Verified:{
  384. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): UpdateServerOP_Verified", pack->opcode, pack->opcode);
  385. update_server_verified = true;
  386. break;
  387. }
  388. case UpdateServerOP_DisplayMsg:{
  389. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): UpdateServerOP_DisplayMsg", pack->opcode, pack->opcode);
  390. LogWrite(WORLD__WARNING, 0, "World", "\t%s", pack->pBuffer);
  391. break;
  392. }
  393. case UpdateServerOP_Completed:{
  394. LogWrite(OPCODE__DEBUG, 1, "Opcode", "Opcode 0x%X (%i): UpdateServerOP_Completed", pack->opcode, pack->opcode);
  395. update_server_completed = true;
  396. break;
  397. }
  398. default:
  399. {
  400. LogWrite(WORLD__ERROR, 0, "World", "Unhandled opcode: %i", pack->opcode);
  401. DumpPacket(pack);
  402. }
  403. }
  404. safe_delete(pack);
  405. // break out if ret is now false
  406. if (!ret)
  407. break;
  408. }
  409. return ret;
  410. }
  411. // this should always be called in a new thread
  412. #ifdef WIN32
  413. void AutoInitLoginServer(void *tmp) {
  414. #else
  415. void *AutoInitLoginServer(void *tmp) {
  416. #endif
  417. if (loginserver.GetState() == TCPS_Ready) {
  418. InitLoginServer();
  419. }
  420. #ifndef WIN32
  421. return 0;
  422. #endif
  423. }
  424. bool InitLoginServer() {
  425. if (loginserver.GetState() != TCPS_Ready) {
  426. LogWrite(WORLD__ERROR, 0, "World", "InitLoginServer() while already attempting connect.");
  427. return false;
  428. }
  429. if (!net.LoginServerInfo) {
  430. LogWrite(WORLD__ERROR, 0, "World", "Login server info not loaded.");
  431. return false;
  432. }
  433. AttemptingConnect = true;
  434. int16 port;
  435. char* address = net.GetLoginInfo(&port);
  436. loginserver.Connect(address, port);
  437. return true;
  438. }
  439. void LoginServer::InitLoginServerVariables()
  440. {
  441. minLockedStatus = rule_manager.GetGlobalRule(R_World, ServerLockedOverrideStatus)->GetSInt16();
  442. maxPlayers = rule_manager.GetGlobalRule(R_World, MaxPlayers)->GetSInt16();
  443. minGameFullStatus = rule_manager.GetGlobalRule(R_World, MaxPlayersOverrideStatus)->GetSInt16();
  444. }
  445. void LoginServer::ProcessDataUpdate(uchar* data){
  446. TableDataQuery data_query;
  447. TableQuery table_queries;
  448. data_query.DeSerialize(data);
  449. string query;
  450. for(int32 i=0;i<data_query.num_queries;i++)
  451. {
  452. query = string("replace into ").append(data_query.tablename).append(" ");
  453. query.append(data_query.columns).append(" values(").append(data_query.queries[i]->query).append(")\0");
  454. char* new_query = new char[query.length() + 1];
  455. memset(new_query, 0, query.length() + 1);
  456. memcpy(new_query, query.c_str(), query.length());
  457. table_queries.AddQuery(new_query);
  458. }
  459. strcpy(table_queries.tablename, data_query.tablename);
  460. table_queries.latest_version = data_query.version;
  461. string queries = table_queries.GetQueriesString();
  462. char answer = 0;
  463. if(UpdatesAsk() || UpdatesVerbose())
  464. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "Pending Queries:\n%s", queries.c_str());
  465. if(!UpdatesAuto() && UpdatesAsk())
  466. {
  467. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "Update to the latest data version? ([Y]es, [N]o, [A]ll)");
  468. cin >> answer;
  469. if(toupper(answer) == 'A')
  470. UpdatesAuto(true);
  471. }
  472. if(UpdatesAuto() || (answer && toupper(answer) == 'Y'))
  473. {
  474. bool success = database.RunDatabaseQueries(&table_queries, false, true);
  475. string table = string(data_query.tablename);
  476. if(table != last_data_update_table)
  477. {
  478. if(success)
  479. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "\tData Updated: '%s' = SUCCESS!", data_query.tablename);
  480. else
  481. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "Data Updated: '%s' = FAILED!", data_query.tablename);
  482. last_data_update_table = table;
  483. }
  484. }
  485. }
  486. void LoginServer::ProcessTableUpdate(uchar* data) {
  487. TableQuery table_query;
  488. table_query.DeSerialize(data);
  489. string queries = table_query.GetQueriesString();
  490. char answer = 0;
  491. if(UpdatesAsk() || UpdatesVerbose())
  492. {
  493. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "\tUpdate Found for '%s'!", table_query.tablename);
  494. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "\tNew Version: %i", table_query.latest_version);
  495. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "\tYour Version: %i", table_query.your_version);
  496. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "Pending Query:\n%s", queries.c_str());
  497. }
  498. if(!UpdatesAuto() && UpdatesAsk())
  499. {
  500. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "Update to the latest table version? ([Y]es, [N]o, [A]ll)");
  501. cin >> answer;
  502. if(toupper(answer) == 'A')
  503. UpdatesAuto(true);
  504. }
  505. if(UpdatesAuto() || (answer && toupper(answer) == 'Y'))
  506. {
  507. bool success = database.RunDatabaseQueries(&table_query, false);
  508. if(success)
  509. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "\tUpdate Table: '%s' = SUCCESS!", table_query.tablename);
  510. else
  511. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "Update Table: '%s' = FAILED!", table_query.tablename);
  512. }
  513. }
  514. int32 LoginServer::ProcessTableUpdates(uchar* data) {
  515. int32 ret = 0;
  516. /*LatestTableVersions table_versions;
  517. table_versions.DeSerialize(data);
  518. int32 total_tables = table_versions.GetTotalTables();
  519. int32 max_version = CURRENT_DATABASE_MAJORVERSION*100 + CURRENT_DATABASE_MINORVERSION;
  520. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Max Version: %i", max_version);
  521. vector<ServerPacket*> packet_requests;
  522. ServerPacket* outpack = 0;
  523. for(int32 i=0;i<total_tables;i++){
  524. float version = database.CheckTableVersions(table_versions.GetTable(i).name);
  525. if( (version < table_versions.GetTable(i).version) )
  526. {
  527. outpack = new ServerPacket(ServerOP_GetTableQuery, sizeof(TableVersion));
  528. TableVersion* out_version = (TableVersion*)outpack->pBuffer;
  529. strcpy(out_version->name, table_versions.GetTable(i).name);
  530. out_version->max_table_version = max_version;
  531. out_version->version = (int32)version;
  532. out_version->last = 0;
  533. packet_requests.push_back(outpack);
  534. ret++;
  535. }
  536. }
  537. if( ret )
  538. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Found Table Updates!");
  539. else
  540. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--No Table Updates, continuing...");
  541. int32 total_packets = packet_requests.size();
  542. for(int32 i=0;i<total_packets;i++)
  543. {
  544. outpack = packet_requests[i];
  545. if((i+1) == total_packets)
  546. {
  547. TableVersion* out_version = (TableVersion*)outpack->pBuffer;
  548. out_version->last = 1;
  549. }
  550. SendPacket(outpack);
  551. safe_delete(outpack);
  552. }*/
  553. return ret;
  554. }
  555. int32 LoginServer::ProcessDataUpdates(uchar* data) {
  556. int32 ret = 0;
  557. /*LatestTableVersions table_versions;
  558. table_versions.DeSerialize(data);
  559. int32 total_tables = table_versions.GetTotalTables();
  560. vector<ServerPacket*> packet_requests;
  561. ServerPacket* outpack = 0;
  562. for(int32 i=0;i<total_tables;i++){
  563. if(UpdatesAutoData()){
  564. float version = database.GetLatestDataTableVersion(table_versions.GetTable(i).name);
  565. if(version >= 0 && version < table_versions.GetTable(i).data_version )
  566. {
  567. ServerPacket* outpack = new ServerPacket(ServerOP_GetTableData, sizeof(TableVersion));
  568. TableVersion* out_version = (TableVersion*)outpack->pBuffer;
  569. strcpy(out_version->name, table_versions.GetTable(i).name);
  570. out_version->max_data_version = CURRENT_DATABASE_MAJORVERSION*100 + CURRENT_DATABASE_MINORVERSION;
  571. out_version->data_version = (sint32)version;
  572. out_version->last = 0;
  573. memset(out_version->column_names, 0, 1000);
  574. string columns = database.GetColumnNames(out_version->name);
  575. if(columns.length() > 1)
  576. strcpy(out_version->column_names, columns.c_str());
  577. packet_requests.push_back(outpack);
  578. ret++;
  579. }
  580. }
  581. }
  582. if( ret )
  583. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Found Data Updates!");
  584. int32 total_packets = packet_requests.size();
  585. for(int32 i=0;i<total_packets;i++)
  586. {
  587. outpack = packet_requests[i];
  588. if((i+1) == total_packets)
  589. {
  590. TableVersion* out_version = (TableVersion*)outpack->pBuffer;
  591. out_version->last = 1;
  592. }
  593. SendPacket(outpack);
  594. safe_delete(outpack);
  595. }*/
  596. return ret;
  597. }
  598. bool LoginServer::CheckAndWait(Timer* timer){
  599. Timer::SetCurrentTime();
  600. if(timer->Check(false)){
  601. if(timer->GetDuration() == 5000){
  602. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "Please wait...");
  603. timer->SetTimer(25000);
  604. timer->Start();
  605. }
  606. else
  607. return false;
  608. }
  609. Sleep(10);
  610. if(!loginserver.Process())
  611. tcpc->Disconnect();
  612. return Connected();
  613. }
  614. bool LoginServer::ConnectToUpdateServer(const char* iAddress, int16 iPort)
  615. {
  616. if(!try_auto_update)
  617. return true;
  618. char errbuf[TCPConnection_ErrorBufferSize];
  619. memset(errbuf, 0, TCPConnection_ErrorBufferSize);
  620. if (iAddress == 0)
  621. {
  622. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "PatchServer::ConnectToUpdateServer: address == 0");
  623. return false;
  624. }
  625. else
  626. {
  627. if ((UpdateServerIP = ResolveIP(iAddress, errbuf)) == 0)
  628. {
  629. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "LoginServer::ConnectToUpdateServer: Resolving IP address: '%s'", errbuf[0] == '\0' ? errbuf : " ");
  630. return false;
  631. }
  632. }
  633. if (iPort != 0)
  634. UpdateServerPort = iPort;
  635. if (UpdateServerIP == 0 || UpdateServerPort == 0)
  636. {
  637. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "PatchServer::ConnectToUpdateServer: Connect info incomplete, cannot connect.");
  638. return false;
  639. }
  640. if (tcpc->Connect(UpdateServerIP, UpdateServerPort, errbuf))
  641. {
  642. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "-Connected to Update Server: %s:%i", iAddress, UpdateServerPort);
  643. SendInfo();
  644. //wait for a max of 30 seconds to be verified by patcher
  645. //display a message at 5 seconds
  646. Timer waitTimer(5000);
  647. waitTimer.Start();
  648. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "-Checking for updates.");
  649. GetLatestTables();
  650. while(CheckAndWait(&waitTimer) && !update_server_verified);
  651. database.CheckVersionTable();
  652. if(!update_server_verified)
  653. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "Error while getting updates!");
  654. if(update_server_verified)
  655. {
  656. update_server_completed = false;
  657. waitTimer.SetTimer(5000);
  658. waitTimer.Start();
  659. while(CheckAndWait(&waitTimer) && !data_waiting);
  660. if(data_waiting)
  661. {
  662. int32 requests = ProcessTableUpdates(data_waiting);
  663. if(requests > 0)
  664. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Found Table Updates.");
  665. uchar* data = 0;
  666. waitTimer.SetTimer(30000);
  667. waitTimer.Start();
  668. if(requests > 0)
  669. {
  670. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Processing Table Updates.");
  671. database.DisableConstraints();
  672. deque<uchar*> alter_table_updates_waiting;
  673. while((CheckAndWait(&waitTimer) && !update_server_completed) || table_updates_waiting.size() > 0)
  674. {
  675. if(table_updates_waiting.size() > 0)
  676. {
  677. data = table_updates_waiting.front();
  678. table_updates_waiting.pop_front();
  679. ProcessTableUpdate(data);
  680. safe_delete(data);
  681. waitTimer.SetTimer(30000);
  682. waitTimer.Start();
  683. }
  684. }
  685. if(!CheckAndWait(&waitTimer))
  686. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "Timeout waiting for updates to complete! Try again later.");
  687. else
  688. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Table Update complete.");
  689. database.EnableConstraints();
  690. }
  691. else
  692. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "-No changes to DB Schema...");
  693. requests = ProcessDataUpdates(data_waiting);
  694. if(requests > 0)
  695. {
  696. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Processing Data Updates.");
  697. LogWrite(INIT__PATCHER_WARNING, 0, "Patcher", "** Data Updates are SLOW! Do not abort! **");
  698. database.DisableConstraints();
  699. deque<uchar*> alter_table_updates_waiting;
  700. int32 count = 0;
  701. while((CheckAndWait(&waitTimer) && count < requests) || data_updates_waiting.size() > 0)
  702. {
  703. if(data_updates_waiting.size() > 0)
  704. {
  705. data = data_updates_waiting.front();
  706. data_updates_waiting.pop_front();
  707. ProcessDataUpdate(data);
  708. count++;
  709. safe_delete_array(data);
  710. waitTimer.SetTimer(30000);
  711. waitTimer.Start();
  712. }
  713. }
  714. if(!CheckAndWait(&waitTimer))
  715. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "Timeout waiting for updates to complete! Try again later.");
  716. else
  717. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "--Data Updates complete.");
  718. database.EnableConstraints();
  719. }
  720. else
  721. LogWrite(INIT__PATCHER_DEBUG, 0, "Patcher", "-No changes to DB Data...");
  722. safe_delete_array(data_waiting);
  723. }
  724. try_auto_update = false;
  725. }
  726. tcpc->Disconnect();
  727. return update_server_verified;
  728. }
  729. else
  730. {
  731. LogWrite(INIT__PATCHER_ERROR, 0, "Patcher", "PatchServer::ConnectToUpdateServer: '%s'", errbuf[0] == '\0' ? errbuf : " ");
  732. return false;
  733. }
  734. }
  735. bool LoginServer::Connect(const char* iAddress, int16 iPort) {
  736. if(!pTryReconnect)
  737. return false;
  738. char errbuf[TCPConnection_ErrorBufferSize];
  739. memset(errbuf, 0, TCPConnection_ErrorBufferSize);
  740. if (iAddress == 0) {
  741. LogWrite(WORLD__ERROR, 0, "World", "LoginServer::Connect: address == 0");
  742. return false;
  743. }
  744. else {
  745. if ((LoginServerIP = ResolveIP(iAddress, errbuf)) == 0) {
  746. LogWrite(WORLD__ERROR, 0, "World", "LoginServer::Connect: Resolving IP address: '%s'", errbuf);
  747. return false;
  748. }
  749. }
  750. if (iPort != 0)
  751. LoginServerPort = iPort;
  752. if (LoginServerIP == 0 || LoginServerPort == 0) {
  753. LogWrite(WORLD__ERROR, 0, "World", "LoginServer::Connect: Connect info incomplete, cannot connect");
  754. return false;
  755. }
  756. if (tcpc->Connect(LoginServerIP, LoginServerPort, errbuf)) {
  757. LogWrite(WORLD__INFO, 0, "World", "Connected to LoginServer: %s: %i", iAddress, LoginServerPort);
  758. SendInfo();
  759. SendStatus();
  760. return true;
  761. }
  762. else {
  763. LogWrite(WORLD__ERROR, 0, "World", "LoginServer::Connect: '%s'", errbuf);
  764. return false;
  765. }
  766. }
  767. void LoginServer::GetLatestTables(){
  768. ServerPacket* pack = new ServerPacket(ServerOP_GetLatestTables, sizeof(GetLatestTables_Struct));
  769. GetLatestTables_Struct* data = (GetLatestTables_Struct*)pack->pBuffer;
  770. data->table_version = CURRENT_DATABASE_MAJORVERSION*100 + CURRENT_DATABASE_MINORVERSION;
  771. data->data_version = CURRENT_DATABASE_MAJORVERSION*100 + CURRENT_DATABASE_MINORVERSION;
  772. SendPacket(pack);
  773. delete pack;
  774. }
  775. void LoginServer::SendInfo() {
  776. ServerPacket* pack = new ServerPacket;
  777. pack->opcode = ServerOP_LSInfo;
  778. pack->size = sizeof(ServerLSInfo_Struct);
  779. pack->pBuffer = new uchar[pack->size];
  780. memset(pack->pBuffer, 0, pack->size);
  781. ServerLSInfo_Struct* lsi = (ServerLSInfo_Struct*) pack->pBuffer;
  782. strcpy(lsi->protocolversion, EQEMU_PROTOCOL_VERSION);
  783. strcpy(lsi->serverversion, CURRENT_VERSION);
  784. strcpy(lsi->name, net.GetWorldName());
  785. strcpy(lsi->account, net.GetWorldAccount());
  786. lsi->dbversion = CURRENT_DATABASE_MAJORVERSION*100 + CURRENT_DATABASE_MINORVERSION;
  787. #ifdef _DEBUG
  788. lsi->servertype = 4;
  789. #endif
  790. string passwdSha512 = sha512(net.GetWorldPassword());
  791. memcpy(lsi->password, (char*)passwdSha512.c_str(), passwdSha512.length());
  792. strcpy(lsi->address, net.GetWorldAddress());
  793. SendPacket(pack);
  794. delete pack;
  795. }
  796. void LoginServer::SendStatus() {
  797. statusupdate_timer->Start();
  798. ServerPacket* pack = new ServerPacket;
  799. pack->opcode = ServerOP_LSStatus;
  800. pack->size = sizeof(ServerLSStatus_Struct);
  801. pack->pBuffer = new uchar[pack->size];
  802. memset(pack->pBuffer, 0, pack->size);
  803. ServerLSStatus_Struct* lss = (ServerLSStatus_Struct*) pack->pBuffer;
  804. if (net.world_locked)
  805. lss->status = -2;
  806. else if(loginserver.maxPlayers > -1 && numclients >= loginserver.maxPlayers)
  807. lss->status = -3;
  808. else
  809. lss->status = 1;
  810. lss->num_zones = numzones;
  811. lss->num_players = numclients;
  812. lss->world_max_level = rule_manager.GetGlobalRule(R_Player, MaxLevel)->GetInt8();
  813. SendPacket(pack);
  814. delete pack;
  815. }
  816. void LoginServer::SendDeleteCharacter ( CharacterTimeStamp_Struct* cts ) {
  817. ServerPacket* outpack = new ServerPacket(ServerOP_BasicCharUpdate, sizeof(CharDataUpdate_Struct));
  818. CharDataUpdate_Struct* cdu = (CharDataUpdate_Struct*)outpack->pBuffer;
  819. cdu->account_id = cts->account_id;
  820. cdu->char_id = cts->char_id;
  821. cdu->update_field = DELETE_UPDATE_FLAG;
  822. cdu->update_data = 1;
  823. SendPacket(outpack);
  824. safe_delete(outpack);
  825. }
  826. void LoginServer::SendFilterNameResponse ( int8 resp, int32 acct_id , int32 char_id ) {
  827. ServerPacket* outpack = new ServerPacket(ServerOP_CharacterCreate, sizeof(WorldCharNameFilterResponse_Struct));
  828. WorldCharNameFilterResponse_Struct* wcfr = (WorldCharNameFilterResponse_Struct*)outpack->pBuffer;
  829. wcfr->response = resp;
  830. wcfr->account_id = acct_id;
  831. wcfr->char_id = char_id;
  832. SendPacket(outpack);
  833. safe_delete(outpack);
  834. }
  835. int32 LoginServer::DetermineCharacterLoginRequest ( UsertoWorldRequest_Struct* utwr ) {
  836. LogWrite(LOGIN__TRACE, 9, "Login", "Enter: %s", __FUNCTION__);
  837. ServerPacket* outpack = new ServerPacket;
  838. outpack->opcode = ServerOP_UsertoWorldResp;
  839. outpack->size = sizeof(UsertoWorldResponse_Struct);
  840. outpack->pBuffer = new uchar[outpack->size];
  841. memset(outpack->pBuffer, 0, outpack->size);
  842. UsertoWorldResponse_Struct* utwrs = (UsertoWorldResponse_Struct*) outpack->pBuffer;
  843. utwrs->lsaccountid = utwr->lsaccountid;
  844. utwrs->char_id = utwr->char_id;
  845. utwrs->ToID = utwr->FromID;
  846. int32 timestamp = Timer::GetUnixTimeStamp();
  847. utwrs->access_key = timestamp;
  848. // set default response to 0
  849. utwrs->response = 0;
  850. sint16 lowestStatus = database.GetLowestCharacterAdminStatus( utwr->lsaccountid );
  851. sint16 status = 0;
  852. if(lowestStatus == -2)
  853. status = -1;
  854. else
  855. status = database.GetCharacterAdminStatus ( utwr->lsaccountid , utwr->char_id );
  856. if(status < 100 && zone_list.ClientConnected(utwr->lsaccountid))
  857. status = -9;
  858. if(status < 0){
  859. LogWrite(WORLD__ERROR, 0, "World", "Login Rejected based on PLAY_ERROR (UserStatus) (MinStatus: %i), UserStatus: %i, CharID: %i",loginserver.minLockedStatus,status,utwr->char_id );
  860. switch(status){
  861. case -10:
  862. utwrs->response = PLAY_ERROR_CHAR_NOT_LOADED;
  863. break;
  864. case -9:
  865. utwrs->response = 0;//PLAY_ERROR_ACCOUNT_IN_USE;
  866. break;
  867. case -8:
  868. utwrs->response = PLAY_ERROR_LOADING_ERROR;
  869. break;
  870. case -1:
  871. utwrs->response = PLAY_ERROR_ACCOUNT_BANNED;
  872. break;
  873. default:
  874. utwrs->response = PLAY_ERROR_PROBLEM;
  875. }
  876. }
  877. else if(net.world_locked == true){
  878. LogWrite(WORLD__INFO, 0, "World", "Login Lock Check (MinStatus: %i):, UserStatus: %i, CharID: %i",loginserver.minLockedStatus,status,utwr->char_id );
  879. // has high enough status, allow it
  880. if(status >= loginserver.minLockedStatus)
  881. utwrs->response = 1;
  882. }
  883. else if(loginserver.maxPlayers > -1 && ((sint16)client_list.Count()) >= loginserver.maxPlayers)
  884. {
  885. LogWrite(WORLD__INFO, 0, "World", "Login GameFull Check (MinStatus: %i):, UserStatus: %i, CharID: %i",loginserver.minGameFullStatus,status,utwr->char_id );
  886. // has high enough status, allow it
  887. if(status >= loginserver.minGameFullStatus)
  888. {
  889. utwrs->response = 1;
  890. }
  891. else
  892. utwrs->response = -3; // server full response is -3
  893. }
  894. else
  895. utwrs->response = 1;
  896. /*sint32 x = database.CommandRequirement("$MAXCLIENTS");
  897. if( (sint32)numplayers >= x && x != -1 && x != 255 && status < 80)
  898. utwrs->response = -3;
  899. if(status == -1)
  900. utwrs->response = -1;
  901. if(status == -2)
  902. utwrs->response = -2;
  903. */
  904. //printf("Response is %i for %i\n",utwrs->response,id);struct sockaddr_in sa;
  905. int32 ipv4addr = 0;
  906. int result = 0;
  907. #ifdef WIN32
  908. struct sockaddr_in myaddr;
  909. ZeroMemory(&myaddr, sizeof(myaddr));
  910. result = InetPton(AF_INET, utwr->ip_address, &(myaddr.sin_addr));
  911. if(result)
  912. ipv4addr = ntohl(myaddr.sin_addr.s_addr);
  913. #else
  914. result = inet_pton(AF_INET, utwr->ip_address, &ipv4addr);
  915. if(result)
  916. ipv4addr = ntohl(ipv4addr);
  917. #endif
  918. if (((result > 0 && IsPrivateAddress(ipv4addr)) || (strcmp(net.GetWorldAddress(), utwr->ip_address) == 0)) && (strlen(net.GetInternalWorldAddress()) > 0))
  919. strcpy(utwrs->ip_address, net.GetInternalWorldAddress());
  920. else
  921. strcpy(utwrs->ip_address, net.GetWorldAddress());
  922. LogWrite(CCLIENT__INFO, 0, "World", "New client login attempt from %s, providing %s as the world server address.",utwr->ip_address, utwrs->ip_address );
  923. utwrs->port = net.GetWorldPort();
  924. utwrs->worldid = utwr->worldid;
  925. SendPacket(outpack);
  926. delete outpack;
  927. LogWrite(LOGIN__TRACE, 9, "Login", "Exit: %s with timestamp=%u", __FUNCTION__, timestamp);
  928. // depending on the response determined above, this could return 0 (for failure)
  929. return timestamp;
  930. }