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

+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>