Example #1
0
void mainLoader(int, char*[], ServiceManager* services)
{
    //dispatcher thread
    g_game.setGameState(GAME_STATE_STARTUP);

    srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
    SetConsoleTitle(STATUS_SERVER_NAME);
#endif
    std::cout << "The " << STATUS_SERVER_NAME << " Version: (" << STATUS_SERVER_VERSION << "." << MINOR_VERSION << " . " << REVISION_VERSION << ") - Codename: ( " << SOFTWARE_CODENAME << " )" << std::endl;
    std::cout << "Compiled with: " << BOOST_COMPILER << std::endl;
    std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
    std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
    std::cout << "x86" << std::endl;
#elif defined(__arm__)
    std::cout << "ARM" << std::endl;
#else
    std::cout << "unknown" << std::endl;
#endif
    std::cout << std::endl;

    std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << "." << std::endl;
    std::cout << "Visit our forum for updates, support, and resources: " << GIT_REPO <<"." << std::endl;
    std::cout << std::endl;

    // read global config
    std::cout << ">> Loading config" << std::endl;
    if (!g_config.load()) {
        startupErrorMessage("Unable to load config.lua!");
        return;
    }

#ifdef _WIN32
    const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
    if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
    } else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
        SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
    }
#endif

    //set RSA key
    const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
    const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
    g_RSA.setKey(p, q);

    std::cout << ">> Establishing database connection..." << std::flush;

    Database* db = Database::getInstance();
    if (!db->connect()) {
        startupErrorMessage("Failed to connect to database.");
        return;
    }

    std::cout << " MySQL " << Database::getClientVersion() << std::endl;

    // run database manager
    std::cout << ">> Running database manager" << std::endl;

    if (!DatabaseManager::isDatabaseSetup()) {
        startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
        return;
    }
    g_databaseTasks.start();

    DatabaseManager::updateDatabase();

    if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
        std::cout << "> No tables were optimized." << std::endl;
    }

    //load vocations
    std::cout << ">> Loading vocations" << std::endl;
    if (!g_vocations.loadFromXml()) {
        startupErrorMessage("Unable to load vocations!");
        return;
    }

    // load item data
    std::cout << ">> Loading items" << std::endl;
    if (Item::items.loadFromOtb("data/items/items.otb") != ERROR_NONE) {
        startupErrorMessage("Unable to load items (OTB)!");
        return;
    }

    if (!Item::items.loadFromXml()) {
        startupErrorMessage("Unable to load items (XML)!");
        return;
    }

    std::cout << ">> Loading script systems" << std::endl;
    if (!ScriptingManager::getInstance()->loadScriptSystems()) {
        startupErrorMessage("Failed to load script systems");
        return;
    }

    std::cout << ">> Loading monsters" << std::endl;
    if (!g_monsters.loadFromXml()) {
        startupErrorMessage("Unable to load monsters!");
        return;
    }

    std::cout << ">> Loading outfits" << std::endl;
    Outfits* outfits = Outfits::getInstance();
    if (!outfits->loadFromXml()) {
        startupErrorMessage("Unable to load outfits!");
        return;
    }

    std::cout << ">> Checking world type... " << std::flush;
    std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
    if (worldType == "pvp") {
        g_game.setWorldType(WORLD_TYPE_PVP);
    } else if (worldType == "no-pvp") {
        g_game.setWorldType(WORLD_TYPE_NO_PVP);
    } else if (worldType == "pvp-enforced") {
        g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
    } else {
        std::cout << std::endl;

        std::ostringstream ss;
        ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced.";
        startupErrorMessage(ss.str());
        return;
    }
    std::cout << asUpperCaseString(worldType) << std::endl;

    std::cout << ">> Loading map" << std::endl;
    if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
        startupErrorMessage("Failed to load map");
        return;
    }

    std::cout << ">> Initializing gamestate" << std::endl;
    g_game.setGameState(GAME_STATE_INIT);

    // Game client protocols
    services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
    services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    // OT protocols
    services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

    // Legacy login protocol
    services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    RentPeriod_t rentPeriod;
    std::string strRentPeriod = asLowerCaseString(g_config.getString(ConfigManager::HOUSE_RENT_PERIOD));

    if (strRentPeriod == "yearly") {
        rentPeriod = RENTPERIOD_YEARLY;
    } else if (strRentPeriod == "weekly") {
        rentPeriod = RENTPERIOD_WEEKLY;
    } else if (strRentPeriod == "monthly") {
        rentPeriod = RENTPERIOD_MONTHLY;
    } else if (strRentPeriod == "daily") {
        rentPeriod = RENTPERIOD_DAILY;
    } else {
        rentPeriod = RENTPERIOD_NEVER;
    }

    g_game.map.houses.payHouses(rentPeriod);

    IOMarket::checkExpiredOffers();
    IOMarket::getInstance()->updateStatistics();

    std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
    if (getuid() == 0 || geteuid() == 0) {
        std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
    }
#endif

    g_game.start(services);
    g_game.setGameState(GAME_STATE_NORMAL);
    g_loaderSignal.notify_all();
}
Example #2
0
void otserv(
#if !defined(WINDOWS) || defined(_CONSOLE)
StringVec,
#endif
ServiceManager* services)
{
	std::srand((uint32_t)OTSYS_TIME());
#if defined(WINDOWS)
#if defined(_CONSOLE)
	SetConsoleTitle(SOFTWARE_NAME);
#else
	GUI::getInstance()->m_connections = false;
#endif
#endif

	g_game.setGameState(GAMESTATE_STARTUP);
#if !defined(WINDOWS) && !defined(__ROOT_PERMISSION__)
	if(!getuid() || !geteuid())
	{
		std::clog << "> WARNING: " "The " << SOFTWARE_NAME << " has been executed as super user! It is "
			<< "recommended to run as a normal user." << std::endl << "Continue? (y/N)" << std::endl;
		char buffer = OTSYS_getch();
		if(buffer != 121 && buffer != 89)
			startupErrorMessage("Aborted.");
	}
#endif

	std::clog << "The " << SOFTWARE_NAME << " Version: (" << SOFTWARE_VERSION << "." << MINOR_VERSION << PATCH_VERSION << " - " << REVISION_VERSION << ") - Codename: (" << SOFTWARE_CODENAME << ")" << std::endl
		<< "Compilied with " << BOOST_COMPILER << " for arch "
		#if defined(__amd64__) || defined(_M_X64)
		"64 Bits"
		#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
		"32 Bits"
		#else
		"unk"
		#endif
		" at " << __DATE__ << " " << __TIME__ << std::endl

		<< std::endl
		<< "A server developed by: "SOFTWARE_DEVELOPERS"." << std::endl
		<< "Visit our forums for updates, support, and resources:" << std::endl
		<< ""FORUMS"" << std::endl;
	std::stringstream ss;
#ifdef __DEBUG__
	ss << " GLOBAL";
#endif
#ifdef __DEBUG_MOVESYS__
	ss << " MOVESYS";
#endif
#ifdef __DEBUG_CHAT__
	ss << " CHAT";
#endif
#ifdef __DEBUG_HOUSES__
	ss << " HOUSES";
#endif
#ifdef __DEBUG_LUASCRIPTS__
	ss << " LUA-SCRIPTS";
#endif
#ifdef __DEBUG_MAILBOX__
	ss << " MAILBOX";
#endif
#ifdef __DEBUG_NET__
	ss << " NET";
#endif
#ifdef __DEBUG_NET_DETAIL__
	ss << " NET-DETAIL";
#endif
#ifdef __DEBUG_RAID__
	ss << " RAIDS";
#endif
#ifdef __DEBUG_SCHEDULER__
	ss << " SCHEDULER";
#endif
#ifdef __DEBUG_SPAWN__
	ss << " SPAWNS";
#endif
#ifdef __SQL_QUERY_DEBUG__
	ss << " SQL-QUERIES";
#endif

	std::string debug = ss.str();
	if(!debug.empty())
	{
		std::clog << ">> Debugging:";
		#if defined(WINDOWS) && !defined(_CONSOLE)
		SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Debugging:");
		#endif
		std::clog << debug << "." << std::endl;
	}
	std::clog << std::endl;
	std::clog << ">> Loading config (" << g_config.getString(ConfigManager::CONFIG_FILE) << ")" << std::endl;
	#if defined(WINDOWS) && !defined(_CONSOLE)
	SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Loading config");
	#endif
	if(!g_config.load())
		startupErrorMessage("Unable to load " + g_config.getString(ConfigManager::CONFIG_FILE) + "!");

#ifndef WINDOWS
	if(g_config.getBool(ConfigManager::DAEMONIZE))
	{
		std::clog << "> Daemonization... ";
		if(fork())
		{
			std::clog << "succeed, bye!" << std::endl;
			exit(0);
		}
		else
			std::clog << "failed, continuing." << std::endl;
	}

#endif
	// silently append trailing slash
	std::string path = g_config.getString(ConfigManager::DATA_DIRECTORY);
	g_config.setString(ConfigManager::DATA_DIRECTORY, path.erase(path.find_last_not_of("/") + 1) + "/");

	path = g_config.getString(ConfigManager::LOGS_DIRECTORY);
	g_config.setString(ConfigManager::LOGS_DIRECTORY, path.erase(path.find_last_not_of("/") + 1) + "/");

	std::clog << ">> Opening logs" << std::endl;
	#if defined(WINDOWS) && !defined(_CONSOLE)
	SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Opening logs");
	#endif
	Logger::getInstance()->open();

	IntegerVec cores = vectorAtoi(explodeString(g_config.getString(ConfigManager::CORES_USED), ","));
	if(cores[0] != -1)
	{
#ifdef WINDOWS
		int32_t mask = 0;
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			mask += 1 << (*it);

		SetProcessAffinityMask(GetCurrentProcess(), mask);
	}

	std::stringstream mutexName;
	mutexName << "otxserver_" << g_config.getNumber(ConfigManager::WORLD_ID);

	CreateMutex(NULL, FALSE, mutexName.str().c_str());
	if(GetLastError() == ERROR_ALREADY_EXISTS)
		startupErrorMessage("Another instance of The OTX Server is already running with the same worldId.\nIf you want to run multiple servers, please change the worldId in configuration file.");

	std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
	if(defaultPriority == "realtime" || defaultPriority == "real")
		SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	else if(defaultPriority == "high" || defaultPriority == "regular")
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	else if(defaultPriority == "higher" || defaultPriority == "above" || defaultPriority == "normal")
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);

#else
#ifndef __APPLE__
		cpu_set_t mask;
		CPU_ZERO(&mask);
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			CPU_SET((*it), &mask);

		sched_setaffinity(getpid(), (int32_t)sizeof(mask), &mask);
	}
Example #3
0
void otserv(
#if !defined(WINDOWS) || defined(__CONSOLE__)
StringVec args,
#endif
ServiceManager* services)
{
	srand((uint32_t)OTSYS_TIME());
	#if defined(WINDOWS)
	#if defined(__CONSOLE__)
	SetConsoleTitle(STATUS_SERVER_NAME);
	#else
	GUI::getInstance()->m_connections = false;
	#endif
	#endif

	g_game.setGameState(GAME_STATE_STARTUP);


	std::cout << STATUS_SERVER_NAME << ", version " << STATUS_SERVER_VERSION << " (" << STATUS_SERVER_CODENAME << ")" << std::endl;
	std::cout << "Compiled with " << BOOST_COMPILER << " at " << __DATE__ << ", " << __TIME__ << "." << std::endl;
	std::cout << "A server developed by Gesior." << std::endl;

	std::stringstream ss;
	#ifdef __DEBUG__
	ss << " GLOBAL";
	#endif
	#ifdef __DEBUG_MOVESYS__
	ss << " MOVESYS";
	#endif
	#ifdef __DEBUG_CHAT__
	ss << " CHAT";
	#endif
	#ifdef __DEBUG_EXCEPTION_REPORT__
	ss << " EXCEPTION-REPORT";
	#endif
	#ifdef __DEBUG_HOUSES__
	ss << " HOUSES";
	#endif
	#ifdef __DEBUG_LUASCRIPTS__
	ss << " LUA-SCRIPTS";
	#endif
	#ifdef __DEBUG_MAILBOX__
	ss << " MAILBOX";
	#endif
	#ifdef __DEBUG_NET__
	ss << " NET";
	#endif
	#ifdef __DEBUG_NET_DETAIL__
	ss << " NET-DETAIL";
	#endif
	#ifdef __DEBUG_RAID__
	ss << " RAIDS";
	#endif
	#ifdef __DEBUG_SCHEDULER__
	ss << " SCHEDULER";
	#endif
	#ifdef __DEBUG_SPAWN__
	ss << " SPAWNS";
	#endif
	#ifdef __SQL_QUERY_DEBUG__
	ss << " SQL-QUERIES";
	#endif

	std::string debug = ss.str();
	if(!debug.empty())
	{
		std::cout << ">> Debugging:";
		#if defined(WINDOWS) && !defined(__CONSOLE__)
		SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Displaying debugged components");
		#endif
		std::cout << debug << "." << std::endl;
	}

	std::cout << ">> Loading config (" << g_config.getString(ConfigManager::CONFIG_FILE) << ")" << std::endl;
	#if defined(WINDOWS) && !defined(__CONSOLE__)
	SendMessage(GUI::getInstance()->m_statusBar, WM_SETTEXT, 0, (LPARAM)">> Loading config");
	#endif
	if(!g_config.load())
		startupErrorMessage("Unable to load " + g_config.getString(ConfigManager::CONFIG_FILE) + "!");

	Logger::getInstance()->open();
	IntegerVec cores = vectorAtoi(explodeString(g_config.getString(ConfigManager::CORES_USED), ","));
	if(cores[0] != -1)
	{
	#ifdef WINDOWS
		int32_t mask = 0;
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			mask += 1 << (*it);

		SetProcessAffinityMask(GetCurrentProcess(), mask);
	}

	std::stringstream mutexName;
	mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::WORLD_ID);

	CreateMutex(NULL, FALSE, mutexName.str().c_str());
	if(GetLastError() == ERROR_ALREADY_EXISTS)
		startupErrorMessage("Another instance of The Forgotten Server is already running with the same worldId.\nIf you want to run multiple servers, please change the worldId in configuration file.");

	std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
	if(defaultPriority == "realtime")
		SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	else if(defaultPriority == "high")
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	else if(defaultPriority == "higher")
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);

	#else
		cpu_set_t mask;
		CPU_ZERO(&mask);
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			CPU_SET((*it), &mask);

		sched_setaffinity(getpid(), (int32_t)sizeof(mask), &mask);
	}
Example #4
0
void mainLoader(int, char*[], ServiceManager* services)
{

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compiled with " << BOOST_COMPILER << std::endl;
	std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "unknown" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

	std::cout << ">> Loading gameserver config..." << std::endl;

	if (!g_gameserver.load()) {
		startupErrorMessage("Unable to load gameservers!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}
	g_databaseTasks.start();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
	}
#endif

	g_loaderSignal.notify_all();
}
Example #5
0
void mainLoader(int argc, char* argv[], ServiceManager* services)
{
	//dispatcher thread
	g_game.setGameState(GAME_STATE_STARTUP);

	srand((unsigned int)OTSYS_TIME());
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compilied on " << __DATE__ << ' ' << __TIME__ << " for arch ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#elif defined(__mips__)
	std::cout << "MIPS" << std::endl;
#else
	std::cout << "unk" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

#ifdef _WIN32
	std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
	if (defaultPriority == "realtime") {
		SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	} else if (defaultPriority == "high") {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (defaultPriority == "higher") {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}

	std::ostringstream mutexName;
	mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::LOGIN_PORT);
	CreateMutex(nullptr, FALSE, mutexName.str().c_str());
	if (GetLastError() == ERROR_ALREADY_EXISTS) {
		startupErrorMessage("Another instance of The Forgotten Server is already running with the same login port, please shut it down first or change ports for this one.");
		return;
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}

	DatabaseManager::updateDatabase();
	DatabaseManager::checkEncryption();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	//load vocations
	std::cout << ">> Loading vocations" << std::endl;
	if (!g_vocations.loadFromXml()) {
		startupErrorMessage("Unable to load vocations!");
		return;
	}

	//load commands
	std::cout << ">> Loading commands" << std::endl;
	if (!g_commands.loadFromXml()) {
		startupErrorMessage("Unable to load commands!");
		return;
	}

	// load item data
	std::cout << ">> Loading items" << std::endl;
	if (Item::items.loadFromOtb("data/items/items.otb")) {
		startupErrorMessage("Unable to load items (OTB)!");
		return;
	}

	if (!Item::items.loadFromXml()) {
		startupErrorMessage("Unable to load items (XML)!");
		return;
	}

	std::cout << ">> Loading script systems" << std::endl;
	if (!ScriptingManager::getInstance()->loadScriptSystems()) {
		startupErrorMessage("Failed to load script systems");
		return;
	}

	std::cout << ">> Loading monsters" << std::endl;
	if (!g_monsters.loadFromXml()) {
		startupErrorMessage("Unable to load monsters!");
		return;
	}

	std::cout << ">> Loading outfits" << std::endl;
	Outfits* outfits = Outfits::getInstance();
	if (!outfits->loadFromXml()) {
		startupErrorMessage("Unable to load outfits!");
		return;
	}

	g_adminConfig = new AdminProtocolConfig();
	std::cout << ">> Loading admin protocol config" << std::endl;
	if (!g_adminConfig->loadXMLConfig()) {
		startupErrorMessage("Unable to load admin protocol config!");
		return;
	}

	std::cout << ">> Loading experience stages" << std::endl;
	if (!g_game.loadExperienceStages()) {
		startupErrorMessage("Unable to load experience stages!");
		return;
	}

	std::string passwordType = asLowerCaseString(g_config.getString(ConfigManager::PASSWORDTYPE));
	if (passwordType == "sha1") {
		g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_SHA1);
		std::cout << ">> Using SHA1 passwords" << std::endl;
	} else {
		g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_PLAIN);
		std::cout << ">> Using plaintext passwords" << std::endl;
	}

	std::cout << ">> Checking world type... " << std::flush;
	std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
	if (worldType == "pvp") {
		g_game.setWorldType(WORLD_TYPE_PVP);
	} else if (worldType == "no-pvp") {
		g_game.setWorldType(WORLD_TYPE_NO_PVP);
	} else if (worldType == "pvp-enforced") {
		g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
	} else {
		std::cout << std::endl;

		std::ostringstream ss;
		ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced.";
		startupErrorMessage(ss.str());
		return;
	}
	std::cout << asUpperCaseString(worldType) << std::endl;

	std::cout << ">> Loading map" << std::endl;

	if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
		startupErrorMessage("Failed to load map");
		return;
	}

	std::cout << ">> Initializing gamestate" << std::endl;
	g_game.setGameState(GAME_STATE_INIT);

	// Tibia protocols
	services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	// OT protocols
	services->add<ProtocolAdmin>(g_config.getNumber(ConfigManager::ADMIN_PORT));
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	// Legacy protocols
	services->add<ProtocolOldLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	services->add<ProtocolOldGame>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	int32_t autoSaveEachMinutes = g_config.getNumber(ConfigManager::AUTO_SAVE_EACH_MINUTES);
	if (autoSaveEachMinutes > 0) {
		g_scheduler->addEvent(createSchedulerTask(autoSaveEachMinutes * 1000 * 60, std::bind(&Game::autoSave, &g_game)));
	}

	if (g_config.getBoolean(ConfigManager::SERVERSAVE_ENABLED)) {
		int32_t serverSaveHour = g_config.getNumber(ConfigManager::SERVERSAVE_H);
		if (serverSaveHour >= 0 && serverSaveHour <= 24) {
			time_t timeNow = time(nullptr);
			tm* timeinfo = localtime(&timeNow);

			if (serverSaveHour == 0) {
				serverSaveHour = 23;
			} else {
				serverSaveHour--;
			}

			timeinfo->tm_hour = serverSaveHour;
			timeinfo->tm_min = 55;
			timeinfo->tm_sec = 0;

			double difference = difftime(mktime(timeinfo), timeNow);
			if (difference < 0) {
				difference += 86400;
			}
			g_scheduler->addEvent(createSchedulerTask(difference * 1000, std::bind(&Game::prepareServerSave, &g_game)));
		}
	}

	Houses::getInstance().payHouses();
	IOLoginData::updateHouseOwners();
	g_game.checkExpiredMarketOffers();
	IOMarket::getInstance()->updateStatistics();

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#if !defined(WIN32) && !defined(__ROOT_PERMISSION__)
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> WARNING: " << STATUS_SERVER_NAME << " has been executed as root user, it is recommended to execute is as a normal user." << std::endl;
	}
#endif

	g_game.start(services);
	g_game.setGameState(GAME_STATE_NORMAL);
	g_loaderSignal.notify_all();
}
Example #6
0
void mainLoader(int, char*[], ServiceManager* services)
{
	//dispatcher thread
	g_game.setGameState(GAME_STATE_STARTUP);

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Versao " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compilado com " << BOOST_COMPILER << std::endl;
	std::cout << "Compilado em " << __DATE__ << ' ' << __TIME__ << " para plataforma ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "desconhecida" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "Este servidor foi desenvolvido por " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visite nosso forum para updates, suporte e pedidos: http://xtibia.com/." << std::endl;
	std::cout << "Um oferecimento OTPanel, OTserv Cloud em 60s." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Carregando configuracoes" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Falha ao carregar o config.lua!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Estabilizando conexao com o banco de dados..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Falha ao conectar-se com o banco de dados.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Carregando banco de dados" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("O banco de dados que especificou no config.lua esta vazio, por favor importar o schema.sql para seu banco de dados.");
		return;
	}
	g_databaseTasks.start();

	DatabaseManager::updateDatabase();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> Nenhuma tabela foi otimizada." << std::endl;
	}

	//load vocations
	std::cout << ">> Carregando vocacoes" << std::endl;
	if (!g_vocations.loadFromXml()) {
		startupErrorMessage("Impossivel carregar vocacoes!");
		return;
	}

	// load item data
	std::cout << ">> Carregando items" << std::endl;
	if (Item::items.loadFromOtb("data/items/items.otb") != ERROR_NONE) {
		startupErrorMessage("Impossivel carregar items (OTB)!");
		return;
	}

	if (!Item::items.loadFromXml()) {
		startupErrorMessage("Impossivel carregar (XML)!");
		return;
	}

	std::cout << ">> Carregando sistemas de scripts" << std::endl;
	if (!ScriptingManager::getInstance()->loadScriptSystems()) {
		startupErrorMessage("Impossivel carregar sistemas de scripts");
		return;
	}

	std::cout << ">> Carregando criaturas" << std::endl;
	if (!g_monsters.loadFromXml()) {
		startupErrorMessage("Impossivel carregar criaturas!");
		return;
	}

	std::cout << ">> Carregando outfits" << std::endl;
	Outfits* outfits = Outfits::getInstance();
	if (!outfits->loadFromXml()) {
		startupErrorMessage("Impossivel carregar outfits!");
		return;
	}

	std::cout << ">> Checando tipo do servidor... " << std::flush;
	std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
	if (worldType == "pvp") {
		g_game.setWorldType(WORLD_TYPE_PVP);
	} else if (worldType == "no-pvp") {
		g_game.setWorldType(WORLD_TYPE_NO_PVP);
	} else if (worldType == "pvp-enforced") {
		g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
	} else {
		std::cout << std::endl;

		std::ostringstream ss;
		ss << "> ERRO: Tipo do servidor desconhecido: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", os tipos validos sao: pvp, no-pvp and pvp-enforced.";
		startupErrorMessage(ss.str());
		return;
	}
	std::cout << asUpperCaseString(worldType) << std::endl;

	std::cout << ">> Carregando mapa" << std::endl;
	if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
		startupErrorMessage("Impossivel carregar o mapa");
		return;
	}

	std::cout << ">> Inicializando o servidor" << std::endl;
	g_game.setGameState(GAME_STATE_INIT);

	// Game client protocols
	services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	// OT protocols
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	// Legacy login protocol
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	RentPeriod_t rentPeriod;
	std::string strRentPeriod = asLowerCaseString(g_config.getString(ConfigManager::HOUSE_RENT_PERIOD));

	if (strRentPeriod == "yearly") {
		rentPeriod = RENTPERIOD_YEARLY;
	} else if (strRentPeriod == "weekly") {
		rentPeriod = RENTPERIOD_WEEKLY;
	} else if (strRentPeriod == "monthly") {
		rentPeriod = RENTPERIOD_MONTHLY;
	} else if (strRentPeriod == "daily") {
		rentPeriod = RENTPERIOD_DAILY;
	} else {
		rentPeriod = RENTPERIOD_NEVER;
	}

	g_game.map.houses.payHouses(rentPeriod);

	IOMarket::checkExpiredOffers();
	IOMarket::getInstance()->updateStatistics();

	std::cout << ">> Todos os modulos carregados, servidor iniciando..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Aviso: O servidor foi executado com usuario root, por favor considere executa-lo como um usuario normal." << std::endl;
	}
#endif

	g_game.start(services);
	g_game.setGameState(GAME_STATE_NORMAL);
	g_loaderSignal.notify_all();
}
Example #7
0
void func()
{
    // Logging stuff.
    boost::log::add_common_attributes();
    boost::shared_ptr< boost::log::core > pCore = boost::log::core::get();
    pCore->add_global_attribute(
        "Scope", boost::make_shared< boost::log::attributes::named_scope >());
    const Util::LogLevel logLevel = LOG_DEBUG;

    boost::log::init_log_to_console
    (
        std::cout, 
        boost::log::keywords::filter = 
        boost::log::filters::attr< LogLevel >( "Severity" ) >= logLevel,
        boost::log::keywords::format = boost::log::formatters::format( "[%1%] [%2%] <%3%> %4%" )
        % boost::log::formatters::date_time( "TimeStamp", "%d.%m-%H:%M:%S.%f" )
        % boost::log::formatters::attr< String >( "Channel" )
        % boost::log::formatters::attr< LogLevel >( "Severity" )
        % boost::log::formatters::message()
    );
    boost::log::init_log_to_file
    (
        boost::log::keywords::file_name = "Log_%d.%m.%y.log",
        boost::log::keywords::open_mode = std::ios::app,
        boost::log::keywords::filter = 
        boost::log::filters::attr< LogLevel >( "Severity" ) >= logLevel,
        boost::log::keywords::format = boost::log::formatters::format( "[%1%] [%2%] <%3%> %4%" )
        % boost::log::formatters::date_time( "TimeStamp", "%H:%M:%S.%f" )
        % boost::log::formatters::attr< String >( "Channel" )
        % boost::log::formatters::attr< LogLevel >( "Severity" )
        % boost::log::formatters::message()
    );

    // Config load
    ConfigManager configManager;
    if( !configManager.load() )
        LOGE << "Config file was not loaded.";

    // Add component factories

    // Add plugin factories
    TemplatePluginFactory<PermissionManager, ServerPluginManager>::registerFactory();
    TemplatePluginFactory<ServerNeighborsPlugin, ServerPluginManager>::registerFactory();
    ObjectManagerFactory<ClientObjectManager, ServerPluginManager>::registerFactory( updateSignal );

    // Delay client startup for the server
    RakSleep( 1000 );

    // Set up communication
    GridManager* gridManager = new GridManager( updateSignal );
    Server& server = gridManager->createServer( GridPosition( 0, 0 ), ServerInfo( "127.0.0.1", 8500 ) );
    ServerPluginManager& pluginManager = server.getPluginManager();

    // Set up DelayedCall.
    DelayedCall::setUpdateSignal( updateSignal );

    // Enter infinite loop to run the system
    LOGI << "Client initialized.";

    static int counter = 1;
    srand( time( NULL ) );
    static int random = (int)Math::RangeRandom( -1000000, 1000000 );
    bool quit=false;
    while (!quit)
    {
        if ( kbhit() )
        {
            char ch;
            ch=getch();
            if (ch=='q' || ch=='Q')
            {
                LOGI << "Quitting.";
                quit=true;
            }
            if (ch=='c' || ch=='C')
            {
                // Create local object and make it remote if everything can be created.
                try
                {
                    StringStream ss;
                    ss << "ClientObject" << random << counter;

                    ss << "a";
                    Object& object1 = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );
                    ss << "b";
                    Object& object2 = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );
                    ss << "c";
                    Object& object3 = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );
                    ss << "d";
                    Object& object4 = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );
                    ss << "e";
                    Object& object5 = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );

                    object5.parent( &object4 );
                    object4.parent( &object3 );
                    object3.parent( &object2 );
                    object2.parent( &object1 );

                    /*try
                    {
                        Position& position = object1.createComponent<Position>( "Position" );
                        object1.createComponent<Position>( "Position2" );
                        position.set( "Position", Vector3( Math::RangeRandom( -1337.0, 1337.0 ) ) );
                        LOGD << "Position: " << position.get( "Position" ).to<Vector3>();
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not create component: " << e.getDescription();
                        pluginManager.getPlugin<ClientObjectManager>().destroyObject( ss.str() );
                    }*/

                    try
                    {
                        object1.setNetworkingType( REMOTE );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not set object to remote: " << e.getDescription();
                        pluginManager.getPlugin<ClientObjectManager>().destroyObjectTree( object1 );
                    }

                    counter++;
                }
                catch ( Exception e )
                {
                    LOGE << "Could not create object: " << e.getDescription();
                }
            }
            if (ch=='v' || ch=='V')
            {
                // Create local object.
                try
                {
                    StringStream ss;
                    ss << "ClientObject" << random << counter;

                    Object& object = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), LOCAL );

                    /*try
                    {
                        object.createComponent<Position>( "Position" );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not create component: " << e.getDescription();

                        pluginManager.getPlugin<ClientObjectManager>().destroyObject( ss.str() );
                    }*/

                    counter++;
                }
                catch ( Exception e )
                {
                    LOGE << "Could not create object: " << e.getDescription();
                }
            }
            if (ch=='b' || ch=='B')
            {
                // Create remote object and make it local.
                try
                {
                    StringStream ss;
                    ss << "ClientObject" << random << counter;

                    Object& object = pluginManager.getPlugin<ClientObjectManager>().createObject( 
                        ss.str(), REMOTE );

                    /*try
                    {
                        object.createComponent<Position>( "Position" );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not create component: " << e.getDescription();
                        pluginManager.getPlugin<ClientObjectManager>().destroyObject( ss.str() );
                    }*/

                    try
                    {
                        object.setNetworkingType( LOCAL );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not set object to local: " << e.getDescription();
                        pluginManager.getPlugin<ClientObjectManager>().destroyObject( ss.str() );
                    }

                    counter++;
                }
                catch ( Exception e )
                {
                    LOGE << "Could not create object: " << e.getDescription();
                }
            }
            if (ch=='d' || ch=='D')
            {
                // Destroy all objects.
                LOGI << "Broadcasting destruction for all objects.";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    try
                    {
                        pluginManager.getPlugin<ClientObjectManager>().destroyObject( i->first );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not destroy object: " << e.getDescription();
                    }
                }
            }
            if (ch=='f' || ch=='F')
            {
                // Destroy all componens.
                LOGI << "Broadcasting destruction for all components.";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    try
                    {
                        const ComponentsByType& components = i->second->getComponentsByType();
                        for( ComponentsByType::const_iterator j = components.begin(); 
                            j != components.end(); ++j )
                        {
                            pluginManager.getPlugin<ClientObjectManager>().getObject( i->first ).destroyComponent( j->first );
                        }
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not destroy object: " << e.getDescription();
                    }
                }
            }
            if (ch=='l' || ch=='L')
            {
                // List all objects.
                LOGI << "Listing all objects:";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    LOGI    << "[" << i->second->getName() << "]"
                            << " T:" << i->second->getNetworkingType()
                            << " S:" << i->second->getSource()
                            << " SID:" << i->second->GetCreatingSystemGUID().g
                            //<< " Pos: " << ( i->second->hasComponent<Position>() ? i->second->getComponent<Position>().get( "Position" ).to<Vector3>() : "No position" )
                            << " Parent: " << ( i->second->hasParent() ? i->second->getParent()->getName() : "No parent" );
                }
            }
            if (ch=='r' || ch=='R')
            {
                // Change all objects to remote.
                LOGI << "Setting all objects to remote.";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    try
                    {
                        i->second->setNetworkingType( REMOTE );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not set object to remote: " << e.getDescription();
                    }
                }
            }
            if (ch=='t' || ch=='T')
            {
                // Change all objects to local.
                LOGI << "Setting all objects to local.";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    try
                    {
                        i->second->setNetworkingType( LOCAL );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not set object to local: " << e.getDescription();
                    }
                }
            }
            if (ch=='s' || ch=='S')
            {
                // Change position for all objects.
                LOGI << "Setting position for all position components.";

                const Objects& objects = pluginManager.getPlugin<ClientObjectManager>().getObjects();
                for( Objects::const_iterator i = objects.begin(); i != objects.end(); ++i )
                {
                    /*try
                    {
                        Vector3 random = Vector3( Math::RangeRandom( -1337.0, 1337.0 ) );
                        camp::Value val = random;
                        i->second->getComponent<Position>().set( "Position", 
                           val );
                    }
                    catch ( Exception e )
                    {
                        LOGE << "Could not set position: " << e.getDescription();
                    }*/
                }
            }
        }

        updateSignal();

        RakSleep( 10 );
    }

    // Remove grid.
    delete gridManager;

    // Config save
    if( configManager.save() )
        LOGE << "Config file was not saved.";
}
Example #8
0
void otserv(StringVec, ServiceManager* services)
{
	srand((uint32_t)OTSYS_TIME());
#if defined(WINDOWS)
	SetConsoleTitle(SOFTWARE_NAME);

#endif
	g_game.setGameState(GAMESTATE_STARTUP);
#if !defined(WINDOWS) && !defined(__ROOT_PERMISSION__)
	if(!getuid() || !geteuid())
	{
		std::clog << "> WARNING: " << SOFTWARE_NAME << " has been executed as super user! It is "
			<< "recommended to run as a normal user." << std::endl << "Continue? (y/N)" << std::endl;
		char buffer = getch();
		if(buffer != 121 && buffer != 89)
			startupErrorMessage("Aborted.");
	}
#endif

	std::clog << SOFTWARE_NAME << " " << SOFTWARE_VERSION << std::endl << std::endl;
	std::stringstream ss;
#ifdef __DEBUG__
	ss << " GLOBAL";
#endif
#ifdef __DEBUG_MOVESYS__
	ss << " MOVESYS";
#endif
#ifdef __DEBUG_CHAT__
	ss << " CHAT";
#endif
#ifdef __DEBUG_EXCEPTION_REPORT__
	ss << " EXCEPTION-REPORT";
#endif
#ifdef __DEBUG_HOUSES__
	ss << " HOUSES";
#endif
#ifdef __DEBUG_LUASCRIPTS__
	ss << " LUA-SCRIPTS";
#endif
#ifdef __DEBUG_MAILBOX__
	ss << " MAILBOX";
#endif
#ifdef __DEBUG_NET__
	ss << " NET";
#endif
#ifdef __DEBUG_NET_DETAIL__
	ss << " NET-DETAIL";
#endif
#ifdef __DEBUG_RAID__
	ss << " RAIDS";
#endif
#ifdef __DEBUG_SCHEDULER__
	ss << " SCHEDULER";
#endif
#ifdef __DEBUG_SPAWN__
	ss << " SPAWNS";
#endif
#ifdef __SQL_QUERY_DEBUG__
	ss << " SQL-QUERIES";
#endif

	std::string debug = ss.str();
	if(!debug.empty())
		std::clog << ">> Debugging:" << debug << "." << std::endl;

	std::clog << ">> Loading config (" << g_config.getString(ConfigManager::CONFIG_FILE) << ")" << std::endl;
	if(!g_config.load())
		startupErrorMessage("Unable to load " + g_config.getString(ConfigManager::CONFIG_FILE) + "!");

	// silently append trailing slash
	std::string path = g_config.getString(ConfigManager::DATA_DIRECTORY);
	g_config.setString(ConfigManager::DATA_DIRECTORY, path.erase(path.find_last_not_of("/") + 1) + "/");

	path = g_config.getString(ConfigManager::LOGS_DIRECTORY);
	g_config.setString(ConfigManager::LOGS_DIRECTORY, path.erase(path.find_last_not_of("/") + 1) + "/");

	std::clog << ">> Opening logs" << std::endl;
	Logger::getInstance()->open();

	IntegerVec cores = vectorAtoi(explodeString(g_config.getString(ConfigManager::CORES_USED), ","));
	if(cores[0] != -1)
	{
#ifdef WINDOWS
		int32_t mask = 0;
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			mask += 1 << (*it);

		SetProcessAffinityMask(GetCurrentProcess(), mask);
	}

	std::stringstream mutexName;
	mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::WORLD_ID);

	CreateMutex(NULL, FALSE, mutexName.str().c_str());
	if(GetLastError() == ERROR_ALREADY_EXISTS)
		startupErrorMessage("Another instance of The Forgotten Server is already running with the same worldId.\nIf you want to run multiple servers, please change the worldId in configuration file.");

	std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
	if(defaultPriority == "realtime")
		SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	else if(defaultPriority == "high")
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	else if(defaultPriority == "higher")
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);

#else
#ifndef MACOS
		cpu_set_t mask;
		CPU_ZERO(&mask);
		for(IntegerVec::iterator it = cores.begin(); it != cores.end(); ++it)
			CPU_SET((*it), &mask);

		sched_setaffinity(getpid(), (int32_t)sizeof(mask), &mask);
	}
Example #9
0
void mainLoader(int, char*[], ServiceManager* services)
{

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compiled with " << BOOST_COMPILER << std::endl;
	std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "unknown" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

	std::cout << ">> Loading gameserver config..." << std::endl;

	if (!g_gameserver.load()) {
		startupErrorMessage("Unable to load gameservers!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	
	//cipsoft
	const char* p("12017580013707233233987537782574702577133548287527131234152948150506251412291888866940292054989907714155267326586216043845592229084368540020196135619327879");
	const char* q("11898921368616868351880508246112101394478760265769325412746398405473436969889506919017477758618276066588858607419440134394668095105156501566867770737187273");
	
	//opentibia
	/*
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	*/

	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}

	g_databaseTasks.start();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	// Game client protocols
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	// OT protocols
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	//check each 1 minute for player amount and record
	ProtocolStatus::getPlayerRecordAndPlayerAmount();

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
	}
#endif

	g_loaderSignal.notify_all();
}