net.cpp 30 KB

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