Example #1
0
cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault)
{
	AString BiomeGenName = a_IniFile.GetValueSet("Generator", "BiomeGen", "");
	if (BiomeGenName.empty())
	{
		LOGWARN("[Generator] BiomeGen value not set in world.ini, using \"MultiStepMap\".");
		BiomeGenName = "MultiStepMap";
	}
	
	cBiomeGen * res = NULL;
	a_CacheOffByDefault = false;
	if (NoCaseCompare(BiomeGenName, "constant") == 0)
	{
		res = new cBioGenConstant;
		a_CacheOffByDefault = true;  // we're generating faster than a cache would retrieve data :)
	}
	else if (NoCaseCompare(BiomeGenName, "checkerboard") == 0)
	{
		res = new cBioGenCheckerboard;
		a_CacheOffByDefault = true;  // we're (probably) generating faster than a cache would retrieve data
	}
	else if (NoCaseCompare(BiomeGenName, "voronoi") == 0)
	{
		res = new cBioGenVoronoi(a_Seed);
	}
	else if (NoCaseCompare(BiomeGenName, "distortedvoronoi") == 0)
	{
		res = new cBioGenDistortedVoronoi(a_Seed);
	}
	else if (NoCaseCompare(BiomeGenName, "twolevel") == 0)
	{
		res = new cBioGenTwoLevel(a_Seed);
	}
	else
	{
		if (NoCaseCompare(BiomeGenName, "multistepmap") != 0)
		{
			LOGWARNING("Unknown BiomeGen \"%s\", using \"MultiStepMap\" instead.", BiomeGenName.c_str());
		}
		res = new cBioGenMultiStepMap(a_Seed);

		/*
		// Performance-testing:
		LOGINFO("Measuring performance of cBioGenMultiStepMap...");
		clock_t BeginTick = clock();
		for (int x = 0; x < 5000; x++)
		{
			cChunkDef::BiomeMap Biomes;
			res->GenBiomes(x * 5, x * 5, Biomes);
		}
		clock_t Duration = clock() - BeginTick;
		LOGINFO("cBioGenMultiStepMap for 5000 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC);
		//*/
	}
	res->InitializeBiomeGen(a_IniFile);
	
	return res;
}
Example #2
0
		Air::U1 Converter::SplitFilePath( const AString& str, AString* strPath /*= NULL*/, AString* strFileName /*= NULL*/, AString* strExe /*= NULL*/ )
		{
			if(str.empty())
				return	false;
			U32	uiStrSize	=	str.size();
			S32	uiPoint	=	uiStrSize;
			S32	uiSlash	=	-1;


			for(S32 i=uiStrSize-1;i>-1;i--){
				if(str[i]	==	'.'	&&	uiPoint	==	uiStrSize){
					uiPoint	=	i;
				}
				if(	str[i]	==	'/'	||
					str[i]	==	'\\'){
					uiSlash	=	i;
					break;
				}
			}

			if(	uiPoint	!=	uiStrSize	&&
				strExe	!=	NULL)
			{
				if(uiPoint!=uiStrSize-1)
					*strExe	=	&str[uiPoint+1];
			}

			if(	uiSlash	!=	-1		&&
				strPath	!=	NULL)
			{
				if(uiSlash<uiStrSize){
					strPath->resize(uiSlash+1);
					memcpy(&((*strPath)[0]),&str[0],uiSlash+1);
				}else{
					*strPath	=	str;
				}
			}

			if(strFileName!=NULL){
				U32	uiFileNameSize	=	uiPoint;
				U32	uiFileNameStart	=	0;
				if(uiPoint==uiStrSize)
					uiFileNameSize--;

				if(uiSlash<uiStrSize){
					if(uiSlash!=-1){
						uiFileNameSize	-=		uiSlash+1;
						uiFileNameStart	=		uiSlash+1;
					}

					strFileName->resize(uiFileNameSize);
					memcpy(&((*strFileName)[0]),&str[uiFileNameStart],uiFileNameSize);
				}
			}
			return	true;
		}
Example #3
0
bool ARTSPConnection::receiveRTSPRequest() {
    AString requestLine;
	LOGI(LOG_TAG,"start receiveLine ......\n");
    if (!receiveLine(&requestLine)) {
        return false;
    }
//	LOGI(LOG_TAG,"receiveLine OK\n");
    sp<AMessage>  request = new AMessage(kWhatRequest,mhandlerID);
	request->setInt32("SessionID",mSessionID);
	LOGI(LOG_TAG,"request->setInt32 SessionID %d\n",mSessionID);
    LOGI(LOG_TAG,"request: %s\n", requestLine.c_str());

    ssize_t space1 = requestLine.find(" ");//寻找空格
    if (space1 < 0) {
        return false;
    }
    ssize_t space2 = requestLine.find(" ", space1 + 1);
    if (space2 < 0) {
        return false;
    }

    AString Method(requestLine.c_str(), space1);
	request->setString("Method",Method.c_str());
	AString URI(requestLine,space1+1,space2-space1-1);
	request->setString("URI",URI.c_str());
    AString line;
    for (;;) {
        if (!receiveLine(&line)) {
            break;
        }

        if (line.empty()) {
            break;
        }

        ssize_t colonPos = line.find(":");
        if (colonPos < 0) {
            // Malformed header line.
            return false;
        }

        AString key(line, 0, colonPos);
        key.trim();
       // key.tolower();

        line.erase(0, colonPos + 1);
        line.trim();
		
        LOGI(LOG_TAG,"line: %s:%s\n", key.c_str(),line.c_str());

	    request->setString(key.c_str(),line.c_str());	
    }
	LOGI(LOG_TAG,"Post the request to handler\n");
    request->post();//将请求消息发送给uplayer 处理
	return OK;
}
Example #4
0
void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni)
{
	LOG("-- Loading Plugins --");
	m_bReloadPlugins = false;
	UnloadPluginsNow();

	FindPlugins();

	cServer::BindBuiltInConsoleCommands();

	// Check if the Plugins section exists.
	int KeyNum = a_SettingsIni.FindKey("Plugins");

	// If it does, how many plugins are there?
	int NumPlugins = ((KeyNum != -1) ? (a_SettingsIni.GetNumValues(KeyNum)) : 0);

	if (KeyNum == -1)
	{
		InsertDefaultPlugins(a_SettingsIni);
	}
	else if (NumPlugins > 0)
	{
		for (int i = 0; i < NumPlugins; i++)
		{
			AString ValueName = a_SettingsIni.GetValueName(KeyNum, i);
			if (ValueName.compare("Plugin") == 0)
			{
				AString PluginFile = a_SettingsIni.GetValue(KeyNum, i);
				if (!PluginFile.empty())
				{
					if (m_Plugins.find(PluginFile) != m_Plugins.end())
					{
						LoadPlugin(PluginFile);
					}
				}
			}
		}
	}

	size_t NumLoadedPlugins = GetNumPlugins();
	if (NumLoadedPlugins == 0)
	{
		LOG("-- No Plugins Loaded --");
	}
	else if (NumLoadedPlugins > 1)
	{
		LOG("-- Loaded %i Plugins --", (int)NumLoadedPlugins);
	}
	else
	{
		LOG("-- Loaded 1 Plugin --");
	}
	CallHookPluginsLoaded();
}
Example #5
0
void cFurnaceRecipe::ReloadRecipes(void)
{
	ClearRecipes();
	LOGD("Loading furnace recipes...");

	std::ifstream f(FURNACE_RECIPE_FILE, std::ios::in);
	if (!f.good())
	{
		LOG("Could not open the furnace recipes file \"%s\". No furnace recipes are available.", FURNACE_RECIPE_FILE);
		return;
	}

	unsigned int LineNum = 0;
	AString ParsingLine;

	while (std::getline(f, ParsingLine))
	{
		LineNum++;
		if (ParsingLine.empty())
		{
			continue;
		}

		// Remove comments from the line:
		size_t FirstCommentSymbol = ParsingLine.find('#');
		if ((FirstCommentSymbol != AString::npos) && (FirstCommentSymbol != 0))
		{
			ParsingLine.erase(ParsingLine.begin() + static_cast<const long>(FirstCommentSymbol), ParsingLine.end());
		}

		switch (ParsingLine[0])
		{
			case '#':
			{
				// Comment
				break;
			}

			case '!':
			{
				AddFuelFromLine(ParsingLine, LineNum);
				break;
			}

			default:
			{
				AddRecipeFromLine(ParsingLine, LineNum);
				break;
			}
		}  // switch (ParsingLine[0])
	}  // while (getline(ParsingLine))

	LOG("Loaded " SIZE_T_FMT " furnace recipes and " SIZE_T_FMT " fuels", m_pState->Recipes.size(), m_pState->Fuel.size());
}
void cPrefabPiecePool::ApplyBaseMetadataCubesetVer1(
	const AString & a_FileName,
	bool a_LogWarnings
)
{
	// Set the metadata values to defaults:
	m_MinDensity = 100;
	m_MaxDensity = 100;
	m_VillageRoadBlockType = E_BLOCK_GRAVEL;
	m_VillageRoadBlockMeta = 0;
	m_VillageWaterRoadBlockType = E_BLOCK_PLANKS;
	m_VillageWaterRoadBlockMeta = 0;

	// Read the metadata values:
	m_IntendedUse = GetMetadata("IntendedUse");
	GetStringMapInteger(m_Metadata, "MaxDensity",                m_MaxDensity);
	GetStringMapInteger(m_Metadata, "MinDensity",                m_MinDensity);
	GetStringMapInteger(m_Metadata, "VillageRoadBlockType",      m_VillageRoadBlockType);
	GetStringMapInteger(m_Metadata, "VillageRoadBlockMeta",      m_VillageRoadBlockMeta);
	GetStringMapInteger(m_Metadata, "VillageWaterRoadBlockType", m_VillageWaterRoadBlockType);
	GetStringMapInteger(m_Metadata, "VillageWaterRoadBlockMeta", m_VillageWaterRoadBlockMeta);

	// Read the allowed biomes:
	AString allowedBiomes = GetMetadata("AllowedBiomes");
	if (allowedBiomes.empty())
	{
		// All biomes are allowed:
		for (int b = biFirstBiome; b <= biMaxBiome; b++)
		{
			m_AllowedBiomes.insert(static_cast<EMCSBiome>(b));
		}
		for (int b = biFirstVariantBiome; b <= biMaxVariantBiome; b++)
		{
			m_AllowedBiomes.insert(static_cast<EMCSBiome>(b));
		}
	}
	else
	{
		auto biomes = StringSplitAndTrim(allowedBiomes, ",");
		for (const auto & biome: biomes)
		{
			EMCSBiome b = StringToBiome(biome);
			if (b == biInvalidBiome)
			{
				CONDWARNING(a_LogWarnings, "Invalid biome (\"%s\") specified in AllowedBiomes in cubeset file %s. Skipping the biome.",
					biome.c_str(), a_FileName.c_str()
				);
				continue;
			}
			m_AllowedBiomes.insert(b);
		}
	}
}
Example #7
0
		virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override
		{
			if (!a_HelpString.empty())
			{
				m_Commands.push_back(AStringPair(a_Command, a_HelpString));
				if (m_MaxLen < a_Command.length())
				{
					m_MaxLen = a_Command.length();
				}
			}
			return false;
		}
Example #8
0
cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions)
{
	AStringVector Split(StringSplit(a_Command, " "));
	if (Split.empty())
	{
		return crUnknownCommand;
	}

	CommandMap::iterator cmd = m_Commands.find(Split[0]);
	if (cmd == m_Commands.end())
	{
		// Command not found
		// If it started with a slash, ask the plugins if they still want to handle it:
		if (!a_Command.empty() && (a_Command[0] == '/'))
		{
			CommandResult Result = crUnknownCommand;
			CallHookExecuteCommand(&a_Player, Split, a_Command, Result);
			return Result;
		}
		return crUnknownCommand;
	}

	// Ask plugins first if a command is okay to execute the command:
	CommandResult Result = crBlocked;
	if (CallHookExecuteCommand(&a_Player, Split, a_Command, Result))
	{
		if (Result == crBlocked)
		{
			LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player.GetName().c_str(), Split[0].c_str());
		}
		return Result;
	}

	if (
		a_ShouldCheckPermissions &&
		!cmd->second.m_Permission.empty() &&
		!a_Player.HasPermission(cmd->second.m_Permission)
	)
	{
		LOGINFO("Player %s tried to execute forbidden command: \"%s\"", a_Player.GetName().c_str(), Split[0].c_str());
		return crNoPermission;
	}

	ASSERT(cmd->second.m_Handler != nullptr);

	if (!cmd->second.m_Handler->ExecuteCommand(Split, &a_Player, a_Command, nullptr))
	{
		return crError;
	}

	return crExecuted;
}
Example #9
0
bool cStatSerializer::Load(void)
{
	AString Data = cFile::ReadWholeFile(FILE_IO_PREFIX + m_Path);
	if (Data.empty())
	{
		Data = cFile::ReadWholeFile(FILE_IO_PREFIX + m_LegacyPath);
		if (Data.empty())
		{
			return false;
		}
	}

	Json::Value Root;
	Json::Reader Reader;

	if (Reader.parse(Data, Root, false))
	{
		return LoadStatFromJSON(Root);
	}

	return false;
}
Example #10
0
bool cHTTPServer::Initialize(void)
{
	// Read the HTTPS cert + key:
	AString CertFile = cFile::ReadWholeFile("webadmin/httpscert.crt");
	AString KeyFile  = cFile::ReadWholeFile("webadmin/httpskey.pem");
	if (!CertFile.empty() && !KeyFile.empty())
	{
		m_Cert.reset(new cX509Cert);
		int res = m_Cert->Parse(CertFile.data(), CertFile.size());
		if (res == 0)
		{
			m_CertPrivKey.reset(new cCryptoKey);
			int res2 = m_CertPrivKey->ParsePrivate(KeyFile.data(), KeyFile.size(), "");
			if (res2 != 0)
			{
				// Reading the private key failed, reset the cert:
				LOGWARNING("WebServer: Cannot read HTTPS certificate private key: -0x%x", -res2);
				m_Cert.reset();
			}
		}
		else
		{
			LOGWARNING("WebServer: Cannot read HTTPS certificate: -0x%x", -res);
		}
	}

	// Notify the admin about the HTTPS / HTTP status
	if (m_Cert.get() == nullptr)
	{
		LOGWARNING("WebServer: The server will run in unsecured HTTP mode.");
		LOGINFO("Put a valid HTTPS certificate in file 'webadmin/httpscert.crt' and its corresponding private key to 'webadmin/httpskey.pem' (without any password) to enable HTTPS support");
	}
	else
	{
		LOGINFO("WebServer: The server will run in secure HTTPS mode.");
	}
	return true;
}
Example #11
0
void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni)
{
	LOG("-- Loading Plugins --");
	m_bReloadPlugins = false;
	UnloadPluginsNow();

	FindPlugins();

	cServer::BindBuiltInConsoleCommands();
	
	unsigned int KeyNum = a_SettingsIni.FindKey("Plugins");
	unsigned int NumPlugins = ((KeyNum != -1) ? (a_SettingsIni.GetNumValues(KeyNum)) : 0);
	if (KeyNum == -1)
	{
		InsertDefaultPlugins(a_SettingsIni);
	}
	else if (NumPlugins > 0)
	{
		for(unsigned int i = 0; i < NumPlugins; i++)
		{
			AString ValueName = a_SettingsIni.GetValueName(KeyNum, i);
			if (ValueName.compare("Plugin") == 0)
			{
				AString PluginFile = a_SettingsIni.GetValue(KeyNum, i);
				if (!PluginFile.empty())
				{
					if (m_Plugins.find(PluginFile) != m_Plugins.end())
					{
						LoadPlugin( PluginFile );
					}
				}
			}
		}
	}

	if (GetNumPlugins() == 0)
	{
		LOG("-- No Plugins Loaded --");
	}
	else if (GetNumPlugins() > 1)
	{
		LOG("-- Loaded %i Plugins --", GetNumPlugins());
	}
	else
	{
		LOG("-- Loaded 1 Plugin --");
	}
}
Example #12
0
AString GetOSErrorString( int a_ErrNo)
{
	char buffer[ 1024 ];
	AString Out;

	#ifdef _WIN32

	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, a_ErrNo, 0, buffer, ARRAYCOUNT(buffer), NULL);
	Printf(Out, "%d: %s", a_ErrNo, buffer);
	if (!Out.empty() && (Out[Out.length() - 1] == '\n'))
	{
		Out.erase(Out.length() - 2);
	}
	return Out;
	
	#else  // _WIN32
	
	// According to http://linux.die.net/man/3/strerror_r there are two versions of strerror_r():
	
	#if !defined(__APPLE__) && ( _GNU_SOURCE) && !defined(ANDROID_NDK)  // GNU version of strerror_r()
	
	char * res = strerror_r( errno, buffer, ARRAYCOUNT(buffer));
	if (res != NULL)
	{
		Printf(Out, "%d: %s", a_ErrNo, res);
		return Out;
	}
	
	#else  // XSI version of strerror_r():
	
	int res = strerror_r( errno, buffer, ARRAYCOUNT(buffer));
	if (res == 0)
	{
		Printf(Out, "%d: %s", a_ErrNo, buffer);
		return Out;
	}
	
	#endif  // strerror_r() version
	
	else
	{
		Printf(Out, "Error %d while getting error string for error #%d!", errno, a_ErrNo);
		return Out;
	}
	
	#endif  // else _WIN32
}
Example #13
0
int cCryptoKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AString & a_Password)
{
	ASSERT(!IsValid());  // Cannot parse a second key
	
	if (a_Password.empty())
	{
		return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0);
	}
	else
	{
		return pk_parse_key(
			&m_Pk,
			(const unsigned char *)a_Data, a_NumBytes,
			(const unsigned char *)a_Password.c_str(), a_Password.size()
		);
	}
}
Example #14
0
void cCompositeChat::AddStyle(AString & a_Style, const AString & a_AddStyle)
{
	if (a_AddStyle.empty())
	{
		return;
	}
	if (a_AddStyle[0] == '@')
	{
		size_t idx = a_Style.find('@');
		if ((idx != AString::npos) && (idx != a_Style.length()))
		{
			a_Style.erase(idx, 2);
		}
		a_Style.append(a_AddStyle);
		return;
	}
	a_Style.append(a_AddStyle);
}
bool cSchematicFileSerializer::SaveToSchematicString(const cBlockArea & a_BlockArea, AString & a_Out)
{
	// Serialize into NBT data:
	AString NBT = SaveToSchematicNBT(a_BlockArea);
	if (NBT.empty())
	{
		LOG("%s: Cannot serialize the area into an NBT representation.", __FUNCTION__);
		return false;
	}

	// Gzip the data:
	int res = CompressStringGZIP(NBT.data(), NBT.size(), a_Out);
	if (res != Z_OK)
	{
		LOG("%s: Cannot Gzip the area data NBT representation: %d", __FUNCTION__, res);
		return false;
	}
	return true;
}
Example #16
0
void cRoot::LoadWorlds(cIniFile & IniFile)
{
	// First get the default world
	AString DefaultWorldName = IniFile.GetValueSet("Worlds", "DefaultWorld", "world");
	m_pDefaultWorld = new cWorld(DefaultWorldName.c_str());
	m_WorldsByName[ DefaultWorldName ] = m_pDefaultWorld;

	// Then load the other worlds
	int KeyNum = IniFile.FindKey("Worlds");
	int NumWorlds = IniFile.GetNumValues(KeyNum);
	if (NumWorlds <= 0)
	{
		return;
	}
	
	bool FoundAdditionalWorlds = false;
	for (int i = 0; i < NumWorlds; i++)
	{
		AString ValueName = IniFile.GetValueName(KeyNum, i);
		if (ValueName.compare("World") != 0)
		{
			continue;
		}
		AString WorldName = IniFile.GetValue(KeyNum, i);
		if (WorldName.empty())
		{
			continue;
		}
		FoundAdditionalWorlds = true;
		cWorld* NewWorld = new cWorld( WorldName.c_str());
		m_WorldsByName[ WorldName ] = NewWorld;
	}  // for i - Worlds

	if (!FoundAdditionalWorlds)
	{
		if (IniFile.GetKeyComment("Worlds", 0) != " World=secondworld")
		{
			IniFile.DeleteKeyComment("Worlds", 0);
			IniFile.AddKeyComment("Worlds", " World=secondworld");
		}
	}
}
Example #17
0
void cRoot::InputThread(cRoot & a_Params)
{
	cLogCommandOutputCallback Output;
	
	while (!a_Params.m_bStop && !a_Params.m_bRestart && !m_TerminateEventRaised && std::cin.good())
	{
		AString Command;
		std::getline(std::cin, Command);
		if (!Command.empty())
		{
			a_Params.ExecuteConsoleCommand(TrimString(Command), Output);
		}
	}

	if (m_TerminateEventRaised || !std::cin.good())
	{
		// We have come here because the std::cin has received an EOF / a terminate signal has been sent, and the server is still running; stop the server:
		a_Params.m_bStop = true;
	}
}
Example #18
0
void cProtocol_1_10_0::HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer)
{
	cServer * Server = cRoot::Get()->GetServer();
	AString ServerDescription = Server->GetDescription();
	auto NumPlayers = static_cast<signed>(Server->GetNumPlayers());
	auto MaxPlayers = static_cast<signed>(Server->GetMaxPlayers());
	AString Favicon = Server->GetFaviconData();
	cRoot::Get()->GetPluginManager()->CallHookServerPing(*m_Client, ServerDescription, NumPlayers, MaxPlayers, Favicon);

	// Version:
	Json::Value Version;
	Version["name"] = "Cuberite 1.10";
	Version["protocol"] = 210;

	// Players:
	Json::Value Players;
	Players["online"] = NumPlayers;
	Players["max"] = MaxPlayers;
	// TODO: Add "sample"

	// Description:
	Json::Value Description;
	Description["text"] = ServerDescription.c_str();

	// Create the response:
	Json::Value ResponseValue;
	ResponseValue["version"] = Version;
	ResponseValue["players"] = Players;
	ResponseValue["description"] = Description;
	m_Client->ForgeAugmentServerListPing(ResponseValue);
	if (!Favicon.empty())
	{
		ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
	}

	Json::FastWriter Writer;
	AString Response = Writer.write(ResponseValue);

	cPacketizer Pkt(*this, 0x00);  // Response packet
	Pkt.WriteString(Response);
}
Example #19
0
void cRoot::LoadWorlds(cSettingsRepositoryInterface & a_Settings)
{
	// First get the default world
	AString DefaultWorldName = a_Settings.GetValueSet("Worlds", "DefaultWorld", "world");
	m_pDefaultWorld = new cWorld(DefaultWorldName.c_str());
	m_WorldsByName[ DefaultWorldName ] = m_pDefaultWorld;

	// Then load the other worlds
	auto Worlds = a_Settings.GetValues("Worlds");
	if (Worlds.size() <= 0)
	{
		return;
	}

	bool FoundAdditionalWorlds = false;
	for (auto WorldNameValue : Worlds)
	{
		AString ValueName = WorldNameValue.first;
		if (ValueName.compare("World") != 0)
		{
			continue;
		}
		AString WorldName = WorldNameValue.second;
		if (WorldName.empty())
		{
			continue;
		}
		FoundAdditionalWorlds = true;
		cWorld * NewWorld = new cWorld(WorldName.c_str());
		m_WorldsByName[WorldName] = NewWorld;
	}  // for i - Worlds

	if (!FoundAdditionalWorlds)
	{
		if (a_Settings.GetKeyComment("Worlds", 0) != " World=secondworld")
		{
			a_Settings.DeleteKeyComment("Worlds", 0);
			a_Settings.AddKeyComment("Worlds", " World=secondworld");
		}
	}
}
Example #20
0
AString cLuaTCPLink::StartTLSClient(
	const AString & a_OwnCertData,
	const AString & a_OwnPrivKeyData,
	const AString & a_OwnPrivKeyPassword
)
{
	// Check preconditions:
	if (m_SslContext != nullptr)
	{
		return "TLS is already active on this link";
	}
	if (
		(a_OwnCertData.empty()  && !a_OwnPrivKeyData.empty()) ||
		(!a_OwnCertData.empty() && a_OwnPrivKeyData.empty())
	)
	{
		return "Either provide both the certificate and private key, or neither";
	}

	// Create the SSL context:
	m_SslContext.reset(new cLinkSslContext(*this));
	m_SslContext->Initialize(true);

	// Create the peer cert, if required:
	if (!a_OwnCertData.empty() && !a_OwnPrivKeyData.empty())
	{
		auto OwnCert = std::make_shared<cX509Cert>();
		int res = OwnCert->Parse(a_OwnCertData.data(), a_OwnCertData.size());
		if (res != 0)
		{
			m_SslContext.reset();
			return Printf("Cannot parse peer certificate: -0x%x", res);
		}
		auto OwnPrivKey = std::make_shared<cCryptoKey>();
		res = OwnPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword);
		if (res != 0)
		{
			m_SslContext.reset();
			return Printf("Cannot parse peer private key: -0x%x", res);
		}
		m_SslContext->SetOwnCert(OwnCert, OwnPrivKey);
	}
	m_SslContext->SetSelf(cLinkSslContextWPtr(m_SslContext));

	// Start the handshake:
	m_SslContext->Handshake();
	return "";
}
void cProtocolRecognizer::SendPingStatusResponse(void)
{
	cServer * Server = cRoot::Get()->GetServer();
	AString ServerDescription = Server->GetDescription();
	int NumPlayers = Server->GetNumPlayers();
	int MaxPlayers = Server->GetMaxPlayers();
	AString Favicon = Server->GetFaviconData();
	cRoot::Get()->GetPluginManager()->CallHookServerPing(*m_Client, ServerDescription, NumPlayers, MaxPlayers, Favicon);

	// Version:
	Json::Value Version;
	Version["name"] = "Cuberite " MCS_CLIENT_VERSIONS;
	Version["protocol"] = 0;  // Force client to think this is an invalid version (no other good default)

	// Players:
	Json::Value Players;
	Players["online"] = NumPlayers;
	Players["max"] = MaxPlayers;
	// TODO: Add "sample"

	// Description:
	Json::Value Description;
	Description["text"] = ServerDescription.c_str();

	// Create the response:
	Json::Value ResponseValue;
	ResponseValue["version"] = Version;
	ResponseValue["players"] = Players;
	ResponseValue["description"] = Description;
	if (!Favicon.empty())
	{
		ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
	}

	Json::StyledWriter Writer;
	AString Response = Writer.write(ResponseValue);

	cPacketizer Pkt(*this, 0x00);  // Response packet
	Pkt.WriteString(Response);
}
/** Binds cLuaTCPLink::StartTLSServer */
static int tolua_cTCPLink_StartTLSServer(lua_State * L)
{
	// Function signature:
	// LinkInstance:StartTLSServer(OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData) -> [true] or [nil, ErrMsg]

	cLuaState S(L);
	if (
		!S.CheckParamUserType(1, "cTCPLink") ||
		!S.CheckParamString(2, 4) ||
		// Param 5 is optional, don't check
		!S.CheckParamEnd(6)
	)
	{
		return 0;
	}
	
	// Get the link:
	cLuaTCPLink * Link;
	if (lua_isnil(L, 1))
	{
		LOGWARNING("cTCPLink:StartTLSServer(): invalid link object. Stack trace:");
		S.LogStackTrace();
		return 0;
	}
	Link = *static_cast<cLuaTCPLink **>(lua_touserdata(L, 1));

	// Read the params:
	AString OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData;
	S.GetStackValues(2, OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData);

	// Start the TLS handshake:
	AString res = Link->StartTLSServer(OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData);
	if (!res.empty())
	{
		S.PushNil();
		S.Push(Printf("Cannot start TLS on link to %s:%d: %s", Link->GetRemoteIP().c_str(), Link->GetRemotePort(), res.c_str()));
		return 2;
	}
	return 1;
}
Example #23
0
cMonster::cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, double a_Width, double a_Height)
	: super(etMonster, a_Width, a_Height)
	, m_EMState(IDLE)
	, m_EMPersonality(AGGRESSIVE)
	, m_Target(nullptr)
	, m_Path(nullptr)
	, m_IsFollowingPath(false)
	, m_PathfinderActivated(false)
	, m_GiveUpCounter(0)
	, m_TicksSinceLastPathReset(1000)
	, m_LastGroundHeight(POSY_TOINT)
	, m_JumpCoolDown(0)
	, m_IdleInterval(0)
	, m_DestroyTimer(0)
	, m_MobType(a_MobType)
	, m_CustomName("")
	, m_CustomNameAlwaysVisible(false)
	, m_SoundHurt(a_SoundHurt)
	, m_SoundDeath(a_SoundDeath)
	, m_AttackRate(3)
	, m_AttackDamage(1)
	, m_AttackRange(1)
	, m_AttackInterval(0)
	, m_SightDistance(25)
	, m_DropChanceWeapon(0.085f)
	, m_DropChanceHelmet(0.085f)
	, m_DropChanceChestplate(0.085f)
	, m_DropChanceLeggings(0.085f)
	, m_DropChanceBoots(0.085f)
	, m_CanPickUpLoot(true)
	, m_TicksSinceLastDamaged(100)
	, m_BurnsInDaylight(false)
	, m_RelativeWalkSpeed(1)
	, m_Age(1)
{
	if (!a_ConfigName.empty())
	{
		GetMonsterConfig(a_ConfigName);
	}
}
Example #24
0
void cPlayer::LoadPermissionsFromDisk()
{
	m_Groups.clear();
	m_Permissions.clear();

	cIniFile IniFile;
	if (IniFile.ReadFile("users.ini"))
	{
		std::string Groups = IniFile.GetValue(m_PlayerName, "Groups", "");
		if (!Groups.empty())
		{
			AStringVector Split = StringSplitAndTrim(Groups, ",");
			for (AStringVector::const_iterator itr = Split.begin(), end = Split.end(); itr != end; ++itr)
			{
				if (!cRoot::Get()->GetGroupManager()->ExistsGroup(*itr))
				{
					LOGWARNING("The group %s for player %s was not found!", itr->c_str(), m_PlayerName.c_str());
				}
				AddToGroup(*itr);
			}
		}
		else
		{
			AddToGroup("Default");
		}

		AString Color = IniFile.GetValue(m_PlayerName, "Color", "-");
		if (!Color.empty())
		{
			m_Color = Color[0];
		}
	}
	else
	{
		cGroupManager::GenerateDefaultUsersIni(IniFile);
		AddToGroup("Default");
	}
	ResolvePermissions();
}
Example #25
0
bool cPluginLua::HandleConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output, const AString & a_FullCommand)
{
	ASSERT(!a_Split.empty());
	CommandMap::iterator cmd = m_ConsoleCommands.find(a_Split[0]);
	if (cmd == m_ConsoleCommands.end())
	{
		LOGWARNING("Console command handler is registered in cPluginManager but not in cPlugin, wtf? Console command \"%s\", plugin \"%s\".",
			a_Split[0].c_str(), GetName().c_str()
		);
		return false;
	}

	cCSLock Lock(m_CriticalSection);
	bool res = false;
	AString str;
	m_LuaState.Call(cmd->second, a_Split, a_FullCommand, cLuaState::Return, res, str);
	if (res && !str.empty())
	{
		a_Output.Out(str);
	}
	return res;
}
Example #26
0
bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message)
{
	bool WasCommandForbidden = false;
	if (HandleCommand(a_Player, a_Message, true, WasCommandForbidden))  // We use HandleCommand as opposed to ExecuteCommand to accomodate the need to the WasCommandForbidden bool
	{
		return true;  // Chat message was handled as command
	}
	else if (WasCommandForbidden) // Couldn't be handled as command, was it because of insufficient permissions?
	{
		return true;  // Yes - message was sent in HandleCommand, abort
	}

	// Check if it was a standard command (starts with a slash)
	// If it was, we know that it was completely unrecognised (WasCommandForbidden == false)
	if (!a_Message.empty() && (a_Message[0] == '/'))
	{
		AStringVector Split(StringSplit(a_Message, " "));
		ASSERT(!Split.empty());  // This should not happen - we know there's at least one char in the message so the split needs to be at least one item long
		a_Player->SendMessage(Printf("%s[INFO] %sUnknown command: \"%s\"", cChatColor::Yellow.c_str(), cChatColor::White.c_str(), Split[0].c_str()));
		LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player->GetName().c_str(), a_Message.c_str());
		return true;  // Cancel sending
	}

	HookMap::iterator Plugins = m_Hooks.find(HOOK_CHAT);
	if (Plugins == m_Hooks.end())
	{
		return false;
	}

	for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
	{
		if ((*itr)->OnChat(a_Player, a_Message))
		{
			return true;
		}
	}

	return false;
}
Example #27
0
bool cPlayer::HasPermission(const AString & a_Permission)
{
	if (a_Permission.empty())
	{
		// Empty permission request is always granted
		return true;
	}
	
	AStringVector Split = StringSplit(a_Permission, ".");

	// Iterate over all granted permissions; if any matches, then return success:
	for (AStringVectorVector::const_iterator itr = m_SplitPermissions.begin(), end = m_SplitPermissions.end(); itr != end; ++itr)
	{
		if (PermissionMatches(Split, *itr))
		{
			return true;
		}
	}  // for itr - m_SplitPermissions[]

	// No granted permission matches
	return false;
}
Example #28
0
void cRoot::InputThread(cRoot & a_Params)
{
	cLogCommandOutputCallback Output;

	while (a_Params.m_InputThreadRunFlag.test_and_set() && std::cin.good())
	{
		AString Command;
		std::getline(std::cin, Command);
		if (!Command.empty())
		{
			// Execute and clear command string when submitted
			a_Params.ExecuteConsoleCommand(TrimString(Command), Output);
		}
	}

	// We have come here because the std::cin has received an EOF / a terminate signal has been sent, and the server is still running
	// Ignore this when running as a service, cin was never opened in that case
	if (!std::cin.good() && !m_RunAsService)
	{
		// Stop the server:
		a_Params.QueueExecuteConsoleCommand("stop");
	}
}
Example #29
0
bool cFile::CreateFolderRecursive(const AString & a_FolderPath)
{
	// Special case: Fail if the path is empty
	if (a_FolderPath.empty())
	{
		return false;
	}

	// Go through each path element and create the folder:
	auto len = a_FolderPath.length();
	auto PathSep = GetPathSeparator()[0];
	for (decltype(len) i = 0; i < len; i++)
	{
		if (a_FolderPath[i] == PathSep)
		{
			CreateFolder(a_FolderPath.substr(0, i));
		}
	}
	CreateFolder(a_FolderPath);

	// Check the result by querying whether the final path exists:
	return IsFolder(a_FolderPath);
}
Example #30
0
			Air::U1 System::AddPackage( CAString& strPackageName ){
				if(strPackageName.empty())
					return	false;

				Package*	p	=	NULL;

				if(strPackageName.size()	<	4){
					p	=	CreateProduct<Package>(strPackageName);

				}else{
					AString	strPostfix	=	Converter::ToLowerCase(Common::GetPostfix(strPackageName));
					if(strPostfix.empty()||	strPostfix[0]=='/'||strPostfix[0]=='\\'){
						p	=	CreateProduct<Package>(strPackageName);
					}else{
						p	=	CreateProduct<Package>(strPackageName,strPostfix);
					}
				}

				if(p!=NULL){
					m_lstPackage.push_back(p);
				}
				return	true;
			}