#include #include "BuiltinTar.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE #include #include #endif #ifndef _WIN32 #include #include #include #else #include #endif namespace Void::Archive { namespace { #if defined(VOID_ARCHIVE_HAS_LIBARCHIVE) && VOID_ARCHIVE_HAS_LIBARCHIVE using ArchiveHandle = std::unique_ptr; [[nodiscard]] Void::Result::Error archive_error(archive *reader, std::string_view operation) { const char *message = archive_error_string(reader); return Void::Result::Error{std::format( "Archive::extract: {}: {}", operation, message == nullptr ? "unknown archive error" : message)}; } #endif [[nodiscard]] std::optional safe_relative_path(std::string_view rawPath, bool directory) { if (rawPath.empty() || rawPath.find('\\') != std::string_view::npos) { return std::nullopt; } if (rawPath.back() == '/') { if (!directory) { return std::nullopt; } rawPath.remove_suffix(1); if (rawPath.empty() || rawPath.back() == '/') { return std::nullopt; } } if (rawPath.front() == '/' || rawPath.find("//") != std::string_view::npos) { return std::nullopt; } const std::filesystem::path path{rawPath}; if (path.empty() || path.is_absolute() || path.has_root_name() || path.lexically_normal() != path) { return std::nullopt; } for (const auto &component : path) { if (component.empty() || component == "." || component == "..") { return std::nullopt; } } return path; } #ifndef _WIN32 class FileDescriptor { public: explicit FileDescriptor(int descriptor = -1) noexcept : m_descriptor(descriptor) { } ~FileDescriptor() { reset(); } FileDescriptor(FileDescriptor &&other) noexcept : m_descriptor(std::exchange(other.m_descriptor, -1)) { } FileDescriptor &operator=(FileDescriptor &&other) noexcept { if (this != &other) { reset(std::exchange(other.m_descriptor, -1)); } return *this; } FileDescriptor(const FileDescriptor &) = delete; FileDescriptor &operator=(const FileDescriptor &) = delete; [[nodiscard]] int get() const noexcept { return m_descriptor; } [[nodiscard]] explicit operator bool() const noexcept { return m_descriptor >= 0; } [[nodiscard]] int release() noexcept { return std::exchange(m_descriptor, -1); } void reset(int descriptor = -1) noexcept { if (m_descriptor >= 0) { (void)::close(m_descriptor); } m_descriptor = descriptor; } private: int m_descriptor{-1}; }; constexpr int directoryOpenFlags = O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW; constexpr std::size_t maximumTemporaryAttempts = 128; std::atomic temporaryCounter{0}; [[nodiscard]] Void::Result::Result open_destination(const std::filesystem::path &destination) { FileDescriptor descriptor{ ::open(destination.c_str(), directoryOpenFlags)}; if (!descriptor) { return Void::Result::fail( std::format("Archive::extract: open destination '{}': {}", destination.string(), std::strerror(errno))); } return descriptor; } [[nodiscard]] Void::Result::Result open_parent_directory(int rootDescriptor, const std::filesystem::path &relativeParent, const std::filesystem::path &displayRoot) { FileDescriptor current{ ::openat(rootDescriptor, ".", directoryOpenFlags)}; if (!current) { return Void::Result::fail(std::format( "Archive::extract: duplicate destination '{}': {}", displayRoot.string(), std::strerror(errno))); } std::filesystem::path displayPath = displayRoot; for (const auto &component : relativeParent) { const std::string name{component.native()}; displayPath /= component; int descriptor = ::openat(current.get(), name.c_str(), directoryOpenFlags); if (descriptor < 0 && errno == ENOENT) { if (::mkdirat(current.get(), name.c_str(), 0755) != 0 && errno != EEXIST) { return Void::Result::fail(std::format( "Archive::extract: cannot create directory '{}': " "{}", displayPath.string(), std::strerror(errno))); } descriptor = ::openat(current.get(), name.c_str(), directoryOpenFlags); } if (descriptor < 0) { return Void::Result::fail(std::format( "Archive::extract: unsafe parent '{}': {}", displayPath.string(), std::strerror(errno))); } current = FileDescriptor{descriptor}; } return current; } [[nodiscard]] Void::Result::Result create_directory_entry( int rootDescriptor, const std::filesystem::path &relative, const std::filesystem::path &displayRoot, bool overwrite) { auto openedParent = open_parent_directory( rootDescriptor, relative.parent_path(), displayRoot); if (!openedParent) { return std::unexpected{openedParent.error()}; } auto parent = std::move(*openedParent); const std::string name{relative.filename().native()}; const auto displayPath = displayRoot / relative; if (::mkdirat(parent.get(), name.c_str(), 0755) == 0) { return {}; } if (errno != EEXIST) { return Void::Result::fail(std::format( "Archive::extract: cannot create directory '{}': {}", displayPath.string(), std::strerror(errno))); } if (!overwrite) { return Void::Result::fail(std::format( "Archive::extract: destination '{}' already exists", displayPath.string())); } FileDescriptor existing{ ::openat(parent.get(), name.c_str(), directoryOpenFlags)}; if (!existing) { return Void::Result::fail(std::format( "Archive::extract: destination '{}' is not a real " "directory", displayPath.string())); } return {}; } template [[nodiscard]] Void::Result::Result 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); if (!openedParent) { return std::unexpected{openedParent.error()}; } auto parent = std::move(*openedParent); const std::string outputName{relative.filename().native()}; const auto displayPath = displayRoot / relative; FileDescriptor descriptor; std::string temporaryName; for (std::size_t attempt = 0; attempt < maximumTemporaryAttempts; ++attempt) { const auto sequence = temporaryCounter.fetch_add(1, std::memory_order_relaxed); temporaryName = std::format(".void-archive-{}-{}", static_cast(::getpid()), sequence); const int opened = ::openat(parent.get(), temporaryName.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, executable ? 0755 : 0644); if (opened >= 0) { descriptor = FileDescriptor{opened}; break; } if (errno != EEXIST) { return Void::Result::fail(std::format( "Archive::extract: create temporary file for '{}': {}", displayPath.string(), std::strerror(errno))); } } if (!descriptor) { return Void::Result::fail(std::format( "Archive::extract: cannot allocate temporary file for '{}'", displayPath.string())); } auto removeTemporary = [&]() noexcept { descriptor.reset(); if (!temporaryName.empty()) { (void)::unlinkat(parent.get(), temporaryName.c_str(), 0); temporaryName.clear(); } }; auto fail = [&](std::string message) -> Void::Result::Result { removeTemporary(); return Void::Result::fail(std::move(message)); }; std::array buffer{}; std::uint64_t fileBytes = 0; for (;;) { auto chunk = read_fn(std::span{buffer}); if (!chunk.has_value()) { return fail(chunk.error().message()); } if (*chunk == 0) { break; } const auto amount = static_cast(*chunk); if (amount > options.maxFileBytes - fileBytes || amount > options.maxTotalBytes - alreadyExtracted - fileBytes) { return fail( "Archive::extract: extracted size exceeds policy"); } std::size_t written = 0; while (written < *chunk) { const auto result = ::write( descriptor.get(), reinterpret_cast(buffer.data()) + written, *chunk - written); if (result < 0 && errno == EINTR) { continue; } if (result <= 0) { const int error = errno; return fail(std::format( "Archive::extract: write '{}': {}", displayPath.string(), std::strerror(error))); } written += static_cast(result); } fileBytes += amount; } if (::fsync(descriptor.get()) != 0) { const int error = errno; return fail(std::format("Archive::extract: fsync '{}': {}", displayPath.string(), std::strerror(error))); } const int rawDescriptor = descriptor.release(); if (::close(rawDescriptor) != 0) { const int error = errno; return fail(std::format("Archive::extract: close '{}': {}", displayPath.string(), std::strerror(error))); } if (options.overwriteExisting) { struct stat status{}; if (::fstatat(parent.get(), outputName.c_str(), &status, AT_SYMLINK_NOFOLLOW) == 0) { if (!S_ISREG(status.st_mode)) { return fail(std::format( "Archive::extract: destination '{}' is not a " "regular file", displayPath.string())); } } else if (errno != ENOENT) { const int error = errno; return fail(std::format( "Archive::extract: inspect destination '{}': {}", displayPath.string(), std::strerror(error))); } if (::renameat(parent.get(), temporaryName.c_str(), parent.get(), outputName.c_str()) != 0) { const int error = errno; return fail(std::format( "Archive::extract: publish '{}': {}", displayPath.string(), std::strerror(error))); } temporaryName.clear(); } else { if (::linkat(parent.get(), temporaryName.c_str(), parent.get(), outputName.c_str(), 0) != 0) { const int error = errno; return fail(std::format( "Archive::extract: publish '{}': {}", displayPath.string(), std::strerror(error))); } int unlinkResult = 0; do { unlinkResult = ::unlinkat(parent.get(), temporaryName.c_str(), 0); } while (unlinkResult != 0 && errno == EINTR); if (unlinkResult != 0 && errno != ENOENT) { const int error = errno; return fail(std::format( "Archive::extract: remove temporary file for '{}': {}", displayPath.string(), std::strerror(error))); } temporaryName.clear(); } return fileBytes; } #else [[nodiscard]] Void::Result::Result safe_parents(const std::filesystem::path &root, const std::filesystem::path &relativeParent) { std::filesystem::path current = root; for (const auto &component : relativeParent) { current /= component; std::error_code error; const auto status = std::filesystem::symlink_status(current, error); if (!error && status.type() != std::filesystem::file_type::not_found) { if (std::filesystem::is_symlink(status) || !std::filesystem::is_directory(status)) { return Void::Result::fail( std::format("Archive::extract: unsafe parent '{}'", current.string())); } continue; } if (error && error != std::errc::no_such_file_or_directory) { return Void::Result::fail( std::format("Archive::extract: cannot inspect '{}': {}", current.string(), error.message())); } error.clear(); std::filesystem::create_directory(current, error); if (error) { return Void::Result::fail( std::format("Archive::extract: cannot create '{}': {}", current.string(), error.message())); } } return {}; } [[nodiscard]] Void::Result::Result create_directory_entry(const std::filesystem::path &path, bool overwrite) { std::error_code error; const auto status = std::filesystem::symlink_status(path, error); if (!error && status.type() != std::filesystem::file_type::not_found) { if (std::filesystem::is_symlink(status) || !std::filesystem::is_directory(status) || !overwrite) { return Void::Result::fail(std::format( "Archive::extract: destination '{}' already exists", path.string())); } return {}; } error.clear(); std::filesystem::create_directory(path, error); if (error) { return Void::Result::fail(std::format( "Archive::extract: cannot create directory '{}': {}", path.string(), error.message())); } return {}; } template [[nodiscard]] Void::Result::Result 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); if (!error && status.type() != std::filesystem::file_type::not_found && (std::filesystem::is_symlink(status) || !std::filesystem::is_regular_file(status))) { return Void::Result::fail(std::format( "Archive::extract: destination '{}' is not a regular file", path.string())); } if (!options.overwriteExisting && !error && status.type() != std::filesystem::file_type::not_found) { return Void::Result::fail(std::format( "Archive::extract: destination '{}' already exists", path.string())); } std::ofstream output{path, std::ios::binary | std::ios::trunc}; if (!output) { return Void::Result::fail(std::format( "Archive::extract: create '{}' failed", path.string())); } auto fail = [&](std::string message) -> Void::Result::Result { output.close(); std::error_code removeError; std::filesystem::remove(path, removeError); return Void::Result::fail(std::move(message)); }; std::array buffer{}; std::uint64_t fileBytes = 0; for (;;) { auto chunk = read_fn(std::span{buffer}); if (!chunk.has_value()) { return fail(chunk.error().message()); } if (*chunk == 0) { break; } const auto amount = static_cast(*chunk); if (amount > options.maxFileBytes - fileBytes || amount > options.maxTotalBytes - alreadyExtracted - fileBytes) { return fail( "Archive::extract: extracted size exceeds policy"); } output.write(reinterpret_cast(buffer.data()), static_cast(*chunk)); if (!output) { return fail("Archive::extract: write failed"); } fileBytes += amount; } return fileBytes; } #endif } // namespace Void::Result::Result extract(const std::filesystem::path &archivePath, const std::filesystem::path &destination, const ExtractionOptions &options) { if (options.maxEntries == 0 || options.maxFileBytes == 0 || options.maxTotalBytes == 0) { return Void::Result::fail( "Archive::extract: extraction limits must be positive"); } std::error_code error; std::filesystem::create_directories(destination, error); if (error) { return Void::Result::fail( std::format("Archive::extract: cannot create destination: {}", error.message())); } #ifndef _WIN32 auto root = open_destination(destination); if (!root) { return std::unexpected{root.error()}; } #else const auto root = std::filesystem::canonical(destination, error); if (error || std::filesystem::is_symlink( std::filesystem::symlink_status(destination, error))) { return Void::Result::fail( "Archive::extract: destination must be a real directory"); } #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()); #ifdef _WIN32 const int opened = archive_read_open_filename_w( reader.get(), archivePath.c_str(), 64 * 1024); #else const int opened = archive_read_open_filename( reader.get(), archivePath.c_str(), 64 * 1024); #endif if (opened != ARCHIVE_OK) { return std::unexpected{archive_error(reader.get(), "open archive")}; } ExtractionResult result; std::set seen; archive_entry *entry = nullptr; for (;;) { const int status = archive_read_next_header(reader.get(), &entry); if (status == ARCHIVE_EOF) { break; } if (status != ARCHIVE_OK) { return std::unexpected{ archive_error(reader.get(), "read header")}; } if (++result.entries > options.maxEntries) { return Void::Result::fail( "Archive::extract: entry count exceeds policy"); } const char *rawPath = archive_entry_pathname(entry); if (rawPath == nullptr) { return Void::Result::fail( "Archive::extract: entry has no path"); } if (archive_entry_hardlink(entry) != nullptr || archive_entry_symlink(entry) != nullptr) { return Void::Result::fail( "Archive::extract: links are not allowed"); } const auto type = archive_entry_filetype(entry); if (type != AE_IFDIR && type != AE_IFREG) { return Void::Result::fail( "Archive::extract: special files are not allowed"); } auto relative = safe_relative_path(rawPath, type == AE_IFDIR); if (!relative || !seen.insert(*relative).second) { return Void::Result::fail(std::format( "Archive::extract: unsafe or duplicate path '{}'", rawPath)); } #ifdef _WIN32 if (auto parents = safe_parents(root, relative->parent_path()); !parents) { return std::unexpected{parents.error()}; } const auto output = root / *relative; #endif if (type == AE_IFDIR) { #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; } const auto declared = archive_entry_size(entry); if (declared < 0 || static_cast(declared) > options.maxFileBytes || static_cast(declared) > options.maxTotalBytes - result.bytes) { return Void::Result::fail( "Archive::extract: declared entry size exceeds policy"); } auto read_libarchive_chunk = [&](std::span dst) -> Void::Result::Result { 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(count); }; #ifndef _WIN32 const bool executable = (archive_entry_perm(entry) & 0111) != 0; auto extracted = extract_regular_stream( root->get(), *relative, destination, options, result.bytes, executable, read_libarchive_chunk); #else auto extracted = extract_regular_stream( output, options, result.bytes, read_libarchive_chunk); #endif if (!extracted) { return std::unexpected{extracted.error()}; } 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::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 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 dst) -> Void::Result::Result { 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