9
3

net.cpp 30 KB

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