Skip to content

feat: add public ArchiveReader API - #105

Merged
blocksmith314 merged 2 commits into
mainfrom
feat/101-public-read-api
Nov 28, 2026
Merged

blocksmith314 merged 2 commits into
mainfrom
feat/101-public-read-api

Conversation

@blocksmith314

@blocksmith314 blocksmith314 commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

Add the public C++ read API and make the installed package genuinely usable for archives.

  • Public headers (installed under include/ctar/): error.h with stable ErrorCode/Error/Result<T>, and reader.h with Entry, Buffer, File, ReaderOptions, ArchiveReader.
  • ArchiveReader: Open, List (direct or recursive), Stat, OpenFile, ReadFile.
    • Paths are virtual absolute paths rooted at /: the directory passed to ctar pack becomes /, so archives can be read without knowing where the source tree lived. .. is rejected, file names must be a single path component, and directory paths that escape the archive root are rejected.
    • A single-file read uses the absolute entry_meta.file_offset to read only that file's stored bytes, never the whole block and never extracting to disk. kNone entries are returned directly; LZ4/LZ4HC entries are decompressed and verified against the archive's XXH64.
    • Buffer is a shared-ownership byte buffer (data(), size(), view()), so callers can hand it to JPEG decoders or pyarrow without copying. Its constructor is private; buffers come from the reader.
    • File is the primitive: Size, sequential Read, ReadAt, ReadAll. A File outlives its reader.
    • ReaderOptions::max_metadata_size is enforced on Open; max_file_size is enforced per read against both the original and the stored size and returns kTooLarge, so one oversized file does not make the archive unreadable.
    • After Open the reader is immutable and safe for concurrent reads (pread-based); individual File objects are not thread-safe.
  • Index validation: the reader builds its virtual-path index from the already-validated metadata and additionally rejects names that are not one component, directory paths that escape the root, and a path that is both a file and a directory.
  • Stored-size invariant: ValidateDataBlockMeta now requires LZ4/LZ4HC stored data to be strictly smaller than the original size (the packer falls back to kNone otherwise). Besides matching what pack writes, this bounds the stored buffer a reader allocates.
  • Consumer smoke test now packs a tree with the CLI and reads it back through the installed headers, exercising the real API end to end (in addition to the pkg-config, no-gtest and bundled-lz4 checks).
  • README/README_CN document the API with an example; CLAUDE.md and the format docs record the invariants.

No archive-format change.

Review fixes

  • Blocked the stored-buffer amplification: strict compressed < original validation plus a stored-size check against max_file_size.
  • Validated path components (single-component file names, no escaping directory paths) with crafted-archive tests.
  • Made Buffer construction private via ArchiveReader::MakeBuffer; removed the unused BlockStore::GetFileDataOffset().

Known boundary

1.0.0 archives use the same validated RestoreBlocksFromPack path, but there is no 1.0.0 end-to-end fixture yet; that coverage is tracked by #84.

Tests

  • Release ctest: 215/215 passed
  • ASan ctest: 215/215 passed
  • New tests include ArchiveReader.* (list/stat/read/read-at, empty and raw files, budgets, path errors, moved-from reader, file outliving reader), DataBlobMeta.RejectsLz4StoredSizeNotSmallerThanOriginal, and crafted-archive tests for a slash file name and an out-of-root directory.
  • Consumer smoke test on a clean default build: install → find_package(ctar) → compile/link/run → pack with CLI → read back via ArchiveReader.

Performance gate

Against origin/main (99693d3): pack -0.8% wall time / -0.3% peak RSS; unpack +1.1% wall time / -1.6% peak RSS (5 runs). No regression.

Closes #101
Closes #83

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

@blocksmith314 blocksmith314 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

The public API shape, the consumer end-to-end test, and the File/Buffer lifetime model are good. Two gaps should be fixed before merge.

1. max_file_size does not bound the stored buffer (blocker)

ReadFileById() checks only original_size against ReaderOptions::max_file_size, then allocates stored_size from the block metadata:

if (options.max_file_size > 0 && original_size > options.max_file_size) { ... }
if (stored_size > 0)
    stored = std::make_unique_for_overwrite<char[]>(stored_size);

ValidateDataBlockMeta() does not require LZ4 compressed_size <= original_size (it only checks the 255x expansion bound and INT_MAX). A crafted entry with type=LZ4, original=1, compressed=1 GiB therefore passes metadata validation, and ReadFile() with max_file_size=1 still allocates a 1 GiB stored buffer before decompression.

Fix options:

  • check stored_size > max_file_size too, and/or
  • require compressed_size <= original_size for LZ4/LZ4HC in ValidateDataBlockMeta (valid pack only stores compressed data when it is strictly smaller).

This also bounds the peak stored + decompressed allocation. Add a malformed-archive test with a tiny original size and oversized stored size.

2. BuildIndexes() trusts file names and directory paths (blocker)

The index builds virtual paths directly:

const fs::path relative = ...lexically_relative(root_fs);
virtual_path = std::format("/{}", relative.generic_string());
...
const std::string full_path = JoinPath(dir_path->second, file_entry.first);

It validates duplicate names/dirs and exact file-vs-directory conflicts, but not path components. A crafted archive can contain:

  • a file name "a/b" or "../evil"
  • a directory stored path outside the root (lexically_relative returns ..)
  • a file name "a/" / "." / ".."

RestoreBlocksFromPack() only checks duplicate directory paths and duplicate names within a directory; it does not validate the name components. Consequences include List() returning paths such as /../evil or duplicate /dir/a/b entries, while Stat()/ReadFile() normalize/reject the input or resolve a different file. Applications may treat Entry::path as a real relative path.

Fix: validate each file name as exactly one component (non-empty, not ./.., no /), normalize each virtual directory path and reject ../escaping, then check file-vs-directory conflicts on normalized paths. Add malformed-archive tests for a slash name and an out-of-root directory.

Minor

  • Buffer(std::unique_ptr<char[]>, size_t) is public although the comment says library-internal; make it private/friend or document it.
  • The 1.0.0 end-to-end gap is explicitly tracked by #84; fine.
  • BlockStore::GetFileDataOffset() is added but unused.
  • If max_file_size starts bounding stored bytes too, update the ReaderOptions comment.

Verified locally: Release ctest 212/212, ASan ctest 212/212, consumer smoke test (including real archive read) passes, CI 5/5 green.

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

@blocksmith314 blocksmith314 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed 7c1e09e.

The previous blockers are fixed:

  • ValidateDataBlockMeta() now requires LZ4 stored size to be strictly smaller than the original, and ReadFileById() bounds both original and stored sizes with max_file_size
  • BuildIndexes() rejects file names that are not a single component and directory paths with absolute/./.. components; file-vs-directory conflicts are checked on the validated paths
  • Buffer's internal constructor is private with an ArchiveReader factory
  • unused GetFileDataOffset() removed
  • docs and malformed-archive tests added for the path cases and LZ4 stored-size case

Verified locally: Release ctest 215/215, ASan ctest 215/215, consumer smoke test (pack + real ArchiveReader read), legacy 1.0.0 stat, CI 5/5 green.

No blockers from my side. Minor follow-ups (not required here):

  • a reader test where stored_size > max_file_size but original_size <= max_file_size would isolate the stored-size branch
  • 1.0.0 end-to-end remains #84
  • File is implicitly copyable; if that is intentional, documenting copy semantics would help

@blocksmith314
blocksmith314 merged commit e377745 into main Nov 28, 2026
5 checks passed
@blocksmith314
blocksmith314 deleted the feat/101-public-read-api branch November 28, 2026 08:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: public C++ API to read files and directories from an archive in memory Build: installed CMake package cannot be consumed

1 participant