示例#1
0
/**
 * Opens suitable DLLs on a given path.
 *  @param libpath A Poco::File object pointing to a directory where the
 * libraries are.
 *  @param loadingBehaviour Control how libraries are searched for
 *  @param excludes If not empty then each string is considered as a substring
 * to search within each library to be opened. If the substring is found then
 * the library is not opened.
 *  @return The number of libraries opened.
 */
int LibraryManagerImpl::openLibraries(
    const Poco::File &libpath,
    LibraryManagerImpl::LoadLibraries loadingBehaviour,
    const std::vector<std::string> &excludes) {
  int libCount(0);
  if (libpath.exists() && libpath.isDirectory()) {
    // Iterate over the available files
    Poco::DirectoryIterator end_itr;
    for (Poco::DirectoryIterator itr(libpath); itr != end_itr; ++itr) {
      const Poco::File &item = *itr;
      if (item.isFile()) {
        if (shouldBeLoaded(itr.path().getFileName(), excludes))
          libCount += openLibrary(itr.path(), itr.path().getFileName());
        else
          continue;
      } else if (loadingBehaviour == LoadLibraries::Recursive) {
        // it must be a directory
        libCount += openLibraries(item, LoadLibraries::Recursive, excludes);
      }
    }
  } else {
    g_log.error("In OpenAllLibraries: " + libpath.path() +
                " must be a directory.");
  }
  return libCount;
}
示例#2
0
    int CStatsUtil::DoExportGameScripts()
    {
        //Validate output + input paths
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
            outpath = inpath.absolute().makeParent().append(DefExportScriptsDir);
        else
            outpath = Poco::Path(m_outputPath).makeAbsolute();

        Poco::File fTestOut = outpath;
        if( ! fTestOut.exists() )
        {
            cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
            fTestOut.createDirectory();
        }
        else if( ! fTestOut.isDirectory() )
            throw runtime_error("CStatsUtil::DoExportGameScripts(): Output path is not a directory!");

        //Setup the script handler
        GameScripts scripts( inpath.absolute().toString() );

        //Convert to XML
        scripts.ExportScriptsToXML( outpath.toString() );

        return 0;
    }
示例#3
0
void GoPlusContext::initFileSystem()
{
   //std::string confDir = Poco::Util::Application::instance().config().getString("application.dir") + "conf";
   //std::string dataDir = Poco::Util::Application::instance().config().getString("application.dir") + "data";
   //std::string logDir = Poco::Util::Application::instance().config().getString("application.dir") + "log";
   //std::string tmpDir = Poco::Util::Application::instance().config().getString("application.dir") + "tmp";
   std::string confDir = "conf";
   std::string dataDir = "data";
   std::string logDir = "log";
   std::string tmpDir = "tmp";

   Poco::File file; 

   file = confDir;
   file.createDirectories();

   file = dataDir;
   file.createDirectories();

   file = logDir;
   file.createDirectories();

   file = tmpDir;
   file.createDirectories();
}
示例#4
0
/** Opens all suitable DLLs on a given path.
*  @param filePath :: The filepath to the directory where the libraries are.
*  @param isRecursive :: Whether to search subdirectories.
*  @return The number of libraries opened.
*/
int LibraryManagerImpl::OpenAllLibraries(const std::string &filePath,
                                         bool isRecursive) {
  g_log.debug() << "Opening all libraries in " << filePath << "\n";
  int libCount = 0;
  // validate inputs
  Poco::File libPath;
  try {
    libPath = Poco::File(filePath);
  } catch (...) {
    return libCount;
  }
  if (libPath.exists() && libPath.isDirectory()) {
    DllOpen::addSearchDirectory(filePath);
    // Iteratate over the available files
    Poco::DirectoryIterator end_itr;
    for (Poco::DirectoryIterator itr(libPath); itr != end_itr; ++itr) {
      const Poco::Path &item = itr.path();
      if (item.isDirectory()) {
        if (isRecursive) {
          libCount += OpenAllLibraries(item.toString());
        }
      } else {
        if (skip(item.toString()))
          continue;
        if (loadLibrary(item.toString())) {
          ++libCount;
        }
      }
    }
  } else {
    g_log.error("In OpenAllLibraries: " + filePath + " must be a directory.");
  }

  return libCount;
}
示例#5
0
    int CStatsUtil::DoExportAll()
    {
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
        {
            outpath = inpath.absolute().makeParent().append(DefExportAllDir);
        }
        else
        {
            outpath = Poco::Path(m_outputPath).makeAbsolute();
        }

        GameStats gstats( m_inputPath, m_langconf );
        gstats.Load();

        //Test output path
        Poco::File fTestOut = outpath;
        if( ! fTestOut.exists() )
        {
            cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
            fTestOut.createDirectory();
        }
        gstats.ExportAll(outpath.toString());
        return 0;
    }
// ---
bool VSWAEImportContentWindow::validateDir (const QString& d)
{
	bool result = false;

	// Calculates the paths for everything: the basic dir, the definition file...
	// ...and the basic path received as parameter during the initialization.
	Poco::Path defPath;
	Poco::File defFile;
	Poco::File defDir (d.toStdString ());
	Poco::Path bPath (_basicPath.toStdString ());
	bool isDefDirADir = defDir.isDirectory (); // The directory has to be a dir (this is guarantte by the window, but just in case)
	if (isDefDirADir) 
	{
		defPath = Poco::Path (d.toStdString ());
		defFile = Poco::File ((d + QString (__PATH_SEPARATOR__) + 
			_name -> text () + QString (".xml")).toStdString ());
	}

	// If the directory is a directory, then it is needed to test whether the
	// directory is or not contained in the basic path received as parameter.
	bool isDefDirInBPath = false;
	if (isDefDirADir)
		isDefDirInBPath = ((defPath.toString () + std::string (__PATH_SEPARATOR__)).
			find (bPath.toString () + std::string (__PATH_SEPARATOR__)) != -1);

	// To determinate whether the dir is or not valid...
	result = !isDefDirADir || (isDefDirADir && isDefDirInBPath);

	return (result);
}
示例#7
0
void Logger::enableFileLogging(const std::string& fileName, int level)
{
    Mutex::ScopedLock lock(loggerMutex);

    Logger::setLevel(level);

    // close the current file log and re-create it.
    disableFileLogging();

    if (!simpleFileChannel)
    {
        std::string realName;

        // figure out what file name to use
        if (fileName.length() == 0) {
            // none given, use one from config.
            realName = Config::getString(Config::LOGGER_LOG_FILE_PATH);
        } else {
            realName = fileName;
        }

        if (realName.length() == 0) {
            // default log name.
            realName = joinPath(getTempDir(), "roadrunner.log");
        } else {
            // expand any env vars and make absolute path.
            realName = Poco::Path::expand(realName);
            Poco::Path path(realName);
            realName = path.makeAbsolute().toString();
        }

        // check if the path is writable
        Poco::Path p(realName);
        Poco::File fdir = p.parent();
        if(!fdir.exists())
        {
            realName = joinPath(getTempDir(), "roadrunner.log");
            Log(Logger::LOG_ERROR) << "The specified log file directory path, "
                    << fdir.path() << " does not exist, using default log file path: "
                    << realName;
        }

        SplitterChannel *splitter = getSplitterChannel();

        simpleFileChannel = new SimpleFileChannel();
        simpleFileChannel->setProperty("path", realName);
        simpleFileChannel->setProperty("rotation", "never");

        logFileName = simpleFileChannel->getProperty("path");

        splitter->addChannel(simpleFileChannel);
        simpleFileChannel->release();
    }
}
示例#8
0
文件: Rules.cpp 项目: Solertis/CLOUDS
void Rules::checkWatchedFile()
{
    Poco::File file = ofFile(watchedFileName).getPocoFile();
    Poco::Timestamp timestamp = file.getLastModified();
    if (timestamp != watchedLastModified)
    {
        clear();
        load(watchedFileName);
        ofNotifyEvent(fileReloaded, branches, this);
        watchedLastModified = timestamp;
    }
}
示例#9
0
 void unlink_directory()
 {
     if ( directory.exists() && directory.isDirectory() )
     {
         try
         {
             directory.remove(true);
         }
         catch(Poco::Exception &e)
         {
             std::cout << e.displayText() << std::endl;
         }
     }
 }
示例#10
0
/**
* Load a library
* @param filepath :: A Poco::File The full path to a library as a string
* @param cacheKey :: An identifier for the cache if loading is successful
* @return 1 if the file loaded successfully, 0 otherwise
*/
int LibraryManagerImpl::openLibrary(const Poco::File &filepath,
                                    const std::string &cacheKey) {
  // Try to open the library. The wrapper will unload the library when it
  // is deleted
  LibraryWrapper dlwrap;
  if (dlwrap.openLibrary(filepath.path())) {
    // Successfully opened, so add to map
    if (g_log.is(Poco::Message::PRIO_DEBUG)) {
      g_log.debug("Opened library: " + filepath.path() + ".\n");
    }
    m_openedLibs.emplace(cacheKey, std::move(dlwrap));
    return 1;
  } else
    return 0;
}
示例#11
0
    /**
     * Module initialization function. Takes a string as input that allows
     * arguments to be passed into the module.
     * @param arguments Tells the module which
     */
    TskModule::Status TSK_MODULE_EXPORT initialize(const char* arguments)
    {
        magicHandle = magic_open(MAGIC_NONE);
        if (magicHandle == NULL) {
            LOGERROR("FileTypeSigModule: Error allocating magic cookie.");
            return TskModule::FAIL;
        }

//Attempt to load magic database from default places on Linux.
//Don't bother trying magic_load() for defaults on win32 because it will always cause an exception instead of gracefully returning.
#ifndef TSK_WIN32
        /* Load the default magic database, which is found in this order:
               1. MAGIC env variable
               2. $HOME/.magic.mgc (or $HOME/.magic dir)
               3. /usr/share/misc/magic.mgc (or /usr/share/misc/magic dir) (unless libmagic was build configured abnormally)
        */
        if (magic_load(magicHandle, NULL)) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Error loading default magic file: " << magic_error(magicHandle);
            LOGERROR(msg.str());
            //don't return, just fall through to the default loading below
        } else {
            return TskModule::OK;
        }
#endif
        //Load the magic database file in the repo
        std::string path = GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR) + Poco::Path::separator() + MODULE_NAME + Poco::Path::separator() + "magic.mgc";

        Poco::File magicFile = Poco::File(path);
        if (magicFile.exists() == false) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Magic file not found: " << path;
            LOGERROR(msg.str());
            return TskModule::FAIL;
        }

        if (magic_load(magicHandle, path.c_str())) {
            std::stringstream msg;
            msg << "FileTypeSigModule: Error loading magic file: " << magic_error(magicHandle) << GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR);
            LOGERROR(msg.str());
            return TskModule::FAIL;
        }

        return TskModule::OK;
    }
示例#12
0
SharedMemoryImpl::SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void*):
	_name(file.path()),
	_memHandle(INVALID_HANDLE_VALUE),
	_fileHandle(INVALID_HANDLE_VALUE),
	_size(0),
	_mode(PAGE_READONLY),
	_address(0)
{
	if (!file.exists() || !file.isFile())
		throw FileNotFoundException(_name);

	_size = static_cast<DWORD>(file.getSize());

	DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
	DWORD fileMode  = GENERIC_READ;

	if (mode == SharedMemory::AM_WRITE)
	{
		_mode = PAGE_READWRITE;
		fileMode |= GENERIC_WRITE;
	}

#if defined (POCO_WIN32_UTF8)
	std::wstring utf16name;
	UnicodeConverter::toUTF16(_name, utf16name);
	_fileHandle = CreateFileW(utf16name.c_str(), fileMode, shareMode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#else
	_fileHandle = CreateFileA(_name.c_str(), fileMode, shareMode, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif

	if (_fileHandle == INVALID_HANDLE_VALUE)
		throw OpenFileException("Cannot open memory mapped file", _name);

	_memHandle = CreateFileMapping(_fileHandle, NULL, _mode, 0, 0, NULL);
	if (!_memHandle)
	{
		CloseHandle(_fileHandle);
		_fileHandle = INVALID_HANDLE_VALUE;
		throw SystemException("Cannot map file into shared memory", _name);
	}
	map();
}
示例#13
0
bool TraverseBase::isDirectory(Poco::File& file)
{
	try
	{
		return file.isDirectory();
	}
	catch (...)
	{
		return false;
	}
}
示例#14
0
SharedMemoryImpl::SharedMemoryImpl(const Poco::File& file, SharedMemory::AccessMode mode, const void* addrHint):
    _size(0),
    _fd(-1),
    _address(0),
    _access(mode),
    _name(file.path()),
    _fileMapped(true),
    _server(false)
{
    if (!file.exists() || !file.isFile())
        throw FileNotFoundException(file.path());

    _size = file.getSize();
    int flag = O_RDONLY;
    if (mode == SharedMemory::AM_WRITE)
        flag = O_RDWR;
    _fd = ::open(_name.c_str(), flag);
    if (-1 == _fd)
        throw OpenFileException("Cannot open memory mapped file", _name);

    map(addrHint);
}
示例#15
0
    persist_fixture(f8String& curPath, bool before_clear = true, bool after_clear = false):
    before(before_clear),
    after(after_clear),
    directory(curPath + "/"+ "store")
    {
        if (before)
        {
            unlink_directory();
            directory.createDirectory();
        }

        filePer = new FilePersister();
        filePer->initialise(curPath + "/" + "store", "utest_log");
    }
示例#16
0
文件: host.cpp 项目: jonnymind/kroll
	void Host::FindBasicModules(std::string& dir)
	{
		ScopedLock lock(&moduleMutex);

		Poco::DirectoryIterator iter = Poco::DirectoryIterator(dir);
		Poco::DirectoryIterator end;
		while (iter != end)
		{
			Poco::File f = *iter;
			if (!f.isDirectory() && !f.isHidden())
			{
				std::string fpath = iter.path().absolute().toString();
				if (IsModule(fpath))
				{
					this->LoadModule(fpath, this);
				}
				else
				{
					this->AddInvalidModuleFile(fpath);
				}
			}
			iter++;
		}
	}
示例#17
0
void FileChecker::updateImpl(const Poco::File & file)
{
	map[Poco::Path(file.path()).getFileName()] = file.getSize();
}
// ---
bool VSWAEImportContentWindow::verifyContent ()
{
	// By default the verification will be true...
	bool result = true;

	// Switch off all the warning indicators...
	switchOffWarnings ();
	
	// First of all, it verifies all the mandatoty fields
	// are introduced. If not the result will be nok.
	if (_name -> text () == QString (__NULL_STRING__) || 
		_implementationFile -> fileName () ==  QString (__NULL_STRING__) ||
		_type -> currentText () == QString (__NULL_STRING__))
		result &= false;

	// If the name introduce already exists...
	// Then a indication is switched on, and the ok button woill not be enabled...
	// But only if something has been introduced.
	if (_name -> text () != QString (__NULL_STRING__))
	{
		bool nameExists = (_contentNames.indexOf (_name -> text ()) != -1);
		if (nameExists) result &= false;
		_nameTF -> setPixmap (QPixmap (nameExists ? 
			":/VSWAdvancedEditor/Resources/Error.png" : ":/VSWAdvancedEditor/Resources/Ok.png"));
	}

	// If the definition directory is not a directory o the directory is not 
	// contained in the basic path, then there is mistake...
	if (_definitionDirName -> dirName () != QString (__NULL_STRING__) && 
		_name -> text () != QString (__NULL_STRING__))
	{
		bool isValidDir = validateDir (_definitionDirName -> dirName ());
		Poco::File defFile = Poco::File ((_definitionDirName -> dirName () + QString (__PATH_SEPARATOR__) + 
			_name -> text () + QString (".xml")).toStdString ());
		if (!isValidDir) result &= false;
		_definitionDirNameTF -> setPixmap (QPixmap (isValidDir ? 
			":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
		if (isValidDir &&  defFile.exists ()) // Being valid, the definition file already exists...
			_definitionDirNameTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
	}

	// If the implementation directory is not a directory o the directory is not 
	// contained in the basic path, then there is mistake...
	if (_implementationDirName -> dirName () != QString (__NULL_STRING__) && 
		_name -> text () != QString (__NULL_STRING__))
	{
		QString iF = _implementationFile -> fileName ();
		#ifdef __WINDOWSPLATFORM__
		iF.replace ("/","\\");
		#endif

		bool isValidDir = validateDir (_implementationDirName -> dirName ());
		Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) + 
			QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
		if (!isValidDir) result &= false;
		_implementationDirNameTF -> setPixmap (QPixmap (isValidDir ? 
			":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
		if (isValidDir &&  defFile.exists ()) // Being valid, the implementation file already exists...
			_implementationDirNameTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
	}

	// Test also the destination of the ocon name,
	// to show a warning icon if an element with the same name already exists in the destination...
	if (_implementationDirName -> dirName () != QString (__NULL_STRING__) && 
		_iconFile -> fileName () != QString (__NULL_STRING__))
	{
		QString iF = _iconFile -> fileName ();
		#ifdef __WINDOWSPLATFORM__
		iF.replace ("/","\\");
		#endif

		bool isValidDir = validateDir (_implementationDirName -> dirName ());
		Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) + 
			QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
		if (!isValidDir) result &= false;
		_iconFileTF -> setPixmap (QPixmap (isValidDir ? 
			":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
		if (isValidDir &&  defFile.exists ()) // Being valid, the implementation file already exists...
			_iconFileTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
	}

	// The same with the resumen file...
	if (_implementationDirName -> dirName () != QString (__NULL_STRING__) && 
		_resumeFile -> fileName () != QString (__NULL_STRING__))
	{
		QString iF = _resumeFile -> fileName ();
		#ifdef __WINDOWSPLATFORM__
		iF.replace ("/","\\");
		#endif

		bool isValidDir = validateDir (_implementationDirName -> dirName ());
		Poco::File defFile = Poco::File ((_implementationDirName -> dirName () + QString (__PATH_SEPARATOR__) + 
			QString (onlyFileName (iF.toStdString ()).c_str ())).toStdString ());
		if (!isValidDir) result &= false;
		_resumeFileTF -> setPixmap (QPixmap (isValidDir ? 
			":/VSWAdvancedEditor/Resources/Ok.png" : ":/VSWAdvancedEditor/Resources/Error.png"));
		if (isValidDir &&  defFile.exists ()) // Being valid, the implementation file already exists...
			_resumeFileTF -> setPixmap (QPixmap (":/VSWAdvancedEditor/Resources/Warning.png"));
	}
		
	return (result);
}
示例#19
0
void BaseDaemon::initialize(Application& self)
{
	task_manager.reset(new Poco::TaskManager);
	ServerApplication::initialize(self);

	bool is_daemon = config().getBool("application.runAsDaemon", false);

	if (is_daemon)
	{
		/** При создании pid файла и поиске конфигурации, будем интерпретировать относительные пути
		  * от директории запуска программы.
		  */
		std::string path = Poco::Path(config().getString("application.path")).setFileName("").toString();
		if (0 != chdir(path.c_str()))
			throw Poco::Exception("Cannot change directory to " + path);
	}

	/// Считаем конфигурацию
	reloadConfiguration();

	/// В случае падения - сохраняем коры
	{
		struct rlimit rlim;
		if (getrlimit(RLIMIT_CORE, &rlim))
			throw Poco::Exception("Cannot getrlimit");
		/// 1 GiB. Если больше - они слишком долго пишутся на диск.
		rlim.rlim_cur = config().getUInt64("core_dump.size_limit", 1024 * 1024 * 1024);

		if (setrlimit(RLIMIT_CORE, &rlim))
		{
			std::string message = "Cannot set max size of core file to " + std::to_string(rlim.rlim_cur);
		#if !defined(ADDRESS_SANITIZER) && !defined(THREAD_SANITIZER)
			throw Poco::Exception(message);
		#else
			/// Не работает под address/thread sanitizer. http://lists.llvm.org/pipermail/llvm-bugs/2013-April/027880.html
			std::cerr << message << std::endl;
		#endif
		}
	}

	/// This must be done before any usage of DateLUT. In particular, before any logging.
	if (config().has("timezone"))
	{
		if (0 != setenv("TZ", config().getString("timezone").data(), 1))
			throw Poco::Exception("Cannot setenv TZ variable");

		tzset();
	}

	std::string log_path = config().getString("logger.log", "");
	if (!log_path.empty())
		log_path = Poco::Path(log_path).setFileName("").toString();

	if (is_daemon)
	{
		/** Переназначим stdout, stderr в отдельные файлы в директориях с логами.
		  * Некоторые библиотеки пишут в stderr в случае ошибок или в отладочном режиме,
		  *  и этот вывод иногда имеет смысл смотреть даже когда программа запущена в режиме демона.
		  * Делаем это до buildLoggers, чтобы ошибки во время инициализации логгера, попали в эти файлы.
		  */
		if (!log_path.empty())
		{
			std::string stdout_path = log_path + "/stdout";
			if (!freopen(stdout_path.c_str(), "a+", stdout))
				throw Poco::OpenFileException("Cannot attach stdout to " + stdout_path);

			std::string stderr_path = log_path + "/stderr";
			if (!freopen(stderr_path.c_str(), "a+", stderr))
				throw Poco::OpenFileException("Cannot attach stderr to " + stderr_path);
		}

		/// Создадим pid-file.
		if (is_daemon && config().has("pid"))
			pid.seed(config().getString("pid"));
	}

	buildLoggers();

	if (is_daemon)
	{
		/** Сменим директорию на ту, куда надо писать core файлы.
		  * Делаем это после buildLoggers, чтобы не менять текущую директорию раньше.
		  * Это важно, если конфиги расположены в текущей директории.
		  */

		std::string core_path = config().getString("core_path", "");
		if (core_path.empty())
			core_path = getDefaultCorePath();

		tryCreateDirectories(&logger(), core_path);

		Poco::File cores = core_path;
		if (!(cores.exists() && cores.isDirectory()))
		{
			core_path = !log_path.empty() ? log_path : "/opt/";
			tryCreateDirectories(&logger(), core_path);
		}

		if (0 != chdir(core_path.c_str()))
			throw Poco::Exception("Cannot change directory to " + core_path);
	}

	/// Ставим terminate_handler
	std::set_terminate(terminate_handler);

	/// Ставим обработчики сигналов
	auto add_signal_handler =
		[](const std::vector<int> & signals, signal_function handler)
		{
			struct sigaction sa;
			memset(&sa, 0, sizeof(sa));
			sa.sa_sigaction = handler;
			sa.sa_flags = SA_SIGINFO;

			{
				if (sigemptyset(&sa.sa_mask))
					throw Poco::Exception("Cannot set signal handler.");

				for (auto signal : signals)
					if (sigaddset(&sa.sa_mask, signal))
						throw Poco::Exception("Cannot set signal handler.");

				for (auto signal : signals)
					if (sigaction(signal, &sa, 0))
						throw Poco::Exception("Cannot set signal handler.");
			}
		};

	add_signal_handler({SIGABRT, SIGSEGV, SIGILL, SIGBUS, SIGSYS, SIGFPE, SIGPIPE}, faultSignalHandler);
	add_signal_handler({SIGHUP, SIGUSR1}, closeLogsSignalHandler);
	add_signal_handler({SIGINT, SIGQUIT, SIGTERM}, terminateRequestedSignalHandler);

	/// Ставим ErrorHandler для потоков
	static KillingErrorHandler killing_error_handler;
	Poco::ErrorHandler::set(&killing_error_handler);

	/// Выведем ревизию демона
	logRevision();

	signal_listener.reset(new SignalListener(*this));
	signal_listener_thread.start(*signal_listener);

	graphite_writer.reset(new GraphiteWriter("graphite"));
}
示例#20
0
    /**
     * Module initialization function. The initialization arguments string should
     * provide the path of a module configuration file that defines what files 
     * are interesting. If the empty string is passed to this function, the module
     * assumes a default config file is present in the output directory.
     *
     * @param args Path of the configuration file that defines what files are 
     * interesting, may be set to the empty string.
     * @return TskModule::OK on success, TskModule::FAIL otherwise. 
     */
    TSK_MODULE_EXPORT TskModule::Status initialize(const char* arguments)
    {
        TskModule::Status status = TskModule::OK;

        const std::string MSG_PREFIX = "InterestingFilesModule::initialize : ";
        try
        {
            // Make sure the file sets are cleared in case initialize() is called more than once.
            fileSets.clear();

            configFilePath.assign(arguments);
            if (configFilePath.empty())
            {
                // Use the default config file path.
                Poco::Path configurationFilePath(Poco::Path::forDirectory(GetSystemProperty(TskSystemProperties::MODULE_CONFIG_DIR)));
                configurationFilePath.pushDirectory(MODULE_NAME);
                configurationFilePath.setFileName(DEFAULT_CONFIG_FILE_NAME);
                configFilePath = configurationFilePath.toString();
            }

            // Compile the contents of the config file into interesting file set definitions.
            Poco::File configFile = Poco::File(configFilePath);
            if (configFile.exists())
            {
                std::ifstream configStream(configFile.path().c_str());
                if (configStream)
                {
                    Poco::XML::InputSource inputSource(configStream);
                    Poco::AutoPtr<Poco::XML::Document> configDoc = Poco::XML::DOMParser().parse(&inputSource);

                    Poco::XML::Element * rootElement = configDoc->documentElement();
                    if (rootElement == NULL)
                    {
                        std::ostringstream msg;
                        msg << MSG_PREFIX << "Root element of config file is NULL.";
                        throw TskException(msg.str());
                    }

                    const std::string& ignoreKnownValue = Poco::XML::fromXMLString(rootElement->getAttribute(IGNORE_KNOWN_TAG));

                    if (!ignoreKnownValue.empty())
                    {
                        knownType = parseKnownType(ignoreKnownValue);
                        ignoreKnown = true;
                    }

                    Poco::AutoPtr<Poco::XML::NodeList> fileSetDefinitions = configDoc->getElementsByTagName(INTERESTING_FILE_SET_ELEMENT_TAG);
                    for (unsigned long i = 0; i < fileSetDefinitions->length(); ++i) 
                    {
                        compileInterestingFilesSet(fileSetDefinitions->item(i));
                    }
                }
                else
                {
                    std::ostringstream msg;
                    msg << MSG_PREFIX << "failed to open config file '" << configFilePath << "'";
                    throw TskException(msg.str());
                }
            }
            else
            {
                std::ostringstream msg;
                msg << MSG_PREFIX << "config file'" << configFilePath << "' does not exist";
                LOGERROR(msg.str());
            }

            // Log the configuration.
            std::ostringstream msg;
            msg << MSG_PREFIX << "configured with " << fileSets.size() << " interesting file set definitions from '" << configFilePath << "'";
            LOGINFO(msg.str());
        }
        catch (TskException &ex)
        {
            status = TskModule::FAIL;
            configFilePath.clear();
            std::ostringstream msg;
            msg << MSG_PREFIX << "TskException: " << ex.message();
            LOGERROR(msg.str());
        }
        catch (Poco::Exception &ex)
        {
            status = TskModule::FAIL;
            configFilePath.clear();
            std::ostringstream msg;
            msg << MSG_PREFIX << "Poco::Exception: " << ex.displayText();
            LOGERROR(msg.str());
        }
        catch (std::exception &ex)
        {
            status = TskModule::FAIL;
            configFilePath.clear();
            std::ostringstream msg;
            msg << MSG_PREFIX << "std::exception: " << ex.what();
            LOGERROR(msg.str());
        }
        catch (...)
        {
            status = TskModule::FAIL;
            configFilePath.clear();
            LOGERROR(MSG_PREFIX + "unrecognized exception");
        }

        return status;
    }