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
+163
-105
@@ -2,135 +2,193 @@
|
||||
|
||||
#include <Void/Functional/Result.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 <fstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace Void::FileSystem
|
||||
{
|
||||
/// RAII scoped *file* under `std::filesystem::temp_directory_path()`.
|
||||
///
|
||||
/// A uniquely-named empty file is created on construction and removed on
|
||||
/// destruction, unless `keep()` was called. Move-only. Useful for staging
|
||||
/// downloads, copying a shared library to a fresh inode, etc.
|
||||
///
|
||||
/// Construction throws `std::system_error` if the file cannot be created;
|
||||
/// use `TempFile::open(prefix, ext)` for a non-throwing factory.
|
||||
class TempFile
|
||||
{
|
||||
public:
|
||||
|
||||
explicit TempFile(std::string_view prefix = "void_",
|
||||
std::string_view extension = "")
|
||||
: m_path(make_unique_file(prefix, extension))
|
||||
{
|
||||
}
|
||||
/// RAII scoped regular file created atomically (`O_CREAT|O_EXCL|O_NOFOLLOW`, `0600`).
|
||||
class TempFile
|
||||
{
|
||||
public:
|
||||
explicit TempFile(std::string_view prefix = "void_",
|
||||
std::string_view extension = "")
|
||||
{
|
||||
auto created = create_unique_file(
|
||||
std::filesystem::temp_directory_path(), prefix, extension);
|
||||
if (!created.has_value()) {
|
||||
throw std::system_error(
|
||||
std::make_error_code(std::errc::file_exists),
|
||||
created.error().message());
|
||||
}
|
||||
*this = std::move(*created);
|
||||
}
|
||||
|
||||
~TempFile() noexcept
|
||||
{
|
||||
if (!m_path.empty() && !m_keep) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove(m_path, ignore);
|
||||
Void::Log::debug("FileSystem", "TempFile: removed '{}'",
|
||||
m_path.string());
|
||||
}
|
||||
}
|
||||
~TempFile() noexcept { remove_if_owned(); }
|
||||
|
||||
TempFile(const TempFile&) = delete;
|
||||
TempFile& operator=(const TempFile&) = delete;
|
||||
TempFile(const TempFile&) = delete;
|
||||
TempFile& operator=(const TempFile&) = delete;
|
||||
|
||||
TempFile(TempFile&& other) noexcept
|
||||
: m_path(std::exchange(other.m_path, {})),
|
||||
m_keep(std::exchange(other.m_keep, true))
|
||||
{
|
||||
}
|
||||
TempFile(TempFile&& other) noexcept
|
||||
: m_path(std::exchange(other.m_path, {})),
|
||||
m_keep(std::exchange(other.m_keep, true)),
|
||||
m_dev(std::exchange(other.m_dev, 0)),
|
||||
m_ino(std::exchange(other.m_ino, 0))
|
||||
{
|
||||
}
|
||||
|
||||
TempFile& operator=(TempFile&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
if (!m_path.empty() && !m_keep) {
|
||||
std::error_code ignore;
|
||||
std::filesystem::remove(m_path, ignore);
|
||||
}
|
||||
m_path = std::exchange(other.m_path, {});
|
||||
m_keep = std::exchange(other.m_keep, true);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
TempFile& operator=(TempFile&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
remove_if_owned();
|
||||
m_path = std::exchange(other.m_path, {});
|
||||
m_keep = std::exchange(other.m_keep, true);
|
||||
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;
|
||||
}
|
||||
|
||||
/// Persist the file beyond this object's lifetime (no removal on
|
||||
/// destruction). Returns the path for convenience.
|
||||
std::filesystem::path keep() noexcept
|
||||
{
|
||||
m_keep = true;
|
||||
return m_path;
|
||||
}
|
||||
std::filesystem::path keep() noexcept
|
||||
{
|
||||
m_keep = true;
|
||||
return m_path;
|
||||
}
|
||||
|
||||
/// Non-throwing factory.
|
||||
[[nodiscard]] static Void::Result::Result<TempFile,
|
||||
Void::Result::Error>
|
||||
open(std::string_view prefix = "void_",
|
||||
std::string_view extension = "")
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(TempFile{prefix, extension});
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(std::string{e.what()});
|
||||
}
|
||||
}
|
||||
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
|
||||
open(std::string_view prefix = "void_",
|
||||
std::string_view extension = "")
|
||||
{
|
||||
return open_in(
|
||||
std::filesystem::temp_directory_path(), prefix, extension);
|
||||
}
|
||||
|
||||
private:
|
||||
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
|
||||
open_in(const std::filesystem::path& directory,
|
||||
std::string_view prefix = "void_",
|
||||
std::string_view extension = "")
|
||||
{
|
||||
return create_unique_file(directory, prefix, extension);
|
||||
}
|
||||
|
||||
std::filesystem::path m_path;
|
||||
bool m_keep = false;
|
||||
private:
|
||||
struct InternalEmpty {};
|
||||
explicit TempFile(InternalEmpty) noexcept {}
|
||||
|
||||
static std::filesystem::path
|
||||
make_unique_file(std::string_view prefix,
|
||||
std::string_view extension)
|
||||
{
|
||||
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, extension);
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::exists(candidate, ec)) {
|
||||
std::ofstream f(candidate);
|
||||
if (f) {
|
||||
Void::Log::debug("FileSystem",
|
||||
"TempFile: created '{}'",
|
||||
candidate.string());
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw std::system_error(
|
||||
std::make_error_code(std::errc::file_exists),
|
||||
"TempFile: failed to create unique file after 16 attempts");
|
||||
}
|
||||
};
|
||||
std::filesystem::path m_path;
|
||||
bool m_keep = true;
|
||||
std::uint64_t m_dev = 0;
|
||||
std::uint64_t m_ino = 0;
|
||||
|
||||
void remove_if_owned() noexcept
|
||||
{
|
||||
if (m_path.empty() || m_keep) {
|
||||
return;
|
||||
}
|
||||
#ifndef _WIN32
|
||||
struct stat st {};
|
||||
if (::lstat(m_path.c_str(), &st) == 0 && !S_ISLNK(st.st_mode) &&
|
||||
S_ISREG(st.st_mode) &&
|
||||
static_cast<std::uint64_t>(st.st_dev) == m_dev &&
|
||||
static_cast<std::uint64_t>(st.st_ino) == m_ino) {
|
||||
(void)::unlink(m_path.c_str());
|
||||
Void::Log::debug(
|
||||
"FileSystem", "TempFile: removed '{}'", m_path.string());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Result::Result<TempFile, Void::Result::Error>
|
||||
create_unique_file(const std::filesystem::path& base,
|
||||
std::string_view prefix,
|
||||
std::string_view extension)
|
||||
{
|
||||
#ifndef _WIN32
|
||||
if (prefix.find('/') != std::string_view::npos ||
|
||||
prefix.find('\0') != std::string_view::npos ||
|
||||
extension.find('/') != std::string_view::npos ||
|
||||
extension.find('\0') != std::string_view::npos) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
"TempFile: prefix/extension 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, extension);
|
||||
const int fd = ::open(candidate.c_str(),
|
||||
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
|
||||
O_CLOEXEC,
|
||||
0600);
|
||||
if (fd >= 0) {
|
||||
Void::System::OwnedFd guard{fd};
|
||||
struct stat st {};
|
||||
if (::fstat(fd, &st) != 0) {
|
||||
const int err = errno;
|
||||
guard.reset();
|
||||
(void)::unlink(candidate.c_str());
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::map_errno_to_system_code(err),
|
||||
"TempFile: fstat failed",
|
||||
err)};
|
||||
}
|
||||
TempFile out{InternalEmpty{}};
|
||||
out.m_path = std::move(candidate);
|
||||
out.m_keep = false;
|
||||
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", "TempFile: 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("TempFile: failed creating '{}'",
|
||||
candidate.string()),
|
||||
last_err)};
|
||||
}
|
||||
}
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::already_exists,
|
||||
"TempFile: failed to create unique file after 32 attempts",
|
||||
last_err)};
|
||||
#else
|
||||
(void)base;
|
||||
(void)prefix;
|
||||
(void)extension;
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::unsupported,
|
||||
"TempFile: unsupported platform")};
|
||||
#endif
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
Reference in new issue
Block a user