diff --git a/config.cc b/config.cc index 64a6ded..ddcef00 100644 --- a/config.cc +++ b/config.cc @@ -34,6 +34,7 @@ #include #include +#include #include #include @@ -321,13 +322,15 @@ static void flushLog() { bool parseFile(nsjconf_t* nsjconf, const char* file) { LOG_D("Parsing configuration from '%s'", file); - std::ifstream ifs(file); - if (!ifs.is_open()) { - PLOG_W("Couldn't open config file '%s'", file); + std::string conf; + if (!util::readFromFileToStr(file, &conf)) { + LOG_E("Couldn't read config file '%s'", file); + return false; + } + if (conf.size() == 0) { + LOG_E("Config file '%s' is empty", file); return false; } - - std::string conf((std::istreambuf_iterator(ifs)), (std::istreambuf_iterator())); /* Use static so we can get c_str() pointers, and copy them into the nsjconf struct */ static nsjail::NsJailConfig json_nsc; diff --git a/util.cc b/util.cc index f7b4f1d..a885444 100644 --- a/util.cc +++ b/util.cc @@ -40,6 +40,7 @@ #include #include +#include #include #include #include @@ -89,6 +90,34 @@ bool writeToFd(int fd, const void* buf, size_t len) { return true; } +bool readFromFileToStr(const char* fname, std::string* str) { + std::fstream fs(fname, std::ios::in | std::ios::binary); + if (!fs.is_open()) { + PLOG_W("Couldn't open file '%s'", fname); + return false; + } + + str->clear(); + + while (fs) { + char buf[4096]; + fs.read(buf, sizeof(buf)); + std::streamsize sz = fs.gcount(); + if (sz > 0) { + str->append(buf, sz); + } + if (fs.eof()) { + return true; + } + if (fs.bad() || fs.fail()) { + PLOG_W("Reading from '%s' failed", fname); + return false; + } + } + + return true; +} + bool writeBufToFile( const char* filename, const void* buf, size_t len, int open_flags, bool log_errors) { int fd; diff --git a/util.h b/util.h index 7b17758..b732cde 100644 --- a/util.h +++ b/util.h @@ -54,6 +54,7 @@ namespace util { ssize_t readFromFd(int fd, void* buf, size_t len); ssize_t readFromFile(const char* fname, void* buf, size_t len); +bool readFromFileToStr(const char* fname, std::string* str); bool writeToFd(int fd, const void* buf, size_t len); bool writeBufToFile( const char* filename, const void* buf, size_t len, int open_flags, bool log_errors = true);