lokinet/llarp/util/fs.cpp

63 lines
1.8 KiB
C++
Raw Normal View History

#include <util/fs.hpp>
2019-06-24 15:51:58 +00:00
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <system_error>
2019-06-24 17:36:25 +00:00
#include <util/logger.hpp>
2019-06-24 15:51:58 +00:00
namespace llarp
{
namespace util
{
2019-06-24 17:36:25 +00:00
static std::error_code
errno_error()
{
int e = errno;
errno = 0;
return std::make_error_code(static_cast< std::errc >(e));
}
2019-06-24 15:51:58 +00:00
error_code_t
EnsurePrivateFile(fs::path pathname)
{
2019-06-24 17:36:25 +00:00
const auto str = pathname.string();
2019-06-24 19:34:30 +00:00
errno = 0;
2019-06-24 17:36:25 +00:00
error_code_t ec = errno_error();
2019-06-24 16:26:15 +00:00
if(fs::exists(pathname, ec)) // file exists
2019-06-24 15:51:58 +00:00
{
2019-06-24 19:34:30 +00:00
auto st = fs::status(pathname, ec);
if(ec)
return ec;
auto perms = st.permissions();
if((perms & fs::perms::others_exec) != fs::perms::none)
perms ^= fs::perms::others_exec;
if((perms & fs::perms::others_write) != fs::perms::none)
perms ^= fs::perms::others_write;
if((perms & fs::perms::others_write) != fs::perms::none)
perms ^= fs::perms::others_write;
if((perms & fs::perms::group_read) != fs::perms::none)
perms ^= fs::perms::group_read;
if((perms & fs::perms::others_read) != fs::perms::none)
perms ^= fs::perms::others_read;
if((perms & fs::perms::owner_exec) != fs::perms::none)
perms ^= fs::perms::owner_exec;
fs::permissions(pathname, perms, ec);
if(ec)
llarp::LogError("failed to set permissions on ", pathname);
2019-06-24 15:51:58 +00:00
}
2019-06-24 16:26:15 +00:00
else if(!ec) // file is not there
2019-06-24 15:51:58 +00:00
{
2019-06-24 17:36:25 +00:00
errno = 0;
int fd = ::open(str.c_str(), O_RDWR | O_CREAT, 0600);
ec = errno_error();
2019-06-24 15:51:58 +00:00
if(fd != -1)
{
::close(fd);
}
}
2019-06-24 17:36:25 +00:00
if(ec)
llarp::LogError("failed to ensure ", str, ", ", ec.message());
2019-06-24 15:51:58 +00:00
return ec;
}
2019-06-24 16:26:15 +00:00
} // namespace util
} // namespace llarp