Skip to content

Commit 84c437e

Browse files
committed
[#3050] Added Umask RAII and use it
1 parent 7d862a0 commit 84c437e

File tree

4 files changed

+41
-1
lines changed

4 files changed

+41
-1
lines changed

src/lib/process/daemon.cc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,9 @@ Daemon::writeConfigFile(const std::string& config_file,
231231
isc_throw(Unexpected, "Can't write configuration: conversion to JSON failed");
232232
}
233233

234+
// Remove rights for other from the umask.
235+
Umask mask(S_IRWXO);
236+
234237
std::ofstream out(config_file, std::ios::trunc);
235238
if (!out.good()) {
236239
isc_throw(Unexpected, "Unable to open file " + config_file + " for writing");

src/lib/util/filesystem.cc

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
#include <string>
2020

2121
#include <fcntl.h>
22-
#include <sys/stat.h>
2322

2423
using namespace isc::util::str;
2524
using namespace std;
@@ -69,6 +68,14 @@ isFile(string const& path) {
6968
return ((statbuf.st_mode & S_IFMT) == S_IFREG);
7069
}
7170

71+
Umask::Umask(mode_t mask) : orig_umask_(umask(S_IWGRP | S_IWOTH)) {
72+
umask(orig_umask_ | mask);
73+
}
74+
75+
Umask::~Umask() {
76+
umask(orig_umask_);
77+
}
78+
7279
Path::Path(string const& full_name) {
7380
if (!full_name.empty()) {
7481
bool dir_present = false;

src/lib/util/filesystem.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#ifndef KEA_UTIL_FILESYSTEM_H
88
#define KEA_UTIL_FILESYSTEM_H
99

10+
#include <sys/stat.h>
1011
#include <string>
1112

1213
namespace isc {
@@ -48,6 +49,23 @@ isDir(const std::string& path);
4849
bool
4950
isFile(const std::string& path);
5051

52+
/// \brief RAII device to limit access of created files.
53+
struct Umask {
54+
/// \brief Constructor
55+
///
56+
/// Set wanted bits in umask.
57+
Umask(mode_t mask);
58+
59+
/// \brief Destructor.
60+
///
61+
/// Restore umask.
62+
~Umask();
63+
64+
private:
65+
/// \brief Original umask.
66+
mode_t orig_umask_;
67+
};
68+
5169
/// \brief Paths on a filesystem
5270
struct Path {
5371
/// \brief Constructor

src/lib/util/tests/filesystem_unittests.cc

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@ TEST_F(FileUtilTest, isFile) {
6969
EXPECT_FALSE(isFile(TEST_DATA_BUILDDIR));
7070
}
7171

72+
/// @brief Check Umask.
73+
TEST_F(FileUtilTest, umask) {
74+
// Protect the test itself assuming that Umask does what we expect...
75+
Umask m0(0);
76+
mode_t orig = umask(0);
77+
{
78+
Umask m(S_IROTH);
79+
EXPECT_EQ(S_IROTH, umask(S_IRWXO));
80+
}
81+
EXPECT_EQ(0, umask(orig));
82+
}
83+
7284
/// @brief Check that the components are split correctly.
7385
TEST(PathTest, components) {
7486
// Complete name

0 commit comments

Comments
 (0)