From fcdbc063b27dc9aa942a13762f6c3953e5a511c0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 24 Nov 2026 14:32:05 +0300 Subject: [PATCH] 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) --- include/Void/System/Metrics.hpp | 189 +- include/Void/System/Path.hpp | 655 +++++-- include/Void/System/Process.hpp | 233 ++- include/Void/System/Query.hpp | 214 ++- include/Void/System/TempDir.hpp | 323 +++- include/Void/System/TempFile.hpp | 268 +-- include/Void/System/Types.hpp | 207 ++ src/System/Process.cpp | 1889 ++++++++++++++++--- src/System/module.cmake | 5 +- tests/package/InstalledComponents.cmake | 10 + tests/package/SystemOnly/CMakeLists.txt | 11 + tests/package/SystemOnly/main.cpp | 31 + tests/standalone/System/ProcessStream.cpp | 97 +- tests/standalone/System/SystemHardening.cpp | 296 +++ 14 files changed, 3538 insertions(+), 890 deletions(-) create mode 100644 include/Void/System/Types.hpp create mode 100644 tests/package/SystemOnly/CMakeLists.txt create mode 100644 tests/package/SystemOnly/main.cpp create mode 100644 tests/standalone/System/SystemHardening.cpp diff --git a/include/Void/System/Metrics.hpp b/include/Void/System/Metrics.hpp index da1215d..d7baf69 100644 --- a/include/Void/System/Metrics.hpp +++ b/include/Void/System/Metrics.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -12,113 +14,132 @@ #include #endif -// Generic, app-agnostic process/system resource queries. Used to feed monitors -// (e.g. Void::Resilience::ResourceMonitor) with real samples. Linux is fully -// supported; other platforms return nullopt / 0 so callers degrade gracefully. - namespace Void::SystemInfo { - // ── memory ────────────────────────────────────────────────────────────── - - /// Resident set size (physical memory) of the current process, in bytes. - /// nullopt if it cannot be determined on this platform. - [[nodiscard]] inline std::optional process_memory_bytes() - { +/// Resident set size (physical memory) of the current process, in bytes. +/// nullopt if it cannot be determined on this platform. +[[nodiscard]] inline std::optional process_memory_bytes() +{ #if defined(__linux__) - // /proc/self/statm: "size resident shared text lib data dt" in pages. - std::ifstream statm{"/proc/self/statm"}; - std::uint64_t total_pages = 0, resident_pages = 0; - if (statm >> total_pages >> resident_pages) { - const long page = ::sysconf(_SC_PAGESIZE); - if (page > 0) { - return resident_pages * static_cast(page); - } - } - return std::nullopt; + std::ifstream statm{"/proc/self/statm"}; + std::uint64_t total_pages = 0, resident_pages = 0; + if (statm >> total_pages >> resident_pages) { + const long page = ::sysconf(_SC_PAGESIZE); + if (page > 0) { + return resident_pages * static_cast(page); + } + } + return std::nullopt; #else - return std::nullopt; + return std::nullopt; #endif - } +} - struct SystemMemory { - std::uint64_t total = 0; ///< total physical RAM, bytes - std::uint64_t available = 0; ///< approx. RAM available to new work - }; +struct SystemMemory { + std::uint64_t total = 0; ///< total physical RAM, bytes + std::uint64_t available = 0; ///< approx. RAM available to new work +}; - /// Total and (approximately) available system memory in bytes. - [[nodiscard]] inline std::optional system_memory() - { +/// Total and (approximately) available system memory in bytes. +[[nodiscard]] inline std::optional system_memory() +{ #if defined(__linux__) - struct ::sysinfo info{}; - if (::sysinfo(&info) != 0) { - return std::nullopt; - } - const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; - SystemMemory m; - m.total = static_cast(info.totalram) * unit; - // freeram excludes reclaimable cache/buffers, so this is conservative. - m.available = - (static_cast(info.freeram) + info.bufferram) * unit; - return m; + struct ::sysinfo info{}; + if (::sysinfo(&info) != 0) { + return std::nullopt; + } + const std::uint64_t unit = info.mem_unit ? info.mem_unit : 1; + SystemMemory m; + m.total = static_cast(info.totalram) * unit; + m.available = + (static_cast(info.freeram) + info.bufferram) * unit; + return m; #else - return std::nullopt; + return std::nullopt; #endif - } +} - // ── CPU ───────────────────────────────────────────────────────────────── +struct CpuSample { + double ratio{0.0}; + bool valid{false}; +}; - /// Samples this process's CPU usage between successive calls. usage() - /// returns the fraction of a single core consumed since the previous - /// usage() call (0.0 = idle, 1.0 = one core saturated; may exceed 1.0 on - /// multi-core workloads). The first call establishes the baseline and - /// returns 0. - class CpuSampler - { - public: +/// Samples this process's CPU usage between successive calls. +/// `sample()` explicitly distinguishes real 0.0 from unavailable sampling. +class CpuSampler +{ +public: + explicit CpuSampler( + const Void::Time::MonotonicClock* clock = + &Void::Time::SystemMonotonicClock::instance()) + : clock_(clock != nullptr ? clock + : &Void::Time::SystemMonotonicClock::instance()) + { + reset(); + } - CpuSampler() { reset(); } - - void reset() - { - wall_ = std::chrono::steady_clock::now(); + void reset() + { + wall_ = clock_->now(); + baseline_valid_ = false; #if defined(__linux__) - struct ::tms t{}; - last_ticks_ = (::times(&t) == static_cast<::clock_t>(-1)) - ? 0 - : (t.tms_utime + t.tms_stime); + struct ::tms t{}; + if (::times(&t) != static_cast<::clock_t>(-1)) { + last_ticks_ = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + baseline_valid_ = true; + } #endif - } + } - [[nodiscard]] double usage() - { - const auto now = std::chrono::steady_clock::now(); - const std::chrono::duration wall = now - wall_; - wall_ = now; + [[nodiscard]] CpuSample sample( + const Void::Time::MonotonicClock* override_clock = nullptr) + { + const Void::Time::MonotonicClock* active = + (override_clock != nullptr) ? override_clock : clock_; + const auto now = active->now(); + const std::chrono::duration wall = now - wall_; + wall_ = now; #if defined(__linux__) - const long hz = ::sysconf(_SC_CLK_TCK); - struct ::tms t{}; - if (hz <= 0 || ::times(&t) == static_cast<::clock_t>(-1) || - wall.count() <= 0.0) { - return 0.0; - } - const std::int64_t ticks = t.tms_utime + t.tms_stime; - const double cpu_seconds = - static_cast(ticks - last_ticks_) / - static_cast(hz); - last_ticks_ = ticks; - return cpu_seconds / wall.count(); + const long hz = ::sysconf(_SC_CLK_TCK); + struct ::tms t{}; + if (!baseline_valid_ || hz <= 0 || + ::times(&t) == static_cast<::clock_t>(-1) || wall.count() <= 0.0) { + if (::times(&t) != static_cast<::clock_t>(-1)) { + last_ticks_ = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + baseline_valid_ = true; + } + return CpuSample{0.0, false}; + } + const std::int64_t ticks = static_cast(t.tms_utime) + + static_cast(t.tms_stime); + const std::int64_t delta_ticks = + (ticks >= last_ticks_) ? (ticks - last_ticks_) : 0; + last_ticks_ = ticks; + const double cpu_seconds = + static_cast(delta_ticks) / static_cast(hz); + return CpuSample{cpu_seconds / wall.count(), true}; #else - return 0.0; + (void)wall; + return CpuSample{0.0, false}; #endif - } + } - private: + [[nodiscard]] double usage() + { + const auto s = sample(); + return s.valid ? s.ratio : 0.0; + } - std::chrono::steady_clock::time_point wall_; +private: + const Void::Time::MonotonicClock* clock_; + Void::Time::MonotonicClock::time_point wall_{}; + bool baseline_valid_{false}; #if defined(__linux__) - std::int64_t last_ticks_ = 0; + std::int64_t last_ticks_{0}; #endif - }; +}; } // namespace Void::SystemInfo diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index d9712df..4627bf2 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -1,144 +1,551 @@ #pragma once -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include +#include #include #include #include #include +#include + +#ifndef _WIN32 +#include +#include +#include +#if defined(__linux__) +#include +#endif +#endif namespace Void::FileSystem { - /// Read the entire contents of a file as a string. - /// - /// Failure modes wrapped in `Result`: - /// - File does not exist - /// - File cannot be opened (permissions, etc.) - /// - I/O error during read - [[nodiscard]] inline Void::Result::Result - read_file(const std::filesystem::path& path) - { - std::ifstream f{path, std::ios::binary}; - if (!f.is_open()) { - Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string()); - return Void::Result::fail(std::format( - "FileSystem::read_file: cannot open '{}'", path.string())); - } - std::string content{std::istreambuf_iterator(f), - std::istreambuf_iterator()}; - if (f.bad()) { - Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'", - path.string()); - return Void::Result::fail( - std::format("FileSystem::read_file: I/O error reading '{}'", - path.string())); - } - Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(), - content.size()); - return Void::Result::ok(std::move(content)); - } - /// Write `content` to `path`, overwriting any existing file. - /// - /// This is NOT crash-safe — a process killed mid-write may leave a - /// truncated file. Use `atomic_write` when you need durability. - [[nodiscard]] inline Void::Result::Result - write_file(const std::filesystem::path& path, std::string_view content) - { - std::ofstream f{path, std::ios::binary | std::ios::trunc}; - if (!f.is_open()) { - Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string()); - return Void::Result::fail(std::format( - "FileSystem::write_file: cannot open '{}'", path.string())); - } - f.write(content.data(), static_cast(content.size())); - f.flush(); - if (!f.good()) { - Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'", - path.string()); - return Void::Result::fail( - std::format("FileSystem::write_file: I/O error writing '{}'", - path.string())); - } - return {}; - } +struct ReadFileOptions { + std::size_t max_bytes{16ULL * 1024ULL * 1024ULL}; +}; - /// Crash-safe write: stage `content` in a sibling `.tmp` file, then - /// atomically rename onto `path`. The rename is atomic on POSIX - /// within the same filesystem; std::filesystem::rename uses the - /// platform-appropriate primitive (`ReplaceFileW` on Windows). - /// - /// Note: this does NOT fsync the staged file before rename. A - /// process or kernel crash between write and rename may leave the - /// `.tmp` file behind, but the original `path` is never corrupted. - [[nodiscard]] inline Void::Result::Result - atomic_write(const std::filesystem::path& path, - std::string_view content) - { - auto staging = path; - staging += ".tmp"; - if (auto r = write_file(staging, content); !r) { - return r; - } - std::error_code ec; - std::filesystem::rename(staging, path, ec); - if (ec) { - std::error_code ignore; - std::filesystem::remove(staging, ignore); - Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}", - path.string(), ec.message()); - return Void::Result::fail(std::format( - "FileSystem::atomic_write: rename failed for '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)", - path.string(), content.size()); - return {}; - } +enum class ReplaceDurability { + atomic_visibility, + durable_sync, +}; - /// Create `path` as a directory, including any missing parents. - /// Succeeds (no-op) if `path` already exists as a directory. - [[nodiscard]] inline Void::Result::Result - ensure_directory(const std::filesystem::path& path) - { - std::error_code ec; - if (std::filesystem::is_directory(path, ec)) { - return {}; - } - std::filesystem::create_directories(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "ensure_directory: cannot create '{}': {}", - path.string(), ec.message()); - return Void::Result::fail(std::format( - "FileSystem::ensure_directory: cannot create '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string()); - return {}; - } +enum class ReplacePhase { + validation, + create_stage, + write_stage, + sync_stage, + rename, + sync_parent, +}; - /// Remove a file or directory (recursively for directories). - /// Succeeds (no-op) if the path doesn't exist. - [[nodiscard]] inline Void::Result::Result - remove_path(const std::filesystem::path& path) - { - std::error_code ec; - std::filesystem::remove_all(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "remove_path: cannot remove '{}': {}", - path.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::remove_path: cannot remove '{}': {}", - path.string(), ec.message())); - } - return {}; - } +struct ReplaceFailure { + Void::Result::Error error{}; + ReplacePhase phase{ReplacePhase::validation}; + bool visible_on_disk{false}; + bool durability_unknown{false}; +}; + +/// Optional test hook: return a POSIX errno to inject a failure at `phase`. +using ReplaceFaultHook = std::function(ReplacePhase phase)>; + +struct ReplaceOptions { + ReplaceDurability durability{ReplaceDurability::durable_sync}; + unsigned mode{0644}; + ReplaceFaultHook fault_hook{}; +}; + +namespace detail +{ + +[[nodiscard]] inline std::uint64_t next_temp_entropy() noexcept +{ + static std::atomic counter{0}; + std::uint64_t rnd = 0; +#if defined(__linux__) + if (::getrandom(&rnd, sizeof(rnd), 0) == static_cast(sizeof(rnd))) { + return rnd ^ (counter.fetch_add(1, std::memory_order_relaxed) << 12); + } +#endif + const auto now = static_cast( + std::chrono::steady_clock::now().time_since_epoch().count()); + return now ^ (counter.fetch_add(1, std::memory_order_relaxed) * + 0x9e3779b97f4a7c15ULL); +} + +#ifndef _WIN32 +[[nodiscard]] inline int fsync_eintr(int fd) noexcept +{ + for (;;) { + if (::fsync(fd) == 0) { + return 0; + } + if (errno == EINTR) { + continue; + } + return errno; + } +} +#endif + +} // namespace detail + +/// Read up to `options.max_bytes` from `path` cleanly with typed errors. +[[nodiscard]] inline Void::Result::Result + read_file_bounded(const std::filesystem::path& path, + ReadFileOptions options = {}) +{ +#ifndef _WIN32 + const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + const int err = errno; + Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::read_file: cannot open '{}'", path.string()), + err)}; + } + Void::System::OwnedFd guard{fd}; + + struct stat st {}; + if (::fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { + const auto sz = static_cast(st.st_size); + if (sz > options.max_bytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' ({} bytes) exceeds limit ({})", + path.string(), + sz, + options.max_bytes))}; + } + } + + std::string content; + std::array buf{}; + for (;;) { + const ssize_t n = ::read(fd, buf.data(), buf.size()); + if (n > 0) { + const auto un = static_cast(n); + if (un > options.max_bytes - content.size()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format("FileSystem::read_file: '{}' exceeded limit ({})", + path.string(), + options.max_bytes))}; + } + content.append(buf.data(), un); + } else if (n == 0) { + break; + } else { + if (errno == EINTR) { + continue; + } + const int err = errno; + Void::Log::warn("FileSystem", + "read_file: I/O error reading '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::read_file: I/O error reading '{}'", + path.string()), + err)}; + } + } + Void::Log::debug("FileSystem", + "read_file: '{}' ({} bytes)", + path.string(), + content.size()); + return content; +#else + (void)path; + (void)options; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::read_file: unsupported platform")}; +#endif +} + +/// Read the entire contents of a file as a string (bounded at 16 MiB default). +[[nodiscard]] inline Void::Result::Result + read_file(const std::filesystem::path& path) +{ + return read_file_bounded(path, ReadFileOptions{}); +} + +/// Write `content` to `path`, overwriting any existing file (not crash-safe). +[[nodiscard]] inline Void::Result::Result + write_file(const std::filesystem::path& path, std::string_view content) +{ +#ifndef _WIN32 + const int fd = + ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) { + const int err = errno; + Void::Log::warn("FileSystem", + "write_file: cannot open '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::write_file: cannot open '{}'", path.string()), + err)}; + } + Void::System::OwnedFd guard{fd}; + + std::size_t off = 0; + while (off < content.size()) { + const ssize_t n = + ::write(fd, content.data() + off, content.size() - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + Void::Log::warn("FileSystem", + "write_file: I/O error writing '{}'", + path.string()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::write_file: I/O error writing '{}'", + path.string()), + err)}; + } + off += static_cast(n); + } + return guard.close(); +#else + (void)path; + (void)content; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::write_file: unsupported platform")}; +#endif +} + +/// Atomically stage and replace `path`, distinguishing atomic visibility vs +/// durable commit (`fsync` stage -> `renameat` -> `fsync` parent dir). +[[nodiscard]] inline std::expected replace_file( + const std::filesystem::path& path, + std::span bytes, + ReplaceOptions options = {}) +{ +#ifndef _WIN32 + auto check_fault = [&](ReplacePhase phase, + bool visible, + bool unknown) -> std::optional { + if (options.fault_hook) { + if (const auto injected = options.fault_hook(phase)) { + return ReplaceFailure{ + Void::System::make_system_error( + unknown + ? Void::System::SystemErrorCode::durability_unknown + : Void::System::map_errno_to_system_code(*injected), + std::format("FileSystem::replace_file: injected fault for '{}'", + path.string()), + *injected), + phase, + visible, + unknown}; + } + } + return std::nullopt; + }; + + if (auto f = check_fault(ReplacePhase::validation, false, false)) { + return std::unexpected{std::move(*f)}; + } + + if (path.empty() || !path.has_filename()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: empty path or missing filename"), + ReplacePhase::validation, + false, + false}}; + } + + const std::filesystem::path parent = + path.parent_path().empty() ? std::filesystem::path{"."} + : path.parent_path(); + const std::string target_name = path.filename().string(); + if (target_name == "." || target_name == "..") { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "FileSystem::replace_file: invalid target filename"), + ReplacePhase::validation, + false, + false}}; + } + + const int raw_dir_fd = ::open( + parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (raw_dir_fd < 0) { + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: cannot open parent '{}'", + parent.string()), + err), + ReplacePhase::validation, + false, + false}}; + } + Void::System::OwnedFd dir_fd{raw_dir_fd}; + + if (auto f = check_fault(ReplacePhase::create_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::string tmp_name; + Void::System::OwnedFd tmp_fd; + int last_err = 0; + for (int attempt = 0; attempt < 32; ++attempt) { + tmp_name = std::format( + ".{}.void_tmp_{:016x}", target_name, detail::next_temp_entropy()); + const int fd = ::openat(dir_fd.get(), + tmp_name.c_str(), + O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW | + O_CLOEXEC, + static_cast(options.mode)); + if (fd >= 0) { + tmp_fd.reset(fd); + break; + } + last_err = errno; + if (last_err != EEXIST) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(last_err), + std::format( + "FileSystem::replace_file: cannot create temp in '{}'", + parent.string()), + last_err), + ReplacePhase::create_stage, + false, + false}}; + } + } + if (!tmp_fd.valid()) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::already_exists, + "FileSystem::replace_file: exhausted temp names", + last_err), + ReplacePhase::create_stage, + false, + false}}; + } + + bool cleanup_temp = true; + struct TempCleanup { + int dir_fd{-1}; + const std::string* name{nullptr}; + bool* active{nullptr}; + ~TempCleanup() noexcept + { + if (active != nullptr && *active && dir_fd >= 0 && name != nullptr) { + (void)::unlinkat(dir_fd, name->c_str(), 0); + } + } + } temp_guard{dir_fd.get(), &tmp_name, &cleanup_temp}; + + if (auto f = check_fault(ReplacePhase::write_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + + std::size_t off = 0; + while (off < bytes.size()) { + const ssize_t n = + ::write(tmp_fd.get(), bytes.data() + off, bytes.size() - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: write failed for '{}'", + path.string()), + err), + ReplacePhase::write_stage, + false, + false}}; + } + off += static_cast(n); + } + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_stage, false, false)) { + return std::unexpected{std::move(*f)}; + } + if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::sync_failed, + std::format( + "FileSystem::replace_file: stage fsync failed for '{}'", + path.string()), + err), + ReplacePhase::sync_stage, + false, + false}}; + } + } + + if (auto closed = tmp_fd.close(); !closed.has_value()) { + return std::unexpected{ReplaceFailure{ + std::move(closed.error()), + ReplacePhase::write_stage, + false, + false}}; + } + + if (auto f = check_fault(ReplacePhase::rename, false, false)) { + return std::unexpected{std::move(*f)}; + } + + if (::renameat( + dir_fd.get(), tmp_name.c_str(), dir_fd.get(), target_name.c_str()) != + 0) { + const int err = errno; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + std::format("FileSystem::replace_file: rename failed for '{}'", + path.string()), + err), + ReplacePhase::rename, + false, + false}}; + } + + // Rename succeeded: target is now visible on disk; never unlink target! + cleanup_temp = false; + + if (options.durability == ReplaceDurability::durable_sync) { + if (auto f = check_fault(ReplacePhase::sync_parent, true, true)) { + return std::unexpected{std::move(*f)}; + } + if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) { + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::durability_unknown, + std::format( + "FileSystem::replace_file: parent dir fsync failed after rename for '{}'", + path.string()), + err), + ReplacePhase::sync_parent, + true, + true}}; + } + } + + Void::Log::debug("FileSystem", + "replace_file: '{}' committed ({} bytes)", + path.string(), + bytes.size()); + return {}; +#else + (void)path; + (void)bytes; + (void)options; + return std::unexpected{ReplaceFailure{ + Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "FileSystem::replace_file: unsupported platform"), + ReplacePhase::validation, + false, + false}}; +#endif +} + +[[nodiscard]] inline std::expected replace_file( + const std::filesystem::path& path, + std::string_view content, + ReplaceOptions options = {}) +{ + const auto* ptr = reinterpret_cast(content.data()); + return replace_file(path, std::span{ptr, content.size()}, std::move(options)); +} + +/// Crash-safe write: stages content in a unique temp file and atomically +/// renames onto `path`. Delegates to `replace_file(..., atomic_visibility)` to +/// preserve 1.x atomic replacement behavior safely across concurrent writers. +[[nodiscard]] inline Void::Result::Result + atomic_write(const std::filesystem::path& path, std::string_view content) +{ + auto res = replace_file( + path, + content, + ReplaceOptions{.durability = ReplaceDurability::atomic_visibility}); + if (!res.has_value()) { + Void::Log::warn("FileSystem", + "atomic_write: failed for '{}': {}", + path.string(), + res.error().error.message()); + return std::unexpected{std::move(res.error().error)}; + } + return {}; +} + +/// Create `path` as a directory, including any missing parents. +[[nodiscard]] inline Void::Result::Result + ensure_directory(const std::filesystem::path& path) +{ + std::error_code ec; + if (std::filesystem::is_directory(path, ec)) { + return {}; + } + std::filesystem::create_directories(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "ensure_directory: cannot create '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::ensure_directory: cannot create '{}': {}", + path.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string()); + return {}; +} + +/// Remove a file or directory (recursively for directories). +[[nodiscard]] inline Void::Result::Result + remove_path(const std::filesystem::path& path) +{ + std::error_code ec; + std::filesystem::remove_all(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "remove_path: cannot remove '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::remove_path: cannot remove '{}': {}", + path.string(), + ec.message()))}; + } + return {}; +} } // namespace Void::FileSystem diff --git a/include/Void/System/Process.hpp b/include/Void/System/Process.hpp index 5e9c3f5..626e4d1 100644 --- a/include/Void/System/Process.hpp +++ b/include/Void/System/Process.hpp @@ -2,72 +2,203 @@ #include #include +#include #include +#include #include #include +#include +#include #include #include +#include #include namespace Void::Process { - /// Captured output from a completed subprocess. - struct Output { - int exit_code{0}; - std::string out; ///< captured stdout - std::string err; ///< captured stderr - }; +inline constexpr std::size_t kMaxSpawnInputBytes = 256ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStdoutBytes = 1024ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStderrBytes = 1024ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxLineBytes = 64ULL * 1024ULL; +inline constexpr std::size_t kDefaultMaxStdinBytes = 4ULL * 1024ULL * 1024ULL; - /// Live line callbacks for run_streaming(). Each fires (on the calling - /// thread, as output arrives) with one line of output, newline stripped. - /// Either may be left empty. The full output is still accumulated into the - /// returned Output. - struct StreamCallbacks { - std::function on_stdout; - std::function on_stderr; - }; +/// Captured output from a completed subprocess. +struct Output { + int exit_code{0}; + std::string out; ///< captured stdout + std::string err; ///< captured stderr +}; - /// Run an executable synchronously, capturing stdout and stderr separately. - /// - /// @param executable Path to the binary (searched via PATH when relative). - /// @param args Additional arguments passed after argv[0]. - /// @param stdin_data Data written to the process's stdin before reading. - /// @param timeout Wall-clock limit; zero means no limit. On expiry the - /// process receives SIGTERM and the call returns. - /// - /// Returns an error only when process creation itself fails (pipe or fork - /// failure). A process that exits non-zero still yields a successful Result - /// with the appropriate exit_code. A process whose executable is not found - /// exits with code 127 (POSIX convention). - [[nodiscard]] Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args = {}, - std::string_view stdin_data = {}, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +/// Live line callbacks for run_streaming() and communicate_blocking(). +struct StreamCallbacks { + std::function on_stdout; + std::function on_stderr; +}; - /// Like run(), but invokes `callbacks` line-by-line as stdout/stderr - /// arrive, for progress reporting on long-running or streaming processes. - /// The complete output is still captured into the returned Output. - [[nodiscard]] Void::Result::Result - run_streaming( - const std::filesystem::path& executable, - std::vector args, - const StreamCallbacks& callbacks, - std::string_view stdin_data = {}, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +enum class OverflowPolicy { + fail_and_terminate, + drain_and_truncate, +}; - /// Run a command through /bin/sh -c "command". - [[nodiscard]] Void::Result::Result - shell(std::string_view command, - std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); +enum class EnvMode { + inherit, + allowlist, + explicit_only, +}; - /// Replace the current process image while preserving its PID and inherited - /// environment. Returns only when the platform does not support re-exec or - /// exec fails. - [[nodiscard]] Void::Result::Result - reexec(const std::filesystem::path& executable, - const std::vector& arguments); +struct EnvironmentPolicy { + EnvMode mode{EnvMode::inherit}; + std::vector allowlist{}; + std::vector> set_vars{}; + std::vector unset_keys{}; + std::vector redacted_keys{}; +}; + +struct CaptureLimits { + std::size_t max_stdout_bytes{kDefaultMaxStdoutBytes}; + std::size_t max_stderr_bytes{kDefaultMaxStderrBytes}; + std::size_t max_line_bytes{kDefaultMaxLineBytes}; + std::size_t max_stdin_bytes{kDefaultMaxStdinBytes}; + OverflowPolicy overflow_policy{OverflowPolicy::fail_and_terminate}; +}; + +struct SpawnOptions { + std::filesystem::path executable{}; + std::vector arguments{}; + std::optional working_directory{}; + EnvironmentPolicy environment{}; + bool stdin_pipe{true}; + bool stdout_pipe{true}; + bool stderr_pipe{true}; + bool search_path{true}; + bool new_process_group{true}; + std::chrono::milliseconds kill_grace{std::chrono::milliseconds{2000}}; +}; + +struct ExitStatus { + bool exited{false}; + int code{-1}; + int signal{0}; + int raw_status{0}; +}; + +struct CommunicateResult { + ExitStatus status{}; + std::string out{}; + std::string err{}; + bool stdout_truncated{false}; + bool stderr_truncated{false}; + bool timed_out{false}; + bool cancelled{false}; + bool overflowed{false}; +}; + +class Child +{ +public: + Child() noexcept = default; + Child(long long pid, + long long pgid, + bool owns_process_group, + Void::System::OwnedFd stdin_fd, + Void::System::OwnedFd stdout_fd, + Void::System::OwnedFd stderr_fd, + std::chrono::milliseconds kill_grace) noexcept; + + ~Child() noexcept; + + Child(const Child&) = delete; + Child& operator=(const Child&) = delete; + Child(Child&& other) noexcept; + Child& operator=(Child&& other) noexcept; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] bool running() const noexcept; + [[nodiscard]] long long pid() const noexcept; + [[nodiscard]] long long pgid() const noexcept; + [[nodiscard]] bool owns_process_group() const noexcept; + + [[nodiscard]] int stdin_fd() const noexcept; + [[nodiscard]] int stdout_fd() const noexcept; + [[nodiscard]] int stderr_fd() const noexcept; + + [[nodiscard]] Void::System::OwnedFd take_stdin_fd() noexcept; + [[nodiscard]] Void::System::OwnedFd take_stdout_fd() noexcept; + [[nodiscard]] Void::System::OwnedFd take_stderr_fd() noexcept; + void close_stdin() noexcept; + + [[nodiscard]] Void::Result::Result + send_signal(int sig) noexcept; + + [[nodiscard]] Void::Result::Result + terminate(std::chrono::milliseconds grace = std::chrono::milliseconds{-1}); + + [[nodiscard]] Void::Result::Result, Void::Result::Error> + try_wait(); + + [[nodiscard]] Void::Result::Result + wait_blocking(std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, + std::stop_token stop = {}, + std::chrono::milliseconds kill_grace = std::chrono::milliseconds{-1}); + +private: + long long pid_{-1}; + long long pgid_{-1}; + bool owns_group_{false}; + bool reaped_{true}; + ExitStatus cached_status_{}; + Void::System::OwnedFd stdin_{}; + Void::System::OwnedFd stdout_{}; + Void::System::OwnedFd stderr_{}; + std::chrono::milliseconds kill_grace_{std::chrono::milliseconds{2000}}; + + void reset_and_reap() noexcept; +}; + +[[nodiscard]] Void::Result::Result + spawn(const SpawnOptions& options); + +[[nodiscard]] Void::Result::Result + communicate_blocking(Child& child, + std::string_view stdin_data = {}, + CaptureLimits limits = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}, + std::stop_token stop = {}, + const StreamCallbacks* callbacks = nullptr); + +/// Run an executable synchronously, capturing stdout and stderr separately. +[[nodiscard]] Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args = {}, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Like run(), but invokes `callbacks` line-by-line as stdout/stderr arrive. +[[nodiscard]] Void::Result::Result + run_streaming( + const std::filesystem::path& executable, + std::vector args, + const StreamCallbacks& callbacks, + std::string_view stdin_data = {}, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Run a command through /bin/sh -c "command". +[[nodiscard]] Void::Result::Result + shell(std::string_view command, + std::chrono::milliseconds timeout = std::chrono::milliseconds{0}); + +/// Replace the current process image while preserving its PID and inherited +/// environment. +[[nodiscard]] Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments); + +/// Replace the current process image with explicit open-descriptor cleanup policy. +[[nodiscard]] Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments, + bool close_extra_fds); } // namespace Void::Process diff --git a/include/Void/System/Query.hpp b/include/Void/System/Query.hpp index d004c9c..2cab9b2 100644 --- a/include/Void/System/Query.hpp +++ b/include/Void/System/Query.hpp @@ -1,9 +1,13 @@ #pragma once -#include #include #include +#include +#include +#include +#include +#include #include #include #include @@ -12,113 +16,161 @@ namespace Void::FileSystem { +struct ListDirectoryOptions { + std::size_t max_entries{65536}; +}; + /// Return true if path exists (file, directory, or symlink). [[nodiscard]] inline bool exists(const std::filesystem::path& path) noexcept { - std::error_code ec; - return std::filesystem::exists(path, ec); + std::error_code ec; + return std::filesystem::exists(path, ec); } /// Return the size of a regular file in bytes. [[nodiscard]] inline Void::Result::Result - file_size(const std::filesystem::path& path) + file_size(const std::filesystem::path& path) { - std::error_code ec; - auto sz = std::filesystem::file_size(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(), - ec.message()); - return Void::Result::fail( - std::format("FileSystem::file_size: cannot stat '{}': {}", - path.string(), ec.message())); - } - return Void::Result::ok(sz); + std::error_code ec; + auto sz = std::filesystem::file_size(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "file_size: cannot stat '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::file_size: cannot stat '{}': {}", + path.string(), + ec.message()))}; + } + return Void::Result::ok(sz); } /// Return the last-write time of a path. [[nodiscard]] inline Void::Result:: - Result - last_modified(const std::filesystem::path& path) + Result + last_modified(const std::filesystem::path& path) { - std::error_code ec; - auto t = std::filesystem::last_write_time(path, ec); - if (ec) { - Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(), - ec.message()); - return Void::Result::fail( - std::format("FileSystem::last_modified: cannot stat '{}': {}", - path.string(), ec.message())); - } - return Void::Result::ok(t); + std::error_code ec; + auto t = std::filesystem::last_write_time(path, ec); + if (ec) { + Void::Log::warn("FileSystem", + "last_modified: cannot stat '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::last_modified: cannot stat '{}': {}", + path.string(), + ec.message()))}; + } + return Void::Result::ok(t); } -/// List all entries in a directory (non-recursive, filesystem order). +/// List entries in a directory up to `options.max_entries`. [[nodiscard]] inline Void::Result:: - Result, Void::Result::Error> - list_directory(const std::filesystem::path& path) + Result, Void::Result::Error> + list_directory_bounded(const std::filesystem::path& path, + ListDirectoryOptions options = {}) { - std::error_code ec; - std::vector entries; - for (const auto& entry : - std::filesystem::directory_iterator{path, ec}) { - if (ec) { - break; - } - entries.push_back(entry.path()); - } - if (ec) { - Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}", - path.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::list_directory: cannot iterate '{}': {}", - path.string(), ec.message())); - } - Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)", - path.string(), entries.size()); - return Void::Result::ok(std::move(entries)); + std::error_code ec; + std::vector entries; + for (const auto& entry : std::filesystem::directory_iterator{path, ec}) { + if (ec) { + break; + } + if (entries.size() >= options.max_entries) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "FileSystem::list_directory: '{}' exceeded max_entries ({})", + path.string(), + options.max_entries))}; + } + entries.push_back(entry.path()); + } + if (ec) { + Void::Log::warn("FileSystem", + "list_directory: cannot iterate '{}': {}", + path.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::list_directory: cannot iterate '{}': {}", + path.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "list_directory: '{}' ({} entries)", + path.string(), + entries.size()); + return Void::Result::ok(std::move(entries)); +} + +/// List all entries in a directory (bounded at 65,536 default). +[[nodiscard]] inline Void::Result:: + Result, Void::Result::Error> + list_directory(const std::filesystem::path& path) +{ + return list_directory_bounded(path, ListDirectoryOptions{}); } /// Copy a single file. Set overwrite=true to allow replacing an existing dst. [[nodiscard]] inline Void::Result::Result - copy_file(const std::filesystem::path& src, - const std::filesystem::path& dst, - bool overwrite = false) + copy_file(const std::filesystem::path& src, + const std::filesystem::path& dst, + bool overwrite = false) { - std::error_code ec; - auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing - : std::filesystem::copy_options::none; - std::filesystem::copy_file(src, dst, opts, ec); - if (ec) { - Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::copy_file: '{}' -> '{}': {}", - src.string(), dst.string(), ec.message())); - } - Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(), - dst.string()); - return {}; + std::error_code ec; + auto opts = overwrite ? std::filesystem::copy_options::overwrite_existing + : std::filesystem::copy_options::none; + std::filesystem::copy_file(src, dst, opts, ec); + if (ec) { + Void::Log::warn("FileSystem", + "copy_file: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::copy_file: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "copy_file: '{}' -> '{}'", + src.string(), + dst.string()); + return {}; } /// Recursively copy a directory tree from src to dst. -/// dst must not already exist; its parent must be accessible. [[nodiscard]] inline Void::Result::Result - copy_dir(const std::filesystem::path& src, - const std::filesystem::path& dst) + copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst) { - std::error_code ec; - std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, - ec); - if (ec) { - Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message()); - return Void::Result::fail( - std::format("FileSystem::copy_dir: '{}' -> '{}': {}", - src.string(), dst.string(), ec.message())); - } - Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(), - dst.string()); - return {}; + std::error_code ec; + std::filesystem::copy( + src, dst, std::filesystem::copy_options::recursive, ec); + if (ec) { + Void::Log::warn("FileSystem", + "copy_dir: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()); + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(ec.value()), + std::format("FileSystem::copy_dir: '{}' -> '{}': {}", + src.string(), + dst.string(), + ec.message()))}; + } + Void::Log::debug("FileSystem", + "copy_dir: '{}' -> '{}'", + src.string(), + dst.string()); + return {}; } } // namespace Void::FileSystem diff --git a/include/Void/System/TempDir.hpp b/include/Void/System/TempDir.hpp index 424f651..c00b656 100644 --- a/include/Void/System/TempDir.hpp +++ b/include/Void/System/TempDir.hpp @@ -1,126 +1,251 @@ #pragma once -#include #include +#include +#include -#include -#include #include +#include #include #include #include #include #include -#include #include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#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 - 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 + open(std::string_view prefix = "void_test_") + { + return open_in(std::filesystem::temp_directory_path(), prefix); + } - private: + [[nodiscard]] static Void::Result::Result + 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 counter{0}; - const auto base = std::filesystem::temp_directory_path(); - for (int attempt = 0; attempt < 16; ++attempt) { - const auto seed = - static_cast( - std::chrono::steady_clock::now() - .time_since_epoch() - .count()) ^ - (counter.fetch_add(1, std::memory_order_relaxed) - << 16) ^ - static_cast(std::hash{}( - 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 subdirs; + std::vector 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(st.st_dev) != m_dev || + static_cast(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(fd_st.st_dev) == m_dev && + static_cast(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 + 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(st.st_dev); + out.m_ino = static_cast(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 diff --git a/include/Void/System/TempFile.hpp b/include/Void/System/TempFile.hpp index 3b0599a..21d6faf 100644 --- a/include/Void/System/TempFile.hpp +++ b/include/Void/System/TempFile.hpp @@ -2,135 +2,193 @@ #include #include +#include +#include #include #include #include +#include #include #include -#include #include #include #include #include #include +#ifndef _WIN32 +#include +#include +#include +#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 - 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 + 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 + 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 counter{0}; - const auto base = std::filesystem::temp_directory_path(); - for (int attempt = 0; attempt < 16; ++attempt) { - const auto seed = - static_cast( - std::chrono::steady_clock::now() - .time_since_epoch() - .count()) ^ - (counter.fetch_add(1, std::memory_order_relaxed) << 16) ^ - static_cast( - std::hash{}( - 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(st.st_dev) == m_dev && + static_cast(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 + 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(st.st_dev); + out.m_ino = static_cast(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 diff --git a/include/Void/System/Types.hpp b/include/Void/System/Types.hpp new file mode 100644 index 0000000..0f2505b --- /dev/null +++ b/include/Void/System/Types.hpp @@ -0,0 +1,207 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +namespace Void::System +{ + +enum class SystemErrorCode : std::int32_t { + invalid_argument = 1, + not_found = 2, + permission_denied = 3, + already_exists = 4, + spawn_failed = 5, + exec_failed = 6, + timed_out = 7, + cancelled = 8, + output_limit = 9, + line_limit = 10, + io_error = 11, + sync_failed = 12, + durability_unknown = 13, + limit_exceeded = 14, + busy = 15, + self_join = 16, + unsupported = 17, + unavailable = 18, + internal = 19, +}; + +[[nodiscard]] constexpr Void::Result::ErrorKind + classify_system_error(SystemErrorCode code) noexcept +{ + switch (code) { + case SystemErrorCode::invalid_argument: + return Void::Result::ErrorKind::invalid_argument; + case SystemErrorCode::not_found: + return Void::Result::ErrorKind::not_found; + case SystemErrorCode::already_exists: + case SystemErrorCode::busy: + case SystemErrorCode::self_join: + return Void::Result::ErrorKind::conflict; + case SystemErrorCode::timed_out: + return Void::Result::ErrorKind::timeout; + case SystemErrorCode::cancelled: + return Void::Result::ErrorKind::cancelled; + case SystemErrorCode::output_limit: + case SystemErrorCode::line_limit: + case SystemErrorCode::limit_exceeded: + return Void::Result::ErrorKind::exhausted; + case SystemErrorCode::unsupported: + return Void::Result::ErrorKind::unsupported; + case SystemErrorCode::unavailable: + return Void::Result::ErrorKind::overloaded; + case SystemErrorCode::permission_denied: + case SystemErrorCode::spawn_failed: + case SystemErrorCode::exec_failed: + case SystemErrorCode::io_error: + case SystemErrorCode::sync_failed: + case SystemErrorCode::durability_unknown: + return Void::Result::ErrorKind::io; + case SystemErrorCode::internal: + return Void::Result::ErrorKind::internal; + } + return Void::Result::ErrorKind::internal; +} + +[[nodiscard]] inline SystemErrorCode + map_errno_to_system_code(int sys_errno) noexcept +{ + switch (sys_errno) { + case ENOENT: + return SystemErrorCode::not_found; + case EACCES: + case EPERM: + case EROFS: + return SystemErrorCode::permission_denied; + case EEXIST: + return SystemErrorCode::already_exists; + case ETIMEDOUT: + return SystemErrorCode::timed_out; + case ECANCELED: + return SystemErrorCode::cancelled; + case EBUSY: + return SystemErrorCode::busy; + case EINVAL: + case ENAMETOOLONG: + case EISDIR: + case ENOTDIR: + return SystemErrorCode::invalid_argument; + case ENOSYS: + case EOPNOTSUPP: +#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP) + case ENOTSUP: +#endif + return SystemErrorCode::unsupported; + case EAGAIN: +#if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN) + case EWOULDBLOCK: +#endif + return SystemErrorCode::unavailable; + default: + return SystemErrorCode::io_error; + } +} + +[[nodiscard]] inline Void::Result::Error make_system_error( + SystemErrorCode code, std::string_view message, int sys_errno = 0) +{ + std::string detail; + if (sys_errno != 0) { + detail = std::format("{} (errno={}: {})", + message, + sys_errno, + std::strerror(sys_errno)); + } else { + detail.assign(message); + } + std::error_code sys_ec{}; + if (sys_errno != 0) { + sys_ec = std::error_code{sys_errno, std::generic_category()}; + } + return Void::Result::Error{ + classify_system_error(code), + std::move(detail), + Void::Result::ErrorCode{Void::Result::kSystemErrorDomain, + static_cast(code)}, + sys_ec}; +} + +class OwnedFd +{ +public: + OwnedFd() noexcept = default; + explicit OwnedFd(int fd) noexcept : fd_(fd) {} + + ~OwnedFd() noexcept { reset(); } + + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + OwnedFd(OwnedFd&& other) noexcept + : fd_(std::exchange(other.fd_, -1)) + { + } + + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(); + fd_ = std::exchange(other.fd_, -1); + } + return *this; + } + + [[nodiscard]] bool valid() const noexcept { return fd_ >= 0; } + [[nodiscard]] explicit operator bool() const noexcept { return valid(); } + [[nodiscard]] int get() const noexcept { return fd_; } + + [[nodiscard]] int release() noexcept { return std::exchange(fd_, -1); } + + void reset(int new_fd = -1) noexcept + { + const int old = std::exchange(fd_, new_fd); +#ifndef _WIN32 + if (old >= 0) { + (void)::close(old); + } +#else + (void)old; +#endif + } + + [[nodiscard]] Void::Result::Result close() noexcept + { + const int old = std::exchange(fd_, -1); + if (old < 0) { + return {}; + } +#ifndef _WIN32 + if (::close(old) != 0) { + const int err = errno; + return std::unexpected{make_system_error( + map_errno_to_system_code(err), "OwnedFd::close failed", err)}; + } +#endif + return {}; + } + +private: + int fd_{-1}; +}; + +} // namespace Void::System diff --git a/src/System/Process.cpp b/src/System/Process.cpp index d367714..5136fbd 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -1,350 +1,1647 @@ -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef _WIN32 namespace Void::Process { - Void::Result::Result - run(const std::filesystem::path&, - std::vector, - std::string_view, - std::chrono::milliseconds) - { - return Void::Result::fail("Process::run: not implemented on Windows"); + +Child::Child(long long, + long long, + bool, + Void::System::OwnedFd, + Void::System::OwnedFd, + Void::System::OwnedFd, + std::chrono::milliseconds) noexcept +{ } - Void::Result::Result - run_streaming(const std::filesystem::path&, - std::vector, - const StreamCallbacks&, - std::string_view, - std::chrono::milliseconds) - { - return Void::Result::fail( - "Process::run_streaming: not implemented on Windows"); - } +Child::~Child() noexcept = default; +Child::Child(Child&&) noexcept = default; +Child& Child::operator=(Child&&) noexcept = default; +bool Child::valid() const noexcept { return false; } +bool Child::running() const noexcept { return false; } +long long Child::pid() const noexcept { return -1; } +long long Child::pgid() const noexcept { return -1; } +bool Child::owns_process_group() const noexcept { return false; } +int Child::stdin_fd() const noexcept { return -1; } +int Child::stdout_fd() const noexcept { return -1; } +int Child::stderr_fd() const noexcept { return -1; } +Void::System::OwnedFd Child::take_stdin_fd() noexcept { return {}; } +Void::System::OwnedFd Child::take_stdout_fd() noexcept { return {}; } +Void::System::OwnedFd Child::take_stderr_fd() noexcept { return {}; } +void Child::close_stdin() noexcept {} - Void::Result::Result - shell(std::string_view, std::chrono::milliseconds) - { - return Void::Result::fail("Process::shell: not implemented on Windows"); - } +Void::Result::Result Child::send_signal(int) noexcept +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::send_signal: not implemented on Windows")}; +} + +Void::Result::Result + Child::terminate(std::chrono::milliseconds) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::terminate: not implemented on Windows")}; +} + +Void::Result::Result, Void::Result::Error> + Child::try_wait() +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::try_wait: not implemented on Windows")}; +} + +Void::Result::Result + Child::wait_blocking(std::chrono::milliseconds, + std::stop_token, + std::chrono::milliseconds) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::Child::wait_blocking: not implemented on Windows")}; +} + +Void::Result::Result spawn(const SpawnOptions&) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::spawn: not implemented on Windows")}; +} + +Void::Result::Result + communicate_blocking(Child&, + std::string_view, + CaptureLimits, + std::chrono::milliseconds, + std::stop_token, + const StreamCallbacks*) +{ + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::unsupported, + "Process::communicate_blocking: not implemented on Windows")}; +} + +Void::Result::Result run( + const std::filesystem::path&, + std::vector, + std::string_view, + std::chrono::milliseconds) +{ + return Void::Result::fail("Process::run: not implemented on Windows"); +} + +Void::Result::Result run_streaming( + const std::filesystem::path&, + std::vector, + const StreamCallbacks&, + std::string_view, + std::chrono::milliseconds) +{ + return Void::Result::fail( + "Process::run_streaming: not implemented on Windows"); +} + +Void::Result::Result + shell(std::string_view, std::chrono::milliseconds) +{ + return Void::Result::fail("Process::shell: not implemented on Windows"); +} + +Void::Result::Result + reexec(const std::filesystem::path&, const std::vector&) +{ + return Void::Result::fail("Process::reexec: not implemented on Windows"); +} + +Void::Result::Result reexec( + const std::filesystem::path&, const std::vector&, bool) +{ + return Void::Result::fail("Process::reexec: not implemented on Windows"); +} - Void::Result::Result - reexec(const std::filesystem::path&, - const std::vector&) - { - return Void::Result::fail("Process::reexec: not implemented on Windows"); - } } // namespace Void::Process #else // POSIX -#include -#include -#include -#include - +#include #include #include +#include +#include +#include #include #include +extern char** environ; + namespace Void::Process { - namespace - { - // Read into buf until EAGAIN (no more data right now) or EOF. - // Returns true on EOF, false on EAGAIN. - bool drain(int fd, std::string& buf) - { - char tmp[4096]; - for (;;) { - ssize_t n = ::read(fd, tmp, sizeof(tmp)); - if (n > 0) { - buf.append(tmp, static_cast(n)); - } else if (n == 0) { - return true; // EOF - } else { - if (errno == EINTR) { - continue; - } - // EAGAIN / EWOULDBLOCK: no data right now - return false; - } - } - } +namespace +{ - void set_nonblock(int fd) - { - int flags = ::fcntl(fd, F_GETFL, 0); - if (flags >= 0) { - ::fcntl(fd, F_SETFL, flags | O_NONBLOCK); - } - } +struct ChildFailureMsg { + int phase{0}; + int err{0}; +}; - // Close an fd if it is >= 0, then set it to -1. - void safe_close(int& fd) - { - if (fd >= 0) { - ::close(fd); - fd = -1; - } - } +[[nodiscard]] bool checked_add_size(std::size_t a, + std::size_t b, + std::size_t& out) noexcept +{ + if (a > std::numeric_limits::max() - b) { + return false; + } + out = a + b; + return true; +} - // Emit newly-completed lines from `buf` (from offset `off`), advancing - // `off`. When `flush` is set, any trailing partial line is emitted too. - void emit_lines(const std::string& buf, std::size_t& off, - const std::function& fn, - bool flush) - { - if (!fn) { - off = buf.size(); - return; - } - std::size_t nl; - while ((nl = buf.find('\n', off)) != std::string::npos) { - std::size_t len = nl - off; - if (len > 0 && buf[off + len - 1] == '\r') { - --len; // strip CR of a CRLF - } - fn(std::string_view{buf.data() + off, len}); - off = nl + 1; - } - if (flush && off < buf.size()) { - fn(std::string_view{buf.data() + off, buf.size() - off}); - off = buf.size(); - } - } - } // namespace +[[nodiscard]] std::string sanitize_diag(std::string_view text) +{ + std::string out; + out.reserve(std::min(text.size(), 256)); + for (char ch : text) { + if (out.size() >= 256) { + break; + } + const auto uc = static_cast(ch); + if (uc < 0x20 || uc == 0x7f) { + out.push_back(' '); + } else { + out.push_back(ch); + } + } + return out; +} - namespace - { - Void::Result::Result - run_impl(const std::filesystem::path& executable, - std::vector args, std::string_view stdin_data, - std::chrono::milliseconds timeout, - const StreamCallbacks* cb) - { - // [0] = read end, [1] = write end - int stdin_pipe[2] = {-1, -1}; - int stdout_pipe[2] = {-1, -1}; - int stderr_pipe[2] = {-1, -1}; +[[nodiscard]] bool create_cloexec_pipe(int fds[2]) noexcept +{ + fds[0] = -1; + fds[1] = -1; +#if defined(__linux__) + return ::pipe2(fds, O_CLOEXEC) == 0; +#else + if (::pipe(fds) != 0) { + return false; + } + for (int i = 0; i < 2; ++i) { + const int fl = ::fcntl(fds[i], F_GETFD, 0); + if (fl < 0 || ::fcntl(fds[i], F_SETFD, fl | FD_CLOEXEC) != 0) { + const int err = errno; + (void)::close(fds[0]); + (void)::close(fds[1]); + fds[0] = -1; + fds[1] = -1; + errno = err; + return false; + } + } + return true; +#endif +} - if (::pipe(stdin_pipe) != 0 || ::pipe(stdout_pipe) != 0 || - ::pipe(stderr_pipe) != 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format( - "Process::run: pipe() failed: {}", std::strerror(errno))); - } +[[nodiscard]] bool set_nonblock(int fd) noexcept +{ + const int flags = ::fcntl(fd, F_GETFL, 0); + if (flags < 0) { + return false; + } + return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0; +} - Void::Log::debug("Process", "run: '{}'", executable.string()); +[[nodiscard]] ssize_t write_pipe_nosigpipe(int fd, + const void* buf, + std::size_t len, + int& out_errno) noexcept +{ + sigset_t pending{}; + ::sigemptyset(&pending); + ::sigpending(&pending); + const bool was_pending = (::sigismember(&pending, SIGPIPE) == 1); - std::vector argv; - argv.push_back(executable.c_str()); - for (const auto& a : args) { - argv.push_back(a.c_str()); - } - argv.push_back(nullptr); + sigset_t block{}; + ::sigemptyset(&block); + ::sigaddset(&block, SIGPIPE); + sigset_t old_mask{}; + const int mask_rc = ::pthread_sigmask(SIG_BLOCK, &block, &old_mask); + const bool was_blocked = + (mask_rc == 0) && (::sigismember(&old_mask, SIGPIPE) == 1); - pid_t pid = ::fork(); - if (pid < 0) { - safe_close(stdin_pipe[0]); - safe_close(stdin_pipe[1]); - safe_close(stdout_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[0]); - safe_close(stderr_pipe[1]); - return Void::Result::fail(std::format( - "Process::run: fork() failed: {}", std::strerror(errno))); - } + ssize_t n = -1; + out_errno = 0; + for (;;) { + n = ::write(fd, buf, len); + if (n < 0) { + out_errno = errno; + if (out_errno == EINTR) { + continue; + } + } + break; + } - if (pid == 0) { - // Child process - ::dup2(stdin_pipe[0], STDIN_FILENO); - ::dup2(stdout_pipe[1], STDOUT_FILENO); - ::dup2(stderr_pipe[1], STDERR_FILENO); - ::close(stdin_pipe[0]); - ::close(stdin_pipe[1]); - ::close(stdout_pipe[0]); - ::close(stdout_pipe[1]); - ::close(stderr_pipe[0]); - ::close(stderr_pipe[1]); - ::execvp( - executable.c_str(), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - const_cast(argv.data())); - // execvp only returns on error; 127 is the POSIX convention - ::_exit(127); - } + if (n < 0 && out_errno == EPIPE && !was_pending && !was_blocked) { + const struct timespec zero_wait{0, 0}; + for (;;) { + if (::sigtimedwait(&block, nullptr, &zero_wait) >= 0) { + break; + } + if (errno != EINTR) { + break; + } + } + } - // Parent: close child-side ends - safe_close(stdin_pipe[0]); - safe_close(stdout_pipe[1]); - safe_close(stderr_pipe[1]); + if (mask_rc == 0 && !was_blocked) { + (void)::pthread_sigmask(SIG_SETMASK, &old_mask, nullptr); + } + return n; +} - // Write stdin and close immediately so the child sees EOF - if (!stdin_data.empty()) { - const char* p = stdin_data.data(); - std::size_t remaining = stdin_data.size(); - while (remaining > 0) { - ssize_t n = ::write(stdin_pipe[1], p, remaining); - if (n < 0) { - if (errno == EINTR) { - continue; - } - break; // child likely closed stdin; ignore - } - p += static_cast(n); - remaining -= static_cast(n); - } - } - safe_close(stdin_pipe[1]); +[[nodiscard]] bool parse_decimal_fd(const char* name, int& out_fd) noexcept +{ + if (name == nullptr || name[0] == '\0') { + return false; + } + long long v = 0; + for (const char* p = name; *p != '\0'; ++p) { + if (*p < '0' || *p > '9') { + return false; + } + if (v > (std::numeric_limits::max() - (*p - '0')) / 10) { + return false; + } + v = v * 10 + (*p - '0'); + } + out_fd = static_cast(v); + return true; +} - set_nonblock(stdout_pipe[0]); - set_nonblock(stderr_pipe[0]); +#if defined(__linux__) +struct LinuxDirent64 { + std::uint64_t d_ino; + std::int64_t d_off; + std::uint16_t d_reclen; + std::uint8_t d_type; + char d_name[1]; +}; +#endif - Output output; - bool out_done = false; - bool err_done = false; - std::size_t out_emitted = 0; - std::size_t err_emitted = 0; +// Strictly async-signal-safe close of inherited fds >= 3 except keep_fd (-1 if none). +void close_fds_from_except(int keep_fd) noexcept +{ +#if defined(__linux__) && defined(SYS_close_range) + if (keep_fd < 3) { + if (::syscall(SYS_close_range, 3U, ~0U, 0U) == 0) { + return; + } + } else { + const long r1 = (keep_fd == 3) + ? 0 + : ::syscall(SYS_close_range, + 3U, + static_cast(keep_fd - 1), + 0U); + const long r2 = ::syscall(SYS_close_range, + static_cast(keep_fd + 1), + ~0U, + 0U); + if (r1 == 0 && r2 == 0) { + return; + } + } +#endif - const bool has_timeout = timeout.count() > 0; - const auto deadline = - std::chrono::steady_clock::now() + - (has_timeout ? timeout : std::chrono::milliseconds{30'000}); +#if defined(__linux__) && defined(SYS_getdents64) + for (int pass = 0; pass < 32; ++pass) { + const int dir_fd = + ::open("/proc/self/fd", O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir_fd < 0) { + break; + } + bool closed_any = false; + std::array buf{}; + for (;;) { + const long nread = + ::syscall(SYS_getdents64, dir_fd, buf.data(), buf.size()); + if (nread <= 0) { + break; + } + std::array to_close{}; + std::size_t count = 0; + for (long pos = 0; pos < nread;) { + const auto* ent = + reinterpret_cast(buf.data() + pos); + int fd_num = -1; + if (parse_decimal_fd(ent->d_name, fd_num) && fd_num >= 3 && + fd_num != dir_fd && fd_num != keep_fd) { + if (count < to_close.size()) { + to_close[count++] = fd_num; + } + } + pos += ent->d_reclen; + } + for (std::size_t i = 0; i < count; ++i) { + (void)::close(to_close[i]); + closed_any = true; + } + } + (void)::close(dir_fd); + if (!closed_any) { + return; + } + } +#endif - while (!out_done || !err_done) { - struct pollfd pfds[2]; - int nfds = 0; - if (!out_done) { - pfds[nfds++] = {stdout_pipe[0], POLLIN, 0}; - } - if (!err_done) { - pfds[nfds++] = {stderr_pipe[0], POLLIN, 0}; - } + long max_fd = ::sysconf(_SC_OPEN_MAX); + if (max_fd <= 0 || max_fd > 4096) { + max_fd = 1024; + } + for (int fd = 3; fd < static_cast(max_fd); ++fd) { + if (fd != keep_fd) { + (void)::close(fd); + } + } +} - auto left_ms = - std::chrono::duration_cast( - deadline - std::chrono::steady_clock::now()) - .count(); - if (left_ms <= 0) { - ::kill(pid, SIGTERM); - break; - } +void reset_child_signals() noexcept +{ + sigset_t empty{}; + ::sigemptyset(&empty); + (void)::pthread_sigmask(SIG_SETMASK, &empty, nullptr); - int ret = ::poll(pfds, static_cast(nfds), - static_cast(left_ms)); - if (ret < 0) { - if (errno == EINTR) { - continue; - } - break; - } - if (ret == 0) { - // Wall-clock timeout expired - ::kill(pid, SIGTERM); - break; - } + struct sigaction sa{}; + sa.sa_handler = SIG_DFL; + ::sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + const int limit = std::min(NSIG, 32); + for (int sig = 1; sig < limit; ++sig) { + if (sig == SIGKILL || sig == SIGSTOP) { + continue; + } + (void)::sigaction(sig, &sa, nullptr); + } +} - for (int i = 0; i < nfds; ++i) { - if ((pfds[i].revents & (POLLIN | POLLHUP | POLLERR)) == 0) { - continue; - } - const bool is_out = (pfds[i].fd == stdout_pipe[0]); - bool& done = is_out ? out_done : err_done; - std::string& buf = is_out ? output.out : output.err; - bool eof = drain(pfds[i].fd, buf); - if (cb) { - emit_lines(buf, is_out ? out_emitted : err_emitted, - is_out ? cb->on_stdout : cb->on_stderr, - /*flush=*/false); - } - // POLLHUP means the write end was closed; no more data will - // arrive - if (eof || (pfds[i].revents & (POLLHUP | POLLERR))) { - done = true; - } - } - } +[[nodiscard]] bool redirect_child_fd(int& src_fd, int target_fd) noexcept +{ + if (src_fd < 0) { + return true; + } + if (src_fd == target_fd) { + const int fl = ::fcntl(target_fd, F_GETFD, 0); + if (fl < 0) { + return false; + } + if ((fl & FD_CLOEXEC) != 0 && + ::fcntl(target_fd, F_SETFD, fl & ~FD_CLOEXEC) != 0) { + return false; + } + return true; + } + while (::dup2(src_fd, target_fd) < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + (void)::close(src_fd); + src_fd = -1; + return true; +} - if (cb) { - emit_lines(output.out, out_emitted, cb->on_stdout, - /*flush=*/true); - emit_lines(output.err, err_emitted, cb->on_stderr, - /*flush=*/true); - } +void write_child_failure(int err_fd, int phase, int err) noexcept +{ + ChildFailureMsg msg{phase, err}; + const auto* ptr = reinterpret_cast(&msg); + std::size_t off = 0; + while (off < sizeof(msg)) { + const ssize_t n = ::write(err_fd, ptr + off, sizeof(msg) - off); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (n == 0) { + break; + } + off += static_cast(n); + } +} - safe_close(stdout_pipe[0]); - safe_close(stderr_pipe[0]); +[[nodiscard]] ExitStatus decode_wait_status(int raw) noexcept +{ + ExitStatus st; + st.raw_status = raw; + if (WIFEXITED(raw)) { + st.exited = true; + st.code = WEXITSTATUS(raw); + } else if (WIFSIGNALED(raw)) { + st.exited = false; + st.signal = WTERMSIG(raw); + st.code = -1; + } + return st; +} - int status = 0; - ::waitpid(pid, &status, 0); - output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; +[[nodiscard]] bool signal_target(pid_t pid, + pid_t pgid, + bool owns_group, + int sig, + int& out_errno) noexcept +{ + if (owns_group && pgid > 0) { + if (::kill(-pgid, sig) == 0) { + return true; + } + out_errno = errno; + if (out_errno != ESRCH && out_errno != EPERM) { + return false; + } + } + if (::kill(pid, sig) == 0) { + return true; + } + out_errno = errno; + return false; +} - Void::Log::debug("Process", "run: '{}' exited {}", - executable.string(), output.exit_code); +[[nodiscard]] std::optional + find_env_value(const std::vector& env_strings, + std::string_view key) +{ + for (const auto& entry : env_strings) { + const auto eq = entry.find('='); + if (eq == key.size() && + std::string_view{entry}.substr(0, eq) == key) { + return entry.substr(eq + 1); + } + } + return std::nullopt; +} - return Void::Result::ok(std::move(output)); - } - } // namespace +[[nodiscard]] Void::Result::Result, Void::Result::Error> + build_environment_strings(const EnvironmentPolicy& policy) +{ + std::vector base; + auto validate_key = [](std::string_view k) -> bool { + return !k.empty() && k.find('=') == std::string_view::npos && + k.find('\0') == std::string_view::npos; + }; - Void::Result::Result - run(const std::filesystem::path& executable, - std::vector args, std::string_view stdin_data, - std::chrono::milliseconds timeout) - { - return run_impl(executable, std::move(args), stdin_data, timeout, - nullptr); - } + std::set> unset_set; + for (const auto& k : policy.unset_keys) { + if (!validate_key(k)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid unset environment variable key")}; + } + unset_set.insert(k); + } - Void::Result::Result run_streaming( - const std::filesystem::path& executable, std::vector args, - const StreamCallbacks& callbacks, std::string_view stdin_data, - std::chrono::milliseconds timeout) - { - return run_impl(executable, std::move(args), stdin_data, timeout, - &callbacks); - } + std::set> allow_set; + if (policy.mode == EnvMode::allowlist) { + for (const auto& k : policy.allowlist) { + if (!validate_key(k)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid allowlist environment key")}; + } + allow_set.insert(k); + } + } - Void::Result::Result - shell(std::string_view command, std::chrono::milliseconds timeout) - { - return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); - } + std::unordered_map env_map; + std::vector key_order; - Void::Result::Result - reexec(const std::filesystem::path& executable, - const std::vector& arguments) - { - if (executable.empty()) { - return Void::Result::fail("Process::reexec: executable is empty"); - } - std::vector owned; - owned.reserve(arguments.size() + 1); - owned.push_back(executable.string()); - owned.insert(owned.end(), arguments.begin(), arguments.end()); - std::vector argv; - argv.reserve(owned.size() + 1); - for (auto& argument : owned) { - argv.push_back(argument.data()); - } - argv.push_back(nullptr); - ::execv(executable.c_str(), argv.data()); - return Void::Result::fail(std::format( - "Process::reexec: execv '{}' failed: {}", executable.string(), - std::strerror(errno))); - } + auto put_var = [&](std::string key, std::string val) { + if (!env_map.contains(key)) { + key_order.push_back(key); + } + env_map.insert_or_assign(std::move(key), std::move(val)); + }; + + if (policy.mode != EnvMode::explicit_only && environ != nullptr) { + for (char** p = environ; *p != nullptr; ++p) { + const std::string_view entry{*p}; + const auto eq = entry.find('='); + if (eq == std::string_view::npos) { + continue; + } + const std::string_view k = entry.substr(0, eq); + const std::string_view v = entry.substr(eq + 1); + if (unset_set.contains(k)) { + continue; + } + if (policy.mode == EnvMode::allowlist && !allow_set.contains(k)) { + continue; + } + put_var(std::string{k}, std::string{v}); + } + } + + for (const auto& [k, v] : policy.set_vars) { + if (!validate_key(k) || v.find('\0') != std::string_view::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "SpawnOptions: invalid environment key/value in set_vars")}; + } + put_var(k, v); + } + + base.reserve(key_order.size()); + for (const auto& k : key_order) { + const auto it = env_map.find(k); + if (it != env_map.end()) { + base.push_back(k + "=" + it->second); + } + } + return base; +} + +[[nodiscard]] std::string resolve_executable_path( + const std::filesystem::path& exe, + bool search_path, + const std::vector& env_strings) +{ + const std::string raw = exe.string(); + if (!search_path || raw.find('/') != std::string::npos) { + return raw; + } + + std::optional path_val = find_env_value(env_strings, "PATH"); + if (!path_val.has_value()) { + if (const char* host_path = std::getenv("PATH")) { + path_val = std::string{host_path}; + } + } + if (!path_val.has_value() || path_val->empty()) { + return raw; + } + + std::size_t pos = 0; + while (pos <= path_val->size()) { + const auto colon = path_val->find(':', pos); + const std::string_view dir = + (colon == std::string::npos) + ? std::string_view{*path_val}.substr(pos) + : std::string_view{*path_val}.substr(pos, colon - pos); + const std::filesystem::path cand = + (dir.empty() ? std::filesystem::path{"."} + : std::filesystem::path{dir}) / + raw; + struct stat st {}; + if (::stat(cand.c_str(), &st) == 0 && !S_ISDIR(st.st_mode) && + ::access(cand.c_str(), X_OK) == 0) { + return cand.string(); + } + if (colon == std::string::npos) { + break; + } + pos = colon + 1; + } + return raw; +} + +void emit_lines_from_offset(const std::string& buf, + std::size_t& off, + const std::function& fn, + bool flush) +{ + if (!fn) { + off = buf.size(); + return; + } + std::size_t nl = 0; + while ((nl = buf.find('\n', off)) != std::string::npos) { + std::size_t len = nl - off; + if (len > 0 && buf[off + len - 1] == '\r') { + --len; + } + fn(std::string_view{buf.data() + off, len}); + off = nl + 1; + } + if (flush && off < buf.size()) { + fn(std::string_view{buf.data() + off, buf.size() - off}); + off = buf.size(); + } +} + +} // namespace + +Child::Child(long long pid, + long long pgid, + bool owns_process_group, + Void::System::OwnedFd stdin_fd, + Void::System::OwnedFd stdout_fd, + Void::System::OwnedFd stderr_fd, + std::chrono::milliseconds kill_grace) noexcept + : pid_(pid), + pgid_(pgid), + owns_group_(owns_process_group), + reaped_(pid <= 0), + stdin_(std::move(stdin_fd)), + stdout_(std::move(stdout_fd)), + stderr_(std::move(stderr_fd)), + kill_grace_(kill_grace.count() >= 0 ? kill_grace + : std::chrono::milliseconds{2000}) +{ +} + +Child::~Child() noexcept { reset_and_reap(); } + +Child::Child(Child&& other) noexcept + : pid_(std::exchange(other.pid_, -1)), + pgid_(std::exchange(other.pgid_, -1)), + owns_group_(std::exchange(other.owns_group_, false)), + reaped_(std::exchange(other.reaped_, true)), + cached_status_(other.cached_status_), + stdin_(std::move(other.stdin_)), + stdout_(std::move(other.stdout_)), + stderr_(std::move(other.stderr_)), + kill_grace_(other.kill_grace_) +{ +} + +Child& Child::operator=(Child&& other) noexcept +{ + if (this != &other) { + reset_and_reap(); + pid_ = std::exchange(other.pid_, -1); + pgid_ = std::exchange(other.pgid_, -1); + owns_group_ = std::exchange(other.owns_group_, false); + reaped_ = std::exchange(other.reaped_, true); + cached_status_ = other.cached_status_; + stdin_ = std::move(other.stdin_); + stdout_ = std::move(other.stdout_); + stderr_ = std::move(other.stderr_); + kill_grace_ = other.kill_grace_; + } + return *this; +} + +bool Child::valid() const noexcept { return pid_ > 0; } +bool Child::running() const noexcept { return pid_ > 0 && !reaped_; } +long long Child::pid() const noexcept { return pid_; } +long long Child::pgid() const noexcept { return pgid_; } +bool Child::owns_process_group() const noexcept { return owns_group_; } + +int Child::stdin_fd() const noexcept { return stdin_.get(); } +int Child::stdout_fd() const noexcept { return stdout_.get(); } +int Child::stderr_fd() const noexcept { return stderr_.get(); } + +Void::System::OwnedFd Child::take_stdin_fd() noexcept +{ + return std::move(stdin_); +} + +Void::System::OwnedFd Child::take_stdout_fd() noexcept +{ + return std::move(stdout_); +} + +Void::System::OwnedFd Child::take_stderr_fd() noexcept +{ + return std::move(stderr_); +} + +void Child::close_stdin() noexcept { stdin_.reset(); } + +Void::Result::Result Child::send_signal(int sig) noexcept +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::send_signal: invalid child")}; + } + if (reaped_) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::busy, + "Process::Child::send_signal: child already reaped")}; + } + int err = 0; + if (!signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + sig, + err)) { + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::send_signal failed", + err)}; + } + return {}; +} + +Void::Result::Result, Void::Result::Error> + Child::try_wait() +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::try_wait: invalid child")}; + } + if (reaped_) { + return std::optional{cached_status_}; + } + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, WNOHANG); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return std::optional{cached_status_}; + } + if (w == 0) { + return std::optional{std::nullopt}; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::try_wait: waitpid failed", + err)}; + } +} + +Void::Result::Result + Child::terminate(std::chrono::milliseconds grace) +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::terminate: invalid child")}; + } + if (reaped_) { + return cached_status_; + } + + const auto effective_grace = + (grace.count() >= 0) ? grace : kill_grace_; + + if (auto polled = try_wait(); !polled.has_value()) { + return std::unexpected{polled.error()}; + } else if (polled->has_value()) { + return **polled; + } + + int sig_err = 0; + (void)signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + SIGTERM, + sig_err); + + const auto grace_deadline = + std::chrono::steady_clock::now() + effective_grace; + while (std::chrono::steady_clock::now() < grace_deadline) { + auto polled = try_wait(); + if (!polled.has_value()) { + return std::unexpected{polled.error()}; + } + if (polled->has_value()) { + return **polled; + } + const auto rem = std::chrono::duration_cast( + grace_deadline - std::chrono::steady_clock::now()); + if (rem.count() <= 0) { + break; + } + std::this_thread::sleep_for( + std::min(rem, std::chrono::milliseconds{10})); + } + + if (auto polled = try_wait(); !polled.has_value()) { + return std::unexpected{polled.error()}; + } else if (polled->has_value()) { + return **polled; + } + + (void)signal_target(static_cast(pid_), + static_cast(pgid_), + owns_group_, + SIGKILL, + sig_err); + + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return cached_status_; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::terminate: final waitpid failed", + err)}; + } +} + +Void::Result::Result Child::wait_blocking( + std::chrono::milliseconds timeout, + std::stop_token stop, + std::chrono::milliseconds kill_grace) +{ + if (pid_ <= 0) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::Child::wait_blocking: invalid child")}; + } + if (reaped_) { + return cached_status_; + } + + const bool has_timeout = timeout.count() > 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + + if (!has_timeout && !stop.stop_possible()) { + int raw = 0; + for (;;) { + const pid_t w = ::waitpid(static_cast(pid_), &raw, 0); + if (w == static_cast(pid_)) { + cached_status_ = decode_wait_status(raw); + reaped_ = true; + return cached_status_; + } + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::Child::wait_blocking: waitpid failed", + err)}; + } + } + + for (;;) { + auto polled = try_wait(); + if (!polled.has_value()) { + return std::unexpected{polled.error()}; + } + if (polled->has_value()) { + return **polled; + } + if (stop.stop_requested()) { + auto term = terminate(kill_grace); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::cancelled, + "Process wait cancelled; child terminated")}; + } + if (has_timeout && std::chrono::steady_clock::now() >= deadline) { + auto term = terminate(kill_grace); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::timed_out, + "Process timed out; child terminated")}; + } + auto sleep_dur = std::chrono::milliseconds{10}; + if (has_timeout) { + const auto rem = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + if (rem.count() <= 0) { + continue; + } + sleep_dur = std::min(sleep_dur, rem); + } + std::this_thread::sleep_for(sleep_dur); + } +} + +void Child::reset_and_reap() noexcept +{ + stdin_.reset(); + stdout_.reset(); + stderr_.reset(); + if (pid_ > 0 && !reaped_) { + (void)terminate(kill_grace_); + } + pid_ = -1; + pgid_ = -1; + owns_group_ = false; + reaped_ = true; +} + +Void::Result::Result + spawn(const SpawnOptions& options) +{ + if (options.executable.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: executable path cannot be empty")}; + } + + auto env_res = build_environment_strings(options.environment); + if (!env_res.has_value()) { + return std::unexpected{std::move(env_res.error())}; + } + std::vector env_strings = std::move(*env_res); + + const std::string resolved_exe = resolve_executable_path( + options.executable, options.search_path, env_strings); + if (resolved_exe.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: executable path contains NUL byte")}; + } + + // Check total argv + env bytes against kMaxSpawnInputBytes before fork(). + std::size_t total_input_bytes = resolved_exe.size() + 1; + for (const auto& arg : options.arguments) { + if (arg.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: argument contains NUL byte")}; + } + if (!checked_add_size( + total_input_bytes, arg.size() + 1, total_input_bytes)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: argument size overflow")}; + } + } + for (const auto& e : env_strings) { + if (!checked_add_size( + total_input_bytes, e.size() + 1, total_input_bytes)) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + "Process::spawn: environment size overflow")}; + } + } + if (total_input_bytes > kMaxSpawnInputBytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "Process::spawn: argv+env payload ({} bytes) exceeds limit ({})", + total_input_bytes, + kMaxSpawnInputBytes))}; + } + + std::string cwd_str; + if (options.working_directory.has_value()) { + cwd_str = options.working_directory->string(); + if (cwd_str.empty() || cwd_str.find('\0') != std::string::npos) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::spawn: invalid working_directory")}; + } + } + + // Prepare contiguous C pointer arrays prior to fork(). + std::vector argv_storage; + argv_storage.reserve(options.arguments.size() + 1); + argv_storage.push_back(options.executable.string()); + for (const auto& arg : options.arguments) { + argv_storage.push_back(arg); + } + + std::vector argv_ptrs; + argv_ptrs.reserve(argv_storage.size() + 1); + for (auto& a : argv_storage) { + argv_ptrs.push_back(a.data()); + } + argv_ptrs.push_back(nullptr); + + std::vector env_ptrs; + env_ptrs.reserve(env_strings.size() + 1); + for (auto& e : env_strings) { + env_ptrs.push_back(e.data()); + } + env_ptrs.push_back(nullptr); + + int stdin_p[2]{-1, -1}; + int stdout_p[2]{-1, -1}; + int stderr_p[2]{-1, -1}; + int err_p[2]{-1, -1}; + + auto close_all_pipes = [&]() noexcept { + for (int* pair : {stdin_p, stdout_p, stderr_p, err_p}) { + if (pair[0] >= 0) { + (void)::close(pair[0]); + pair[0] = -1; + } + if (pair[1] >= 0) { + (void)::close(pair[1]); + pair[1] = -1; + } + } + }; + + if ((options.stdin_pipe && !create_cloexec_pipe(stdin_p)) || + (options.stdout_pipe && !create_cloexec_pipe(stdout_p)) || + (options.stderr_pipe && !create_cloexec_pipe(stderr_p)) || + !create_cloexec_pipe(err_p)) { + const int err = errno; + close_all_pipes(); + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: pipe2 failed", + err)}; + } + + const pid_t pid = ::fork(); + if (pid < 0) { + const int err = errno; + close_all_pipes(); + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::spawn_failed, + "Process::spawn: fork failed", + err)}; + } + + if (pid == 0) { + // Strictly async-signal-safe path: no heap allocs, locks, or logging. + if (err_p[0] >= 0) { + (void)::close(err_p[0]); + } + if (stdin_p[1] >= 0) { + (void)::close(stdin_p[1]); + } + if (stdout_p[0] >= 0) { + (void)::close(stdout_p[0]); + } + if (stderr_p[0] >= 0) { + (void)::close(stderr_p[0]); + } + + int err_write = err_p[1]; + if (err_write >= 0 && err_write <= 2) { + const int moved = ::fcntl(err_write, F_DUPFD_CLOEXEC, 3); + if (moved >= 0) { + (void)::close(err_write); + err_write = moved; + } + } + + if (options.new_process_group && ::setpgid(0, 0) != 0) { + const int err = errno; + write_child_failure(err_write, 1, err); + ::_exit(127); + } + + reset_child_signals(); + + if (!redirect_child_fd(stdin_p[0], STDIN_FILENO) || + !redirect_child_fd(stdout_p[1], STDOUT_FILENO) || + !redirect_child_fd(stderr_p[1], STDERR_FILENO)) { + const int err = errno; + write_child_failure(err_write, 3, err); + ::_exit(127); + } + + close_fds_from_except(err_write); + + if (!cwd_str.empty() && ::chdir(cwd_str.c_str()) != 0) { + const int err = errno; + write_child_failure(err_write, 2, err); + ::_exit(127); + } + + ::execve(resolved_exe.c_str(), argv_ptrs.data(), env_ptrs.data()); + const int exec_err = errno; + write_child_failure(err_write, 4, exec_err); + ::_exit(127); + } + + // Parent: close child-side pipe ends immediately. + for (int fd : {err_p[1], stdin_p[0], stdout_p[1], stderr_p[1]}) { + if (fd >= 0) { + (void)::close(fd); + } + } + + ChildFailureMsg child_fail{}; + auto* fail_bytes = reinterpret_cast(&child_fail); + std::size_t fail_got = 0; + while (fail_got < sizeof(child_fail)) { + const ssize_t n = + ::read(err_p[0], fail_bytes + fail_got, sizeof(child_fail) - fail_got); + if (n < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if (n == 0) { + break; + } + fail_got += static_cast(n); + } + (void)::close(err_p[0]); + + if (fail_got == sizeof(child_fail)) { + if (stdin_p[1] >= 0) { + (void)::close(stdin_p[1]); + } + if (stdout_p[0] >= 0) { + (void)::close(stdout_p[0]); + } + if (stderr_p[0] >= 0) { + (void)::close(stderr_p[0]); + } + int raw_status = 0; + while (::waitpid(pid, &raw_status, 0) < 0 && errno == EINTR) { + } + const auto err_code = (child_fail.phase == 4) + ? Void::System::SystemErrorCode::exec_failed + : Void::System::map_errno_to_system_code( + child_fail.err); + const char* phase_desc = (child_fail.phase == 4) + ? "Process::spawn: exec failed" + : (child_fail.phase == 2) + ? "Process::spawn: chdir failed" + : "Process::spawn: child setup failed"; + return std::unexpected{Void::System::make_system_error( + err_code, + std::format("{} '{}'", phase_desc, sanitize_diag(options.executable.string())), + child_fail.err)}; + } + + const long long pgid = options.new_process_group ? pid : ::getpgid(pid); + Void::Log::debug("Process", "spawn: '{}' pid={}", options.executable.string(), pid); + + return Child{ + static_cast(pid), + pgid, + options.new_process_group, + Void::System::OwnedFd{stdin_p[1]}, + Void::System::OwnedFd{stdout_p[0]}, + Void::System::OwnedFd{stderr_p[0]}, + options.kill_grace}; +} + +Void::Result::Result + communicate_blocking(Child& child, + std::string_view stdin_data, + CaptureLimits limits, + std::chrono::milliseconds timeout, + std::stop_token stop, + const StreamCallbacks* callbacks) +{ + if (!child.valid()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::communicate_blocking: invalid child")}; + } + if (stdin_data.size() > limits.max_stdin_bytes) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::limit_exceeded, + std::format( + "Process::communicate_blocking: stdin ({} bytes) exceeds limit ({})", + stdin_data.size(), + limits.max_stdin_bytes))}; + } + + if (child.stdin_fd() >= 0) { + if (stdin_data.empty()) { + child.close_stdin(); + } else { + (void)set_nonblock(child.stdin_fd()); + } + } + if (child.stdout_fd() >= 0) { + (void)set_nonblock(child.stdout_fd()); + } + if (child.stderr_fd() >= 0) { + (void)set_nonblock(child.stderr_fd()); + } + + CommunicateResult res; + std::size_t stdin_offset = 0; + bool stdin_done = (child.stdin_fd() < 0) || stdin_data.empty(); + bool out_done = (child.stdout_fd() < 0); + bool err_done = (child.stderr_fd() < 0); + + std::size_t out_emitted = 0; + std::size_t err_emitted = 0; + std::size_t out_cur_line = 0; + std::size_t err_cur_line = 0; + bool out_line_exceeded = false; + bool err_line_exceeded = false; + bool fail_line_error = false; + bool fail_output_error = false; + std::string limit_msg; + + auto handle_read_chunk = [&](const char* data, + std::size_t len, + bool is_out) -> bool { + std::string& dst = is_out ? res.out : res.err; + const std::size_t max_bytes = + is_out ? limits.max_stdout_bytes : limits.max_stderr_bytes; + bool& truncated = is_out ? res.stdout_truncated : res.stderr_truncated; + std::size_t& cur_line = is_out ? out_cur_line : err_cur_line; + bool& line_exceeded = is_out ? out_line_exceeded : err_line_exceeded; + + // Track line length across non-'\n' bytes. + if (limits.max_line_bytes > 0) { + for (std::size_t i = 0; i < len; ++i) { + if (data[i] == '\n') { + cur_line = 0; + } else { + ++cur_line; + if (cur_line > limits.max_line_bytes) { + line_exceeded = true; + res.overflowed = true; + truncated = true; + if (limits.overflow_policy == + OverflowPolicy::fail_and_terminate) { + fail_line_error = true; + limit_msg = std::format( + "Process {} line exceeded max_line_bytes ({})", + is_out ? "stdout" : "stderr", + limits.max_line_bytes); + return false; + } + } + } + } + } + + const std::size_t remaining_cap = + (dst.size() < max_bytes) ? (max_bytes - dst.size()) : 0; + const std::size_t to_store = std::min(len, remaining_cap); + if (to_store > 0) { + dst.append(data, to_store); + } + if (to_store < len) { + truncated = true; + res.overflowed = true; + if (limits.overflow_policy == OverflowPolicy::fail_and_terminate) { + fail_output_error = true; + limit_msg = std::format( + "Process {} output exceeded limit ({} bytes)", + is_out ? "stdout" : "stderr", + max_bytes); + return false; + } + } + return true; + }; + + const bool has_timeout = timeout.count() > 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + + while (!stdin_done || !out_done || !err_done) { + if (stop.stop_requested()) { + res.cancelled = true; + break; + } + if (has_timeout && std::chrono::steady_clock::now() >= deadline) { + res.timed_out = true; + break; + } + + std::array pfds{}; + nfds_t nfds = 0; + if (!stdin_done && child.stdin_fd() >= 0) { + pfds[nfds++] = {child.stdin_fd(), POLLOUT, 0}; + } + if (!out_done && child.stdout_fd() >= 0) { + pfds[nfds++] = {child.stdout_fd(), POLLIN, 0}; + } + if (!err_done && child.stderr_fd() >= 0) { + pfds[nfds++] = {child.stderr_fd(), POLLIN, 0}; + } + if (nfds == 0) { + break; + } + + int poll_timeout_ms = -1; + if (has_timeout) { + const auto rem = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (rem <= 0) { + res.timed_out = true; + break; + } + poll_timeout_ms = static_cast( + std::min(rem, std::numeric_limits::max())); + } + if (stop.stop_possible()) { + poll_timeout_ms = (poll_timeout_ms < 0) + ? 25 + : std::min(poll_timeout_ms, 25); + } + + const int rc = ::poll(pfds.data(), nfds, poll_timeout_ms); + if (rc < 0) { + if (errno == EINTR) { + continue; + } + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::map_errno_to_system_code(err), + "Process::communicate_blocking: poll failed", + err)}; + } + if (rc == 0) { + continue; + } + + bool abort_loop = false; + for (nfds_t i = 0; i < nfds; ++i) { + const short rev = pfds[i].revents; + if (rev == 0) { + continue; + } + if (pfds[i].fd == child.stdin_fd()) { + if ((rev & (POLLERR | POLLHUP | POLLNVAL)) != 0 && + (rev & POLLOUT) == 0) { + child.close_stdin(); + stdin_done = true; + continue; + } + while (stdin_offset < stdin_data.size()) { + const std::size_t rem = stdin_data.size() - stdin_offset; + int write_err = 0; + const ssize_t n = write_pipe_nosigpipe( + child.stdin_fd(), + stdin_data.data() + stdin_offset, + rem, + write_err); + if (n > 0) { + stdin_offset += static_cast(n); + continue; + } + if (n < 0 && + (write_err == EAGAIN || write_err == EWOULDBLOCK)) { + break; + } + child.close_stdin(); + stdin_done = true; + break; + } + if (stdin_offset >= stdin_data.size()) { + child.close_stdin(); + stdin_done = true; + } + } else { + const bool is_out = (pfds[i].fd == child.stdout_fd()); + std::array buf{}; + bool eof = false; + for (;;) { + const ssize_t n = + ::read(pfds[i].fd, buf.data(), buf.size()); + if (n > 0) { + if (!handle_read_chunk( + buf.data(), + static_cast(n), + is_out)) { + abort_loop = true; + break; + } + if (callbacks != nullptr) { + emit_lines_from_offset( + is_out ? res.out : res.err, + is_out ? out_emitted : err_emitted, + is_out ? callbacks->on_stdout + : callbacks->on_stderr, + false); + } + } else if (n == 0) { + eof = true; + break; + } else { + if (errno == EINTR) { + continue; + } + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + eof = true; + break; + } + } + if (abort_loop) { + break; + } + if (eof || (rev & (POLLHUP | POLLERR | POLLNVAL)) != 0) { + if (is_out) { + out_done = true; + } else { + err_done = true; + } + } + } + } + if (abort_loop) { + break; + } + } + + if (callbacks != nullptr) { + emit_lines_from_offset( + res.out, out_emitted, callbacks->on_stdout, true); + emit_lines_from_offset( + res.err, err_emitted, callbacks->on_stderr, true); + } + + (void)child.take_stdin_fd(); + (void)child.take_stdout_fd(); + (void)child.take_stderr_fd(); + + if (fail_line_error || fail_output_error) { + (void)child.terminate(); + return std::unexpected{Void::System::make_system_error( + fail_line_error ? Void::System::SystemErrorCode::line_limit + : Void::System::SystemErrorCode::output_limit, + limit_msg)}; + } + + if (res.timed_out || res.cancelled) { + auto term = child.terminate(); + if (!term.has_value()) { + return std::unexpected{term.error()}; + } + res.status = *term; + return res; + } + + auto waited = child.wait_blocking( + has_timeout + ? std::max(std::chrono::milliseconds{1}, + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now())) + : std::chrono::milliseconds{0}, + stop); + if (!waited.has_value()) { + if (waited.error().kind() == Void::Result::ErrorKind::timeout) { + res.timed_out = true; + if (auto st = child.try_wait(); st.has_value() && st->has_value()) { + res.status = **st; + } + return res; + } + if (waited.error().kind() == Void::Result::ErrorKind::cancelled) { + res.cancelled = true; + if (auto st = child.try_wait(); st.has_value() && st->has_value()) { + res.status = **st; + } + return res; + } + return std::unexpected{waited.error()}; + } + + res.status = *waited; + return res; +} + +namespace +{ + +Void::Result::Result + run_legacy_impl(const std::filesystem::path& executable, + std::vector args, + std::string_view stdin_data, + std::chrono::milliseconds timeout, + const StreamCallbacks* cb) +{ + SpawnOptions opts; + opts.executable = executable; + opts.arguments = std::move(args); + opts.search_path = true; + opts.new_process_group = true; + + auto spawned = spawn(opts); + if (!spawned.has_value()) { + // Preserve legacy 1.x behavior where exec failure returns exit_code 127. + if (spawned.error().code().domain == Void::Result::kSystemErrorDomain && + spawned.error().code().value == + static_cast( + Void::System::SystemErrorCode::exec_failed)) { + Output out; + out.exit_code = 127; + return out; + } + return std::unexpected{std::move(spawned.error())}; + } + + CaptureLimits limits; + limits.max_stdout_bytes = 64ULL * 1024ULL * 1024ULL; + limits.max_stderr_bytes = 64ULL * 1024ULL * 1024ULL; + limits.max_line_bytes = 0; // Do not fail legacy unbounded line reads + limits.max_stdin_bytes = 64ULL * 1024ULL * 1024ULL; + limits.overflow_policy = OverflowPolicy::drain_and_truncate; + + auto comm = communicate_blocking( + *spawned, stdin_data, limits, timeout, {}, cb); + if (!comm.has_value()) { + return std::unexpected{std::move(comm.error())}; + } + Output out; + out.exit_code = comm->status.exited ? comm->status.code : -1; + out.out = std::move(comm->out); + out.err = std::move(comm->err); + return out; +} + +} // namespace + +Void::Result::Result + run(const std::filesystem::path& executable, + std::vector args, + std::string_view stdin_data, + std::chrono::milliseconds timeout) +{ + return run_legacy_impl( + executable, std::move(args), stdin_data, timeout, nullptr); +} + +Void::Result::Result run_streaming( + const std::filesystem::path& executable, + std::vector args, + const StreamCallbacks& callbacks, + std::string_view stdin_data, + std::chrono::milliseconds timeout) +{ + return run_legacy_impl( + executable, std::move(args), stdin_data, timeout, &callbacks); +} + +Void::Result::Result + shell(std::string_view command, std::chrono::milliseconds timeout) +{ + return run("/bin/sh", {"-c", std::string{command}}, {}, timeout); +} + +Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments) +{ + return reexec(executable, arguments, false); +} + +Void::Result::Result + reexec(const std::filesystem::path& executable, + const std::vector& arguments, + bool close_extra_fds) +{ + if (executable.empty()) { + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::invalid_argument, + "Process::reexec: executable is empty")}; + } + std::vector owned; + owned.reserve(arguments.size() + 1); + owned.push_back(executable.string()); + owned.insert(owned.end(), arguments.begin(), arguments.end()); + std::vector argv; + argv.reserve(owned.size() + 1); + for (auto& argument : owned) { + argv.push_back(argument.data()); + } + argv.push_back(nullptr); + + if (close_extra_fds) { + close_fds_from_except(-1); + } + + ::execv(executable.c_str(), argv.data()); + const int err = errno; + return std::unexpected{Void::System::make_system_error( + Void::System::SystemErrorCode::exec_failed, + std::format("Process::reexec: execv '{}' failed", executable.string()), + err)}; +} } // namespace Void::Process diff --git a/src/System/module.cmake b/src/System/module.cmake index 0d0815a..d94dd64 100644 --- a/src/System/module.cmake +++ b/src/System/module.cmake @@ -1,4 +1,7 @@ void_add_module(System - INTERNAL_DEPS Functional LogState + INTERNAL_DEPS Functional Time LogState EXTERNAL_DEPS Threads::Threads + EXCLUDE_HEADERS + Void/System/AsyncProcess.hpp + Void/System/AsyncWatcher.hpp ) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index e9c6905..52da158 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -116,6 +116,16 @@ if(_has_runtime) run_consumer(RuntimeOnly "${install_prefix}" "RuntimeOnly" ${_no_external_deps}) endif() +has_modules(_has_system System Functional Time LogState) +if(_has_system) + run_consumer(SystemOnly "${install_prefix}" "SystemOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + has_modules(_has_obs_hooks ObservabilityHooks) if(_has_obs_hooks) run_consumer(ObservabilityHooksOnly "${install_prefix}" "ObservabilityHooksOnly" ${_no_external_deps}) diff --git a/tests/package/SystemOnly/CMakeLists.txt b/tests/package/SystemOnly/CMakeLists.txt new file mode 100644 index 0000000..00849b2 --- /dev/null +++ b/tests/package/SystemOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSystemOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS System) + +add_executable(void_system_only_consumer main.cpp) +target_link_libraries(void_system_only_consumer PRIVATE Void::System) +target_compile_features(void_system_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SystemOnlyConsumer COMMAND void_system_only_consumer) diff --git a/tests/package/SystemOnly/main.cpp b/tests/package/SystemOnly/main.cpp new file mode 100644 index 0000000..be4524a --- /dev/null +++ b/tests/package/SystemOnly/main.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include + +#include + +int main() +{ + auto tmp = Void::FileSystem::TempDir::open("void_pkg_sys_"); + if (!tmp.has_value()) { + std::cerr << tmp.error().message() << '\n'; + return 1; + } + const auto cfg = tmp->path() / "item.txt"; + if (!Void::FileSystem::replace_file(cfg, "ok").has_value()) { + return 2; + } + auto content = Void::FileSystem::read_file_bounded(cfg); + if (!content.has_value() || *content != "ok") { + return 3; + } + Void::Process::SpawnOptions opts; + opts.executable = "/nonexistent/void/binary"; + opts.search_path = false; + auto bad = Void::Process::spawn(opts); + if (bad.has_value()) { + return 4; + } + return 0; +} diff --git a/tests/standalone/System/ProcessStream.cpp b/tests/standalone/System/ProcessStream.cpp index 2a8e355..acf7b30 100644 --- a/tests/standalone/System/ProcessStream.cpp +++ b/tests/standalone/System/ProcessStream.cpp @@ -7,60 +7,59 @@ namespace { - using Void::Testing::Test; - struct ProcessStream : Void::Testing::Suite { - // stdout lines are delivered to the callback as they arrive, and - // the full output is still captured. - Test streams_stdout_lines() - { - std::vector lines; - Void::Process::StreamCallbacks cb; - cb.on_stdout = [&](std::string_view l) { - lines.emplace_back(l); - }; +using Void::Testing::Test; - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'a\\nb\\nc\\n'"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(r->exit_code, 0); +struct ProcessStream : Void::Testing::Suite { + Test streams_stdout_lines() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; - const std::vector expected{"a", "b", "c"}; - Void::Testing::expect(lines == expected); - Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); - } + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, {"lines", "a", "b", "c"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(r->exit_code, 0); - // A trailing partial line (no newline) is flushed at EOF. - Test flushes_trailing_partial_line() - { - std::vector lines; - Void::Process::StreamCallbacks cb; - cb.on_stdout = [&](std::string_view l) { - lines.emplace_back(l); - }; + const std::vector expected{"a", "b", "c"}; + Void::Testing::expect(lines == expected); + Void::Testing::expect_eq(r->out, std::string{"a\nb\nc\n"}); + } - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'no-newline'"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(lines.size(), std::size_t{1}); - Void::Testing::expect_eq(lines.at(0), - std::string{"no-newline"}); - } + Test flushes_trailing_partial_line() + { + std::vector lines; + Void::Process::StreamCallbacks cb; + cb.on_stdout = [&](std::string_view l) { + lines.emplace_back(l); + }; - // stderr is routed to its own callback. - Test streams_stderr_separately() - { - std::vector errs; - Void::Process::StreamCallbacks cb; - cb.on_stderr = [&](std::string_view l) { - errs.emplace_back(l); - }; + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, + {"lines", "--no-newline", "no-newline"}, + cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(lines.size(), std::size_t{1}); + Void::Testing::expect_eq(lines.at(0), std::string{"no-newline"}); + } + + Test streams_stderr_separately() + { + std::vector errs; + Void::Process::StreamCallbacks cb; + cb.on_stderr = [&](std::string_view l) { + errs.emplace_back(l); + }; + + auto r = Void::Process::run_streaming( + VOID_PROCESS_HELPER_PATH, {"lines", "--stderr", "oops"}, cb); + Void::Testing::expect(r.has_value()); + Void::Testing::expect_eq(errs.size(), std::size_t{1}); + Void::Testing::expect_eq(errs.at(0), std::string{"oops"}); + } +}; - auto r = Void::Process::run_streaming( - "/bin/sh", {"-c", "printf 'oops\\n' 1>&2"}, cb); - Void::Testing::expect(r.has_value()); - Void::Testing::expect_eq(errs.size(), std::size_t{1}); - Void::Testing::expect_eq(errs.at(0), std::string{"oops"}); - } - }; } // namespace diff --git a/tests/standalone/System/SystemHardening.cpp b/tests/standalone/System/SystemHardening.cpp new file mode 100644 index 0000000..224e6e6 --- /dev/null +++ b/tests/standalone/System/SystemHardening.cpp @@ -0,0 +1,296 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +} // namespace + +Void::Testing::Test system_spawn_distinguishes_exec_failure_and_hygiene() +{ + // 1. spawn() returns exec_failed distinct from a child exiting 127. + Void::Process::SpawnOptions missing_opts; + missing_opts.executable = "/nonexistent/void/missing_binary"; + missing_opts.search_path = false; + auto missing_res = Void::Process::spawn(missing_opts); + require(!missing_res.has_value()); + expect_eq(missing_res.error().code().domain, Void::Result::kSystemErrorDomain); + expect_eq(missing_res.error().code().value, + static_cast(Void::System::SystemErrorCode::exec_failed)); + + Void::Process::SpawnOptions exit127_opts; + exit127_opts.executable = VOID_PROCESS_HELPER_PATH; + exit127_opts.arguments = {"exit", "127"}; + auto exit127_child = Void::Process::spawn(exit127_opts); + require(exit127_child.has_value()); + auto exit127_res = Void::Process::communicate_blocking(*exit127_child); + require(exit127_res.has_value()); + expect(exit127_res->status.exited); + expect_eq(exit127_res->status.code, 127); + + // 2. Non-CLOEXEC inherited fds in parent are never leaked across spawn(). + int dummy_pipe[2]{-1, -1}; + require(::pipe(dummy_pipe) == 0); + Void::System::OwnedFd leak0{dummy_pipe[0]}; + Void::System::OwnedFd leak1{dummy_pipe[1]}; + + Void::Process::SpawnOptions fd_opts; + fd_opts.executable = VOID_PROCESS_HELPER_PATH; + fd_opts.arguments = {"check-fds"}; + auto fd_child = Void::Process::spawn(fd_opts); + require(fd_child.has_value()); + auto fd_res = Void::Process::communicate_blocking(*fd_child); + require(fd_res.has_value()); + expect_eq(fd_res->out, std::string{"clean\n"}); + + // 3. EnvironmentPolicy allowlist & explicit_only + working_directory. + Void::FileSystem::TempDir tmp{"void_sys_cwd_"}; + Void::Process::SpawnOptions env_opts; + env_opts.executable = VOID_PROCESS_HELPER_PATH; + env_opts.arguments = {"env-dump"}; + env_opts.environment.mode = Void::Process::EnvMode::explicit_only; + env_opts.environment.set_vars = {{"VOID_Z", "two"}, {"VOID_A", "one"}}; + auto env_child = Void::Process::spawn(env_opts); + require(env_child.has_value()); + auto env_res = Void::Process::communicate_blocking(*env_child); + require(env_res.has_value()); + expect_eq(env_res->out, std::string{"VOID_A=one\nVOID_Z=two\n"}); + + Void::Process::SpawnOptions cwd_opts; + cwd_opts.executable = VOID_PROCESS_HELPER_PATH; + cwd_opts.arguments = {"cwd"}; + cwd_opts.working_directory = tmp.path(); + auto cwd_child = Void::Process::spawn(cwd_opts); + require(cwd_child.has_value()); + auto cwd_res = Void::Process::communicate_blocking(*cwd_child); + require(cwd_res.has_value()); + expect_eq(cwd_res->out, std::filesystem::canonical(tmp.path()).string() + "\n"); + + // 4. argv+env limit rejected cleanly before fork(). + Void::Process::SpawnOptions big_opts; + big_opts.executable = VOID_PROCESS_HELPER_PATH; + big_opts.arguments = {std::string(Void::Process::kMaxSpawnInputBytes + 64, 'x')}; + auto big_res = Void::Process::spawn(big_opts); + require(!big_res.has_value()); + expect_eq(big_res.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); +} + +Void::Testing::Test system_communicate_duplex_limits_escalation_and_cancel() +{ + // 1. Full-duplex simultaneous 256 KiB stdin + stdout + stderr without deadlock. + const std::size_t payload_bytes = 256ULL * 1024ULL; + const std::string big_in(payload_bytes, 'i'); + Void::Process::SpawnOptions sim_opts; + sim_opts.executable = VOID_PROCESS_HELPER_PATH; + sim_opts.arguments = {"simultaneous-io", std::to_string(payload_bytes)}; + auto sim_child = Void::Process::spawn(sim_opts); + require(sim_child.has_value()); + Void::Process::CaptureLimits sim_lim; + sim_lim.max_line_bytes = 512ULL * 1024ULL; + auto sim_res = Void::Process::communicate_blocking( + *sim_child, + big_in, + sim_lim, + std::chrono::milliseconds{0}); // explicit zero-timeout completes normally + require(sim_res.has_value()); + expect(!sim_res->timed_out); + expect_eq(sim_res->status.code, 0); + expect_eq(sim_res->out.size(), payload_bytes); + expect_eq(sim_res->err.size(), payload_bytes); + + // 2. Capture limit fail_and_terminate vs drain_and_truncate, plus line_limit. + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "0"}; + auto ch = Void::Process::spawn(flood_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 512; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::output_limit)); + } + { + Void::Process::SpawnOptions flood_opts; + flood_opts.executable = VOID_PROCESS_HELPER_PATH; + flood_opts.arguments = {"flood", "4096", "256"}; + auto ch = Void::Process::spawn(flood_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_stdout_bytes = 512; + lim.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(res.has_value()); + expect(res->overflowed); + expect(res->stdout_truncated); + expect_eq(res->out.size(), std::size_t{512}); + expect_eq(res->err.size(), std::size_t{256}); + } + { + Void::Process::SpawnOptions long_opts; + long_opts.executable = VOID_PROCESS_HELPER_PATH; + long_opts.arguments = {"long-line", "2048"}; + auto ch = Void::Process::spawn(long_opts); + require(ch.has_value()); + Void::Process::CaptureLimits lim; + lim.max_line_bytes = 128; + lim.overflow_policy = Void::Process::OverflowPolicy::fail_and_terminate; + auto res = Void::Process::communicate_blocking(*ch, {}, lim); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::line_limit)); + } + + // 3. SIGTERM-ignoring child escalates to SIGKILL within short kill_grace. + { + Void::Process::SpawnOptions sig_opts; + sig_opts.executable = VOID_PROCESS_HELPER_PATH; + sig_opts.arguments = {"ignore-sigterm", "10000"}; + sig_opts.kill_grace = std::chrono::milliseconds{40}; + auto ch = Void::Process::spawn(sig_opts); + require(ch.has_value()); + auto res = Void::Process::communicate_blocking( + *ch, {}, Void::Process::CaptureLimits{}, std::chrono::milliseconds{80}); + require(res.has_value()); + expect(res->timed_out); + expect(!res->status.exited); + expect_eq(res->status.signal, SIGKILL); + } + + // 4. Stop token cancels child cleanly. + { + Void::Process::SpawnOptions wait_opts; + wait_opts.executable = VOID_PROCESS_HELPER_PATH; + wait_opts.arguments = {"ignore-sigterm", "10000"}; + wait_opts.kill_grace = std::chrono::milliseconds{20}; + auto ch = Void::Process::spawn(wait_opts); + require(ch.has_value()); + std::stop_source ss; + ss.request_stop(); + auto res = ch->wait_blocking( + std::chrono::milliseconds{5000}, + ss.get_token(), + std::chrono::milliseconds{20}); + require(!res.has_value()); + expect_eq(res.error().code().value, + static_cast(Void::System::SystemErrorCode::cancelled)); + } +} + +Void::Testing::Test system_replace_file_temp_ownership_and_metrics() +{ + Void::FileSystem::TempDir tmp{"void_sys_fs_"}; + struct stat tmp_st {}; + require(::lstat(tmp.path().c_str(), &tmp_st) == 0); + expect_eq(static_cast(tmp_st.st_mode & 0777), 0700U); + + const auto target = tmp / "state.cfg"; + require(Void::FileSystem::replace_file(target, "initial").has_value()); + expect_eq(Void::FileSystem::read_file(target).value(), std::string{"initial"}); + + // Fault during write/sync/rename removes ONLY owned temp and leaves target intact. + for (auto phase : {Void::FileSystem::ReplacePhase::write_stage, + Void::FileSystem::ReplacePhase::sync_stage, + Void::FileSystem::ReplacePhase::rename}) { + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [phase](Void::FileSystem::ReplacePhase p) + -> std::optional { + return (p == phase) ? std::optional{EIO} : std::nullopt; + }; + auto fail_res = Void::FileSystem::replace_file(target, "bad", opts); + require(!fail_res.has_value()); + expect(!fail_res.error().visible_on_disk); + expect(!fail_res.error().durability_unknown); + expect_eq(Void::FileSystem::read_file(target).value(), + std::string{"initial"}); + } + + // Post-rename parent sync failure reports visible_on_disk + durability_unknown. + { + Void::FileSystem::ReplaceOptions opts; + opts.fault_hook = [](Void::FileSystem::ReplacePhase p) + -> std::optional { + return (p == Void::FileSystem::ReplacePhase::sync_parent) + ? std::optional{EIO} + : std::nullopt; + }; + auto sync_res = Void::FileSystem::replace_file(target, "committed", opts); + require(!sync_res.has_value()); + expect(sync_res.error().visible_on_disk); + expect(sync_res.error().durability_unknown); + expect_eq(Void::FileSystem::read_file(target).value(), + std::string{"committed"}); + } + + // Bounded read_file & list_directory. + auto small_read = Void::FileSystem::read_file_bounded( + target, Void::FileSystem::ReadFileOptions{.max_bytes = 4}); + require(!small_read.has_value()); + expect_eq(small_read.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); + + (void)Void::FileSystem::write_file(tmp / "extra1.txt", "1"); + (void)Void::FileSystem::write_file(tmp / "extra2.txt", "2"); + auto bounded_list = Void::FileSystem::list_directory_bounded( + tmp.path(), Void::FileSystem::ListDirectoryOptions{.max_entries = 1}); + require(!bounded_list.has_value()); + expect_eq(bounded_list.error().code().value, + static_cast(Void::System::SystemErrorCode::limit_exceeded)); + + // TempFile 0600 mode & symlink-swap refusal (destructor must not delete swap target). + const auto victim = tmp / "victim.txt"; + require(Void::FileSystem::write_file(victim, "keep_me").has_value()); + std::filesystem::path tf_path; + { + auto tf = Void::FileSystem::TempFile::open_in(tmp.path(), "tf_"); + require(tf.has_value()); + tf_path = tf->path(); + struct stat tf_st {}; + require(::lstat(tf_path.c_str(), &tf_st) == 0); + expect_eq(static_cast(tf_st.st_mode & 0777), 0600U); + + // Replace tf_path with symlink to victim; ~TempFile must NOT unlink it! + std::filesystem::remove(tf_path); + std::filesystem::create_symlink(victim, tf_path); + } + expect(std::filesystem::exists(victim)); + expect(std::filesystem::is_symlink(tf_path)); + std::filesystem::remove(tf_path); + + // CpuSampler::sample with injected ManualClock distinguishes valid vs zero interval. + Void::Time::ManualClock clock; + Void::SystemInfo::CpuSampler sampler{&clock}; + expect(!sampler.sample().valid); // zero elapsed delta on ManualClock + (void)clock.advance(std::chrono::seconds{1}); + const auto sample = sampler.sample(); + expect(sample.valid); + expect(sample.ratio >= 0.0); +}