/*************************************************
* FTW EntropySource Source File                  *
* (C) 1999-2004 The Botan Project                *
*************************************************/

#ifndef _XOPEN_SOURCE
  #define _XOPEN_SOURCE 500
#endif

#ifndef _XOPEN_SOURCE_EXTENDED
  #define _XOPEN_SOURCE_EXTENDED 1
#endif

#include <botan/es_ftw.h>
#include <botan/util.h>
#include <fstream>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

namespace Botan {

/*************************************************
* FTW_EntropySource Constructor                  *
*************************************************/
FTW_EntropySource::FTW_EntropySource(const std::string& p) : path(p)
   {
   }

/*************************************************
* FTW Fast Poll                                  *
*************************************************/
void FTW_EntropySource::do_fast_poll()
   {
   files_read = 0;
   gather_from_dir(path, 16);
   }

/*************************************************
* FTW Slow Poll                                  *
*************************************************/
void FTW_EntropySource::do_slow_poll()
   {
   files_read = 0;
   gather_from_dir(path, 256);
   }

/*************************************************
* Gather Entropy From Directory Tree             *
*************************************************/
void FTW_EntropySource::gather_from_dir(const std::string& dirname,
                                        u32bit limit)
   {
   if(dirname == "")
      return;

   DIR* dir = opendir(dirname.c_str());
   if(dir == 0)
      return;

   dirent* entry = readdir(dir);
   while(entry && (files_read < limit))
      {
      if((std::strcmp(entry->d_name, ".") == 0) ||
         (std::strcmp(entry->d_name, "..") == 0))
         { entry = readdir(dir); continue; }

      const std::string filename = dirname + '/' + entry->d_name;

      struct stat stat_buf;
      if(lstat(filename.c_str(), &stat_buf) == -1)
         { entry = readdir(dir); continue; }

      if(S_ISREG(stat_buf.st_mode))
         gather_from_file(filename);
      else if(S_ISDIR(stat_buf.st_mode))
         gather_from_dir(filename, limit - files_read);
      entry = readdir(dir);
      }

   closedir(dir);
   }

/*************************************************
* Gather Entropy From A File                     *
*************************************************/
void FTW_EntropySource::gather_from_file(const std::string& filename)
   {
   std::ifstream in(filename.c_str());
   if(!in) return;

   SecureVector<byte> read_buf(128);
   in.read((char*)read_buf.begin(), read_buf.size());

   u32bit got = in.gcount();

   if(got > 0)
      {
      add_bytes(read_buf, got);
      files_read++;
      }
   }

}
