net.cpp 29 KB

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