#include "BuiltinTar.hpp" #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #endif namespace Void::Archive::Detail { namespace { constexpr std::size_t kTarBlockSize = 512; [[nodiscard]] bool is_zero_block(const std::array& block) noexcept { for (const std::byte b : block) { if (b != std::byte{0}) { return false; } } return true; } inline void write_octal(std::span 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('0' + (value & 7ULL)); value >>= 3ULL; } } [[nodiscard]] Void::Result::Result parse_octal(std::span field, const char* name) { const auto* p = reinterpret_cast(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(p[0] & 0x3FU); for (std::size_t i = 1; i < n; ++i) { if (v > (std::numeric_limits::max() >> 8U)) { return std::unexpected{make_archive_error( ArchiveErrorCode::corrupt_archive, std::format("Archive: overflowing field '{}'", name))}; } v = (v << 8U) | static_cast(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::max() >> 3U)) { return std::unexpected{make_archive_error( ArchiveErrorCode::corrupt_archive, std::format("Archive: octal overflow in '{}'", name))}; } out = (out << 3U) | static_cast(p[i] - '0'); saw_digit = true; } if (!saw_digit) { return std::uint64_t{0}; } return out; } [[nodiscard]] std::string_view c_field(std::span field) noexcept { const char* s = reinterpret_cast(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& block) noexcept { std::uint32_t sum = 0; for (std::size_t i = 0; i < kTarBlockSize; ++i) { if (i >= 148 && i < 156) { sum += static_cast(' '); } else { sum += static_cast( std::to_integer(block[i])); } } return sum; } [[nodiscard]] std::int32_t compute_checksum_signed(const std::array& block) noexcept { std::int32_t sum = 0; for (std::size_t i = 0; i < kTarBlockSize; ++i) { if (i >= 148 && i < 156) { sum += static_cast(' '); } else { sum += static_cast( static_cast( std::to_integer(block[i]))); } } return sum; } void build_ustar_header(std::array& 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(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(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(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(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 write_padding(ByteSink& sink, std::uint64_t written) { const std::size_t rem = static_cast(written % kTarBlockSize); if (rem == 0) { return {}; } std::array 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(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 parse_pax_records(std::string_view payload, std::string& path_out, std::string& link_out, std::optional& 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 write_builtin_tar(ByteSink& sink, std::span items, const CreationOptions& options) { const std::uint64_t mtime = options.reproducible ? static_cast(std::max( 0, options.canonical_mtime)) : static_cast(std::max( 0, std::chrono::duration_cast( 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 hdr{}; std::vector 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( 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::min(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{ io_buf.data(), static_cast(r)}); !w.has_value()) { return w; } remaining -= static_cast(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 eof_blocks{}; return sink.write(eof_blocks); } BuiltinTarStream::BuiltinTarStream( ByteSource& source, const ReadLimits& limits, std::stop_token stop, std::optional 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 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 BuiltinTarStream::read_exact_or_eof(std::span 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(*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 BuiltinTarStream::read_exact_required(std::span 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 BuiltinTarStream::discard_bytes(std::uint64_t count, const char* context) { std::array scratch{}; std::uint64_t rem = count; while (rem > 0) { const std::size_t want = static_cast( std::min(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 BuiltinTarStream::open() { if (auto chk = check_stop_deadline(); !chk.has_value()) { return chk; } m_prefetch.resize(std::min(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(*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> BuiltinTarStream::next_entry() { if (m_reached_eof) { return std::optional{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 next_pax_size; std::string global_pax_path; std::string global_pax_link; std::optional global_pax_size; std::string gnu_long_name; std::string gnu_long_link; std::array 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{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{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(*recorded_sum) != static_cast(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(std::to_integer(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(*parsed_size); std::string payload(static_cast(*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((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(*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{std::move(out)}; } } Void::Result::Result 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 BuiltinTarStream::read_entry_data(std::span 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::min(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 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