net.cpp 30 KB

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