net.cpp 30 KB

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