net.cpp 29 KB

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