net.cpp 28 KB

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