Example #1
0
std::vector<String> icinga::GetBashCompletionSuggestions(const String& type, const String& word)
{
	std::vector<String> result;

#ifndef _WIN32
	String bashArg = "compgen -A " + Utility::EscapeShellArg(type) + " " + Utility::EscapeShellArg(word);
	String cmd = "bash -c " + Utility::EscapeShellArg(bashArg);

	FILE *fp = popen(cmd.CStr(), "r");

	char line[4096];
	while (fgets(line, sizeof(line), fp)) {
		String wline = line;
		boost::algorithm::trim_right_if(wline, boost::is_any_of("\r\n"));
		result.push_back(wline);
	}
	fclose(fp);
	
	/* Append a slash if there's only one suggestion and it's a directory */
	if ((type == "file" || type == "directory") && result.size() == 1) {
		String path = result[0];

		struct stat statbuf;
		if (lstat(path.CStr(), &statbuf) >= 0) {
			if (S_ISDIR(statbuf.st_mode)) {
				result.clear(),
				result.push_back(path + "/");
			}
		}
	}
#endif /* _WIN32 */

	return result;
}
Example #2
0
void HttpRequest::FinishHeaders()
{
	if (m_State == HttpRequestStart) {
		String rqline = RequestMethod + " " + RequestUrl->Format(true) + " HTTP/1." + (ProtocolVersion == HttpVersion10 ? "0" : "1") + "\r\n";
		m_Stream->Write(rqline.CStr(), rqline.GetLength());
		m_State = HttpRequestHeaders;
	}

	if (m_State == HttpRequestHeaders) {
		AddHeader("User-Agent", "Icinga/" + Application::GetAppVersion());

		if (ProtocolVersion == HttpVersion11) {
			AddHeader("Transfer-Encoding", "chunked");
			if (!Headers->Contains("Host"))
				AddHeader("Host", RequestUrl->GetHost() + ":" + RequestUrl->GetPort());
		}

		ObjectLock olock(Headers);
		for (const Dictionary::Pair& kv : Headers)
		{
			String header = kv.first + ": " + kv.second + "\r\n";
			m_Stream->Write(header.CStr(), header.GetLength());
		}

		m_Stream->Write("\r\n", 2);

		m_State = HttpRequestBody;
	}
}
Example #3
0
int PkiUtility::SignCsr(const String& csrfile, const String& certfile)
{
	char errbuf[120];

	InitializeOpenSSL();

	BIO *csrbio = BIO_new_file(csrfile.CStr(), "r");
	X509_REQ *req = PEM_read_bio_X509_REQ(csrbio, NULL, NULL, NULL);

	if (!req) {
		Log(LogCritical, "SSL")
		    << "Could not read X509 certificate request from '" << csrfile << "': " << ERR_peek_error() << ", \"" << ERR_error_string(ERR_peek_error(), errbuf) << "\"";
		return 1;
	}

	BIO_free(csrbio);

	boost::shared_ptr<X509> cert = CreateCertIcingaCA(X509_REQ_get_pubkey(req), X509_REQ_get_subject_name(req));

	X509_REQ_free(req);

	std::ofstream fpcert;
	fpcert.open(certfile.CStr());

	if (!fpcert) {
		Log(LogCritical, "cli")
		    << "Failed to open certificate file '" << certfile << "' for output";
		return 1;
	}

	fpcert << CertificateToString(cert);
	fpcert.close();

	return 0;
}
Example #4
0
String ScriptUtils::MsiGetComponentPathShim(const String& component)
{
#ifdef _WIN32
	TCHAR productCode[39];
	if (MsiGetProductCode(component.CStr(), productCode) != ERROR_SUCCESS)
		return "";
	TCHAR path[2048];
	DWORD szPath = sizeof(path);
	path[0] = '\0';
	MsiGetComponentPath(productCode, component.CStr(), path, &szPath);
	return path;
#else /* _WIN32 */
	return String();
#endif /* _WIN32 */
}
Example #5
0
void UnixSocket::Bind(const String& path)
{
	unlink(path.CStr());

	sockaddr_un s_un;
	memset(&s_un, 0, sizeof(s_un));
	s_un.sun_family = AF_UNIX;
	strncpy(s_un.sun_path, path.CStr(), sizeof(s_un.sun_path));
	s_un.sun_path[sizeof(s_un.sun_path) - 1] = '\0';

	if (bind(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0) {
		BOOST_THROW_EXCEPTION(posix_error()
			<< boost::errinfo_api_function("bind")
			<< boost::errinfo_errno(errno));
	}
}
Example #6
0
String Base64::Decode(const String& input)
{
	BIO *biomem = BIO_new_mem_buf(
		const_cast<char*>(input.CStr()), input.GetLength());
	BIO *bio64 = BIO_new(BIO_f_base64());
	BIO_push(bio64, biomem);
	BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);

	auto *outbuf = new char[input.GetLength()];

	size_t len = 0;
	int rc;

	while ((rc = BIO_read(bio64, outbuf + len, input.GetLength() - len)) > 0)
		len += rc;

	String ret = String(outbuf, outbuf + len);
	BIO_free_all(bio64);
	delete [] outbuf;

	if (ret.IsEmpty() && !input.IsEmpty())
		throw std::invalid_argument("Not a valid base64 string");

	return ret;
}
Example #7
0
const char *posix_error::what(void) const throw()
{
	if (!m_Message) {
		std::ostringstream msgbuf;

		const char * const *func = boost::get_error_info<boost::errinfo_api_function>(*this);

		if (func)
			msgbuf << "Function call '" << *func << "'";
		else
			msgbuf << "Function call";

		const std::string *fname = boost::get_error_info<boost::errinfo_file_name>(*this);

		if (fname)
			msgbuf << " for file '" << *fname << "'";

		msgbuf << " failed";

		const int *errnum = boost::get_error_info<boost::errinfo_errno>(*this);

		if (errnum)
			msgbuf << " with error code " << *errnum << ", '" << strerror(*errnum) << "'";

		String str = msgbuf.str();
		m_Message = strdup(str.CStr());
	}

	return m_Message;
}
Example #8
0
void DynamicObject::DumpObjects(const String& filename, int attributeTypes)
{
	Log(LogInformation, "DynamicObject", "Dumping program state to file '" + filename + "'");

	String tempFilename = filename + ".tmp";

	std::fstream fp;
	fp.open(tempFilename.CStr(), std::ios_base::out);

	if (!fp)
		BOOST_THROW_EXCEPTION(std::runtime_error("Could not open '" + filename + "' file"));

	StdioStream::Ptr sfp = make_shared<StdioStream>(&fp, false);

	BOOST_FOREACH(const DynamicType::Ptr& type, DynamicType::GetTypes()) {
		BOOST_FOREACH(const DynamicObject::Ptr& object, type->GetObjects()) {
			Dictionary::Ptr persistentObject = make_shared<Dictionary>();

			persistentObject->Set("type", type->GetName());
			persistentObject->Set("name", object->GetName());

			Dictionary::Ptr update = Serialize(object, attributeTypes);

			if (!update)
				continue;

			persistentObject->Set("update", update);

			String json = JsonSerialize(persistentObject);

			NetString::WriteStringToStream(sfp, json);
		}
	}
void ApiListener::ApiTimerHandler(void)
{
	double now = Utility::GetTime();

	std::vector<int> files;
	Utility::Glob(GetApiDir() + "log/*", boost::bind(&ApiListener::LogGlobHandler, boost::ref(files), _1), GlobFile);
	std::sort(files.begin(), files.end());

	BOOST_FOREACH(int ts, files) {
		bool need = false;

		BOOST_FOREACH(const Endpoint::Ptr& endpoint, ConfigType::GetObjectsByType<Endpoint>()) {
			if (endpoint == GetLocalEndpoint())
				continue;

			if (endpoint->GetLogDuration() >= 0 && ts < now - endpoint->GetLogDuration())
				continue;

			if (ts > endpoint->GetLocalLogPosition()) {
				need = true;
				break;
			}
		}

		if (!need) {
			String path = GetApiDir() + "log/" + Convert::ToString(ts);
			Log(LogNotice, "ApiListener")
			    << "Removing old log file: " << path;
			(void)unlink(path.CStr());
		}
	}
Example #10
0
    void SoundFX::Play(const String& name, int group)
    {
        if (audioDevice == nullptr)
            return;

        SoundCollection* items = FindSounds(group);
        if (items == nullptr)
        {
            soundGroups.push_back(group);
            sounds.push_back(SoundCollection());
            items = &sounds.back();
        }

        if (ISoundEngine* engine = audioDevice->GetEngine())
        {
            if (ISound* sound = engine->play2D(name.CStr(), false, true))
            {
                if (mute)
                    sound->setVolume(0.0f);
                else
                    sound->setVolume(volume);
                sound->setSoundStopEventReceiver(eventListener, reinterpret_cast<void*>(group));
                sound->setIsPaused(false);
                items->push_back(sound);
            }
        }
    }
Example #11
0
void HttpUtility::SendJsonBody(HttpResponse& response, const Value& val)
{
	response.AddHeader("Content-Type", "application/json");

	String body = JsonEncode(val);
	response.WriteBody(body.CStr(), body.GetLength());
}
Example #12
0
bool ApiListener::UpdateConfigDir(const Dictionary::Ptr& oldConfig, const Dictionary::Ptr& newConfig, const String& configDir)
{
	bool configChange = false;

	if (oldConfig->Contains(".timestamp") && newConfig->Contains(".timestamp")) {
		double oldTS = Convert::ToDouble(oldConfig->Get(".timestamp"));
		double newTS = Convert::ToDouble(newConfig->Get(".timestamp"));

		/* skip update if our config is newer */
		if (oldTS <= newTS)
			return false;
	}

	BOOST_FOREACH(const Dictionary::Pair& kv, newConfig) {
		if (oldConfig->Get(kv.first) != kv.second) {
			configChange = true;

			String path = configDir + "/" + kv.first;
			Log(LogInformation, "ApiListener")
			    << "Updating configuration file: " << path;

			//pass the directory and generate a dir tree, if not existing already
			Utility::MkDirP(Utility::DirName(path), 0755);
			std::ofstream fp(path.CStr(), std::ofstream::out | std::ostream::trunc);
			fp << kv.second;
			fp.close();
		}
	}

	BOOST_FOREACH(const Dictionary::Pair& kv, oldConfig) {
		if (!newConfig->Contains(kv.first)) {
			configChange = true;

			String path = configDir + "/" + kv.first;
			(void) unlink(path.CStr());
		}
	}

	String tsPath = configDir + "/.timestamp";
	if (!Utility::PathExists(tsPath)) {
		std::ofstream fp(tsPath.CStr(), std::ofstream::out | std::ostream::trunc);
		fp << Utility::GetTime();
		fp.close();
	}

	return configChange;
}
Example #13
0
static Array::Ptr StringSplit(const String& delims)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	String self = vframe->Self;
	std::vector<String> tokens = self.Split(delims.CStr());

	return Array::FromVector(tokens);
}
Example #14
0
/**
 * Returns the directory component of a path. See dirname(3) for details.
 *
 * @param path The full path.
 * @returns The directory.
 */
String Utility::DirName(const String& path)
{
	char *dir;

#ifdef _WIN32
	String dupPath = path;

	/* PathRemoveFileSpec doesn't properly handle forward slashes. */
	BOOST_FOREACH(char& ch, dupPath) {
		if (ch == '/')
			ch = '\\';
	}

	dir = strdup(dupPath.CStr());
#else /* _WIN32 */
	dir = strdup(path.CStr());
#endif /* _WIN32 */

	if (dir == NULL)
		BOOST_THROW_EXCEPTION(std::bad_alloc());

	String result;

#ifndef _WIN32
	result = dirname(dir);
#else /* _WIN32 */
	if (!PathRemoveFileSpec(dir)) {
		free(dir);

		BOOST_THROW_EXCEPTION(win32_error()
		    << boost::errinfo_api_function("PathRemoveFileSpec")
		    << errinfo_win32_error(GetLastError()));
	}

	result = dir;

	if (result.IsEmpty())
		result = ".";
#endif /* _WIN32 */

	free(dir);

	return result;
}
Example #15
0
    MPQStream::MPQStream(MPQ* mpq, const String& path)
        : handle(nullptr)
    {
        if (mpq == nullptr || mpq->GetHandle() == nullptr)
            return;

        HANDLE internalHandle = NULL;
        if (SFileOpenFileEx(mpq->GetHandle(), path.CStr(), SFILE_OPEN_FROM_MPQ, &internalHandle))
            handle = internalHandle;
    }
Example #16
0
void HttpResponse::AddHeader(const String& key, const String& value)
{
	if (m_State != HttpResponseHeaders) {
		Log(LogWarning, "HttpResponse", "Tried to add header after headers had already been sent.");
		return;
	}

	String header = key + ": " + value + "\r\n";
	m_Stream->Write(header.CStr(), header.GetLength());
}
Example #17
0
/**
 * Loads the specified library.
 *
 * @param name The name of the library.
 */
Library::Library(const String& name)
{
	String path;
#if defined(_WIN32)
	path = name + ".dll";
#elif defined(__APPLE__)
	path = "lib" + name + "." + Application::GetAppSpecVersion() + ".dylib";
#else /* __APPLE__ */
	path = "lib" + name + ".so." + Application::GetAppSpecVersion();
#endif /* _WIN32 */

	Log(LogNotice, "Library")
		<< "Loading library '" << path << "'";

#ifdef _WIN32
	HMODULE hModule = LoadLibrary(path.CStr());

	if (!hModule) {
		BOOST_THROW_EXCEPTION(win32_error()
			<< boost::errinfo_api_function("LoadLibrary")
			<< errinfo_win32_error(GetLastError())
			<< boost::errinfo_file_name(path));
	}
#else /* _WIN32 */
	void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL);

	if (!hModule) {
		BOOST_THROW_EXCEPTION(std::runtime_error("Could not load library '" + path + "': " + dlerror()));
	}
#endif /* _WIN32 */

	Loader::ExecuteDeferredInitializers();

	m_Handle.reset(new LibraryHandle(hModule), [](LibraryHandle *handle) {
#ifdef _WIN32
		FreeLibrary(*handle);
#else /* _WIN32 */
		dlclose(*handle);
#endif /* _WIN32 */
	});
}
Example #18
0
HMODULE
#else /* _WIN32 */
void *
#endif /* _WIN32 */
Utility::LoadExtensionLibrary(const String& library)
{
	String path;
#if defined(_WIN32)
	path = library + ".dll";
#elif defined(__APPLE__)
	path = "lib" + library + ".dylib";
#else /* __APPLE__ */
	path = "lib" + library + ".so";
#endif /* _WIN32 */

	Log(LogInformation, "Utility")
	    << "Loading library '" << path << "'";

#ifdef _WIN32
	HMODULE hModule = LoadLibrary(path.CStr());

	if (hModule == NULL) {
		BOOST_THROW_EXCEPTION(win32_error()
		    << boost::errinfo_api_function("LoadLibrary")
		    << errinfo_win32_error(GetLastError())
		    << boost::errinfo_file_name(path));
	}
#else /* _WIN32 */
	void *hModule = dlopen(path.CStr(), RTLD_NOW | RTLD_GLOBAL);

	if (hModule == NULL) {
		BOOST_THROW_EXCEPTION(std::runtime_error("Could not load library '" + path + "': " + dlerror()));
	}
#endif /* _WIN32 */

	ExecuteDeferredInitializers();


	return hModule;
}
Example #19
0
String PkiUtility::GetCertificateInformation(const boost::shared_ptr<X509>& cert) {
	BIO *out = BIO_new(BIO_s_mem());
	String pre;

	pre = "\n Subject:     ";
	BIO_write(out, pre.CStr(), pre.GetLength());
	X509_NAME_print_ex(out, X509_get_subject_name(cert.get()), 0, XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);

	pre = "\n Issuer:      ";
	BIO_write(out, pre.CStr(), pre.GetLength());
	X509_NAME_print_ex(out, X509_get_issuer_name(cert.get()), 0, XN_FLAG_ONELINE & ~ASN1_STRFLGS_ESC_MSB);

	pre = "\n Valid From:  ";
	BIO_write(out, pre.CStr(), pre.GetLength());
	ASN1_TIME_print(out, X509_get_notBefore(cert.get()));

	pre = "\n Valid Until: ";
	BIO_write(out, pre.CStr(), pre.GetLength());
	ASN1_TIME_print(out, X509_get_notAfter(cert.get()));

	pre = "\n Fingerprint: ";
	BIO_write(out, pre.CStr(), pre.GetLength());
	unsigned char md[EVP_MAX_MD_SIZE];
	unsigned int diglen;
	X509_digest(cert.get(), EVP_sha1(), md, &diglen);

	char *data;
	long length = BIO_get_mem_data(out, &data);

	std::stringstream info;
	info << String(data, data + length);
	for (unsigned int i = 0; i < diglen; i++) {
		info << std::setfill('0') << std::setw(2) << std::uppercase
		    << std::hex << static_cast<int>(md[i]) << ' ';
	}
	info << '\n';

	return info.str();
}
Example #20
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());
	if (!fp)
		return;

	String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
	config->Set(file.SubStr(path.GetLength()), content);
}
Example #21
0
/**
 * Compiles a file.
 *
 * @param path The path.
 * @returns Configuration items.
 */
void ConfigCompiler::CompileFile(const String& path)
{
	CONTEXT("Compiling configuration file '" + path + "'");

	std::ifstream stream;
	stream.open(path.CStr(), std::ifstream::in);

	if (!stream)
		BOOST_THROW_EXCEPTION(std::invalid_argument("Could not open config file: " + path));

	Log(LogInformation, "config", "Compiling config file: " + path);

	return CompileStream(path, &stream);
}
Example #22
0
void UnixSocket::Connect(const String& path)
{
	sockaddr_un s_un;
	memset(&s_un, 0, sizeof(s_un));
	s_un.sun_family = AF_UNIX;
	strncpy(s_un.sun_path, path.CStr(), sizeof(s_un.sun_path));
	s_un.sun_path[sizeof(s_un.sun_path) - 1] = '\0';

	if (connect(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0 && errno != EINPROGRESS) {
		BOOST_THROW_EXCEPTION(posix_error()
			<< boost::errinfo_api_function("connect")
			<< boost::errinfo_errno(errno));
	}
}
Example #23
0
/**
 * Demangles a symbol name.
 *
 * @param sym The symbol name.
 * @returns A human-readable version of the symbol name.
 */
String Utility::DemangleSymbolName(const String& sym)
{
	String result = sym;

#ifdef HAVE_CXXABI_H
	int status;
	char *realname = abi::__cxa_demangle(sym.CStr(), 0, 0, &status);

	if (realname != NULL) {
		result = String(realname);
		free(realname);
	}
#elif defined(_MSC_VER) /* HAVE_CXXABI_H */
	CHAR output[256];

	if (UnDecorateSymbolName(sym.CStr(), output, sizeof(output), UNDNAME_COMPLETE) > 0)
		result = output;
#else /* _MSC_VER */
	/* We're pretty much out of options here. */
#endif /* _MSC_VER */

	return result;
}
/**
 * Retrieves the full path of the executable.
 *
 * @param argv0 The first command-line argument.
 * @returns The path.
 */
String Application::GetExePath(const String& argv0)
{
	String executablePath;

#ifndef _WIN32
	char buffer[MAXPATHLEN];
	if (getcwd(buffer, sizeof(buffer)) == NULL) {
		BOOST_THROW_EXCEPTION(posix_error()
		    << boost::errinfo_api_function("getcwd")
		    << boost::errinfo_errno(errno));
	}

	String workingDirectory = buffer;

	if (argv0[0] != '/')
		executablePath = workingDirectory + "/" + argv0;
	else
		executablePath = argv0;

	bool foundSlash = false;
	for (size_t i = 0; i < argv0.GetLength(); i++) {
		if (argv0[i] == '/') {
			foundSlash = true;
			break;
		}
	}

	if (!foundSlash) {
		const char *pathEnv = getenv("PATH");
		if (pathEnv != NULL) {
			std::vector<String> paths;
			boost::algorithm::split(paths, pathEnv, boost::is_any_of(":"));

			bool foundPath = false;
			BOOST_FOREACH(String& path, paths) {
				String pathTest = path + "/" + argv0;

				if (access(pathTest.CStr(), X_OK) == 0) {
					executablePath = pathTest;
					foundPath = true;
					break;
				}
			}

			if (!foundPath) {
				executablePath.Clear();
				BOOST_THROW_EXCEPTION(std::runtime_error("Could not determine executable path."));
			}
		}
Example #25
0
/**
 * The entry point for the "object list" CLI command.
 *
 * @returns An exit status.
 */
int ObjectListCommand::Run(const boost::program_options::variables_map& vm, const std::vector<std::string>& ap) const
{
	String objectfile = Application::GetObjectsPath();

	if (!Utility::PathExists(objectfile)) {
		Log(LogCritical, "cli")
		    << "Cannot open objects file '" << Application::GetObjectsPath() << "'.";
		Log(LogCritical, "cli", "Run 'icinga2 daemon -C' to validate config and generate the cache file.");
		return 1;
	}

	std::fstream fp;
	fp.open(objectfile.CStr(), std::ios_base::in);

	StdioStream::Ptr sfp = new StdioStream(&fp, false);
	unsigned long objects_count = 0;
	std::map<String, int> type_count;

	String message;
	String name_filter, type_filter;

	if (vm.count("name"))
		name_filter = vm["name"].as<std::string>();
	if (vm.count("type"))
		type_filter = vm["type"].as<std::string>();

	bool first = true;

	while (NetString::ReadStringFromStream(sfp, &message)) {
		PrintObject(std::cout, first, message, type_count, name_filter, type_filter);
		objects_count++;
	}

	sfp->Close();
	fp.close();

	if (vm.count("count")) {
		if (!first)
			std::cout << "\n";

		PrintTypeCounts(std::cout, type_count);
		std::cout << "\n";
	}

	Log(LogNotice, "cli")
	    << "Parsed " << objects_count << " objects.";

	return 0;
}
Example #26
0
String Base64::Encode(const String& input)
{
	BIO *biomem = BIO_new(BIO_s_mem());
	BIO *bio64 = BIO_new(BIO_f_base64());
	BIO_push(bio64, biomem);
	BIO_set_flags(bio64, BIO_FLAGS_BASE64_NO_NL);
	BIO_write(bio64, input.CStr(), input.GetLength());
	(void) BIO_flush(bio64);

	char *outbuf;
	long len = BIO_get_mem_data(biomem, &outbuf);

	String ret = String(outbuf, outbuf + len);
	BIO_free_all(bio64);

	return ret;
}
Example #27
0
void FileLogger::ReopenLogFile()
{
	auto *stream = new std::ofstream();

	String path = GetPath();

	try {
		stream->open(path.CStr(), std::fstream::app | std::fstream::out);

		if (!stream->good())
			BOOST_THROW_EXCEPTION(std::runtime_error("Could not open logfile '" + path + "'"));
	} catch (...) {
		delete stream;
		throw;
	}

	BindStream(stream, true);
}
Example #28
0
int PkiUtility::WriteCert(const boost::shared_ptr<X509>& cert, const String& trustedfile)
{
	std::ofstream fpcert;
	fpcert.open(trustedfile.CStr());
	fpcert << CertificateToString(cert);
	fpcert.close();

	if (fpcert.fail()) {
		Log(LogCritical, "pki")
		    << "Could not write certificate to file '" << trustedfile << "'.";
		return 1;
	}

	Log(LogInformation, "pki")
	    << "Writing trusted certificate to file '" << trustedfile << "'.";

	return 0;
}
Example #29
0
/**
 * Returns the file component of a path. See basename(3) for details.
 *
 * @param path The full path.
 * @returns The filename.
 */
String Utility::BaseName(const String& path)
{
	char *dir = strdup(path.CStr());
	String result;

	if (dir == NULL)
		BOOST_THROW_EXCEPTION(std::bad_alloc());

#ifndef _WIN32
	result = basename(dir);
#else /* _WIN32 */
	result = PathFindFileName(dir);
#endif /* _WIN32 */

	free(dir);

	return result;
}
Example #30
0
void HttpResponse::SetStatus(int code, const String& message)
{
	ASSERT(code >= 100 && code <= 599);
	ASSERT(!message.IsEmpty());

	if (m_State != HttpResponseStart) {
		Log(LogWarning, "HttpResponse", "Tried to set Http response status after headers had already been sent.");
		return;
	}

	String status = "HTTP/";

	if (m_Request.ProtocolVersion == HttpVersion10)
		status += "1.0";
	else
		status += "1.1";

	status += " " + Convert::ToString(code) + " " + message + "\r\n";

	m_Stream->Write(status.CStr(), status.GetLength());

	m_State = HttpResponseHeaders;
}