3110 lines
97 KiB
C++
3110 lines
97 KiB
C++
#include <Void/Archive/Archive.hpp>
|
|
#include <Void/System/Process.hpp>
|
|
|
|
#include "BuiltinTar.hpp"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <cerrno>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <cstring>
|
|
#include <format>
|
|
#include <fstream>
|
|
#include <limits>
|
|
#include <map>
|
|
#include <set>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
#include <archive.h>
|
|
#include <archive_entry.h>
|
|
#endif
|
|
|
|
#ifndef _WIN32
|
|
#include <dirent.h>
|
|
#include <fcntl.h>
|
|
#include <sys/resource.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/syscall.h>
|
|
#include <unistd.h>
|
|
#ifdef __linux__
|
|
#include <linux/fs.h>
|
|
#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<std::uint64_t> 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";
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
using ArchiveReadPtr =
|
|
std::unique_ptr<archive, decltype(&archive_read_free)>;
|
|
using ArchiveWritePtr =
|
|
std::unique_ptr<archive, decltype(&archive_write_free)>;
|
|
using ArchiveEntryPtr =
|
|
std::unique_ptr<archive_entry, decltype(&archive_entry_free)>;
|
|
#endif
|
|
|
|
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()});
|
|
}
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
[[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));
|
|
}
|
|
#endif
|
|
|
|
[[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<std::string> components{};
|
|
};
|
|
|
|
[[nodiscard]] Void::Result::Result<ValidatedPath>
|
|
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<void>
|
|
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<std::string>&
|
|
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<std::string> m_files{};
|
|
std::set<std::string> m_explicit_dirs{};
|
|
std::set<std::string> m_all_dirs{};
|
|
};
|
|
|
|
[[nodiscard]] Void::Result::Result<void>
|
|
write_all_fd(int fd, std::span<const std::byte> data)
|
|
{
|
|
std::size_t written = 0;
|
|
while (written < data.size()) {
|
|
const ssize_t n = ::write(
|
|
fd,
|
|
reinterpret_cast<const char*>(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<std::size_t>(n);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<void>
|
|
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<void>
|
|
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<void> 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<void>
|
|
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<OwnedFd>
|
|
open_or_create_relative_dir(int root_fd,
|
|
const std::vector<std::string>& 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<void>
|
|
fsync_directories_bottom_up(int tree_fd,
|
|
const std::set<std::string>& dirs)
|
|
{
|
|
std::vector<std::string> 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<std::uint64_t> 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<std::uint64_t>(page_size);
|
|
}
|
|
|
|
[[nodiscard]] std::string
|
|
serialize_inventory(const std::vector<EntryInfo>& 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<std::vector<EntryInfo>>
|
|
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<EntryInfo> 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<void>
|
|
verify_staged_tree_on_disk(int tree_fd,
|
|
const std::vector<EntryInfo>& inventory,
|
|
const ReadLimits& limits,
|
|
std::uint64_t& out_verified_bytes)
|
|
{
|
|
std::map<std::string, const EntryInfo*> expected_files;
|
|
std::set<std::string> 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<std::string> seen_files;
|
|
std::set<std::string> seen_dirs;
|
|
out_verified_bytes = 0;
|
|
|
|
std::function<Void::Result::Result<void>(int, const std::string&,
|
|
std::size_t)>
|
|
walk = [&](int dir_fd, const std::string& prefix,
|
|
std::size_t depth) -> Void::Result::Result<void> {
|
|
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<void> 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<std::uint64_t>(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
|
|
|
|
bool has_libarchive_backend() noexcept
|
|
{
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
return true;
|
|
#else
|
|
return false;
|
|
#endif
|
|
}
|
|
|
|
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<unsigned char>(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<char>(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<std::size_t>
|
|
SpanByteSource::read(std::span<std::byte> 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> 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>
|
|
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>();
|
|
impl->fd = std::move(fd);
|
|
return FileByteSource{std::move(impl)};
|
|
}
|
|
|
|
Void::Result::Result<std::size_t>
|
|
FileByteSource::read(std::span<std::byte> 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<std::size_t>(n);
|
|
}
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
VectorByteSink::write(std::span<const std::byte> 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> 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>
|
|
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>();
|
|
impl->fd = std::move(fd);
|
|
return FileByteSink{std::move(impl)};
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
FileByteSink::write(std::span<const std::byte> 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<void> 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<FileByteSource> owned_source{};
|
|
ByteSource* source{nullptr};
|
|
ReadLimits limits{};
|
|
std::stop_token stop{};
|
|
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
|
|
const Void::Time::MonotonicClock* clock{
|
|
&Void::Time::SystemMonotonicClock::instance()};
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
ArchiveReadPtr handle{nullptr, &archive_read_free};
|
|
std::vector<std::byte> read_buf{};
|
|
std::optional<Void::Result::Error> source_error{};
|
|
#endif
|
|
std::unique_ptr<Detail::BuiltinTarStream> builtin_stream{};
|
|
bool using_builtin{false};
|
|
PathTracker tracker;
|
|
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),
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
read_buf(lim.transfer_buffer_bytes),
|
|
#endif
|
|
tracker(lim.max_metadata_bytes)
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<void> 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 {};
|
|
}
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
static la_ssize_t libarchive_read_cb(archive* a, void* client_data,
|
|
const void** buffer)
|
|
{
|
|
auto* self = static_cast<Impl*>(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<std::uint64_t>(*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<la_ssize_t>(n);
|
|
}
|
|
#endif
|
|
};
|
|
|
|
Reader::Reader(std::unique_ptr<Impl> 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> Reader::open(
|
|
ByteSource& source, ReadLimits limits, std::stop_token stop,
|
|
std::optional<Void::Time::MonotonicClock::time_point> 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<Impl>(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())};
|
|
}
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
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_gzip(impl->handle.get());
|
|
(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)};
|
|
}
|
|
impl->using_builtin = false;
|
|
#else
|
|
impl->builtin_stream = std::make_unique<Detail::BuiltinTarStream>(
|
|
source, limits, stop, deadline, clock);
|
|
if (auto opened = impl->builtin_stream->open(); !opened.has_value()) {
|
|
return std::unexpected{std::move(opened.error())};
|
|
}
|
|
impl->total_compressed = impl->builtin_stream->total_compressed_bytes();
|
|
impl->using_builtin = true;
|
|
#endif
|
|
return Reader{std::move(impl)};
|
|
}
|
|
|
|
Void::Result::Result<Reader> Reader::open_file(
|
|
const std::filesystem::path& archive_path, ReadLimits limits,
|
|
std::stop_token stop,
|
|
std::optional<Void::Time::MonotonicClock::time_point> 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<FileByteSource>(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<std::optional<EntryInfo>> 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<EntryInfo>{std::nullopt};
|
|
}
|
|
if (auto chk = m_impl->check_stop_deadline(); !chk.has_value()) {
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{std::move(chk.error())};
|
|
}
|
|
|
|
if (m_impl->using_builtin) {
|
|
auto next = m_impl->builtin_stream->next_entry();
|
|
m_impl->total_compressed =
|
|
m_impl->builtin_stream->total_compressed_bytes();
|
|
if (!next.has_value()) {
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{std::move(next.error())};
|
|
}
|
|
if (!next->has_value()) {
|
|
m_impl->reached_eof = true;
|
|
return std::optional<EntryInfo>{std::nullopt};
|
|
}
|
|
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 auto& raw = **next;
|
|
if (raw.path.empty()) {
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{make_archive_error(
|
|
ArchiveErrorCode::unsafe_entry,
|
|
"Archive::Reader: entry has no pathname")};
|
|
}
|
|
if (raw.type == EntryType::Hardlink ||
|
|
raw.type == EntryType::Symlink || !raw.linkname.empty()) {
|
|
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)))};
|
|
}
|
|
if (raw.type != EntryType::Directory &&
|
|
raw.type != EntryType::RegularFile) {
|
|
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 = (raw.type == EntryType::Directory);
|
|
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) {
|
|
declared_size = raw.declared_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 = (raw.mode & 0111U) != 0U;
|
|
m_impl->has_active_file = true;
|
|
m_impl->entry_bytes_read = 0;
|
|
}
|
|
|
|
return std::optional<EntryInfo>{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,
|
|
}};
|
|
}
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
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<EntryInfo>{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<std::uint64_t>(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>{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,
|
|
}};
|
|
#else
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{make_archive_error(
|
|
ArchiveErrorCode::unsupported_format,
|
|
"Archive::Reader: libarchive backend unavailable")};
|
|
#endif
|
|
}
|
|
|
|
Void::Result::Result<std::size_t>
|
|
Reader::read_chunk(std::span<std::byte> 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);
|
|
std::size_t read_bytes = 0;
|
|
if (m_impl->using_builtin) {
|
|
auto r =
|
|
m_impl->builtin_stream->read_entry_data(dst.subspan(0, to_read));
|
|
m_impl->total_compressed =
|
|
m_impl->builtin_stream->total_compressed_bytes();
|
|
if (!r.has_value()) {
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{std::move(r.error())};
|
|
}
|
|
read_bytes = *r;
|
|
if (read_bytes == 0) {
|
|
m_impl->has_active_file = false;
|
|
return std::size_t{0};
|
|
}
|
|
} else {
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
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")};
|
|
}
|
|
read_bytes = static_cast<std::size_t>(n);
|
|
#else
|
|
m_impl->poisoned = true;
|
|
return std::unexpected{make_archive_error(
|
|
ArchiveErrorCode::unsupported_format,
|
|
"Archive::Reader: libarchive backend unavailable")};
|
|
#endif
|
|
}
|
|
const auto amount = static_cast<std::uint64_t>(read_bytes);
|
|
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 read_bytes;
|
|
}
|
|
|
|
Void::Result::Result<std::uint64_t> 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<std::byte> 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<std::uint64_t>(*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<std::vector<EntryInfo>>
|
|
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<EntryInfo> 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.
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
struct ForensicState {
|
|
ByteSource* source{nullptr};
|
|
ReadLimits limits{};
|
|
std::vector<std::byte> buf{};
|
|
std::uint64_t compressed{0};
|
|
std::optional<Void::Result::Error> err{};
|
|
};
|
|
ForensicState st{&source, limits,
|
|
std::vector<std::byte>(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_gzip(handle.get());
|
|
(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<ForensicState*>(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<std::uint64_t>(*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<la_ssize_t>(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<EntryInfo> 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) : "<missing>";
|
|
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<std::uint64_t>(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;
|
|
#else
|
|
Detail::BuiltinTarStream stream{
|
|
source, limits, {}, std::nullopt,
|
|
Void::Time::SystemMonotonicClock::instance()};
|
|
if (auto opened = stream.open(); !opened.has_value()) {
|
|
return std::unexpected{std::move(opened.error())};
|
|
}
|
|
|
|
std::vector<EntryInfo> out;
|
|
PathTracker tracker{limits.max_metadata_bytes};
|
|
std::size_t metadata_bytes = 0;
|
|
for (;;) {
|
|
auto next = stream.next_entry();
|
|
if (!next.has_value()) {
|
|
return std::unexpected{std::move(next.error())};
|
|
}
|
|
if (!next->has_value()) {
|
|
break;
|
|
}
|
|
if (out.size() >= limits.max_entries) {
|
|
return std::unexpected{make_archive_error(
|
|
ArchiveErrorCode::limit_exceeded,
|
|
"Archive::list_entries: entry count exceeds limit")};
|
|
}
|
|
|
|
const auto& raw = **next;
|
|
const std::string sanitized =
|
|
raw.path.empty() ? "<missing>"
|
|
: 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;
|
|
if (raw.type == EntryType::Hardlink) {
|
|
info.type = EntryType::Hardlink;
|
|
info.accepted = false;
|
|
info.rejection_reason = "hardlink disallowed";
|
|
} else if (raw.type == EntryType::Symlink ||
|
|
!raw.linkname.empty()) {
|
|
info.type = EntryType::Symlink;
|
|
info.accepted = false;
|
|
info.rejection_reason = "symlink disallowed";
|
|
} else if (raw.type != EntryType::Directory &&
|
|
raw.type != EntryType::RegularFile) {
|
|
info.type = EntryType::Other;
|
|
info.accepted = false;
|
|
info.rejection_reason = "special file disallowed";
|
|
} else {
|
|
const bool is_dir = (raw.type == EntryType::Directory);
|
|
info.type =
|
|
is_dir ? EntryType::Directory : EntryType::RegularFile;
|
|
info.declared_size = raw.declared_size;
|
|
info.executable = !is_dir && ((raw.mode & 0111U) != 0U);
|
|
info.safe_mode =
|
|
is_dir ? 0755U : (info.executable ? 0755U : 0644U);
|
|
auto vp = validate_archive_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));
|
|
if (auto sk = stream.skip_entry_data(); !sk.has_value()) {
|
|
return std::unexpected{std::move(sk.error())};
|
|
}
|
|
}
|
|
return out;
|
|
#endif
|
|
}
|
|
|
|
Void::Result::Result<std::vector<EntryInfo>>
|
|
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<EntryInfo> 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> 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<EntryInfo>& StagedTree::inventory() const noexcept
|
|
{
|
|
static const std::vector<EntryInfo> kEmpty;
|
|
return m_impl ? m_impl->inventory : kEmpty;
|
|
}
|
|
|
|
Void::Result::Result<void> 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<PublicationReceipt>
|
|
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<int>(::syscall(
|
|
SYS_renameat2, m_impl->stage_fd.get(), "tree",
|
|
m_impl->parent_fd.get(), target_name.c_str(),
|
|
static_cast<unsigned int>(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<void> extract_into_pinned_stage(
|
|
ByteSource& source, int stage_fd, int tree_fd,
|
|
const StagedExtractionOptions& options, std::uint64_t max_rss_bytes,
|
|
std::vector<EntryInfo>& 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<std::string> created_dirs;
|
|
std::vector<std::byte> 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<void> {
|
|
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<const std::byte>{chunk.data(), *n});
|
|
!w.has_value()) {
|
|
return w;
|
|
}
|
|
actual_file_bytes += static_cast<std::uint64_t>(*n);
|
|
out_bytes += static_cast<std::uint64_t>(*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<std::uint32_t>(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<AllocatedStage>
|
|
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<long long>(::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::seconds>(
|
|
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<long long>(::getpid()),
|
|
static_cast<unsigned long>(::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<StagedTree>
|
|
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<EntryInfo> 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<StagedTree::Impl>();
|
|
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<StagedTree>
|
|
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<std::size_t>
|
|
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::seconds>(
|
|
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<char, 512> 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<std::size_t>(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<void>
|
|
create_archive(ByteSink& sink, std::span<const CreateEntry> 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<NormalizedCreate> 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<std::uint64_t>(st.st_size);
|
|
item.file_fd = std::move(fd);
|
|
} else {
|
|
item.size = static_cast<std::uint64_t>(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;
|
|
});
|
|
|
|
if (options.compression == ArchiveCompression::None &&
|
|
(options.prefer_builtin_tar || !has_libarchive_backend())) {
|
|
std::vector<Detail::BuiltinCreateItem> builtin_items;
|
|
builtin_items.reserve(normalized.size());
|
|
for (const auto& item : normalized) {
|
|
const bool is_dir = (item.src->type == EntryType::Directory);
|
|
const std::uint32_t perm =
|
|
item.src->mode.has_value()
|
|
? (*item.src->mode & 0777U)
|
|
: (is_dir ? 0755U
|
|
: (item.src->executable ? 0755U : 0644U));
|
|
builtin_items.push_back(Detail::BuiltinCreateItem{
|
|
.path = item.path,
|
|
.is_directory = is_dir,
|
|
.mode = perm,
|
|
.size = item.size,
|
|
.inline_content = item.src->content,
|
|
.source_fd = item.file_fd.get(),
|
|
});
|
|
}
|
|
return Detail::write_builtin_tar(sink, builtin_items, options);
|
|
}
|
|
|
|
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
|
|
struct SinkBridge {
|
|
ByteSink* sink{nullptr};
|
|
std::optional<Void::Result::Error> 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 (options.compression == ArchiveCompression::Gzip) {
|
|
if (archive_write_add_filter_gzip(writer.get()) != ARCHIVE_OK) {
|
|
return std::unexpected{
|
|
make_libarchive_error(writer.get(), "add gzip filter")};
|
|
}
|
|
if (options.reproducible) {
|
|
if (archive_write_set_filter_option(
|
|
writer.get(), "gzip", "timestamp", nullptr) !=
|
|
ARCHIVE_OK) {
|
|
return std::unexpected{make_libarchive_error(
|
|
writer.get(), "disable gzip timestamp header")};
|
|
}
|
|
}
|
|
} 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<SinkBridge*>(data);
|
|
auto res = b->sink->write(std::span<const std::byte>{
|
|
static_cast<const std::byte*>(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<la_ssize_t>(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<std::byte> 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;
|
|
const std::uint32_t perm =
|
|
item.src->mode.has_value()
|
|
? (*item.src->mode & 0777U)
|
|
: (is_dir ? 0755U
|
|
: (item.src->executable ? 0755U : 0644U));
|
|
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(), static_cast<mode_t>(perm));
|
|
if (options.reproducible) {
|
|
archive_entry_set_mtime(
|
|
ae.get(),
|
|
static_cast<std::time_t>(
|
|
std::max<std::int64_t>(0, options.canonical_mtime)),
|
|
0);
|
|
archive_entry_set_uid(
|
|
ae.get(), static_cast<la_int64_t>(options.canonical_uid));
|
|
archive_entry_set_gid(
|
|
ae.get(), static_cast<la_int64_t>(options.canonical_gid));
|
|
archive_entry_set_uname(ae.get(), "");
|
|
archive_entry_set_gname(ae.get(), "");
|
|
}
|
|
if (!is_dir) {
|
|
archive_entry_set_size(ae.get(),
|
|
static_cast<la_int64_t>(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::size_t>(
|
|
std::min<std::uint64_t>(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<std::size_t>(r)) {
|
|
const la_ssize_t w = archive_write_data(
|
|
writer.get(), io_buf.data() + off,
|
|
static_cast<std::size_t>(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<std::size_t>(w);
|
|
}
|
|
remaining -= static_cast<std::uint64_t>(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<std::size_t>(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 {};
|
|
#else
|
|
return std::unexpected{make_archive_error(
|
|
ArchiveErrorCode::unsupported_format,
|
|
"Archive::create_archive: compressed archives require "
|
|
"LibArchive backend")};
|
|
#endif
|
|
}
|
|
|
|
Void::Result::Result<void>
|
|
create_archive(const std::filesystem::path& output_path,
|
|
std::span<const CreateEntry> 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();
|
|
}
|
|
|
|
Void::Result::Result<void> create(ByteSink& sink,
|
|
std::span<const CreateEntry> entries,
|
|
const CreationOptions& options)
|
|
{
|
|
return create_archive(sink, entries, options);
|
|
}
|
|
|
|
Void::Result::Result<void> create(const std::filesystem::path& output_path,
|
|
std::span<const CreateEntry> entries,
|
|
const CreationOptions& options)
|
|
{
|
|
return create_archive(output_path, entries, options);
|
|
}
|
|
|
|
// ── Isolated Child Decoder Profile ───────────────────────────────────────
|
|
|
|
Void::Result::Result<StagedTree>
|
|
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<StagedTree> {
|
|
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<char, 4096> 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<std::size_t>(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<std::size_t>(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<StagedTree::Impl>();
|
|
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<std::size_t>(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<std::size_t>(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<rlim_t>(std::max<std::uint64_t>(
|
|
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<rlim_t>(
|
|
std::max<std::uint64_t>(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<EntryInfo> 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<std::int32_t>(ArchiveErrorCode::limit_exceeded)) {
|
|
return 42;
|
|
}
|
|
return 5;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
} // namespace Void::Archive
|