net.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 <stdlib.h>
  23. #include <algorithm>
  24. #include <chrono>
  25. #include <signal.h>
  26. #include "../common/queue.h"
  27. #include "../common/timer.h"
  28. #include "../common/EQStreamFactory.h"
  29. #include "../common/EQStream.h"
  30. #include "net.h"
  31. #include "Variables.h"
  32. #include "WorldDatabase.h"
  33. #include "../common/seperator.h"
  34. #include "../common/version.h"
  35. #include "../common/EQEMuError.h"
  36. #include "../common/opcodemgr.h"
  37. #include "../common/Common_Defines.h"
  38. #include "LoginServer.h"
  39. #include "Commands/Commands.h"
  40. #include "Factions.h"
  41. #include "World.h"
  42. #include "../common/ConfigReader.h"
  43. #include "Skills.h"
  44. #include "LuaInterface.h"
  45. #include "Guilds/Guild.h"
  46. #include "Commands/ConsoleCommands.h"
  47. #include "Traits/Traits.h"
  48. #include "Transmute.h"
  49. #include "Zone/ChestTrap.h"
  50. double frame_time = 0.0;
  51. #ifdef WIN32
  52. #include <process.h>
  53. #define strncasecmp _strnicmp
  54. #define strcasecmp _stricmp
  55. #include <conio.h>
  56. #else
  57. #include <pthread.h>
  58. #include "../common/unix.h"
  59. #endif
  60. #ifdef PROFILER
  61. #define SHINY_PROFILER TRUE
  62. #include "../Profiler/src/Shiny.h"
  63. #endif
  64. NetConnection net;
  65. World world;
  66. EQStreamFactory eqsf(LoginStream);
  67. LoginServer loginserver;
  68. LuaInterface* lua_interface = new LuaInterface();
  69. #include "MutexList.h"
  70. #include "Rules/Rules.h"
  71. #include "Titles.h"
  72. #include "Languages.h"
  73. #include "Achievements/Achievements.h"
  74. volatile bool RunLoops = true;
  75. sint32 numclients = 0;
  76. sint32 numzones = 0;
  77. extern ClientList client_list;
  78. extern ZoneList zone_list;
  79. extern MasterFactionList master_faction_list;
  80. extern WorldDatabase database;
  81. extern MasterSpellList master_spell_list;
  82. extern MasterTraitList master_trait_list;
  83. extern MasterSkillList master_skill_list;
  84. extern MasterItemList master_item_list;
  85. extern GuildList guild_list;
  86. extern Variables variables;
  87. ConfigReader configReader;
  88. int32 MasterItemList::next_unique_id = 0;
  89. int last_signal = 0;
  90. RuleManager rule_manager;
  91. MasterTitlesList master_titles_list;
  92. MasterLanguagesList master_languages_list;
  93. ChestTrapList chest_trap_list;
  94. extern MasterAchievementList master_achievement_list;
  95. extern map<int16, int16> EQOpcodeVersions;
  96. ThreadReturnType ItemLoad (void* tmp);
  97. ThreadReturnType AchievmentLoad (void* tmp);
  98. ThreadReturnType SpellLoad (void* tmp);
  99. int main(int argc, char** argv) {
  100. #ifdef PROFILER
  101. PROFILE_FUNC();
  102. #endif
  103. int32 t_total = Timer::GetUnixTimeStamp();
  104. LogStart();
  105. LogParseConfigs();
  106. net.WelcomeHeader();
  107. LogWrite(INIT__INFO, 0, "Init", "Starting EQ2Emulator WorldServer...");
  108. //int32 server_startup = time(NULL);
  109. //remove this when all database calls are using the new database class
  110. if (!database.Init()) {
  111. LogStop();
  112. return EXIT_FAILURE;
  113. }
  114. if (!database.ConnectNewDatabase())
  115. return EXIT_FAILURE;
  116. #ifdef _DEBUG
  117. _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  118. #endif
  119. if (signal(SIGINT, CatchSignal) == SIG_ERR) {
  120. LogWrite(INIT__ERROR, 0, "Init", "Could not set signal handler");
  121. return 0;
  122. }
  123. if (signal(SIGSEGV, CatchSignal) == SIG_ERR) {
  124. LogWrite(INIT__ERROR, 0, "Init", "Could not set signal handler");
  125. return 0;
  126. }
  127. if (signal(SIGILL, CatchSignal) == SIG_ERR) {
  128. LogWrite(INIT__ERROR, 0, "Init", "Could not set signal handler");
  129. return 0;
  130. }
  131. #ifndef WIN32
  132. if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
  133. LogWrite(INIT__ERROR, 0, "Init", "Could not set signal handler");
  134. return 0;
  135. }
  136. #endif
  137. LogWrite(WORLD__DEBUG, 0, "World", "Randomizing World...");
  138. srand(time(NULL));
  139. net.ReadLoginINI();
  140. // JA: Grouping all System (core) data loads together for timing purposes
  141. LogWrite(WORLD__INFO, 0, "World", "Loading System Data...");
  142. int32 t_now = Timer::GetUnixTimeStamp();
  143. LogWrite(WORLD__DEBUG, 1, "World", "-Loading opcodes...");
  144. EQOpcodeVersions = database.GetVersions();
  145. map<int16,int16>::iterator version_itr;
  146. int16 version1 = 0;
  147. int16 prevVersion = 0;
  148. std::string prevString = std::string("");
  149. std::string builtString = std::string("");
  150. for (version_itr = EQOpcodeVersions.begin(); version_itr != EQOpcodeVersions.end(); version_itr++) {
  151. version1 = version_itr->first;
  152. EQOpcodeManager[version1] = new RegularOpcodeManager();
  153. map<string, uint16> eq = database.GetOpcodes(version1);
  154. std::string missingOpcodesList = std::string("");
  155. if(!EQOpcodeManager[version1]->LoadOpcodes(&eq, &missingOpcodesList)) {
  156. LogWrite(INIT__ERROR, 0, "Init", "Loading opcodes failed. Make sure you have sourced the opcodes.sql file!");
  157. return false;
  158. }
  159. if(version1 == 0) // we don't need to display version 0
  160. continue;
  161. if(prevString.size() > 0) {
  162. if(prevString == missingOpcodesList) {
  163. builtString += ", " + std::to_string(version1);
  164. }
  165. else {
  166. LogWrite(OPCODE__WARNING, 1, "Opcode", "Opcodes %s.", builtString.c_str());
  167. builtString = std::string("");
  168. prevString = std::string("");
  169. }
  170. }
  171. if(prevString.size() < 1) {
  172. prevString = std::string(missingOpcodesList);
  173. builtString = std::string(missingOpcodesList + " are missing from the opcodes table for version(s) " + std::to_string(version1));
  174. }
  175. }
  176. if(builtString.size() > 0) {
  177. LogWrite(OPCODE__WARNING, 1, "Opcode", "Opcodes %s.", builtString.c_str());
  178. }
  179. LogWrite(WORLD__DEBUG, 1, "World", "-Loading structs...");
  180. if(!configReader.LoadFile("CommonStructs.xml") || !configReader.LoadFile("WorldStructs.xml") || !configReader.LoadFile("SpawnStructs.xml") || !configReader.LoadFile("ItemStructs.xml")) {
  181. LogWrite(INIT__ERROR, 0, "Init", "Loading structs failed. Make sure you have CommonStructs.xml, WorldStructs.xml, SpawnStructs.xml, and ItemStructs.xml in the working directory!");
  182. return false;
  183. }
  184. world.init();
  185. bool threadedLoad = rule_manager.GetGlobalRule(R_World, ThreadedLoad)->GetBool();
  186. LogWrite(WORLD__DEBUG, 1, "World", "-Loading EQ2 time of day...");
  187. loginserver.InitLoginServerVariables();
  188. LogWrite(WORLD__INFO, 0, "World", "Loaded System Data (took %u seconds)", Timer::GetUnixTimeStamp() - t_now);
  189. // JA: End System Data loading functions
  190. if (threadedLoad) {
  191. LogWrite(WORLD__WARNING, 0, "Threaded", "Using Threaded loading of static data...");
  192. #ifdef WIN32
  193. _beginthread(ItemLoad, 0, &world);
  194. _beginthread(SpellLoad, 0, &world);
  195. //_beginthread(AchievmentLoad, 0, &world);
  196. #else
  197. pthread_t thread;
  198. pthread_create(&thread, NULL, ItemLoad, &world);
  199. pthread_detach(thread);
  200. pthread_t thread2;
  201. pthread_create(&thread2, NULL, SpellLoad, &world);
  202. pthread_detach(thread2);
  203. //pthread_t thread3;
  204. //pthread_create(&thread3, NULL, AchievmentLoad, &world);
  205. //pthread_detach(thread3);
  206. #endif
  207. }
  208. // Called as a function so we can use /reload spawns any time
  209. /*LogWrite(SPAWN__INFO, 0, "Spawn", "Initializing Spawn Subsystem...");
  210. t_now = Timer::GetUnixTimeStamp();
  211. world.LoadSpawnInformation();
  212. LogWrite(SPAWN__INFO, 0, "Spawn", "Initialize Spawn Subsystem complete (took %u seconds)", Timer::GetUnixTimeStamp() - t_now);*/
  213. // JA temp logger
  214. LogWrite(MISC__TODO, 0, "Reformat", "JA: This is as far as I got reformatting the console logs.");
  215. if (!threadedLoad) {
  216. // JA: Load all Item info
  217. LogWrite(ITEM__INFO, 0, "Items", "Loading Items...");
  218. database.LoadItemList();
  219. MasterItemList::ResetUniqueID(database.LoadNextUniqueItemID());
  220. }
  221. if (!threadedLoad) {
  222. // JA: Load all Spell info
  223. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spells...");
  224. database.LoadSpells();
  225. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spell Errors...");
  226. database.LoadSpellErrors();
  227. // Jabantiz: Load traits
  228. LogWrite(WORLD__INFO, 0, "Traits", "Loading Traits...");
  229. database.LoadTraits();
  230. }
  231. if (!threadedLoad) {
  232. // JA: Load all Quest info
  233. LogWrite(QUEST__INFO, 0, "Quests", "Loading Quests...");
  234. database.LoadQuests();
  235. }
  236. if (!threadedLoad) {
  237. LogWrite(COLLECTION__INFO, 0, "Collect", "Loading Collections...");
  238. database.LoadCollections();
  239. }
  240. LogWrite(GUILD__INFO, 0, "Guilds", "Loading Guilds...");
  241. database.LoadGuilds();
  242. LogWrite(TRADESKILL__INFO, 0, "Recipes", "Loading Recipe Books...");
  243. database.LoadRecipeBooks();
  244. LogWrite(TRADESKILL__INFO, 0, "Recipes", "Loading Recipes...");
  245. database.LoadRecipes();
  246. LogWrite(TRADESKILL__INFO, 0, "Tradeskills", "Loading Tradeskill Events...");
  247. database.LoadTradeskillEvents();
  248. if (!threadedLoad) {
  249. LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Loading Achievements...");
  250. //database.LoadAchievements();
  251. //master_achievement_list.CreateMasterAchievementListPacket();
  252. }
  253. LogWrite(SPELL__INFO, 0, "AA", "Loading Alternate Advancements...");
  254. database.LoadAltAdvancements();
  255. LogWrite(SPELL__INFO, 0, "AA", "Loading AA Tree Nodes...");
  256. database.LoadTreeNodes();
  257. LogWrite(WORLD__INFO, 0, "Titles", "Loading Titles...");
  258. database.LoadTitles();
  259. LogWrite(WORLD__INFO, 0, "Languages", "Loading Languages...");
  260. database.LoadLanguages();
  261. LogWrite(CHAT__INFO, 0, "Chat", "Loading channels...");
  262. database.LoadChannels();
  263. if (!threadedLoad) {
  264. LogWrite(MERCHANT__INFO, 0, "Merchants", "Loading Merchants...");
  265. database.LoadMerchantInformation();
  266. }
  267. LogWrite(LUA__INFO, 0, "LUA", "Loading Spawn Scripts...");
  268. database.LoadSpawnScriptData();
  269. LogWrite(LUA__INFO, 0, "LUA", "Loading Zone Scripts...");
  270. database.LoadZoneScriptData();
  271. LogWrite(WORLD__INFO, 0, "World", "Loading House Zone Data...");
  272. database.LoadHouseZones();
  273. database.LoadPlayerHouses();
  274. LogWrite(WORLD__INFO, 0, "World", "Loading Heroic OP Data...");
  275. database.LoadHOStarters();
  276. database.LoadHOWheel();
  277. LogWrite(WORLD__INFO, 0, "World", "Loading Race Types Data...");
  278. database.LoadRaceTypes();
  279. LogWrite(WORLD__INFO, 0, "World", "Loading Transmuting Data...");
  280. database.LoadTransmuting();
  281. LogWrite(WORLD__INFO, 0, "World", "Loading Chest Trap Data...");
  282. database.LoadChestTraps();
  283. if (threadedLoad) {
  284. LogWrite(WORLD__INFO, 0, "World", "Waiting for load threads to finish.");
  285. while (!world.items_loaded || !world.spells_loaded /*|| !world.achievments_loaded*/)
  286. Sleep(10);
  287. LogWrite(WORLD__INFO, 0, "World", "Load threads finished.");
  288. }
  289. LogWrite(WORLD__INFO, 0, "World", "Total World startup time: %u seconds.", Timer::GetUnixTimeStamp() - t_total);
  290. int ret_code = 0;
  291. if (eqsf.Open(net.GetWorldPort())) {
  292. if (strlen(net.GetWorldAddress()) == 0)
  293. LogWrite(NET__INFO, 0, "Net", "World server listening on port %i", net.GetWorldPort());
  294. else
  295. LogWrite(NET__INFO, 0, "Net", "World server listening on: %s:%i", net.GetWorldAddress(), net.GetWorldPort());
  296. if(strlen(net.GetInternalWorldAddress())>0)
  297. LogWrite(NET__INFO, 0, "Net", "World server listening on: %s:%i", net.GetInternalWorldAddress(), net.GetWorldPort());
  298. }
  299. else {
  300. LogWrite(NET__ERROR, 0, "Net", "Failed to open port %i.", net.GetWorldPort());
  301. ret_code = 1;
  302. }
  303. Timer* TimeoutTimer = 0;
  304. if (ret_code == 0) {
  305. Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect
  306. InterserverTimer.Trigger();
  307. TimeoutTimer = new Timer(5000);
  308. TimeoutTimer->Start();
  309. EQStream* eqs = 0;
  310. UpdateWindowTitle(0);
  311. LogWrite(ZONE__INFO, 0, "Zone", "Starting static zones...");
  312. database.LoadSpecialZones();
  313. map<EQStream*, int32> connecting_clients;
  314. map<EQStream*, int32>::iterator cc_itr;
  315. LogWrite(WORLD__DEBUG, 0, "Thread", "Starting console command thread...");
  316. #ifdef WIN32
  317. _beginthread(EQ2ConsoleListener, 0, NULL);
  318. #else
  319. /*pthread_t thread;
  320. pthread_create(&thread, NULL, &EQ2ConsoleListener, NULL);
  321. pthread_detach(thread);*/
  322. #endif
  323. //
  324. // just before starting loops, announce how to get console help
  325. LogWrite(WORLD__INFO, 0, "Console", "Type 'help' or '?' and press enter for menu options.");
  326. std::chrono::time_point<std::chrono::system_clock> frame_prev = std::chrono::system_clock::now();
  327. while (RunLoops) {
  328. Timer::SetCurrentTime();
  329. std::chrono::time_point<std::chrono::system_clock> frame_now = std::chrono::system_clock::now();
  330. frame_time = std::chrono::duration_cast<std::chrono::duration<double>>(frame_now - frame_prev).count();
  331. frame_prev = frame_now;
  332. #ifndef NO_CATCH
  333. try
  334. {
  335. #endif
  336. while ((eqs = eqsf.Pop())) {
  337. struct in_addr in;
  338. in.s_addr = eqs->GetRemoteIP();
  339. LogWrite(NET__DEBUG, 0, "Net", "New client from ip: %s port: %i", inet_ntoa(in), ntohs(eqs->GetRemotePort()));
  340. // JA: Check for BannedIPs
  341. if (rule_manager.GetGlobalRule(R_World, UseBannedIPsTable)->GetInt8() == 1)
  342. {
  343. LogWrite(WORLD__DEBUG, 0, "World", "Checking inbound connection %s against BannedIPs table", inet_ntoa(in));
  344. if (database.CheckBannedIPs(inet_ntoa(in)))
  345. {
  346. LogWrite(WORLD__DEBUG, 0, "World", "Connection from %s FAILED banned IPs check. Closing connection.", inet_ntoa(in));
  347. eqs->Close(); // JA: If the inbound IP is on the banned table, close the EQStream.
  348. }
  349. }
  350. if (eqs && eqs->CheckActive() && client_list.ContainsStream(eqs) == false) {
  351. LogWrite(NET__DEBUG, 0, "Net", "Adding new client...");
  352. Client* client = new Client(eqs);
  353. client_list.Add(client);
  354. }
  355. else if (eqs && !client_list.ContainsStream(eqs)) {
  356. LogWrite(NET__DEBUG, 0, "Net", "Adding client to waiting list...");
  357. connecting_clients[eqs] = Timer::GetCurrentTime2();
  358. }
  359. }
  360. if (connecting_clients.size() > 0) {
  361. for (cc_itr = connecting_clients.begin(); cc_itr != connecting_clients.end(); cc_itr++) {
  362. if (cc_itr->first && cc_itr->first->CheckActive() && client_list.ContainsStream(cc_itr->first) == false) {
  363. LogWrite(NET__DEBUG, 0, "Net", "Removing client from waiting list...");
  364. Client* client = new Client(cc_itr->first);
  365. client_list.Add(client);
  366. connecting_clients.erase(cc_itr);
  367. break;
  368. }
  369. else if (Timer::GetCurrentTime2() >= (cc_itr->second + 10000)) {
  370. connecting_clients.erase(cc_itr);
  371. break;
  372. }
  373. }
  374. }
  375. world.Process();
  376. client_list.Process();
  377. loginserver.Process();
  378. if (TimeoutTimer->Check()) {
  379. eqsf.CheckTimeout();
  380. }
  381. if (InterserverTimer.Check()) {
  382. InterserverTimer.Start();
  383. database.ping();
  384. database.PingNewDB();
  385. database.PingAsyncDatabase();
  386. if (net.LoginServerInfo && loginserver.Connected() == false && loginserver.CanReconnect()) {
  387. LogWrite(WORLD__DEBUG, 0, "Thread", "Starting autoinit loginserver thread...");
  388. #ifdef WIN32
  389. _beginthread(AutoInitLoginServer, 0, NULL);
  390. #else
  391. pthread_t thread;
  392. pthread_create(&thread, NULL, &AutoInitLoginServer, NULL);
  393. pthread_detach(thread);
  394. #endif
  395. }
  396. }
  397. #ifndef NO_CATCH
  398. }
  399. catch (...) {
  400. LogWrite(WORLD__ERROR, 0, "World", "Exception caught in net main loop!");
  401. }
  402. #endif
  403. if (numclients == 0) {
  404. Sleep(10);
  405. continue;
  406. }
  407. Sleep(1);
  408. }
  409. }
  410. LogWrite(WORLD__DEBUG, 0, "World", "The world is ending!");
  411. LogWrite(WORLD__DEBUG, 0, "World", "Shutting down zones...");
  412. zone_list.ShutDownZones();
  413. LogWrite(WORLD__DEBUG, 0, "World", "Shutting down LUA interface...");
  414. safe_delete(lua_interface);
  415. safe_delete(TimeoutTimer);
  416. eqsf.Close();
  417. map<int16, OpcodeManager*>::iterator opcode_itr;
  418. for(opcode_itr=EQOpcodeManager.begin();opcode_itr!=EQOpcodeManager.end();opcode_itr++){
  419. safe_delete(opcode_itr->second);
  420. }
  421. CheckEQEMuErrorAndPause();
  422. #ifdef PROFILER
  423. PROFILER_UPDATE();
  424. PROFILER_OUTPUT();
  425. #endif
  426. LogWrite(WORLD__INFO, 0, "World", "Exiting... we hope you enjoyed your flight.");
  427. LogStop();
  428. return ret_code;
  429. }
  430. ThreadReturnType ItemLoad (void* tmp)
  431. {
  432. LogWrite(WORLD__WARNING, 0, "Thread", "Item Loading Thread started.");
  433. #ifdef WIN32
  434. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  435. #endif
  436. if (tmp == 0) {
  437. ThrowError("ItemLoad(): tmp = 0!");
  438. THREAD_RETURN(NULL);
  439. }
  440. World* world = (World*) tmp;
  441. WorldDatabase db;
  442. db.Init();
  443. db.ConnectNewDatabase();
  444. LogWrite(ITEM__INFO, 0, "Items", "Loading Items...");
  445. db.LoadItemList();
  446. MasterItemList::ResetUniqueID(db.LoadNextUniqueItemID());
  447. // Relies on the item list so needs to be in the item thread
  448. LogWrite(COLLECTION__INFO, 0, "Collect", "Loading Collections...");
  449. db.LoadCollections();
  450. LogWrite(MERCHANT__INFO, 0, "Merchants", "Loading Merchants...");
  451. db.LoadMerchantInformation();
  452. LogWrite(QUEST__INFO, 0, "Quests", "Loading Quests...");
  453. db.LoadQuests();
  454. world->items_loaded = true;
  455. LogWrite(WORLD__WARNING, 0, "Thread", "Item Loading Thread completed.");
  456. mysql_thread_end();
  457. THREAD_RETURN(NULL);
  458. }
  459. ThreadReturnType SpellLoad (void* tmp)
  460. {
  461. LogWrite(WORLD__WARNING, 0, "Thread", "Spell Loading Thread started.");
  462. #ifdef WIN32
  463. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  464. #endif
  465. if (tmp == 0) {
  466. ThrowError("ItemLoad(): tmp = 0!");
  467. THREAD_RETURN(NULL);
  468. }
  469. World* world = (World*) tmp;
  470. WorldDatabase db;
  471. db.Init();
  472. db.ConnectNewDatabase();
  473. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spells...");
  474. db.LoadSpells();
  475. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spell Errors...");
  476. db.LoadSpellErrors();
  477. LogWrite(WORLD__INFO, 0, "Traits", "Loading Traits...");
  478. db.LoadTraits();
  479. world->spells_loaded = true;
  480. LogWrite(WORLD__WARNING, 0, "Thread", "Spell Loading Thread completed.");
  481. mysql_thread_end();
  482. THREAD_RETURN(NULL);
  483. }
  484. ThreadReturnType AchievmentLoad (void* tmp)
  485. {
  486. LogWrite(WORLD__WARNING, 0, "Thread", "Achievement Loading Thread started.");
  487. #ifdef WIN32
  488. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  489. #endif
  490. if (tmp == 0) {
  491. ThrowError("ItemLoad(): tmp = 0!");
  492. THREAD_RETURN(NULL);
  493. }
  494. World* world = (World*) tmp;
  495. WorldDatabase db;
  496. db.Init();
  497. db.ConnectNewDatabase();
  498. LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Loading Achievements...");
  499. int32 t_now = Timer::GetUnixTimeStamp();
  500. db.LoadAchievements();
  501. master_achievement_list.CreateMasterAchievementListPacket();
  502. LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Achievements loaded (took %u seconds)", Timer::GetUnixTimeStamp() - t_now);
  503. world->achievments_loaded = true;
  504. LogWrite(WORLD__WARNING, 0, "Thread", "Achievement Loading Thread completed.");
  505. mysql_thread_end();
  506. THREAD_RETURN(NULL);
  507. }
  508. ThreadReturnType EQ2ConsoleListener(void* tmp)
  509. {
  510. char cmd[300];
  511. size_t i = 0;
  512. size_t len;
  513. while( RunLoops )
  514. {
  515. // Read in single line from "stdin"
  516. memset( cmd, 0, sizeof( cmd ) );
  517. if( fgets( cmd, 300, stdin ) == NULL )
  518. continue;
  519. if( !RunLoops )
  520. break;
  521. len = strlen(cmd);
  522. for( i = 0; i < len; ++i )
  523. {
  524. if(cmd[i] == '\n' || cmd[i] == '\r')
  525. cmd[i] = '\0';
  526. }
  527. ProcessConsoleInput(cmd);
  528. }
  529. THREAD_RETURN(NULL);
  530. }
  531. #include <fstream>
  532. void CatchSignal(int sig_num) {
  533. // In rare cases this can be called after the log system is shut down causing a deadlock or crash
  534. // when the world shuts down, if this happens again comment out the LogWrite and uncomment the printf
  535. if (last_signal != sig_num){
  536. static Mutex lock;
  537. static std::ofstream signal_out;
  538. lock.lock();
  539. if (!signal_out.is_open())
  540. signal_out.open("signal_catching.log", ios::trunc);
  541. if (signal_out){
  542. signal_out << "Caught signal " << sig_num << "\n";
  543. signal_out.flush();
  544. }
  545. printf("Caught signal %i\n", sig_num);
  546. lock.unlock();
  547. last_signal = sig_num;
  548. RunLoops = false;
  549. }
  550. }
  551. bool NetConnection::ReadLoginINI() {
  552. char buf[201], type[201];
  553. int items[3] = {0, 0};
  554. FILE *f;
  555. if (!(f = fopen (MAIN_INI_FILE, "r"))) {
  556. LogWrite(INIT__ERROR, 0, "Init", "File '%s' could not be opened", MAIN_INI_FILE);
  557. return false;
  558. }
  559. do {
  560. if (fgets (buf, 200, f) == NULL || feof(f))
  561. {
  562. LogWrite(INIT__ERROR, 0, "Init", "[LoginServer] block not found in '%s'.", MAIN_INI_FILE);
  563. fclose (f);
  564. return false;
  565. }
  566. }
  567. while (strncasecmp (buf, "[LoginServer]\n", 14) != 0 && strncasecmp (buf, "[LoginServer]\r\n", 15) != 0);
  568. while (!feof (f))
  569. {
  570. #ifdef WIN32
  571. if (fscanf (f, "%[^=]=%[^\n]\r\n", type, buf) == 2)
  572. #else
  573. if (fscanf (f, "%[^=]=%[^\r\n]\n", type, buf) == 2)
  574. #endif
  575. {
  576. if (!strncasecmp(type, "[", 1)) {
  577. // new block after LoginServer, skip
  578. break;
  579. }
  580. if (!strncasecmp (type, "worldname", 9)) {
  581. snprintf(worldname, sizeof(worldname), "%s", buf);
  582. items[1] = 1;
  583. if(strlen(worldname)<4)
  584. LogWrite(INIT__ERROR, 0, "Init", "Invalid worldname, please edit LoginServer.ini. Server name must be at least 4 characters.");
  585. }
  586. if (!strncasecmp (type, "account", 7)) {
  587. strncpy(worldaccount, buf, 30);
  588. }
  589. if (!strncasecmp (type, "logstats", 8)) {
  590. if (strcasecmp(buf, "true") == 0 || (buf[0] == '1' && buf[1] == 0))
  591. net.UpdateStats = true;
  592. }
  593. if (!strncasecmp (type, "password", 8)) {
  594. strncpy (worldpassword, buf, 30);
  595. for(int i=strlen(worldpassword);i>=0;i--){
  596. if(worldpassword[i] == ' ' || worldpassword[i] == '\n' || worldpassword[i] == '\t' || worldpassword[i] == '\r')
  597. worldpassword[i] = '\0';
  598. }
  599. }
  600. if (!strncasecmp (type, "locked", 6)) {
  601. if (strcasecmp(buf, "true") == 0 || (buf[0] == '1' && buf[1] == 0))
  602. world_locked = true;
  603. }
  604. if (!strncasecmp (type, "worldaddress", 12)) {
  605. if (strlen(buf) >= 3) {
  606. strncpy (worldaddress, buf, 250);
  607. }
  608. }
  609. if (!strncasecmp (type, "internalworldaddress", 20)) {
  610. if (strlen(buf) >= 3) {
  611. strncpy(internalworldaddress, buf, 20);
  612. }
  613. }
  614. if (!strncasecmp (type, "worldport", 9)) {
  615. if(Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF)
  616. worldport = atoi(buf);
  617. }
  618. if ((!strcasecmp (type, "loginserver")) || (!strcasecmp (type, "loginserver1"))) {
  619. strncpy (loginaddress[0], buf, 100);
  620. items[0] = 1;
  621. }
  622. if ((!strcasecmp(type, "loginport")) || (!strcasecmp(type, "loginport1"))) {
  623. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  624. loginport[0] = atoi(buf);
  625. }
  626. }
  627. if (!strcasecmp (type, "loginserver2")) {
  628. strncpy (loginaddress[1], buf, 250);
  629. }
  630. if (!strcasecmp(type, "loginport2")) {
  631. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  632. loginport[1] = atoi(buf);
  633. }
  634. }
  635. if (!strcasecmp (type, "loginserver3")) {
  636. strncpy (loginaddress[2], buf, 250);
  637. }
  638. if (!strcasecmp(type, "loginport3")) {
  639. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  640. loginport[2] = atoi(buf);
  641. }
  642. }
  643. }
  644. }
  645. if (!items[0] || !items[1])
  646. {
  647. LogWrite(INIT__ERROR, 0, "Init", "Incomplete LoginServer.INI file.");
  648. fclose (f);
  649. return false;
  650. }
  651. /*
  652. if (strcasecmp(worldname, "Unnamed server") == 0) {
  653. cout << "LoginServer.ini: server unnamed, disabling uplink" << endl;
  654. fclose (f);
  655. return false;
  656. }
  657. */
  658. fclose(f);
  659. f=fopen (MAIN_INI_FILE, "r");
  660. do {
  661. if (fgets (buf, 200, f) == NULL || feof(f))
  662. {
  663. LogWrite(INIT__ERROR, 0, "Init", "[WorldServer] block not found in %s", MAIN_INI_FILE);
  664. fclose (f);
  665. return true;
  666. }
  667. }
  668. while (strncasecmp (buf, "[WorldServer]\n", 14) != 0 && strncasecmp (buf, "[WorldServer]\r\n", 15) != 0);
  669. while (!feof (f))
  670. {
  671. #ifdef WIN32
  672. if (fscanf (f, "%[^=]=%[^\n]\r\n", type, buf) == 2)
  673. #else
  674. if (fscanf (f, "%[^=]=%[^\r\n]\n", type, buf) == 2)
  675. #endif
  676. {
  677. if (!strcasecmp(type, "Defaultstatus")) {
  678. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  679. DEFAULTSTATUS = atoi(buf);
  680. }
  681. }
  682. }
  683. }
  684. fclose (f);
  685. LogWrite(INIT__DEBUG, 0, "Init", "%s read...", MAIN_INI_FILE);
  686. LoginServerInfo=1;
  687. return true;
  688. }
  689. char* NetConnection::GetLoginInfo(int16* oPort) {
  690. if (oPort == 0)
  691. return 0;
  692. if (loginaddress[0][0] == 0)
  693. return 0;
  694. int8 tmp[3] = { 0, 0, 0 };
  695. int8 count = 0;
  696. for (int i=0; i<3; i++) {
  697. if (loginaddress[i][0])
  698. tmp[count++] = i;
  699. }
  700. int x = rand() % count;
  701. *oPort = loginport[tmp[x]];
  702. return loginaddress[tmp[x]];
  703. }
  704. void UpdateWindowTitle(char* iNewTitle) {
  705. char tmp[500];
  706. if (iNewTitle) {
  707. snprintf(tmp, sizeof(tmp), "World: %s", iNewTitle);
  708. }
  709. else {
  710. string servername = net.GetWorldName();
  711. snprintf(tmp, sizeof(tmp), "%s (%s), Version: %s: %i Clients(s) in %i Zones(s)", EQ2EMU_MODULE, servername.c_str(), CURRENT_VERSION, numclients, numzones);
  712. }
  713. // Zero terminate ([max - 1] = 0) the string to prevent a warning
  714. tmp[499] = 0;
  715. #ifdef WIN32
  716. SetConsoleTitle(tmp);
  717. #else
  718. printf("%c]0;%s%c", '\033', tmp, '\007');
  719. #endif
  720. }
  721. ZoneAuthRequest::ZoneAuthRequest(int32 account_id, char* name, int32 access_key) {
  722. accountid = account_id;
  723. character_name = string(name);
  724. accesskey = access_key;
  725. timestamp = Timer::GetUnixTimeStamp();
  726. firstlogin = false;
  727. }
  728. ZoneAuthRequest::~ZoneAuthRequest ( )
  729. {
  730. }
  731. void ZoneAuth::AddAuth(ZoneAuthRequest *zar) {
  732. LogWrite(NET__DEBUG, 0, "Net", "AddAuth: %u Key: %u", zar->GetAccountID(), zar->GetAccessKey());
  733. list.Insert(zar);
  734. }
  735. ZoneAuthRequest* ZoneAuth::GetAuth(int32 account_id, int32 access_key) {
  736. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  737. iterator.Reset();
  738. while(iterator.MoreElements()) {
  739. if (iterator.GetData()->GetAccountID() == account_id && iterator.GetData()->GetAccessKey() == access_key) {
  740. ZoneAuthRequest* tmp = iterator.GetData();
  741. return tmp;
  742. }
  743. iterator.Advance();
  744. }
  745. return 0;
  746. }
  747. void ZoneAuth::PurgeInactiveAuth() {
  748. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  749. iterator.Reset();
  750. int32 current_time = Timer::GetUnixTimeStamp();
  751. while(iterator.MoreElements()) {
  752. if ((iterator.GetData()->GetTimeStamp()+60) < current_time) {
  753. iterator.RemoveCurrent();
  754. }
  755. iterator.Advance();
  756. }
  757. }
  758. void ZoneAuth::RemoveAuth(ZoneAuthRequest *zar) {
  759. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  760. iterator.Reset();
  761. while(iterator.MoreElements()) {
  762. if (iterator.GetData() == zar) {
  763. iterator.RemoveCurrent();
  764. break;
  765. }
  766. iterator.Advance();
  767. }
  768. }
  769. void NetConnection::WelcomeHeader()
  770. {
  771. #ifdef _WIN32
  772. HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
  773. SetConsoleTextAttribute(console, FOREGROUND_WHITE_BOLD);
  774. #endif
  775. printf("Module: %s, Version: %s", EQ2EMU_MODULE, CURRENT_VERSION);
  776. #ifdef _WIN32
  777. SetConsoleTextAttribute(console, FOREGROUND_YELLOW_BOLD);
  778. #endif
  779. printf("\n\nCopyright (C) 2007-2022 EQ2Emulator. https://www.eq2emu.com \n\n");
  780. printf("EQ2Emulator is free software: you can redistribute it and/or modify\n");
  781. printf("it under the terms of the GNU General Public License as published by\n");
  782. printf("the Free Software Foundation, either version 3 of the License, or\n");
  783. printf("(at your option) any later version.\n\n");
  784. printf("EQ2Emulator is distributed in the hope that it will be useful,\n");
  785. printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
  786. printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
  787. printf("GNU General Public License for more details.\n\n");
  788. #ifdef _WIN32
  789. SetConsoleTextAttribute(console, FOREGROUND_GREEN_BOLD);
  790. #endif
  791. printf(" /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ \n");
  792. printf("| $$_____/ /$$__ $$ /$$__ $$| $$_____/ \n");
  793. printf("| $$ | $$ \\ $$|__/ \\ $$| $$ /$$$$$$/$$$$ /$$ /$$\n");
  794. printf("| $$$$$ | $$ | $$ /$$$$$$/| $$$$$ | $$_ $$_ $$| $$ | $$\n");
  795. printf("| $$__/ | $$ | $$ /$$____/ | $$__/ | $$ \\ $$ \\ $$| $$ | $$\n");
  796. printf("| $$ | $$/$$ $$| $$ | $$ | $$ | $$ | $$| $$ | $$\n");
  797. printf("| $$$$$$$$| $$$$$$/| $$$$$$$$| $$$$$$$$| $$ | $$ | $$| $$$$$$/\n");
  798. printf("|________/ \\____ $$$|________/|________/|__/ |__/ |__/ \\______/ \n");
  799. printf(" \\__/ \n\n");
  800. #ifdef _WIN32
  801. SetConsoleTextAttribute(console, FOREGROUND_MAGENTA_BOLD);
  802. #endif
  803. printf(" Website : https://eq2emu.com \n");
  804. printf(" Wiki : https://wiki.eq2emu.com \n");
  805. printf(" Git : https://git.eq2emu.com \n");
  806. printf(" Discord : https://discord.gg/5Cavm9NYQf \n\n");
  807. #ifdef _WIN32
  808. SetConsoleTextAttribute(console, FOREGROUND_WHITE_BOLD);
  809. #endif
  810. printf("For more detailed logging, modify 'Level' param the log_config.xml file.\n\n");
  811. #ifdef _WIN32
  812. SetConsoleTextAttribute(console, FOREGROUND_WHITE);
  813. #endif
  814. fflush(stdout);
  815. }