Beispiel #1
0
bool EQLConfig::BootStaticZone(Const_char *short_name, uint16 port) {
	//make sure the short name is valid.
	if(database.GetZoneID(short_name) == 0)
		return false;

	//database update
	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

    std::string query = StringFormat("INSERT INTO launcher_zones (launcher, zone, port) "
                                    "VALUES('%s', '%s', %d)", namebuf, zonebuf, port);
    auto results = database.QueryDatabase(query);
	if (!results.Success()) {
		return false;
	}

	//update our internal state.
	LauncherZone lz;
	lz.name = short_name;
	lz.port = port;
	m_zones[lz.name] = lz;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->BootZone(short_name, port);
	}

	return true;
}
Beispiel #2
0
void EQLConfig::DeleteLauncher() {

	launcher_list.Remove(m_name.c_str());

	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"DELETE FROM launcher WHERE name='%s'",
		namebuf), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in DeleteLauncher 1 query: %s", errbuf);
		safe_delete_array(query);
		return;
	}
	safe_delete_array(query);

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"DELETE FROM launcher_zones WHERE launcher='%s'",
		namebuf), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in DeleteLauncher 2 query: %s", errbuf);
		safe_delete_array(query);
		return;
	}
	safe_delete_array(query);
}
Beispiel #3
0
map<string,string> EQW::GetZoneDetails(Const_char *zone_ref) {
	map<string,string> res;
	
	ZoneServer *zs = zoneserver_list.FindByID(atoi(zone_ref));
	if(zs == NULL) {
		res["error"] = "Invalid zone.";
		return(res);
	}
	
	res["type"] = zs->IsStaticZone()?"static":"dynamic";
	res["zone_id"] = itoa(zs->GetZoneID());
	res["launch_name"] = zs->GetLaunchName();
	res["launched_name"] = zs->GetLaunchedName();
	res["short_name"] = zs->GetZoneName();
	res["long_name"] = zs->GetZoneLongName();
	res["port"] = itoa(zs->GetCPort());
	res["player_count"] = itoa(zs->NumPlayers());
	
	//this isnt gunna work for dynamic zones...
	res["launcher"] = "";
	if(zs->GetZoneID() != 0) {
		LauncherLink *ll = launcher_list.FindByZone(zs->GetLaunchName());
		if(ll != NULL)
			res["launcher"] = ll->GetName();
	}
	
	return(res);
}
Beispiel #4
0
bool EQLConfig::DeleteStaticZone(Const_char *short_name) {
	//check internal state
	std::map<std::string, LauncherZone>::iterator res;
	res = m_zones.find(short_name);
	if(res == m_zones.end()) {
		//not found.
		Log.Out(Logs::General, Logs::Error, "Update for unknown zone %s", short_name);
		return false;
	}

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

    std::string query = StringFormat("DELETE FROM launcher_zones WHERE "
                                    "launcher = '%s' AND zone = '%s'", namebuf, zonebuf);
    auto results = database.QueryDatabase(query);
	if (!results.Success()) {
		return false;
	}

	//internal update.
	m_zones.erase(res);

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->StopZone(short_name);
	}

	return true;
}
Beispiel #5
0
bool EQLConfig::SetDynamicCount(int count) {
	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"UPDATE launcher SET dynamics=%d WHERE name='%s'",
		count, namebuf), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in SetDynamicCount query: %s", errbuf);
		safe_delete_array(query);
		return false;
	}
	safe_delete_array(query);

	//update in-memory version.
	m_dynamics = count;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->BootDynamics(count);
	}

	return(false);
}
Beispiel #6
0
int EQW::CountLaunchers(bool active_only) {
	if(active_only)
		return(launcher_list.GetLauncherCount());
	
	vector<string> it(EQW::ListLaunchers());
	return(it.size());
}
Beispiel #7
0
vector<string> EQW::ListLaunchers() {
//	vector<string> list;
//	database.GetLauncherList(list);
	vector<string> launchers;
	launcher_list.GetLauncherNameList(launchers);
	return(launchers);
	
/*	if(list.empty()) {
		return(launchers);
	} else if(launchers.empty()) {
		return(list);
	}
	
	//union the two lists.
	vector<string>::iterator curo, endo, curi, endi;
	curo = list.begin();
	endo = list.end();
	for(; curo != endo; curo++) {
		bool found = false;
		curi = launchers.begin();
		endi = launchers.end();
		for(; curi != endi; curi++) {
			if(*curo == *curi) {
				found = true;
				break;
			}
		}
		if(found)
			break;
		launchers.push_back(*curo);
	}
	return(launchers);*/
}
Beispiel #8
0
std::map<std::string,std::string> EQLConfig::GetZoneDetails(Const_char *zone_ref) {
	std::map<std::string,std::string> res;

	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll == nullptr) {
		res["name"] = zone_ref;
		res["up"] = "0";
		res["starts"] = "0";
		res["port"] = "0";
	} else {
		ll->GetZoneDetails(zone_ref, res);
	}

	return(res);
}
Beispiel #9
0
bool EQLConfig::ChangeStaticZone(Const_char *short_name, uint16 port) {
	//make sure the short name is valid.
	if(database.GetZoneID(short_name) == 0)
		return(false);

	//check internal state
	std::map<std::string, LauncherZone>::iterator res;
	res = m_zones.find(short_name);
	if(res == m_zones.end()) {
		//not found.
		LogFile->write(EQEMuLog::Error, "Update for unknown zone %s", short_name);
		return(false);
	}


	//database update
	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"UPDATE launcher_zones SET port=%d WHERE launcher='%s' AND zone='%s'",
		port, namebuf, zonebuf), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in ChangeStaticZone query: %s", errbuf);
		safe_delete_array(query);
		return false;
	}
	safe_delete_array(query);


	//update internal state
	res->second.port = port;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->RestartZone(short_name);
	}

	return(true);
}
Beispiel #10
0
std::vector<std::string> EQLConfig::ListZones() {
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	std::vector<std::string> res;
	if(ll == nullptr) {
		//if the launcher isnt connected, use the list from the database.
		std::map<std::string, LauncherZone>::iterator cur, end;
		cur = m_zones.begin();
		end = m_zones.end();
		for(; cur != end; cur++) {
			res.push_back(cur->first);
		}
	} else {
		//otherwise, use the zone list from the launcher link.
		ll->GetZoneList(res);
	}
	return(res);
}
Beispiel #11
0
void EQLConfig::DeleteLauncher() {

	launcher_list.Remove(m_name.c_str());

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';

    std::string query = StringFormat("DELETE FROM launcher WHERE name = '%s'", namebuf);
    auto results = database.QueryDatabase(query);
	if (!results.Success()) {
		return;
	}

    query = StringFormat("DELETE FROM launcher_zones WHERE launcher = '%s'", namebuf);
    results = database.QueryDatabase(query);
	if (!results.Success()) {
		return;
	}
}
Beispiel #12
0
bool EQLConfig::DeleteStaticZone(Const_char *short_name) {
	//check internal state
	std::map<std::string, LauncherZone>::iterator res;
	res = m_zones.find(short_name);
	if(res == m_zones.end()) {
		//not found.
		LogFile->write(EQEMuLog::Error, "Update for unknown zone %s", short_name);
		return(false);
	}

	//database update
	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"DELETE FROM launcher_zones WHERE launcher='%s' AND zone='%s'",
		namebuf, zonebuf), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in DeleteStaticZone query: %s", errbuf);
		safe_delete_array(query);
		return false;
	}
	safe_delete_array(query);

	//internal update.
	m_zones.erase(res);

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->StopZone(short_name);
	}

	return true;
}
Beispiel #13
0
bool EQLConfig::ChangeStaticZone(Const_char *short_name, uint16 port) {
	//make sure the short name is valid.
	if(database.GetZoneID(short_name) == 0)
		return false;

	//check internal state
	std::map<std::string, LauncherZone>::iterator res;
	res = m_zones.find(short_name);
	if(res == m_zones.end()) {
		//not found.
		Log.Out(Logs::General, Logs::Error, "Update for unknown zone %s", short_name);
		return false;
	}

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

    std::string query = StringFormat("UPDATE launcher_zones SET port=%d WHERE "
                                    "launcher = '%s' AND zone = '%s'",port, namebuf, zonebuf);
    auto results = database.QueryDatabase(query);
	if (!results.Success()) {
		return false;
	}

	//update internal state
	res->second.port = port;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->RestartZone(short_name);
	}

	return true;
}
Beispiel #14
0
bool EQLConfig::BootStaticZone(Const_char *short_name, uint16 port) {
	//make sure the short name is valid.
	if(database.GetZoneID(short_name) == 0)
		return(false);

	//database update
	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';
	char zonebuf[32];
	database.DoEscapeString(zonebuf, short_name, strlen(short_name)&0xF);	//limit len to 16
	zonebuf[31] = '\0';

	if (!database.RunQuery(query, MakeAnyLenString(&query,
		"INSERT INTO launcher_zones (launcher,zone,port) VALUES('%s', '%s', %d)",
		namebuf, zonebuf, port), errbuf)) {
		LogFile->write(EQEMuLog::Error, "Error in BootStaticZone query: %s", errbuf);
		safe_delete_array(query);
		return false;
	}
	safe_delete_array(query);

	//update our internal state.
	LauncherZone lz;
	lz.name = short_name;
	lz.port = port;
	m_zones[lz.name] = lz;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->BootZone(short_name, port);
	}

	return(true);
}
Beispiel #15
0
bool EQLConfig::SetDynamicCount(int count) {

	char namebuf[128];
	database.DoEscapeString(namebuf, m_name.c_str(), m_name.length()&0x3F);	//limit len to 64
	namebuf[127] = '\0';

    std::string query = StringFormat("UPDATE launcher SET dynamics=%d WHERE name='%s'", count, namebuf);
    auto results = database.QueryDatabase(query);
	if (!results.Success()) {
		return false;
	}

	//update in-memory version.
	m_dynamics = count;

	//if the launcher is connected, update it.
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll != nullptr) {
		ll->BootDynamics(count);
	}

	return false;
}
Beispiel #16
0
int main(int argc, char** argv) {
    RegisterExecutablePlatform(ExePlatformWorld);
    set_exception_handler();

	// Load server configuration
	_log(WORLD__INIT, "Loading server configuration..");
	if (!WorldConfig::LoadConfig()) {
		_log(WORLD__INIT_ERR, "Loading server configuration failed.");
		return(1);
	}
	const WorldConfig *Config=WorldConfig::get();

	if(!load_log_settings(Config->LogSettingsFile.c_str()))
		_log(WORLD__INIT, "Warning: Unable to read %s", Config->LogSettingsFile.c_str());
	else
		_log(WORLD__INIT, "Log settings loaded from %s", Config->LogSettingsFile.c_str());


	_log(WORLD__INIT, "CURRENT_VERSION: %s", CURRENT_VERSION);
	
	#ifdef _DEBUG
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	#endif
	
	if (signal(SIGINT, CatchSignal) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	if (signal(SIGTERM, CatchSignal) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	#ifndef WIN32
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	#endif

	// add login server config to list
	if (Config->LoginCount == 0) {
		if (Config->LoginHost.length()) {
			loginserverlist.Add(Config->LoginHost.c_str(), Config->LoginPort, Config->LoginAccount.c_str(), Config->LoginPassword.c_str());
			_log(WORLD__INIT, "Added loginserver %s:%i", Config->LoginHost.c_str(), Config->LoginPort);
		}
	} else {
		LinkedList<LoginConfig*> loginlist=Config->loginlist;
		LinkedListIterator<LoginConfig*> iterator(loginlist);
		iterator.Reset();
		while(iterator.MoreElements()) {
			loginserverlist.Add(iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort, iterator.GetData()->LoginAccount.c_str(), iterator.GetData()->LoginPassword.c_str());
			_log(WORLD__INIT, "Added loginserver %s:%i", iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort);
			iterator.Advance();
		}
	}
	
	_log(WORLD__INIT, "Connecting to MySQL...");
	if (!database.Connect(
		Config->DatabaseHost.c_str(),
		Config->DatabaseUsername.c_str(),
		Config->DatabasePassword.c_str(),
		Config->DatabaseDB.c_str(),
		Config->DatabasePort)) {
		_log(WORLD__INIT_ERR, "Cannot continue without a database connection.");
		return(1);
	}
	dbasync = new DBAsync(&database);
	guild_mgr.SetDatabase(&database);
	
	if (argc >= 2) {
		char tmp[2];
		if (strcasecmp(argv[1], "help") == 0 || strcasecmp(argv[1], "?") == 0 || strcasecmp(argv[1], "/?") == 0 || strcasecmp(argv[1], "-?") == 0 || strcasecmp(argv[1], "-h") == 0 || strcasecmp(argv[1], "-help") == 0) {
			cout << "Worldserver command line commands:" << endl;
			cout << "adduser username password flag    - adds a user account" << endl;
			cout << "flag username flag    - sets GM flag on the account" << endl;
			cout << "startzone zoneshortname    - sets the starting zone" << endl;
			cout << "-holdzones    - reboots lost zones" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "-holdzones") == 0) {
			cout << "Reboot Zones mode ON" << endl;
			holdzones = true;
		}
		else if (database.GetVariable("disablecommandline", tmp, 2)) {
			if (strlen(tmp) == 1) {
				if (tmp[0] == '1') {
					cout << "Command line disabled in database... exiting" << endl;
					return 0;
				}
			}
		}
		else if (strcasecmp(argv[1], "adduser") == 0) {
			if (argc == 5) {
				if (Seperator::IsNumber(argv[4])) {
					if (atoi(argv[4]) >= 0 && atoi(argv[4]) <= 255) {
						if (database.CreateAccount(argv[2], argv[3], atoi(argv[4])) == 0)
							cout << "database.CreateAccount failed." << endl;
						else
							cout << "Account created: Username='******', Password='******', status=" << argv[4] << endl;
						return 0;
					}
				}
			}
			cout << "Usage: world adduser username password flag" << endl;
			cout << "flag = 0, 1 or 2" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "flag") == 0) {
			if (argc == 4) {
				if (Seperator::IsNumber(argv[3])) {

					if (atoi(argv[3]) >= 0 && atoi(argv[3]) <= 255) {
						if (database.SetAccountStatus(argv[2], atoi(argv[3])))
							cout << "Account flagged: Username='******', status=" << argv[3] << endl;
						else
							cout << "database.SetAccountStatus failed." << endl;
						return 0;
					}
				}
			}
			cout << "Usage: world flag username flag" << endl;
			cout << "flag = 0-200" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "startzone") == 0) {
			if (argc == 3) {
				if (strlen(argv[2]) < 3) {
					cout << "Error: zone name too short" << endl;
				}
				else if (strlen(argv[2]) > 15) {
					cout << "Error: zone name too long" << endl;
				}
				else {
					if (database.SetVariable("startzone", argv[2]))
						cout << "Starting zone changed: '" << argv[2] << "'" << endl;
					else
						cout << "database.SetVariable failed." << endl;
				}
				return 0;
			}
			cout << "Usage: world startzone zoneshortname" << endl;
			return 0;
		}
		else {
			cout << "Error, unknown command line option" << endl;
			return 0;
		}
	}
	
	if(Config->WorldHTTPEnabled) {
		_log(WORLD__INIT, "Starting HTTP world service...");
		http_server.Start(Config->WorldHTTPPort, Config->WorldHTTPMimeFile.c_str());
	} else {
		_log(WORLD__INIT, "HTTP world service disabled.");
	}
	
	_log(WORLD__INIT, "Loading variables..");
	database.LoadVariables();
	_log(WORLD__INIT, "Loading zones..");
	database.LoadZoneNames();
	_log(WORLD__INIT, "Clearing groups..");
	database.ClearGroup();
	_log(WORLD__INIT, "Clearing raids..");
	database.ClearRaid();
	database.ClearRaidDetails();
	_log(WORLD__INIT, "Loading items..");
	if (!database.LoadItems()) {
		_log(WORLD__INIT_ERR, "Error: Could not load item data.  But ignoring");
	}
	_log(WORLD__INIT, "Loading guilds..");
	guild_mgr.LoadGuilds();
	//rules:
	{
		char tmp[64];
		if (database.GetVariable("RuleSet", tmp, sizeof(tmp)-1)) {
			_log(WORLD__INIT, "Loading rule set '%s'", tmp);
			if(!RuleManager::Instance()->LoadRules(&database, tmp)) {
				_log(WORLD__INIT_ERR, "Failed to load ruleset '%s', falling back to defaults.", tmp);
			}
		} else {
			if(!RuleManager::Instance()->LoadRules(&database, "default")) {
				_log(WORLD__INIT, "No rule set configured, using default rules");
			} else {
				_log(WORLD__INIT, "Loaded default rule set 'default'", tmp);
			}
		}
	}
	if(RuleB(World, ClearTempMerchantlist)){
        _log(WORLD__INIT, "Clearing temporary merchant lists..");
		database.ClearMerchantTemp();
      }
	_log(WORLD__INIT, "Loading EQ time of day..");
	if (!zoneserver_list.worldclock.loadFile(Config->EQTimeFile.c_str()))
		_log(WORLD__INIT_ERR, "Unable to load %s", Config->EQTimeFile.c_str());
	_log(WORLD__INIT, "Loading launcher list..");
	launcher_list.LoadList();
	
	char tmp[20];
	tmp[0] = '\0';
	database.GetVariable("holdzones",tmp, 20);	
	if ((strcasecmp(tmp, "1") == 0)) {
		holdzones = true;
	}
	_log(WORLD__INIT, "Reboot zone modes %s",holdzones ? "ON" : "OFF");
	
	_log(WORLD__INIT, "Deleted %i stale player corpses from database", database.DeleteStalePlayerCorpses());
	if (RuleB(World, DeleteStaleCorpeBackups) == true) {
	_log(WORLD__INIT, "Deleted %i stale player backups from database", database.DeleteStalePlayerBackups());
	}

	_log(WORLD__INIT, "Loading adventures...");
	if(!adventure_manager.LoadAdventureTemplates())
	{
		_log(WORLD__INIT_ERR, "Unable to load adventure templates.");
	}

	if(!adventure_manager.LoadAdventureEntries())
	{
		_log(WORLD__INIT_ERR, "Unable to load adventure templates.");
	}

	adventure_manager.Load();
	adventure_manager.LoadLeaderboardInfo();

	_log(WORLD__INIT, "Purging expired instances");
	database.PurgeExpiredInstances();
	Timer PurgeInstanceTimer(450000);
	PurgeInstanceTimer.Start(450000);

    _log(WORLD__INIT, "Loading char create info...");
    database.LoadCharacterCreateAllocations();
    database.LoadCharacterCreateCombos();

	char errbuf[TCPConnection_ErrorBufferSize];
	if (tcps.Open(Config->WorldTCPPort, errbuf)) {
		_log(WORLD__INIT,"Zone (TCP) listener started.");
	} else {
		_log(WORLD__INIT_ERR,"Failed to start zone (TCP) listener on port %d:",Config->WorldTCPPort);
		_log(WORLD__INIT_ERR,"        %s",errbuf);
		return 1;
	}
	if (eqsf.Open()) {
		_log(WORLD__INIT,"Client (UDP) listener started.");
	} else {
		_log(WORLD__INIT_ERR,"Failed to start client (UDP) listener (port 9000)");
		return 1;
	}

	//register all the patches we have avaliable with the stream identifier.
	EQStreamIdentifier stream_identifier;
	RegisterAllPatches(stream_identifier);
	zoneserver_list.shutdowntimer = new Timer(60000);
	zoneserver_list.shutdowntimer->Disable();
	zoneserver_list.reminder = new Timer(20000);
	zoneserver_list.reminder->Disable();
	Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect
	InterserverTimer.Trigger();
	uint8 ReconnectCounter = 100;
	EQStream* eqs;
	EmuTCPConnection* tcpc;
	EQStreamInterface *eqsi;
	
	while(RunLoops) {
		Timer::SetCurrentTime();
		
		//check the factory for any new incoming streams.
		while ((eqs = eqsf.Pop())) {
			//pull the stream out of the factory and give it to the stream identifier
			//which will figure out what patch they are running, and set up the dynamic
			//structures and opcodes for that patch.
			struct in_addr	in;
			in.s_addr = eqs->GetRemoteIP();
			_log(WORLD__CLIENT, "New connection from %s:%d", inet_ntoa(in),ntohs(eqs->GetRemotePort()));
			stream_identifier.AddStream(eqs);	//takes the stream
		}
		
		//give the stream identifier a chance to do its work....
		stream_identifier.Process();
		
		//check the stream identifier for any now-identified streams
		while((eqsi = stream_identifier.PopIdentified())) {
			//now that we know what patch they are running, start up their client object
			struct in_addr	in;
			in.s_addr = eqsi->GetRemoteIP();
 			if (RuleB(World, UseBannedIPsTable)){ //Lieka:  Check to see if we have the responsibility for blocking IPs.
				_log(WORLD__CLIENT, "Checking inbound connection %s against BannedIPs table", inet_ntoa(in));
 				if (!database.CheckBannedIPs(inet_ntoa(in))){ //Lieka:  Check inbound IP against banned IP table.
 					_log(WORLD__CLIENT, "Connection %s PASSED banned IPs check.  Processing connection.", inet_ntoa(in));
 					Client* client = new Client(eqsi);
 					// @merth: client->zoneattempt=0;
 					client_list.Add(client);
 				} else {
 					_log(WORLD__CLIENT, "Connection from %s FAILED banned IPs check.  Closing connection.", inet_ntoa(in));
 					eqsi->Close(); //Lieka:  If the inbound IP is on the banned table, close the EQStream.
 				}
 			}
 			if (!RuleB(World, UseBannedIPsTable)){
 					_log(WORLD__CLIENT, "New connection from %s:%d, processing connection", inet_ntoa(in), ntohs(eqsi->GetRemotePort()));
 					Client* client = new Client(eqsi);
 					// @merth: client->zoneattempt=0;
 					client_list.Add(client);
 			}
		}
		
		client_list.Process();
		
		while ((tcpc = tcps.NewQueuePop())) {
			struct in_addr in;
			in.s_addr = tcpc->GetrIP();
			_log(WORLD__ZONE, "New TCP connection from %s:%d", inet_ntoa(in),tcpc->GetrPort());
			console_list.Add(new Console(tcpc));
		}

		if(PurgeInstanceTimer.Check())
		{
			database.PurgeExpiredInstances();
		}
		
		//check for timeouts in other threads
		timeout_manager.CheckTimeouts();
		
		loginserverlist.Process();
		
		console_list.Process();
		
		zoneserver_list.Process();
		
		launcher_list.Process();

		UCSLink.Process();
	
		QSLink.Process();

		LFPGroupList.Process();

		adventure_manager.Process();
		
		if (InterserverTimer.Check()) {
			InterserverTimer.Start();
			database.ping();
			AsyncLoadVariables(dbasync, &database);
			ReconnectCounter++;
			if (ReconnectCounter >= 12) { // only create thread to reconnect every 10 minutes. previously we were creating a new thread every 10 seconds
				ReconnectCounter = 0;
				if (loginserverlist.AllConnected() == false) {
#ifdef _WINDOWS
					_beginthread(AutoInitLoginServer, 0, nullptr);
#else
					pthread_t thread;
					pthread_create(&thread, nullptr, &AutoInitLoginServer, nullptr);
#endif
				}
			}
		}
		if (numclients == 0) {
			Sleep(50);
			continue;
		}
		Sleep(20);
	}
	_log(WORLD__SHUTDOWN,"World main loop completed.");
	_log(WORLD__SHUTDOWN,"Shutting down console connections (if any).");
	console_list.KillAll();
	_log(WORLD__SHUTDOWN,"Shutting down zone connections (if any).");
	zoneserver_list.KillAll();
	_log(WORLD__SHUTDOWN,"Zone (TCP) listener stopped.");
	tcps.Close();
	_log(WORLD__SHUTDOWN,"Client (UDP) listener stopped.");
	eqsf.Close();
	_log(WORLD__SHUTDOWN,"Signaling HTTP service to stop...");
	http_server.Stop();

	CheckEQEMuErrorAndPause();
	return 0;
}
Beispiel #17
0
bool LauncherLink::Process() {
	if (!tcpc->Connected())
		return false;

	if(m_bootTimer.Check(false)) {
		//force a boot on any zone which isnt running.
		std::map<std::string, ZoneState>::iterator cur, end;
		cur = m_states.begin();
		end = m_states.end();
		for(; cur != end; ++cur) {
			if(!cur->second.up) {
				StartZone(cur->first.c_str());
			}
		}
		m_bootTimer.Disable();
	}

	ServerPacket *pack = 0;
	while((pack = tcpc->PopPacket())) {
		_hex(WORLD__ZONE_TRACE,pack->pBuffer,pack->size);
		if (!authenticated) {
			if (WorldConfig::get()->SharedKey.length() > 0) {
				if (pack->opcode == ServerOP_ZAAuth && pack->size == 16) {
					uint8 tmppass[16];
					MD5::Generate((const uchar*) WorldConfig::get()->SharedKey.c_str(), WorldConfig::get()->SharedKey.length(), tmppass);
					if (memcmp(pack->pBuffer, tmppass, 16) == 0)
						authenticated = true;
					else {
						struct in_addr in;
						in.s_addr = GetIP();
						_log(WORLD__LAUNCH_ERR, "Launcher authorization failed.");
						ServerPacket* pack = new ServerPacket(ServerOP_ZAAuthFailed);
						SendPacket(pack);
						delete pack;
						Disconnect();
						return false;
					}
				}
				else {
					struct in_addr in;
					in.s_addr = GetIP();
					_log(WORLD__LAUNCH_ERR, "Launcher authorization failed.");
					ServerPacket* pack = new ServerPacket(ServerOP_ZAAuthFailed);
					SendPacket(pack);
					delete pack;
					Disconnect();
					return false;
				}
			}
			else
			{
				_log(WORLD__LAUNCH,"**WARNING** You have not configured a world shared key in your config file. You should add a <key>STRING</key> element to your <world> element to prevent unauthroized zone access.");
				authenticated = true;
			}
			delete pack;
			continue;
		}
		switch(pack->opcode) {
		case 0:
			break;
		case ServerOP_KeepAlive: {
			// ignore this
			break;
		}
		case ServerOP_ZAAuth: {
			_log(WORLD__LAUNCH, "Got authentication from %s when they are already authenticated.", m_name.c_str());
			break;
		}
		case ServerOP_LauncherConnectInfo: {
			const LauncherConnectInfo *it = (const LauncherConnectInfo *) pack->pBuffer;
			if(HasName()) {
				_log(WORLD__LAUNCH_ERR, "Launcher '%s' received an additional connect packet with name '%s'. Ignoring.", m_name.c_str(), it->name);
				break;
			}
			m_name = it->name;

			EQLConfig *config = launcher_list.GetConfig(m_name.c_str());
			if(config == nullptr) {
				_log(WORLD__LAUNCH, "Unknown launcher '%s' connected. Disconnecting.", it->name);
				Disconnect();
				break;
			}

			_log(WORLD__LAUNCH, "Launcher Identified itself as '%s'. Loading zone list.", it->name);

			std::vector<LauncherZone> result;
			//database.GetLauncherZones(it->name, result);
			config->GetZones(result);

			std::vector<LauncherZone>::iterator cur, end;
			cur = result.begin();
			end = result.end();
			ZoneState zs;
			for(; cur != end; cur++) {
				zs.port = cur->port;
				zs.up = false;
				zs.starts = 0;
				_log(WORLD__LAUNCH_TRACE, "%s: Loaded zone '%s' on port %d", m_name.c_str(), cur->name.c_str(), zs.port);
				m_states[cur->name] = zs;
			}

			//now we add all the dynamics.
			BootDynamics(config->GetDynamicCount());

			m_bootTimer.Start();

			break;
		}
		case ServerOP_LauncherZoneStatus: {
			const LauncherZoneStatus *it = (const LauncherZoneStatus *) pack->pBuffer;
			std::map<std::string, ZoneState>::iterator res;
			res = m_states.find(it->short_name);
			if(res == m_states.end()) {
				_log(WORLD__LAUNCH_ERR, "%s: reported state for zone %s which it does not have.", m_name.c_str(), it->short_name);
				break;
			}
			_log(WORLD__LAUNCH, "%s: %s reported state %s (%d starts)", m_name.c_str(), it->short_name, it->running?"STARTED":"STOPPED", it->start_count);
			res->second.up = it->running;
			res->second.starts = it->start_count;
			break;
		}
		default:
		{
			_log(WORLD__LAUNCH_ERR, "Unknown ServerOPcode from launcher 0x%04x, size %d",pack->opcode,pack->size);
			DumpPacket(pack->pBuffer, pack->size);
			break;
		}
		}

		delete pack;
	}
	return(true);
}
Beispiel #18
0
int main(int argc, char** argv) {
	RegisterExecutablePlatform(ExePlatformWorld);
	LogSys.LoadLogSettingsDefaults();
	set_exception_handler();

	/* Database Version Check */
	uint32 Database_Version = CURRENT_BINARY_DATABASE_VERSION;
	uint32 Bots_Database_Version = CURRENT_BINARY_BOTS_DATABASE_VERSION;
	if (argc >= 2) {
		if (strcasecmp(argv[1], "db_version") == 0) {
			std::cout << "Binary Database Version: " << Database_Version << " : " << Bots_Database_Version << std::endl;
			return 0;
		}
	}

	// Load server configuration
	Log(Logs::General, Logs::World_Server, "Loading server configuration..");
	if (!WorldConfig::LoadConfig()) {
		Log(Logs::General, Logs::World_Server, "Loading server configuration failed.");
		return 1;
	}

	Config = WorldConfig::get();

	Log(Logs::General, Logs::World_Server, "CURRENT_VERSION: %s", CURRENT_VERSION);

	if (signal(SIGINT, CatchSignal) == SIG_ERR) {
		Log(Logs::General, Logs::World_Server, "Could not set signal handler");
		return 1;
	}

	if (signal(SIGTERM, CatchSignal) == SIG_ERR) {
		Log(Logs::General, Logs::World_Server, "Could not set signal handler");
		return 1;
	}

#ifndef WIN32
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
		Log(Logs::General, Logs::World_Server, "Could not set signal handler");
		return 1;
	}
#endif

	// add login server config to list
	if (Config->LoginCount == 0) {
		if (Config->LoginHost.length()) {
			loginserverlist.Add(Config->LoginHost.c_str(), Config->LoginPort, Config->LoginAccount.c_str(), Config->LoginPassword.c_str(), Config->LoginLegacy);
			Log(Logs::General, Logs::World_Server, "Added loginserver %s:%i", Config->LoginHost.c_str(), Config->LoginPort);
		}
	}
	else {
		LinkedList<LoginConfig*> loginlist = Config->loginlist;
		LinkedListIterator<LoginConfig*> iterator(loginlist);
		iterator.Reset();
		while (iterator.MoreElements()) {
			loginserverlist.Add(iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort, iterator.GetData()->LoginAccount.c_str(), iterator.GetData()->LoginPassword.c_str(),
				iterator.GetData()->LoginLegacy);
			Log(Logs::General, Logs::World_Server, "Added loginserver %s:%i", iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort);
			iterator.Advance();
		}
	}

	Log(Logs::General, Logs::World_Server, "Connecting to MySQL...");
	if (!database.Connect(
		Config->DatabaseHost.c_str(),
		Config->DatabaseUsername.c_str(),
		Config->DatabasePassword.c_str(),
		Config->DatabaseDB.c_str(),
		Config->DatabasePort)) {
		Log(Logs::General, Logs::World_Server, "Cannot continue without a database connection.");
		return 1;
	}
	guild_mgr.SetDatabase(&database);

	/* Register Log System and Settings */
	database.LoadLogSettings(LogSys.log_settings);
	LogSys.StartFileLogs();

	bool ignore_db = false;
	if (argc >= 2) {
		std::string tmp;
		if (strcasecmp(argv[1], "help") == 0 || strcasecmp(argv[1], "?") == 0 || strcasecmp(argv[1], "/?") == 0 || strcasecmp(argv[1], "-?") == 0 || strcasecmp(argv[1], "-h") == 0 || strcasecmp(argv[1], "-help") == 0) {
			std::cout << "Worldserver command line commands:" << std::endl;
			std::cout << "adduser username password flag    - adds a user account" << std::endl;
			std::cout << "flag username flag    - sets GM flag on the account" << std::endl;
			std::cout << "startzone zoneshortname    - sets the starting zone" << std::endl;
			std::cout << "-holdzones    - reboots lost zones" << std::endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "-holdzones") == 0) {
			std::cout << "Reboot Zones mode ON" << std::endl;
			holdzones = true;
		}
		else if (database.GetVariable("disablecommandline", tmp)) {
			if (tmp.length() == 1) {
				if (tmp[0] == '1') {
					std::cerr << "Command line disabled in database... exiting" << std::endl;
					return 1;
				}
			}
		}
		else if (strcasecmp(argv[1], "adduser") == 0) {
			if (argc == 5) {
				if (Seperator::IsNumber(argv[4])) {
					if (atoi(argv[4]) >= 0 && atoi(argv[4]) <= 255) {
						if (database.CreateAccount(argv[2], argv[3], atoi(argv[4])) == 0) {
							std::cerr << "database.CreateAccount failed." << std::endl;
							return 1;
						}
						else {
							std::cout << "Account created: Username='******', Password='******', status=" << argv[4] << std::endl;
							return 0;
						}
					}
				}
			}
			std::cout << "Usage: world adduser username password flag" << std::endl;
			std::cout << "flag = 0, 1 or 2" << std::endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "flag") == 0) {
			if (argc == 4) {
				if (Seperator::IsNumber(argv[3])) {
					if (atoi(argv[3]) >= 0 && atoi(argv[3]) <= 255) {
						if (database.SetAccountStatus(argv[2], atoi(argv[3]))) {
							std::cout << "Account flagged: Username='******', status=" << argv[3] << std::endl;
							return 0;
						}
						else {
							std::cerr << "database.SetAccountStatus failed." << std::endl;
							return 1;
						}
					}
				}
			}
			std::cout << "Usage: world flag username flag" << std::endl;
			std::cout << "flag = 0-200" << std::endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "startzone") == 0) {
			if (argc == 3) {
				if (strlen(argv[2]) < 3) {
					std::cerr << "Error: zone name too short" << std::endl;
					return 1;
				}
				else if (strlen(argv[2]) > 15) {
					std::cerr << "Error: zone name too long" << std::endl;
					return 1;
				}
				else {
					if (database.SetVariable("startzone", argv[2])) {
						std::cout << "Starting zone changed: '" << argv[2] << "'" << std::endl;
						return 0;
					}
					else {
						std::cerr << "database.SetVariable failed." << std::endl;
						return 1;
					}
				}
			}
			std::cout << "Usage: world startzone zoneshortname" << std::endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "ignore_db") == 0) {
			ignore_db = true;
		}
		else {
			std::cerr << "Error, unknown command line option" << std::endl;
			return 1;
		}
	}

	if (!ignore_db) {
		Log(Logs::General, Logs::World_Server, "Checking Database Conversions..");
		database.CheckDatabaseConversions();
	}
	Log(Logs::General, Logs::World_Server, "Loading variables..");
	database.LoadVariables();

	std::string hotfix_name;
	if (database.GetVariable("hotfix_name", hotfix_name)) {
		if (!hotfix_name.empty()) {
			Log(Logs::General, Logs::Zone_Server, "Current hotfix in use: '%s'", hotfix_name.c_str());
		}
	}

	Log(Logs::General, Logs::World_Server, "Loading zones..");
	database.LoadZoneNames();
	Log(Logs::General, Logs::World_Server, "Clearing groups..");
	database.ClearGroup();
	Log(Logs::General, Logs::World_Server, "Clearing raids..");
	database.ClearRaid();
	database.ClearRaidDetails();
	database.ClearRaidLeader();
	Log(Logs::General, Logs::World_Server, "Clearing inventory snapshots..");
	database.ClearInvSnapshots();
	Log(Logs::General, Logs::World_Server, "Loading items..");
	if (!database.LoadItems(hotfix_name))
		Log(Logs::General, Logs::World_Server, "Error: Could not load item data. But ignoring");
	Log(Logs::General, Logs::World_Server, "Loading skill caps..");
	if (!database.LoadSkillCaps(std::string(hotfix_name)))
		Log(Logs::General, Logs::World_Server, "Error: Could not load skill cap data. But ignoring");
	Log(Logs::General, Logs::World_Server, "Loading guilds..");
	guild_mgr.LoadGuilds();
	//rules:
	{
		std::string tmp;
		if (database.GetVariable("RuleSet", tmp)) {
			Log(Logs::General, Logs::World_Server, "Loading rule set '%s'", tmp.c_str());
			if (!RuleManager::Instance()->LoadRules(&database, tmp.c_str())) {
				Log(Logs::General, Logs::World_Server, "Failed to load ruleset '%s', falling back to defaults.", tmp.c_str());
			}
		}
		else {
			if (!RuleManager::Instance()->LoadRules(&database, "default")) {
				Log(Logs::General, Logs::World_Server, "No rule set configured, using default rules");
			}
			else {
				Log(Logs::General, Logs::World_Server, "Loaded default rule set 'default'", tmp.c_str());
			}
		}
	}

	if (RuleB(World, ClearTempMerchantlist)) {
		Log(Logs::General, Logs::World_Server, "Clearing temporary merchant lists..");
		database.ClearMerchantTemp();
	}

	RuleManager::Instance()->SaveRules(&database);

	Log(Logs::General, Logs::World_Server, "Loading EQ time of day..");
	TimeOfDay_Struct eqTime;
	time_t realtime;
	eqTime = database.LoadTime(realtime);
	zoneserver_list.worldclock.SetCurrentEQTimeOfDay(eqTime, realtime);
	Timer EQTimeTimer(600000);
	EQTimeTimer.Start(600000);

	Log(Logs::General, Logs::World_Server, "Loading launcher list..");
	launcher_list.LoadList();

	std::string tmp;
	database.GetVariable("holdzones", tmp);
	if (tmp.length() == 1 && tmp[0] == '1') {
		holdzones = true;
	}
	Log(Logs::General, Logs::World_Server, "Reboot zone modes %s", holdzones ? "ON" : "OFF");

	Log(Logs::General, Logs::World_Server, "Deleted %i stale player corpses from database", database.DeleteStalePlayerCorpses());

	Log(Logs::General, Logs::World_Server, "Loading adventures...");
	if (!adventure_manager.LoadAdventureTemplates())
	{
		Log(Logs::General, Logs::World_Server, "Unable to load adventure templates.");
	}

	if (!adventure_manager.LoadAdventureEntries())
	{
		Log(Logs::General, Logs::World_Server, "Unable to load adventure templates.");
	}

	adventure_manager.Load();
	adventure_manager.LoadLeaderboardInfo();

	Log(Logs::General, Logs::World_Server, "Purging expired instances");
	database.PurgeExpiredInstances();
	Timer PurgeInstanceTimer(450000);
	PurgeInstanceTimer.Start(450000);

	Log(Logs::General, Logs::World_Server, "Loading char create info...");
	database.LoadCharacterCreateAllocations();
	database.LoadCharacterCreateCombos();

	std::unique_ptr<EQ::Net::ConsoleServer> console;
	if (Config->TelnetEnabled) {
		Log(Logs::General, Logs::World_Server, "Console (TCP) listener started.");
		console.reset(new EQ::Net::ConsoleServer(Config->TelnetIP, Config->TelnetTCPPort));
		RegisterConsoleFunctions(console);
	}

	std::unique_ptr<EQ::Net::ServertalkServer> server_connection;
	server_connection.reset(new EQ::Net::ServertalkServer());

	EQ::Net::ServertalkServerOptions server_opts;
	server_opts.port = Config->WorldTCPPort;
	server_opts.ipv6 = false;
	server_opts.credentials = Config->SharedKey;
	server_connection->Listen(server_opts);
	Log(Logs::General, Logs::World_Server, "Server (TCP) listener started.");

	server_connection->OnConnectionIdentified("Zone", [&console](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "New Zone Server connection from {2} at {0}:{1}",
			connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID());

		numzones++;
		zoneserver_list.Add(new ZoneServer(connection, console.get()));
	});

	server_connection->OnConnectionRemoved("Zone", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "Removed Zone Server connection from {0}",
			connection->GetUUID());

		numzones--;
		zoneserver_list.Remove(connection->GetUUID());
	});

	server_connection->OnConnectionIdentified("Launcher", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "New Launcher connection from {2} at {0}:{1}",
			connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID());

		launcher_list.Add(connection);
	});

	server_connection->OnConnectionRemoved("Launcher", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "Removed Launcher connection from {0}",
			connection->GetUUID());

		launcher_list.Remove(connection);
	});

	server_connection->OnConnectionIdentified("QueryServ", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "New Query Server connection from {2} at {0}:{1}",
			connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID());

		QSLink.AddConnection(connection);
	});

	server_connection->OnConnectionRemoved("QueryServ", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "Removed Query Server connection from {0}",
			connection->GetUUID());

		QSLink.RemoveConnection(connection);
	});

	server_connection->OnConnectionIdentified("UCS", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "New UCS Server connection from {2} at {0}:{1}",
			connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID());

		UCSLink.SetConnection(connection);
	});

	server_connection->OnConnectionRemoved("UCS", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "Removed Query Server connection from {0}",
			connection->GetUUID());

		UCSLink.SetConnection(nullptr);
	});

	server_connection->OnConnectionIdentified("WebInterface", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "New WebInterface Server connection from {2} at {0}:{1}",
			connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID());

		web_interface.AddConnection(connection);
	});

	server_connection->OnConnectionRemoved("WebInterface", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) {
		LogF(Logs::General, Logs::World_Server, "Removed WebInterface Server connection from {0}",
			connection->GetUUID());

		web_interface.RemoveConnection(connection);
	});

	EQ::Net::EQStreamManagerOptions opts(9000, false, false);
	EQ::Net::EQStreamManager eqsm(opts);

	//register all the patches we have avaliable with the stream identifier.
	EQStreamIdentifier stream_identifier;
	RegisterAllPatches(stream_identifier);
	zoneserver_list.shutdowntimer = new Timer(60000);
	zoneserver_list.shutdowntimer->Disable();
	zoneserver_list.reminder = new Timer(20000);
	zoneserver_list.reminder->Disable();
	Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect
	InterserverTimer.Trigger();
	uint8 ReconnectCounter = 100;
	std::shared_ptr<EQStreamInterface> eqs;
	EQStreamInterface *eqsi;

	eqsm.OnNewConnection([&stream_identifier](std::shared_ptr<EQ::Net::EQStream> stream) {
		stream_identifier.AddStream(stream);
		LogF(Logs::Detail, Logs::World_Server, "New connection from IP {0}:{1}", stream->RemoteEndpoint(), ntohs(stream->GetRemotePort()));
	});

	while (RunLoops) {
		Timer::SetCurrentTime();
		eqs = nullptr;

		//give the stream identifier a chance to do its work....
		stream_identifier.Process();

		//check the stream identifier for any now-identified streams
		while ((eqsi = stream_identifier.PopIdentified())) {
			//now that we know what patch they are running, start up their client object
			struct in_addr	in;
			in.s_addr = eqsi->GetRemoteIP();
			if (RuleB(World, UseBannedIPsTable)) { //Lieka: Check to see if we have the responsibility for blocking IPs.
				Log(Logs::Detail, Logs::World_Server, "Checking inbound connection %s against BannedIPs table", inet_ntoa(in));
				if (!database.CheckBannedIPs(inet_ntoa(in))) { //Lieka: Check inbound IP against banned IP table.
					Log(Logs::Detail, Logs::World_Server, "Connection %s PASSED banned IPs check. Processing connection.", inet_ntoa(in));
					auto client = new Client(eqsi);
					// @merth: client->zoneattempt=0;
					client_list.Add(client);
				}
				else {
					Log(Logs::General, Logs::World_Server, "Connection from %s FAILED banned IPs check. Closing connection.", inet_ntoa(in));
					eqsi->Close(); //Lieka: If the inbound IP is on the banned table, close the EQStream.
				}
			}
			if (!RuleB(World, UseBannedIPsTable)) {
				Log(Logs::Detail, Logs::World_Server, "New connection from %s:%d, processing connection", inet_ntoa(in), ntohs(eqsi->GetRemotePort()));
				auto client = new Client(eqsi);
				// @merth: client->zoneattempt=0;
				client_list.Add(client);
			}
		}

		client_list.Process();

		if (PurgeInstanceTimer.Check())
		{
			database.PurgeExpiredInstances();
		}

		if (EQTimeTimer.Check()) {
			TimeOfDay_Struct tod;
			zoneserver_list.worldclock.GetCurrentEQTimeOfDay(time(0), &tod);
			if (!database.SaveTime(tod.minute, tod.hour, tod.day, tod.month, tod.year))
				Log(Logs::General, Logs::World_Server, "Failed to save eqtime.");
			else
				Log(Logs::Detail, Logs::World_Server, "EQTime successfully saved.");
		}

		zoneserver_list.Process();
		launcher_list.Process();
		LFPGroupList.Process();
		adventure_manager.Process();

		if (InterserverTimer.Check()) {
			InterserverTimer.Start();
			database.ping();

			std::string window_title = StringFormat("World: %s Clients: %i", Config->LongName.c_str(), client_list.GetClientCount());
			UpdateWindowTitle(window_title);
		}

		EQ::EventLoop::Get().Process();
		Sleep(5);
	}
	Log(Logs::General, Logs::World_Server, "World main loop completed.");
	Log(Logs::General, Logs::World_Server, "Shutting down zone connections (if any).");
	zoneserver_list.KillAll();
	Log(Logs::General, Logs::World_Server, "Zone (TCP) listener stopped.");
	Log(Logs::General, Logs::World_Server, "Signaling HTTP service to stop...");
	LogSys.CloseFileLogs();

	return 0;
}
Beispiel #19
0
void EQW__GetLauncherCount(WebInterface *i, const std::string& method, const std::string& id, const Json::Value& params) {
	Json::Value ret = launcher_list.GetLauncherCount();
	i->SendResponse(id, ret);
}
Beispiel #20
0
int main(int argc, char** argv) {
	// Load server configuration
	_log(WORLD__INIT, "Loading server configuration..");
	if (!WorldConfig::LoadConfig()) {
		_log(WORLD__INIT_ERR, "Loading server configuration failed.");
		return(1);
	}
	const WorldConfig *Config=WorldConfig::get();

	if(!load_log_settings(Config->LogSettingsFile.c_str()))
		_log(WORLD__INIT, "Warning: Unable to read %s", Config->LogSettingsFile.c_str());
	else
		_log(WORLD__INIT, "Log settings loaded from %s", Config->LogSettingsFile.c_str());


	_log(WORLD__INIT, "CURRENT_WORLD_VERSION:%s", CURRENT_WORLD_VERSION);
	
	#ifdef _DEBUG
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	#endif
	
	if (signal(SIGINT, CatchSignal) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	if (signal(SIGTERM, CatchSignal) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	#ifndef WIN32
	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)	{
		_log(WORLD__INIT_ERR, "Could not set signal handler");
		return 0;
	}
	#endif
	
	_log(WORLD__INIT, "Connecting to MySQL...");
	if (!database.Connect(
		Config->DatabaseHost.c_str(),
		Config->DatabaseUsername.c_str(),
		Config->DatabasePassword.c_str(),
		Config->DatabaseDB.c_str(),
		Config->DatabasePort)) {
		_log(WORLD__INIT_ERR, "Cannot continue without a database connection.");
		return(1);
	}
	dbasync = new DBAsync(&database);
	guild_mgr.SetDatabase(&database);
	
	if (argc >= 2) {
		char tmp[2];
		if (strcasecmp(argv[1], "help") == 0 || strcasecmp(argv[1], "?") == 0 || strcasecmp(argv[1], "/?") == 0 || strcasecmp(argv[1], "-?") == 0 || strcasecmp(argv[1], "-h") == 0 || strcasecmp(argv[1], "-help") == 0) {
			cout << "Worldserver command line commands:" << endl;
			cout << "adduser username password flag    - adds a user account" << endl;
			cout << "flag username flag    - sets GM flag on the account" << endl;
			cout << "startzone zoneshortname    - sets the starting zone" << endl;
			cout << "-holdzones    - reboots lost zones" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "-holdzones") == 0) {
			cout << "Reboot Zones mode ON" << endl;
			holdzones = true;
		}
		else if (database.GetVariable("disablecommandline", tmp, 2)) {
			if (strlen(tmp) == 1) {
				if (tmp[0] == '1') {
					cout << "Command line disabled in database... exiting" << endl;
					return 0;
				}
			}
		}
		else if (strcasecmp(argv[1], "adduser") == 0) {
			if (argc == 5) {
				if (Seperator::IsNumber(argv[4])) {
					if (atoi(argv[4]) >= 0 && atoi(argv[4]) <= 255) {
						if (database.CreateAccount(argv[2], argv[3], atoi(argv[4])) == 0)
							cout << "database.CreateAccount failed." << endl;
						else
							cout << "Account created: Username='******', Password='******', status=" << argv[4] << endl;
						return 0;
					}
				}
			}
			cout << "Usage: world adduser username password flag" << endl;
			cout << "flag = 0, 1 or 2" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "flag") == 0) {
			if (argc == 4) {
				if (Seperator::IsNumber(argv[3])) {

					if (atoi(argv[3]) >= 0 && atoi(argv[3]) <= 255) {
						if (database.SetAccountStatus(argv[2], atoi(argv[3])))
							cout << "Account flagged: Username='******', status=" << argv[3] << endl;
						else
							cout << "database.SetAccountStatus failed." << endl;
						return 0;
					}
				}
			}
			cout << "Usage: world flag username flag" << endl;
			cout << "flag = 0-200" << endl;
			return 0;
		}
		else if (strcasecmp(argv[1], "startzone") == 0) {
			if (argc == 3) {
				if (strlen(argv[2]) < 3) {
					cout << "Error: zone name too short" << endl;
				}
				else if (strlen(argv[2]) > 15) {
					cout << "Error: zone name too long" << endl;
				}
				else {
					if (database.SetVariable("startzone", argv[2]))
						cout << "Starting zone changed: '" << argv[2] << "'" << endl;
					else
						cout << "database.SetVariable failed." << endl;
				}
				return 0;
			}
			cout << "Usage: world startzone zoneshortname" << endl;
			return 0;
		}
		else {
			cout << "Error, unknown command line option" << endl;
			return 0;
		}
	}
	srand(time(NULL));
	
	if(Config->WorldHTTPEnabled) {
		_log(WORLD__INIT, "Starting HTTP world service...");
		http_server.Start(Config->WorldHTTPPort, Config->WorldHTTPMimeFile.c_str());
	} else {
		_log(WORLD__INIT, "HTTP world service disabled.");
	}
	
	_log(WORLD__INIT, "Loading variables..");
	database.LoadVariables();
	_log(WORLD__INIT, "Loading zones..");
	database.LoadZoneNames();
	_log(WORLD__INIT, "Clearing groups..");
	database.ClearGroup();
	_log(WORLD__INIT, "Clearing raids..");
	database.ClearRaid();
	database.ClearRaidDetails();
	_log(WORLD__INIT, "Loading items..");
	if (!database.LoadItems()) {
		_log(WORLD__INIT_ERR, "Error: Could not load item data.  But ignoring");
	}
	_log(WORLD__INIT, "Loading guilds..");
	guild_mgr.LoadGuilds();
	//rules:
	{
		char tmp[64];
		if (database.GetVariable("RuleSet", tmp, sizeof(tmp)-1)) {
			_log(WORLD__INIT, "Loading rule set '%s'", tmp);
			if(!rules->LoadRules(&database, tmp)) {
				_log(WORLD__INIT_ERR, "Failed to load ruleset '%s', falling back to defaults.", tmp);
			}
		} else {
			if(!rules->LoadRules(&database, "default")) {
				_log(WORLD__INIT, "No rule set configured, using default rules");
			} else {
				_log(WORLD__INIT, "Loaded default rule set 'default'", tmp);
			}
		}
	}
	if(RuleB(World, ClearTempMerchantlist)){
        _log(WORLD__INIT, "Clearing temporary merchant lists..");
		database.ClearMerchantTemp();
      }
	_log(WORLD__INIT, "Loading EQ time of day..");
	if (!zoneserver_list.worldclock.loadFile(Config->EQTimeFile.c_str()))
		_log(WORLD__INIT_ERR, "Unable to load %s", Config->EQTimeFile.c_str());
	_log(WORLD__INIT, "Loading launcher list..");
	launcher_list.LoadList();
	
	char tmp[20];
	tmp[0] = '\0';
	database.GetVariable("holdzones",tmp, 20);	
	if ((strcasecmp(tmp, "1") == 0)) {
		holdzones = true;
	}
	_log(WORLD__INIT, "Reboot zone modes %s",holdzones ? "ON" : "OFF");
	
	_log(WORLD__INIT, "Deleted %i stale player corpses from database", database.DeleteStalePlayerCorpses());
	_log(WORLD__INIT, "Deleted %i stale player backups from database", database.DeleteStalePlayerBackups());

	_log(WORLD__INIT, "Purging expired instances");
	database.PurgeExpiredInstances();
	Timer PurgeInstanceTimer(450000);
	PurgeInstanceTimer.Start(450000);

	char errbuf[TCPConnection_ErrorBufferSize];
	if (tcps.Open(Config->WorldTCPPort, errbuf)) {
		_log(WORLD__INIT,"Zone (TCP) listener started.");
	} else {
		_log(WORLD__INIT_ERR,"Failed to start zone (TCP) listener on port %d:",Config->WorldTCPPort);
		_log(WORLD__INIT_ERR,"        %s",errbuf);
		return 1;
	}
	if (eqsf.Open()) {
		_log(WORLD__INIT,"Client (UDP) listener started.");
	} else {
		_log(WORLD__INIT_ERR,"Failed to start client (UDP) listener (port 9000)");
		return 1;
	}

	//ItemInst a((SharedDatabase *)&database,(uint32)17354,0);
	//ItemInst b((SharedDatabase *)&database,(uint32)26885,0);
	//ItemInst c((SharedDatabase *)&database,(uint32)41075,0);
	//ItemInst d((SharedDatabase *)&database,(uint32)29041,0);
	//d.PutAugment(&database,0,41006);
	//a.PutItem(0,b);
	//a.PutItem(1,c);
	//a.PutItem(2,d);
	//_log(WORLD__INIT,"%s\n",Client62::SerializeItem(&a,30,0));
	
	//register all the patches we have avaliable with the stream identifier.
	EQStreamIdentifier stream_identifier;
	RegisterAllPatches(stream_identifier);
	
	
	zoneserver_list.shutdowntimer=new Timer(60000);
	zoneserver_list.shutdowntimer->Disable();
	zoneserver_list.reminder = new Timer(20000);
	zoneserver_list.reminder->Disable();
	Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect
	InterserverTimer.Trigger();
	EQStream* eqs;
	EmuTCPConnection* tcpc;
	EQStreamInterface *eqsi;
	
	while(RunLoops) {
		Timer::SetCurrentTime();
		
		//check the factory for any new incoming streams.
		while ((eqs = eqsf.Pop())) {
			//pull the stream out of the factory and give it to the stream identifier
			//which will figure out what patch they are running, and set up the dynamic
			//structures and opcodes for that patch.
			struct in_addr	in;
			in.s_addr = eqs->GetRemoteIP();
			_log(WORLD__CLIENT, "New connection from %s:%d", inet_ntoa(in),ntohs(eqs->GetRemotePort()));
			stream_identifier.AddStream(eqs);	//takes the stream
		}
		
		//give the stream identifier a chance to do its work....
		stream_identifier.Process();
		
		//check the stream identifier for any now-identified streams
		while((eqsi = stream_identifier.PopIdentified())) {
			//now that we know what patch they are running, start up their client object
			struct in_addr	in;
			in.s_addr = eqsi->GetRemoteIP();
 			if (RuleB(World, UseBannedIPsTable)){ //Lieka:  Check to see if we have the responsibility for blocking IPs.
				_log(WORLD__CLIENT, "Checking inbound connection %s against BannedIPs table", inet_ntoa(in));
 				if (!database.CheckBannedIPs(inet_ntoa(in))){ //Lieka:  Check inbound IP against banned IP table.
 					_log(WORLD__CLIENT, "Connection %s PASSED banned IPs check.  Processing connection.", inet_ntoa(in));
 					Client* client = new Client(eqsi);
 					// @merth: client->zoneattempt=0;
 					client_list.Add(client);
 				} else {
 					_log(WORLD__CLIENT, "Connection from %s FAILED banned IPs check.  Closing connection.", inet_ntoa(in));
 					eqsi->Close(); //Lieka:  If the inbound IP is on the banned table, close the EQStream.
 				}
 			}
 			if (!RuleB(World, UseBannedIPsTable)){
 					_log(WORLD__CLIENT, "New connection from %s:%d, processing connection", inet_ntoa(in), ntohs(eqsi->GetRemotePort()));
 					Client* client = new Client(eqsi);
 					// @merth: client->zoneattempt=0;
 					client_list.Add(client);
 			}
		}
		
		client_list.Process();
		
		while ((tcpc = tcps.NewQueuePop())) {
			struct in_addr in;
			in.s_addr = tcpc->GetrIP();
			_log(WORLD__ZONE, "New TCP connection from %s:%d", inet_ntoa(in),tcpc->GetrPort());
			console_list.Add(new Console(tcpc));
		}

		if(PurgeInstanceTimer.Check())
		{
			database.PurgeExpiredInstances();
		}
		
		//check for timeouts in other threads
		timeout_manager.CheckTimeouts();
		
		loginserver.Process();
		
		console_list.Process();
		
		zoneserver_list.Process();
		
		launcher_list.Process();

		LFPGroupList.Process();
		
		if (InterserverTimer.Check()) {
			InterserverTimer.Start();
			database.ping();
			AsyncLoadVariables(dbasync, &database);
			if (Config->LoginHost.length() && loginserver.Connected() == false) {
#ifdef WIN32
				_beginthread(AutoInitLoginServer, 0, NULL);
#else
				pthread_t thread;
				pthread_create(&thread, NULL, &AutoInitLoginServer, NULL);
#endif
			}
		}
		if (numclients == 0) {
			Sleep(50);
			continue;
		}
		Sleep(20);
	}
	_log(WORLD__SHUTDOWN,"World main loop completed.");
	_log(WORLD__SHUTDOWN,"Shutting down console connections (if any).");
	console_list.KillAll();
	_log(WORLD__SHUTDOWN,"Shutting down zone connections (if any).");
	zoneserver_list.KillAll();
	_log(WORLD__SHUTDOWN,"Zone (TCP) listener stopped.");
	tcps.Close();
	_log(WORLD__SHUTDOWN,"Client (UDP) listener stopped.");
	eqsf.Close();
	_log(WORLD__SHUTDOWN,"Signaling HTTP service to stop...");
	http_server.Stop();
#if 0
#if defined(SHAREMEM) && !defined(WIN32)
		for (int ipc_files = 0; ipc_files <= 4; ipc_files++) {
			key_t share_key;
			switch (ipc_files) {
				// Item
				case 0: share_key = ftok(".", 'I'); break;
				// Npctype
				case 1: share_key = ftok(".", 'N'); break;
				// Door
				case 2: share_key = ftok(".", 'D'); break;
				// Spell
				case 3: share_key = ftok(".", 'S'); break;
				// Faction
				case 4: share_key = ftok(".", 'F'); break;
				// ERROR Fatal
				default: cerr<<"Opps!"<<endl; share_key = 0xFF; break;
			}
			
			int share_id = shmget(share_key, 0, IPC_NOWAIT|0400);
			if (share_id <= 0) {
				cerr<<"exiting could not check user count on shared memory ipcs mem leak!!!!!!!! id="<<share_id<<" key:"<<share_key<<endl;
				exit(1);
			}
			struct shmid_ds mem_users;
			if ((shmctl(share_id, IPC_STAT, &mem_users)) != 0) {
				cerr<<"exiting error checking user count on shared memory, marking for deletion!!!!!id="<<share_id<<" key:"<<share_key<<endl;
				shmctl(share_id, IPC_RMID, 0);
				exit(1);
			}
			if (mem_users.shm_nattch == 0) {
				//cerr<<"exiting stale share marked for deletion!id="<<share_id<<" key:"<<share_key<<endl;
				shmctl(share_id, IPC_RMID, 0);
			}
			else if (mem_users.shm_nattch == 1) {
				//cerr<<"mem_users = 1"<<endl;
				// Detatch and delete shared mem here
				EMuShareMemDLL.Unload();
				shmctl(share_id, IPC_RMID, 0);
			}

		}
#endif
#endif

	CheckEQEMuErrorAndPause();
	return 0;
}
Beispiel #21
0
EQLConfig * EQW::GetLauncher(Const_char *launcher_name) {
	return(launcher_list.GetConfig(launcher_name));
}
Beispiel #22
0
bool EQLConfig::IsConnected() const {
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	return(ll != nullptr);
}
Beispiel #23
0
void EQLConfig::StartZone(Const_char *zone_ref) {
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll == nullptr)
		return;
	ll->StartZone(zone_ref);
}
Beispiel #24
0
void EQW::CreateLauncher(Const_char *launcher_name, int dynamic_count) {
	launcher_list.CreateLauncher(launcher_name, dynamic_count);
}
Beispiel #25
0
void EQLConfig::RestartZone(Const_char *zone_ref) {
	LauncherLink *ll = launcher_list.Get(m_name.c_str());
	if(ll == NULL)
		return;
	ll->RestartZone(zone_ref);
}