net.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. // JA temp logger
  209. LogWrite(MISC__TODO, 0, "Reformat", "JA: This is as far as I got reformatting the console logs.");
  210. if (!threadedLoad) {
  211. // JA: Load all Item info
  212. LogWrite(ITEM__INFO, 0, "Items", "Loading Items...");
  213. database.LoadItemList();
  214. MasterItemList::ResetUniqueID(database.LoadNextUniqueItemID());
  215. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spells...");
  216. database.LoadSpells();
  217. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spell Errors...");
  218. database.LoadSpellErrors();
  219. // Jabantiz: Load traits
  220. LogWrite(WORLD__INFO, 0, "Traits", "Loading Traits...");
  221. database.LoadTraits();
  222. // JA: Load all Quest info
  223. LogWrite(QUEST__INFO, 0, "Quests", "Loading Quests...");
  224. database.LoadQuests();
  225. LogWrite(COLLECTION__INFO, 0, "Collect", "Loading Collections...");
  226. database.LoadCollections();
  227. LogWrite(MISC__TODO, 1, "TODO", "TODO loading achievements\n\t(%s, function: %s, line #: %i)", __FILE__, __FUNCTION__, __LINE__);
  228. //LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Loading Achievements...");
  229. //database.LoadAchievements();
  230. //master_achievement_list.CreateMasterAchievementListPacket();
  231. LogWrite(MERCHANT__INFO, 0, "Merchants", "Loading Merchants...");
  232. database.LoadMerchantInformation();
  233. }
  234. LogWrite(GUILD__INFO, 0, "Guilds", "Loading Guilds...");
  235. database.LoadGuilds();
  236. LogWrite(TRADESKILL__INFO, 0, "Recipes", "Loading Recipe Books...");
  237. database.LoadRecipeBooks();
  238. LogWrite(TRADESKILL__INFO, 0, "Recipes", "Loading Recipes...");
  239. database.LoadRecipes();
  240. LogWrite(TRADESKILL__INFO, 0, "Tradeskills", "Loading Tradeskill Events...");
  241. database.LoadTradeskillEvents();
  242. LogWrite(SPELL__INFO, 0, "AA", "Loading Alternate Advancements...");
  243. database.LoadAltAdvancements();
  244. LogWrite(SPELL__INFO, 0, "AA", "Loading AA Tree Nodes...");
  245. database.LoadTreeNodes();
  246. LogWrite(WORLD__INFO, 0, "Titles", "Loading Titles...");
  247. database.LoadTitles();
  248. LogWrite(WORLD__INFO, 0, "Languages", "Loading Languages...");
  249. database.LoadLanguages();
  250. LogWrite(CHAT__INFO, 0, "Chat", "Loading channels...");
  251. database.LoadChannels();
  252. LogWrite(LUA__INFO, 0, "LUA", "Loading Spawn Scripts...");
  253. database.LoadSpawnScriptData();
  254. LogWrite(LUA__INFO, 0, "LUA", "Loading Zone Scripts...");
  255. database.LoadZoneScriptData();
  256. LogWrite(WORLD__INFO, 0, "World", "Loading House Zone Data...");
  257. database.LoadHouseZones();
  258. database.LoadPlayerHouses();
  259. LogWrite(WORLD__INFO, 0, "World", "Loading Heroic OP Data...");
  260. database.LoadHOStarters();
  261. database.LoadHOWheel();
  262. LogWrite(WORLD__INFO, 0, "World", "Loading Race Types Data...");
  263. database.LoadRaceTypes();
  264. LogWrite(WORLD__INFO, 0, "World", "Loading Transmuting Data...");
  265. database.LoadTransmuting();
  266. LogWrite(WORLD__INFO, 0, "World", "Loading Chest Trap Data...");
  267. database.LoadChestTraps();
  268. LogWrite(WORLD__INFO, 0, "World", "Loading NPC Spells...");
  269. database.LoadNPCSpells();
  270. if (threadedLoad) {
  271. LogWrite(WORLD__INFO, 0, "World", "Waiting for load threads to finish.");
  272. while (!world.items_loaded || !world.spells_loaded /*|| !world.achievments_loaded*/)
  273. Sleep(10);
  274. LogWrite(WORLD__INFO, 0, "World", "Load threads finished.");
  275. }
  276. LogWrite(WORLD__INFO, 0, "World", "Total World startup time: %u seconds.", Timer::GetUnixTimeStamp() - t_total);
  277. int ret_code = 0;
  278. if (eqsf.Open(net.GetWorldPort())) {
  279. if (strlen(net.GetWorldAddress()) == 0)
  280. LogWrite(NET__INFO, 0, "Net", "World server listening on port %i", net.GetWorldPort());
  281. else
  282. LogWrite(NET__INFO, 0, "Net", "World server listening on: %s:%i", net.GetWorldAddress(), net.GetWorldPort());
  283. if(strlen(net.GetInternalWorldAddress())>0)
  284. LogWrite(NET__INFO, 0, "Net", "World server listening on: %s:%i", net.GetInternalWorldAddress(), net.GetWorldPort());
  285. }
  286. else {
  287. LogWrite(NET__ERROR, 0, "Net", "Failed to open port %i.", net.GetWorldPort());
  288. ret_code = 1;
  289. }
  290. Timer* TimeoutTimer = 0;
  291. if (ret_code == 0) {
  292. Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect
  293. InterserverTimer.Trigger();
  294. TimeoutTimer = new Timer(5000);
  295. TimeoutTimer->Start();
  296. EQStream* eqs = 0;
  297. UpdateWindowTitle(0);
  298. LogWrite(ZONE__INFO, 0, "Zone", "Starting static zones...");
  299. database.LoadSpecialZones();
  300. map<EQStream*, int32> connecting_clients;
  301. map<EQStream*, int32>::iterator cc_itr;
  302. LogWrite(WORLD__DEBUG, 0, "Thread", "Starting console command thread...");
  303. #ifdef WIN32
  304. _beginthread(EQ2ConsoleListener, 0, NULL);
  305. #else
  306. /*pthread_t thread;
  307. pthread_create(&thread, NULL, &EQ2ConsoleListener, NULL);
  308. pthread_detach(thread);*/
  309. #endif
  310. //
  311. // just before starting loops, announce how to get console help (only to windows)
  312. #ifdef WIN32
  313. LogWrite(WORLD__INFO, 0, "Console", "Type 'help' or '?' and press enter for menu options.");
  314. #endif
  315. std::chrono::time_point<std::chrono::system_clock> frame_prev = std::chrono::system_clock::now();
  316. while (RunLoops) {
  317. Timer::SetCurrentTime();
  318. std::chrono::time_point<std::chrono::system_clock> frame_now = std::chrono::system_clock::now();
  319. frame_time = std::chrono::duration_cast<std::chrono::duration<double>>(frame_now - frame_prev).count();
  320. frame_prev = frame_now;
  321. #ifndef NO_CATCH
  322. try
  323. {
  324. #endif
  325. while ((eqs = eqsf.Pop())) {
  326. struct in_addr in;
  327. in.s_addr = eqs->GetRemoteIP();
  328. LogWrite(NET__DEBUG, 0, "Net", "New client from ip: %s port: %i", inet_ntoa(in), ntohs(eqs->GetRemotePort()));
  329. // JA: Check for BannedIPs
  330. if (rule_manager.GetGlobalRule(R_World, UseBannedIPsTable)->GetInt8() == 1)
  331. {
  332. LogWrite(WORLD__DEBUG, 0, "World", "Checking inbound connection %s against BannedIPs table", inet_ntoa(in));
  333. if (database.CheckBannedIPs(inet_ntoa(in)))
  334. {
  335. LogWrite(WORLD__DEBUG, 0, "World", "Connection from %s FAILED banned IPs check. Closing connection.", inet_ntoa(in));
  336. eqs->Close(); // JA: If the inbound IP is on the banned table, close the EQStream.
  337. }
  338. }
  339. if (eqs && eqs->CheckActive() && client_list.ContainsStream(eqs) == false) {
  340. LogWrite(NET__DEBUG, 0, "Net", "Adding new client...");
  341. Client* client = new Client(eqs);
  342. client_list.Add(client);
  343. }
  344. else if (eqs && !client_list.ContainsStream(eqs)) {
  345. LogWrite(NET__DEBUG, 0, "Net", "Adding client to waiting list...");
  346. connecting_clients[eqs] = Timer::GetCurrentTime2();
  347. }
  348. }
  349. if (connecting_clients.size() > 0) {
  350. for (cc_itr = connecting_clients.begin(); cc_itr != connecting_clients.end(); cc_itr++) {
  351. if (cc_itr->first && cc_itr->first->CheckActive() && client_list.ContainsStream(cc_itr->first) == false) {
  352. LogWrite(NET__DEBUG, 0, "Net", "Removing client from waiting list...");
  353. Client* client = new Client(cc_itr->first);
  354. client_list.Add(client);
  355. connecting_clients.erase(cc_itr);
  356. break;
  357. }
  358. else if (Timer::GetCurrentTime2() >= (cc_itr->second + 10000)) {
  359. connecting_clients.erase(cc_itr);
  360. break;
  361. }
  362. }
  363. }
  364. world.Process();
  365. client_list.Process();
  366. loginserver.Process();
  367. if (TimeoutTimer->Check()) {
  368. eqsf.CheckTimeout();
  369. }
  370. if (InterserverTimer.Check()) {
  371. InterserverTimer.Start();
  372. database.ping();
  373. database.PingNewDB();
  374. database.PingAsyncDatabase();
  375. if (net.LoginServerInfo && loginserver.Connected() == false && loginserver.CanReconnect()) {
  376. LogWrite(WORLD__DEBUG, 0, "Thread", "Starting autoinit loginserver thread...");
  377. #ifdef WIN32
  378. _beginthread(AutoInitLoginServer, 0, NULL);
  379. #else
  380. pthread_t thread;
  381. pthread_create(&thread, NULL, &AutoInitLoginServer, NULL);
  382. pthread_detach(thread);
  383. #endif
  384. }
  385. }
  386. #ifndef NO_CATCH
  387. }
  388. catch (...) {
  389. LogWrite(WORLD__ERROR, 0, "World", "Exception caught in net main loop!");
  390. }
  391. #endif
  392. if (numclients == 0) {
  393. Sleep(10);
  394. continue;
  395. }
  396. Sleep(1);
  397. }
  398. }
  399. LogWrite(WORLD__DEBUG, 0, "World", "The world is ending!");
  400. LogWrite(WORLD__DEBUG, 0, "World", "Shutting down zones...");
  401. zone_list.ShutDownZones();
  402. LogWrite(WORLD__DEBUG, 0, "World", "Shutting down LUA interface...");
  403. safe_delete(lua_interface);
  404. safe_delete(TimeoutTimer);
  405. eqsf.Close();
  406. map<int16, OpcodeManager*>::iterator opcode_itr;
  407. for(opcode_itr=EQOpcodeManager.begin();opcode_itr!=EQOpcodeManager.end();opcode_itr++){
  408. safe_delete(opcode_itr->second);
  409. }
  410. CheckEQEMuErrorAndPause();
  411. #ifdef PROFILER
  412. PROFILER_UPDATE();
  413. PROFILER_OUTPUT();
  414. #endif
  415. LogWrite(WORLD__INFO, 0, "World", "Exiting... we hope you enjoyed your flight.");
  416. LogStop();
  417. return ret_code;
  418. }
  419. ThreadReturnType ItemLoad (void* tmp)
  420. {
  421. LogWrite(WORLD__WARNING, 0, "Thread", "Item Loading Thread started.");
  422. #ifdef WIN32
  423. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  424. #endif
  425. if (tmp == 0) {
  426. ThrowError("ItemLoad(): tmp = 0!");
  427. THREAD_RETURN(NULL);
  428. }
  429. World* world = (World*) tmp;
  430. WorldDatabase db;
  431. db.Init();
  432. db.ConnectNewDatabase();
  433. LogWrite(ITEM__INFO, 0, "Items", "Loading Items...");
  434. db.LoadItemList();
  435. MasterItemList::ResetUniqueID(db.LoadNextUniqueItemID());
  436. // Relies on the item list so needs to be in the item thread
  437. LogWrite(COLLECTION__INFO, 0, "Collect", "Loading Collections...");
  438. db.LoadCollections();
  439. LogWrite(MERCHANT__INFO, 0, "Merchants", "Loading Merchants...");
  440. db.LoadMerchantInformation();
  441. LogWrite(QUEST__INFO, 0, "Quests", "Loading Quests...");
  442. db.LoadQuests();
  443. world->items_loaded = true;
  444. LogWrite(WORLD__WARNING, 0, "Thread", "Item Loading Thread completed.");
  445. mysql_thread_end();
  446. THREAD_RETURN(NULL);
  447. }
  448. ThreadReturnType SpellLoad (void* tmp)
  449. {
  450. LogWrite(WORLD__WARNING, 0, "Thread", "Spell Loading Thread started.");
  451. #ifdef WIN32
  452. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  453. #endif
  454. if (tmp == 0) {
  455. ThrowError("ItemLoad(): tmp = 0!");
  456. THREAD_RETURN(NULL);
  457. }
  458. World* world = (World*) tmp;
  459. WorldDatabase db;
  460. db.Init();
  461. db.ConnectNewDatabase();
  462. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spells...");
  463. db.LoadSpells();
  464. LogWrite(SPELL__INFO, 0, "Spells", "Loading Spell Errors...");
  465. db.LoadSpellErrors();
  466. LogWrite(WORLD__INFO, 0, "Traits", "Loading Traits...");
  467. db.LoadTraits();
  468. world->spells_loaded = true;
  469. LogWrite(WORLD__WARNING, 0, "Thread", "Spell Loading Thread completed.");
  470. mysql_thread_end();
  471. THREAD_RETURN(NULL);
  472. }
  473. ThreadReturnType AchievmentLoad (void* tmp)
  474. {
  475. LogWrite(WORLD__WARNING, 0, "Thread", "Achievement Loading Thread started.");
  476. #ifdef WIN32
  477. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);
  478. #endif
  479. if (tmp == 0) {
  480. ThrowError("ItemLoad(): tmp = 0!");
  481. THREAD_RETURN(NULL);
  482. }
  483. World* world = (World*) tmp;
  484. WorldDatabase db;
  485. db.Init();
  486. db.ConnectNewDatabase();
  487. LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Loading Achievements...");
  488. int32 t_now = Timer::GetUnixTimeStamp();
  489. db.LoadAchievements();
  490. master_achievement_list.CreateMasterAchievementListPacket();
  491. LogWrite(ACHIEVEMENT__INFO, 0, "Achievements", "Achievements loaded (took %u seconds)", Timer::GetUnixTimeStamp() - t_now);
  492. world->achievments_loaded = true;
  493. LogWrite(WORLD__WARNING, 0, "Thread", "Achievement Loading Thread completed.");
  494. mysql_thread_end();
  495. THREAD_RETURN(NULL);
  496. }
  497. ThreadReturnType EQ2ConsoleListener(void* tmp)
  498. {
  499. char cmd[300];
  500. size_t i = 0;
  501. size_t len;
  502. while( RunLoops )
  503. {
  504. // Read in single line from "stdin"
  505. memset( cmd, 0, sizeof( cmd ) );
  506. if( fgets( cmd, 300, stdin ) == NULL )
  507. continue;
  508. if( !RunLoops )
  509. break;
  510. len = strlen(cmd);
  511. for( i = 0; i < len; ++i )
  512. {
  513. if(cmd[i] == '\n' || cmd[i] == '\r')
  514. cmd[i] = '\0';
  515. }
  516. ProcessConsoleInput(cmd);
  517. }
  518. THREAD_RETURN(NULL);
  519. }
  520. #include <fstream>
  521. void CatchSignal(int sig_num) {
  522. // In rare cases this can be called after the log system is shut down causing a deadlock or crash
  523. // when the world shuts down, if this happens again comment out the LogWrite and uncomment the printf
  524. if (last_signal != sig_num){
  525. static Mutex lock;
  526. static std::ofstream signal_out;
  527. lock.lock();
  528. if (!signal_out.is_open())
  529. signal_out.open("signal_catching.log", ios::trunc);
  530. if (signal_out){
  531. signal_out << "Caught signal " << sig_num << "\n";
  532. signal_out.flush();
  533. }
  534. printf("Caught signal %i\n", sig_num);
  535. lock.unlock();
  536. last_signal = sig_num;
  537. RunLoops = false;
  538. }
  539. }
  540. bool NetConnection::ReadLoginINI() {
  541. char buf[201], type[201];
  542. int items[3] = {0, 0};
  543. FILE *f;
  544. if (!(f = fopen (MAIN_INI_FILE, "r"))) {
  545. LogWrite(INIT__ERROR, 0, "Init", "File '%s' could not be opened", MAIN_INI_FILE);
  546. return false;
  547. }
  548. do {
  549. if (fgets (buf, 200, f) == NULL || feof(f))
  550. {
  551. LogWrite(INIT__ERROR, 0, "Init", "[LoginServer] block not found in '%s'.", MAIN_INI_FILE);
  552. fclose (f);
  553. return false;
  554. }
  555. }
  556. while (strncasecmp (buf, "[LoginServer]\n", 14) != 0 && strncasecmp (buf, "[LoginServer]\r\n", 15) != 0);
  557. while (!feof (f))
  558. {
  559. #ifdef WIN32
  560. if (fscanf (f, "%[^=]=%[^\n]\r\n", type, buf) == 2)
  561. #else
  562. if (fscanf (f, "%[^=]=%[^\r\n]\n", type, buf) == 2)
  563. #endif
  564. {
  565. if (!strncasecmp(type, "[", 1)) {
  566. // new block after LoginServer, skip
  567. break;
  568. }
  569. if (!strncasecmp (type, "worldname", 9)) {
  570. snprintf(worldname, sizeof(worldname), "%s", buf);
  571. items[1] = 1;
  572. if(strlen(worldname)<4)
  573. LogWrite(INIT__ERROR, 0, "Init", "Invalid worldname, please edit LoginServer.ini. Server name must be at least 4 characters.");
  574. }
  575. if (!strncasecmp (type, "account", 7)) {
  576. strncpy(worldaccount, buf, 30);
  577. }
  578. if (!strncasecmp (type, "logstats", 8)) {
  579. if (strcasecmp(buf, "true") == 0 || (buf[0] == '1' && buf[1] == 0))
  580. net.UpdateStats = true;
  581. }
  582. if (!strncasecmp (type, "password", 8)) {
  583. strncpy (worldpassword, buf, 30);
  584. for(int i=strlen(worldpassword);i>=0;i--){
  585. if(worldpassword[i] == ' ' || worldpassword[i] == '\n' || worldpassword[i] == '\t' || worldpassword[i] == '\r')
  586. worldpassword[i] = '\0';
  587. }
  588. }
  589. if (!strncasecmp (type, "locked", 6)) {
  590. if (strcasecmp(buf, "true") == 0 || (buf[0] == '1' && buf[1] == 0))
  591. world_locked = true;
  592. }
  593. if (!strncasecmp (type, "worldaddress", 12)) {
  594. if (strlen(buf) >= 3) {
  595. strncpy (worldaddress, buf, 250);
  596. }
  597. }
  598. if (!strncasecmp (type, "internalworldaddress", 20)) {
  599. if (strlen(buf) >= 3) {
  600. strncpy(internalworldaddress, buf, 20);
  601. }
  602. }
  603. if (!strncasecmp (type, "worldport", 9)) {
  604. if(Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF)
  605. worldport = atoi(buf);
  606. }
  607. if ((!strcasecmp (type, "loginserver")) || (!strcasecmp (type, "loginserver1"))) {
  608. strncpy (loginaddress[0], buf, 100);
  609. items[0] = 1;
  610. }
  611. if ((!strcasecmp(type, "loginport")) || (!strcasecmp(type, "loginport1"))) {
  612. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  613. loginport[0] = atoi(buf);
  614. }
  615. }
  616. if (!strcasecmp (type, "loginserver2")) {
  617. strncpy (loginaddress[1], buf, 250);
  618. }
  619. if (!strcasecmp(type, "loginport2")) {
  620. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  621. loginport[1] = atoi(buf);
  622. }
  623. }
  624. if (!strcasecmp (type, "loginserver3")) {
  625. strncpy (loginaddress[2], buf, 250);
  626. }
  627. if (!strcasecmp(type, "loginport3")) {
  628. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  629. loginport[2] = atoi(buf);
  630. }
  631. }
  632. }
  633. }
  634. if (!items[0] || !items[1])
  635. {
  636. LogWrite(INIT__ERROR, 0, "Init", "Incomplete LoginServer.INI file.");
  637. fclose (f);
  638. return false;
  639. }
  640. /*
  641. if (strcasecmp(worldname, "Unnamed server") == 0) {
  642. cout << "LoginServer.ini: server unnamed, disabling uplink" << endl;
  643. fclose (f);
  644. return false;
  645. }
  646. */
  647. fclose(f);
  648. f=fopen (MAIN_INI_FILE, "r");
  649. do {
  650. if (fgets (buf, 200, f) == NULL || feof(f))
  651. {
  652. LogWrite(INIT__ERROR, 0, "Init", "[WorldServer] block not found in %s", MAIN_INI_FILE);
  653. fclose (f);
  654. return true;
  655. }
  656. }
  657. while (strncasecmp (buf, "[WorldServer]\n", 14) != 0 && strncasecmp (buf, "[WorldServer]\r\n", 15) != 0);
  658. while (!feof (f))
  659. {
  660. #ifdef WIN32
  661. if (fscanf (f, "%[^=]=%[^\n]\r\n", type, buf) == 2)
  662. #else
  663. if (fscanf (f, "%[^=]=%[^\r\n]\n", type, buf) == 2)
  664. #endif
  665. {
  666. if (!strcasecmp(type, "Defaultstatus")) {
  667. if (Seperator::IsNumber(buf) && atoi(buf) > 0 && atoi(buf) < 0xFFFF) {
  668. DEFAULTSTATUS = atoi(buf);
  669. }
  670. }
  671. }
  672. }
  673. fclose (f);
  674. LogWrite(INIT__DEBUG, 0, "Init", "%s read...", MAIN_INI_FILE);
  675. LoginServerInfo=1;
  676. return true;
  677. }
  678. char* NetConnection::GetLoginInfo(int16* oPort) {
  679. if (oPort == 0)
  680. return 0;
  681. if (loginaddress[0][0] == 0)
  682. return 0;
  683. int8 tmp[3] = { 0, 0, 0 };
  684. int8 count = 0;
  685. for (int i=0; i<3; i++) {
  686. if (loginaddress[i][0])
  687. tmp[count++] = i;
  688. }
  689. int x = rand() % count;
  690. *oPort = loginport[tmp[x]];
  691. return loginaddress[tmp[x]];
  692. }
  693. void UpdateWindowTitle(char* iNewTitle) {
  694. char tmp[500];
  695. if (iNewTitle) {
  696. snprintf(tmp, sizeof(tmp), "World: %s", iNewTitle);
  697. }
  698. else {
  699. string servername = net.GetWorldName();
  700. snprintf(tmp, sizeof(tmp), "%s (%s), Version: %s: %i Clients(s) in %i Zones(s)", EQ2EMU_MODULE, servername.c_str(), CURRENT_VERSION, numclients, numzones);
  701. }
  702. // Zero terminate ([max - 1] = 0) the string to prevent a warning
  703. tmp[499] = 0;
  704. #ifdef WIN32
  705. SetConsoleTitle(tmp);
  706. #else
  707. printf("%c]0;%s%c", '\033', tmp, '\007');
  708. #endif
  709. }
  710. ZoneAuthRequest::ZoneAuthRequest(int32 account_id, char* name, int32 access_key) {
  711. accountid = account_id;
  712. character_name = string(name);
  713. accesskey = access_key;
  714. timestamp = Timer::GetUnixTimeStamp();
  715. firstlogin = false;
  716. }
  717. ZoneAuthRequest::~ZoneAuthRequest ( )
  718. {
  719. }
  720. void ZoneAuth::AddAuth(ZoneAuthRequest *zar) {
  721. LogWrite(NET__DEBUG, 0, "Net", "AddAuth: %u Key: %u", zar->GetAccountID(), zar->GetAccessKey());
  722. list.Insert(zar);
  723. }
  724. ZoneAuthRequest* ZoneAuth::GetAuth(int32 account_id, int32 access_key) {
  725. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  726. iterator.Reset();
  727. while(iterator.MoreElements()) {
  728. if (iterator.GetData()->GetAccountID() == account_id && iterator.GetData()->GetAccessKey() == access_key) {
  729. ZoneAuthRequest* tmp = iterator.GetData();
  730. return tmp;
  731. }
  732. iterator.Advance();
  733. }
  734. return 0;
  735. }
  736. void ZoneAuth::PurgeInactiveAuth() {
  737. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  738. iterator.Reset();
  739. int32 current_time = Timer::GetUnixTimeStamp();
  740. while(iterator.MoreElements()) {
  741. if ((iterator.GetData()->GetTimeStamp()+60) < current_time) {
  742. iterator.RemoveCurrent();
  743. }
  744. iterator.Advance();
  745. }
  746. }
  747. void ZoneAuth::RemoveAuth(ZoneAuthRequest *zar) {
  748. LinkedListIterator<ZoneAuthRequest*> iterator(list);
  749. iterator.Reset();
  750. while(iterator.MoreElements()) {
  751. if (iterator.GetData() == zar) {
  752. iterator.RemoveCurrent();
  753. break;
  754. }
  755. iterator.Advance();
  756. }
  757. }
  758. void NetConnection::WelcomeHeader()
  759. {
  760. #ifdef _WIN32
  761. HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
  762. SetConsoleTextAttribute(console, FOREGROUND_WHITE_BOLD);
  763. #endif
  764. printf("Module: %s, Version: %s", EQ2EMU_MODULE, CURRENT_VERSION);
  765. #ifdef _WIN32
  766. SetConsoleTextAttribute(console, FOREGROUND_YELLOW_BOLD);
  767. #endif
  768. printf("\n\nCopyright (C) 2007-2022 EQ2Emulator. https://www.eq2emu.com \n\n");
  769. printf("EQ2Emulator is free software: you can redistribute it and/or modify\n");
  770. printf("it under the terms of the GNU General Public License as published by\n");
  771. printf("the Free Software Foundation, either version 3 of the License, or\n");
  772. printf("(at your option) any later version.\n\n");
  773. printf("EQ2Emulator is distributed in the hope that it will be useful,\n");
  774. printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
  775. printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
  776. printf("GNU General Public License for more details.\n\n");
  777. #ifdef _WIN32
  778. SetConsoleTextAttribute(console, FOREGROUND_GREEN_BOLD);
  779. #endif
  780. printf(" /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ \n");
  781. printf("| $$_____/ /$$__ $$ /$$__ $$| $$_____/ \n");
  782. printf("| $$ | $$ \\ $$|__/ \\ $$| $$ /$$$$$$/$$$$ /$$ /$$\n");
  783. printf("| $$$$$ | $$ | $$ /$$$$$$/| $$$$$ | $$_ $$_ $$| $$ | $$\n");
  784. printf("| $$__/ | $$ | $$ /$$____/ | $$__/ | $$ \\ $$ \\ $$| $$ | $$\n");
  785. printf("| $$ | $$/$$ $$| $$ | $$ | $$ | $$ | $$| $$ | $$\n");
  786. printf("| $$$$$$$$| $$$$$$/| $$$$$$$$| $$$$$$$$| $$ | $$ | $$| $$$$$$/\n");
  787. printf("|________/ \\____ $$$|________/|________/|__/ |__/ |__/ \\______/ \n");
  788. printf(" \\__/ \n\n");
  789. #ifdef _WIN32
  790. SetConsoleTextAttribute(console, FOREGROUND_MAGENTA_BOLD);
  791. #endif
  792. printf(" Website : https://eq2emu.com \n");
  793. printf(" Wiki : https://wiki.eq2emu.com \n");
  794. printf(" Git : https://git.eq2emu.com \n");
  795. printf(" Discord : https://discord.gg/5Cavm9NYQf \n\n");
  796. #ifdef _WIN32
  797. SetConsoleTextAttribute(console, FOREGROUND_WHITE_BOLD);
  798. #endif
  799. printf("For more detailed logging, modify 'Level' param the log_config.xml file.\n\n");
  800. #ifdef _WIN32
  801. SetConsoleTextAttribute(console, FOREGROUND_WHITE);
  802. #endif
  803. fflush(stdout);
  804. }