diff options
| author | Shauren <shauren.trinity@gmail.com> | 2014-07-19 03:38:57 +0200 |
|---|---|---|
| committer | Shauren <shauren.trinity@gmail.com> | 2014-07-19 03:51:11 +0200 |
| commit | 909acdbac3223d8c788b1b5dc42b6dfab8b604ab (patch) | |
| tree | 2a0ade312aad77ca032015c6957a4a9005aa0b94 /src/server/worldserver | |
| parent | 5daf3d360686ea8ff2d97a48fca24f0bf42ef098 (diff) | |
| parent | 1866d8cc06e2b8c2722ccf69ee3f52ceda93bc27 (diff) | |
Merge remote-tracking branch 'origin/master' into 4.3.4
Conflicts:
src/server/authserver/Main.cpp
src/server/authserver/Realms/RealmList.cpp
src/server/authserver/Realms/RealmList.h
src/server/authserver/Server/AuthSession.cpp
src/server/authserver/Server/AuthSocket.h
src/server/authserver/Server/RealmAcceptor.h
src/server/game/Accounts/AccountMgr.h
src/server/game/Achievements/AchievementMgr.cpp
src/server/game/Achievements/AchievementMgr.h
src/server/game/Battlegrounds/ArenaTeamMgr.cpp
src/server/game/Conditions/ConditionMgr.cpp
src/server/game/DungeonFinding/LFGMgr.h
src/server/game/Entities/Object/Object.h
src/server/game/Entities/Player/Player.cpp
src/server/game/Entities/Player/Player.h
src/server/game/Entities/Unit/Unit.cpp
src/server/game/Handlers/BattleGroundHandler.cpp
src/server/game/Movement/Spline/MoveSplineFlag.h
src/server/game/Quests/QuestDef.cpp
src/server/game/Quests/QuestDef.h
src/server/game/Server/WorldSession.cpp
src/server/game/Server/WorldSession.h
src/server/game/Server/WorldSocket.cpp
src/server/game/Server/WorldSocket.h
src/server/game/Spells/Spell.cpp
src/server/scripts/Commands/cs_debug.cpp
src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp
src/server/scripts/Spells/spell_mage.cpp
src/server/scripts/Spells/spell_rogue.cpp
src/server/scripts/Spells/spell_shaman.cpp
src/server/scripts/Spells/spell_warrior.cpp
src/server/shared/Cryptography/BigNumber.h
src/server/worldserver/RemoteAccess/RASocket.cpp
src/server/worldserver/worldserver.conf.dist
Diffstat (limited to 'src/server/worldserver')
18 files changed, 833 insertions, 1449 deletions
diff --git a/src/server/worldserver/CMakeLists.txt b/src/server/worldserver/CMakeLists.txt index 2f4d557fec0..e48cbc9c7c7 100644 --- a/src/server/worldserver/CMakeLists.txt +++ b/src/server/worldserver/CMakeLists.txt @@ -11,7 +11,6 @@ file(GLOB_RECURSE sources_CommandLine CommandLine/*.cpp CommandLine/*.h) file(GLOB_RECURSE sources_RemoteAccess RemoteAccess/*.cpp RemoteAccess/*.h) file(GLOB_RECURSE sources_TCSoap TCSoap/*.cpp TCSoap/*.h) -file(GLOB_RECURSE sources_WorldThread WorldThread/*.cpp WorldThread/*.h) file(GLOB sources_localdir *.cpp *.h) if (USE_COREPCH) @@ -24,7 +23,6 @@ set(worldserver_SRCS ${sources_CommandLine} ${sources_RemoteAccess} ${sources_TCSoap} - ${sources_WorldThread} ${sources_localdir} ) @@ -62,6 +60,7 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic/LinkedReference ${CMAKE_SOURCE_DIR}/src/server/shared/Dynamic ${CMAKE_SOURCE_DIR}/src/server/shared/Logging + ${CMAKE_SOURCE_DIR}/src/server/shared/Networking ${CMAKE_SOURCE_DIR}/src/server/shared/Packets ${CMAKE_SOURCE_DIR}/src/server/shared/Threading ${CMAKE_SOURCE_DIR}/src/server/shared/Utilities @@ -139,8 +138,6 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/CommandLine ${CMAKE_CURRENT_SOURCE_DIR}/RemoteAccess ${CMAKE_CURRENT_SOURCE_DIR}/TCSoap - ${CMAKE_CURRENT_SOURCE_DIR}/WorldThread - ${ACE_INCLUDE_DIR} ${MYSQL_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR} ) @@ -175,11 +172,11 @@ target_link_libraries(worldserver ${JEMALLOC_LIBRARY} ${READLINE_LIBRARY} ${TERMCAP_LIBRARY} - ${ACE_LIBRARY} ${MYSQL_LIBRARY} ${OPENSSL_LIBRARIES} ${ZLIB_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} + ${Boost_LIBRARIES} ) if( WIN32 ) diff --git a/src/server/worldserver/CommandLine/CliRunnable.cpp b/src/server/worldserver/CommandLine/CliRunnable.cpp index ac46b218305..295e63c696b 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.cpp +++ b/src/server/worldserver/CommandLine/CliRunnable.cpp @@ -131,7 +131,7 @@ int kb_hit_return() #endif /// %Thread start -void CliRunnable::run() +void CliThread() { ///- Display the list of available CLI functions then beep //TC_LOG_INFO("server.worldserver", ""); diff --git a/src/server/worldserver/CommandLine/CliRunnable.h b/src/server/worldserver/CommandLine/CliRunnable.h index 5510173973e..7ed3a44995f 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.h +++ b/src/server/worldserver/CommandLine/CliRunnable.h @@ -23,12 +23,7 @@ #ifndef __CLIRUNNABLE_H #define __CLIRUNNABLE_H -/// Command Line Interface handling thread -class CliRunnable : public ACE_Based::Runnable -{ - public: - void run() override; -}; +void CliThread(); #endif diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index 75d9ca5145d..0c051eae37a 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -22,19 +22,38 @@ #include <openssl/opensslv.h> #include <openssl/crypto.h> -#include <ace/Version.h> +#include <boost/asio/io_service.hpp> +#include <boost/asio/deadline_timer.hpp> +#include <boost/program_options.hpp> #include "Common.h" -#include "Database/DatabaseEnv.h" +#include "DatabaseEnv.h" +#include "AsyncAcceptor.h" +#include "RASession.h" #include "Configuration/Config.h" +#include "OpenSSLCrypto.h" +#include "ProcessPriority.h" +#include "BigNumber.h" +#include "RealmList.h" +#include "World.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "ScriptMgr.h" +#include "OutdoorPvP/OutdoorPvPMgr.h" +#include "BattlegroundMgr.h" +#include "TCSoap.h" +#include "CliRunnable.h" +#include "SystemConfig.h" +#include "WorldSocket.h" -#include "Log.h" -#include "Master.h" +using namespace boost::program_options; #ifndef _TRINITY_CORE_CONFIG -# define _TRINITY_CORE_CONFIG "worldserver.conf" + #define _TRINITY_CORE_CONFIG "worldserver.conf" #endif +#define WORLD_SLEEP_CONST 50 + #ifdef _WIN32 #include "ServiceWin32.h" char serviceName[] = "worldserver"; @@ -49,104 +68,504 @@ char serviceDescription[] = "TrinityCore World of Warcraft emulator world servic int m_ServiceStatus = -1; #endif +boost::asio::io_service _ioService; +boost::asio::deadline_timer _freezeCheckTimer(_ioService); +uint32 _worldLoopCounter(0); +uint32 _lastChangeMsTime(0); +uint32 _maxCoreStuckTimeInMs(0); + WorldDatabaseWorkerPool WorldDatabase; ///< Accessor to the world database CharacterDatabaseWorkerPool CharacterDatabase; ///< Accessor to the character database LoginDatabaseWorkerPool LoginDatabase; ///< Accessor to the realm/login database - uint32 realmID; ///< Id of the realm -/// Print out the usage string for this program on the console. -void usage(const char* prog) +void SignalHandler(const boost::system::error_code& error, int signalNumber); +void FreezeDetectorHandler(const boost::system::error_code& error); +AsyncAcceptor<RASession>* StartRaSocketAcceptor(boost::asio::io_service& ioService); +bool StartDB(); +void StopDB(); +void WorldUpdateLoop(); +void ClearOnlineAccounts(); +variables_map GetConsoleArguments(int argc, char** argv, std::string& cfg_file, std::string& cfg_service); + +/// Launch the Trinity server +extern int main(int argc, char** argv) { - printf("Usage:\n"); - printf(" %s [<options>]\n", prog); - printf(" -c config_file use config_file as configuration file\n"); + std::string configFile = _TRINITY_CORE_CONFIG; + std::string configService; + + auto vm = GetConsoleArguments(argc, argv, configFile, configService); + // exit if help is enabled + if (vm.count("help")) + return 0; + +#ifdef _WIN32 + if (configService.compare("install") == 0) + return WinServiceInstall() == true ? 0 : 1; + else if (configService.compare("uninstall") == 0) + return WinServiceUninstall() == true ? 0 : 1; + else if (configService.compare("run") == 0) + WinServiceRun(); +#endif + + if (!sConfigMgr->LoadInitial(configFile)) + { + printf("Invalid or missing configuration file : %s\n", configFile.c_str()); + printf("Verify that the file exists and has \'[worldserver]' written in the top of the file!\n"); + return 1; + } + + if (sConfigMgr->GetBoolDefault("Log.Async.Enable", false)) + { + // If logs are supposed to be handled async then we need to pass the io_service into the Log singleton + Log::instance(&_ioService); + } + + TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", _FULLVERSION); + TC_LOG_INFO("server.worldserver", "<Ctrl-C> to stop.\n"); + TC_LOG_INFO("server.worldserver", " ______ __"); + TC_LOG_INFO("server.worldserver", "/\\__ _\\ __ __/\\ \\__"); + TC_LOG_INFO("server.worldserver", "\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); + TC_LOG_INFO("server.worldserver", " \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); + TC_LOG_INFO("server.worldserver", " \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); + TC_LOG_INFO("server.worldserver", " \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); + TC_LOG_INFO("server.worldserver", " \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); + TC_LOG_INFO("server.worldserver", " C O R E /\\___/"); + TC_LOG_INFO("server.worldserver", "http://TrinityCore.org \\/__/\n"); + TC_LOG_INFO("server.worldserver", "Using configuration file %s.", configFile.c_str()); + TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); + TC_LOG_INFO("server.worldserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + + OpenSSLCrypto::threadsSetup(); + + // Seed the OpenSSL's PRNG here. + // That way it won't auto-seed when calling BigNumber::SetRand and slow down the first world login + BigNumber seed; + seed.SetRand(16 * 8); + + /// worldserver PID file creation + std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); + if (!pidFile.empty()) + { + if (uint32 pid = CreatePIDFile(pidFile)) + TC_LOG_INFO("server.worldserver", "Daemon PID: %u\n", pid); + else + { + TC_LOG_ERROR("server.worldserver", "Cannot create PID file %s.\n", pidFile.c_str()); + return 1; + } + } + + // Set signal handlers (this must be done before starting io_service threads, because otherwise they would unblock and exit) + boost::asio::signal_set signals(_ioService, SIGINT, SIGTERM); + signals.async_wait(SignalHandler); + + // Start the Boost based thread pool + int numThreads = sConfigMgr->GetIntDefault("ThreadPool", 1); + std::vector<std::thread> threadPool; + + if (numThreads < 1) + numThreads = 1; + + for (int i = 0; i < numThreads; ++i) + threadPool.push_back(std::thread(boost::bind(&boost::asio::io_service::run, &_ioService))); + + // Set process priority according to configuration settings + SetProcessPriority("server.worldserver"); + + // Start the databases + if (!StartDB()) + return 1; + + // Set server offline (not connectable) + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = (flag & ~%u) | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, REALM_FLAG_INVALID, realmID); + + // Initialize the World + sWorld->SetInitialWorldSettings(); + + // Launch CliRunnable thread + std::thread* cliThread = nullptr; #ifdef _WIN32 - printf(" Running as service functions:\n"); - printf(" --service run as service\n"); - printf(" -s install install service\n"); - printf(" -s uninstall uninstall service\n"); + if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/) +#else + if (sConfigMgr->GetBoolDefault("Console.Enable", true)) #endif + { + cliThread = new std::thread(CliThread); + } + + // Start the Remote Access port (acceptor) if enabled + AsyncAcceptor<RASession>* raAcceptor = nullptr; + if (sConfigMgr->GetBoolDefault("Ra.Enable", false)) + raAcceptor = StartRaSocketAcceptor(_ioService); + + // Start soap serving thread if enabled + std::thread* soapThread = nullptr; + if (sConfigMgr->GetBoolDefault("SOAP.Enabled", false)) + { + soapThread = new std::thread(TCSoapThread, sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878))); + } + + // Launch the worldserver listener socket + uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD)); + std::string worldListener = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); + bool tcpNoDelay = sConfigMgr->GetBoolDefault("Network.TcpNodelay", true); + + AsyncAcceptor<WorldSocket> worldAcceptor(_ioService, worldListener, worldPort, tcpNoDelay); + + sScriptMgr->OnStartup(); + + // Set server online (allow connecting now) + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_INVALID, realmID); + + // Start the freeze check callback cycle in 5 seconds (cycle itself is 1 sec) + if (int coreStuckTime = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0)) + { + _maxCoreStuckTimeInMs = coreStuckTime * 1000; + _freezeCheckTimer.expires_from_now(boost::posix_time::seconds(5)); + _freezeCheckTimer.async_wait(FreezeDetectorHandler); + TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", coreStuckTime); + } + + TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon) ready...", _FULLVERSION); + + WorldUpdateLoop(); + + // Shutdown starts here + + _ioService.stop(); + + for (auto& thread : threadPool) + { + thread.join(); + } + + sScriptMgr->OnShutdown(); + + sWorld->KickAll(); // save and kick all players + sWorld->UpdateSessions(1); // real players unload required UpdateSessions call + + // unload battleground templates before different singletons destroyed + sBattlegroundMgr->DeleteAllBattlegrounds(); + + sMapMgr->UnloadAll(); // unload all grids (including locked in memory) + sObjectAccessor->UnloadAll(); // unload 'i_player2corpse' storage and remove from world + sScriptMgr->Unload(); + sOutdoorPvPMgr->Die(); + + // set server offline + LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realmID); + + // Clean up threads if any + if (soapThread != nullptr) + { + soapThread->join(); + delete soapThread; + } + + if (raAcceptor != nullptr) + delete raAcceptor; + + ///- Clean database before leaving + ClearOnlineAccounts(); + + StopDB(); + + TC_LOG_INFO("server.worldserver", "Halting process..."); + + if (cliThread != nullptr) + { +#ifdef _WIN32 + + // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API) + //_exit(1); + // send keyboard input to safely unblock the CLI thread + INPUT_RECORD b[4]; + HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); + b[0].EventType = KEY_EVENT; + b[0].Event.KeyEvent.bKeyDown = TRUE; + b[0].Event.KeyEvent.uChar.AsciiChar = 'X'; + b[0].Event.KeyEvent.wVirtualKeyCode = 'X'; + b[0].Event.KeyEvent.wRepeatCount = 1; + + b[1].EventType = KEY_EVENT; + b[1].Event.KeyEvent.bKeyDown = FALSE; + b[1].Event.KeyEvent.uChar.AsciiChar = 'X'; + b[1].Event.KeyEvent.wVirtualKeyCode = 'X'; + b[1].Event.KeyEvent.wRepeatCount = 1; + + b[2].EventType = KEY_EVENT; + b[2].Event.KeyEvent.bKeyDown = TRUE; + b[2].Event.KeyEvent.dwControlKeyState = 0; + b[2].Event.KeyEvent.uChar.AsciiChar = '\r'; + b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN; + b[2].Event.KeyEvent.wRepeatCount = 1; + b[2].Event.KeyEvent.wVirtualScanCode = 0x1c; + + b[3].EventType = KEY_EVENT; + b[3].Event.KeyEvent.bKeyDown = FALSE; + b[3].Event.KeyEvent.dwControlKeyState = 0; + b[3].Event.KeyEvent.uChar.AsciiChar = '\r'; + b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN; + b[3].Event.KeyEvent.wVirtualScanCode = 0x1c; + b[3].Event.KeyEvent.wRepeatCount = 1; + DWORD numb; + WriteConsoleInput(hStdIn, b, 4, &numb); +#endif + cliThread->join(); + delete cliThread; + } + + OpenSSLCrypto::threadsCleanup(); + + // 0 - normal shutdown + // 1 - shutdown at error + // 2 - restart command used, this code can be used by restarter for restart Trinityd + + return World::GetExitCode(); } -/// Launch the Trinity server -extern int main(int argc, char** argv) + +void WorldUpdateLoop() { - ///- Command line parsing to get the configuration file name - char const* cfg_file = _TRINITY_CORE_CONFIG; - int c = 1; - while (c < argc) + uint32 realCurrTime = 0; + uint32 realPrevTime = getMSTime(); + + uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST + + ///- While we have not World::m_stopEvent, update the world + while (!World::IsStopped()) { - if (!strcmp(argv[c], "-c")) + ++World::m_worldLoopCounter; + realCurrTime = getMSTime(); + + uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime); + + sWorld->Update(diff); + realPrevTime = realCurrTime; + + // diff (D0) include time of previous sleep (d0) + tick time (t0) + // we want that next d1 + t1 == WORLD_SLEEP_CONST + // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement + // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0 + if (diff <= WORLD_SLEEP_CONST + prevSleepTime) { - if (++c >= argc) - { - printf("Runtime-Error: -c option requires an input argument"); - usage(argv[0]); - return 1; - } - else - cfg_file = argv[c]; + prevSleepTime = WORLD_SLEEP_CONST + prevSleepTime - diff; + + std::this_thread::sleep_for(std::chrono::milliseconds(prevSleepTime)); } + else + prevSleepTime = 0; + +#ifdef _WIN32 + if (m_ServiceStatus == 0) + World::StopNow(SHUTDOWN_EXIT_CODE); + + while (m_ServiceStatus == 2) + Sleep(1000); +#endif + } +} - #ifdef _WIN32 - if (strcmp(argv[c], "-s") == 0) // Services +void SignalHandler(const boost::system::error_code& error, int signalNumber) +{ + if (!error) + { + switch (signalNumber) { - if (++c >= argc) - { - printf("Runtime-Error: -s option requires an input argument"); - usage(argv[0]); - return 1; - } - - if (strcmp(argv[c], "install") == 0) - { - if (WinServiceInstall()) - printf("Installing service\n"); - return 1; - } - else if (strcmp(argv[c], "uninstall") == 0) - { - if (WinServiceUninstall()) - printf("Uninstalling service\n"); - return 1; - } - else - { - printf("Runtime-Error: unsupported option %s", argv[c]); - usage(argv[0]); - return 1; - } + case SIGINT: + case SIGTERM: + World::StopNow(SHUTDOWN_EXIT_CODE); + break; } + } +} - if (strcmp(argv[c], "--service") == 0) - WinServiceRun(); - #endif - ++c; +void FreezeDetectorHandler(const boost::system::error_code& error) +{ + if (!error) + { + uint32 curtime = getMSTime(); + + uint32 worldLoopCounter = World::m_worldLoopCounter; + if (_worldLoopCounter != worldLoopCounter) + { + _lastChangeMsTime = curtime; + _worldLoopCounter = worldLoopCounter; + } + // possible freeze + else if (getMSTimeDiff(_lastChangeMsTime, curtime) > _maxCoreStuckTimeInMs) + { + TC_LOG_ERROR("server.worldserver", "World Thread hangs, kicking out server!"); + ASSERT(false); + } + + _freezeCheckTimer.expires_from_now(boost::posix_time::seconds(1)); + _freezeCheckTimer.async_wait(FreezeDetectorHandler); } +} - if (!sConfigMgr->LoadInitial(cfg_file)) +AsyncAcceptor<RASession>* StartRaSocketAcceptor(boost::asio::io_service& ioService) +{ + uint16 raPort = uint16(sConfigMgr->GetIntDefault("Ra.Port", 3443)); + std::string raListener = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0"); + + return new AsyncAcceptor<RASession>(ioService, raListener, raPort); +} + +/// Initialize connection to the databases +bool StartDB() +{ + MySQL::Library_Init(); + + std::string dbString; + uint8 asyncThreads, synchThreads; + + dbString = sConfigMgr->GetStringDefault("WorldDatabaseInfo", ""); + if (dbString.empty()) { - printf("Invalid or missing configuration file : %s\n", cfg_file); - printf("Verify that the file exists and has \'[worldserver]' written in the top of the file!\n"); - return 1; + TC_LOG_ERROR("server.worldserver", "World database not specified in configuration file"); + return false; } - TC_LOG_INFO("server.worldserver", "Using configuration file %s.", cfg_file); + asyncThreads = uint8(sConfigMgr->GetIntDefault("WorldDatabase.WorkerThreads", 1)); + if (asyncThreads < 1 || asyncThreads > 32) + { + TC_LOG_ERROR("server.worldserver", "World database: invalid number of worker threads specified. " + "Please pick a value between 1 and 32."); + return false; + } - TC_LOG_INFO("server.worldserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); - TC_LOG_INFO("server.worldserver", "Using ACE version: %s", ACE_VERSION); + synchThreads = uint8(sConfigMgr->GetIntDefault("WorldDatabase.SynchThreads", 1)); + ///- Initialize the world database + if (!WorldDatabase.Open(dbString, asyncThreads, synchThreads)) + { + TC_LOG_ERROR("server.worldserver", "Cannot connect to world database %s", dbString.c_str()); + return false; + } - ///- and run the 'Master' - /// @todo Why do we need this 'Master'? Can't all of this be in the Main as for Realmd? - int ret = sMaster->Run(); + ///- Get character database info from configuration file + dbString = sConfigMgr->GetStringDefault("CharacterDatabaseInfo", ""); + if (dbString.empty()) + { + TC_LOG_ERROR("server.worldserver", "Character database not specified in configuration file"); + return false; + } - // at sMaster return function exist with codes - // 0 - normal shutdown - // 1 - shutdown at error - // 2 - restart command used, this code can be used by restarter for restart Trinityd + asyncThreads = uint8(sConfigMgr->GetIntDefault("CharacterDatabase.WorkerThreads", 1)); + if (asyncThreads < 1 || asyncThreads > 32) + { + TC_LOG_ERROR("server.worldserver", "Character database: invalid number of worker threads specified. " + "Please pick a value between 1 and 32."); + return false; + } + + synchThreads = uint8(sConfigMgr->GetIntDefault("CharacterDatabase.SynchThreads", 2)); + + ///- Initialize the Character database + if (!CharacterDatabase.Open(dbString, asyncThreads, synchThreads)) + { + TC_LOG_ERROR("server.worldserver", "Cannot connect to Character database %s", dbString.c_str()); + return false; + } + + ///- Get login database info from configuration file + dbString = sConfigMgr->GetStringDefault("LoginDatabaseInfo", ""); + if (dbString.empty()) + { + TC_LOG_ERROR("server.worldserver", "Login database not specified in configuration file"); + return false; + } + + asyncThreads = uint8(sConfigMgr->GetIntDefault("LoginDatabase.WorkerThreads", 1)); + if (asyncThreads < 1 || asyncThreads > 32) + { + TC_LOG_ERROR("server.worldserver", "Login database: invalid number of worker threads specified. " + "Please pick a value between 1 and 32."); + return false; + } + + synchThreads = uint8(sConfigMgr->GetIntDefault("LoginDatabase.SynchThreads", 1)); + ///- Initialise the login database + if (!LoginDatabase.Open(dbString, asyncThreads, synchThreads)) + { + TC_LOG_ERROR("server.worldserver", "Cannot connect to login database %s", dbString.c_str()); + return false; + } + + ///- Get the realm Id from the configuration file + realmID = sConfigMgr->GetIntDefault("RealmID", 0); + if (!realmID) + { + TC_LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file"); + return false; + } + TC_LOG_INFO("server.worldserver", "Realm running as realm ID %d", realmID); + + ///- Clean the database before starting + ClearOnlineAccounts(); + + ///- Insert version info into DB + WorldDatabase.PExecute("UPDATE version SET core_version = '%s', core_revision = '%s'", _FULLVERSION, _HASH); // One-time query + + sWorld->LoadDBVersion(); - return ret; + TC_LOG_INFO("server.worldserver", "Using World DB: %s", sWorld->GetDBVersion()); + return true; +} + +void StopDB() +{ + CharacterDatabase.Close(); + WorldDatabase.Close(); + LoginDatabase.Close(); + + MySQL::Library_End(); +} + +/// Clear 'online' status for all accounts with characters in this realm +void ClearOnlineAccounts() +{ + // Reset online status for all accounts with characters on the current realm + LoginDatabase.DirectPExecute("UPDATE account SET online = 0 WHERE online > 0 AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = %d)", realmID); + + // Reset online status for all characters + CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0"); + + // Battleground instance ids reset at server restart + CharacterDatabase.DirectExecute("UPDATE character_battleground_data SET instanceId = 0"); } /// @} + +variables_map GetConsoleArguments(int argc, char** argv, std::string& configFile, std::string& configService) +{ + options_description all("Allowed options"); + all.add_options() + ("help,h", "print usage message") + ("config,c", value<std::string>(&configFile)->default_value(_TRINITY_CORE_CONFIG), "use <arg> as configuration file") + ; +#ifdef _WIN32 + options_description win("Windows platform specific options"); + win.add_options() + ("service,s", value<std::string>(&configService)->default_value(""), "Windows service options: [install | uninstall]") + ; + + all.add(win); +#endif + variables_map vm; + try + { + store(command_line_parser(argc, argv).options(all).allow_unregistered().run(), vm); + notify(vm); + } + catch (std::exception& e) { + std::cerr << e.what() << "\n"; + } + + if (vm.count("help")) { + std::cout << all << "\n"; + } + + return vm; +} diff --git a/src/server/worldserver/Master.cpp b/src/server/worldserver/Master.cpp deleted file mode 100644 index 6e4214603cb..00000000000 --- a/src/server/worldserver/Master.cpp +++ /dev/null @@ -1,508 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/** \file - \ingroup Trinityd -*/ - -#include <ace/Sig_Handler.h> - -#include "Common.h" -#include "SystemConfig.h" -#include "SignalHandler.h" -#include "World.h" -#include "WorldRunnable.h" -#include "WorldSocket.h" -#include "WorldSocketMgr.h" -#include "Configuration/Config.h" -#include "Database/DatabaseEnv.h" -#include "Database/DatabaseWorkerPool.h" - -#include "CliRunnable.h" -#include "Log.h" -#include "Master.h" -#include "RARunnable.h" -#include "TCSoap.h" -#include "Timer.h" -#include "Util.h" -#include "AuthSocket.h" -#include "RealmList.h" - -#include "BigNumber.h" -#include "OpenSSLCrypto.h" - -#ifdef _WIN32 -#include "ServiceWin32.h" -extern int m_ServiceStatus; -#endif - -#ifdef __linux__ -#include <sched.h> -#include <sys/resource.h> -#define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 -#endif - -/// Handle worldservers's termination signals -class WorldServerSignalHandler : public Trinity::SignalHandler -{ - public: - virtual void HandleSignal(int sigNum) - { - switch (sigNum) - { - case SIGINT: - World::StopNow(RESTART_EXIT_CODE); - break; - case SIGTERM: -#ifdef _WIN32 - case SIGBREAK: - if (m_ServiceStatus != 1) -#endif - World::StopNow(SHUTDOWN_EXIT_CODE); - break; - } - } -}; - -class FreezeDetectorRunnable : public ACE_Based::Runnable -{ -private: - uint32 _loops; - uint32 _lastChange; - uint32 _delaytime; -public: - FreezeDetectorRunnable() - { - _loops = 0; - _lastChange = 0; - _delaytime = 0; - } - - void SetDelayTime(uint32 t) { _delaytime = t; } - - void run() override - { - if (!_delaytime) - return; - - TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", _delaytime/1000); - _loops = 0; - _lastChange = 0; - while (!World::IsStopped()) - { - ACE_Based::Thread::Sleep(1000); - uint32 curtime = getMSTime(); - // normal work - uint32 worldLoopCounter = World::m_worldLoopCounter.value(); - if (_loops != worldLoopCounter) - { - _lastChange = curtime; - _loops = worldLoopCounter; - } - // possible freeze - else if (getMSTimeDiff(_lastChange, curtime) > _delaytime) - { - TC_LOG_ERROR("server.worldserver", "World Thread hangs, kicking out server!"); - ASSERT(false); - } - } - TC_LOG_INFO("server.worldserver", "Anti-freeze thread exiting without problems."); - } -}; - -/// Main function -int Master::Run() -{ - OpenSSLCrypto::threadsSetup(); - BigNumber seed1; - seed1.SetRand(16 * 8); - - TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", _FULLVERSION); - TC_LOG_INFO("server.worldserver", "<Ctrl-C> to stop.\n"); - - TC_LOG_INFO("server.worldserver", " ______ __"); - TC_LOG_INFO("server.worldserver", "/\\__ _\\ __ __/\\ \\__"); - TC_LOG_INFO("server.worldserver", "\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); - TC_LOG_INFO("server.worldserver", " \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); - TC_LOG_INFO("server.worldserver", " C O R E /\\___/"); - TC_LOG_INFO("server.worldserver", "http://TrinityCore.org \\/__/\n"); - - /// worldserver PID file creation - std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); - if (!pidFile.empty()) - { - if (uint32 pid = CreatePIDFile(pidFile)) - TC_LOG_INFO("server.worldserver", "Daemon PID: %u\n", pid); - else - { - TC_LOG_ERROR("server.worldserver", "Cannot create PID file %s.\n", pidFile.c_str()); - return 1; - } - } - - ///- Start the databases - if (!_StartDB()) - return 1; - - // set server offline (not connectable) - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = (flag & ~%u) | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, REALM_FLAG_INVALID, realmID); - - ///- Initialize the World - sWorld->SetInitialWorldSettings(); - - ///- Initialize the signal handlers - WorldServerSignalHandler signalINT, signalTERM; - #ifdef _WIN32 - WorldServerSignalHandler signalBREAK; - #endif /* _WIN32 */ - - ///- Register worldserver's signal handlers - ACE_Sig_Handler handle; - handle.register_handler(SIGINT, &signalINT); - handle.register_handler(SIGTERM, &signalTERM); -#ifdef _WIN32 - handle.register_handler(SIGBREAK, &signalBREAK); -#endif - - ///- Launch WorldRunnable thread - ACE_Based::Thread worldThread(new WorldRunnable); - worldThread.setPriority(ACE_Based::Highest); - - ACE_Based::Thread* cliThread = NULL; - -#ifdef _WIN32 - if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/) -#else - if (sConfigMgr->GetBoolDefault("Console.Enable", true)) -#endif - { - ///- Launch CliRunnable thread - cliThread = new ACE_Based::Thread(new CliRunnable); - } - - ACE_Based::Thread rarThread(new RARunnable); - -#if defined(_WIN32) || defined(__linux__) - - ///- Handle affinity for multiple processors and process priority - uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0); - bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false); - -#ifdef _WIN32 // Windows - - HANDLE hProcess = GetCurrentProcess(); - - if (affinity > 0) - { - ULONG_PTR appAff; - ULONG_PTR sysAff; - - if (GetProcessAffinityMask(hProcess, &appAff, &sysAff)) - { - ULONG_PTR currentAffinity = affinity & appAff; // remove non accessible processors - - if (!currentAffinity) - TC_LOG_ERROR("server.worldserver", "Processors marked in UseProcessors bitmask (hex) %x are not accessible for the worldserver. Accessible processors bitmask (hex): %x", affinity, appAff); - else if (SetProcessAffinityMask(hProcess, currentAffinity)) - TC_LOG_INFO("server.worldserver", "Using processors (bitmask, hex): %x", currentAffinity); - else - TC_LOG_ERROR("server.worldserver", "Can't set used processors (hex): %x", currentAffinity); - } - } - - if (highPriority) - { - if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS)) - TC_LOG_INFO("server.worldserver", "worldserver process priority class set to HIGH"); - else - TC_LOG_ERROR("server.worldserver", "Can't set worldserver process priority class."); - } - -#else // Linux - - if (affinity > 0) - { - cpu_set_t mask; - CPU_ZERO(&mask); - - for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i) - if (affinity & (1 << i)) - CPU_SET(i, &mask); - - if (sched_setaffinity(0, sizeof(mask), &mask)) - TC_LOG_ERROR("server.worldserver", "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); - else - { - CPU_ZERO(&mask); - sched_getaffinity(0, sizeof(mask), &mask); - TC_LOG_INFO("server.worldserver", "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); - } - } - - if (highPriority) - { - if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) - TC_LOG_ERROR("server.worldserver", "Can't set worldserver process priority class, error: %s", strerror(errno)); - else - TC_LOG_INFO("server.worldserver", "worldserver process priority class set to %i", getpriority(PRIO_PROCESS, 0)); - } - -#endif -#endif - - //Start soap serving thread - ACE_Based::Thread* soapThread = NULL; - - if (sConfigMgr->GetBoolDefault("SOAP.Enabled", false)) - { - TCSoapRunnable* runnable = new TCSoapRunnable(); - runnable->SetListenArguments(sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878))); - soapThread = new ACE_Based::Thread(runnable); - } - - ///- Start up freeze catcher thread - if (uint32 freezeDelay = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0)) - { - FreezeDetectorRunnable* fdr = new FreezeDetectorRunnable(); - fdr->SetDelayTime(freezeDelay * 1000); - ACE_Based::Thread freezeThread(fdr); - freezeThread.setPriority(ACE_Based::Highest); - } - - ///- Launch the world listener socket - uint16 worldPort = uint16(sWorld->getIntConfig(CONFIG_PORT_WORLD)); - std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); - - if (sWorldSocketMgr->StartNetwork(worldPort, bindIp.c_str()) == -1) - { - TC_LOG_ERROR("server.worldserver", "Failed to start network"); - World::StopNow(ERROR_EXIT_CODE); - // go down and shutdown the server - } - - // set server online (allow connecting now) - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag & ~%u, population = 0 WHERE id = '%u'", REALM_FLAG_INVALID, realmID); - - TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon) ready...", _FULLVERSION); - - // when the main thread closes the singletons get unloaded - // since worldrunnable uses them, it will crash if unloaded after master - worldThread.wait(); - rarThread.wait(); - - if (soapThread) - { - soapThread->wait(); - soapThread->destroy(); - delete soapThread; - } - - // set server offline - LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realmID); - - ///- Clean database before leaving - ClearOnlineAccounts(); - - _StopDB(); - - TC_LOG_INFO("server.worldserver", "Halting process..."); - - if (cliThread) - { - #ifdef _WIN32 - - // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API) - //_exit(1); - // send keyboard input to safely unblock the CLI thread - INPUT_RECORD b[4]; - HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE); - b[0].EventType = KEY_EVENT; - b[0].Event.KeyEvent.bKeyDown = TRUE; - b[0].Event.KeyEvent.uChar.AsciiChar = 'X'; - b[0].Event.KeyEvent.wVirtualKeyCode = 'X'; - b[0].Event.KeyEvent.wRepeatCount = 1; - - b[1].EventType = KEY_EVENT; - b[1].Event.KeyEvent.bKeyDown = FALSE; - b[1].Event.KeyEvent.uChar.AsciiChar = 'X'; - b[1].Event.KeyEvent.wVirtualKeyCode = 'X'; - b[1].Event.KeyEvent.wRepeatCount = 1; - - b[2].EventType = KEY_EVENT; - b[2].Event.KeyEvent.bKeyDown = TRUE; - b[2].Event.KeyEvent.dwControlKeyState = 0; - b[2].Event.KeyEvent.uChar.AsciiChar = '\r'; - b[2].Event.KeyEvent.wVirtualKeyCode = VK_RETURN; - b[2].Event.KeyEvent.wRepeatCount = 1; - b[2].Event.KeyEvent.wVirtualScanCode = 0x1c; - - b[3].EventType = KEY_EVENT; - b[3].Event.KeyEvent.bKeyDown = FALSE; - b[3].Event.KeyEvent.dwControlKeyState = 0; - b[3].Event.KeyEvent.uChar.AsciiChar = '\r'; - b[3].Event.KeyEvent.wVirtualKeyCode = VK_RETURN; - b[3].Event.KeyEvent.wVirtualScanCode = 0x1c; - b[3].Event.KeyEvent.wRepeatCount = 1; - DWORD numb; - WriteConsoleInput(hStdIn, b, 4, &numb); - - cliThread->wait(); - - #else - - cliThread->destroy(); - - #endif - - delete cliThread; - } - - // for some unknown reason, unloading scripts here and not in worldrunnable - // fixes a memory leak related to detaching threads from the module - //UnloadScriptingModule(); - - OpenSSLCrypto::threadsCleanup(); - // Exit the process with specified return value - return World::GetExitCode(); -} - -/// Initialize connection to the databases -bool Master::_StartDB() -{ - MySQL::Library_Init(); - - std::string dbString; - uint8 asyncThreads, synchThreads; - - dbString = sConfigMgr->GetStringDefault("WorldDatabaseInfo", ""); - if (dbString.empty()) - { - TC_LOG_ERROR("server.worldserver", "World database not specified in configuration file"); - return false; - } - - asyncThreads = uint8(sConfigMgr->GetIntDefault("WorldDatabase.WorkerThreads", 1)); - if (asyncThreads < 1 || asyncThreads > 32) - { - TC_LOG_ERROR("server.worldserver", "World database: invalid number of worker threads specified. " - "Please pick a value between 1 and 32."); - return false; - } - - synchThreads = uint8(sConfigMgr->GetIntDefault("WorldDatabase.SynchThreads", 1)); - ///- Initialize the world database - if (!WorldDatabase.Open(dbString, asyncThreads, synchThreads)) - { - TC_LOG_ERROR("server.worldserver", "Cannot connect to world database %s", dbString.c_str()); - return false; - } - - ///- Get character database info from configuration file - dbString = sConfigMgr->GetStringDefault("CharacterDatabaseInfo", ""); - if (dbString.empty()) - { - TC_LOG_ERROR("server.worldserver", "Character database not specified in configuration file"); - return false; - } - - asyncThreads = uint8(sConfigMgr->GetIntDefault("CharacterDatabase.WorkerThreads", 1)); - if (asyncThreads < 1 || asyncThreads > 32) - { - TC_LOG_ERROR("server.worldserver", "Character database: invalid number of worker threads specified. " - "Please pick a value between 1 and 32."); - return false; - } - - synchThreads = uint8(sConfigMgr->GetIntDefault("CharacterDatabase.SynchThreads", 2)); - - ///- Initialize the Character database - if (!CharacterDatabase.Open(dbString, asyncThreads, synchThreads)) - { - TC_LOG_ERROR("server.worldserver", "Cannot connect to Character database %s", dbString.c_str()); - return false; - } - - ///- Get login database info from configuration file - dbString = sConfigMgr->GetStringDefault("LoginDatabaseInfo", ""); - if (dbString.empty()) - { - TC_LOG_ERROR("server.worldserver", "Login database not specified in configuration file"); - return false; - } - - asyncThreads = uint8(sConfigMgr->GetIntDefault("LoginDatabase.WorkerThreads", 1)); - if (asyncThreads < 1 || asyncThreads > 32) - { - TC_LOG_ERROR("server.worldserver", "Login database: invalid number of worker threads specified. " - "Please pick a value between 1 and 32."); - return false; - } - - synchThreads = uint8(sConfigMgr->GetIntDefault("LoginDatabase.SynchThreads", 1)); - ///- Initialise the login database - if (!LoginDatabase.Open(dbString, asyncThreads, synchThreads)) - { - TC_LOG_ERROR("server.worldserver", "Cannot connect to login database %s", dbString.c_str()); - return false; - } - - ///- Get the realm Id from the configuration file - realmID = sConfigMgr->GetIntDefault("RealmID", 0); - if (!realmID) - { - TC_LOG_ERROR("server.worldserver", "Realm ID not defined in configuration file"); - return false; - } - TC_LOG_INFO("server.worldserver", "Realm running as realm ID %d", realmID); - - ///- Clean the database before starting - ClearOnlineAccounts(); - - ///- Insert version info into DB - WorldDatabase.PExecute("UPDATE version SET core_version = '%s', core_revision = '%s'", _FULLVERSION, _HASH); // One-time query - - sWorld->LoadDBVersion(); - - TC_LOG_INFO("server.worldserver", "Using World DB: %s", sWorld->GetDBVersion()); - return true; -} - -void Master::_StopDB() -{ - CharacterDatabase.Close(); - WorldDatabase.Close(); - LoginDatabase.Close(); - - MySQL::Library_End(); -} - -/// Clear 'online' status for all accounts with characters in this realm -void Master::ClearOnlineAccounts() -{ - // Reset online status for all accounts with characters on the current realm - LoginDatabase.DirectPExecute("UPDATE account SET online = 0 WHERE online > 0 AND id IN (SELECT acctid FROM realmcharacters WHERE realmid = %d)", realmID); - - // Reset online status for all characters - CharacterDatabase.DirectExecute("UPDATE characters SET online = 0 WHERE online <> 0"); - - // Battleground instance ids reset at server restart - CharacterDatabase.DirectExecute("UPDATE character_battleground_data SET instanceId = 0"); -} diff --git a/src/server/worldserver/Master.h b/src/server/worldserver/Master.h deleted file mode 100644 index 9ee94a44acb..00000000000 --- a/src/server/worldserver/Master.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/// \addtogroup Trinityd -/// @{ -/// \file - -#ifndef _MASTER_H -#define _MASTER_H - -#include "Common.h" - -/// Start the server -class Master -{ - public: - int Run(); - - private: - bool _StartDB(); - void _StopDB(); - - void ClearOnlineAccounts(); -}; - -#define sMaster ACE_Singleton<Master, ACE_Null_Mutex>::instance() - -#endif - -/// @} diff --git a/src/server/worldserver/PrecompiledHeaders/worldPCH.h b/src/server/worldserver/PrecompiledHeaders/worldPCH.h index f94dd953bba..6407485f70b 100644 --- a/src/server/worldserver/PrecompiledHeaders/worldPCH.h +++ b/src/server/worldserver/PrecompiledHeaders/worldPCH.h @@ -1,5 +1,3 @@ -#include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it - #include "Common.h" #include "World.h" #include "Log.h" diff --git a/src/server/worldserver/RemoteAccess/RARunnable.cpp b/src/server/worldserver/RemoteAccess/RARunnable.cpp deleted file mode 100644 index 44b07163294..00000000000 --- a/src/server/worldserver/RemoteAccess/RARunnable.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/** \file - \ingroup Trinityd - */ - -#include "Common.h" -#include "Config.h" -#include "Log.h" -#include "RARunnable.h" -#include "World.h" - -#include <ace/Reactor_Impl.h> -#include <ace/TP_Reactor.h> -#include <ace/Dev_Poll_Reactor.h> -#include <ace/Acceptor.h> -#include <ace/SOCK_Acceptor.h> - -#include "RASocket.h" - -RARunnable::RARunnable() -{ - ACE_Reactor_Impl* imp; - -#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) - imp = new ACE_Dev_Poll_Reactor(); - imp->max_notify_iterations (128); - imp->restart (1); -#else - imp = new ACE_TP_Reactor(); - imp->max_notify_iterations (128); -#endif - - m_Reactor = new ACE_Reactor (imp, 1); -} - -RARunnable::~RARunnable() -{ - delete m_Reactor; -} - -void RARunnable::run() -{ - if (!sConfigMgr->GetBoolDefault("Ra.Enable", false)) - return; - - ACE_Acceptor<RASocket, ACE_SOCK_ACCEPTOR> acceptor; - - uint16 raPort = uint16(sConfigMgr->GetIntDefault("Ra.Port", 3443)); - std::string stringIp = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0"); - ACE_INET_Addr listenAddress(raPort, stringIp.c_str()); - - if (acceptor.open(listenAddress, m_Reactor) == -1) - { - TC_LOG_ERROR("server.worldserver", "Trinity RA can not bind to port %d on %s", raPort, stringIp.c_str()); - return; - } - - TC_LOG_INFO("server.worldserver", "Starting Trinity RA on port %d on %s", raPort, stringIp.c_str()); - - while (!World::IsStopped()) - { - ACE_Time_Value interval(0, 100000); - if (m_Reactor->run_reactor_event_loop(interval) == -1) - break; - } - - TC_LOG_DEBUG("server.worldserver", "Trinity RA thread exiting"); -} diff --git a/src/server/worldserver/RemoteAccess/RARunnable.h b/src/server/worldserver/RemoteAccess/RARunnable.h deleted file mode 100644 index 540ac762f30..00000000000 --- a/src/server/worldserver/RemoteAccess/RARunnable.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/// \addtogroup Trinityd -/// @{ -/// \file - -#ifndef _TRINITY_RARUNNABLE_H_ -#define _TRINITY_RARUNNABLE_H_ - -#include "Common.h" - -#include <ace/Reactor.h> - -class RARunnable : public ACE_Based::Runnable -{ -public: - RARunnable(); - virtual ~RARunnable(); - void run() override; - -private: - ACE_Reactor* m_Reactor; - -}; - -#endif /* _TRINITY_RARUNNABLE_H_ */ - -/// @} diff --git a/src/server/worldserver/RemoteAccess/RASession.cpp b/src/server/worldserver/RemoteAccess/RASession.cpp new file mode 100644 index 00000000000..846a4eb39e3 --- /dev/null +++ b/src/server/worldserver/RemoteAccess/RASession.cpp @@ -0,0 +1,222 @@ +/* +* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> +* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#include <memory> +#include <boost/asio/write.hpp> +#include <boost/asio/read_until.hpp> +#include <boost/array.hpp> +#include "RASession.h" +#include "AccountMgr.h" +#include "Log.h" +#include "DatabaseEnv.h" +#include "World.h" +#include "Config.h" + +using boost::asio::ip::tcp; + +void RASession::Start() +{ + boost::asio::socket_base::bytes_readable command(true); + _socket.io_control(command); + std::size_t bytes_readable = command.get(); + + // Check if there are bytes available, if they are, then the client is requesting the negotiation + if (bytes_readable > 0) + { + // Handle subnegotiation + boost::array<char, 1024> buf; + _socket.read_some(boost::asio::buffer(buf)); + + // Send the end-of-negotiation packet + uint8 const reply[2] = { 0xFF, 0xF0 }; + _socket.write_some(boost::asio::buffer(reply)); + } + + Send("Authentication Required\r\n"); + Send("Username: "); + + std::string username = ReadString(); + + if (username.empty()) + return; + + TC_LOG_INFO("commands.ra", "Accepting RA connection from user %s (IP: %s)", username.c_str(), GetRemoteIpAddress().c_str()); + + Send("Password: "); + + std::string password = ReadString(); + if (password.empty()) + return; + + if (!CheckAccessLevel(username) || !CheckPassword(username, password)) + { + Send("Authentication failed\r\n"); + _socket.close(); + return; + } + + TC_LOG_INFO("commands.ra", "User %s (IP: %s) authenticated correctly to RA", username.c_str(), GetRemoteIpAddress().c_str()); + + // Authentication successful, send the motd + Send(std::string(std::string(sWorld->GetMotd()) + "\r\n").c_str()); + + // Read commands + for (;;) + { + Send("TC>"); + std::string command = ReadString(); + + if (ProcessCommand(command)) + break; + } + + _socket.close(); +} + +int RASession::Send(const char* data) +{ + std::ostream os(&_writeBuffer); + os << data; + size_t written = _socket.send(_writeBuffer.data()); + _writeBuffer.consume(written); + return written; +} + +std::string RASession::ReadString() +{ + boost::system::error_code error; + size_t read = boost::asio::read_until(_socket, _readBuffer, "\r\n", error); + if (!read) + { + _socket.close(); + return ""; + } + + std::string line; + std::istream is(&_readBuffer); + std::getline(is, line); + + if (*line.rbegin() == '\r') + line.erase(line.length() - 1); + + return line; +} + +bool RASession::CheckAccessLevel(const std::string& user) +{ + std::string safeUser = user; + + AccountMgr::normalizeString(safeUser); + + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS); + stmt->setString(0, safeUser); + PreparedQueryResult result = LoginDatabase.Query(stmt); + + if (!result) + { + TC_LOG_INFO("commands.ra", "User %s does not exist in database", user.c_str()); + return false; + } + + Field* fields = result->Fetch(); + + if (fields[1].GetUInt8() < sConfigMgr->GetIntDefault("RA.MinLevel", 3)) + { + TC_LOG_INFO("commands.ra", "User %s has no privilege to login", user.c_str()); + return false; + } + else if (fields[2].GetInt32() != -1) + { + TC_LOG_INFO("commands.ra", "User %s has to be assigned on all realms (with RealmID = '-1')", user.c_str()); + return false; + } + + return true; +} + +bool RASession::CheckPassword(const std::string& user, const std::string& pass) +{ + std::string safe_user = user; + std::transform(safe_user.begin(), safe_user.end(), safe_user.begin(), ::toupper); + AccountMgr::normalizeString(safe_user); + + std::string safe_pass = pass; + AccountMgr::normalizeString(safe_pass); + std::transform(safe_pass.begin(), safe_pass.end(), safe_pass.begin(), ::toupper); + + std::string hash = AccountMgr::CalculateShaPassHash(safe_user, safe_pass); + + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME); + + stmt->setString(0, safe_user); + stmt->setString(1, hash); + + PreparedQueryResult result = LoginDatabase.Query(stmt); + + if (!result) + { + TC_LOG_INFO("commands.ra", "Wrong password for user: %s", user.c_str()); + return false; + } + + return true; +} + +bool RASession::ProcessCommand(std::string& command) +{ + if (command.length() == 0) + return true; + + TC_LOG_INFO("commands.ra", "Received command: %s", command.c_str()); + + // handle quit, exit and logout commands to terminate connection + if (command == "quit" || command == "exit" || command == "logout") + { + Send("Bye\r\n"); + return true; + } + + // Obtain a new promise per command + if (_commandExecuting != nullptr) + delete _commandExecuting; + + _commandExecuting = new std::promise<void>(); + + CliCommandHolder* cmd = new CliCommandHolder(this, command.c_str(), &RASession::CommandPrint, &RASession::CommandFinished); + sWorld->QueueCliCommand(cmd); + + // Wait for the command to finish + _commandExecuting->get_future().wait(); + + return false; +} + +void RASession::CommandPrint(void* callbackArg, const char* text) +{ + if (!text || !*text) + return; + + RASession* session = static_cast<RASession*>(callbackArg); + session->Send(text); +} + +void RASession::CommandFinished(void* callbackArg, bool /*success*/) +{ + RASession* session = static_cast<RASession*>(callbackArg); + session->_commandExecuting->set_value(); +} diff --git a/src/server/worldserver/RemoteAccess/RASession.h b/src/server/worldserver/RemoteAccess/RASession.h new file mode 100644 index 00000000000..61156a0fa53 --- /dev/null +++ b/src/server/worldserver/RemoteAccess/RASession.h @@ -0,0 +1,63 @@ +/* +* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> +* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of the GNU General Public License as published by the +* Free Software Foundation; either version 2 of the License, or (at your +* option) any later version. +* +* This program is distributed in the hope that it will be useful, but WITHOUT +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +* more details. +* +* You should have received a copy of the GNU General Public License along +* with this program. If not, see <http://www.gnu.org/licenses/>. +*/ + +#ifndef __RASESSION_H__ +#define __RASESSION_H__ + +#include <memory> +#include <boost/asio/ip/tcp.hpp> +#include <boost/asio/streambuf.hpp> +#include "Common.h" + +#include <future> + +using boost::asio::ip::tcp; + +const size_t bufferSize = 4096; + +#define BUFFER_SIZE 4096 + +class RASession : public std::enable_shared_from_this <RASession> +{ +public: + RASession(tcp::socket&& socket) : _socket(std::move(socket)), _commandExecuting(nullptr) + { + } + + void Start(); + + const std::string GetRemoteIpAddress() const { return _socket.remote_endpoint().address().to_string(); } + unsigned short GetRemotePort() const { return _socket.remote_endpoint().port(); } + +private: + int Send(const char* data); + std::string ReadString(); + bool CheckAccessLevel(const std::string& user); + bool CheckPassword(const std::string& user, const std::string& pass); + bool ProcessCommand(std::string& command); + + static void CommandPrint(void* callbackArg, const char* text); + static void CommandFinished(void* callbackArg, bool); + + tcp::socket _socket; + boost::asio::streambuf _readBuffer; + boost::asio::streambuf _writeBuffer; + std::promise<void>* _commandExecuting; +}; + +#endif diff --git a/src/server/worldserver/RemoteAccess/RASocket.cpp b/src/server/worldserver/RemoteAccess/RASocket.cpp deleted file mode 100644 index f2c7a8e0f02..00000000000 --- a/src/server/worldserver/RemoteAccess/RASocket.cpp +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/** \file - \ingroup Trinityd -*/ - -#include "Common.h" -#include "Configuration/Config.h" -#include "Database/DatabaseEnv.h" -#include "AccountMgr.h" -#include "Log.h" -#include "RASocket.h" -#include "Util.h" -#include "World.h" -#include "SHA1.h" - -RASocket::RASocket() -{ - _minLevel = uint8(sConfigMgr->GetIntDefault("RA.MinLevel", 3)); - _commandExecuting = false; -} - -int RASocket::open(void *) -{ - ACE_INET_Addr remoteAddress; - - if (peer().get_remote_addr(remoteAddress) == -1) - { - TC_LOG_ERROR("server.worldserver", "RASocket::open: peer().get_remote_addr error is %s", ACE_OS::strerror(errno)); - return -1; - } - - TC_LOG_INFO("commands.ra", "Incoming connection from %s", remoteAddress.get_host_addr()); - - return activate(); -} - -int RASocket::handle_close(ACE_HANDLE /*handle*/, ACE_Reactor_Mask /*mask*/) -{ - TC_LOG_INFO("commands.ra", "Closing connection"); - peer().close_reader(); - wait(); - // While the above wait() will wait for the ::svc() to finish, it will not wait for the async event - // RASocket::commandfinished to be completed. Calling destroy() before the latter function ends - // will lead to using a freed pointer -> crash. - while (_commandExecuting.value()) - ACE_OS::sleep(1); - - destroy(); - return 0; -} - -int RASocket::send(const std::string& line) -{ -#ifdef MSG_NOSIGNAL - ssize_t n = peer().send(line.c_str(), line.length(), MSG_NOSIGNAL); -#else - ssize_t n = peer().send(line.c_str(), line.length()); -#endif // MSG_NOSIGNAL - - return n == ssize_t(line.length()) ? 0 : -1; -} - -int RASocket::recv_line(ACE_Message_Block& buffer) -{ - char byte; - for (;;) - { - ssize_t n = peer().recv(&byte, sizeof(byte)); - - if (n < 0) - return -1; - - if (n == 0) - { - // EOF, connection was closed - errno = ECONNRESET; - return -1; - } - - ACE_ASSERT(n == sizeof(byte)); - - if (byte == '\n') - break; - else if (byte == '\r') /* Ignore CR */ - continue; - else if (buffer.copy(&byte, sizeof(byte)) == -1) - return -1; - } - - const char nullTerm = '\0'; - if (buffer.copy(&nullTerm, sizeof(nullTerm)) == -1) - return -1; - - return 0; -} - -int RASocket::recv_line(std::string& out_line) -{ - char buf[4096]; - - ACE_Data_Block db(sizeof (buf), - ACE_Message_Block::MB_DATA, - buf, - 0, - 0, - ACE_Message_Block::DONT_DELETE, - 0); - - ACE_Message_Block message_block(&db, - ACE_Message_Block::DONT_DELETE, - 0); - - if (recv_line(message_block) == -1) - { - TC_LOG_DEBUG("commands.ra", "Recv error %s", ACE_OS::strerror(errno)); - return -1; - } - - out_line = message_block.rd_ptr(); - - return 0; -} - -int RASocket::process_command(const std::string& command) -{ - if (command.length() == 0) - return 0; - - TC_LOG_INFO("commands.ra", "Received command: %s", command.c_str()); - - // handle quit, exit and logout commands to terminate connection - if (command == "quit" || command == "exit" || command == "logout") { - (void) send("Bye\r\n"); - return -1; - } - - _commandExecuting = true; - CliCommandHolder* cmd = new CliCommandHolder(this, command.c_str(), &RASocket::zprint, &RASocket::commandFinished); - sWorld->QueueCliCommand(cmd); - - // wait for result - ACE_Message_Block* mb; - for (;;) - { - if (getq(mb) == -1) - return -1; - - if (mb->msg_type() == ACE_Message_Block::MB_BREAK) - { - mb->release(); - break; - } - - if (send(std::string(mb->rd_ptr(), mb->length())) == -1) - { - mb->release(); - return -1; - } - - mb->release(); - } - - return 0; -} - -int RASocket::check_access_level(const std::string& user) -{ - std::string safeUser = user; - - Utf8ToUpperOnlyLatin(safeUser); - - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS); - stmt->setString(0, safeUser); - PreparedQueryResult result = LoginDatabase.Query(stmt); - - if (!result) - { - TC_LOG_INFO("commands.ra", "User %s does not exist in database", user.c_str()); - return -1; - } - - Field* fields = result->Fetch(); - - if (fields[1].GetUInt8() < _minLevel) - { - TC_LOG_INFO("commands.ra", "User %s has no privilege to login", user.c_str()); - return -1; - } - else if (fields[2].GetInt32() != -1) - { - TC_LOG_INFO("commands.ra", "User %s has to be assigned on all realms (with RealmID = '-1')", user.c_str()); - return -1; - } - - return 0; -} - -int RASocket::check_password(const std::string& user, const std::string& pass) -{ - std::string safe_user = user; - Utf8ToUpperOnlyLatin(safe_user); - - std::string safe_pass = pass; - Utf8ToUpperOnlyLatin(safe_pass); - - std::string hash = AccountMgr::CalculateShaPassHash(safe_user, safe_pass); - - PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME); - - stmt->setString(0, safe_user); - stmt->setString(1, hash); - - PreparedQueryResult result = LoginDatabase.Query(stmt); - - if (!result) - { - TC_LOG_INFO("commands.ra", "Wrong password for user: %s", user.c_str()); - return -1; - } - - return 0; -} - -int RASocket::authenticate() -{ - if (send(std::string("Username: ")) == -1) - return -1; - - std::string user; - if (recv_line(user) == -1) - return -1; - - if (send(std::string("Password: ")) == -1) - return -1; - - std::string pass; - if (recv_line(pass) == -1) - return -1; - - TC_LOG_INFO("commands.ra", "Login attempt for user: %s", user.c_str()); - - if (check_access_level(user) == -1) - return -1; - - if (check_password(user, pass) == -1) - return -1; - - TC_LOG_INFO("commands.ra", "User login: %s", user.c_str()); - - return 0; -} - - -int RASocket::subnegotiate() -{ - char buf[1024]; - - ACE_Data_Block db(sizeof (buf), - ACE_Message_Block::MB_DATA, - buf, - 0, - 0, - ACE_Message_Block::DONT_DELETE, - 0); - - ACE_Message_Block message_block(&db, - ACE_Message_Block::DONT_DELETE, - 0); - - const size_t recv_size = message_block.space(); - - // Wait a maximum of 1000ms for negotiation packet - not all telnet clients may send it - ACE_Time_Value waitTime = ACE_Time_Value(1); - const ssize_t n = peer().recv(message_block.wr_ptr(), - recv_size, &waitTime); - - if (n <= 0) - return int(n); - - if (n >= 1024) - { - TC_LOG_DEBUG("commands.ra", "RASocket::subnegotiate: allocated buffer 1024 bytes was too small for negotiation packet, size: %u", uint32(n)); - return -1; - } - - buf[n] = '\0'; - - #ifdef _DEBUG - for (uint8 i = 0; i < n; ) - { - uint8 iac = buf[i]; - if (iac == 0xFF) // "Interpret as Command" (IAC) - { - uint8 command = buf[++i]; - std::stringstream ss; - switch (command) - { - case 0xFB: // WILL - ss << "WILL "; - break; - case 0xFC: // WON'T - ss << "WON'T "; - break; - case 0xFD: // DO - ss << "DO "; - break; - case 0xFE: // DON'T - ss << "DON'T "; - break; - default: - return -1; // not allowed - } - - uint8 param = buf[++i]; - ss << uint32(param); - TC_LOG_DEBUG("commands.ra", ss.str().c_str()); - } - ++i; - } - #endif - - //! Just send back end of subnegotiation packet - uint8 const reply[2] = {0xFF, 0xF0}; - -#ifdef MSG_NOSIGNAL - return int(peer().send(reply, 2, MSG_NOSIGNAL)); -#else - return int(peer().send(reply, 2)); -#endif // MSG_NOSIGNAL -} - -int RASocket::svc(void) -{ - //! Subnegotiation may differ per client - do not react on it - subnegotiate(); - - if (send("Authentication required\r\n") == -1) - return -1; - - if (authenticate() == -1) - { - (void) send("Authentication failed\r\n"); - return -1; - } - - // send motd - if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1) - return -1; - - for (;;) - { - // show prompt - if (send("TC> ") == -1) - return -1; - - std::string line; - - if (recv_line(line) == -1) - return -1; - - if (process_command(line) == -1) - return -1; - } - - return 0; -} - -void RASocket::zprint(void* callbackArg, const char * szText) -{ - if (!szText || !callbackArg) - return; - - RASocket* socket = static_cast<RASocket*>(callbackArg); - size_t sz = strlen(szText); - - ACE_Message_Block* mb = new ACE_Message_Block(sz); - mb->copy(szText, sz); - - ACE_Time_Value tv = ACE_Time_Value::zero; - if (socket->putq(mb, &tv) == -1) - { - TC_LOG_DEBUG("commands.ra", "Failed to enqueue message, queue is full or closed. Error is %s", ACE_OS::strerror(errno)); - mb->release(); - } -} - -void RASocket::commandFinished(void* callbackArg, bool /*success*/) -{ - if (!callbackArg) - return; - - RASocket* socket = static_cast<RASocket*>(callbackArg); - - ACE_Message_Block* mb = new ACE_Message_Block(); - - mb->msg_type(ACE_Message_Block::MB_BREAK); - - // the message is 0 size control message to tell that command output is finished - // hence we don't put timeout, because it shouldn't increase queue size and shouldn't block - if (socket->putq(mb->duplicate()) == -1) - // getting here is bad, command can't be marked as complete - TC_LOG_DEBUG("commands.ra", "Failed to enqueue command end message. Error is %s", ACE_OS::strerror(errno)); - - mb->release(); - - socket->_commandExecuting = false; -} diff --git a/src/server/worldserver/RemoteAccess/RASocket.h b/src/server/worldserver/RemoteAccess/RASocket.h deleted file mode 100644 index 2cbb14b3578..00000000000 --- a/src/server/worldserver/RemoteAccess/RASocket.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/// \addtogroup Trinityd -/// @{ -/// \file - -#ifndef _RASOCKET_H -#define _RASOCKET_H - -#include "Common.h" - -#include <ace/Synch_Traits.h> -#include <ace/Svc_Handler.h> -#include <ace/SOCK_Stream.h> -#include <ace/SOCK_Acceptor.h> - -/// Remote Administration socket -class RASocket : public ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_MT_SYNCH> -{ - public: - RASocket(); - virtual ~RASocket() { } - - virtual int svc() override; - virtual int open(void* = 0) override; - virtual int handle_close(ACE_HANDLE = ACE_INVALID_HANDLE, ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK) override; - - private: - int recv_line(std::string& outLine); - int recv_line(ACE_Message_Block& buffer); - int process_command(const std::string& command); - int authenticate(); - int subnegotiate(); ///< Used by telnet protocol RFC 854 / 855 - int check_access_level(const std::string& user); - int check_password(const std::string& user, const std::string& pass); - int send(const std::string& line); - - static void zprint(void* callbackArg, const char* szText); - static void commandFinished(void* callbackArg, bool success); - - private: - uint8 _minLevel; ///< Minimum security level required to connect - ACE_Atomic_Op<ACE_Thread_Mutex, bool> _commandExecuting; -}; - -#endif - -/// @} diff --git a/src/server/worldserver/TCSoap/TCSoap.cpp b/src/server/worldserver/TCSoap/TCSoap.cpp index 1549019352d..5122752f3a4 100644 --- a/src/server/worldserver/TCSoap/TCSoap.cpp +++ b/src/server/worldserver/TCSoap/TCSoap.cpp @@ -22,7 +22,7 @@ #include "AccountMgr.h" #include "Log.h" -void TCSoapRunnable::run() +void TCSoapThread(const std::string& host, uint16 port) { struct soap soap; soap_init(&soap); @@ -33,13 +33,13 @@ void TCSoapRunnable::run() soap.accept_timeout = 3; soap.recv_timeout = 5; soap.send_timeout = 5; - if (!soap_valid_socket(soap_bind(&soap, _host.c_str(), _port, 100))) + if (!soap_valid_socket(soap_bind(&soap, host.c_str(), port, 100))) { - TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", _host.c_str(), _port); + TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", host.c_str(), port); exit(-1); } - TC_LOG_INFO("network.soap", "Bound to http://%s:%d", _host.c_str(), _port); + TC_LOG_INFO("network.soap", "Bound to http://%s:%d", host.c_str(), port); while (!World::IsStopped()) { @@ -48,28 +48,21 @@ void TCSoapRunnable::run() TC_LOG_DEBUG("network.soap", "Accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF); struct soap* thread_soap = soap_copy(&soap);// make a safe copy - - ACE_Message_Block* mb = new ACE_Message_Block(sizeof(struct soap*)); - ACE_OS::memcpy(mb->wr_ptr(), &thread_soap, sizeof(struct soap*)); - process_message(mb); + process_message(thread_soap); } soap_done(&soap); } -void TCSoapRunnable::process_message(ACE_Message_Block* mb) +void process_message(struct soap* soap_message) { - ACE_TRACE (ACE_TEXT ("SOAPWorkingThread::process_message")); - - struct soap* soap; - ACE_OS::memcpy(&soap, mb->rd_ptr (), sizeof(struct soap*)); - mb->release(); + TC_LOG_TRACE("network.soap", "SOAPWorkingThread::process_message"); - soap_serve(soap); - soap_destroy(soap); // dealloc C++ data - soap_end(soap); // dealloc data and clean up - soap_done(soap); // detach soap struct - free(soap); + soap_serve(soap_message); + soap_destroy(soap_message); // dealloc C++ data + soap_end(soap_message); // dealloc data and clean up + soap_done(soap_message); // detach soap struct + free(soap_message); } /* Code used for generating stubs: @@ -112,19 +105,15 @@ int ns1__executeCommand(soap* soap, char* command, char** result) // commands are executed in the world thread. We have to wait for them to be completed { - // CliCommandHolder will be deleted from world, accessing after queueing is NOT save + // CliCommandHolder will be deleted from world, accessing after queueing is NOT safe CliCommandHolder* cmd = new CliCommandHolder(&connection, command, &SOAPCommand::print, &SOAPCommand::commandFinished); sWorld->QueueCliCommand(cmd); } - // wait for callback to complete command - - int acc = connection.pendingCommands.acquire(); - if (acc) - TC_LOG_ERROR("network.soap", "Error while acquiring lock, acc = %i, errno = %u", acc, errno); - - // alright, command finished + // Wait until the command has finished executing + connection.finishedPromise.get_future().wait(); + // The command has finished executing already char* printBuffer = soap_strdup(soap, connection.m_printBuffer.c_str()); if (connection.hasCommandSucceeded()) { @@ -139,7 +128,6 @@ void SOAPCommand::commandFinished(void* soapconnection, bool success) { SOAPCommand* con = (SOAPCommand*)soapconnection; con->setCommandSuccess(success); - con->pendingCommands.release(); } //////////////////////////////////////////////////////////////////////////////// diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index 427d37ef0cc..999a03a9009 100644 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -19,36 +19,17 @@ #define _TCSOAP_H #include "Define.h" +#include <mutex> +#include <future> -#include <ace/Semaphore.h> -#include <ace/Task.h> -#include <Threading.h> - -class TCSoapRunnable : public ACE_Based::Runnable -{ - public: - TCSoapRunnable() : _port(0) { } - - void run() override; - - void SetListenArguments(const std::string& host, uint16 port) - { - _host = host; - _port = port; - } - - private: - void process_message(ACE_Message_Block* mb); - - std::string _host; - uint16 _port; -}; +void process_message(struct soap* soap_message); +void TCSoapThread(const std::string& host, uint16 port); class SOAPCommand { public: SOAPCommand(): - pendingCommands(0, USYNC_THREAD, "pendingCommands"), m_success(false) + m_success(false) { } @@ -61,11 +42,10 @@ class SOAPCommand m_printBuffer += msg; } - ACE_Semaphore pendingCommands; - void setCommandSuccess(bool val) { m_success = val; + finishedPromise.set_value(); } bool hasCommandSucceeded() const @@ -82,6 +62,7 @@ class SOAPCommand bool m_success; std::string m_printBuffer; + std::promise<void> finishedPromise; }; #endif diff --git a/src/server/worldserver/WorldThread/WorldRunnable.cpp b/src/server/worldserver/WorldThread/WorldRunnable.cpp deleted file mode 100644 index 476007f6ea0..00000000000 --- a/src/server/worldserver/WorldThread/WorldRunnable.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/** \file - \ingroup Trinityd -*/ - -#include "Common.h" -#include "ObjectAccessor.h" -#include "World.h" -#include "WorldSocketMgr.h" -#include "Database/DatabaseEnv.h" -#include "ScriptMgr.h" -#include "BattlegroundMgr.h" -#include "MapManager.h" -#include "Timer.h" -#include "WorldRunnable.h" -#include "OutdoorPvPMgr.h" - -#define WORLD_SLEEP_CONST 50 - -#ifdef _WIN32 -#include "ServiceWin32.h" -extern int m_ServiceStatus; -#endif - -/// Heartbeat for the World -void WorldRunnable::run() -{ - uint32 realCurrTime = 0; - uint32 realPrevTime = getMSTime(); - - uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST - - sScriptMgr->OnStartup(); - - ///- While we have not World::m_stopEvent, update the world - while (!World::IsStopped()) - { - ++World::m_worldLoopCounter; - realCurrTime = getMSTime(); - - uint32 diff = getMSTimeDiff(realPrevTime, realCurrTime); - - sWorld->Update( diff ); - realPrevTime = realCurrTime; - - // diff (D0) include time of previous sleep (d0) + tick time (t0) - // we want that next d1 + t1 == WORLD_SLEEP_CONST - // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement - // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0 - if (diff <= WORLD_SLEEP_CONST+prevSleepTime) - { - prevSleepTime = WORLD_SLEEP_CONST+prevSleepTime-diff; - ACE_Based::Thread::Sleep(prevSleepTime); - } - else - prevSleepTime = 0; - - #ifdef _WIN32 - if (m_ServiceStatus == 0) - World::StopNow(SHUTDOWN_EXIT_CODE); - - while (m_ServiceStatus == 2) - Sleep(1000); - #endif - } - - sScriptMgr->OnShutdown(); - - sWorld->KickAll(); // save and kick all players - sWorld->UpdateSessions( 1 ); // real players unload required UpdateSessions call - - // unload battleground templates before different singletons destroyed - sBattlegroundMgr->DeleteAllBattlegrounds(); - - sWorldSocketMgr->StopNetwork(); - - sMapMgr->UnloadAll(); // unload all grids (including locked in memory) - sObjectAccessor->UnloadAll(); // unload 'i_player2corpse' storage and remove from world - sScriptMgr->Unload(); - sOutdoorPvPMgr->Die(); -} diff --git a/src/server/worldserver/WorldThread/WorldRunnable.h b/src/server/worldserver/WorldThread/WorldRunnable.h deleted file mode 100644 index dfc74dd1e3a..00000000000 --- a/src/server/worldserver/WorldThread/WorldRunnable.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> - * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/// \addtogroup Trinityd -/// @{ -/// \file - -#ifndef __WORLDRUNNABLE_H -#define __WORLDRUNNABLE_H - -/// Heartbeat thread for the World -class WorldRunnable : public ACE_Based::Runnable -{ - public: - void run() override; -}; - -#endif - -/// @} diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist index 18c4d63b879..f9c88e0dcef 100644 --- a/src/server/worldserver/worldserver.conf.dist +++ b/src/server/worldserver/worldserver.conf.dist @@ -145,6 +145,14 @@ WorldServerPort = 8085 BindIP = "0.0.0.0" # +# ThreadPool +# Description: Number of threads to be used for the global thread pool +# The thread pool is currently used for the signal handler and remote access +# Default: 1 + +ThreadPool = 1 + +# ################################################################################################### ################################################################################################### @@ -162,7 +170,8 @@ UseProcessors = 0 # # ProcessPriority # Description: Process priority setting for Windows and Linux based systems. -# Details: On Linux, a nice value of -15 is used. (requires superuser). On Windows, process is set to HIGH class. +# Details: On Linux, a nice value of -15 is used. (requires superuser). +# On Windows, process is set to HIGH class. # Default: 0 - (Normal) # 1 - (High) @@ -1042,6 +1051,16 @@ AccountInstancesPerHour = 5 Account.PasswordChangeSecurity = 0 # +# BirthdayTime +# Description: Set to date of project's birth in UNIX time. By default the date when +# TrinityCore was started (Thu Oct 2, 2008) +# Default: 1222964635 +# +# + +BirthdayTime = 1222964635 + +# ################################################################################################### ################################################################################################### @@ -2586,8 +2605,10 @@ UI.ShowQuestLevelsInDialogs = 0 # 1 - Prefix Timestamp to the text # 2 - Prefix Log Level to the text # 4 - Prefix Log Filter type to the text -# 8 - Append timestamp to the log file name. Format: YYYY-MM-DD_HH-MM-SS (Only used with Type = 2) -# 16 - Make a backup of existing file before overwrite (Only used with Mode = w) +# 8 - Append timestamp to the log file name. Format: YYYY-MM-DD_HH-MM-SS +# (Only used with Type = 2) +# 16 - Make a backup of existing file before overwrite +# (Only used with Mode = w) # # Colors (read as optional1 if Type = Console) # Format: "fatal error warn info debug trace" @@ -2703,7 +2724,8 @@ Log.Async.Enable = 0 # # Allow.IP.Based.Action.Logging -# Description: Logs actions, e.g. account login and logout to name a few, based on IP of current session. +# Description: Logs actions, e.g. account login and logout to name a few, based on IP of +# current session. # Default: 0 - (Disabled) # 1 - (Enabled) |
