Skip to content

Commit

Permalink
util: provide readFromFileToStr primitive, which doesn't throw except…
Browse files Browse the repository at this point in the history
…ions
  • Loading branch information
robertswiecki committed Jun 26, 2024
1 parent f6f63bd commit 6ca807a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
13 changes: 8 additions & 5 deletions config.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

#include <fstream>
#include <list>
#include <sstream>
#include <string>
#include <vector>

Expand Down Expand Up @@ -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<char>(ifs)), (std::istreambuf_iterator<char>()));

/* Use static so we can get c_str() pointers, and copy them into the nsjconf struct */
static nsjail::NsJailConfig json_nsc;
Expand Down
29 changes: 29 additions & 0 deletions util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
#include <time.h>
#include <unistd.h>

#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
Expand Down Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 6ca807a

Please sign in to comment.