From 5f35ce98416322c0d6dfab8f51c96e68e3bd4638 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Sat, 28 Nov 2026 12:52:30 +0800 Subject: [PATCH 1/2] feat: add public ArchiveReader API Add ctar::ArchiveReader with Open, List, Stat, OpenFile and ReadFile over the validated archive index. Paths are virtual absolute paths rooted at '/'; a single-file read uses the absolute entry offset to touch only that file's stored bytes, decompresses kNone/LZ4/LZ4HC as recorded, and verifies XXH64 before returning. The public headers expose stable Error/Result types and shared-ownership Buffer/File handles so callers can hand data to JPEG decoders or pyarrow without copying. ReaderOptions bounds metadata size on open and file size per read (0 disables); oversized files return kTooLarge instead of failing the whole archive. The consumer smoke test now packs a tree with the CLI and reads it back through the installed headers, so the installed package is exercised end to end. Closes #101 Closes #83 --- CMakeLists.txt | 9 +- README.md | 28 +- README_CN.md | 25 +- include/ctar/ctar.h | 6 +- include/ctar/error.h | 35 ++ include/ctar/reader.h | 150 ++++++++ scripts/consumer_smoke_test.sh | 11 + src/core/archive_reader.cpp | 535 +++++++++++++++++++++++++++++ src/core/block_store.h | 9 + test/cases/test_archive_reader.cpp | 318 +++++++++++++++++ test/consumer/main.cpp | 57 ++- 11 files changed, 1171 insertions(+), 12 deletions(-) create mode 100644 include/ctar/error.h create mode 100644 include/ctar/reader.h create mode 100644 src/core/archive_reader.cpp create mode 100644 test/cases/test_archive_reader.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 235ad2e..7085cf1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,6 +82,7 @@ endif () # ========= Core Library ========= set(CORE_SOURCES + src/core/archive_reader.cpp src/core/block_store.cpp src/core/file_format.cpp src/core/file_handle.cpp @@ -187,6 +188,7 @@ if (BUILD_TEST) include(GoogleTest) set(TEST_SOURCES + test/cases/test_archive_reader.cpp test/cases/test_block_store.cpp test/cases/test_cli.cpp test/cases/test_compress.cpp @@ -292,10 +294,9 @@ endif() # Public headers only. Internal headers under src/ and api/ are implementation # details and are deliberately not installed. -install(FILES - ${PROJECT_SOURCE_DIR}/include/ctar/ctar.h - ${PROJECT_SOURCE_DIR}/include/ctar/version.h - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/ctar +install(DIRECTORY + ${PROJECT_SOURCE_DIR}/include/ctar + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install(EXPORT ${PROJECT_NAME}Targets diff --git a/README.md b/README.md index e09caef..dee7592 100644 --- a/README.md +++ b/README.md @@ -355,8 +355,32 @@ target_link_libraries(app PRIVATE ctar::ctar) The installed `libctar.a` bundles LZ4 and xxhash, so no separate compression library is needed. Only the headers under `include/ctar/` are public; `src/` and `api/` headers are internal and are not installed. The -current public API exposes version information; the archive read API is tracked in #101. The bundled -`LZ4_*`/`XXH*` symbols are part of `libctar.a` and may collide with a consumer's own copies of those libraries. +bundled `LZ4_*`/`XXH*` symbols are part of `libctar.a` and may collide with a consumer's own copies of those +libraries. + +### Reading an archive from C++ + +```cpp +#include + +auto reader = ctar::ArchiveReader::Open("pack_file.ctar"); +if (!reader) +{ + // reader.error().code, reader.error().message +} + +auto entries = reader->List("/", /*recursive=*/true); +auto info = reader->Stat("/hello.txt"); +auto data = reader->ReadFile("/image.jpg"); // std::shared_ptr +auto file = reader->OpenFile("/data.parquet"); +char buf[4096]; +file->ReadAt(0, buf); +``` + +Reading one file touches only that file's stored bytes; `.parquet`, `.jpeg` and other suffix-listed entries +are stored raw and are returned without decompression. Compressed files are decompressed and verified +against the archive's XXH64 before being returned. `ReaderOptions` bounds the metadata size and the +per-file size (`0` disables the limit). Nothing is extracted to disk. **Not supported**: Windows, Intel Macs, arm64 Linux, systems with glibc older than 2.28 (such as CentOS 7), and musl-based distributions such as Alpine. diff --git a/README_CN.md b/README_CN.md index fab3c3f..0c0c597 100644 --- a/README_CN.md +++ b/README_CN.md @@ -339,9 +339,32 @@ target_link_libraries(app PRIVATE ctar::ctar) ``` 安装的 `libctar.a` 已内置 LZ4 和 xxhash,不需要额外安装压缩库。只有 `include/ctar/` 下的头文件是公共的; -`src/` 和 `api/` 下的头文件属于内部实现,不会安装。当前公共 API 只提供版本信息,归档读取 API 见 #101。 +`src/` 和 `api/` 下的头文件属于内部实现,不会安装。 内置的 `LZ4_*`/`XXH*` 符号属于 `libctar.a`,可能与使用方自己的同名库冲突。 +### 在 C++ 中读取归档 + +```cpp +#include + +auto reader = ctar::ArchiveReader::Open("pack_file.ctar"); +if (!reader) +{ + // reader.error().code, reader.error().message +} + +auto entries = reader->List("/", /*recursive=*/true); +auto info = reader->Stat("/hello.txt"); +auto data = reader->ReadFile("/image.jpg"); // std::shared_ptr +auto file = reader->OpenFile("/data.parquet"); +char buf[4096]; +file->ReadAt(0, buf); +``` + +读取单个文件只访问该文件自身存储的字节;`.parquet`、`.jpeg` 等后缀列表中的文件以原始形式存储, +返回时无需解压。压缩文件会解压并按归档中的 XXH64 校验后再返回。`ReaderOptions` 可限制 metadata +大小和单文件大小(`0` 表示不限制)。整个过程不会解压到磁盘。 + **暂不支持**:Windows、Intel Mac、arm64 Linux、glibc 低于 2.28 的系统(如 CentOS 7),以及使用 musl 的系统(如 Alpine)。 ### Sanitizer 构建 diff --git a/include/ctar/ctar.h b/include/ctar/ctar.h index 95f4524..0a4a12a 100644 --- a/include/ctar/ctar.h +++ b/include/ctar/ctar.h @@ -6,10 +6,8 @@ // Only public, self-contained headers belong here. Internal headers under // src/ and api/ are not installed and must never be included from this file. // -// The public surface currently exposes version information only; the archive -// read API (ctar::ArchiveReader) is tracked in issue #101 and will be added -// here without changing the install layout. - +#include +#include #include #endif // CTAR_CTAR_PUBLIC_H diff --git a/include/ctar/error.h b/include/ctar/error.h new file mode 100644 index 0000000..2d9ec88 --- /dev/null +++ b/include/ctar/error.h @@ -0,0 +1,35 @@ +#ifndef CTAR_ERROR_H +#define CTAR_ERROR_H + +#include +#include +#include + +namespace ctar +{ + + /// Stable error codes exposed by the public API. Internal error types are + /// mapped onto these values and never leak through the installed headers. + enum class ErrorCode : uint8_t + { + kNotFound = 0, + kInvalidArgument, + kCorruption, + kIo, + kTooLarge, + kUnsupported, + kRuntimeError, + }; + + struct Error + { + ErrorCode code = ErrorCode::kRuntimeError; + std::string message; + }; + + template + using Result = std::expected; + +} // namespace ctar + +#endif // CTAR_ERROR_H diff --git a/include/ctar/reader.h b/include/ctar/reader.h new file mode 100644 index 0000000..58ce720 --- /dev/null +++ b/include/ctar/reader.h @@ -0,0 +1,150 @@ +#ifndef CTAR_READER_H +#define CTAR_READER_H + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace ctar +{ + + enum class EntryKind : uint8_t + { + kFile = 0, + kDirectory, + }; + + /// One file or directory recorded in an archive. + /// + /// `path` is a virtual absolute path rooted at "/": the directory that was + /// passed to `ctar pack` becomes "/", so the archive can be read without + /// knowing where the source tree lived. + struct Entry + { + std::string path; + EntryKind kind = EntryKind::kFile; + uint64_t size = 0; // original file size; 0 for directories + int64_t mtime_ms = 0; + uint32_t permissions = 0; + std::string owner; + std::string group; + }; + + /// Immutable, shared-ownership byte buffer. + /// + /// The data pointer stays valid while the owning `std::shared_ptr` is alive, + /// so it can be handed to libraries that need a contiguous buffer (JPEG + /// decoders, pyarrow, ...) without copying. + class Buffer + { + public: + Buffer() = default; + /// Library-internal: takes ownership of an already-filled buffer. + Buffer(std::unique_ptr data, size_t size) noexcept; + + Buffer(const Buffer&) = delete; + Buffer& operator=(const Buffer&) = delete; + + [[nodiscard]] const char* data() const noexcept { return data_.get(); } + [[nodiscard]] size_t size() const noexcept { return size_; } + [[nodiscard]] std::string_view view() const noexcept + { + return size_ == 0 ? std::string_view{} : std::string_view(data_.get(), size_); + } + + private: + std::unique_ptr data_; + size_t size_ = 0; + }; + + /// A file opened from an archive. + /// + /// The archive format compresses each file as a whole (LZ4 has no seek + /// points), so opening a file decompresses it into memory once; subsequent + /// reads are served from that buffer. A `File` is not thread-safe; distinct + /// `File` objects are independent. The reader that created it may be + /// destroyed first. + class File + { + public: + File() = default; + + [[nodiscard]] uint64_t Size() const noexcept; + /// Copies up to `dst.size()` bytes from the current position and + /// advances it. Returns the number of bytes copied. + [[nodiscard]] Result Read(std::span dst); + /// Copies up to `dst.size()` bytes starting at `offset`. Returns the + /// number of bytes copied; an offset past the end is an error. + [[nodiscard]] Result ReadAt(uint64_t offset, std::span dst) const; + /// The whole file. Shared ownership, no copy. + [[nodiscard]] std::shared_ptr ReadAll() const; + + private: + friend class ArchiveReader; + explicit File(std::shared_ptr data) noexcept; + + std::shared_ptr data_; + size_t offset_ = 0; + }; + + struct ReaderOptions + { + /// Reject archives whose uncompressed metadata exceeds this many bytes. + /// 0 means unlimited. Matches the CLI's --max-metadata-size. + uint64_t max_metadata_size = 1ULL << 30; + /// Reject files whose original size exceeds this many bytes. 0 means + /// unlimited. Matches the CLI's --max-decompressed-size. + uint64_t max_file_size = 1ULL << 30; + }; + + /// Read-only, random-access view of a `.ctar` archive. + /// + /// Open loads and validates the metadata index; List/Stat only consult it. + /// Reading one file touches only that file's stored bytes, never extracts + /// the archive to disk. After Open the reader is immutable, and read calls + /// may be made concurrently from several threads (the underlying I/O uses + /// pread); individual `File` objects are not thread-safe. + class ArchiveReader + { + public: + ArchiveReader() noexcept; + ~ArchiveReader(); + + ArchiveReader(ArchiveReader&&) noexcept; + ArchiveReader& operator=(ArchiveReader&&) noexcept; + ArchiveReader(const ArchiveReader&) = delete; + ArchiveReader& operator=(const ArchiveReader&) = delete; + + /// Opens an archive and loads its metadata index. + static Result Open(std::string archive_path, ReaderOptions options = {}); + + /// Lists the direct children of `dir` (or every descendant when + /// `recursive` is true), sorted by path in byte order. + [[nodiscard]] Result> List(std::string_view dir = "/", bool recursive = false) const; + + /// Metadata for one file or directory. + [[nodiscard]] Result Stat(std::string_view path) const; + + /// Opens a file and decompresses it into memory (bounded by + /// ReaderOptions::max_file_size). + [[nodiscard]] Result OpenFile(std::string_view path) const; + + /// Convenience wrapper around OpenFile().ReadAll(). + [[nodiscard]] Result> ReadFile(std::string_view path) const; + + private: + struct Impl; + explicit ArchiveReader(std::unique_ptr impl) noexcept; + + std::unique_ptr impl_; + }; + +} // namespace ctar + +#endif // CTAR_READER_H diff --git a/scripts/consumer_smoke_test.sh b/scripts/consumer_smoke_test.sh index 0fa5406..e6693ea 100755 --- a/scripts/consumer_smoke_test.sh +++ b/scripts/consumer_smoke_test.sh @@ -38,6 +38,17 @@ cmake --build "$consumer_build" >/dev/null echo "== running the consumer ==" "$consumer_build/ctar_consumer" +echo "== reading a real archive through the public API ==" +if [[ -x "$build_dir/ctar" ]]; then + tree_dir="$tmp_root/consumer-tree" + mkdir -p "$tree_dir" + printf 'hello\n' >"$tree_dir/hello.txt" + "$build_dir/ctar" pack "$tree_dir" "$tmp_root/consumer.ctar" >/dev/null + "$consumer_build/ctar_consumer" "$tmp_root/consumer.ctar" +else + echo "ctar CLI not built; skipping the archive read check" +fi + echo "== checking that no test framework was installed ==" pollution=$(find "$prefix" \( -name '*gtest*' -o -name '*gmock*' \) -print) if [[ -n "$pollution" ]]; then diff --git a/src/core/archive_reader.cpp b/src/core/archive_reader.cpp new file mode 100644 index 0000000..971c51f --- /dev/null +++ b/src/core/archive_reader.cpp @@ -0,0 +1,535 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "block_store.h" +#include "compress.h" +#include "file_format.h" +#include "file_handle.h" +#include "options.h" +#include "src/utils/status.h" +#include "xxhash.h" + +namespace ctar +{ + +namespace +{ + Error MakeError(const ErrorCode code, std::string message) { return {code, std::move(message)}; } + + ErrorCode MapErrorType(const ErrorType type) noexcept + { + switch (type) + { + case ErrorType::kNotFound: + return ErrorCode::kNotFound; + case ErrorType::kCorruption: + return ErrorCode::kCorruption; + case ErrorType::kNotSupported: + return ErrorCode::kUnsupported; + case ErrorType::kInvalidArgument: + return ErrorCode::kInvalidArgument; + case ErrorType::kIoError: + return ErrorCode::kIo; + case ErrorType::kRuntimeError: + return ErrorCode::kRuntimeError; + case ErrorType::kSuccess: + break; + } + return ErrorCode::kRuntimeError; + } + + Error FromStatus(const ErrorStatus& status) { return {MapErrorType(status.type()), status.err_message}; } + + /// Normalizes a virtual archive path: leading slash optional, empty + /// components collapsed, "." and ".." rejected. + Result NormalizePath(const std::string_view path) + { + std::string normalized; + normalized.reserve(path.size() + 1); + size_t start = 0; + while (start < path.size()) + { + const size_t end = path.find('/', start); + const size_t stop = end == std::string_view::npos ? path.size() : end; + const std::string_view part = path.substr(start, stop - start); + if (!part.empty()) + { + if (part == "." || part == "..") + { + return std::unexpected( + MakeError(ErrorCode::kInvalidArgument, std::format("invalid path '{}'", path))); + } + normalized.push_back('/'); + normalized.append(part); + } + if (end == std::string_view::npos) + { + break; + } + start = end + 1; + } + if (normalized.empty()) + { + normalized = "/"; + } + return normalized; + } + + std::string JoinPath(const std::string_view parent, const std::string_view name) + { + if (parent == "/") + { + return std::format("/{}", name); + } + return std::format("{}/{}", parent, name); + } +} // namespace + +struct ArchiveReader::Impl +{ + struct Resolved + { + entry_id_t id = 0; + bool is_dir = false; + std::string path; + }; + + BlockStore store; + ReaderOptions options; + std::unique_ptr read_file; + std::string root_stored_path; + // virtual directory path -> dir id (root is "/") + std::unordered_map dir_path_to_id; + // dir id -> virtual directory path + std::unordered_map dir_id_to_path; + // dir id -> (file name -> file id); the name views point into the + // PackFileHandle buffers, which stay stable after deserialization. + std::unordered_map> file_name_to_id; + // block id -> validated block metadata + std::unordered_map block_by_id; + + Result BuildIndexes() + { + const auto& handle = store.GetPackFileHandle(); + const auto root_path = handle.GetDirPathByDirId(kRootDirId); + if (!root_path) + { + return std::unexpected(FromStatus(root_path.error())); + } + root_stored_path = std::string(root_path.value()); + dir_path_to_id.emplace("/", kRootDirId); + dir_id_to_path.emplace(kRootDirId, "/"); + + const fs::path root_fs = fs::path(root_stored_path).lexically_normal(); + for (const auto& dir_entry : handle.GetDirEntryRecords()) + { + const entry_id_t dir_id = dir_entry.first; + if (dir_id == kRootDirId) + { + continue; + } + const auto stored = handle.GetDirPathByDirId(dir_id); + if (!stored) + { + return std::unexpected(FromStatus(stored.error())); + } + const fs::path relative = fs::path(stored.value()).lexically_normal().lexically_relative(root_fs); + std::string virtual_path; + if (relative.empty() || relative == ".") + { + virtual_path = "/"; + } + else + { + virtual_path = std::format("/{}", relative.generic_string()); + } + if (!dir_path_to_id.emplace(virtual_path, dir_id).second) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("duplicate directory path '{}'", virtual_path))); + } + dir_id_to_path.emplace(dir_id, std::move(virtual_path)); + } + + for (const auto& dir_entry : handle.GetDirIdToChildFileIds()) + { + auto& names = file_name_to_id[dir_entry.first]; + for (const entry_id_t file_id : dir_entry.second) + { + const auto name = handle.GetFileNameByFileId(file_id); + if (!name) + { + return std::unexpected(FromStatus(name.error())); + } + if (!names.emplace(name.value(), file_id).second) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("duplicate file name '{}'", name.value()))); + } + } + } + + // A path must not be both a file and a directory; otherwise Resolve + // would silently shadow one of them. + for (const auto& dir_entry : file_name_to_id) + { + const auto dir_path = dir_id_to_path.find(dir_entry.first); + if (dir_path == dir_id_to_path.end()) + { + return std::unexpected(MakeError( + ErrorCode::kCorruption, std::format("directory {} has no path", dir_entry.first))); + } + for (const auto& file_entry : dir_entry.second) + { + const std::string full_path = JoinPath(dir_path->second, file_entry.first); + if (dir_path_to_id.contains(full_path)) + { + return std::unexpected(MakeError( + ErrorCode::kCorruption, + std::format("path '{}' is both a file and a directory", full_path))); + } + } + } + + for (const auto& block : store.GetDataBlockMetas()) + { + block_by_id.emplace(block.block_id, &block); + } + return {}; + } + + Result Resolve(const std::string_view raw_path) const + { + auto normalized = NormalizePath(raw_path); + if (!normalized) + { + return std::unexpected(normalized.error()); + } + const std::string& path = normalized.value(); + if (const auto it = dir_path_to_id.find(path); it != dir_path_to_id.end()) + { + return Resolved{it->second, true, path}; + } + const size_t sep = path.rfind('/'); + const std::string parent = sep == 0 ? "/" : path.substr(0, sep); + const std::string_view name(path.data() + sep + 1, path.size() - sep - 1); + const auto parent_it = dir_path_to_id.find(parent); + if (parent_it == dir_path_to_id.end()) + { + return std::unexpected(MakeError(ErrorCode::kNotFound, std::format("no such path '{}'", path))); + } + const auto dir_files = file_name_to_id.find(parent_it->second); + if (dir_files == file_name_to_id.end()) + { + return std::unexpected(MakeError(ErrorCode::kNotFound, std::format("no such path '{}'", path))); + } + const auto file_it = dir_files->second.find(name); + if (file_it == dir_files->second.end()) + { + return std::unexpected(MakeError(ErrorCode::kNotFound, std::format("no such path '{}'", path))); + } + return Resolved{file_it->second, false, path}; + } + + Result MakeEntry(const entry_id_t id, const bool is_dir, std::string path) const + { + const auto& handle = store.GetPackFileHandle(); + const auto& records = is_dir ? handle.GetDirEntryRecords() : handle.GetFileEntryRecords(); + const auto record = records.find(id); + if (record == records.end()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("entry {} has no metadata record", id))); + } + const EntryMeta& meta = record->second.entry_meta; + Entry entry; + entry.path = std::move(path); + entry.kind = is_dir ? EntryKind::kDirectory : EntryKind::kFile; + entry.size = is_dir ? 0 : meta.file_orig_size; + entry.mtime_ms = meta.modify_time; + entry.permissions = meta.permissions; + entry.owner.assign(meta.owner_name, strnlen(meta.owner_name, sizeof(meta.owner_name))); + entry.group.assign(meta.group_name, strnlen(meta.group_name, sizeof(meta.group_name))); + return entry; + } + + Result> ReadFileById(const entry_id_t file_id) const + { + const auto& handle = store.GetPackFileHandle(); + const auto& records = handle.GetFileEntryRecords(); + const auto record = records.find(file_id); + if (record == records.end()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("file {} has no metadata record", file_id))); + } + const EntryMeta& entry = record->second.entry_meta; + + const auto block_it = block_by_id.find(entry.block_id); + if (block_it == block_by_id.end()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("file {} names unknown block {}", file_id, entry.block_id))); + } + const DataBlockMeta& block = *block_it->second; + const auto file_it = std::lower_bound(block.file_ids.begin(), block.file_ids.end(), file_id); + if (file_it == block.file_ids.end() || *file_it != file_id) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("block {} does not contain file {}", block.block_id, file_id))); + } + const size_t index = static_cast(file_it - block.file_ids.begin()); + const uint64_t original_size = block.file_orig_sizes[index]; + const uint64_t stored_size = block.file_compressed_sizes[index]; + const CompressionType compression_type = block.file_compressed_types[index]; + + if (options.max_file_size > 0 && original_size > options.max_file_size) + { + return std::unexpected(MakeError( + ErrorCode::kTooLarge, + std::format("file is {} bytes, above the configured limit of {} bytes", original_size, + options.max_file_size))); + } + + std::unique_ptr stored; + if (stored_size > 0) + { + stored = std::make_unique_for_overwrite(static_cast(stored_size)); + const auto read_status = + read_file->RandomRead(entry.file_offset, static_cast(stored_size), stored.get()); + if (!read_status || read_status.value() != stored_size) + { + return std::unexpected(MakeError(ErrorCode::kIo, "failed to read file data from the archive")); + } + } + + std::unique_ptr data; + uint64_t hash = kZeroXXHash; + if (original_size > 0) + { + if (compression_type == CompressionType::kNone) + { + data = std::move(stored); + hash = XXH64(data.get(), original_size, kHashSeed); + } + else + { + data = std::make_unique_for_overwrite(static_cast(original_size)); + const uint64_t decompressed_size = compress::Decompress(compression_type, stored.get(), data.get(), + stored_size, original_size); + if (decompressed_size != original_size) + { + return std::unexpected(MakeError(ErrorCode::kCorruption, "failed to decompress file data")); + } + stored.reset(); + hash = XXH64(data.get(), original_size, kHashSeed); + } + } + if (hash != block.file_hashes[index]) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, "file data does not match the recorded hash")); + } + return std::shared_ptr( + std::make_shared(std::move(data), static_cast(original_size))); + } +}; + +Buffer::Buffer(std::unique_ptr data, const size_t size) noexcept : data_(std::move(data)), size_(size) {} + +File::File(std::shared_ptr data) noexcept : data_(std::move(data)) {} + +uint64_t File::Size() const noexcept { return data_ ? data_->size() : 0; } + +Result File::Read(const std::span dst) +{ + auto count = ReadAt(offset_, dst); + if (count) + { + offset_ += count.value(); + } + return count; +} + +Result File::ReadAt(const uint64_t offset, const std::span dst) const +{ + const uint64_t size = Size(); + if (offset > size) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, "offset is past the end of the file")); + } + const size_t available = static_cast(size - offset); + const size_t count = std::min(dst.size(), available); + if (count > 0) + { + std::memcpy(dst.data(), data_->data() + static_cast(offset), count); + } + return count; +} + +std::shared_ptr File::ReadAll() const { return data_; } + +ArchiveReader::ArchiveReader() noexcept = default; +ArchiveReader::~ArchiveReader() = default; +ArchiveReader::ArchiveReader(std::unique_ptr impl) noexcept : impl_(std::move(impl)) {} +ArchiveReader::ArchiveReader(ArchiveReader&&) noexcept = default; +ArchiveReader& ArchiveReader::operator=(ArchiveReader&&) noexcept = default; + +Result ArchiveReader::Open(std::string archive_path, const ReaderOptions options) +{ + auto impl = std::make_unique(); + impl->options = options; + impl->store.SetMaxMetadataSize(options.max_metadata_size); + // The per-file budget is enforced per read (kTooLarge) so a legitimate file + // above the limit does not make the whole archive unreadable. Metadata + // validation still checks the structural LZ4 bounds with no size budget. + if (auto status = impl->store.RestoreBlocksFromPack(archive_path, 0); !status) + { + return std::unexpected(FromStatus(status.error())); + } + auto read_file = NewPosixReadFile(archive_path); + if (!read_file) + { + return std::unexpected(FromStatus(read_file.error())); + } + impl->read_file = std::move(read_file.value()); + if (auto built = impl->BuildIndexes(); !built) + { + return std::unexpected(built.error()); + } + return ArchiveReader(std::move(impl)); +} + +Result> ArchiveReader::List(const std::string_view dir, const bool recursive) const +{ + if (!impl_) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, "reader is not open")); + } + auto resolved = impl_->Resolve(dir); + if (!resolved) + { + return std::unexpected(resolved.error()); + } + if (!resolved->is_dir) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, std::format("'{}' is not a directory", dir))); + } + + const auto& handle = impl_->store.GetPackFileHandle(); + std::vector entries; + std::vector queue{resolved->id}; + for (size_t head = 0; head < queue.size(); ++head) + { + const entry_id_t dir_id = queue[head]; + const auto dir_path_it = impl_->dir_id_to_path.find(dir_id); + if (dir_path_it == impl_->dir_id_to_path.end()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("directory {} has no path", dir_id))); + } + const std::string& dir_path = dir_path_it->second; + + for (const entry_id_t child_id : handle.GetChildDirIdsByDirId(dir_id)) + { + const auto child_path = impl_->dir_id_to_path.find(child_id); + if (child_path == impl_->dir_id_to_path.end()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("directory {} has no path", child_id))); + } + auto entry = impl_->MakeEntry(child_id, true, child_path->second); + if (!entry) + { + return std::unexpected(entry.error()); + } + entries.push_back(std::move(entry.value())); + if (recursive) + { + queue.push_back(child_id); + } + } + for (const entry_id_t child_id : handle.GetChildFileIdsByDirId(dir_id)) + { + const auto name = handle.GetFileNameByFileId(child_id); + if (!name) + { + return std::unexpected(FromStatus(name.error())); + } + auto entry = impl_->MakeEntry(child_id, false, JoinPath(dir_path, name.value())); + if (!entry) + { + return std::unexpected(entry.error()); + } + entries.push_back(std::move(entry.value())); + } + } + std::ranges::sort(entries, {}, &Entry::path); + return entries; +} + +Result ArchiveReader::Stat(const std::string_view path) const +{ + if (!impl_) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, "reader is not open")); + } + auto resolved = impl_->Resolve(path); + if (!resolved) + { + return std::unexpected(resolved.error()); + } + return impl_->MakeEntry(resolved->id, resolved->is_dir, std::move(resolved->path)); +} + +Result ArchiveReader::OpenFile(const std::string_view path) const +{ + if (!impl_) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, "reader is not open")); + } + auto resolved = impl_->Resolve(path); + if (!resolved) + { + return std::unexpected(resolved.error()); + } + if (resolved->is_dir) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, std::format("'{}' is a directory", path))); + } + auto data = impl_->ReadFileById(resolved->id); + if (!data) + { + return std::unexpected(data.error()); + } + return File(std::move(data.value())); +} + +Result> ArchiveReader::ReadFile(const std::string_view path) const +{ + if (!impl_) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, "reader is not open")); + } + auto resolved = impl_->Resolve(path); + if (!resolved) + { + return std::unexpected(resolved.error()); + } + if (resolved->is_dir) + { + return std::unexpected(MakeError(ErrorCode::kInvalidArgument, std::format("'{}' is a directory", path))); + } + return impl_->ReadFileById(resolved->id); +} + +} // namespace ctar diff --git a/src/core/block_store.h b/src/core/block_store.h index 3da476c..825cfe8 100644 --- a/src/core/block_store.h +++ b/src/core/block_store.h @@ -338,6 +338,15 @@ namespace ctar [[nodiscard]] const PackFileHeader& GetPackHeader() const noexcept { return pack_file_header_; } + // Read-only access to the validated index. Internal: these are used by + // the public ArchiveReader and are not part of the installed headers. + [[nodiscard]] const PackFileHandle& GetPackFileHandle() const noexcept { return pack_file_handle_; } + [[nodiscard]] const std::vector& GetDataBlockMetas() const noexcept + { + return data_block_metas_; + } + [[nodiscard]] uint64_t GetFileDataOffset() const noexcept { return file_data_offset_; } + /// @brief Read and validate only the archive header; no metadata is parsed. [[nodiscard]] Status ReadPackHeaderOnly(const std::string& pack_file_path); }; diff --git a/test/cases/test_archive_reader.cpp b/test/cases/test_archive_reader.cpp new file mode 100644 index 0000000..659189e --- /dev/null +++ b/test/cases/test_archive_reader.cpp @@ -0,0 +1,318 @@ +#include +#include +#include +#include +#include + +#include + +#include + +#include "src/core/block_store.h" + +namespace ctar +{ + + namespace + { + struct ArchiveReaderFixture + { + fs::path root{"archive_reader_test"}; + fs::path source{root / "source"}; + fs::path archive{root / "sample.ctar"}; + + void Create() + { + fs::remove_all(root); + fs::create_directories(source / "sub" / "deep"); + std::ofstream(source / "hello.txt") << "hello world\n"; + std::ofstream empty_file(source / "empty.bin"); + // Listed in kNoCompressSuffixes, so it is stored raw. + std::ofstream(source / "sample.parquet") << "PAR1-not-really"; + std::ofstream(source / "sub" / "nested.txt") << "nested"; + std::ofstream(source / "sub" / "deep" / "leaf.bin") << std::string(4096, 'x'); + + BlockStore store; + ASSERT_TRUE(store.Scan(source.string())); + ASSERT_TRUE(store.PackPipeline(archive.string())); + } + + void Cleanup() const { fs::remove_all(root); } + + [[nodiscard]] ArchiveReader OpenReader(ReaderOptions options = {}) const + { + auto reader = ArchiveReader::Open(archive.string(), options); + EXPECT_TRUE(reader) << reader.error().message; + return reader ? std::move(reader.value()) : ArchiveReader{}; + } + }; + + std::vector EntryPaths(const std::vector& entries) + { + std::vector paths; + paths.reserve(entries.size()); + for (const auto& entry : entries) + { + paths.push_back(entry.path); + } + return paths; + } + + const Entry* FindEntry(const std::vector& entries, const std::string_view path) + { + for (const auto& entry : entries) + { + if (entry.path == path) + { + return &entry; + } + } + return nullptr; + } + } // namespace + + TEST(ArchiveReader, ListRootDirectChildren) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto entries = reader.List("/"); + ASSERT_TRUE(entries) << entries.error().message; + EXPECT_EQ(EntryPaths(entries.value()), + (std::vector{"/empty.bin", "/hello.txt", "/sample.parquet", "/sub"})); + + const Entry* hello = FindEntry(entries.value(), "/hello.txt"); + ASSERT_NE(hello, nullptr); + EXPECT_EQ(hello->kind, EntryKind::kFile); + EXPECT_EQ(hello->size, 12U); + + const Entry* sub = FindEntry(entries.value(), "/sub"); + ASSERT_NE(sub, nullptr); + EXPECT_EQ(sub->kind, EntryKind::kDirectory); + EXPECT_EQ(sub->size, 0U); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, ListSubdirectory) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto entries = reader.List("/sub"); + ASSERT_TRUE(entries) << entries.error().message; + EXPECT_EQ(EntryPaths(entries.value()), (std::vector{"/sub/deep", "/sub/nested.txt"})); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, ListRecursive) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto entries = reader.List("/", true); + ASSERT_TRUE(entries) << entries.error().message; + EXPECT_EQ(EntryPaths(entries.value()), + (std::vector{"/empty.bin", "/hello.txt", "/sample.parquet", "/sub", "/sub/deep", + "/sub/deep/leaf.bin", "/sub/nested.txt"})); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, StatFileAndDirectory) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto file = reader.Stat("/hello.txt"); + ASSERT_TRUE(file) << file.error().message; + EXPECT_EQ(file->kind, EntryKind::kFile); + EXPECT_EQ(file->size, 12U); + EXPECT_GT(file->mtime_ms, 0); + + auto dir = reader.Stat("/sub"); + ASSERT_TRUE(dir) << dir.error().message; + EXPECT_EQ(dir->kind, EntryKind::kDirectory); + + auto root = reader.Stat("/"); + ASSERT_TRUE(root) << root.error().message; + EXPECT_EQ(root->kind, EntryKind::kDirectory); + EXPECT_EQ(root->path, "/"); + + // A path without a leading slash is accepted as root-relative. + auto relative = reader.Stat("hello.txt"); + ASSERT_TRUE(relative) << relative.error().message; + EXPECT_EQ(relative->path, "/hello.txt"); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, StatErrors) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto missing = reader.Stat("/does-not-exist"); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().code, ErrorCode::kNotFound); + + auto traversal = reader.Stat("/../etc/passwd"); + ASSERT_FALSE(traversal); + EXPECT_EQ(traversal.error().code, ErrorCode::kInvalidArgument); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, ReadFileContents) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto hello = reader.ReadFile("/hello.txt"); + ASSERT_TRUE(hello) << hello.error().message; + EXPECT_EQ(hello.value()->view(), "hello world\n"); + + auto empty = reader.ReadFile("/empty.bin"); + ASSERT_TRUE(empty) << empty.error().message; + EXPECT_EQ(empty.value()->size(), 0U); + + // Stored raw because of the suffix. + auto parquet = reader.ReadFile("/sample.parquet"); + ASSERT_TRUE(parquet) << parquet.error().message; + EXPECT_EQ(parquet.value()->view(), "PAR1-not-really"); + + auto missing = reader.ReadFile("/nope"); + ASSERT_FALSE(missing); + EXPECT_EQ(missing.error().code, ErrorCode::kNotFound); + + auto directory = reader.ReadFile("/sub"); + ASSERT_FALSE(directory); + EXPECT_EQ(directory.error().code, ErrorCode::kInvalidArgument); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, OpenFileReadAt) + { + ArchiveReaderFixture fixture; + fixture.Create(); + auto reader = fixture.OpenReader(); + + auto file = reader.OpenFile("/hello.txt"); + ASSERT_TRUE(file) << file.error().message; + EXPECT_EQ(file->Size(), 12U); + + char buffer[5] = {}; + auto count = file->ReadAt(6, std::span(buffer, sizeof(buffer))); + ASSERT_TRUE(count) << count.error().message; + EXPECT_EQ(count.value(), 5U); + EXPECT_EQ(std::string_view(buffer, 5), "world"); + + auto at_end = file->ReadAt(12, std::span(buffer, sizeof(buffer))); + ASSERT_TRUE(at_end) << at_end.error().message; + EXPECT_EQ(at_end.value(), 0U); + + char sequential[8] = {}; + auto first = file->Read(std::span(sequential, 5)); + ASSERT_TRUE(first) << first.error().message; + EXPECT_EQ(std::string_view(sequential, first.value()), "hello"); + auto second = file->Read(std::span(sequential, sizeof(sequential))); + ASSERT_TRUE(second) << second.error().message; + EXPECT_EQ(std::string_view(sequential, second.value()), " world\n"); + auto third = file->Read(std::span(sequential, sizeof(sequential))); + ASSERT_TRUE(third) << third.error().message; + EXPECT_EQ(third.value(), 0U); + + auto past_end = file->ReadAt(13, std::span(buffer, sizeof(buffer))); + ASSERT_FALSE(past_end); + EXPECT_EQ(past_end.error().code, ErrorCode::kInvalidArgument); + + EXPECT_EQ(file->ReadAll()->view(), "hello world\n"); + + auto directory = reader.OpenFile("/sub"); + ASSERT_FALSE(directory); + EXPECT_EQ(directory.error().code, ErrorCode::kInvalidArgument); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, FileOutlivesReader) + { + ArchiveReaderFixture fixture; + fixture.Create(); + + std::optional reader = fixture.OpenReader(); + auto file = reader->OpenFile("/hello.txt"); + ASSERT_TRUE(file) << file.error().message; + reader.reset(); + + EXPECT_EQ(file->ReadAll()->view(), "hello world\n"); + EXPECT_EQ(file->Size(), 12U); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, EnforcesFileBudgetPerRead) + { + ArchiveReaderFixture fixture; + fixture.Create(); + + ReaderOptions options; + options.max_file_size = 1; + auto reader = fixture.OpenReader(options); + // Opening still succeeds: the budget applies to individual reads. + EXPECT_TRUE(reader.ReadFile("/empty.bin")); + auto too_large = reader.ReadFile("/hello.txt"); + ASSERT_FALSE(too_large); + EXPECT_EQ(too_large.error().code, ErrorCode::kTooLarge); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, EnforcesMetadataBudgetOnOpen) + { + ArchiveReaderFixture fixture; + fixture.Create(); + + ReaderOptions options; + options.max_metadata_size = 1; + auto reader = ArchiveReader::Open(fixture.archive.string(), options); + ASSERT_FALSE(reader); + EXPECT_EQ(reader.error().code, ErrorCode::kCorruption); + + fixture.Cleanup(); + } + + TEST(ArchiveReader, MovedFromReaderIsUnusable) + { + ArchiveReaderFixture fixture; + fixture.Create(); + + ArchiveReader empty; + auto status = empty.List("/"); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().code, ErrorCode::kInvalidArgument); + + auto reader = fixture.OpenReader(); + ArchiveReader moved = std::move(reader); + auto entries = moved.List("/"); + ASSERT_TRUE(entries) << entries.error().message; + EXPECT_FALSE(entries->empty()); + + fixture.Cleanup(); + } + +} // namespace ctar + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/consumer/main.cpp b/test/consumer/main.cpp index 259a363..c1a6de6 100644 --- a/test/consumer/main.cpp +++ b/test/consumer/main.cpp @@ -2,8 +2,58 @@ #include #include +#include -int main() +namespace +{ + int ReadArchive(const char* archive_path) + { + auto reader = ctar::ArchiveReader::Open(archive_path); + if (!reader) + { + std::cerr << "open failed: " << reader.error().message << '\n'; + return 1; + } + + auto entries = reader->List("/", true); + if (!entries) + { + std::cerr << "list failed: " << entries.error().message << '\n'; + return 1; + } + + const ctar::Entry* hello = nullptr; + for (const auto& entry : entries.value()) + { + if (entry.path == "/hello.txt") + { + hello = &entry; + } + } + if (hello == nullptr) + { + std::cerr << "hello.txt is missing from the archive\n"; + return 1; + } + + auto data = reader->ReadFile("/hello.txt"); + if (!data) + { + std::cerr << "read failed: " << data.error().message << '\n'; + return 1; + } + if (data.value()->view() != "hello\n") + { + std::cerr << "unexpected file contents\n"; + return 1; + } + + std::cout << "read " << data.value()->size() << " bytes from " << entries->size() << " archive entries\n"; + return 0; + } +} // namespace + +int main(int argc, char** argv) { // VersionString() is defined in libctar, so this only links when the // installed archive is actually usable. @@ -15,5 +65,10 @@ int main() return 1; } std::cout << "ctar " << version << " (format " << ctar::kFileFormatVersion.to_string() << ")\n"; + + if (argc > 1) + { + return ReadArchive(argv[1]); + } return 0; } From 7c1e09e146af8400d77905d3b85f5842aac08eb9 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Sat, 28 Nov 2026 13:20:34 +0800 Subject: [PATCH 2/2] fix: bound stored sizes and validate archive path components Require LZ4/LZ4HC stored data to be strictly smaller than the original size in ValidateDataBlockMeta (the packer falls back to kNone otherwise). This also bounds the stored buffer a reader allocates before decompression, and max_file_size now checks the stored size as well. Reject file names that are not a single path component and directory paths that escape the archive root when building the ArchiveReader index, so Entry::path cannot contain separators or '..' components. Make Buffer construction private through ArchiveReader::MakeBuffer and remove the unused BlockStore::GetFileDataOffset. Refs #101 --- doc/file_format.md | 2 +- doc/file_format_CN.md | 2 +- include/ctar/reader.h | 12 +++-- src/core/archive_reader.cpp | 43 ++++++++++++++-- src/core/block_store.h | 1 - src/core/file_format.cpp | 9 ++++ test/cases/test_block_store.cpp | 87 +++++++++++++++++++++++++++++++++ test/cases/test_file_format.cpp | 22 +++++++++ 8 files changed, 166 insertions(+), 12 deletions(-) diff --git a/doc/file_format.md b/doc/file_format.md index 7bf699c..b7090b7 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -163,7 +163,7 @@ The reader rejects archives that violate these cross-field invariants; a writer - `file_ids` are strictly increasing within a block, so a block cannot reference the same file twice. - File ranges (`file_offsets` + `file_compressed_sizes`) are ordered, non-overlapping, and fit inside `payload_size`. -- For `kLZ4`/`kLZ4HC`, `file_orig_sizes` and `file_compressed_sizes` fit the LZ4 `int` API, `file_orig_sizes <= 255 * file_compressed_sizes`, and a zero original size requires a zero stored size. +- For `kLZ4`/`kLZ4HC`, `file_orig_sizes` and `file_compressed_sizes` fit the LZ4 `int` API, `file_orig_sizes <= 255 * file_compressed_sizes`, a zero original size requires a zero stored size, and the stored size must be strictly smaller than the original size (the packer stores the file raw when compression does not shrink it). - Every `file_ids[i]` exists in `file_entry_records`; the entry's `block_id`, `file_orig_size`, `file_compressed_size` and absolute `file_offset` agree with the block, and every indexed file is referenced exactly once. - Directory paths are unique, and a directory contains no duplicate file names, so every extracted file has a distinct output path. - The directory index must form a tree rooted at `kRootDirId` (1): every non-root directory appears exactly once as a child, no directory is its own ancestor, and every directory is reachable from the root. The rendering commands (`tree`, `ls`, `dump`) additionally reject trees deeper than 128 to bound their recursion; `unpack` and `stat` do not apply that limit. diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index c827c84..c6f2903 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -161,7 +161,7 @@ data_block_meta[data_block_count] - 块内 `file_ids` 严格递增,同一块不能引用同一个文件两次。 - 文件区间(`file_offsets` + `file_compressed_sizes`)有序、互不重叠,且都位于 `payload_size` 内。 -- 对 `kLZ4`/`kLZ4HC`,`file_orig_sizes` 和 `file_compressed_sizes` 必须落在 LZ4 的 `int` API 范围内,`file_orig_sizes <= 255 * file_compressed_sizes`,且原始大小为 0 时存储大小也必须为 0。 +- 对 `kLZ4`/`kLZ4HC`,`file_orig_sizes` 和 `file_compressed_sizes` 必须落在 LZ4 的 `int` API 范围内,`file_orig_sizes <= 255 * file_compressed_sizes`,原始大小为 0 时存储大小也必须为 0,且存储大小必须严格小于原始大小(压缩没有变小时打包器会存原始数据)。 - 每个 `file_ids[i]` 都必须存在于 `file_entry_records`,其 `block_id`、`file_orig_size`、`file_compressed_size` 和绝对 `file_offset` 与块元数据一致;所有索引文件都必须被且仅被引用一次。 - 目录路径唯一,同一目录内文件名唯一,保证每个解压文件有唯一的输出路径。 - 目录索引必须是以 `kRootDirId`(1)为根的树:每个非 root 目录恰好出现一次作为子节点,任何目录都不是自己的祖先,所有目录都能从 root 到达。渲染命令(`tree`、`ls`、`dump`)额外拒绝深度超过 128 的树以限制递归;`unpack` 和 `stat` 不施加该限制。空 data block 是非法的。 diff --git a/include/ctar/reader.h b/include/ctar/reader.h index 58ce720..c679e20 100644 --- a/include/ctar/reader.h +++ b/include/ctar/reader.h @@ -45,8 +45,6 @@ namespace ctar { public: Buffer() = default; - /// Library-internal: takes ownership of an already-filled buffer. - Buffer(std::unique_ptr data, size_t size) noexcept; Buffer(const Buffer&) = delete; Buffer& operator=(const Buffer&) = delete; @@ -59,6 +57,10 @@ namespace ctar } private: + friend class ArchiveReader; + /// Created only by ArchiveReader::MakeBuffer. + Buffer(std::unique_ptr data, size_t size) noexcept; + std::unique_ptr data_; size_t size_ = 0; }; @@ -98,8 +100,9 @@ namespace ctar /// Reject archives whose uncompressed metadata exceeds this many bytes. /// 0 means unlimited. Matches the CLI's --max-metadata-size. uint64_t max_metadata_size = 1ULL << 30; - /// Reject files whose original size exceeds this many bytes. 0 means - /// unlimited. Matches the CLI's --max-decompressed-size. + /// Reject files whose original size, or whose stored size in the + /// archive, exceeds this many bytes. 0 means unlimited. Matches the + /// CLI's --max-decompressed-size. uint64_t max_file_size = 1ULL << 30; }; @@ -141,6 +144,7 @@ namespace ctar private: struct Impl; explicit ArchiveReader(std::unique_ptr impl) noexcept; + static std::shared_ptr MakeBuffer(std::unique_ptr data, size_t size); std::unique_ptr impl_; }; diff --git a/src/core/archive_reader.cpp b/src/core/archive_reader.cpp index 971c51f..cbe4eb1 100644 --- a/src/core/archive_reader.cpp +++ b/src/core/archive_reader.cpp @@ -92,6 +92,14 @@ namespace } return std::format("{}/{}", parent, name); } + + /// A stored file name must be exactly one path component. The archive is + /// untrusted: names containing separators or "."/".." would otherwise + /// escape the virtual root or change the meaning of Entry::path. + bool IsValidPathComponent(const std::string_view name) + { + return !name.empty() && name != "." && name != ".." && name.find('/') == std::string_view::npos; + } } // namespace struct ArchiveReader::Impl @@ -143,6 +151,21 @@ struct ArchiveReader::Impl return std::unexpected(FromStatus(stored.error())); } const fs::path relative = fs::path(stored.value()).lexically_normal().lexically_relative(root_fs); + if (relative.is_absolute()) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, + std::format("directory path '{}' is outside the archive root", stored.value()))); + } + for (const auto& component : relative) + { + if (component == "." || component == "..") + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, + std::format("directory path '{}' escapes the archive root", stored.value()))); + } + } std::string virtual_path; if (relative.empty() || relative == ".") { @@ -170,6 +193,11 @@ struct ArchiveReader::Impl { return std::unexpected(FromStatus(name.error())); } + if (!IsValidPathComponent(name.value())) + { + return std::unexpected( + MakeError(ErrorCode::kCorruption, std::format("invalid file name '{}'", name.value()))); + } if (!names.emplace(name.value(), file_id).second) { return std::unexpected( @@ -292,12 +320,13 @@ struct ArchiveReader::Impl const uint64_t stored_size = block.file_compressed_sizes[index]; const CompressionType compression_type = block.file_compressed_types[index]; - if (options.max_file_size > 0 && original_size > options.max_file_size) + if (options.max_file_size > 0 && + (original_size > options.max_file_size || stored_size > options.max_file_size)) { return std::unexpected(MakeError( ErrorCode::kTooLarge, - std::format("file is {} bytes, above the configured limit of {} bytes", original_size, - options.max_file_size))); + std::format("file is {} bytes ({} stored), above the configured limit of {} bytes", original_size, + stored_size, options.max_file_size))); } std::unique_ptr stored; @@ -339,13 +368,17 @@ struct ArchiveReader::Impl return std::unexpected( MakeError(ErrorCode::kCorruption, "file data does not match the recorded hash")); } - return std::shared_ptr( - std::make_shared(std::move(data), static_cast(original_size))); + return ArchiveReader::MakeBuffer(std::move(data), static_cast(original_size)); } }; Buffer::Buffer(std::unique_ptr data, const size_t size) noexcept : data_(std::move(data)), size_(size) {} +std::shared_ptr ArchiveReader::MakeBuffer(std::unique_ptr data, const size_t size) +{ + return std::shared_ptr(new Buffer(std::move(data), size)); +} + File::File(std::shared_ptr data) noexcept : data_(std::move(data)) {} uint64_t File::Size() const noexcept { return data_ ? data_->size() : 0; } diff --git a/src/core/block_store.h b/src/core/block_store.h index 825cfe8..8205d66 100644 --- a/src/core/block_store.h +++ b/src/core/block_store.h @@ -345,7 +345,6 @@ namespace ctar { return data_block_metas_; } - [[nodiscard]] uint64_t GetFileDataOffset() const noexcept { return file_data_offset_; } /// @brief Read and validate only the archive header; no metadata is parsed. [[nodiscard]] Status ReadPackHeaderOnly(const std::string& pack_file_path); diff --git a/src/core/file_format.cpp b/src/core/file_format.cpp index 26213c5..add7d25 100644 --- a/src/core/file_format.cpp +++ b/src/core/file_format.cpp @@ -474,6 +474,15 @@ namespace "{}: original size {} exceeds the LZ4 expansion bound of {} x stored size {}", entry_label(i), original, kLz4MaxExpansion, compressed); } + // The packer stores LZ4 data only when it is strictly smaller; + // equal or larger stored data is the kNone fallback. Rejecting + // it here also bounds the stored buffer a reader allocates. + if (compressed >= original) + { + return error_corruption( + "{}: LZ4 stored size {} is not smaller than the original size {}", entry_label(i), + compressed, original); + } } break; default: diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index ef5e20e..84eaa4c 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -7,6 +7,8 @@ #include #include +#include + #include "src/core/block_store.h" #include "src/core/file_handle.h" #include "src/utils/coding.h" @@ -1034,6 +1036,91 @@ namespace ctar fs::remove_all(root); } + TEST(MalformedArchive, ArchiveReaderRejectsFileNameWithSeparator) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + + constexpr size_t kMetadataOffsetField = 96; + constexpr size_t kMetadataSizeField = 112; + constexpr size_t kMetadataTypeField = 120; + constexpr size_t kMetadataChecksumField = 128; + const size_t metadata_offset = ReadU64At(bytes, kMetadataOffsetField); + const size_t metadata_size = ReadU64At(bytes, kMetadataSizeField); + ASSERT_EQ(ReadU64At(bytes, kMetadataTypeField), static_cast(CompressionType::kNone)); + + // PackFileMeta: four scalars, dir_name_data, file_name_data. + size_t pos = metadata_offset; + for (int i = 0; i < 4; ++i) + { + pos += sizeof(uint64_t); + } + const uint64_t dir_len = ReadU64At(bytes, pos); + pos += sizeof(uint64_t) + static_cast(dir_len); + const uint64_t file_len = ReadU64At(bytes, pos); + pos += sizeof(uint64_t); + const size_t file_data_start = pos; + + const size_t dot = bytes.find('.', file_data_start); + ASSERT_LT(dot, file_data_start + static_cast(file_len)); + bytes[dot] = '/'; + + const std::string metadata = bytes.substr(metadata_offset, metadata_size); + WriteU64At(bytes, kMetadataChecksumField, XXH64(metadata.data(), metadata.size(), kHashSeed)); + WriteWholeFile(fixture.archive.string(), bytes); + + auto reader = ArchiveReader::Open(fixture.archive.string()); + ASSERT_FALSE(reader); + EXPECT_EQ(reader.error().code, ErrorCode::kCorruption); + EXPECT_NE(reader.error().message.find("invalid file name"), std::string::npos) << reader.error().message; + + fixture.Cleanup(); + } + + TEST(MalformedArchive, ArchiveReaderRejectsDirectoryEscapingRoot) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + + constexpr size_t kMetadataOffsetField = 96; + constexpr size_t kMetadataSizeField = 112; + constexpr size_t kMetadataTypeField = 120; + constexpr size_t kMetadataChecksumField = 128; + const size_t metadata_offset = ReadU64At(bytes, kMetadataOffsetField); + const size_t metadata_size = ReadU64At(bytes, kMetadataSizeField); + ASSERT_EQ(ReadU64At(bytes, kMetadataTypeField), static_cast(CompressionType::kNone)); + + size_t pos = metadata_offset; + for (int i = 0; i < 4; ++i) + { + pos += sizeof(uint64_t); + } + const uint64_t dir_len = ReadU64At(bytes, pos); + pos += sizeof(uint64_t); + const size_t dir_data_start = pos; + ASSERT_GE(dir_len, 3U); + + // The last directory name is "sub"; make the stored path end in "/../". + ASSERT_EQ(bytes.substr(dir_data_start + static_cast(dir_len) - 3, 3), "sub"); + bytes[dir_data_start + static_cast(dir_len) - 3] = '.'; + bytes[dir_data_start + static_cast(dir_len) - 2] = '.'; + bytes[dir_data_start + static_cast(dir_len) - 1] = '/'; + + const std::string metadata = bytes.substr(metadata_offset, metadata_size); + WriteU64At(bytes, kMetadataChecksumField, XXH64(metadata.data(), metadata.size(), kHashSeed)); + WriteWholeFile(fixture.archive.string(), bytes); + + auto reader = ArchiveReader::Open(fixture.archive.string()); + ASSERT_FALSE(reader); + EXPECT_EQ(reader.error().code, ErrorCode::kCorruption); + EXPECT_NE(reader.error().message.find("escapes the archive root"), std::string::npos) + << reader.error().message; + + fixture.Cleanup(); + } + namespace { struct UnpackPolicyFixture diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index f1622ad..bda0e48 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -341,6 +341,28 @@ namespace ctar << status.error().message(); } + TEST(DataBlobMeta, RejectsLz4StoredSizeNotSmallerThanOriginal) + { + for (const uint64_t stored : {100ULL, 150ULL}) + { + DataBlockMeta block; + block.file_ids = {1}; + block.file_orig_sizes = {100}; + block.file_compressed_sizes = {stored}; + block.file_compressed_types = {CompressionType::kLZ4}; + block.file_offsets = {0}; + block.file_hashes = {0}; + block.payload_size = stored; + block.block_size = stored; + + const Status status = ValidateDataBlockMeta(block); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("not smaller"), std::string::npos) + << status.error().message(); + } + } + TEST(DataBlobMeta, RejectsLz4EntryWithZeroOriginalSize) { DataBlockMeta block;