feat(crypto,archive): implement VL-007 built-in hashes and VL-006 archive creation/gzip/tar fallback

This commit is contained in:
faumaray committed 2026-11-26 20:55:45 +03:00
1 parent b50131f52e
commit 22c8538754
19 files changed
+3326 -133

No files matched your search

+148 -30
View File
@@ -1,10 +1,13 @@
#include <Void/Archive/Archive.hpp>
#include "BuiltinTar.hpp"
#include <array>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <format>
#include <limits>
#include <memory>
#include <optional>
#include <set>
@@ -13,8 +16,10 @@
#include <system_error>
#include <utility>
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
#include <archive.h>
#include <archive_entry.h>
#endif
#ifndef _WIN32
#include <fcntl.h>
@@ -28,6 +33,7 @@ namespace Void::Archive
{
namespace
{
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
using ArchiveHandle =
std::unique_ptr<archive, decltype(&archive_read_free)>;
@@ -39,6 +45,7 @@ namespace Void::Archive
"Archive::extract: {}: {}", operation,
message == nullptr ? "unknown archive error" : message)};
}
#endif
[[nodiscard]] std::optional<std::filesystem::path>
safe_relative_path(std::string_view rawPath, bool directory)
@@ -225,12 +232,14 @@ namespace Void::Archive
return {};
}
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, int rootDescriptor,
const std::filesystem::path &relative,
const std::filesystem::path &displayRoot,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted, bool executable)
extract_regular_stream(int rootDescriptor,
const std::filesystem::path &relative,
const std::filesystem::path &displayRoot,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted,
bool executable, ReadFn &&read_fn)
{
auto openedParent = open_parent_directory(
rootDescriptor, relative.parent_path(), displayRoot);
@@ -286,15 +295,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
auto chunk = read_fn(std::span{buffer});
if (!chunk.has_value()) {
return fail(chunk.error().message());
}
if (*chunk == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
const auto amount = static_cast<std::uint64_t>(*chunk);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -303,11 +311,11 @@ namespace Void::Archive
}
std::size_t written = 0;
while (written < static_cast<std::size_t>(count)) {
while (written < *chunk) {
const auto result = ::write(
descriptor.get(),
reinterpret_cast<const char *>(buffer.data()) + written,
static_cast<std::size_t>(count) - written);
*chunk - written);
if (result < 0 && errno == EINTR) {
continue;
}
@@ -448,10 +456,12 @@ namespace Void::Archive
return {};
}
template <typename ReadFn>
[[nodiscard]] Void::Result::Result<std::uint64_t>
extract_regular(archive *reader, const std::filesystem::path &path,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted)
extract_regular_stream(const std::filesystem::path &path,
const ExtractionOptions &options,
std::uint64_t alreadyExtracted,
ReadFn &&read_fn)
{
std::error_code error;
const auto status = std::filesystem::symlink_status(path, error);
@@ -486,15 +496,14 @@ namespace Void::Archive
std::array<std::byte, 64 * 1024> buffer{};
std::uint64_t fileBytes = 0;
for (;;) {
const auto count =
archive_read_data(reader, buffer.data(), buffer.size());
if (count == 0) {
auto chunk = read_fn(std::span{buffer});
if (!chunk.has_value()) {
return fail(chunk.error().message());
}
if (*chunk == 0) {
break;
}
if (count < 0) {
return fail(archive_error(reader, "read entry").message());
}
const auto amount = static_cast<std::uint64_t>(count);
const auto amount = static_cast<std::uint64_t>(*chunk);
if (amount > options.maxFileBytes - fileBytes ||
amount >
options.maxTotalBytes - alreadyExtracted - fileBytes) {
@@ -502,7 +511,7 @@ namespace Void::Archive
"Archive::extract: extracted size exceeds policy");
}
output.write(reinterpret_cast<const char *>(buffer.data()),
count);
static_cast<std::streamsize>(*chunk));
if (!output) {
return fail("Archive::extract: write failed");
}
@@ -544,11 +553,13 @@ namespace Void::Archive
}
#endif
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
ArchiveHandle reader{archive_read_new(), &archive_read_free};
if (!reader) {
return Void::Result::fail(
"Archive::extract: cannot allocate archive reader");
}
archive_read_support_filter_gzip(reader.get());
archive_read_support_filter_zstd(reader.get());
archive_read_support_filter_none(reader.get());
archive_read_support_format_tar(reader.get());
@@ -633,14 +644,23 @@ namespace Void::Archive
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_libarchive_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
const auto count =
archive_read_data(reader.get(), dst.data(), dst.size());
if (count < 0) {
return std::unexpected{archive_error(reader.get(), "read entry")};
}
return static_cast<std::size_t>(count);
};
#ifndef _WIN32
const bool executable = (archive_entry_perm(entry) & 0111) != 0;
auto extracted =
extract_regular(reader.get(), root->get(), *relative,
destination, options, result.bytes, executable);
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_libarchive_chunk);
#else
auto extracted =
extract_regular(reader.get(), output, options, result.bytes);
auto extracted = extract_regular_stream(
output, options, result.bytes, read_libarchive_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
@@ -648,5 +668,103 @@ namespace Void::Archive
result.bytes += *extracted;
}
return result;
#else
auto source = FileByteSource::open(archivePath);
if (!source.has_value()) {
return std::unexpected{std::move(source.error())};
}
ReadLimits limits;
limits.max_entries = options.maxEntries;
limits.max_file_bytes = options.maxFileBytes;
limits.max_total_bytes = options.maxTotalBytes;
limits.max_compressed_bytes = std::numeric_limits<std::uint64_t>::max();
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())};
}
ExtractionResult result;
std::set<std::filesystem::path> seen;
for (;;) {
auto next = stream.next_entry();
if (!next.has_value()) {
return std::unexpected{std::move(next.error())};
}
if (!next->has_value()) {
break;
}
if (++result.entries > options.maxEntries) {
return Void::Result::fail(
"Archive::extract: entry count exceeds policy");
}
const auto &entry = **next;
if (entry.type == EntryType::Hardlink ||
entry.type == EntryType::Symlink || !entry.linkname.empty()) {
return Void::Result::fail(
"Archive::extract: links are not allowed");
}
if (entry.type != EntryType::Directory &&
entry.type != EntryType::RegularFile) {
return Void::Result::fail(
"Archive::extract: special files are not allowed");
}
const bool is_dir = (entry.type == EntryType::Directory);
auto relative = safe_relative_path(entry.path, is_dir);
if (!relative || !seen.insert(*relative).second) {
return Void::Result::fail(std::format(
"Archive::extract: unsafe or duplicate path '{}'",
entry.path));
}
#ifdef _WIN32
if (auto parents = safe_parents(root, relative->parent_path());
!parents) {
return std::unexpected{parents.error()};
}
const auto output = root / *relative;
#endif
if (is_dir) {
#ifndef _WIN32
auto created =
create_directory_entry(root->get(), *relative, destination,
options.overwriteExisting);
#else
auto created =
create_directory_entry(output, options.overwriteExisting);
#endif
if (!created) {
return std::unexpected{created.error()};
}
continue;
}
if (entry.declared_size > options.maxFileBytes ||
entry.declared_size > options.maxTotalBytes - result.bytes) {
return Void::Result::fail(
"Archive::extract: declared entry size exceeds policy");
}
auto read_builtin_chunk =
[&](std::span<std::byte> dst) -> Void::Result::Result<std::size_t> {
return stream.read_entry_data(dst);
};
#ifndef _WIN32
const bool executable = (entry.mode & 0111U) != 0U;
auto extracted = extract_regular_stream(
root->get(), *relative, destination, options, result.bytes,
executable, read_builtin_chunk);
#else
auto extracted = extract_regular_stream(
output, options, result.bytes, read_builtin_chunk);
#endif
if (!extracted) {
return std::unexpected{extracted.error()};
}
result.bytes += *extracted;
}
return result;
#endif
}
} // namespace Void::Archive
+867
View File
@@ -0,0 +1,867 @@
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <cstring>
#include <format>
#include <string_view>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace Void::Archive::Detail
{
namespace
{
constexpr std::size_t kTarBlockSize = 512;
[[nodiscard]] bool is_zero_block(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
for (const std::byte b : block) {
if (b != std::byte{0}) {
return false;
}
}
return true;
}
inline void write_octal(std::span<std::byte> field, std::uint64_t value) noexcept
{
if (field.size() < 2) {
return;
}
field.back() = std::byte{0};
std::size_t pos = field.size() - 1;
while (pos > 0) {
--pos;
field[pos] = static_cast<std::byte>('0' + (value & 7ULL));
value >>= 3ULL;
}
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
parse_octal(std::span<const std::byte> field, const char* name)
{
const auto* p = reinterpret_cast<const unsigned char*>(field.data());
std::size_t n = field.size();
if (n > 0 && (p[0] & 0x80U) != 0U) {
// POSIX / GNU big-endian base-256 unsigned extension.
if ((p[0] & 0x40U) != 0U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: negative base-256 field '{}'",
name))};
}
std::uint64_t v = static_cast<std::uint64_t>(p[0] & 0x3FU);
for (std::size_t i = 1; i < n; ++i) {
if (v > (std::numeric_limits<std::uint64_t>::max() >> 8U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: overflowing field '{}'",
name))};
}
v = (v << 8U) | static_cast<std::uint64_t>(p[i]);
}
return v;
}
std::size_t i = 0;
while (i < n && (p[i] == ' ' || p[i] == '\0')) {
++i;
}
if (i == n) {
return std::uint64_t{0};
}
std::uint64_t out = 0;
bool saw_digit = false;
for (; i < n; ++i) {
if (p[i] == '\0' || p[i] == ' ') {
break;
}
if (p[i] < '0' || p[i] > '7') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: invalid octal character in '{}'",
name))};
}
if (out > (std::numeric_limits<std::uint64_t>::max() >> 3U)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive: octal overflow in '{}'", name))};
}
out = (out << 3U) | static_cast<std::uint64_t>(p[i] - '0');
saw_digit = true;
}
if (!saw_digit) {
return std::uint64_t{0};
}
return out;
}
[[nodiscard]] std::string_view
c_field(std::span<const std::byte> field) noexcept
{
const char* s = reinterpret_cast<const char*>(field.data());
std::size_t len = 0;
while (len < field.size() && s[len] != '\0') {
++len;
}
return {s, len};
}
[[nodiscard]] std::uint32_t
compute_checksum_unsigned(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::uint32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::uint32_t>(' ');
} else {
sum += static_cast<std::uint32_t>(
std::to_integer<std::uint8_t>(block[i]));
}
}
return sum;
}
[[nodiscard]] std::int32_t
compute_checksum_signed(const std::array<std::byte, kTarBlockSize>& block) noexcept
{
std::int32_t sum = 0;
for (std::size_t i = 0; i < kTarBlockSize; ++i) {
if (i >= 148 && i < 156) {
sum += static_cast<std::int32_t>(' ');
} else {
sum += static_cast<std::int32_t>(
static_cast<signed char>(
std::to_integer<unsigned char>(block[i])));
}
}
return sum;
}
void build_ustar_header(std::array<std::byte, kTarBlockSize>& hdr,
std::string_view wire_name, char typeflag,
std::uint32_t mode, std::uint32_t uid,
std::uint32_t gid, std::uint64_t size,
std::uint64_t mtime) noexcept
{
hdr.fill(std::byte{0});
// Split into prefix (<=155) + name (<=100) only when needed and valid;
// callers handling paths >255 emit PAX 'x' before this header.
std::string_view prefix{};
std::string_view name = wire_name;
if (wire_name.size() > 100) {
const std::size_t min_split =
wire_name.size() > 100 ? wire_name.size() - 101 : 0;
const std::size_t max_split = std::min<std::size_t>(155, wire_name.size() - 1);
std::size_t chosen = std::string_view::npos;
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_name.size() && wire_name[pos] == '/') {
const std::string_view cand_prefix = wire_name.substr(0, pos);
const std::string_view cand_name = wire_name.substr(pos + 1);
if (!cand_prefix.empty() && cand_prefix.size() <= 155 &&
!cand_name.empty() && cand_name.size() <= 100) {
chosen = pos;
break;
}
}
if (pos == 0) {
break;
}
}
if (chosen != std::string_view::npos) {
prefix = wire_name.substr(0, chosen);
name = wire_name.substr(chosen + 1);
} else {
name = wire_name.substr(0, 100);
}
}
std::memcpy(hdr.data() + 0, name.data(), std::min<std::size_t>(name.size(), 100));
write_octal(std::span{hdr}.subspan(100, 8), mode & 07777U);
write_octal(std::span{hdr}.subspan(108, 8), uid);
write_octal(std::span{hdr}.subspan(116, 8), gid);
// Clamp size field to 11 octal digits when PAX overrides size.
const std::uint64_t ustar_size =
size <= 077777777777ULL ? size : 0ULL;
write_octal(std::span{hdr}.subspan(124, 12), ustar_size);
write_octal(std::span{hdr}.subspan(136, 12), mtime);
std::fill(hdr.begin() + 148, hdr.begin() + 156, std::byte{' '});
hdr[156] = static_cast<std::byte>(typeflag);
std::memcpy(hdr.data() + 257, "ustar\0", 6);
hdr[263] = std::byte{'0'};
hdr[264] = std::byte{'0'};
write_octal(std::span{hdr}.subspan(329, 8), 0);
write_octal(std::span{hdr}.subspan(337, 8), 0);
if (!prefix.empty()) {
std::memcpy(hdr.data() + 345, prefix.data(),
std::min<std::size_t>(prefix.size(), 155));
}
const std::uint32_t sum = compute_checksum_unsigned(hdr);
write_octal(std::span{hdr}.subspan(148, 7), sum);
hdr[155] = std::byte{' '};
}
[[nodiscard]] std::string
make_pax_record(std::string_view key, std::string_view value)
{
const std::size_t rest_len = 1U + key.size() + 1U + value.size() + 1U;
std::size_t total = rest_len + 1U;
for (;;) {
const std::string digits = std::to_string(total);
const std::size_t next = digits.size() + rest_len;
if (next == total) {
break;
}
total = next;
}
return std::format("{} {}={}\n", total, key, value);
}
[[nodiscard]] Void::Result::Result<void>
write_padding(ByteSink& sink, std::uint64_t written)
{
const std::size_t rem = static_cast<std::size_t>(written % kTarBlockSize);
if (rem == 0) {
return {};
}
std::array<std::byte, kTarBlockSize> zeros{};
return sink.write(std::span{zeros}.subspan(0, kTarBlockSize - rem));
}
[[nodiscard]] bool
can_fit_ustar_path(std::string_view wire_path) noexcept
{
if (wire_path.size() <= 100) {
return true;
}
if (wire_path.size() > 256) {
return false;
}
const std::size_t min_split = wire_path.size() - 101;
const std::size_t max_split = std::min<std::size_t>(155, wire_path.size() - 1);
for (std::size_t pos = max_split; pos >= min_split; --pos) {
if (pos < wire_path.size() && wire_path[pos] == '/') {
const std::size_t p_len = pos;
const std::size_t n_len = wire_path.size() - (pos + 1);
if (p_len >= 1 && p_len <= 155 && n_len >= 1 && n_len <= 100) {
return true;
}
}
if (pos == 0) {
break;
}
}
return false;
}
[[nodiscard]] Void::Result::Result<void>
parse_pax_records(std::string_view payload, std::string& path_out,
std::string& link_out,
std::optional<std::uint64_t>& size_out,
std::size_t max_path_bytes)
{
std::size_t pos = 0;
while (pos < payload.size()) {
const std::size_t sp = payload.find(' ', pos);
if (sp == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: malformed PAX record length")};
}
std::size_t rec_len = 0;
const auto lr = std::from_chars(payload.data() + pos,
payload.data() + sp, rec_len);
if (lr.ec != std::errc{} || lr.ptr != payload.data() + sp ||
rec_len == 0 || pos + rec_len > payload.size() ||
sp >= pos + rec_len) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX extended header record length")};
}
const std::string_view rec =
payload.substr(sp + 1, pos + rec_len - (sp + 1));
if (rec.empty() || rec.back() != '\n') {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing trailing newline")};
}
const std::string_view kv = rec.substr(0, rec.size() - 1);
const std::size_t eq = kv.find('=');
if (eq == std::string_view::npos) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: PAX record missing '='")};
}
const std::string_view key = kv.substr(0, eq);
const std::string_view val = kv.substr(eq + 1);
if (key == "path") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX path exceeds configured limit")};
}
path_out.assign(val);
} else if (key == "linkpath") {
if (val.size() > max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive: PAX linkpath exceeds configured limit")};
}
link_out.assign(val);
} else if (key == "size") {
std::uint64_t parsed_size = 0;
const auto sr = std::from_chars(
val.data(), val.data() + val.size(), parsed_size);
if (sr.ec != std::errc{} ||
sr.ptr != val.data() + val.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive: invalid PAX size field")};
}
size_out = parsed_size;
}
pos += rec_len;
}
return {};
}
} // namespace
Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options)
{
const std::uint64_t mtime =
options.reproducible
? static_cast<std::uint64_t>(std::max<std::int64_t>(
0, options.canonical_mtime))
: static_cast<std::uint64_t>(std::max<std::int64_t>(
0,
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count()));
const std::uint32_t uid =
options.reproducible ? options.canonical_uid : 0U;
const std::uint32_t gid =
options.reproducible ? options.canonical_gid : 0U;
std::array<std::byte, kTarBlockSize> hdr{};
std::vector<std::byte> io_buf(options.limits.transfer_buffer_bytes);
for (const auto& item : items) {
if (options.stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::create_archive: cancelled")};
}
const std::string wire_path =
item.is_directory ? (item.path + "/") : item.path;
const bool need_pax_path = !can_fit_ustar_path(wire_path);
const bool need_pax_size = item.size > 077777777777ULL;
if (need_pax_path || need_pax_size) {
std::string pax;
if (need_pax_path) {
pax += make_pax_record("path", wire_path);
}
if (need_pax_size) {
pax += make_pax_record("size", std::to_string(item.size));
}
std::string pax_name = "PaxHeaders.0/";
const std::size_t suffix_take = std::min<std::size_t>(
100U - pax_name.size(), item.path.size());
pax_name.append(item.path.substr(0, suffix_take));
build_ustar_header(hdr, pax_name, 'x', 0644U, 0U, 0U,
pax.size(), 0ULL);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
const auto pax_bytes =
std::as_bytes(std::span{pax.data(), pax.size()});
if (auto w = sink.write(pax_bytes); !w.has_value()) {
return w;
}
if (auto p = write_padding(sink, pax.size()); !p.has_value()) {
return p;
}
}
build_ustar_header(hdr, wire_path, item.is_directory ? '5' : '0',
item.mode, uid, gid, item.size, mtime);
if (auto w = sink.write(hdr); !w.has_value()) {
return w;
}
if (!item.is_directory) {
if (item.source_fd >= 0) {
#ifndef _WIN32
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.source_fd, 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")};
}
if (auto w = sink.write(std::span<const std::byte>{
io_buf.data(), static_cast<std::size_t>(r)});
!w.has_value()) {
return w;
}
remaining -= static_cast<std::uint64_t>(r);
}
#endif
} else if (!item.inline_content.empty()) {
if (auto w = sink.write(item.inline_content);
!w.has_value()) {
return w;
}
}
if (auto p = write_padding(sink, item.size); !p.has_value()) {
return p;
}
}
}
// Standard two 512-byte zero EOF blocks.
std::array<std::byte, kTarBlockSize * 2> eof_blocks{};
return sink.write(eof_blocks);
}
BuiltinTarStream::BuiltinTarStream(
ByteSource& source, const ReadLimits& limits, std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock)
: m_source(&source), m_limits(limits), m_stop(std::move(stop)),
m_deadline(deadline), m_clock(&clock)
{
}
Void::Result::Result<void> BuiltinTarStream::check_stop_deadline() const
{
if (m_stop.stop_requested()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::cancelled,
"Archive::Reader: operation cancelled")};
}
if (m_deadline.has_value() && m_clock->now() >= *m_deadline) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::timeout,
"Archive::Reader: deadline expired")};
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_exact_or_eof(std::span<std::byte> dst)
{
std::size_t filled = 0;
if (m_prefetch_off < m_prefetch.size()) {
const std::size_t take =
std::min(dst.size(), m_prefetch.size() - m_prefetch_off);
std::memcpy(dst.data(), m_prefetch.data() + m_prefetch_off, take);
m_prefetch_off += take;
filled += take;
if (m_prefetch_off == m_prefetch.size()) {
m_prefetch.clear();
m_prefetch_off = 0;
}
}
while (filled < dst.size()) {
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return std::unexpected{std::move(chk.error())};
}
const std::size_t want = dst.size() - filled;
auto r = m_source->read(dst.subspan(filled, want));
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
if (*r == 0) {
break;
}
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes - m_total_compressed) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: compressed input exceeds limit")};
}
m_total_compressed += n;
filled += *r;
}
return filled;
}
Void::Result::Result<void>
BuiltinTarStream::read_exact_required(std::span<std::byte> dst,
const char* context)
{
auto n = read_exact_or_eof(dst);
if (!n.has_value()) {
return std::unexpected{std::move(n.error())};
}
if (*n != dst.size()) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
std::format("Archive::Reader: unexpected EOF while reading {}",
context))};
}
return {};
}
Void::Result::Result<void>
BuiltinTarStream::discard_bytes(std::uint64_t count,
const char* context)
{
std::array<std::byte, 4096> scratch{};
std::uint64_t rem = count;
while (rem > 0) {
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(rem, scratch.size()));
if (auto r = read_exact_required(std::span{scratch}.subspan(0, want),
context);
!r.has_value()) {
return r;
}
rem -= want;
}
return {};
}
Void::Result::Result<void> BuiltinTarStream::open()
{
if (auto chk = check_stop_deadline(); !chk.has_value()) {
return chk;
}
m_prefetch.resize(std::min<std::size_t>(512U,
m_limits.transfer_buffer_bytes));
auto r = m_source->read(m_prefetch);
if (!r.has_value()) {
return std::unexpected{std::move(r.error())};
}
m_prefetch.resize(*r);
m_prefetch_off = 0;
const auto n = static_cast<std::uint64_t>(*r);
if (n > m_limits.max_compressed_bytes) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: input exceeds compressed limit")};
}
m_total_compressed = n;
if (*r == 0) {
m_reached_eof = true;
return {};
}
// Reject compressed streams cleanly when LibArchive is unavailable.
if (m_prefetch.size() >= 2 &&
m_prefetch[0] == std::byte{0x1F} &&
m_prefetch[1] == std::byte{0x8B}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: gzip archives require LibArchive backend")};
}
if (m_prefetch.size() >= 4 &&
m_prefetch[0] == std::byte{0x28} &&
m_prefetch[1] == std::byte{0xB5} &&
m_prefetch[2] == std::byte{0x2F} &&
m_prefetch[3] == std::byte{0xFD}) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::unsupported_format,
"Archive::Reader: zstd archives require LibArchive backend")};
}
return {};
}
Void::Result::Result<std::optional<BuiltinTarEntry>>
BuiltinTarStream::next_entry()
{
if (m_reached_eof) {
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (m_has_active_entry) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::conflict,
"Archive::Reader: active entry must be drained or skipped")};
}
std::string next_pax_path;
std::string next_pax_link;
std::optional<std::uint64_t> next_pax_size;
std::string global_pax_path;
std::string global_pax_link;
std::optional<std::uint64_t> global_pax_size;
std::string gnu_long_name;
std::string gnu_long_link;
std::array<std::byte, kTarBlockSize> hdr{};
for (;;) {
auto nread = read_exact_or_eof(hdr);
if (!nread.has_value()) {
return std::unexpected{std::move(nread.error())};
}
if (*nread == 0) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
if (*nread != kTarBlockSize) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: truncated tar header block")};
}
if (is_zero_block(hdr)) {
m_reached_eof = true;
return std::optional<BuiltinTarEntry>{std::nullopt};
}
auto recorded_sum = parse_octal(std::span{hdr}.subspan(148, 8),
"chksum");
if (!recorded_sum.has_value()) {
return std::unexpected{std::move(recorded_sum.error())};
}
const std::uint32_t usum = compute_checksum_unsigned(hdr);
const std::int32_t ssum = compute_checksum_signed(hdr);
if (*recorded_sum != usum &&
static_cast<std::int64_t>(*recorded_sum) !=
static_cast<std::int64_t>(ssum)) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::corrupt_archive,
"Archive::Reader: tar header checksum mismatch")};
}
auto parsed_mode =
parse_octal(std::span{hdr}.subspan(100, 8), "mode");
if (!parsed_mode.has_value()) {
return std::unexpected{std::move(parsed_mode.error())};
}
auto parsed_size =
parse_octal(std::span{hdr}.subspan(124, 12), "size");
if (!parsed_size.has_value()) {
return std::unexpected{std::move(parsed_size.error())};
}
const char typeflag = static_cast<char>(std::to_integer<unsigned char>(hdr[156]));
if (typeflag == 'x' || typeflag == 'g' || typeflag == 'L' ||
typeflag == 'K') {
if (*parsed_size > m_limits.max_metadata_bytes ||
*parsed_size >
m_limits.max_metadata_bytes - m_metadata_budget_used) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: tar extended header exceeds metadata "
"limit")};
}
m_metadata_budget_used += static_cast<std::size_t>(*parsed_size);
std::string payload(static_cast<std::size_t>(*parsed_size), '\0');
if (!payload.empty()) {
if (auto rr = read_exact_required(
std::as_writable_bytes(std::span{payload}),
"extended tar header");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
}
const std::size_t pad =
static_cast<std::size_t>((kTarBlockSize - (*parsed_size % kTarBlockSize)) % kTarBlockSize);
if (pad > 0) {
if (auto dr = discard_bytes(pad, "extended header padding");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (typeflag == 'x') {
if (auto pr = parse_pax_records(
payload, next_pax_path, next_pax_link,
next_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else if (typeflag == 'g') {
if (auto pr = parse_pax_records(
payload, global_pax_path, global_pax_link,
global_pax_size, m_limits.max_path_bytes);
!pr.has_value()) {
return std::unexpected{std::move(pr.error())};
}
} else {
while (!payload.empty() && payload.back() == '\0') {
payload.pop_back();
}
if (payload.size() > m_limits.max_path_bytes + 1U) {
return std::unexpected{make_archive_error(
ArchiveErrorCode::limit_exceeded,
"Archive::Reader: GNU long name exceeds limit")};
}
if (typeflag == 'L') {
gnu_long_name = std::move(payload);
} else {
gnu_long_link = std::move(payload);
}
}
continue;
}
const std::string_view magic_view =
c_field(std::span{hdr}.subspan(257, 6));
std::string path;
if (!next_pax_path.empty()) {
path = std::move(next_pax_path);
} else if (!gnu_long_name.empty()) {
path = std::move(gnu_long_name);
} else if (!global_pax_path.empty()) {
path = global_pax_path;
} else {
const std::string_view name =
c_field(std::span{hdr}.subspan(0, 100));
const std::string_view prefix =
magic_view.starts_with("ustar")
? c_field(std::span{hdr}.subspan(345, 155))
: std::string_view{};
if (!prefix.empty()) {
path = std::string{prefix} + "/" + std::string{name};
} else {
path.assign(name);
}
}
std::string link;
if (!next_pax_link.empty()) {
link = std::move(next_pax_link);
} else if (!gnu_long_link.empty()) {
link = std::move(gnu_long_link);
} else if (!global_pax_link.empty()) {
link = global_pax_link;
} else {
link.assign(c_field(std::span{hdr}.subspan(157, 100)));
}
const std::uint64_t entry_size =
next_pax_size.has_value()
? *next_pax_size
: (global_pax_size.has_value() ? *global_pax_size
: *parsed_size);
EntryType etype = EntryType::Other;
if (typeflag == '1') {
etype = EntryType::Hardlink;
} else if (typeflag == '2') {
etype = EntryType::Symlink;
} else if (typeflag == '5') {
etype = EntryType::Directory;
} else if (typeflag == '0' || typeflag == '\0') {
if (typeflag == '\0' && !magic_view.starts_with("ustar") &&
entry_size == 0 && path.ends_with('/')) {
etype = EntryType::Directory;
} else {
etype = EntryType::RegularFile;
}
}
BuiltinTarEntry out{};
out.path = std::move(path);
out.linkname = std::move(link);
out.type = etype;
out.mode = static_cast<std::uint32_t>(*parsed_mode & 07777ULL);
out.declared_size =
(etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_size = (etype == EntryType::RegularFile) ? entry_size : 0ULL;
m_entry_remaining = m_entry_size;
m_has_active_entry = (etype == EntryType::RegularFile);
// Non-regular entries with declared non-zero payload must advance
// over padding if any (standard tar has 0 size for dirs/links).
if (!m_has_active_entry && entry_size > 0) {
const std::uint64_t pad =
(kTarBlockSize - (entry_size % kTarBlockSize)) % kTarBlockSize;
if (auto dr = discard_bytes(entry_size + pad,
"non-regular entry payload");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
return std::optional<BuiltinTarEntry>{std::move(out)};
}
}
Void::Result::Result<void> BuiltinTarStream::finish_active_entry_padding()
{
m_has_active_entry = false;
const std::uint64_t pad =
(kTarBlockSize - (m_entry_size % kTarBlockSize)) % kTarBlockSize;
m_entry_size = 0;
m_entry_remaining = 0;
if (pad > 0) {
return discard_bytes(pad, "tar entry block padding");
}
return {};
}
Void::Result::Result<std::size_t>
BuiltinTarStream::read_entry_data(std::span<std::byte> dst)
{
if (!m_has_active_entry) {
return std::size_t{0};
}
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return std::size_t{0};
}
if (dst.empty()) {
return std::size_t{0};
}
const std::size_t want = static_cast<std::size_t>(
std::min<std::uint64_t>(dst.size(), m_entry_remaining));
if (auto rr = read_exact_required(dst.subspan(0, want),
"tar entry data");
!rr.has_value()) {
return std::unexpected{std::move(rr.error())};
}
m_entry_remaining -= want;
if (m_entry_remaining == 0) {
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
}
return want;
}
Void::Result::Result<std::uint64_t> BuiltinTarStream::skip_entry_data()
{
if (!m_has_active_entry) {
return std::uint64_t{0};
}
const std::uint64_t skipped = m_entry_remaining;
const std::uint64_t rem = m_entry_remaining;
m_entry_remaining = 0;
if (rem > 0) {
if (auto dr = discard_bytes(rem, "tar entry data");
!dr.has_value()) {
return std::unexpected{std::move(dr.error())};
}
}
if (auto fin = finish_active_entry_padding(); !fin.has_value()) {
return std::unexpected{std::move(fin.error())};
}
return skipped;
}
} // namespace Void::Archive::Detail
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <Void/Archive/Types.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
namespace Void::Archive::Detail
{
struct BuiltinCreateItem {
std::string path{};
bool is_directory{false};
std::uint32_t mode{0644};
std::uint64_t size{0};
std::span<const std::byte> inline_content{};
int source_fd{-1};
};
[[nodiscard]] Void::Result::Result<void>
write_builtin_tar(ByteSink& sink,
std::span<const BuiltinCreateItem> items,
const CreationOptions& options);
struct BuiltinTarEntry {
std::string path{};
std::string linkname{};
EntryType type{EntryType::RegularFile};
std::uint64_t declared_size{0};
std::uint32_t mode{0644};
};
class BuiltinTarStream
{
public:
BuiltinTarStream(
ByteSource& source, const ReadLimits& limits,
std::stop_token stop,
std::optional<Void::Time::MonotonicClock::time_point> deadline,
const Void::Time::MonotonicClock& clock);
[[nodiscard]] Void::Result::Result<void> open();
[[nodiscard]] Void::Result::Result<std::optional<BuiltinTarEntry>>
next_entry();
[[nodiscard]] Void::Result::Result<std::size_t>
read_entry_data(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<std::uint64_t> skip_entry_data();
[[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept
{
return m_total_compressed;
}
private:
[[nodiscard]] Void::Result::Result<void> check_stop_deadline() const;
[[nodiscard]] Void::Result::Result<std::size_t>
read_exact_or_eof(std::span<std::byte> dst);
[[nodiscard]] Void::Result::Result<void>
read_exact_required(std::span<std::byte> dst,
const char* context);
[[nodiscard]] Void::Result::Result<void>
discard_bytes(std::uint64_t count, const char* context);
[[nodiscard]] Void::Result::Result<void>
finish_active_entry_padding();
ByteSource* m_source{nullptr};
ReadLimits m_limits{};
std::stop_token m_stop{};
std::optional<Void::Time::MonotonicClock::time_point> m_deadline{};
const Void::Time::MonotonicClock* m_clock{
&Void::Time::SystemMonotonicClock::instance()};
std::vector<std::byte> m_prefetch{};
std::size_t m_prefetch_off{0};
std::uint64_t m_total_compressed{0};
bool m_reached_eof{false};
bool m_has_active_entry{false};
std::uint64_t m_entry_size{0};
std::uint64_t m_entry_remaining{0};
std::size_t m_metadata_budget_used{0};
};
} // namespace Void::Archive::Detail
+326 -21
View File
@@ -1,6 +1,8 @@
#include <Void/Archive/Archive.hpp>
#include <Void/System/Process.hpp>
#include "BuiltinTar.hpp"
#include <algorithm>
#include <array>
#include <atomic>
@@ -18,8 +20,10 @@
#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>
@@ -51,12 +55,14 @@ namespace Void::Archive
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
{
@@ -129,6 +135,7 @@ namespace Void::Archive
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 =
@@ -140,6 +147,7 @@ namespace Void::Archive
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
@@ -894,6 +902,15 @@ namespace Void::Archive
}
} // 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;
@@ -1088,10 +1105,14 @@ namespace Void::Archive
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{};
PathTracker tracker;
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};
@@ -1101,7 +1122,10 @@ namespace Void::Archive
std::uint64_t total_compressed{0};
explicit Impl(const ReadLimits& lim)
: limits(lim), read_buf(lim.transfer_buffer_bytes),
: limits(lim),
#if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE
read_buf(lim.transfer_buffer_bytes),
#endif
tracker(lim.max_metadata_bytes)
{
}
@@ -1121,6 +1145,7 @@ namespace Void::Archive
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)
{
@@ -1150,6 +1175,7 @@ namespace Void::Archive
*buffer = self->read_buf.data();
return static_cast<la_ssize_t>(n);
}
#endif
};
Reader::Reader(std::unique_ptr<Impl> impl) noexcept
@@ -1178,6 +1204,7 @@ namespace Void::Archive
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) {
@@ -1185,6 +1212,7 @@ namespace Void::Archive
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());
@@ -1199,6 +1227,16 @@ namespace Void::Archive
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)};
}
@@ -1242,6 +1280,91 @@ namespace Void::Archive
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);
@@ -1335,6 +1458,12 @@ namespace Void::Archive
.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>
@@ -1358,21 +1487,46 @@ namespace Void::Archive
const std::size_t to_read =
std::min(dst.size(), m_impl->limits.transfer_buffer_bytes);
const la_ssize_t n =
archive_read_data(m_impl->handle.get(), dst.data(), to_read);
if (n == 0) {
m_impl->has_active_file = false;
return std::size_t{0};
}
if (n < 0) {
m_impl->poisoned = true;
if (m_impl->source_error.has_value()) {
return std::unexpected{std::move(*m_impl->source_error)};
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())};
}
return std::unexpected{
make_libarchive_error(m_impl->handle.get(), "read entry data")};
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>(n);
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) {
@@ -1383,7 +1537,7 @@ namespace Void::Archive
}
m_impl->entry_bytes_read += amount;
m_impl->total_decompressed += amount;
return static_cast<std::size_t>(n);
return read_bytes;
}
Void::Result::Result<std::uint64_t> Reader::skip_entry()
@@ -1462,6 +1616,7 @@ namespace Void::Archive
}
// 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{};
@@ -1477,6 +1632,7 @@ namespace Void::Archive
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());
@@ -1592,6 +1748,88 @@ namespace Void::Archive
(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>>
@@ -2314,6 +2552,30 @@ namespace Void::Archive
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{};
@@ -2331,6 +2593,19 @@ namespace Void::Archive
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{
@@ -2380,14 +2655,24 @@ namespace Void::Archive
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(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644));
archive_entry_set_perm(ae.get(), static_cast<mode_t>(perm));
if (options.reproducible) {
archive_entry_set_mtime(ae.get(), 0, 0);
archive_entry_set_uid(ae.get(), 0);
archive_entry_set_gid(ae.get(), 0);
archive_entry_set_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(), "");
}
@@ -2473,6 +2758,12 @@ namespace Void::Archive
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>
@@ -2491,6 +2782,20 @@ namespace Void::Archive
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>
+16 -1
View File
@@ -1,4 +1,19 @@
set(_void_archive_ext_deps "")
set(_void_archive_has_libarchive 0)
if(NOT CMAKE_DISABLE_FIND_PACKAGE_LibArchive)
if(NOT TARGET LibArchive::LibArchive)
find_package(LibArchive QUIET)
endif()
if(TARGET LibArchive::LibArchive)
list(APPEND _void_archive_ext_deps LibArchive::LibArchive)
set(_void_archive_has_libarchive 1)
endif()
endif()
void_add_module(Archive
INTERNAL_DEPS Functional Time System
EXTERNAL_DEPS LibArchive::LibArchive
EXTERNAL_DEPS ${_void_archive_ext_deps}
)
target_compile_definitions(Void_Archive PUBLIC
VOID_ARCHIVE_HAS_LIBARCHIVE=${_void_archive_has_libarchive}
)