net.cpp 30 KB

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