diff --git a/include/Void/Archive/Archive.hpp b/include/Void/Archive/Archive.hpp index f708045..22b4318 100644 --- a/include/Void/Archive/Archive.hpp +++ b/include/Void/Archive/Archive.hpp @@ -1,11 +1,19 @@ #pragma once +#include #include #include +#include #include #include #include +#include +#include +#include +#include +#include +#include namespace Void::Archive { @@ -21,12 +29,176 @@ namespace Void::Archive std::uint64_t bytes{0}; }; - /// Extract a tar/tar.zst archive without invoking an external process. - /// Only regular files and directories are accepted. Absolute/traversal - /// paths, links, special files, duplicates and configured size/count - /// overages fail the whole operation. + /// Extract a tar/tar.zst archive incrementally into `destination` without + /// invoking an external process. Preserved 1.x incremental API; callers + /// requiring all-or-nothing directory visibility should use + /// `extract_staged` + `StagedTree::publish`. [[nodiscard]] Void::Result::Result extract(const std::filesystem::path& archivePath, const std::filesystem::path& destination, const ExtractionOptions& options = {}); + + /// Caller-driven bounded tar/tar.zst reader. Maintains one active entry at + /// a time; callers must drain (`read_chunk` returning 0) or call + /// `skip_entry()` before advancing with `next_entry()`. + class Reader + { + public: + + ~Reader(); + Reader(Reader&&) noexcept; + Reader& operator=(Reader&&) noexcept; + Reader(const Reader&) = delete; + Reader& operator=(const Reader&) = delete; + + [[nodiscard]] static Void::Result::Result open( + ByteSource& source, ReadLimits limits = {}, + std::stop_token stop = {}, + std::optional deadline = + std::nullopt, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + [[nodiscard]] static Void::Result::Result open_file( + const std::filesystem::path& archive_path, + ReadLimits limits = {}, std::stop_token stop = {}, + std::optional deadline = + std::nullopt, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + /// Advance to the next archive entry. Returns std::nullopt on clean + /// EOF. + [[nodiscard]] Void::Result::Result> + next_entry(); + + /// Read up to dst.size() decompressed bytes of the active regular + /// file entry. Returns 0 on entry EOF. + [[nodiscard]] Void::Result::Result + read_chunk(std::span dst); + + /// Drain and discard remaining bytes of the active entry while + /// still accounting decompressed bytes against policy limits. + [[nodiscard]] Void::Result::Result skip_entry(); + + [[nodiscard]] std::size_t entries_seen() const noexcept; + [[nodiscard]] std::uint64_t total_decompressed_bytes() const noexcept; + [[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept; + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit Reader(std::unique_ptr impl) noexcept; + }; + + /// Bounded metadata listing of archive entries. Normal mode (`forensic = + /// false`) rejects unsafe/duplicate/conflicting entries. Opt-in forensic + /// mode reports rejected entries without writing to disk. + [[nodiscard]] Void::Result::Result> + list_entries(ByteSource& source, ReadLimits limits = {}, + bool forensic = false); + + [[nodiscard]] Void::Result::Result> + list_entries(const std::filesystem::path& archive_path, + ReadLimits limits = {}, bool forensic = false); + + /// Move-only handle owning an unpublished private staging directory beneath + /// a pinned parent directory. Unlinks only names under its staging + /// descriptor without following links if destroyed before publication. + class StagedTree + { + public: + + StagedTree() noexcept = default; + ~StagedTree() noexcept; + StagedTree(StagedTree&&) noexcept; + StagedTree& operator=(StagedTree&&) noexcept; + StagedTree(const StagedTree&) = delete; + StagedTree& operator=(const StagedTree&) = delete; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] bool published() const noexcept; + [[nodiscard]] std::string_view staging_id() const noexcept; + [[nodiscard]] const std::filesystem::path& + staging_root() const noexcept; + [[nodiscard]] const std::filesystem::path& + tree_path() const noexcept; + [[nodiscard]] std::size_t entries() const noexcept; + [[nodiscard]] std::uint64_t bytes() const noexcept; + [[nodiscard]] const std::vector& + inventory() const noexcept; + + /// Publish the staged tree into a previously absent immediate child + /// of the pinned parent directory using atomic no-replace rename + /// (`renameat2(..., RENAME_NOREPLACE)`). Never overwrites existing + /// directories or falls back to a racy existence check. + [[nodiscard]] Void::Result::Result + publish(std::string_view new_child_name); + + /// Explicitly discard an unpublished staging tree. + [[nodiscard]] Void::Result::Result discard(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit StagedTree(std::unique_ptr impl) noexcept; + + friend Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options); + friend Void::Result::Result + extract_staged_isolated( + const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options); + }; + + /// Extract a tar/tar.zst stream into an exclusive 0700 staging directory + /// beneath `parent_directory`, fsync files and directories bottom-up, write + /// a bounded completion inventory, and return an unpublished StagedTree. + [[nodiscard]] Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options = {}); + + [[nodiscard]] Void::Result::Result + extract_staged(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options = {}); + + /// Remove abandoned staging directories under `parent_directory` that carry + /// a valid exclusive operation marker owned by the current user and are at + /// least `min_age` old. Never touches directories without a valid marker. + [[nodiscard]] Void::Result::Result + cleanup_stale_staging(const std::filesystem::path& parent_directory, + std::chrono::seconds min_age = + std::chrono::seconds{300}); + + /// Create a bounded, optionally reproducible tar or tar.zst archive from + /// regular file and directory entries. Sorts normalized paths, rejects + /// duplicates/conflicts, and opens source files with O_NOFOLLOW. + [[nodiscard]] Void::Result::Result + create_archive(ByteSink& sink, std::span entries, + const CreationOptions& options = {}); + + [[nodiscard]] Void::Result::Result + create_archive(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options = {}); + + /// Hardened untrusted-input profile: extracts the archive in an isolated + /// System child process with bounded execution time and RSS checks, then + /// independently verifies the staged tree and inventory in the parent + /// before returning StagedTree. + [[nodiscard]] Void::Result::Result + extract_staged_isolated(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options); + + /// Entry point invoked by the isolated archive decoder worker binary. + [[nodiscard]] int run_isolated_worker_main(int argc, char** argv); + } // namespace Void::Archive diff --git a/include/Void/Archive/Types.hpp b/include/Void/Archive/Types.hpp new file mode 100644 index 0000000..44de549 --- /dev/null +++ b/include/Void/Archive/Types.hpp @@ -0,0 +1,342 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Archive +{ + enum class ArchiveErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + unsafe_entry = 2, + unsupported_format = 3, + corrupt_archive = 4, + limit_exceeded = 5, + permission_denied = 6, + no_space = 7, + io_error = 8, + cancelled = 9, + timeout = 10, + unknown_publication = 11, + unsupported_capability = 12, + already_exists = 13, + conflict = 14, + isolation_failed = 15 + }; + + [[nodiscard]] inline Void::Result::Error + make_archive_error(ArchiveErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ArchiveErrorCode::none: + kind = ErrorKind::internal; + break; + case ArchiveErrorCode::invalid_argument: + case ArchiveErrorCode::unsafe_entry: + kind = ErrorKind::invalid_argument; + break; + case ArchiveErrorCode::unsupported_format: + case ArchiveErrorCode::unsupported_capability: + kind = ErrorKind::unsupported; + break; + case ArchiveErrorCode::corrupt_archive: + kind = ErrorKind::corrupt; + break; + case ArchiveErrorCode::limit_exceeded: + case ArchiveErrorCode::no_space: + kind = ErrorKind::exhausted; + break; + case ArchiveErrorCode::permission_denied: + case ArchiveErrorCode::io_error: + kind = ErrorKind::io; + break; + case ArchiveErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ArchiveErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case ArchiveErrorCode::already_exists: + case ArchiveErrorCode::conflict: + kind = ErrorKind::conflict; + break; + case ArchiveErrorCode::unknown_publication: + case ArchiveErrorCode::isolation_failed: + kind = ErrorKind::internal; + break; + } + + const ErrorCode domain_code{Void::Result::kArchiveErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; + } + + /// Render an untrusted archive entry path safely for diagnostics: capped at + /// 4 KiB with control characters and newlines escaped. + [[nodiscard]] std::string + sanitize_diagnostic_path(std::string_view raw) noexcept; + + struct ReadLimits { + std::size_t max_entries{10'000}; + bool allow_zero_entries{false}; + std::uint64_t max_file_bytes{512ULL * 1024 * 1024}; + std::uint64_t max_total_bytes{2ULL * 1024 * 1024 * 1024}; + std::uint64_t max_compressed_bytes{1ULL * 1024 * 1024 * 1024}; + std::size_t max_metadata_bytes{8ULL * 1024 * 1024}; + std::size_t transfer_buffer_bytes{64ULL * 1024}; + std::size_t max_path_bytes{4096}; + std::size_t max_component_bytes{255}; + std::size_t max_path_components{64}; + + [[nodiscard]] Void::Result::Result validate() const + { + if ((max_entries == 0 && !allow_zero_entries) || + max_file_bytes == 0 || max_total_bytes == 0 || + max_compressed_bytes == 0 || max_metadata_bytes == 0 || + transfer_buffer_bytes == 0 || max_path_bytes == 0 || + max_component_bytes == 0 || max_path_components == 0) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::ReadLimits: limits must be non-zero unless " + "allow_zero_entries is explicitly enabled")}; + } + return {}; + } + }; + + enum class EntryType : std::uint8_t { + RegularFile = 0, + Directory, + Symlink, + Hardlink, + Other + }; + + struct EntryInfo { + std::string path{}; + EntryType type{EntryType::RegularFile}; + std::uint64_t declared_size{0}; + std::uint32_t safe_mode{0644}; + bool executable{false}; + bool accepted{true}; + std::string rejection_reason{}; + }; + + struct ProgressEvent { + std::size_t entries_processed{0}; + std::uint64_t bytes_extracted{0}; + std::string current_path{}; + }; + + using ProgressCallback = std::function; + + enum class PublicationOutcome : std::uint8_t { + Published = 0, + NotPublished, + Unknown + }; + + struct PublicationReceipt { + PublicationOutcome outcome{PublicationOutcome::NotPublished}; + std::filesystem::path destination_path{}; + std::string staging_id{}; + std::size_t entries{0}; + std::uint64_t bytes{0}; + std::string diagnostic{}; + }; + + struct StagedExtractionOptions { + ReadLimits limits{}; + bool preserve_executable_bit{true}; + std::stop_token stop{}; + std::optional deadline{}; + const Void::Time::MonotonicClock* clock{nullptr}; + ProgressCallback on_progress{}; + }; + + enum class ArchiveCompression : std::uint8_t { None = 0, Zstd }; + + struct CreationOptions { + ArchiveCompression compression{ArchiveCompression::Zstd}; + bool reproducible{true}; + ReadLimits limits{}; + std::stop_token stop{}; + }; + + struct CreateEntry { + std::string path{}; + EntryType type{EntryType::RegularFile}; + bool executable{false}; + std::vector content{}; + std::optional source_file{}; + }; + + struct IsolationOptions { + std::filesystem::path worker_executable{}; + std::uint64_t max_rss_bytes{128ULL * 1024 * 1024}; + std::chrono::milliseconds timeout{std::chrono::seconds{60}}; + StagedExtractionOptions extraction{}; + }; + + /// Synchronous byte source interface borrowed through completion. + class ByteSource + { + public: + + virtual ~ByteSource() = default; + /// Read up to dst.size() bytes. Returns 0 on clean EOF. + [[nodiscard]] virtual Void::Result::Result + read(std::span dst) = 0; + }; + + /// Synchronous byte sink interface borrowed through completion. + class ByteSink + { + public: + + virtual ~ByteSink() = default; + [[nodiscard]] virtual Void::Result::Result + write(std::span src) = 0; + }; + + class SpanByteSource final : public ByteSource + { + public: + + explicit SpanByteSource(std::span data) noexcept + : m_data(data) + { + } + + [[nodiscard]] Void::Result::Result + read(std::span dst) override; + + private: + + std::span m_data{}; + std::size_t m_offset{0}; + }; + + class FileByteSource final : public ByteSource + { + public: + + [[nodiscard]] static Void::Result::Result + open(const std::filesystem::path& path); + + FileByteSource(FileByteSource&&) noexcept; + FileByteSource& operator=(FileByteSource&&) noexcept; + ~FileByteSource() override; + + FileByteSource(const FileByteSource&) = delete; + FileByteSource& operator=(const FileByteSource&) = delete; + + [[nodiscard]] Void::Result::Result + read(std::span dst) override; + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit FileByteSource(std::unique_ptr impl) noexcept; + }; + + class VectorByteSink final : public ByteSink + { + public: + + explicit VectorByteSink( + std::size_t max_bytes = 256ULL * 1024 * 1024) noexcept + : m_max_bytes(max_bytes) + { + } + + [[nodiscard]] Void::Result::Result + write(std::span src) override; + + [[nodiscard]] const std::vector& bytes() const noexcept + { + return m_bytes; + } + [[nodiscard]] std::vector take_bytes() noexcept + { + return std::move(m_bytes); + } + + private: + + std::size_t m_max_bytes{256ULL * 1024 * 1024}; + std::vector m_bytes{}; + }; + + class FileByteSink final : public ByteSink + { + public: + + [[nodiscard]] static Void::Result::Result + create(const std::filesystem::path& path); + + FileByteSink(FileByteSink&&) noexcept; + FileByteSink& operator=(FileByteSink&&) noexcept; + ~FileByteSink() override; + + FileByteSink(const FileByteSink&) = delete; + FileByteSink& operator=(const FileByteSink&) = delete; + + [[nodiscard]] Void::Result::Result + write(std::span src) override; + [[nodiscard]] Void::Result::Result sync_and_close(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit FileByteSink(std::unique_ptr impl) noexcept; + }; + + enum class FaultPoint : std::uint8_t { + none = 0, + rename_enosys, + post_rename_parent_sync, + staging_cleanup_fail + }; + + class ScopedFaultGuard + { + public: + + explicit ScopedFaultGuard(FaultPoint point) noexcept; + ~ScopedFaultGuard() noexcept; + + ScopedFaultGuard(const ScopedFaultGuard&) = delete; + ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete; + ScopedFaultGuard(ScopedFaultGuard&&) = delete; + ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete; + + private: + + FaultPoint m_previous{FaultPoint::none}; + }; + +} // namespace Void::Archive diff --git a/src/Archive/StagedArchive.cpp b/src/Archive/StagedArchive.cpp new file mode 100644 index 0000000..c0da04c --- /dev/null +++ b/src/Archive/StagedArchive.cpp @@ -0,0 +1,2804 @@ +#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 +#include +#include +#include +#ifdef __linux__ +#include +#endif +#ifndef RENAME_NOREPLACE +#define RENAME_NOREPLACE (1U << 0) +#endif +#endif + +namespace Void::Archive +{ + namespace + { + thread_local FaultPoint g_fault_point{FaultPoint::none}; + std::atomic g_stage_counter{0}; + + constexpr int kDirOpenFlags = + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW; + constexpr std::size_t kMaxDiagnosticPathBytes = 4096; + constexpr std::string_view kStagePrefix = ".void-stage-"; + constexpr std::string_view kMarkerFilename = ".void-stage.marker"; + constexpr std::string_view kInventoryFilename = "inventory.txt"; + constexpr std::string_view kTreeSubdir = "tree"; + + using ArchiveReadPtr = + std::unique_ptr; + using ArchiveWritePtr = + std::unique_ptr; + using ArchiveEntryPtr = + std::unique_ptr; + + class OwnedFd + { + public: + + explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {} + ~OwnedFd() noexcept { reset(); } + OwnedFd(OwnedFd&& other) noexcept + : m_fd(std::exchange(other.m_fd, -1)) + { + } + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(std::exchange(other.m_fd, -1)); + } + return *this; + } + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + [[nodiscard]] int get() const noexcept { return m_fd; } + [[nodiscard]] explicit operator bool() const noexcept + { + return m_fd >= 0; + } + [[nodiscard]] int release() noexcept + { + return std::exchange(m_fd, -1); + } + void reset(int fd = -1) noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + } + m_fd = fd; + } + + private: + + int m_fd{-1}; + }; + + [[nodiscard]] ArchiveErrorCode errno_to_archive_code(int err) noexcept + { + switch (err) { + case EACCES: + case EPERM: + return ArchiveErrorCode::permission_denied; + case ENOSPC: + case EDQUOT: + return ArchiveErrorCode::no_space; + case EEXIST: + case ENOTEMPTY: + return ArchiveErrorCode::already_exists; + case ENOSYS: + case EINVAL: + return ArchiveErrorCode::unsupported_capability; + default: + return ArchiveErrorCode::io_error; + } + } + + [[nodiscard]] Void::Result::Error + make_errno_error(int err, std::string message) + { + return make_archive_error( + errno_to_archive_code(err), + std::format("{}: {}", message, std::strerror(err)), + std::error_code{err, std::generic_category()}); + } + + [[nodiscard]] Void::Result::Error + make_libarchive_error(archive* a, std::string_view op, + ArchiveErrorCode fallback = + ArchiveErrorCode::corrupt_archive) + { + const char* raw = a ? archive_error_string(a) : nullptr; + const std::string detail = + raw ? sanitize_diagnostic_path(raw) : "unknown archive error"; + return make_archive_error(fallback, + std::format("Archive: {}: {}", op, detail)); + } + + [[nodiscard]] bool is_safe_single_component( + std::string_view name, std::size_t max_bytes = 255) noexcept + { + if (name.empty() || name.size() > max_bytes || name == "." || + name == "..") { + return false; + } + for (const unsigned char ch : name) { + if (ch == '/' || ch == '\\' || ch == '\0') { + return false; + } + } + return true; + } + + struct ValidatedPath { + std::string normalized{}; + std::vector components{}; + }; + + [[nodiscard]] Void::Result::Result + validate_archive_path(std::string_view raw, bool is_directory, + const ReadLimits& limits) + { + if (raw.empty()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: entry path is empty")}; + } + if (raw.size() > limits.max_path_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + std::format("Archive: entry path exceeds {} byte cap: '{}'", + limits.max_path_bytes, + sanitize_diagnostic_path(raw)))}; + } + if (raw.find('\0') != std::string_view::npos || + raw.find('\\') != std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unsafe characters in path '{}'", + sanitize_diagnostic_path(raw)))}; + } + + std::string_view trimmed = raw; + if (trimmed.back() == '/') { + if (!is_directory) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: regular file path ends with '/': " + "'{}'", + sanitize_diagnostic_path(raw)))}; + } + trimmed.remove_suffix(1); + if (trimmed.empty() || trimmed.back() == '/') { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: invalid directory path '{}'", + sanitize_diagnostic_path(raw)))}; + } + } + if (trimmed.front() == '/' || + trimmed.find("//") != std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: absolute or non-normal path '{}'", + sanitize_diagnostic_path(raw)))}; + } + + ValidatedPath out; + std::size_t pos = 0; + while (pos < trimmed.size()) { + const std::size_t slash = trimmed.find('/', pos); + const std::string_view comp = + slash == std::string_view::npos + ? trimmed.substr(pos) + : trimmed.substr(pos, slash - pos); + if (!is_safe_single_component(comp, + limits.max_component_bytes)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unsafe path component in '{}'", + sanitize_diagnostic_path(raw)))}; + } + if (out.components.size() >= limits.max_path_components) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + std::format( + "Archive: path exceeds {} components: '{}'", + limits.max_path_components, + sanitize_diagnostic_path(raw)))}; + } + out.components.emplace_back(comp); + if (slash == std::string_view::npos) { + break; + } + pos = slash + 1; + } + + const std::filesystem::path fspath{trimmed}; + if (fspath.empty() || fspath.is_absolute() || + fspath.has_root_name() || fspath.lexically_normal() != fspath) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: non-normalized path '{}'", + sanitize_diagnostic_path(raw)))}; + } + out.normalized.assign(trimmed); + return out; + } + + class PathTracker + { + public: + + explicit PathTracker(std::size_t max_metadata_bytes) noexcept + : m_max_metadata_bytes(max_metadata_bytes) + { + } + + [[nodiscard]] Void::Result::Result + record(const ValidatedPath& vp, bool is_directory) + { + const std::size_t cost = vp.normalized.size() + 64U; + if (cost > m_max_metadata_bytes || + m_metadata_bytes > m_max_metadata_bytes - cost) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: aggregate path/inventory metadata " + "exceeds limit")}; + } + + // Check exact duplicate. + if (m_files.contains(vp.normalized) || + m_explicit_dirs.contains(vp.normalized)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: duplicate entry path '{}'", + sanitize_diagnostic_path( + vp.normalized)))}; + } + + // If registering a file, ensure no implicit/explicit dir + // already owns this path as a parent. + if (!is_directory && m_all_dirs.contains(vp.normalized)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: file conflicts with existing " + "directory '{}'", + sanitize_diagnostic_path( + vp.normalized)))}; + } + + // Every parent prefix must not already be a regular file. + std::string prefix; + for (std::size_t i = 0; i + 1 < vp.components.size(); ++i) { + if (i > 0) { + prefix.push_back('/'); + } + prefix.append(vp.components[i]); + if (m_files.contains(prefix)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: file-as-parent conflict " + "at '{}'", + sanitize_diagnostic_path(prefix)))}; + } + if (m_all_dirs.insert(prefix).second) { + const std::size_t pcost = prefix.size() + 32U; + if (pcost > m_max_metadata_bytes || + m_metadata_bytes > + m_max_metadata_bytes - pcost) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: aggregate metadata exceeds " + "limit")}; + } + m_metadata_bytes += pcost; + } + } + + m_metadata_bytes += cost; + if (is_directory) { + m_explicit_dirs.insert(vp.normalized); + m_all_dirs.insert(vp.normalized); + } else { + m_files.insert(vp.normalized); + } + return {}; + } + + [[nodiscard]] const std::set& + all_dirs() const noexcept + { + return m_all_dirs; + } + + private: + + std::size_t m_max_metadata_bytes{0}; + std::size_t m_metadata_bytes{0}; + std::set m_files{}; + std::set m_explicit_dirs{}; + std::set m_all_dirs{}; + }; + + [[nodiscard]] Void::Result::Result + write_all_fd(int fd, std::span data) + { + std::size_t written = 0; + while (written < data.size()) { + const ssize_t n = ::write( + fd, + reinterpret_cast(data.data()) + written, + data.size() - written); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return std::unexpected{ + make_errno_error(errno, "Archive: write failed")}; + } + written += static_cast(n); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + write_file_at(int dir_fd, const char* filename, + std::string_view content, mode_t mode) + { + OwnedFd fd{::openat(dir_fd, filename, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | + O_NOFOLLOW, + mode)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: create '{}'", filename))}; + } + const auto bytes = + std::as_bytes(std::span{content.data(), content.size()}); + if (auto w = write_all_fd(fd.get(), bytes); !w.has_value()) { + fd.reset(); + (void)::unlinkat(dir_fd, filename, 0); + return w; + } + if (::fsync(fd.get()) != 0) { + const int err = errno; + fd.reset(); + (void)::unlinkat(dir_fd, filename, 0); + return std::unexpected{make_errno_error( + err, std::format("Archive: fsync '{}'", filename))}; + } + const int raw = fd.release(); + if (::close(raw) != 0) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: close '{}'", filename))}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result + remove_directory_contents_nofollow(int dir_fd) + { + OwnedFd dup_fd{::openat(dir_fd, ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate dir fd for cleanup")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{ + make_errno_error(errno, "Archive: fdopendir failed")}; + } + (void)dup_fd.release(); // owned by dir now + + Void::Result::Result first_err{}; + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + if (errno != 0 && first_err.has_value()) { + first_err = std::unexpected{ + make_errno_error(errno, "Archive: readdir failed")}; + } + break; + } + 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) { + if (errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: fstatat during cleanup")}; + } + continue; + } + if (S_ISDIR(st.st_mode)) { + OwnedFd sub{::openat(dir_fd, ent->d_name, kDirOpenFlags)}; + if (!sub) { + if (first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, + "Archive: openat subdir during cleanup")}; + } + continue; + } + if (auto sub_res = remove_directory_contents_nofollow( + sub.get()); + !sub_res.has_value() && first_err.has_value()) { + first_err = std::move(sub_res); + } + sub.reset(); + if (::unlinkat(dir_fd, ent->d_name, AT_REMOVEDIR) != 0 && + errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: unlinkat subdir")}; + } + } else { + if (::unlinkat(dir_fd, ent->d_name, 0) != 0 && + errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: unlinkat entry")}; + } + } + } + (void)::closedir(dir); + return first_err; + } + + [[nodiscard]] Void::Result::Result + remove_stage_dir(int parent_fd, std::string_view stage_name) + { + if (g_fault_point == FaultPoint::staging_cleanup_fail) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive: injected staging cleanup failure")}; + } + const std::string name_str{stage_name}; + OwnedFd stage_fd{::openat(parent_fd, name_str.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + if (errno == ENOENT) { + return {}; + } + return std::unexpected{make_errno_error( + errno, "Archive: open staging root for cleanup")}; + } + auto content_res = remove_directory_contents_nofollow(stage_fd.get()); + stage_fd.reset(); + if (::unlinkat(parent_fd, name_str.c_str(), AT_REMOVEDIR) != 0 && + errno != ENOENT) { + if (content_res.has_value()) { + return std::unexpected{make_errno_error( + errno, "Archive: remove staging root")}; + } + } + return content_res; + } + + [[nodiscard]] Void::Result::Result + open_or_create_relative_dir(int root_fd, + const std::vector& comps, + std::size_t count) + { + OwnedFd cur{::openat(root_fd, ".", kDirOpenFlags)}; + if (!cur) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate staging tree fd")}; + } + for (std::size_t i = 0; i < count; ++i) { + const char* part = comps[i].c_str(); + int fd = ::openat(cur.get(), part, kDirOpenFlags); + if (fd < 0 && errno == ENOENT) { + if (::mkdirat(cur.get(), part, 0755) != 0 && + errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: mkdirat in staging tree")}; + } + fd = ::openat(cur.get(), part, kDirOpenFlags); + } + if (fd < 0) { + return std::unexpected{make_errno_error( + errno, "Archive: unsafe parent in staging tree")}; + } + cur = OwnedFd{fd}; + } + return cur; + } + + [[nodiscard]] Void::Result::Result + fsync_directories_bottom_up(int tree_fd, + const std::set& dirs) + { + std::vector sorted(dirs.begin(), dirs.end()); + std::sort(sorted.begin(), sorted.end(), + [](const std::string& a, const std::string& b) { + const auto da = + std::count(a.begin(), a.end(), '/'); + const auto db = + std::count(b.begin(), b.end(), '/'); + if (da != db) { + return da > db; + } + return a.size() > b.size(); + }); + + for (const auto& dir_rel : sorted) { + OwnedFd cur{::openat(tree_fd, ".", kDirOpenFlags)}; + if (!cur) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate tree fd for fsync")}; + } + std::size_t pos = 0; + while (pos < dir_rel.size()) { + const std::size_t slash = dir_rel.find('/', pos); + const std::string comp = + slash == std::string::npos + ? dir_rel.substr(pos) + : dir_rel.substr(pos, slash - pos); + OwnedFd next{::openat(cur.get(), comp.c_str(), kDirOpenFlags)}; + if (!next) { + return std::unexpected{make_errno_error( + errno, "Archive: open dir for fsync")}; + } + cur = std::move(next); + if (slash == std::string::npos) { + break; + } + pos = slash + 1; + } + if (::fsync(cur.get()) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged subdirectory")}; + } + } + if (::fsync(tree_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged tree root")}; + } + return {}; + } + + [[nodiscard]] std::optional current_rss_bytes() noexcept + { + std::ifstream statm{"/proc/self/statm"}; + if (!statm.is_open()) { + return std::nullopt; + } + std::uint64_t total_pages = 0; + std::uint64_t resident_pages = 0; + if (!(statm >> total_pages >> resident_pages)) { + return std::nullopt; + } + const long page_size = ::sysconf(_SC_PAGESIZE); + if (page_size <= 0) { + return std::nullopt; + } + return resident_pages * static_cast(page_size); + } + + [[nodiscard]] std::string + serialize_inventory(const std::vector& inventory) + { + std::string out; + out += "VOID_ARCHIVE_INVENTORY_V1\n"; + for (const auto& entry : inventory) { + const char tag = + entry.type == EntryType::Directory ? 'D' : 'F'; + out += std::format("{} {} {:o} {}\n", tag, entry.declared_size, + entry.safe_mode, entry.path); + } + return out; + } + + [[nodiscard]] Void::Result::Result> + parse_inventory(std::string_view text, const ReadLimits& limits) + { + if (text.size() > limits.max_metadata_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory exceeds metadata limit")}; + } + std::vector out; + std::size_t pos = 0; + const auto next_line = [&](std::string_view& line) -> bool { + if (pos >= text.size()) { + return false; + } + const std::size_t nl = text.find('\n', pos); + if (nl == std::string_view::npos) { + line = text.substr(pos); + pos = text.size(); + } else { + line = text.substr(pos, nl - pos); + pos = nl + 1; + } + return true; + }; + + std::string_view header; + if (!next_line(header) || header != "VOID_ARCHIVE_INVENTORY_V1") { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid completion inventory header")}; + } + + PathTracker tracker{limits.max_metadata_bytes}; + std::uint64_t total_bytes = 0; + std::string_view line; + while (next_line(line)) { + if (line.empty()) { + continue; + } + if (out.size() >= limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory entry count exceeds limit")}; + } + if (line.size() < 6 || (line[0] != 'F' && line[0] != 'D') || + line[1] != ' ') { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory line")}; + } + const bool is_dir = line[0] == 'D'; + const std::size_t sp2 = line.find(' ', 2); + if (sp2 == std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory size field")}; + } + const std::size_t sp3 = line.find(' ', sp2 + 1); + if (sp3 == std::string_view::npos || sp3 + 1 >= line.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory mode/path field")}; + } + + std::uint64_t size = 0; + const auto sres = std::from_chars(line.data() + 2, + line.data() + sp2, size); + if (sres.ec != std::errc{} || sres.ptr != line.data() + sp2) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid inventory size")}; + } + std::uint32_t mode = 0; + const auto mres = std::from_chars( + line.data() + sp2 + 1, line.data() + sp3, mode, 8); + if (mres.ec != std::errc{} || mres.ptr != line.data() + sp3) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid inventory mode")}; + } + const std::string_view path_view = line.substr(sp3 + 1); + auto vp = validate_archive_path(path_view, is_dir, limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = tracker.record(*vp, is_dir); !rec.has_value()) { + return std::unexpected{std::move(rec.error())}; + } + if (!is_dir) { + if (size > limits.max_file_bytes || + size > limits.max_total_bytes - total_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory byte totals exceed limit")}; + } + total_bytes += size; + } + out.push_back(EntryInfo{ + .path = std::move(vp->normalized), + .type = is_dir ? EntryType::Directory + : EntryType::RegularFile, + .declared_size = size, + .safe_mode = mode, + .executable = !is_dir && ((mode & 0111U) != 0U), + .accepted = true, + }); + } + return out; + } + + [[nodiscard]] Void::Result::Result + verify_staged_tree_on_disk(int tree_fd, + const std::vector& inventory, + const ReadLimits& limits, + std::uint64_t& out_verified_bytes) + { + std::map expected_files; + std::set expected_dirs; + for (const auto& e : inventory) { + if (e.type == EntryType::Directory) { + expected_dirs.insert(e.path); + } else { + expected_files[e.path] = &e; + } + // Add all parent prefixes as expected directories. + std::size_t pos = 0; + while ((pos = e.path.find('/', pos)) != std::string::npos) { + expected_dirs.insert(e.path.substr(0, pos)); + ++pos; + } + } + + std::set seen_files; + std::set seen_dirs; + out_verified_bytes = 0; + + std::function(int, const std::string&, + std::size_t)> + walk = [&](int dir_fd, const std::string& prefix, + std::size_t depth) -> Void::Result::Result { + if (depth > limits.max_path_components) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: staged directory depth exceeds limit")}; + } + OwnedFd dup_fd{::openat(dir_fd, ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: verify openat dir")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{make_errno_error( + errno, "Archive: verify fdopendir")}; + } + (void)dup_fd.release(); + + Void::Result::Result status{}; + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + if (errno != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify readdir")}; + } + break; + } + const std::string_view name{ent->d_name}; + if (name == "." || name == "..") { + continue; + } + const std::string rel = + prefix.empty() ? std::string{name} + : (prefix + "/" + std::string{name}); + struct stat st{}; + if (::fstatat(dir_fd, ent->d_name, &st, + AT_SYMLINK_NOFOLLOW) != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify fstatat")}; + break; + } + if (S_ISLNK(st.st_mode)) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected symlink in " + "staged tree")}; + break; + } + if (S_ISDIR(st.st_mode)) { + if (!expected_dirs.contains(rel)) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unexpected directory in " + "staged tree '{}'", + sanitize_diagnostic_path(rel)))}; + break; + } + seen_dirs.insert(rel); + OwnedFd sub{ + ::openat(dir_fd, ent->d_name, kDirOpenFlags)}; + if (!sub) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify openat subdir")}; + break; + } + if (auto sr = walk(sub.get(), rel, depth + 1U); + !sr.has_value()) { + status = std::move(sr); + break; + } + } else if (S_ISREG(st.st_mode)) { + if (st.st_nlink > 1) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected " + "hardlink in staged tree")}; + break; + } + auto it = expected_files.find(rel); + if (it == expected_files.end()) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unexpected file in " + "staged tree '{}'", + sanitize_diagnostic_path(rel)))}; + break; + } + const auto actual_size = + static_cast(st.st_size); + if (actual_size != it->second->declared_size || + actual_size > limits.max_file_bytes || + actual_size > + limits.max_total_bytes - out_verified_bytes) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: staged file size disagrees with " + "inventory or exceeds limit")}; + break; + } + out_verified_bytes += actual_size; + seen_files.insert(rel); + OwnedFd rfd{::openat(dir_fd, ent->d_name, + O_RDONLY | O_CLOEXEC | + O_NOFOLLOW)}; + if (!rfd || ::fsync(rfd.get()) != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: parent verify fsync file")}; + break; + } + } else { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected special " + "file in staged tree")}; + break; + } + } + (void)::closedir(dir); + return status; + }; + + if (auto wr = walk(tree_fd, "", 0); !wr.has_value()) { + return wr; + } + if (seen_files.size() != expected_files.size() || + seen_dirs.size() != expected_dirs.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: staged tree missing entries declared in " + "inventory")}; + } + return fsync_directories_bottom_up(tree_fd, expected_dirs); + } + } // namespace + + std::string sanitize_diagnostic_path(std::string_view raw) noexcept + { + std::string out; + const std::size_t cap = std::min(raw.size(), kMaxDiagnosticPathBytes); + out.reserve(cap); + for (std::size_t i = 0; i < raw.size(); ++i) { + if (out.size() >= kMaxDiagnosticPathBytes) { + break; + } + const unsigned char ch = static_cast(raw[i]); + if (ch == '\n') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\n"; + } else if (ch == '\r') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\r"; + } else if (ch == '\t') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\t"; + } else if (ch < 0x20U || ch == 0x7FU) { + if (out.size() + 4 > kMaxDiagnosticPathBytes) { + break; + } + static constexpr char kHex[] = "0123456789abcdef"; + out += "\\x"; + out.push_back(kHex[ch >> 4U]); + out.push_back(kHex[ch & 0x0FU]); + } else { + out.push_back(static_cast(ch)); + } + } + return out; + } + + ScopedFaultGuard::ScopedFaultGuard(FaultPoint point) noexcept + : m_previous(g_fault_point) + { + g_fault_point = point; + } + + ScopedFaultGuard::~ScopedFaultGuard() noexcept + { + g_fault_point = m_previous; + } + + // ── ByteSource & ByteSink Adapters ─────────────────────────────────────── + + Void::Result::Result + SpanByteSource::read(std::span dst) + { + if (m_offset >= m_data.size() || dst.empty()) { + return std::size_t{0}; + } + const std::size_t n = std::min(dst.size(), m_data.size() - m_offset); + std::memcpy(dst.data(), m_data.data() + m_offset, n); + m_offset += n; + return n; + } + + struct FileByteSource::Impl { + OwnedFd fd{}; + }; + + FileByteSource::FileByteSource(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + FileByteSource::FileByteSource(FileByteSource&&) noexcept = default; + FileByteSource& + FileByteSource::operator=(FileByteSource&&) noexcept = default; + FileByteSource::~FileByteSource() = default; + + Void::Result::Result + FileByteSource::open(const std::filesystem::path& path) + { + OwnedFd fd{::open(path.c_str(), O_RDONLY | O_CLOEXEC)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: open '{}'", + sanitize_diagnostic_path(path.string())))}; + } + auto impl = std::make_unique(); + impl->fd = std::move(fd); + return FileByteSource{std::move(impl)}; + } + + Void::Result::Result + FileByteSource::read(std::span dst) + { + if (!m_impl || !m_impl->fd) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::FileByteSource: source is closed")}; + } + if (dst.empty()) { + return std::size_t{0}; + } + for (;;) { + const ssize_t n = + ::read(m_impl->fd.get(), dst.data(), dst.size()); + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSource: read")}; + } + return static_cast(n); + } + } + + Void::Result::Result + VectorByteSink::write(std::span src) + { + if (src.size() > m_max_bytes || m_bytes.size() > m_max_bytes - src.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::VectorByteSink: output exceeds buffer limit")}; + } + m_bytes.insert(m_bytes.end(), src.begin(), src.end()); + return {}; + } + + struct FileByteSink::Impl { + OwnedFd fd{}; + }; + + FileByteSink::FileByteSink(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + FileByteSink::FileByteSink(FileByteSink&&) noexcept = default; + FileByteSink& FileByteSink::operator=(FileByteSink&&) noexcept = default; + FileByteSink::~FileByteSink() = default; + + Void::Result::Result + FileByteSink::create(const std::filesystem::path& path) + { + OwnedFd fd{::open(path.c_str(), + O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: create '{}'", + sanitize_diagnostic_path(path.string())))}; + } + auto impl = std::make_unique(); + impl->fd = std::move(fd); + return FileByteSink{std::move(impl)}; + } + + Void::Result::Result + FileByteSink::write(std::span src) + { + if (!m_impl || !m_impl->fd) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::FileByteSink: sink is closed")}; + } + return write_all_fd(m_impl->fd.get(), src); + } + + Void::Result::Result FileByteSink::sync_and_close() + { + if (!m_impl || !m_impl->fd) { + return {}; + } + if (::fsync(m_impl->fd.get()) != 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSink: fsync")}; + } + const int raw = m_impl->fd.release(); + if (::close(raw) != 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSink: close")}; + } + return {}; + } + + // ── Reader ─────────────────────────────────────────────────────────────── + + struct Reader::Impl { + std::unique_ptr owned_source{}; + ByteSource* source{nullptr}; + ReadLimits limits{}; + std::stop_token stop{}; + std::optional deadline{}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + ArchiveReadPtr handle{nullptr, &archive_read_free}; + std::vector read_buf{}; + PathTracker tracker; + std::optional source_error{}; + bool has_active_file{false}; + bool reached_eof{false}; + bool poisoned{false}; + std::size_t entries_seen{0}; + std::uint64_t entry_bytes_read{0}; + std::uint64_t total_decompressed{0}; + std::uint64_t total_compressed{0}; + + explicit Impl(const ReadLimits& lim) + : limits(lim), read_buf(lim.transfer_buffer_bytes), + tracker(lim.max_metadata_bytes) + { + } + + [[nodiscard]] Void::Result::Result check_stop_deadline() const + { + if (stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::Reader: operation cancelled")}; + } + if (deadline.has_value() && clock->now() >= *deadline) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::timeout, + "Archive::Reader: deadline expired")}; + } + return {}; + } + + static la_ssize_t libarchive_read_cb(archive* a, void* client_data, + const void** buffer) + { + auto* self = static_cast(client_data); + if (auto chk = self->check_stop_deadline(); !chk.has_value()) { + self->source_error = std::move(chk.error()); + archive_set_error(a, ECANCELED, "cancelled or timed out"); + return -1; + } + auto res = self->source->read(self->read_buf); + if (!res.has_value()) { + self->source_error = std::move(res.error()); + archive_set_error(a, EIO, "source read failed"); + return -1; + } + const std::uint64_t n = static_cast(*res); + if (n > self->limits.max_compressed_bytes - + self->total_compressed) { + self->source_error = make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: compressed input exceeds limit"); + archive_set_error(a, EFBIG, + "compressed input exceeds limit"); + return -1; + } + self->total_compressed += n; + *buffer = self->read_buf.data(); + return static_cast(n); + } + }; + + Reader::Reader(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + Reader::~Reader() = default; + Reader::Reader(Reader&&) noexcept = default; + Reader& Reader::operator=(Reader&&) noexcept = default; + + Void::Result::Result Reader::open( + ByteSource& source, ReadLimits limits, std::stop_token stop, + std::optional deadline, + const Void::Time::MonotonicClock& clock) + { + if (auto valid = limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + auto impl = std::make_unique(limits); + impl->source = &source; + impl->stop = stop; + impl->deadline = deadline; + impl->clock = &clock; + + if (auto chk = impl->check_stop_deadline(); !chk.has_value()) { + return std::unexpected{std::move(chk.error())}; + } + + impl->handle = + ArchiveReadPtr{archive_read_new(), &archive_read_free}; + if (!impl->handle) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::Reader: cannot allocate libarchive reader")}; + } + (void)archive_read_support_filter_zstd(impl->handle.get()); + (void)archive_read_support_filter_none(impl->handle.get()); + (void)archive_read_support_format_tar(impl->handle.get()); + + if (archive_read_open2(impl->handle.get(), impl.get(), nullptr, + &Impl::libarchive_read_cb, nullptr, + nullptr) != ARCHIVE_OK) { + if (impl->source_error.has_value()) { + return std::unexpected{std::move(*impl->source_error)}; + } + return std::unexpected{make_libarchive_error( + impl->handle.get(), "open archive", + ArchiveErrorCode::unsupported_format)}; + } + return Reader{std::move(impl)}; + } + + Void::Result::Result Reader::open_file( + const std::filesystem::path& archive_path, ReadLimits limits, + std::stop_token stop, + std::optional deadline, + const Void::Time::MonotonicClock& clock) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + auto owned = std::make_unique(std::move(*file)); + auto reader = open(*owned, limits, stop, deadline, clock); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + reader->m_impl->owned_source = std::move(owned); + return reader; + } + + Void::Result::Result> Reader::next_entry() + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (m_impl->has_active_file) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: active entry must be drained or skipped " + "before advancing")}; + } + if (m_impl->reached_eof) { + return std::optional{std::nullopt}; + } + if (auto chk = m_impl->check_stop_deadline(); !chk.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(chk.error())}; + } + + archive_entry* entry = nullptr; + const int status = + archive_read_next_header(m_impl->handle.get(), &entry); + if (status == ARCHIVE_EOF) { + m_impl->reached_eof = true; + return std::optional{std::nullopt}; + } + if (status != ARCHIVE_OK) { + m_impl->poisoned = true; + if (m_impl->source_error.has_value()) { + return std::unexpected{std::move(*m_impl->source_error)}; + } + return std::unexpected{ + make_libarchive_error(m_impl->handle.get(), "read header")}; + } + + if (m_impl->entries_seen >= m_impl->limits.max_entries) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: entry count exceeds limit")}; + } + ++m_impl->entries_seen; + + const char* raw_path = archive_entry_pathname(entry); + if (raw_path == nullptr) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::Reader: entry has no pathname")}; + } + if (archive_entry_hardlink(entry) != nullptr || + archive_entry_symlink(entry) != nullptr) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive::Reader: links are not allowed ('{}')", + sanitize_diagnostic_path(raw_path)))}; + } + + const auto ftype = archive_entry_filetype(entry); + if (ftype != AE_IFDIR && ftype != AE_IFREG) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive::Reader: special files are not allowed " + "('{}')", + sanitize_diagnostic_path(raw_path)))}; + } + + const bool is_dir = (ftype == AE_IFDIR); + auto vp = validate_archive_path(raw_path, is_dir, m_impl->limits); + if (!vp.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = m_impl->tracker.record(*vp, is_dir); !rec.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(rec.error())}; + } + + std::uint64_t declared_size = 0; + bool executable = false; + if (!is_dir) { + const auto raw_size = archive_entry_size(entry); + if (raw_size < 0) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive::Reader: negative entry size")}; + } + declared_size = static_cast(raw_size); + if (declared_size > m_impl->limits.max_file_bytes || + declared_size > m_impl->limits.max_total_bytes - + m_impl->total_decompressed) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: declared entry size exceeds policy")}; + } + executable = (archive_entry_perm(entry) & 0111) != 0; + m_impl->has_active_file = true; + m_impl->entry_bytes_read = 0; + } + + return std::optional{EntryInfo{ + .path = std::move(vp->normalized), + .type = is_dir ? EntryType::Directory : EntryType::RegularFile, + .declared_size = declared_size, + .safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U), + .executable = executable, + .accepted = true, + }}; + } + + Void::Result::Result + Reader::read_chunk(std::span dst) + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (!m_impl->has_active_file) { + return std::size_t{0}; + } + if (dst.empty()) { + return std::size_t{0}; + } + if (auto chk = m_impl->check_stop_deadline(); !chk.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(chk.error())}; + } + + const std::size_t to_read = + std::min(dst.size(), m_impl->limits.transfer_buffer_bytes); + const la_ssize_t n = + archive_read_data(m_impl->handle.get(), dst.data(), to_read); + if (n == 0) { + m_impl->has_active_file = false; + return std::size_t{0}; + } + if (n < 0) { + m_impl->poisoned = true; + if (m_impl->source_error.has_value()) { + return std::unexpected{std::move(*m_impl->source_error)}; + } + return std::unexpected{ + make_libarchive_error(m_impl->handle.get(), "read entry data")}; + } + const auto amount = static_cast(n); + if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read || + amount > m_impl->limits.max_total_bytes - + m_impl->total_decompressed) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: actual decompressed bytes exceed limit")}; + } + m_impl->entry_bytes_read += amount; + m_impl->total_decompressed += amount; + return static_cast(n); + } + + Void::Result::Result Reader::skip_entry() + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (!m_impl->has_active_file) { + return std::uint64_t{0}; + } + // Explicitly decompress and account every byte so skipping cannot + // bypass file/total decompression limits. + std::vector scratch(m_impl->limits.transfer_buffer_bytes); + std::uint64_t skipped = 0; + for (;;) { + auto n = read_chunk(scratch); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + break; + } + skipped += static_cast(*n); + } + return skipped; + } + + std::size_t Reader::entries_seen() const noexcept + { + return m_impl ? m_impl->entries_seen : 0; + } + + std::uint64_t Reader::total_decompressed_bytes() const noexcept + { + return m_impl ? m_impl->total_decompressed : 0; + } + + std::uint64_t Reader::total_compressed_bytes() const noexcept + { + return m_impl ? m_impl->total_compressed : 0; + } + + // ── Listing ────────────────────────────────────────────────────────────── + + Void::Result::Result> + list_entries(ByteSource& source, ReadLimits limits, bool forensic) + { + if (auto valid = limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + + if (!forensic) { + auto reader = Reader::open(source, limits); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + std::vector out; + for (;;) { + auto next = reader->next_entry(); + if (!next.has_value()) { + return std::unexpected{std::move(next.error())}; + } + if (!next->has_value()) { + break; + } + if ((*next)->type == EntryType::RegularFile) { + if (auto skip = reader->skip_entry(); !skip.has_value()) { + return std::unexpected{std::move(skip.error())}; + } + } + out.push_back(std::move(**next)); + } + return out; + } + + // Opt-in forensic listing: reports rejected entries without writing. + struct ForensicState { + ByteSource* source{nullptr}; + ReadLimits limits{}; + std::vector buf{}; + std::uint64_t compressed{0}; + std::optional err{}; + }; + ForensicState st{&source, limits, + std::vector(limits.transfer_buffer_bytes)}; + ArchiveReadPtr handle{archive_read_new(), &archive_read_free}; + if (!handle) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::list_entries: cannot allocate reader")}; + } + (void)archive_read_support_filter_zstd(handle.get()); + (void)archive_read_support_filter_none(handle.get()); + (void)archive_read_support_format_tar(handle.get()); + + auto cb = [](archive* a, void* data, + const void** out_buf) -> la_ssize_t { + auto* s = static_cast(data); + auto r = s->source->read(s->buf); + if (!r.has_value()) { + s->err = std::move(r.error()); + archive_set_error(a, EIO, "read error"); + return -1; + } + const auto n = static_cast(*r); + if (n > s->limits.max_compressed_bytes - s->compressed) { + s->err = make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: compressed limit exceeded"); + archive_set_error(a, EFBIG, "compressed limit exceeded"); + return -1; + } + s->compressed += n; + *out_buf = s->buf.data(); + return static_cast(n); + }; + if (archive_read_open2(handle.get(), &st, nullptr, cb, nullptr, + nullptr) != ARCHIVE_OK) { + if (st.err.has_value()) { + return std::unexpected{std::move(*st.err)}; + } + return std::unexpected{make_libarchive_error( + handle.get(), "forensic open", + ArchiveErrorCode::unsupported_format)}; + } + + std::vector out; + PathTracker tracker{limits.max_metadata_bytes}; + std::size_t metadata_bytes = 0; + archive_entry* entry = nullptr; + for (;;) { + const int status = archive_read_next_header(handle.get(), &entry); + if (status == ARCHIVE_EOF) { + break; + } + if (status != ARCHIVE_OK) { + if (st.err.has_value()) { + return std::unexpected{std::move(*st.err)}; + } + return std::unexpected{ + make_libarchive_error(handle.get(), "forensic header")}; + } + if (out.size() >= limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: entry count exceeds limit")}; + } + + const char* raw_path = archive_entry_pathname(entry); + const std::string sanitized = + raw_path ? sanitize_diagnostic_path(raw_path) : ""; + if (sanitized.size() + 64U > limits.max_metadata_bytes || + metadata_bytes > + limits.max_metadata_bytes - (sanitized.size() + 64U)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: metadata limit exceeded")}; + } + metadata_bytes += sanitized.size() + 64U; + + EntryInfo info; + info.path = sanitized; + const auto ftype = archive_entry_filetype(entry); + if (archive_entry_hardlink(entry) != nullptr) { + info.type = EntryType::Hardlink; + info.accepted = false; + info.rejection_reason = "hardlink disallowed"; + } else if (archive_entry_symlink(entry) != nullptr || + ftype == AE_IFLNK) { + info.type = EntryType::Symlink; + info.accepted = false; + info.rejection_reason = "symlink disallowed"; + } else if (ftype != AE_IFDIR && ftype != AE_IFREG) { + info.type = EntryType::Other; + info.accepted = false; + info.rejection_reason = "special file disallowed"; + } else { + const bool is_dir = (ftype == AE_IFDIR); + info.type = + is_dir ? EntryType::Directory : EntryType::RegularFile; + info.declared_size = + archive_entry_size(entry) > 0 + ? static_cast(archive_entry_size(entry)) + : 0; + info.executable = + !is_dir && ((archive_entry_perm(entry) & 0111) != 0); + info.safe_mode = + is_dir ? 0755U : (info.executable ? 0755U : 0644U); + auto vp = validate_archive_path(raw_path ? raw_path : "", + is_dir, limits); + if (!vp.has_value()) { + info.accepted = false; + info.rejection_reason = vp.error().message(); + } else if (auto rec = tracker.record(*vp, is_dir); + !rec.has_value()) { + info.accepted = false; + info.rejection_reason = rec.error().message(); + } else { + info.path = std::move(vp->normalized); + info.accepted = true; + } + } + out.push_back(std::move(info)); + (void)archive_read_data_skip(handle.get()); + } + return out; + } + + Void::Result::Result> + list_entries(const std::filesystem::path& archive_path, + ReadLimits limits, bool forensic) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + return list_entries(*file, limits, forensic); + } + + // ── StagedTree & Atomic Publication ────────────────────────────────────── + + struct StagedTree::Impl { + OwnedFd parent_fd{}; + OwnedFd stage_fd{}; + std::filesystem::path parent_path{}; + std::filesystem::path staging_root{}; + std::filesystem::path tree_path{}; + std::string staging_id{}; + std::size_t entries{0}; + std::uint64_t bytes{0}; + std::vector inventory{}; + bool published{false}; + bool discarded{false}; + + ~Impl() noexcept + { + if (!published && !discarded && parent_fd && !staging_id.empty()) { + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), staging_id); + } + } + }; + + StagedTree::StagedTree(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + StagedTree::~StagedTree() noexcept = default; + StagedTree::StagedTree(StagedTree&&) noexcept = default; + StagedTree& StagedTree::operator=(StagedTree&&) noexcept = default; + + bool StagedTree::valid() const noexcept + { + return m_impl != nullptr && !m_impl->discarded; + } + bool StagedTree::published() const noexcept + { + return m_impl != nullptr && m_impl->published; + } + std::string_view StagedTree::staging_id() const noexcept + { + return m_impl ? std::string_view{m_impl->staging_id} + : std::string_view{}; + } + const std::filesystem::path& StagedTree::staging_root() const noexcept + { + static const std::filesystem::path kEmpty; + return m_impl ? m_impl->staging_root : kEmpty; + } + const std::filesystem::path& StagedTree::tree_path() const noexcept + { + static const std::filesystem::path kEmpty; + return m_impl ? m_impl->tree_path : kEmpty; + } + std::size_t StagedTree::entries() const noexcept + { + return m_impl ? m_impl->entries : 0; + } + std::uint64_t StagedTree::bytes() const noexcept + { + return m_impl ? m_impl->bytes : 0; + } + const std::vector& StagedTree::inventory() const noexcept + { + static const std::vector kEmpty; + return m_impl ? m_impl->inventory : kEmpty; + } + + Void::Result::Result StagedTree::discard() + { + if (!m_impl || m_impl->discarded) { + return {}; + } + if (m_impl->published) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::StagedTree::discard: tree is already published")}; + } + m_impl->stage_fd.reset(); + auto res = remove_stage_dir(m_impl->parent_fd.get(), m_impl->staging_id); + if (!res.has_value()) { + return std::unexpected{res.error().with_context(std::format( + "retryable staging_id={}", m_impl->staging_id))}; + } + m_impl->discarded = true; + return {}; + } + + Void::Result::Result + StagedTree::publish(std::string_view new_child_name) + { + if (!m_impl || m_impl->discarded || m_impl->published) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::StagedTree::publish: invalid or already published " + "tree")}; + } + if (!is_safe_single_component(new_child_name)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::StagedTree::publish: new_child_name must be a safe " + "immediate directory name")}; + } + + const std::string target_name{new_child_name}; + const auto dest_path = m_impl->parent_path / target_name; + + int rc = -1; + int err = 0; + if (g_fault_point == FaultPoint::rename_enosys) { + errno = ENOSYS; + rc = -1; + err = ENOSYS; + } else { +#if defined(__linux__) && defined(SYS_renameat2) + rc = static_cast(::syscall( + SYS_renameat2, m_impl->stage_fd.get(), "tree", + m_impl->parent_fd.get(), target_name.c_str(), + static_cast(RENAME_NOREPLACE))); + err = errno; +#else + rc = -1; + err = ENOSYS; +#endif + } + + if (rc != 0) { + if (err == ENOSYS || err == EINVAL) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsupported_capability, + "Archive::StagedTree::publish: atomic no-replace rename " + "is unsupported on this filesystem", + std::error_code{err, std::generic_category()})}; + } + return std::unexpected{make_errno_error( + err, std::format("Archive::StagedTree::publish '{}'", + sanitize_diagnostic_path(target_name)))}; + } + + // Rename succeeded; publication is no longer reversible as staging. + m_impl->published = true; + + bool sync_failed = false; + int sync_err = 0; + if (g_fault_point == FaultPoint::post_rename_parent_sync) { + sync_failed = true; + sync_err = EIO; + } else if (::fsync(m_impl->parent_fd.get()) != 0) { + sync_failed = true; + sync_err = errno; + } + + // Best-effort cleanup of now-empty staging wrapper metadata. + m_impl->stage_fd.reset(); + (void)remove_stage_dir(m_impl->parent_fd.get(), m_impl->staging_id); + + if (sync_failed) { + return PublicationReceipt{ + .outcome = PublicationOutcome::Unknown, + .destination_path = dest_path, + .staging_id = m_impl->staging_id, + .entries = m_impl->entries, + .bytes = m_impl->bytes, + .diagnostic = std::format( + "parent directory fsync failed after atomic rename ({}): " + "publication durability is unknown; inspect destination " + "rather than assuming rollback", + std::strerror(sync_err)), + }; + } + + return PublicationReceipt{ + .outcome = PublicationOutcome::Published, + .destination_path = dest_path, + .staging_id = m_impl->staging_id, + .entries = m_impl->entries, + .bytes = m_impl->bytes, + .diagnostic = {}, + }; + } + + namespace + { + [[nodiscard]] Void::Result::Result extract_into_pinned_stage( + ByteSource& source, int stage_fd, int tree_fd, + const StagedExtractionOptions& options, std::uint64_t max_rss_bytes, + std::vector& out_inventory, std::uint64_t& out_bytes) + { + const auto& clock = + options.clock ? *options.clock + : Void::Time::SystemMonotonicClock::instance(); + auto reader = Reader::open(source, options.limits, options.stop, + options.deadline, clock); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + + out_inventory.clear(); + out_bytes = 0; + std::set created_dirs; + std::vector chunk(options.limits.transfer_buffer_bytes); + auto last_progress = clock.now() - std::chrono::seconds{1}; + + auto emit_progress = [&](const std::string& path, bool force) { + if (!options.on_progress) { + return; + } + const auto now = clock.now(); + if (!force && now - last_progress < + std::chrono::milliseconds{100}) { + return; + } + last_progress = now; + try { + options.on_progress(ProgressEvent{ + .entries_processed = out_inventory.size(), + .bytes_extracted = out_bytes, + .current_path = sanitize_diagnostic_path(path), + }); + } catch (...) { + // Progress failure never changes extraction success. + } + }; + + auto check_rss = [&]() -> Void::Result::Result { + if (max_rss_bytes == 0) { + return {}; + } + if (auto rss = current_rss_bytes(); + rss.has_value() && *rss > max_rss_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: decoder exceeded configured RSS limit")}; + } + return {}; + }; + + for (;;) { + if (auto r = check_rss(); !r.has_value()) { + return r; + } + auto next = reader->next_entry(); + if (!next.has_value()) { + return std::unexpected{std::move(next.error())}; + } + if (!next->has_value()) { + break; + } + EntryInfo info = std::move(**next); + auto vp = validate_archive_path( + info.path, info.type == EntryType::Directory, + options.limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + + // Record every implicit parent dir for bottom-up fsync. + std::string prefix; + for (std::size_t i = 0; i + 1 < vp->components.size(); ++i) { + if (i > 0) { + prefix.push_back('/'); + } + prefix.append(vp->components[i]); + created_dirs.insert(prefix); + } + + auto parent_dir = open_or_create_relative_dir( + tree_fd, vp->components, vp->components.size() - 1U); + if (!parent_dir.has_value()) { + return std::unexpected{std::move(parent_dir.error())}; + } + const std::string& leaf = vp->components.back(); + + if (info.type == EntryType::Directory) { + if (::mkdirat(parent_dir->get(), leaf.c_str(), 0755) != 0 && + errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: mkdirat staged directory")}; + } + created_dirs.insert(info.path); + info.declared_size = 0; + info.safe_mode = 0755U; + out_inventory.push_back(std::move(info)); + emit_progress(out_inventory.back().path, false); + continue; + } + + const mode_t mode = + (options.preserve_executable_bit && info.executable) ? 0755 + : 0644; + OwnedFd out_fd{::openat( + parent_dir->get(), leaf.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, mode)}; + if (!out_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: openat staged file")}; + } + + std::uint64_t actual_file_bytes = 0; + for (;;) { + if (auto r = check_rss(); !r.has_value()) { + return r; + } + auto n = reader->read_chunk(chunk); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + break; + } + if (auto w = write_all_fd( + out_fd.get(), + std::span{chunk.data(), *n}); + !w.has_value()) { + return w; + } + actual_file_bytes += static_cast(*n); + out_bytes += static_cast(*n); + } + if (::fsync(out_fd.get()) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged regular file")}; + } + const int raw_fd = out_fd.release(); + if (::close(raw_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: close staged regular file")}; + } + info.declared_size = actual_file_bytes; + info.safe_mode = static_cast(mode); + out_inventory.push_back(std::move(info)); + emit_progress(out_inventory.back().path, false); + } + + if (auto synced = + fsync_directories_bottom_up(tree_fd, created_dirs); + !synced.has_value()) { + return synced; + } + + const std::string inv_text = serialize_inventory(out_inventory); + if (inv_text.size() > options.limits.max_metadata_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: completion inventory exceeds metadata limit")}; + } + if (auto inv_w = write_file_at(stage_fd, "inventory.txt", inv_text, + 0600); + !inv_w.has_value()) { + return inv_w; + } + if (::fsync(stage_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staging root")}; + } + emit_progress("", true); + return {}; + } + + struct AllocatedStage { + OwnedFd parent_fd{}; + OwnedFd stage_fd{}; + OwnedFd tree_fd{}; + std::string stage_name{}; + std::filesystem::path stage_path{}; + std::filesystem::path tree_path{}; + }; + + [[nodiscard]] Void::Result::Result + allocate_stage(const std::filesystem::path& parent_directory) + { + std::error_code ec; + std::filesystem::create_directories(parent_directory, ec); + if (ec) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + std::format("Archive: cannot create parent directory: {}", + ec.message()), + ec)}; + } + OwnedFd parent_fd{::open(parent_directory.c_str(), kDirOpenFlags)}; + if (!parent_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: open parent directory")}; + } + + AllocatedStage allocated; + for (std::size_t attempt = 0; attempt < 128; ++attempt) { + const auto seq = + g_stage_counter.fetch_add(1, std::memory_order_relaxed); + const std::string name = + std::format("{}{}-{}", kStagePrefix, + static_cast(::getpid()), seq); + if (::mkdirat(parent_fd.get(), name.c_str(), 0700) == 0) { + OwnedFd stage_fd{ + ::openat(parent_fd.get(), name.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + const int err = errno; + (void)::unlinkat(parent_fd.get(), name.c_str(), + AT_REMOVEDIR); + return std::unexpected{make_errno_error( + err, "Archive: open created staging dir")}; + } + const auto epoch_s = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + const std::string marker = std::format( + "VOID_STAGE_MARKER_V1\npid={}\nuid={}\ncreated={}\n", + static_cast(::getpid()), + static_cast(::geteuid()), epoch_s); + if (auto mw = write_file_at( + stage_fd.get(), std::string{kMarkerFilename}.c_str(), + marker, 0600); + !mw.has_value()) { + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{std::move(mw.error())}; + } + if (::mkdirat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + 0755) != 0) { + const int err = errno; + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{make_errno_error( + err, "Archive: mkdirat staging tree")}; + } + OwnedFd tree_fd{::openat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + kDirOpenFlags)}; + if (!tree_fd) { + const int err = errno; + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{make_errno_error( + err, "Archive: open staging tree")}; + } + allocated.parent_fd = std::move(parent_fd); + allocated.stage_fd = std::move(stage_fd); + allocated.tree_fd = std::move(tree_fd); + allocated.stage_name = name; + allocated.stage_path = parent_directory / name; + allocated.tree_path = allocated.stage_path / kTreeSubdir; + return allocated; + } + if (errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: create exclusive staging dir")}; + } + } + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive: exhausted attempts to create exclusive staging dir")}; + } + } // namespace + + Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options) + { + if (auto valid = options.limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + + auto stage = allocate_stage(parent_directory); + if (!stage.has_value()) { + return std::unexpected{std::move(stage.error())}; + } + + std::vector inventory; + std::uint64_t total_bytes = 0; + auto extracted = extract_into_pinned_stage( + source, stage->stage_fd.get(), stage->tree_fd.get(), options, 0, + inventory, total_bytes); + if (!extracted.has_value()) { + auto primary_err = std::move(extracted.error()); + stage->tree_fd.reset(); + stage->stage_fd.reset(); + if (auto clean = remove_stage_dir(stage->parent_fd.get(), + stage->stage_name); + !clean.has_value()) { + primary_err = primary_err.with_context(std::format( + "staging cleanup also failed (retryable staging_id={}): {}", + stage->stage_name, clean.error().message())); + } + return std::unexpected{std::move(primary_err)}; + } + + auto impl = std::make_unique(); + impl->parent_fd = std::move(stage->parent_fd); + impl->stage_fd = std::move(stage->stage_fd); + impl->parent_path = parent_directory; + impl->staging_root = std::move(stage->stage_path); + impl->tree_path = std::move(stage->tree_path); + impl->staging_id = std::move(stage->stage_name); + impl->entries = inventory.size(); + impl->bytes = total_bytes; + impl->inventory = std::move(inventory); + return StagedTree{std::move(impl)}; + } + + Void::Result::Result + extract_staged(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + return extract_staged(*file, parent_directory, options); + } + + Void::Result::Result + cleanup_stale_staging(const std::filesystem::path& parent_directory, + std::chrono::seconds min_age) + { + OwnedFd parent_fd{::open(parent_directory.c_str(), kDirOpenFlags)}; + if (!parent_fd) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: open parent")}; + } + OwnedFd dup_fd{::openat(parent_fd.get(), ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: dup parent")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: fdopendir")}; + } + (void)dup_fd.release(); + + const uid_t my_uid = ::geteuid(); + const auto now_s = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + std::size_t removed = 0; + + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + break; + } + const std::string_view name{ent->d_name}; + if (!name.starts_with(kStagePrefix)) { + continue; + } + struct stat st{}; + if (::fstatat(parent_fd.get(), ent->d_name, &st, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISDIR(st.st_mode) || st.st_uid != my_uid) { + continue; + } + OwnedFd stage_fd{ + ::openat(parent_fd.get(), ent->d_name, kDirOpenFlags)}; + if (!stage_fd) { + continue; + } + // Require exclusive operation marker owned by current user. + struct stat mst{}; + if (::fstatat(stage_fd.get(), std::string{kMarkerFilename}.c_str(), + &mst, AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISREG(mst.st_mode) || mst.st_uid != my_uid) { + continue; + } + OwnedFd mfd{::openat(stage_fd.get(), + std::string{kMarkerFilename}.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!mfd) { + continue; + } + std::array mbuf{}; + const ssize_t mlen = ::read(mfd.get(), mbuf.data(), mbuf.size()); + mfd.reset(); + stage_fd.reset(); + if (mlen <= 0) { + continue; + } + const std::string_view mtext{mbuf.data(), + static_cast(mlen)}; + if (!mtext.starts_with("VOID_STAGE_MARKER_V1\n")) { + continue; + } + const auto created_pos = mtext.find("created="); + if (created_pos == std::string_view::npos) { + continue; + } + const auto created_end = mtext.find('\n', created_pos); + const std::string_view ts_view = mtext.substr( + created_pos + 8U, + created_end == std::string_view::npos + ? std::string_view::npos + : created_end - (created_pos + 8U)); + std::int64_t created_s = 0; + const auto tres = std::from_chars( + ts_view.data(), ts_view.data() + ts_view.size(), created_s); + if (tres.ec != std::errc{} || + tres.ptr != ts_view.data() + ts_view.size()) { + continue; + } + if (now_s - created_s < min_age.count()) { + continue; + } + if (auto rr = remove_stage_dir(parent_fd.get(), name); + rr.has_value()) { + ++removed; + } + } + (void)::closedir(dir); + return removed; + } + + // ── Reproducible Archive Creation ──────────────────────────────────────── + + Void::Result::Result + create_archive(ByteSink& sink, std::span entries, + const CreationOptions& options) + { + if (auto valid = options.limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + if (entries.size() > options.limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::create_archive: entry count exceeds limit")}; + } + + struct NormalizedCreate { + std::string path{}; + const CreateEntry* src{nullptr}; + std::uint64_t size{0}; + OwnedFd file_fd{}; + }; + + PathTracker tracker{options.limits.max_metadata_bytes}; + std::vector normalized; + normalized.reserve(entries.size()); + std::uint64_t total_bytes = 0; + + for (const auto& entry : entries) { + if (options.stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::create_archive: cancelled")}; + } + if (entry.type != EntryType::RegularFile && + entry.type != EntryType::Directory) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::create_archive: only regular files and " + "directories are allowed")}; + } + const bool is_dir = (entry.type == EntryType::Directory); + auto vp = validate_archive_path(entry.path, is_dir, options.limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = tracker.record(*vp, is_dir); !rec.has_value()) { + return std::unexpected{std::move(rec.error())}; + } + + NormalizedCreate item; + item.path = std::move(vp->normalized); + item.src = &entry; + if (!is_dir) { + if (entry.source_file.has_value()) { + OwnedFd fd{::open(entry.source_file->c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, "Archive::create_archive: open source file " + "(links disallowed)")}; + } + struct stat st{}; + if (::fstat(fd.get(), &st) != 0 || !S_ISREG(st.st_mode)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::create_archive: source_file is not a " + "regular file")}; + } + item.size = static_cast(st.st_size); + item.file_fd = std::move(fd); + } else { + item.size = static_cast(entry.content.size()); + } + if (item.size > options.limits.max_file_bytes || + item.size > options.limits.max_total_bytes - total_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::create_archive: content size exceeds limit")}; + } + total_bytes += item.size; + } + normalized.push_back(std::move(item)); + } + + // Sort lexicographically for reproducible archives. + std::sort(normalized.begin(), normalized.end(), + [](const NormalizedCreate& a, const NormalizedCreate& b) { + return a.path < b.path; + }); + + struct SinkBridge { + ByteSink* sink{nullptr}; + std::optional err{}; + }; + SinkBridge bridge{&sink}; + + ArchiveWritePtr writer{archive_write_new(), &archive_write_free}; + if (!writer) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::create_archive: cannot allocate writer")}; + } + if (options.compression == ArchiveCompression::Zstd) { + if (archive_write_add_filter_zstd(writer.get()) != ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "add zstd filter")}; + } + } else { + if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "add none filter")}; + } + } + if (archive_write_set_format_pax_restricted(writer.get()) != + ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "set pax_restricted")}; + } + if (archive_write_set_bytes_in_last_block(writer.get(), 1) != + ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "set bytes_in_last_block")}; + } + + auto write_cb = [](archive* a, void* data, const void* buf, + std::size_t len) -> la_ssize_t { + auto* b = static_cast(data); + auto res = b->sink->write(std::span{ + static_cast(buf), len}); + if (!res.has_value()) { + b->err = std::move(res.error()); + archive_set_error(a, EIO, "sink write failed"); + return -1; + } + return static_cast(len); + }; + if (archive_write_open2(writer.get(), &bridge, nullptr, write_cb, + nullptr, nullptr) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "open archive writer")}; + } + + std::vector io_buf(options.limits.transfer_buffer_bytes); + for (auto& item : normalized) { + if (options.stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::create_archive: cancelled")}; + } + ArchiveEntryPtr ae{archive_entry_new(), &archive_entry_free}; + const bool is_dir = (item.src->type == EntryType::Directory); + const std::string wire_path = + is_dir ? (item.path + "/") : item.path; + archive_entry_set_pathname(ae.get(), wire_path.c_str()); + archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG); + archive_entry_set_perm( + ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644)); + if (options.reproducible) { + archive_entry_set_mtime(ae.get(), 0, 0); + archive_entry_set_uid(ae.get(), 0); + archive_entry_set_gid(ae.get(), 0); + archive_entry_set_uname(ae.get(), ""); + archive_entry_set_gname(ae.get(), ""); + } + if (!is_dir) { + archive_entry_set_size(ae.get(), + static_cast(item.size)); + } + + if (archive_write_header(writer.get(), ae.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "write header")}; + } + + if (!is_dir) { + if (item.file_fd) { + std::uint64_t remaining = item.size; + while (remaining > 0) { + const std::size_t want = static_cast( + std::min(remaining, io_buf.size())); + const ssize_t r = + ::read(item.file_fd.get(), io_buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::create_archive: source file shrunk " + "or read failed")}; + } + std::size_t off = 0; + while (off < static_cast(r)) { + const la_ssize_t w = archive_write_data( + writer.get(), io_buf.data() + off, + static_cast(r) - off); + if (w < 0) { + if (bridge.err.has_value()) { + return std::unexpected{ + std::move(*bridge.err)}; + } + return std::unexpected{make_libarchive_error( + writer.get(), "write data")}; + } + off += static_cast(w); + } + remaining -= static_cast(r); + } + } else { + std::size_t off = 0; + while (off < item.src->content.size()) { + const la_ssize_t w = archive_write_data( + writer.get(), item.src->content.data() + off, + item.src->content.size() - off); + if (w < 0) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{make_libarchive_error( + writer.get(), "write data")}; + } + off += static_cast(w); + } + } + } + + if (archive_write_finish_entry(writer.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "finish entry")}; + } + } + + if (archive_write_close(writer.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "close archive writer")}; + } + return {}; + } + + Void::Result::Result + create_archive(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options) + { + auto sink = FileByteSink::create(output_path); + if (!sink.has_value()) { + return std::unexpected{std::move(sink.error())}; + } + if (auto res = create_archive(*sink, entries, options); + !res.has_value()) { + return res; + } + return sink->sync_and_close(); + } + + // ── Isolated Child Decoder Profile ─────────────────────────────────────── + + Void::Result::Result + extract_staged_isolated(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options) + { + if (options.worker_executable.empty()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::extract_staged_isolated: worker_executable is " + "required")}; + } + if (auto valid = options.extraction.limits.validate(); + !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + if (options.timeout <= std::chrono::milliseconds{0}) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::extract_staged_isolated: timeout must be positive")}; + } + + auto stage = allocate_stage(parent_directory); + if (!stage.has_value()) { + return std::unexpected{std::move(stage.error())}; + } + + auto cleanup_on_fail = [&](Void::Result::Error primary) + -> Void::Result::Result { + stage->tree_fd.reset(); + stage->stage_fd.reset(); + if (auto clean = remove_stage_dir(stage->parent_fd.get(), + stage->stage_name); + !clean.has_value()) { + primary = primary.with_context(std::format( + "staging cleanup failed (retryable staging_id={})", + stage->stage_name)); + } + return std::unexpected{std::move(primary)}; + }; + + const auto& lim = options.extraction.limits; + Void::Process::SpawnOptions spawn_opts{}; + spawn_opts.executable = options.worker_executable; + spawn_opts.arguments = { + "--archive", + archive_path.string(), + "--stage", + stage->stage_path.string(), + "--max-entries", + std::to_string(lim.max_entries), + "--max-file", + std::to_string(lim.max_file_bytes), + "--max-total", + std::to_string(lim.max_total_bytes), + "--max-compressed", + std::to_string(lim.max_compressed_bytes), + "--max-metadata", + std::to_string(lim.max_metadata_bytes), + "--max-rss", + std::to_string(options.max_rss_bytes), + "--timeout-ms", + std::to_string(options.timeout.count()), + "--preserve-exec", + options.extraction.preserve_executable_bit ? "1" : "0", + "--allow-zero", + lim.allow_zero_entries ? "1" : "0", + }; + spawn_opts.stdin_pipe = false; + spawn_opts.stdout_pipe = true; + spawn_opts.stderr_pipe = true; + spawn_opts.search_path = false; + spawn_opts.new_process_group = true; + + auto child = Void::Process::spawn(spawn_opts); + if (!child.has_value()) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::isolation_failed, + std::format("Archive::extract_staged_isolated: spawn failed: " + "{}", + child.error().message()))); + } + + Void::Process::CaptureLimits cap{}; + cap.max_stdout_bytes = 64 * 1024; + cap.max_stderr_bytes = 64 * 1024; + cap.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate; + + auto comm = Void::Process::communicate_blocking( + *child, {}, cap, options.timeout, options.extraction.stop); + if (!comm.has_value()) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::isolation_failed, + std::format("Archive::extract_staged_isolated: communicate " + "failed: {}", + comm.error().message()))); + } + if (comm->cancelled) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::extract_staged_isolated: cancelled")); + } + if (comm->timed_out) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::timeout, + "Archive::extract_staged_isolated: worker timed out")); + } + if (!comm->status.exited || comm->status.code != 0) { + const auto code = comm->status.exited && comm->status.code == 42 + ? ArchiveErrorCode::limit_exceeded + : ArchiveErrorCode::isolation_failed; + return cleanup_on_fail(make_archive_error( + code, + std::format("Archive::extract_staged_isolated: worker failed " + "(exited={}, code={}, signal={}): {}", + comm->status.exited, comm->status.code, + comm->status.signal, + sanitize_diagnostic_path(comm->err)))); + } + + // Parent independently verifies inventory & staged tree before + // granting publication authority. + OwnedFd inv_fd{::openat(stage->stage_fd.get(), + std::string{kInventoryFilename}.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!inv_fd) { + return cleanup_on_fail(make_errno_error( + errno, "Archive::extract_staged_isolated: missing inventory")); + } + std::string inv_text; + std::array rbuf{}; + for (;;) { + const ssize_t n = ::read(inv_fd.get(), rbuf.data(), rbuf.size()); + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0) { + return cleanup_on_fail(make_errno_error( + errno, + "Archive::extract_staged_isolated: read inventory")); + } + if (n == 0) { + break; + } + if (inv_text.size() + static_cast(n) > + lim.max_metadata_bytes) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::extract_staged_isolated: inventory exceeds " + "metadata limit")); + } + inv_text.append(rbuf.data(), static_cast(n)); + } + inv_fd.reset(); + + auto parsed_inv = parse_inventory(inv_text, lim); + if (!parsed_inv.has_value()) { + return cleanup_on_fail(std::move(parsed_inv.error())); + } + + std::uint64_t verified_bytes = 0; + if (auto vr = verify_staged_tree_on_disk( + stage->tree_fd.get(), *parsed_inv, lim, verified_bytes); + !vr.has_value()) { + return cleanup_on_fail(std::move(vr.error())); + } + if (::fsync(stage->stage_fd.get()) != 0) { + return cleanup_on_fail(make_errno_error( + errno, "Archive::extract_staged_isolated: fsync staging root")); + } + + auto impl = std::make_unique(); + impl->parent_fd = std::move(stage->parent_fd); + impl->stage_fd = std::move(stage->stage_fd); + impl->parent_path = parent_directory; + impl->staging_root = std::move(stage->stage_path); + impl->tree_path = std::move(stage->tree_path); + impl->staging_id = std::move(stage->stage_name); + impl->entries = parsed_inv->size(); + impl->bytes = verified_bytes; + impl->inventory = std::move(*parsed_inv); + return StagedTree{std::move(impl)}; + } + + int run_isolated_worker_main(int argc, char** argv) + { + std::filesystem::path archive_path; + std::filesystem::path stage_path; + StagedExtractionOptions opts{}; + std::uint64_t max_rss_bytes = 128ULL * 1024 * 1024; + std::uint64_t timeout_ms = 60'000; + + auto parse_u64 = [](const char* s, std::uint64_t& out) -> bool { + if (s == nullptr) { + return false; + } + const std::string_view sv{s}; + auto res = + std::from_chars(sv.data(), sv.data() + sv.size(), out); + return res.ec == std::errc{} && res.ptr == sv.data() + sv.size(); + }; + + for (int i = 1; i < argc; ++i) { + const std::string_view arg{argv[i]}; + auto next_val = [&]() -> const char* { + return (i + 1 < argc) ? argv[++i] : nullptr; + }; + std::uint64_t v = 0; + if (arg == "--archive") { + if (const char* p = next_val()) { + archive_path = p; + } + } else if (arg == "--stage") { + if (const char* p = next_val()) { + stage_path = p; + } + } else if (arg == "--max-entries" && parse_u64(next_val(), v)) { + opts.limits.max_entries = static_cast(v); + } else if (arg == "--max-file" && parse_u64(next_val(), v)) { + opts.limits.max_file_bytes = v; + } else if (arg == "--max-total" && parse_u64(next_val(), v)) { + opts.limits.max_total_bytes = v; + } else if (arg == "--max-compressed" && parse_u64(next_val(), v)) { + opts.limits.max_compressed_bytes = v; + } else if (arg == "--max-metadata" && parse_u64(next_val(), v)) { + opts.limits.max_metadata_bytes = static_cast(v); + } else if (arg == "--max-rss" && parse_u64(next_val(), v)) { + max_rss_bytes = v; + } else if (arg == "--timeout-ms" && parse_u64(next_val(), v)) { + timeout_ms = v; + } else if (arg == "--preserve-exec" && parse_u64(next_val(), v)) { + opts.preserve_executable_bit = (v != 0); + } else if (arg == "--allow-zero" && parse_u64(next_val(), v)) { + opts.limits.allow_zero_entries = (v != 0); + } else { + const std::string msg = "unknown worker argument\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 2; + } + } + + if (archive_path.empty() || stage_path.empty()) { + const std::string msg = "missing --archive or --stage\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 2; + } + + // Apply safe OS resource limits (guard RLIMIT_AS under ASan; RSS is + // enforced via /proc/self/statm directly). + { + const rlim_t cpu_secs = + static_cast(std::max( + 1, (timeout_ms + 999ULL) / 1000ULL + 1ULL)); + struct rlimit rl_cpu{cpu_secs, cpu_secs}; + (void)::setrlimit(RLIMIT_CPU, &rl_cpu); + + const rlim_t fsize_cap = static_cast( + std::max(opts.limits.max_file_bytes, + opts.limits.max_metadata_bytes) + + 1024ULL * 1024ULL); + struct rlimit rl_fsize{fsize_cap, fsize_cap}; + (void)::setrlimit(RLIMIT_FSIZE, &rl_fsize); + + struct rlimit rl_nofile{128, 128}; + (void)::setrlimit(RLIMIT_NOFILE, &rl_nofile); + } + + opts.deadline = Void::Time::SystemMonotonicClock::instance().now() + + std::chrono::milliseconds{timeout_ms}; + + OwnedFd stage_fd{::open(stage_path.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + const std::string msg = "cannot open stage dir\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 3; + } + OwnedFd tree_fd{::openat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + kDirOpenFlags)}; + if (!tree_fd) { + const std::string msg = "cannot open stage tree dir\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 3; + } + + auto source = FileByteSource::open(archive_path); + if (!source.has_value()) { + const std::string msg = source.error().message() + "\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 4; + } + + std::vector inventory; + std::uint64_t bytes = 0; + auto res = extract_into_pinned_stage( + *source, stage_fd.get(), tree_fd.get(), opts, max_rss_bytes, + inventory, bytes); + if (!res.has_value()) { + const std::string msg = res.error().message() + "\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + if (res.error().code().value == + static_cast(ArchiveErrorCode::limit_exceeded)) { + return 42; + } + return 5; + } + return 0; + } + +} // namespace Void::Archive diff --git a/src/Archive/module.cmake b/src/Archive/module.cmake index b2b2c52..824c085 100644 --- a/src/Archive/module.cmake +++ b/src/Archive/module.cmake @@ -1,4 +1,4 @@ void_add_module(Archive - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Time System EXTERNAL_DEPS LibArchive::LibArchive ) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1f5520e..8d6e724 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -170,6 +170,20 @@ if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC)) add_dependencies(VoidTests VoidProcessHelper) endif() +if(TARGET VoidTests AND TARGET Void::Archive) + add_executable(VoidArchiveWorker + "${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp") + target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive) + set_target_properties(VoidArchiveWorker PROPERTIES + CXX_STANDARD 26 + CXX_STANDARD_REQUIRED ON + CXX_EXTENSIONS OFF + VOID_TESTING_NO_AUTO_SCAN TRUE) + target_compile_definitions(VoidTests PRIVATE + "VOID_ARCHIVE_WORKER_PATH=\"$\"") + add_dependencies(VoidTests VoidArchiveWorker) +endif() + if(TARGET VoidTests AND TARGET Void::Plugin) set(_test_plugin_src "${CMAKE_CURRENT_SOURCE_DIR}/plugins/TestPlugin.cpp") if(EXISTS "${_test_plugin_src}") diff --git a/tests/helpers/ArchiveWorker.cpp b/tests/helpers/ArchiveWorker.cpp new file mode 100644 index 0000000..bd1d613 --- /dev/null +++ b/tests/helpers/ArchiveWorker.cpp @@ -0,0 +1,6 @@ +#include + +int main(int argc, char** argv) +{ + return Void::Archive::run_isolated_worker_main(argc, argv); +} diff --git a/tests/package/ArchiveOnly/CMakeLists.txt b/tests/package/ArchiveOnly/CMakeLists.txt new file mode 100644 index 0000000..f21c093 --- /dev/null +++ b/tests/package/ArchiveOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidArchiveOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Archive) + +add_executable(void_archive_only_consumer main.cpp) +target_link_libraries(void_archive_only_consumer PRIVATE Void::Archive) +target_compile_features(void_archive_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ArchiveOnlyConsumer COMMAND void_archive_only_consumer) diff --git a/tests/package/ArchiveOnly/main.cpp b/tests/package/ArchiveOnly/main.cpp new file mode 100644 index 0000000..ef36ad9 --- /dev/null +++ b/tests/package/ArchiveOnly/main.cpp @@ -0,0 +1,26 @@ +#include + +#include +#include + +int main() +{ + const std::array entries{{ + Void::Archive::CreateEntry{ + .path = "hello.txt", + .type = Void::Archive::EntryType::RegularFile, + .content = {std::byte{'h'}, std::byte{'i'}}, + }, + }}; + Void::Archive::VectorByteSink sink; + if (!Void::Archive::create_archive(sink, entries).has_value()) { + return 1; + } + Void::Archive::SpanByteSource src{sink.bytes()}; + auto listed = Void::Archive::list_entries(src); + if (!listed.has_value() || listed->size() != 1U || + (*listed)[0].path != "hello.txt") { + return 2; + } + return 0; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 64a9e1b..f1feb57 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -197,6 +197,15 @@ if(_has_security_async) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_archive Archive System Time Functional) +if(_has_archive) + run_consumer(ArchiveOnly "${install_prefix}" "ArchiveOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/standalone/Archive/ArchiveHardening.cpp b/tests/standalone/Archive/ArchiveHardening.cpp new file mode 100644 index 0000000..9c2754a --- /dev/null +++ b/tests/standalone/Archive/ArchiveHardening.cpp @@ -0,0 +1,392 @@ +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Archive; + + std::vector to_bytes(std::string_view s) + { + std::vector out(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(static_cast(s[i])); + } + return out; + } + + std::string read_file_str(const std::filesystem::path& p) + { + std::ifstream in{p, std::ios::binary}; + Void::Testing::require(in.is_open()); + return std::string{std::istreambuf_iterator{in}, + std::istreambuf_iterator{}}; + } + + std::vector make_raw_tar( + std::span> + entries) + { + using W = std::unique_ptr; + using E = + std::unique_ptr; + std::vector out; + W writer{archive_write_new(), &archive_write_free}; + Void::Testing::require(static_cast(writer)); + Void::Testing::require(archive_write_add_filter_zstd(writer.get()) == + ARCHIVE_OK); + Void::Testing::require(archive_write_set_format_pax_restricted( + writer.get()) == ARCHIVE_OK); + Void::Testing::require( + archive_write_set_bytes_in_last_block(writer.get(), 1) == + ARCHIVE_OK); + auto cb = [](archive*, void* data, const void* buf, + std::size_t len) -> la_ssize_t { + auto* vec = static_cast*>(data); + const auto* p = static_cast(buf); + vec->insert(vec->end(), p, p + len); + return static_cast(len); + }; + Void::Testing::require(archive_write_open2(writer.get(), &out, nullptr, + cb, nullptr, nullptr) == + ARCHIVE_OK); + for (const auto& [path, content, type, link] : entries) { + E ae{archive_entry_new(), &archive_entry_free}; + const std::string p{path}; + archive_entry_set_pathname(ae.get(), p.c_str()); + archive_entry_set_filetype(ae.get(), type); + archive_entry_set_perm(ae.get(), type == AE_IFDIR ? 0755 : 0644); + if (type == AE_IFREG) { + archive_entry_set_size(ae.get(), + static_cast(content.size())); + } + if (!link.empty()) { + const std::string l{link}; + archive_entry_set_symlink(ae.get(), l.c_str()); + } + Void::Testing::require(archive_write_header(writer.get(), ae.get()) == + ARCHIVE_OK); + if (!content.empty()) { + Void::Testing::require( + archive_write_data(writer.get(), content.data(), + content.size()) == + static_cast(content.size())); + } + Void::Testing::require(archive_write_finish_entry(writer.get()) == + ARCHIVE_OK); + } + Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); + return out; + } +} // namespace + +Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing() +{ + // 1. Reproducible creation produces identical bytes regardless of entry + // ordering. + const std::array order_a{{ + CreateEntry{.path = "bin/run", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("#!/bin/sh\necho hi\n")}, + CreateEntry{.path = "docs/readme.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("hello archive")}, + CreateEntry{.path = "bin/", .type = EntryType::Directory}, + }}; + const std::array order_b{order_a[2], order_a[1], order_a[0]}; + + VectorByteSink sink_a; + VectorByteSink sink_b; + CreationOptions copts{.compression = ArchiveCompression::Zstd, + .reproducible = true}; + Void::Testing::require(create_archive(sink_a, order_a, copts).has_value()); + Void::Testing::require(create_archive(sink_b, order_b, copts).has_value()); + Void::Testing::expect_eq(sink_a.bytes(), sink_b.bytes()); + + // 2. Caller-driven Reader enforces drain/skip before next_entry and + // accounts skipped decompressed bytes against max_total_bytes. + { + SpanByteSource src{sink_a.bytes()}; + auto reader = Reader::open(src); + Void::Testing::require(reader.has_value()); + + auto e1 = reader->next_entry(); + Void::Testing::require(e1.has_value() && e1->has_value()); + Void::Testing::expect_eq((*e1)->path, std::string{"bin"}); + Void::Testing::expect_eq(static_cast((*e1)->type), + static_cast(EntryType::Directory)); + + auto e2 = reader->next_entry(); + Void::Testing::require(e2.has_value() && e2->has_value()); + Void::Testing::expect_eq((*e2)->path, std::string{"bin/run"}); + Void::Testing::expect((*e2)->executable); + + // Calling next_entry before draining/skipping active file fails. + auto premature = reader->next_entry(); + Void::Testing::require(!premature.has_value()); + } + + // Skip accounting catches total limit even when caller skips data! + { + SpanByteSource src{sink_a.bytes()}; + ReadLimits tight{}; + tight.max_total_bytes = 20; // bin/run (18B) + readme (13B) = 31B > 20B + auto reader = Reader::open(src, tight); + Void::Testing::require(reader.has_value()); + Void::Testing::require(reader->next_entry().has_value()); // bin/ + Void::Testing::require(reader->next_entry().has_value()); // bin/run + auto skipped = reader->skip_entry(); + Void::Testing::require(skipped.has_value()); + Void::Testing::expect_eq(*skipped, 18ULL); + auto e3 = reader->next_entry(); // docs/readme.txt declared 13B > 2B rem + Void::Testing::require(!e3.has_value()); + Void::Testing::expect_eq( + e3.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); + } + + // 3. Zero limits rejected unless allow_zero_entries is explicitly set. + { + ReadLimits zero_entries{}; + zero_entries.max_entries = 0; + Void::Testing::expect(!zero_entries.validate().has_value()); + zero_entries.allow_zero_entries = true; + Void::Testing::expect(zero_entries.validate().has_value()); + } + + // 4. File-as-parent conflict rejected cleanly (both orderings). + { + const std::array< + std::tuple, + 2> + conflict_entries{{ + {"foo", "file-bytes", AE_IFREG, ""}, + {"foo/child", "nested", AE_IFREG, ""}, + }}; + const auto raw = make_raw_tar(conflict_entries); + SpanByteSource src{raw}; + auto listed = list_entries(src, {}, false); + Void::Testing::require(!listed.has_value()); + Void::Testing::expect_eq( + listed.error().code().value, + static_cast(ArchiveErrorCode::unsafe_entry)); + } + + // 5. Normal vs forensic listing + sanitized diagnostics. + { + const std::array< + std::tuple, + 3> + mixed{{ + {"safe.txt", "ok", AE_IFREG, ""}, + {"bad\nlink", "", AE_IFLNK, "/etc/passwd"}, + {"../escape", "nope", AE_IFREG, ""}, + }}; + const auto raw = make_raw_tar(mixed); + + SpanByteSource src1{raw}; + Void::Testing::expect(!list_entries(src1, {}, false).has_value()); + + SpanByteSource src2{raw}; + auto forensic = list_entries(src2, {}, true); + Void::Testing::require(forensic.has_value()); + Void::Testing::expect_eq(forensic->size(), 3U); + Void::Testing::expect((*forensic)[0].accepted); + Void::Testing::expect(!(*forensic)[1].accepted); + Void::Testing::expect((*forensic)[1].path.find('\n') == + std::string::npos); + Void::Testing::expect(!(*forensic)[2].accepted); + } + + // Diagnostic sanitizer caps at 4 KiB and escapes newlines. + const std::string huge_diag(6000, 'a'); + Void::Testing::expect_eq(sanitize_diagnostic_path(huge_diag).size(), 4096U); + Void::Testing::expect_eq(sanitize_diagnostic_path("a\nb\rc"), + std::string{"a\\nb\\rc"}); +} + +Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup() +{ + Void::FileSystem::TempDir tmp{"void_archive_staged_"}; + const auto archive_path = tmp / "pkg.tar.zst"; + const auto parent_dir = tmp / "versions"; + std::filesystem::create_directories(parent_dir); + + const std::array entries{{ + CreateEntry{.path = "bin/app", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("binary-payload")}, + CreateEntry{.path = "etc/config.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("key=val")}, + }}; + Void::Testing::require(create_archive(archive_path, entries).has_value()); + + // 1. Staged extraction + atomic no-replace publication + safe modes. + std::size_t progress_calls = 0; + StagedExtractionOptions sopts{}; + sopts.on_progress = [&](const ProgressEvent&) { ++progress_calls; }; + auto staged = extract_staged(archive_path, parent_dir, sopts); + Void::Testing::require(staged.has_value()); + Void::Testing::expect(staged->valid()); + Void::Testing::expect(!staged->published()); + Void::Testing::expect_eq(staged->entries(), 2U); + Void::Testing::expect(progress_calls >= 1U); + + // Unsupported renameat2 ENOSYS returns unsupported_capability without + // fallback or consuming the staging tree. + { + ScopedFaultGuard fault{FaultPoint::rename_enosys}; + auto unsupported = staged->publish("v1"); + Void::Testing::require(!unsupported.has_value()); + Void::Testing::expect_eq( + unsupported.error().code().value, + static_cast(ArchiveErrorCode::unsupported_capability)); + Void::Testing::expect(!staged->published()); + Void::Testing::expect(!std::filesystem::exists(parent_dir / "v1")); + } + + // Atomic publish succeeds. + auto receipt = staged->publish("v1"); + Void::Testing::require(receipt.has_value()); + Void::Testing::expect_eq(static_cast(receipt->outcome), + static_cast(PublicationOutcome::Published)); + Void::Testing::expect(staged->published()); + Void::Testing::expect_eq(read_file_str(parent_dir / "v1/bin/app"), + std::string{"binary-payload"}); + Void::Testing::expect_eq(read_file_str(parent_dir / "v1/etc/config.txt"), + std::string{"key=val"}); + + struct stat st_exec{}; + struct stat st_reg{}; + Void::Testing::require(::stat((parent_dir / "v1/bin/app").c_str(), &st_exec) == + 0); + Void::Testing::require( + ::stat((parent_dir / "v1/etc/config.txt").c_str(), &st_reg) == 0); + Void::Testing::expect_eq(st_exec.st_mode & 0777, mode_t{0755}); + Void::Testing::expect_eq(st_reg.st_mode & 0777, mode_t{0644}); + + // 2. Never overwrites an existing child directory. + auto staged2 = extract_staged(archive_path, parent_dir); + Void::Testing::require(staged2.has_value()); + auto conflict = staged2->publish("v1"); + Void::Testing::require(!conflict.has_value()); + Void::Testing::expect_eq( + conflict.error().code().value, + static_cast(ArchiveErrorCode::already_exists)); + const auto stage2_root = staged2->staging_root(); + Void::Testing::expect(std::filesystem::exists(stage2_root)); + // Destroying unpublished StagedTree cleans up its staging directory. + staged2 = std::unexpected{make_archive_error(ArchiveErrorCode::none)}; + Void::Testing::expect(!std::filesystem::exists(stage2_root)); + + // 3. Post-rename parent fsync failure reports Unknown outcome with identity + // and does NOT claim rollback. + auto staged3 = extract_staged(archive_path, parent_dir); + Void::Testing::require(staged3.has_value()); + { + ScopedFaultGuard fault{FaultPoint::post_rename_parent_sync}; + auto unknown = staged3->publish("v2"); + Void::Testing::require(unknown.has_value()); + Void::Testing::expect_eq(static_cast(unknown->outcome), + static_cast(PublicationOutcome::Unknown)); + Void::Testing::expect_eq(unknown->destination_path, parent_dir / "v2"); + Void::Testing::expect(!unknown->staging_id.empty()); + Void::Testing::expect(std::filesystem::exists(parent_dir / "v2/bin/app")); + } + + // 4. Failed extraction with cleanup fault preserves primary error + + // retryable staging_id; cleanup_stale_staging cleans only valid marked dirs. + const auto foreign_dir = parent_dir / ".void-stage-foreign"; + std::filesystem::create_directories(foreign_dir); + { + ScopedFaultGuard fault{FaultPoint::staging_cleanup_fail}; + StagedExtractionOptions tight{}; + tight.limits.max_file_bytes = 4; + auto failed = extract_staged(archive_path, parent_dir, tight); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect_eq( + failed.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); + Void::Testing::expect(failed.error().message().find("staging_id=") != + std::string::npos); + } + auto cleaned = cleanup_stale_staging(parent_dir, std::chrono::seconds{0}); + Void::Testing::require(cleaned.has_value()); + Void::Testing::expect_eq(*cleaned, 1U); + Void::Testing::expect(std::filesystem::exists(foreign_dir)); +} + +Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes() +{ +#ifdef VOID_ARCHIVE_WORKER_PATH + Void::FileSystem::TempDir tmp{"void_archive_iso_"}; + const auto archive_path = tmp / "untrusted.tar.zst"; + const auto parent_dir = tmp / "out"; + std::filesystem::create_directories(parent_dir); + + const std::array entries{{ + CreateEntry{.path = "bin/tool", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("isolated-ok")}, + CreateEntry{.path = "data/info.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("verified-by-parent")}, + }}; + Void::Testing::require(create_archive(archive_path, entries).has_value()); + + IsolationOptions iso{}; + iso.worker_executable = VOID_ARCHIVE_WORKER_PATH; + iso.timeout = std::chrono::seconds{30}; + iso.max_rss_bytes = 256ULL * 1024 * 1024; + + auto staged = extract_staged_isolated(archive_path, parent_dir, iso); + Void::Testing::require(staged.has_value()); + Void::Testing::expect_eq(staged->entries(), 2U); + + auto published = staged->publish("rel-1"); + Void::Testing::require(published.has_value()); + Void::Testing::expect_eq(static_cast(published->outcome), + static_cast(PublicationOutcome::Published)); + Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/bin/tool"), + std::string{"isolated-ok"}); + Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/data/info.txt"), + std::string{"verified-by-parent"}); + + // Worker limit violation returns limit_exceeded and cleans staging. + IsolationOptions tight = iso; + tight.extraction.limits.max_file_bytes = 4; + auto failed = extract_staged_isolated(archive_path, parent_dir, tight); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect_eq( + failed.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); +#else + Void::Testing::expect(true); +#endif +}