feat(System): harden OwnedFd/Child process spawn, full-duplex bounds, durable replace_file, safe TempFile/TempDir, and SystemOnly consumer (M-SYSTEM-01, M-SYSTEM-02, M-SYSTEM-05)
This commit is contained in:
1 parent
3f67b1ecb7
commit
fcdbc063b2
14 files changed
+3538
-890
No files matched your search
+224
-99
@@ -1,126 +1,251 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <dirent.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Void::FileSystem
|
||||
{
|
||||
/// RAII scoped directory under `std::filesystem::temp_directory_path()`.
|
||||
///
|
||||
/// The directory is created with a unique name on construction and
|
||||
/// recursively removed on destruction. Useful in tests that need a
|
||||
/// scratch area without manual cleanup.
|
||||
///
|
||||
/// Construction throws `std::system_error` if the directory cannot
|
||||
/// be created. Use `TempDir::open(prefix)` for a non-throwing
|
||||
/// `Result`-returning factory.
|
||||
class TempDir
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TempDir(std::string_view prefix = "void_test_")
|
||||
: m_path(make_unique_dir(prefix))
|
||||
{
|
||||
}
|
||||
/// RAII scoped directory created with private `0700` permissions and removed
|
||||
/// safely without following symlinks or deleting replaced directories.
|
||||
class TempDir
|
||||
{
|
||||
public:
|
||||
explicit TempDir(std::string_view prefix = "void_test_")
|
||||
{
|
||||
auto created = create_unique_dir(
|
||||
std::filesystem::temp_directory_path(), prefix);
|
||||
if (!created.has_value()) {
|
||||
throw std::system_error(
|
||||
std::make_error_code(std::errc::file_exists),
|
||||
created.error().message());
|
||||
}
|
||||
*this = std::move(*created);
|
||||
}
|
||||
|
||||
~TempDir() noexcept
|
||||
{
|
||||
if (!m_path.empty()) {
|
||||
Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string());
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove_all(m_path, ignore);
|
||||
}
|
||||
}
|
||||
~TempDir() noexcept { remove_if_owned(); }
|
||||
|
||||
TempDir(const TempDir&) = delete;
|
||||
TempDir& operator=(const TempDir&) = delete;
|
||||
TempDir(const TempDir&) = delete;
|
||||
TempDir& operator=(const TempDir&) = delete;
|
||||
|
||||
TempDir(TempDir&& other) noexcept
|
||||
: m_path(std::exchange(other.m_path, {}))
|
||||
{
|
||||
}
|
||||
TempDir(TempDir&& other) noexcept
|
||||
: m_path(std::exchange(other.m_path, {})),
|
||||
m_dev(std::exchange(other.m_dev, 0)),
|
||||
m_ino(std::exchange(other.m_ino, 0))
|
||||
{
|
||||
}
|
||||
|
||||
TempDir& operator=(TempDir&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
if (!m_path.empty()) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove_all(m_path, ignore);
|
||||
}
|
||||
m_path = std::exchange(other.m_path, {});
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
TempDir& operator=(TempDir&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
remove_if_owned();
|
||||
m_path = std::exchange(other.m_path, {});
|
||||
m_dev = std::exchange(other.m_dev, 0);
|
||||
m_ino = std::exchange(other.m_ino, 0);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
|
||||
/// Build a path inside the temp dir.
|
||||
/// Example: `auto log_path = tmp / "test.log";`
|
||||
[[nodiscard]] std::filesystem::path
|
||||
operator/(std::string_view relative) const
|
||||
{
|
||||
return m_path / relative;
|
||||
}
|
||||
[[nodiscard]] std::filesystem::path
|
||||
operator/(std::string_view relative) const
|
||||
{
|
||||
return m_path / relative;
|
||||
}
|
||||
|
||||
/// Non-throwing factory.
|
||||
[[nodiscard]] static Void::Result::Result<TempDir,
|
||||
Void::Result::Error>
|
||||
open(std::string_view prefix = "void_test_")
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(TempDir{prefix});
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(std::string{e.what()});
|
||||
}
|
||||
}
|
||||
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
|
||||
open(std::string_view prefix = "void_test_")
|
||||
{
|
||||
return open_in(std::filesystem::temp_directory_path(), prefix);
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
|
||||
open_in(const std::filesystem::path& directory,
|
||||
std::string_view prefix = "void_test_")
|
||||
{
|
||||
return create_unique_dir(directory, prefix);
|
||||
}
|
||||
|
||||
std::filesystem::path m_path;
|
||||
private:
|
||||
struct InternalEmpty {};
|
||||
explicit TempDir(InternalEmpty) noexcept {}
|
||||
|
||||
static std::filesystem::path
|
||||
make_unique_dir(std::string_view prefix)
|
||||
{
|
||||
static std::atomic<std::uint64_t> counter{0};
|
||||
const auto base = std::filesystem::temp_directory_path();
|
||||
for (int attempt = 0; attempt < 16; ++attempt) {
|
||||
const auto seed =
|
||||
static_cast<std::uint64_t>(
|
||||
std::chrono::steady_clock::now()
|
||||
.time_since_epoch()
|
||||
.count()) ^
|
||||
(counter.fetch_add(1, std::memory_order_relaxed)
|
||||
<< 16) ^
|
||||
static_cast<std::uint64_t>(std::hash<std::thread::id>{}(
|
||||
std::this_thread::get_id()));
|
||||
auto candidate =
|
||||
base / std::format("{}{:016x}", prefix, seed);
|
||||
std::error_code ec;
|
||||
if (std::filesystem::create_directory(candidate, ec)) {
|
||||
Void::Log::debug("FileSystem", "TempDir: created '{}'",
|
||||
candidate.string());
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
throw std::system_error(
|
||||
std::make_error_code(std::errc::file_exists),
|
||||
"TempDir: failed to create unique directory after 16 "
|
||||
"attempts");
|
||||
}
|
||||
};
|
||||
std::filesystem::path m_path;
|
||||
std::uint64_t m_dev = 0;
|
||||
std::uint64_t m_ino = 0;
|
||||
|
||||
#ifndef _WIN32
|
||||
static void clear_dir_contents_nofollow(int dir_fd) noexcept
|
||||
{
|
||||
const int dup_fd = ::dup(dir_fd);
|
||||
if (dup_fd < 0) {
|
||||
return;
|
||||
}
|
||||
DIR* dir = ::fdopendir(dup_fd);
|
||||
if (dir == nullptr) {
|
||||
(void)::close(dup_fd);
|
||||
return;
|
||||
}
|
||||
std::vector<std::string> subdirs;
|
||||
std::vector<std::string> files;
|
||||
while (const struct dirent* ent = ::readdir(dir)) {
|
||||
const std::string_view name{ent->d_name};
|
||||
if (name == "." || name == "..") {
|
||||
continue;
|
||||
}
|
||||
struct stat st {};
|
||||
if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0) {
|
||||
continue;
|
||||
}
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
subdirs.emplace_back(name);
|
||||
} else {
|
||||
files.emplace_back(name);
|
||||
}
|
||||
}
|
||||
(void)::closedir(dir);
|
||||
|
||||
for (const auto& f : files) {
|
||||
(void)::unlinkat(dir_fd, f.c_str(), 0);
|
||||
}
|
||||
for (const auto& d : subdirs) {
|
||||
const int sub_fd = ::openat(
|
||||
dir_fd,
|
||||
d.c_str(),
|
||||
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (sub_fd >= 0) {
|
||||
clear_dir_contents_nofollow(sub_fd);
|
||||
(void)::close(sub_fd);
|
||||
(void)::unlinkat(dir_fd, d.c_str(), AT_REMOVEDIR);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void remove_if_owned() noexcept
|
||||
{
|
||||
if (m_path.empty()) {
|
||||
return;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
struct stat st {};
|
||||
if (::lstat(m_path.c_str(), &st) != 0 || S_ISLNK(st.st_mode) ||
|
||||
!S_ISDIR(st.st_mode)) {
|
||||
return;
|
||||
}
|
||||
if (static_cast<std::uint64_t>(st.st_dev) != m_dev ||
|
||||
static_cast<std::uint64_t>(st.st_ino) != m_ino ||
|
||||
st.st_uid != ::geteuid()) {
|
||||
return;
|
||||
}
|
||||
const int dir_fd = ::open(
|
||||
m_path.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (dir_fd < 0) {
|
||||
return;
|
||||
}
|
||||
struct stat fd_st {};
|
||||
if (::fstat(dir_fd, &fd_st) == 0 &&
|
||||
static_cast<std::uint64_t>(fd_st.st_dev) == m_dev &&
|
||||
static_cast<std::uint64_t>(fd_st.st_ino) == m_ino) {
|
||||
clear_dir_contents_nofollow(dir_fd);
|
||||
}
|
||||
(void)::close(dir_fd);
|
||||
(void)::rmdir(m_path.c_str());
|
||||
Void::Log::debug(
|
||||
"FileSystem", "TempDir: removed '{}'", m_path.string());
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<TempDir, Void::Result::Error>
|
||||
create_unique_dir(const std::filesystem::path& base,
|
||||
std::string_view prefix)
|
||||
{
|
||||
#ifndef _WIN32
|
||||
if (prefix.find('/') != std::string_view::npos ||
|
||||
prefix.find('\0') != std::string_view::npos) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
"TempDir: prefix must not contain '/' or NUL")};
|
||||
}
|
||||
|
||||
int last_err = 0;
|
||||
for (int attempt = 0; attempt < 32; ++attempt) {
|
||||
const auto seed = detail::next_temp_entropy();
|
||||
auto candidate = base / std::format("{}{:016x}", prefix, seed);
|
||||
if (::mkdir(candidate.c_str(), 0700) == 0) {
|
||||
const int fd = ::open(
|
||||
candidate.c_str(),
|
||||
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
const int err = errno;
|
||||
(void)::rmdir(candidate.c_str());
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
"TempDir: open failed after mkdir",
|
||||
err)};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
struct stat st {};
|
||||
if (::fstat(fd, &st) != 0) {
|
||||
const int err = errno;
|
||||
guard.reset();
|
||||
(void)::rmdir(candidate.c_str());
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
"TempDir: fstat failed",
|
||||
err)};
|
||||
}
|
||||
TempDir out{InternalEmpty{}};
|
||||
out.m_path = std::move(candidate);
|
||||
out.m_dev = static_cast<std::uint64_t>(st.st_dev);
|
||||
out.m_ino = static_cast<std::uint64_t>(st.st_ino);
|
||||
Void::Log::debug(
|
||||
"FileSystem", "TempDir: created '{}'", out.m_path.string());
|
||||
return out;
|
||||
}
|
||||
last_err = errno;
|
||||
if (last_err != EEXIST) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(last_err),
|
||||
std::format(
|
||||
"TempDir: failed creating '{}'", candidate.string()),
|
||||
last_err)};
|
||||
}
|
||||
}
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::already_exists,
|
||||
"TempDir: failed to create unique directory after 32 attempts",
|
||||
last_err)};
|
||||
#else
|
||||
(void)base;
|
||||
(void)prefix;
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::unsupported,
|
||||
"TempDir: unsupported platform")};
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
Reference in new issue
Block a user