Kea 3.0.3-git
filesystem.cc
Go to the documentation of this file.
1// Copyright (C) 2021-2026 Internet Systems Consortium, Inc. ("ISC")
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7#include <config.h>
8
10#include <util/filesystem.h>
11#include <util/str.h>
12
13#include <cstdio>
14#include <cstdlib>
15#include <fstream>
16#include <string>
17#include <iostream>
18
19#include <dirent.h>
20#include <fcntl.h>
21
22using namespace isc;
23using namespace isc::util::str;
24using namespace std;
25
26namespace isc {
27namespace util {
28namespace file {
29
30
31string
32getContent(string const& file_name) {
33 if (!exists(file_name)) {
34 isc_throw(BadValue, "Expected a file at path '" << file_name << "'");
35 }
36 if (!isFile(file_name)) {
37 isc_throw(BadValue, "Expected '" << file_name << "' to be a regular file");
38 }
39 ifstream file(file_name, ios::in);
40 if (!file.is_open()) {
41 isc_throw(BadValue, "Cannot open '" << file_name);
42 }
43 string content;
44 file >> content;
45 return (content);
46}
47
48bool
49exists(string const& path) {
50 struct stat statbuf;
51 return (::stat(path.c_str(), &statbuf) == 0);
52}
53
54mode_t
55getPermissions(const std::string path) {
56 struct stat statbuf;
57 if (::stat(path.c_str(), &statbuf) < 0) {
58 return (0);
59 }
60
61 return (statbuf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO));
62}
63
64bool
65hasPermissions(const std::string path, const mode_t& permissions) {
66 return (getPermissions(path) == permissions);
67}
68
69bool
70isDir(string const& path) {
71 struct stat statbuf;
72 if (::stat(path.c_str(), &statbuf) < 0) {
73 return (false);
74 }
75 return ((statbuf.st_mode & S_IFMT) == S_IFDIR);
76}
77
78bool
79isFile(string const& path) {
80 struct stat statbuf;
81 if (::stat(path.c_str(), &statbuf) < 0) {
82 return (false);
83 }
84 return ((statbuf.st_mode & S_IFMT) == S_IFREG);
85}
86
87bool
88isSocket(string const& path) {
89 struct stat statbuf;
90 if (::stat(path.c_str(), &statbuf) < 0) {
91 return (false);
92 }
93 return ((statbuf.st_mode & S_IFMT) == S_IFSOCK);
94}
95
96void
98 // No group write and no other access.
99 mode_t mask(S_IWGRP | S_IRWXO);
100 mode_t orig = umask(mask);
101 // Handle the case where the original umask was already more restrictive.
102 if ((orig | mask) != mask) {
103 static_cast<void>(umask(orig | mask));
104 }
105}
106
107RelaxUmask::RelaxUmask() : orig_umask_(umask(S_IRWXO)) {
108}
109
111 static_cast<void>(umask(orig_umask_));
112}
113
114Path::Path(string const& full_name) {
115 dir_present_ = false;
116 if (!full_name.empty()) {
117 // Find the directory.
118 size_t last_slash = full_name.find_last_of('/');
119 if (last_slash != string::npos) {
120 // Found a directory so note the fact.
121 dir_present_ = true;
122
123 // Found the last slash, so extract directory component and
124 // set where the scan for the last_dot should terminate.
125 parent_path_ = full_name.substr(0, last_slash);
126 if (last_slash == full_name.size()) {
127 // The entire string was a directory, so exit and don't
128 // do any more searching.
129 return;
130 }
131 }
132
133 // Now search backwards for the last ".".
134 size_t last_dot = full_name.find_last_of('.');
135 if ((last_dot == string::npos) || (dir_present_ && (last_dot < last_slash))) {
136 // Last "." either not found or it occurs to the left of the last
137 // slash if a directory was present (so it is part of a directory
138 // name). In this case, the remainder of the string after the slash
139 // is the name part.
140 stem_ = full_name.substr(last_slash + 1);
141 return;
142 }
143
144 // Did find a valid dot, so it and everything to the right is the
145 // extension...
146 extension_ = full_name.substr(last_dot);
147
148 // ... and the name of the file is everything in between.
149 if ((last_dot - last_slash) > 1) {
150 stem_ = full_name.substr(last_slash + 1, last_dot - last_slash - 1);
151 }
152 }
153}
154
155string
156Path::str() const {
157 return (parent_path_ + (dir_present_ ? "/" : "") + stem_ + extension_);
158}
159
160string
162 return (parent_path_);
163}
164
165string
167 return (parent_path_ + (dir_present_ ? "/" : ""));
168}
169
170string
171Path::stem() const {
172 return (stem_);
173}
174
175string
177 return (extension_);
178}
179
180string
182 return (stem_ + extension_);
183}
184
185Path&
186Path::replaceExtension(string const& replacement) {
187 string const trimmed_replacement(trim(replacement));
188 if (trimmed_replacement.empty()) {
189 extension_ = string();
190 } else {
191 size_t const last_dot(trimmed_replacement.find_last_of('.'));
192 if (last_dot == string::npos) {
193 extension_ = "." + trimmed_replacement;
194 } else {
195 extension_ = trimmed_replacement.substr(last_dot);
196 }
197 }
198 return (*this);
199}
200
201Path&
202Path::replaceParentPath(string const& replacement) {
203 string const trimmed_replacement(trim(replacement));
204 dir_present_ = (trimmed_replacement.find_last_of('/') != string::npos);
205 if (trimmed_replacement.empty() || (trimmed_replacement == "/")) {
206 parent_path_ = string();
207 } else if (trimmed_replacement.at(trimmed_replacement.size() - 1) == '/') {
208 parent_path_ = trimmed_replacement.substr(0, trimmed_replacement.size() - 1);
209 } else {
210 parent_path_ = trimmed_replacement;
211 }
212 return (*this);
213}
214
216 char dir[]("/tmp/kea-tmpdir-XXXXXX");
217 char const* dir_name = mkdtemp(dir);
218 if (!dir_name) {
219 isc_throw(Unexpected, "mkdtemp failed " << dir << ": " << strerror(errno));
220 }
221 dir_name_ = string(dir_name);
222}
223
225 DIR *dir(opendir(dir_name_.c_str()));
226 if (!dir) {
227 return;
228 }
229
230 std::unique_ptr<DIR, void(*)(DIR*)> defer(dir, [](DIR* d) { closedir(d); });
231
232 struct dirent *i;
233 string filepath;
234 while ((i = readdir(dir))) {
235 if (strcmp(i->d_name, ".") == 0 || strcmp(i->d_name, "..") == 0) {
236 continue;
237 }
238
239 filepath = dir_name_ + '/' + i->d_name;
240 remove(filepath.c_str());
241 }
242
243 rmdir(dir_name_.c_str());
244}
245
247 return dir_name_;
248}
249
250PathChecker::PathChecker(const std::string default_path,
251 const std::string env_name /* = "" */)
252 : default_path_(default_path), env_name_(env_name),
253 default_overridden_(false) {
254 getPath(true);
255}
256
257std::string
258PathChecker::getPath(bool reset /* = false */,
259 const std::string explicit_path /* = "" */) {
260 if (reset) {
261 if (!explicit_path.empty()) {
262 path_ = explicit_path;
263 } else if (!env_name_.empty()) {
264 path_ = std::string(std::getenv(env_name_.c_str()) ?
265 std::getenv(env_name_.c_str()) : default_path_);
266 } else {
267 path_ = default_path_;
268 }
269
270 // Remove the trailing "/" if it is present so comparison to
271 // other Path::parentPath() works.
272 while (!path_.empty() && path_.back() == '/') {
273 path_.pop_back();
274 }
275
276 default_overridden_ = (path_ != default_path_);
277 }
278
279 return (path_);
280}
281
282std::string
283PathChecker::validatePath(const std::string input_path_str,
284 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
285 Path input_path(trim(input_path_str));
286 auto filename = input_path.filename();
287 if (filename.empty()) {
288 isc_throw(BadValue, "path: '" << input_path.str() << "' has no filename");
289 }
290
291 auto parent_path = input_path.parentPath();
292 auto parent_dir = input_path.parentDirectory();
293 if (!parent_dir.empty()) {
294 if (!enforce_path) {
295 // Security set to lax, let it fly.
296 return (input_path_str);
297 }
298
299 // We only allow absolute path equal to default. Catch an invalid path.
300 if ((parent_path != path_) || (parent_dir == "/")) {
301 isc_throw(BadValue, "invalid path specified: '"
302 << (parent_path.empty() ? "/" : parent_path)
303 << "', supported path is '"
304 << path_ << "'");
305 }
306 }
307
308 std::string valid_path(path_ + "/" + filename);
309 return (valid_path);
310}
311
312std::string
313PathChecker::validateDirectory(const std::string input_path_str,
314 bool enforce_path /* = PathChecker::shouldEnforceSecurity() */) const {
315 std::string input_copy = trim(input_path_str);
316 if (!enforce_path) {
317 return(input_copy);
318 }
319
320 // We only allow absolute path equal to default. Catch an invalid path.
321 if (!input_path_str.empty()) {
322 std::string input_copy = input_path_str;
323 while (!input_copy.empty() && input_copy.back() == '/') {
324 input_copy.pop_back();
325 }
326
327 if (input_copy != path_) {
328 isc_throw(BadValue, "invalid path specified: '"
329 << input_path_str << "', supported path is '"
330 << path_ << "'");
331 }
332 }
333
334 return (path_);
335}
336
337bool
338PathChecker::pathHasPermissions(mode_t permissions, bool enforce_perms
339 /* = PathChecker::shouldEnforceSecurity() */) const {
340 return((!enforce_perms) || hasPermissions(path_, permissions));
341}
342
343bool
345 return (default_overridden_);
346}
347
349 return (enforce_security_);
350}
351
353 enforce_security_ = enable;
354}
355
356bool PathChecker::enforce_security_ = true;
357
358} // namespace file
359} // namespace util
360} // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
A generic exception that is thrown when an unexpected error condition occurs.
std::string getPath(bool reset=false, const std::string explicit_path="")
Fetches the supported path.
static bool shouldEnforceSecurity()
Indicates security checks should be enforced.
PathChecker(const std::string default_path, const std::string env_name="")
Constructor.
bool isDefaultOverridden()
Indicates if the default path has been overridden.
static void enableEnforcement(bool enable)
Enables or disables security enforcment checks.
std::string validateDirectory(const std::string input_path_str, bool enforce_path=shouldEnforceSecurity()) const
Validates a directory against a supported path.
bool pathHasPermissions(mode_t permissions, bool enforce_perms=shouldEnforceSecurity()) const
Check if the path has expected permissions.
std::string validatePath(const std::string input_path_str, bool enforce_path=shouldEnforceSecurity()) const
Validates a file path against a supported path.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
bool isSocket(string const &path)
Check if there is a socket at the given path.
Definition filesystem.cc:88
string getContent(string const &file_name)
Get the content of a regular file.
Definition filesystem.cc:32
bool isFile(string const &path)
Check if there is a file at the given path.
Definition filesystem.cc:79
bool exists(string const &path)
Check if there is a file or directory at the given path.
Definition filesystem.cc:49
bool isDir(string const &path)
Check if there is a directory at the given path.
Definition filesystem.cc:70
mode_t getPermissions(const std::string path)
Fetches the file permissions mask.
Definition filesystem.cc:55
bool hasPermissions(const std::string path, const mode_t &permissions)
Check if there if file or directory has the given permissions.
Definition filesystem.cc:65
void setUmask()
Set umask (at least 0027 i.e. no group write and no other access).
Definition filesystem.cc:97
string trim(const string &input)
Trim leading and trailing spaces.
Definition str.cc:32
Defines the logger used by the top-level component of kea-lfc.
Paths on a filesystem.
Definition filesystem.h:99
Path(std::string const &path)
Constructor.
Path & replaceParentPath(std::string const &replacement=std::string())
Trims {replacement} and replaces this instance's parent path with it.
std::string parentDirectory() const
Get the parent directory.
std::string extension() const
Get the extension of the file.
Path & replaceExtension(std::string const &replacement=std::string())
Identifies the extension in {replacement}, trims it, and replaces this instance's extension with it.
std::string stem() const
Get the base name of the file without the extension.
std::string parentPath() const
Get the parent path.
std::string filename() const
Get the name of the file, extension included.
std::string str() const
Get the path in textual format.