Example #1
0
/*********************************************************************\
	Function name    : WriteString
	Description      : writes a string without length information into a file
										 bReplace == true : ä ö ü will be replaced
	Created at       : 30.08.01, @ 10:35:54
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
Bool WriteString(BaseFile* pFile, String str, Bool bReplace)
{
	Int32 lPos, lStart = 0;
	Int32 lLen = str.GetLength();
	if (bReplace)
	{
		while (str.FindFirst('\"', &lPos, lStart))
		{
			str = str.SubStr(0, lPos) + "$\"" + str.SubStr(lPos + 1, lLen - lPos - 1);
			lStart = lPos + 2;
			lLen++;
		}
	}

	lLen = str.GetCStringLen(STRINGENCODING_7BITHEX);
	char* pCh = bNewDeprecatedUseArraysInstead<char>(lLen + 2);
	str.GetCString(pCh, lLen + 1, STRINGENCODING_7BITHEX);

	for (Int32 l = 0; l < lLen; l++)
		pFile->WriteChar(pCh[l]);

	bDelete(pCh);

	return true;
}
Example #2
0
ApiUser::Ptr ApiUser::GetByAuthHeader(const String& auth_header)
{
	String::SizeType pos = auth_header.FindFirstOf(" ");
	String username, password;

	if (pos != String::NPos && auth_header.SubStr(0, pos) == "Basic") {
		String credentials_base64 = auth_header.SubStr(pos + 1);
		String credentials = Base64::Decode(credentials_base64);

		String::SizeType cpos = credentials.FindFirstOf(":");

		if (cpos != String::NPos) {
			username = credentials.SubStr(0, cpos);
			password = credentials.SubStr(cpos + 1);
		}
	}

	const ApiUser::Ptr& user = ApiUser::GetByName(username);

	/* Deny authentication if:
	 * 1) user does not exist
	 * 2) given password is empty
	 * 2) configured password does not match.
	 */
	if (!user || password.IsEmpty())
		return nullptr;
	else if (user && user->GetPassword() != password)
		return nullptr;

	return user;
}
Example #3
0
String Type::GetPluralName(void) const
{
	String name = GetName();

	if (name.GetLength() >= 2 && name[name.GetLength() - 1] == 'y' &&
	    name.SubStr(name.GetLength() - 2, 1).FindFirstOf("aeiou") == String::NPos)
		return name.SubStr(0, name.GetLength() - 1) + "ies";
	else
		return name + "s";
}
Example #4
0
void StringReplace::FindAndReplace(String &str, const String &strFind, const String &strReplace)
{
	Int32 lStart = 0;
	Int32 lPos;
	while (str.FindFirst(strFind, &lPos, lStart))
	{
		str = str.SubStr(0, lPos) + strReplace + str.SubStr(lPos + strFind.GetLength(), str.GetLength() - lPos - strFind.GetLength());
		lStart = lPos;
	}
}
Example #5
0
void HttpConnection::ProcessMessageAsync(HttpRequest& request)
{
	Log(LogInformation, "HttpConnection", "Processing Http message");

	String auth_header = request.Headers->Get("authorization");

	String::SizeType pos = auth_header.FindFirstOf(" ");
	String username, password;

	if (pos != String::NPos && auth_header.SubStr(0, pos) == "Basic") {
		String credentials_base64 = auth_header.SubStr(pos + 1);
		String credentials = Base64::Decode(credentials_base64);

		String::SizeType cpos = credentials.FindFirstOf(":");

		if (cpos != String::NPos) {
			username = credentials.SubStr(0, cpos);
			password = credentials.SubStr(cpos + 1);
		}
	}

	ApiUser::Ptr user;

	if (m_ApiUser)
		user = m_ApiUser;
	else {
		user = ApiUser::GetByName(username);

		if (!user || !user->CheckPassword(password))
			user.reset();
	}

	HttpResponse response(m_Stream, request);

	if (!user) {
		response.SetStatus(401, "Unauthorized");
		response.AddHeader("Content-Type", "text/html");
		response.AddHeader("WWW-Authenticate", "Basic realm=\"Icinga 2\"");
		String msg = "<h1>Unauthorized</h1>";
		response.WriteBody(msg.CStr(), msg.GetLength());
	} else {
		try {
			HttpHandler::ProcessRequest(user, request, response);
		} catch (const std::exception& ex) {
			response.SetStatus(503, "Unhandled exception");
			response.AddHeader("Content-Type", "text/plain");
			String errorInfo = DiagnosticInformation(ex);
			response.WriteBody(errorInfo.CStr(), errorInfo.GetLength());
		}
	}

	response.Finish();

	m_PendingRequests--;
}
Example #6
0
Url::Url(const String& base_url)
{
	String url = base_url;

	if (url.GetLength() == 0)
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Empty URL."));

	size_t pHelper = url.Find(":");

	if (pHelper != String::NPos) {
		if (!ParseScheme(url.SubStr(0, pHelper)))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Scheme."));
		url = url.SubStr(pHelper + 1);
	}

	if (*url.Begin() != '/')
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL: '/' expected after scheme."));

	if (url.GetLength() == 1) {
		return;
	}

	if (*(url.Begin() + 1) == '/') {
		pHelper = url.Find("/", 2);

		if (pHelper == String::NPos)
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL: Missing '/' after authority."));

		if (!ParseAuthority(url.SubStr(0, pHelper)))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Authority"));

		url = url.SubStr(pHelper);
	}

	if (*url.Begin() == '/') {
		pHelper = url.FindFirstOf("#?");
		if (!ParsePath(url.SubStr(1, pHelper - 1)))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Path"));

		if (pHelper != String::NPos)
			url = url.SubStr(pHelper);
	} else
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL: Missing path."));

	if (*url.Begin() == '?') {
		pHelper = url.Find("#");
		if (!ParseQuery(url.SubStr(1, pHelper - 1)))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Query"));

		if (pHelper != String::NPos)
			url = url.SubStr(pHelper);
	}

	if (*url.Begin() == '#') {
		if (!ParseFragment(url.SubStr(1)))
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid URL Fragment"));
	}
}
Example #7
0
static String StringSubstr(const std::vector<Value>& args)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	String self = vframe->Self;

	if (args.empty())
		BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments"));

	if (static_cast<double>(args[0]) < 0 || static_cast<double>(args[0]) >= self.GetLength())
		BOOST_THROW_EXCEPTION(std::invalid_argument("String index is out of range"));

	if (args.size() > 1)
		return self.SubStr(args[0], args[1]);
	else
		return self.SubStr(args[0]);
}
Example #8
0
static String LoadAppType(const String& typeSpec)
{
	int index;

	Log(LogInformation, "icinga-app", "Loading application type: " + typeSpec);

	index = typeSpec.FindFirstOf('/');

	if (index == String::NPos)
		return typeSpec;

	String library = typeSpec.SubStr(0, index);

	(void) Utility::LoadExtensionLibrary(library);

	return typeSpec.SubStr(index + 1);
}
Example #9
0
bool Url::ParseUserinfo(const String& userinfo)
{
	size_t pos = userinfo.Find(":");
	m_Username = userinfo.SubStr(0, pos);
	if (!ValidateToken(m_Username, ACUSERINFO))
		return false;
	m_Username = Utility::UnescapeString(m_Username);
	if (pos != String::NPos && pos != userinfo.GetLength() - 1) {
		m_Password = userinfo.SubStr(pos+1);
		if (!ValidateToken(m_Username, ACUSERINFO))
			return false;
		m_Password = Utility::UnescapeString(m_Password);
	} else
		m_Password = "";

	return true;
}
Example #10
0
int VcfHelper::chromName2Num(const String & chr) {
  int n = atoi(chr.c_str());
  if ( n > 0 ) { return n; }
  else {
    String s = chr;
    if ( s.Left(3).Compare("chr") == 0 ) {
      n = atoi(s.SubStr(3).c_str());
      if ( n > 0 ) { return n; }
      s = s.SubStr(3);
    }
    for(int i=0; i < asChromNames.Length(); ++i) {
      if ( s.Compare(asChromNames[i]) == 0 ) {
	return vnChromNums[i];
      }
    }
  }
  throw VcfFileException("Cannot recognize chromosome %s",chr.c_str());
}
Example #11
0
/*********************************************************************\
	Function name    : TrimNumbers
	Description      : deletes the numbers at the end of a string
	Created at       : 05.01.02, @ 10:33:17
	Created by       : Thomas Kunert
	Modified by      :
\*********************************************************************/
String TrimNumbers(String str)
{
	String strRet;
	String str1;

	Int32 lLen = str.GetLength();
	Int32 l;
	for (l = lLen - 1; l >= 0; l--)
	{
		str1 = str.SubStr(l, lLen - l);
		if (!IsInteger(str1)) break;
	}

	if (l == -1) strRet = str1;
	else strRet = str.SubStr(0, l + 1);

	return strRet;
}
Example #12
0
bool Url::ParseAuthority(const String& authority)
{
	String auth = authority.SubStr(2);
	size_t pos = auth.Find("@");
	if (pos != String::NPos && pos != 0) {
		if (!Url::ParseUserinfo(auth.SubStr(0, pos)))
			return false;
		auth = auth.SubStr(pos+1);
	}

	pos = auth.Find(":");
	if (pos != String::NPos) {
		if (pos == 0 || pos == auth.GetLength() - 1 || !Url::ParsePort(auth.SubStr(pos+1)))
			return false;
	}

	m_Host = auth.SubStr(0, pos);
	return ValidateToken(m_Host, ACHOST);
}
Example #13
0
FileSearch::Ref PosixFileSearch::New(
	const String &path,
	const String &prefix,
	SearchOptions options
) {
	String dir, pattern;

	// split the pattern out of the directory
	const char *sz = path.c_str;
	for (int i = path.numBytes - 1; i >= 0; --i) {
		if (sz[i] == '/') {
			dir = String(sz, i, string::CopyTag);
			pattern = path.SubStr(i+1); // no leading /
			break;
		}
	}

	if (dir.empty || pattern.empty)
		return FileSearch::Ref();

	PosixFileSearch *s = new (ZFile) PosixFileSearch(dir, prefix, pattern, options);

	s->m_sdir = opendir(dir.c_str);
	if (!s->m_sdir) {
		delete s;
		return FileSearch::Ref();
	}
	
	s->m_cur = new (ZFile) dirent;
	s->m_cur->d_name[0] = 0;
	
	// must see if a file exists that matches our pattern (prime the search).
	for (;;) {
		struct dirent *next;
		if ((readdir_r((DIR*)s->m_sdir, s->m_cur, &next) != 0) || (next == 0)) {
			::closedir((DIR*)s->m_sdir);
			s->m_sdir = 0;
			break;
		}
		if (next->d_type == DT_REG) {
			if (fnmatch(pattern.c_str, &next->d_name[0], 0) != FNM_NOMATCH)
				break;
		}
	}
	
	if (!s->m_sdir) {
		if (s->NextState() == kState_Done) {
			delete s;
			return FileSearch::Ref();
		}
	}

	return FileSearch::Ref(s);
}
Example #14
0
	FileInfo FileSystem::GetFileInfo(const String& path) const
	{
		FileInfo res;
		res.path = "invalid_file";

		FILETIME creationTime, lastAccessTime, lastWriteTime;
		HANDLE hFile = CreateFileA(path.Data(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
		if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
		{
			auto err = GetLastError();
			return res;
		}

		if (!GetFileTime(hFile, &creationTime, &lastAccessTime, &lastWriteTime))
		{
			CloseHandle(hFile);
			return res;
		}

		SYSTEMTIME stUTC, stLocal;

		FileTimeToSystemTime(&creationTime, &stUTC);
		SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
		res.createdDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear);

		FileTimeToSystemTime(&lastAccessTime, &stUTC);
		SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
		res.accessDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear);

		FileTimeToSystemTime(&lastWriteTime, &stUTC);
		SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
		res.editDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear);

		res.path = path;
		String extension = path.SubStr(path.FindLast(".") + 1);
		res.fileType = FileType::File;

		for (auto iext : mInstance->mExtensions)
		{
			if (iext.Value().Contains(extension))
			{
				res.fileType = iext.Key();
				break;
			}
		}

		DWORD dwSizeHigh = 0, dwSizeLow = 0;
		dwSizeLow = GetFileSize(hFile, &dwSizeHigh);
		res.size = (dwSizeHigh * (MAXDWORD+1)) + dwSizeLow;

		CloseHandle(hFile);

		return res;
	}
void CServerBrowser::MasterListQueryHandler(std::vector<String> serverVector)
{
	// Loop through all servers
	for(std::vector<String>::iterator iter = serverVector.begin(); iter != serverVector.end(); iter++)
	{
		// Get the address
		String strAddress = (*iter);

		// Get the ip and port
		size_t sSplit = strAddress.Find(':', 0);
		String strIp = strAddress.SubStr(0, sSplit++);
		String strPort = strAddress.SubStr(sSplit, (strAddress.GetLength() - sSplit));

		// Do we have a valid ip and port?
		if(strIp.IsEmpty() || strPort.IsEmpty())
			continue;

		// Query the server
		CServerBrowser::GetSingleton()->m_pServerQuery->Query(strIp, strPort.ToInteger(), "i");
	}
}
Example #16
0
/**
 * Prints a stacktrace to the specified stream.
 *
 * @param fp The stream.
 * @param ignoreFrames The number of stackframes to ignore (in addition to
 *		       the one this function is executing in).
 * @returns true if the stacktrace was printed, false otherwise.
 */
void StackTrace::Print(std::ostream& fp, int ignoreFrames) const
{
	fp << std::endl;

#ifndef _WIN32
#	ifdef HAVE_BACKTRACE_SYMBOLS
	char **messages = backtrace_symbols(m_Frames, m_Count);

	for (int i = ignoreFrames + 1; i < m_Count && messages != NULL; ++i) {
		String message = messages[i];

		char *sym_begin = strchr(messages[i], '(');

		if (sym_begin) {
			char *sym_end = strchr(sym_begin, '+');

			if (sym_end != NULL) {
				String sym = String(sym_begin + 1, sym_end);
				String sym_demangled = Utility::DemangleSymbolName(sym);

				if (sym_demangled.IsEmpty())
					sym_demangled = "<unknown function>";

				String path = String(messages[i], sym_begin);

				size_t slashp = path.RFind("/");

				if (slashp != String::NPos)
					path = path.SubStr(slashp + 1);

				message = path + ": " + sym_demangled + " (" + String(sym_end);
			}
		}

		fp << "\t(" << i - ignoreFrames - 1 << ") " << message << std::endl;
	}

	std::free(messages);

	fp << std::endl;
#	else /* HAVE_BACKTRACE_SYMBOLS */
	fp << "(not available)" << std::endl;
#	endif /* HAVE_BACKTRACE_SYMBOLS */
#else /* _WIN32 */
	for (int i = ignoreFrames + 1; i < m_Count; i++) {
		fp << "\t(" << i - ignoreFrames - 1 << "): "
		   << Utility::GetSymbolName(m_Frames[i])
		   << std::endl;
	}
#endif /* _WIN32 */
}
Example #17
0
void StringReplace::Replace(String &str)
{
	// test for environment variables
	Int32 lStart, lEnd, lStartSearch = 0;
	Int32 lStringLen;
	String strExpr;
	char* pchEnvVar;
	char pszVar[1000];
	BaseContainer bc;

	while (str.FindFirst("($", &lStart, lStartSearch))
	{
		if (!str.FindFirst("$)", &lEnd, lStart))
			return;
		lStartSearch = lStart + 1;

		strExpr = str.SubStr(lStart + 2, lEnd - lStart - 2);
		lStringLen = strExpr.GetCStringLen(STRINGENCODING_8BIT);
		Char* pchString = NewMem(Char,lStringLen + 2);
		if (!pchString)
			return;
		strExpr.GetCString(pchString, lStringLen + 1, STRINGENCODING_8BIT);
		pchEnvVar = GetOSEnvironmentVariable(pchString, pszVar, 1000);
		DeleteMem(pchString);
		if (pchEnvVar)
			str = str.SubStr(0, lStart) + String(pchEnvVar) + str.SubStr(lEnd + 2, str.GetLength() - lEnd - 2);
	}

	FindAndReplace(str, String("($CINEMA_4D_ROOT$)"), m_strStartupPath);
	FindAndReplace(str, String("($CINEMA_4D_PLUGIN$)"), m_strPluginPath);
	FindAndReplace(str, String("($CINEMA_4D_VERSION$)"), m_strCurrentVersion);
	FindAndReplace(str, String("($CURRENT_DATE$)"), m_strDate);
	FindAndReplace(str, String("($CURRENT_TIME$)"), m_strTime);
	FindAndReplace(str, String("($CURRENT_DATE_TIME$)"), m_strDateTime);
	FindAndReplace(str, String("($BUILD_VERSION$)"), m_strBuildVersion);
	FindAndReplace(str, String("($RELEASE_LINE$)"), m_strReleaseLine);
	FindAndReplace(str, String("($BUILD_ID$)"), m_strBuildID);
}
Example #18
0
void ApiListener::ConfigGlobHandler(Dictionary::Ptr& config, const String& path, const String& file)
{
	CONTEXT("Creating config update for file '" + file + "'");

	Log(LogNotice, "ApiListener")
	    << "Creating config update for file '" << file << "'";

	std::ifstream fp(file.CStr(), std::ifstream::binary);
	if (!fp)
		return;

	String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
	config->Set(file.SubStr(path.GetLength()), content);
}
Example #19
0
bool Url::ParseQuery(const String& query)
{
	/* Tokenizer does not like String AT ALL */
	std::string queryStr = query;
	boost::char_separator<char> sep("&");
	boost::tokenizer<boost::char_separator<char> > tokens(queryStr, sep);

	for (const String& token : tokens) {
		size_t pHelper = token.Find("=");

		if (pHelper == 0)
			// /?foo=bar&=bar == invalid
			return false;

		String key = token.SubStr(0, pHelper);
		String value = Empty;

		if (pHelper != String::NPos && pHelper != token.GetLength() - 1)
			value = token.SubStr(pHelper+1);

		if (!ValidateToken(value, ACQUERY))
			return false;

		value = Utility::UnescapeString(value);

		pHelper = key.Find("[]");

		if (pHelper == 0 || (pHelper != String::NPos && pHelper != key.GetLength()-2))
			return false;

		key = key.SubStr(0, pHelper);

		if (!ValidateToken(key, ACQUERY))
			return false;

		key = Utility::UnescapeString(key);

		auto it = m_Query.find(key);

		if (it == m_Query.end()) {
			m_Query[key] = std::vector<String>();
			m_Query[key].push_back(value);
		} else
			m_Query[key].push_back(value);

	}

	return true;
}
Example #20
0
Column Table::GetColumn(const String& name) const
{
	String dname = name;
	String prefix = GetPrefix() + "_";

	if (dname.Find(prefix) == 0)
		dname = dname.SubStr(prefix.GetLength());

	auto it = m_Columns.find(dname);

	if (it == m_Columns.end())
		BOOST_THROW_EXCEPTION(std::invalid_argument("Column '" + dname + "' does not exist in table '" + GetName() + "'."));

	return it->second;
}
Example #21
0
bool VcfHelper::isAutosome(const String & chr)
{
    // Return true for numeric chromosome number (1-22 or chr1-chr22),
    // false for anything else
    int n = atoi(chr.c_str());
    if ( n > 0 ) { return true; }
    else {
        String s = chr;
        if ( s.Left(3).Compare("chr") == 0 ) {
            n = atoi(s.SubStr(3).c_str());
            if ( n > 0 ) { return true; }
        }
        return false;
    }
}
Example #22
0
std::vector<String> ConsoleHandler::GetAutocompletionSuggestions(const String& word, ScriptFrame& frame)
{
	std::vector<String> matches;

	for (const String& keyword : ConfigWriter::GetKeywords()) {
		AddSuggestion(matches, word, keyword);
	}

	{
		ObjectLock olock(frame.Locals);
		for (const Dictionary::Pair& kv : frame.Locals) {
			AddSuggestion(matches, word, kv.first);
		}
	}

	{
		ObjectLock olock(ScriptGlobal::GetGlobals());
		for (const Namespace::Pair& kv : ScriptGlobal::GetGlobals()) {
			AddSuggestion(matches, word, kv.first);
		}
	}

	Namespace::Ptr systemNS = ScriptGlobal::Get("System");

	AddSuggestions(matches, word, "", false, systemNS);
	AddSuggestions(matches, word, "", true, systemNS->Get("Configuration"));
	AddSuggestions(matches, word, "", false, ScriptGlobal::Get("Types"));
	AddSuggestions(matches, word, "", false, ScriptGlobal::Get("Icinga"));

	String::SizeType cperiod = word.RFind(".");

	if (cperiod != String::NPos) {
		String pword = word.SubStr(0, cperiod);

		Value value;

		try {
			std::unique_ptr<Expression> expr = ConfigCompiler::CompileText("temp", pword);

			if (expr)
				value = expr->Evaluate(frame);

			AddSuggestions(matches, word, pword, true, value);
		} catch (...) { /* Ignore the exception */ }
	}

	return matches;
}
void LegacyTimePeriod::ParseTimeRange(const String& timerange, tm *begin, tm *end, int *stride, tm *reference)
{
	String def = timerange;

	/* Figure out the stride. */
	size_t pos = def.FindFirstOf('/');

	if (pos != String::NPos) {
		String strStride = def.SubStr(pos + 1).Trim();
		*stride = Convert::ToLong(strStride);

		/* Remove the stride parameter from the definition. */
		def = def.SubStr(0, pos);
	} else {
		*stride = 1; /* User didn't specify anything, assume default. */
	}

	/* Figure out whether the user has specified two dates. */
	pos = def.Find("- ");

	if (pos != String::NPos) {
		String first = def.SubStr(0, pos).Trim();

		String second = def.SubStr(pos + 1).Trim();

		ParseTimeSpec(first, begin, NULL, reference);

		/* If the second definition starts with a number we need
		 * to add the first word from the first definition, e.g.:
		 * day 1 - 15 --> "day 15" */
		bool is_number = true;
		size_t xpos = second.FindFirstOf(' ');
		String fword = second.SubStr(0, xpos);

		try {
			Convert::ToLong(fword);
		} catch (...) {
			is_number = false;
		}

		if (is_number) {
			xpos = first.FindFirstOf(' ');
			ASSERT(xpos != String::NPos);
			second = first.SubStr(0, xpos + 1) + second;
		}

		ParseTimeSpec(second, NULL, end, reference);
	} else {
		ParseTimeSpec(def, begin, end, reference);
	}
}
Example #24
0
void ApiListener::ConfigGlobHandler(ConfigDirInformation& config, const String& path, const String& file)
{
	CONTEXT("Creating config update for file '" + file + "'");

	Log(LogNotice, "ApiListener")
		<< "Creating config update for file '" << file << "'.";

	std::ifstream fp(file.CStr(), std::ifstream::binary);
	if (!fp)
		return;

	String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());

	Dictionary::Ptr update;

	if (Utility::Match("*.conf", file))
		update = config.UpdateV1;
	else
		update = config.UpdateV2;

	update->Set(file.SubStr(path.GetLength()), content);
}
Example #25
0
bool HttpRequest::Parse(StreamReadContext& src, bool may_wait)
{
	if (m_State != HttpRequestBody) {
		String line;
		StreamReadStatus srs = m_Stream->ReadLine(&line, src, may_wait);

		if (srs != StatusNewItem)
			return false;

		if (m_State == HttpRequestStart) {
			/* ignore trailing new-lines */
			if (line == "")
				return true;

			std::vector<String> tokens;
			boost::algorithm::split(tokens, line, boost::is_any_of(" "));
			Log(LogDebug, "HttpRequest")
			    << "line: " << line << ", tokens: " << tokens.size();
			if (tokens.size() != 3)
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid HTTP request"));
			RequestMethod = tokens[0];
			RequestUrl = new class Url(tokens[1]);

			if (tokens[2] == "HTTP/1.0")
				ProtocolVersion = HttpVersion10;
			else if (tokens[2] == "HTTP/1.1") {
				ProtocolVersion = HttpVersion11;
			} else
				BOOST_THROW_EXCEPTION(std::invalid_argument("Unsupported HTTP version"));

			m_State = HttpRequestHeaders;
		} else if (m_State == HttpRequestHeaders) {
			if (line == "") {
				m_State = HttpRequestBody;

				/* we're done if the request doesn't contain a message body */
				if (!Headers->Contains("content-length") && !Headers->Contains("transfer-encoding"))
					Complete = true;
				else
					m_Body = new FIFO();

				return true;

			} else {
				String::SizeType pos = line.FindFirstOf(":");
				if (pos == String::NPos)
					BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid HTTP request"));
				String key = line.SubStr(0, pos).ToLower().Trim();

				String value = line.SubStr(pos + 1).Trim();
				Headers->Set(key, value);

				if (key == "x-http-method-override")
					RequestMethod = value;
			}
		} else {
			VERIFY(!"Invalid HTTP request state.");
		}
	} else if (m_State == HttpRequestBody) {
		if (Headers->Get("transfer-encoding") == "chunked") {
			if (!m_ChunkContext)
				m_ChunkContext = boost::make_shared<ChunkReadContext>(src);

			char *data;
			size_t size;
			StreamReadStatus srs = HttpChunkedEncoding::ReadChunkFromStream(m_Stream, &data, &size, *m_ChunkContext.get(), may_wait);

			if (srs != StatusNewItem)
				return false;

			Log(LogInformation, "HttpRequest")
			    << "Read " << size << " bytes";

			m_Body->Write(data, size);

			delete [] data;

			if (size == 0) {
				Complete = true;
				return true;
			}
		} else {
			if (src.Eof)
				BOOST_THROW_EXCEPTION(std::invalid_argument("Unexpected EOF in HTTP body"));

			if (src.MustRead) {
				if (!src.FillFromStream(m_Stream, false)) {
					src.Eof = true;
					BOOST_THROW_EXCEPTION(std::invalid_argument("Unexpected EOF in HTTP body"));
				}

				src.MustRead = false;
			}

			size_t length_indicator = Convert::ToLong(Headers->Get("content-length"));

			if (src.Size < length_indicator) {
				src.MustRead = true;
				return false;
			}

			m_Body->Write(src.Buffer, length_indicator);
			src.DropData(length_indicator);
			Complete = true;
			return true;
		}
	}

	return true;
}
Example #26
0
/**
 * Prints a stacktrace to the specified stream.
 *
 * @param fp The stream.
 * @param ignoreFrames The number of stackframes to ignore (in addition to
 *		       the one this function is executing in).
 * @returns true if the stacktrace was printed, false otherwise.
 */
void StackTrace::Print(std::ostream& fp, int ignoreFrames) const
{
	fp << std::endl;

#ifndef _WIN32
#	ifdef HAVE_BACKTRACE_SYMBOLS
	char **messages = backtrace_symbols(m_Frames, m_Count);

	for (int i = ignoreFrames + 1; i < m_Count && messages != NULL; ++i) {
		String message = messages[i];

		char *sym_begin = strchr(messages[i], '(');

		if (sym_begin) {
			char *sym_end = strchr(sym_begin, '+');

			if (sym_end != NULL) {
				String sym = String(sym_begin + 1, sym_end);
				String sym_demangled = Utility::DemangleSymbolName(sym);

				if (sym_demangled.IsEmpty())
					sym_demangled = "<unknown function>";

				String path = String(messages[i], sym_begin);

				size_t slashp = path.RFind("/");

				if (slashp != String::NPos)
					path = path.SubStr(slashp + 1);

				message = path + ": " + sym_demangled + " (" + String(sym_end);

#ifdef HAVE_DLADDR
				Dl_info dli;

				if (dladdr(m_Frames[i], &dli) > 0) {
					uintptr_t rva = reinterpret_cast<uintptr_t>(m_Frames[i]) - reinterpret_cast<uintptr_t>(dli.dli_fbase);
					message += " (" + Addr2Line(dli.dli_fname, rva) + ")";
				}
#endif /* HAVE_DLADDR */
			}
		}

        	fp << "\t(" << i - ignoreFrames - 1 << ") " << message << std::endl;
	}

	free(messages);

	fp << std::endl;
#	else /* HAVE_BACKTRACE_SYMBOLS */
	fp << "(not available)" << std::endl;
#	endif /* HAVE_BACKTRACE_SYMBOLS */
#else /* _WIN32 */
	for (int i = ignoreFrames + 1; i < m_Count; i++) {
		char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
		PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
		pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
		pSymbol->MaxNameLen = MAX_SYM_NAME;

		DWORD64 dwAddress = (DWORD64)m_Frames[i];
		DWORD dwDisplacement;
		DWORD64 dwDisplacement64;

		IMAGEHLP_LINE64 line;
		line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

		fp << "\t(" << i - ignoreFrames - 1 << ") ";

		if (SymGetLineFromAddr64(GetCurrentProcess(), dwAddress, &dwDisplacement, &line))
			fp << line.FileName << ":" << line.LineNumber;
		else
			fp << "(unknown file/line)";

		fp << ": ";

		if (SymFromAddr(GetCurrentProcess(), dwAddress, &dwDisplacement64, pSymbol))
			fp << pSymbol->Name << "+" << dwDisplacement64;
		else
			fp << "(unknown function)";

		 fp << std::endl;
	}
#endif /* _WIN32 */
}
Example #27
0
Dictionary::Ptr LivestatusLogUtility::GetAttributes(const String& text)
{
	Dictionary::Ptr bag = new Dictionary();

	/*
	 * [1379025342] SERVICE NOTIFICATION: contactname;hostname;servicedesc;WARNING;true;foo output
	 */
	unsigned long time = atoi(text.SubStr(1, 11).CStr());

	Log(LogDebug, "LivestatusLogUtility")
		<< "Processing log line: '" << text << "'.";
	bag->Set("time", time);

	size_t colon = text.FindFirstOf(':');
	size_t colon_offset = colon - 13;

	String type = String(text.SubStr(13, colon_offset)).Trim();
	String options = String(text.SubStr(colon + 1)).Trim();

	bag->Set("type", type);
	bag->Set("options", options);

	std::vector<String> tokens = options.Split(";");

	/* set default values */
	bag->Set("class", LogEntryClassInfo);
	bag->Set("log_type", 0);
	bag->Set("state", 0);
	bag->Set("attempt", 0);
	bag->Set("message", text); /* used as 'message' in log table, and 'log_output' in statehist table */

	if (type.Contains("INITIAL HOST STATE") ||
		type.Contains("CURRENT HOST STATE") ||
		type.Contains("HOST ALERT")) {
		if (tokens.size() < 5)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("state", Host::StateFromString(tokens[1]));
		bag->Set("state_type", tokens[2]);
		bag->Set("attempt", atoi(tokens[3].CStr()));
		bag->Set("plugin_output", tokens[4]);

		if (type.Contains("INITIAL HOST STATE")) {
			bag->Set("class", LogEntryClassState);
			bag->Set("log_type", LogEntryTypeHostInitialState);
		}
		else if (type.Contains("CURRENT HOST STATE")) {
			bag->Set("class", LogEntryClassState);
			bag->Set("log_type", LogEntryTypeHostCurrentState);
		}
		else {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeHostAlert);
		}

		return bag;
	} else if (type.Contains("HOST DOWNTIME ALERT") ||  type.Contains("HOST FLAPPING ALERT")) {
		if (tokens.size() < 3)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("state_type", tokens[1]);
		bag->Set("comment", tokens[2]);

		if (type.Contains("HOST FLAPPING ALERT")) {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeHostFlapping);
		} else {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeHostDowntimeAlert);
		}

		return bag;
	} else if (type.Contains("INITIAL SERVICE STATE") ||
		type.Contains("CURRENT SERVICE STATE") ||
		type.Contains("SERVICE ALERT")) {
		if (tokens.size() < 6)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("service_description", tokens[1]);
		bag->Set("state", Service::StateFromString(tokens[2]));
		bag->Set("state_type", tokens[3]);
		bag->Set("attempt", atoi(tokens[4].CStr()));
		bag->Set("plugin_output", tokens[5]);

		if (type.Contains("INITIAL SERVICE STATE")) {
			bag->Set("class", LogEntryClassState);
			bag->Set("log_type", LogEntryTypeServiceInitialState);
		}
		else if (type.Contains("CURRENT SERVICE STATE")) {
			bag->Set("class", LogEntryClassState);
			bag->Set("log_type", LogEntryTypeServiceCurrentState);
		}
		else {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeServiceAlert);
		}

		return bag;
	} else if (type.Contains("SERVICE DOWNTIME ALERT") ||
		type.Contains("SERVICE FLAPPING ALERT")) {
		if (tokens.size() < 4)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("service_description", tokens[1]);
		bag->Set("state_type", tokens[2]);
		bag->Set("comment", tokens[3]);

		if (type.Contains("SERVICE FLAPPING ALERT")) {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeServiceFlapping);
		} else {
			bag->Set("class", LogEntryClassAlert);
			bag->Set("log_type", LogEntryTypeServiceDowntimeAlert);
		}

		return bag;
	} else if (type.Contains("TIMEPERIOD TRANSITION")) {
		if (tokens.size() < 4)
			return bag;

		bag->Set("class", LogEntryClassState);
		bag->Set("log_type", LogEntryTypeTimeperiodTransition);

		bag->Set("host_name", tokens[0]);
		bag->Set("service_description", tokens[1]);
		bag->Set("state_type", tokens[2]);
		bag->Set("comment", tokens[3]);
	} else if (type.Contains("HOST NOTIFICATION")) {
		if (tokens.size() < 6)
			return bag;

		bag->Set("contact_name", tokens[0]);
		bag->Set("host_name", tokens[1]);
		bag->Set("state_type", tokens[2].CStr());
		bag->Set("state", Service::StateFromString(tokens[3]));
		bag->Set("command_name", tokens[4]);
		bag->Set("plugin_output", tokens[5]);

		bag->Set("class", LogEntryClassNotification);
		bag->Set("log_type", LogEntryTypeHostNotification);

		return bag;
	} else if (type.Contains("SERVICE NOTIFICATION")) {
		if (tokens.size() < 7)
			return bag;

		bag->Set("contact_name", tokens[0]);
		bag->Set("host_name", tokens[1]);
		bag->Set("service_description", tokens[2]);
		bag->Set("state_type", tokens[3].CStr());
		bag->Set("state", Service::StateFromString(tokens[4]));
		bag->Set("command_name", tokens[5]);
		bag->Set("plugin_output", tokens[6]);

		bag->Set("class", LogEntryClassNotification);
		bag->Set("log_type", LogEntryTypeServiceNotification);

		return bag;
	} else if (type.Contains("PASSIVE HOST CHECK")) {
		if (tokens.size() < 3)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("state", Host::StateFromString(tokens[1]));
		bag->Set("plugin_output", tokens[2]);

		bag->Set("class", LogEntryClassPassive);

		return bag;
	} else if (type.Contains("PASSIVE SERVICE CHECK")) {
		if (tokens.size() < 4)
			return bag;

		bag->Set("host_name", tokens[0]);
		bag->Set("service_description", tokens[1]);
		bag->Set("state", Host::StateFromString(tokens[2]));
		bag->Set("plugin_output", tokens[3]);

		bag->Set("class", LogEntryClassPassive);

		return bag;
	} else if (type.Contains("EXTERNAL COMMAND")) {
		bag->Set("class", LogEntryClassCommand);
		/* string processing not implemented in 1.x */

		return bag;
	} else if (type.Contains("LOG VERSION")) {
		bag->Set("class", LogEntryClassProgram);
		bag->Set("log_type", LogEntryTypeVersion);

		return bag;
	} else if (type.Contains("logging initial states")) {
		bag->Set("class", LogEntryClassProgram);
		bag->Set("log_type", LogEntryTypeInitialStates);

		return bag;
	} else if (type.Contains("starting... (PID=")) {
		bag->Set("class", LogEntryClassProgram);
		bag->Set("log_type", LogEntryTypeProgramStarting);

		return bag;
	}
	/* program */
	else if (type.Contains("restarting...") ||
		type.Contains("shutting down...") ||
		type.Contains("Bailing out") ||
		type.Contains("active mode...") ||
		type.Contains("standby mode...")) {
		bag->Set("class", LogEntryClassProgram);

		return bag;
	}

	return bag;
}
Example #28
0
void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc,
    po::options_description *hiddenDesc,
    ArgumentCompletionCallback globalArgCompletionCallback,
    bool autocomplete, int autoindex)
{
	boost::mutex::scoped_lock lock(GetRegistryMutex());

	typedef std::map<std::vector<String>, CLICommand::Ptr>::value_type CLIKeyValue;

	std::vector<String> best_match;
	int arg_begin = 0;
	CLICommand::Ptr command;

	BOOST_FOREACH(const CLIKeyValue& kv, GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		arg_begin = 0;

		for (int i = 0, k = 1; i < vname.size() && k < argc; i++, k++) {
			if (strcmp(argv[k], "--no-stack-rlimit") == 0 || strcmp(argv[k], "--autocomplete") == 0 || strcmp(argv[k], "--scm") == 0) {
				i--;
				arg_begin++;
				continue;
			}

			if (autocomplete && i >= autoindex - 1)
				break;

			if (vname[i] != argv[k])
				break;

			if (i >= best_match.size()) {
				best_match.push_back(vname[i]);
			}

			if (i == vname.size() - 1) {
				command = kv.second;
				break;
			}
		}
	}

	String aword;

	if (autocomplete) {
		if (autoindex < argc)
			aword = argv[autoindex];

		if (autoindex - 1 > best_match.size() && !command)
			return;
	} else
		std::cout << "Supported commands: " << std::endl;

	BOOST_FOREACH(const CLIKeyValue& kv, GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		if (vname.size() < best_match.size())
			continue;

		bool match = true;

		for (int i = 0; i < best_match.size(); i++) {
			if (vname[i] != best_match[i]) {
				match = false;
				break;
			}
		}

		if (!match)
			continue;

		if (autocomplete) {
			String cname;

			if (autoindex - 1 < vname.size()) {
				cname = vname[autoindex - 1];

				if (cname.Find(aword) == 0)
					std::cout << cname << "\n";
			}
		} else
			std::cout << "  * " << boost::algorithm::join(vname, " ") << " (" << kv.second->GetShortDescription() << ")" << std::endl;
	}

	if (!autocomplete)
		std::cout << std::endl;

	if (command && autocomplete) {
		String aname, prefix, pword;
		const po::option_description *odesc;
	
		if (autoindex - 2 >= 0 && strcmp(argv[autoindex - 1], "=") == 0 && strstr(argv[autoindex - 2], "--") == argv[autoindex - 2]) {
			aname = argv[autoindex - 2] + 2;
			pword = aword;
		} else if (autoindex - 1 >= 0 && argv[autoindex - 1][0] == '-' && argv[autoindex - 1][1] == '-') {
			aname = argv[autoindex - 1] + 2;
			pword = aword;
			
			if (pword == "=")
				pword = "";
		} else if (aword.GetLength() > 1 && aword[0] == '-' && aword[1] != '-') {
			aname = aword.SubStr(1, 1);
			prefix = aword.SubStr(0, 2);
			pword = aword.SubStr(2);
		} else {
			goto complete_option;
		}

		odesc = visibleDesc->find_nothrow(aname, false);

		if (!odesc)
			return;

		if (odesc->semantic()->min_tokens() == 0)
			goto complete_option;

		BOOST_FOREACH(const String& suggestion, globalArgCompletionCallback(aname, pword)) {
			std::cout << prefix << suggestion << "\n";
		}
int TroubleshootCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
{
#ifdef _WIN32 //Dislikes ':' in filenames
	String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-"
		+ Utility::FormatDateTime("%Y-%m-%d_%H-%M-%S", Utility::GetTime()) + ".log";
#else
	String path = Application::GetLocalStateDir() + "/log/icinga2/troubleshooting-"
		+ Utility::FormatDateTime("%Y-%m-%d_%H:%M:%S", Utility::GetTime()) + ".log";
#endif /*_WIN32*/

	InfoLog *log;
	Logger::SetConsoleLogSeverity(LogWarning);

	if (vm.count("output"))
		path = vm["output"].as<std::string>();

	if (vm.count("console")) {
		log = new InfoLog("", true);
	} else {
		log = new InfoLog(path, false);
		if (!log->GetStreamHealth()) {
			Log(LogCritical, "troubleshoot", "Failed to open file to write: " + path);
			delete log;
			return 3;
		}
	}

	String appName = Utility::BaseName(Application::GetArgV()[0]);
	double goTime = Utility::GetTime();

	InfoLogLine(*log)
		<< appName << " -- Troubleshooting help:\n"
		<< "Should you run into problems with Icinga please add this file to your help request\n"
		<< "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n";

	InfoLogLine(*log, Console_ForegroundMagenta)
		<< std::string(52, '=') << "\n\n";

	if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
		appName = appName.SubStr(3, appName.GetLength() - 3);

	Dictionary::Ptr logs = new Dictionary;

	if (!GeneralInfo(*log, vm) ||
		!FeatureInfo(*log, vm) ||
		!ObjectInfo(*log, vm, logs, path) ||
		!ReportInfo(*log, vm, logs) ||
		!ConfigInfo(*log, vm)) {
		InfoLogLine(*log, 0, LogCritical)
			<< "Could not recover from critical failure, exiting.\n";

		delete log;
		return 3;
	}

	double endTime = Utility::GetTime();

	InfoLogLine(*log, Console_ForegroundMagenta)
		<< std::string(52, '=') << '\n';
	InfoLogLine(*log, Console_ForegroundGreen)
		<< "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
		<< "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n";

	if (!vm.count("console")) {
		std::cout << "Started collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", goTime) << "\n"
			<< "Finished collection at " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S", endTime)
			<< "\nTook " << Convert::ToString(endTime - goTime) << " seconds\n\n";

		std::cout << "General log file: '" << path << "'\n";

		if (vm.count("include-vars"))
			std::cout << "Vars log file: '" << path << "-vars'\n";
		if (vm.count("include-objects"))
			std::cout << "Objects log file: '" << path << "-objects'\n";

		std::cout << "\nPlease compress the files before uploading them,, for example:\n"
			<< "  # tar czf troubleshoot.tar.gz " << path << "*\n";
	}

	delete log;
	return 0;
}
Example #30
0
String Texture2D::Reload(const String& filePath, SupportedFileTypes fileType)
{
    if (fileType == UNKNOWN)
    {
        if (filePath.GetSize() < 4)
            return "File-name was too short to infer a type";

        String extension = filePath.SubStr(filePath.GetSize() - 4, 4);

        if (extension == ".png")
            fileType = PNG;
        else if (extension == ".bmp")
            fileType = BMP;
        else
            return "Couldn't infer type from file name";
    }

    switch (fileType)
    {
        case BMP: {

            unsigned long width;
            long height;
            unsigned char *reds,
                          *greens,
                          *blues;
            if (bmp_read(filePath.CStr(), &width, &height, &reds, &greens, &blues))
            {
                return "Error reading the BMP file";
            }

            Resize(width, height);

            //Convert to texture data.
            float invMaxVal = 1.0f / (float)std::numeric_limits<unsigned char>::max();
            for (long y = 0; y < height; ++y)
            {
                for (unsigned long x = 0; x < width; ++x)
                {
                    long i = x + (y * width);
                    Vector3f col((float)reds[i] * invMaxVal,
                                 (float)greens[i] * invMaxVal,
                                 (float)blues[i] * invMaxVal);
                    SetColor(x, y, col);
                }
            }
            } break;

        case PNG: {

            std::vector<unsigned char> bytes;
            unsigned width, height;
            unsigned errCode = lodepng::decode(bytes, width, height, filePath.CStr());
            if (errCode != 0)
            {
                return String("Error reading the PNG file: ") + lodepng_error_text(errCode);
            }

            Resize(width, height);

            //Convert to texture data.
            float invMaxVal = 1.0f / (float)std::numeric_limits<unsigned char>::max();
            for (size_t y = 0; y < height; ++y)
            {
                size_t indexOffset = y * width * 4;

                for (size_t x = 0; x < width; ++x)
                {
                    size_t indexOffset2 = indexOffset + (x * 4);

                    SetColor(x, height - y - 1,
                             Vector3f((float)bytes[indexOffset2] * invMaxVal,
                                      (float)bytes[indexOffset2 + 1] * invMaxVal,
                                      (float)bytes[indexOffset2 + 2] * invMaxVal));
                }
            }
            } break;

        default:
            return String("Unexpected file type enum value: ") + String(fileType);
    }

    return "";
}