net.cpp 33 KB

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