From 7b73ab681f37f3022b7a172dc2d79f94da6fc973 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Thu, 26 Nov 2026 21:56:31 +0800 Subject: [PATCH 1/3] fix: reject cyclic directory graphs before rendering PackFileMeta::Deserialize accepted child maps without validating the directory graph, and RenderDirListing recursed without a visited set. A crafted archive whose root or a subdirectory lists an ancestor made ls, tree and dump recurse until stack overflow; repeated child edges could also blow up output exponentially. Validate the graph after metadata deserialization: root presence, one parent per non-root directory, no self/root edges or duplicate parents, reachability and cycle checks via BFS, and a depth limit of 1024. Add an active-set and depth guard to the renderer as defense in depth, and cover both with unit and malformed-archive tests. Empty data blocks are also documented as invalid (the reader already rejects them). No format change; archive bytes are unchanged. Closes #75 --- doc/file_format.md | 5 +- doc/file_format_CN.md | 3 +- src/core/block_store.cpp | 4 + src/core/file_format.cpp | 126 ++++++++++++++++++++++- src/core/file_format.h | 20 ++++ src/core/options.h | 5 + test/cases/test_block_store.cpp | 69 +++++++++++++ test/cases/test_file_format.cpp | 176 ++++++++++++++++++++++++++++++++ 8 files changed, 402 insertions(+), 6 deletions(-) diff --git a/doc/file_format.md b/doc/file_format.md index db5d9ee..cd43437 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -141,8 +141,8 @@ data_block_meta[data_block_count] | 11 | 8 + 8n | `file_offsets` | `u64 count` + `count × u64`, relative to the block payload | | 12 | 8 + 8n | `file_hashes` | `u64 count` + `count × u64`, XXH64 of the original bytes | -The raw `u64` arrays are stored as consecutive little-endian values. A data block meta is at least -12 × 8 = 96 bytes. +The raw `u64` arrays are stored as consecutive little-endian values. Empty data blocks are invalid; the +smallest valid block contains one file and is 137 bytes. ### magic_number @@ -166,6 +166,7 @@ The reader rejects archives that violate these cross-field invariants; a writer - 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. - 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, every directory is reachable from the root, and the depth does not exceed 1024. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). - All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, compressed metadata must be strictly smaller than its original size, and empty data blocks are invalid. diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index fc04041..13efca9 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -140,7 +140,7 @@ data_block_meta[data_block_count] | 11 | 8 + 8n | `file_offsets` | `u64 count` + `count × u64`,相对于块 payload 起点 | | 12 | 8 + 8n | `file_hashes` | `u64 count` + `count × u64`,原始数据的 XXH64 | -原始 `u64` 数组按连续的小端数值存储。一个 data block meta 至少为 12 × 8 = 96 字节。 +原始 `u64` 数组按连续的小端数值存储。空 data block 是非法的;最小的合法块包含一个文件,共 137 字节。 ### magic_number @@ -164,6 +164,7 @@ data_block_meta[data_block_count] - 对 `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 到达,且深度不超过 1024。空 data block 是非法的。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 - 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小,空 data block 也是非法的。 diff --git a/src/core/block_store.cpp b/src/core/block_store.cpp index ad9befc..fbe0d18 100644 --- a/src/core/block_store.cpp +++ b/src/core/block_store.cpp @@ -1300,6 +1300,10 @@ namespace ctar { return s; } + if (auto graph_status = pack_file_handle_.ValidateDirectoryGraph(); !graph_status) + { + return error_corruption("corrupt archive '{}': {}", pack_file_path, graph_status.error().message()); + } if (static_cast(meta_end - meta_ptr) < sizeof(uint64_t)) { return error_corruption("corrupt archive '{}': missing data block count", pack_file_path); diff --git a/src/core/file_format.cpp b/src/core/file_format.cpp index b855124..35e66e1 100644 --- a/src/core/file_format.cpp +++ b/src/core/file_format.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include "file_format.h" #include "src/utils/coding.h" @@ -482,6 +484,95 @@ namespace return {}; } + Status ValidateDirectoryGraph(const PackFileMeta& meta) + { + // Directory entries are identified by their presence in dir_entry_records; + // entry_type is not reliable for directories in existing archives (the + // scanner re-adds each directory with a default EntryMeta), so the graph + // structure is validated by id membership only. + if (meta.dir_entry_records.find(kRootDirId) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: root directory {} has no entry", kRootDirId); + } + + // Every non-root directory must have exactly one parent; duplicate edges and + // multiple parents are rejected here, before any traversal can loop. + std::unordered_map parent_of; + parent_of.reserve(meta.dir_entry_records.size()); + for (const auto& children_entry : meta.dir_id_to_child_dir_ids) + { + const entry_id_t parent_id = children_entry.first; + if (meta.dir_entry_records.find(parent_id) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: parent {} has no directory entry", parent_id); + } + for (const entry_id_t child_id : children_entry.second) + { + if (child_id == parent_id) + { + return error_corruption("directory graph: directory {} lists itself as a child", parent_id); + } + if (child_id == kRootDirId) + { + return error_corruption("directory graph: root directory {} appears as a child", kRootDirId); + } + if (meta.dir_entry_records.find(child_id) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: child {} of directory {} has no entry", child_id, + parent_id); + } + if (!parent_of.emplace(child_id, parent_id).second) + { + return error_corruption("directory graph: directory {} has more than one parent", child_id); + } + } + } + for (const auto& dir_entry : meta.dir_entry_records) + { + if (dir_entry.first != kRootDirId && parent_of.find(dir_entry.first) == parent_of.end()) + { + return error_corruption("directory graph: directory {} has no parent", dir_entry.first); + } + } + + // Breadth-first traversal from the root detects cycles reachable from it and + // directories that are only part of a disconnected cycle. The depth bound + // keeps the recursive renderer's stack safe for an otherwise valid chain. + std::unordered_set visited; + visited.reserve(meta.dir_entry_records.size()); + std::vector> queue; + queue.reserve(meta.dir_entry_records.size()); + queue.emplace_back(kRootDirId, 0); + visited.insert(kRootDirId); + for (size_t head = 0; head < queue.size(); ++head) + { + const auto [dir_id, depth] = queue[head]; + if (depth > kMaxDirectoryDepth) + { + return error_corruption("directory graph: depth exceeds the limit {}", kMaxDirectoryDepth); + } + const auto children = meta.dir_id_to_child_dir_ids.find(dir_id); + if (children == meta.dir_id_to_child_dir_ids.end()) + { + continue; + } + for (const entry_id_t child_id : children->second) + { + if (!visited.insert(child_id).second) + { + return error_corruption("directory graph: cycle detected at directory {}", child_id); + } + queue.emplace_back(child_id, depth + 1); + } + } + if (visited.size() != meta.dir_entry_records.size()) + { + return error_corruption("directory graph: {} directories are unreachable from root", + meta.dir_entry_records.size() - visited.size()); + } + return {}; + } + PackFileMeta::PackFileMeta() { dir_name_data.reserve(kEntryNameBufferSize); @@ -1168,9 +1259,37 @@ namespace } + Status PackFileHandle::ValidateDirectoryGraph() const + { + return ctar::ValidateDirectoryGraph(pack_file_meta_); + } + Status PackFileHandle::RenderDirListing(std::ostream& out, entry_id_t dir_id, const std::string& prefix, const OutputMode output_mode, bool human_readable, bool has_header) const { + std::unordered_set active; + return RenderDirListingImpl(out, dir_id, prefix, output_mode, human_readable, has_header, active, 0); + } + + Status PackFileHandle::RenderDirListingImpl(std::ostream& out, entry_id_t dir_id, const std::string& prefix, + const OutputMode output_mode, bool human_readable, bool has_header, + std::unordered_set& active, const size_t depth) const + { + if (depth > kMaxDirectoryDepth) + { + return error_corruption("directory tree depth exceeds the limit {}", kMaxDirectoryDepth); + } + if (!active.insert(dir_id).second) + { + return error_corruption("directory cycle detected at directory {}", dir_id); + } + struct ActiveDirectoryGuard + { + std::unordered_set& active; + entry_id_t dir_id; + ~ActiveDirectoryGuard() { active.erase(dir_id); } + } active_guard{active, dir_id}; + auto dir_name_res = GetDirPathByDirId(dir_id); if (!dir_name_res) { @@ -1234,8 +1353,8 @@ namespace if (entry.is_directory) { std::string new_prefix = prefix + (is_last ? " " : "│ "); - auto status = - RenderDirListing(out, entry.id, new_prefix, OutputMode::TREE, human_readable, has_header); + auto status = RenderDirListingImpl(out, entry.id, new_prefix, OutputMode::TREE, human_readable, + has_header, active, depth + 1); if (!status) return status; } @@ -1277,7 +1396,8 @@ namespace } else { - auto status = RenderDirListing(out, entry.id, prefix, output_mode, human_readable, has_header); + auto status = RenderDirListingImpl(out, entry.id, prefix, output_mode, human_readable, has_header, + active, depth + 1); if (!status) return status; } diff --git a/src/core/file_format.h b/src/core/file_format.h index fdf776b..6e45bd2 100644 --- a/src/core/file_format.h +++ b/src/core/file_format.h @@ -12,6 +12,7 @@ #include #include #include +#include #include "options.h" #include "sorted_map.h" @@ -279,6 +280,11 @@ namespace ctar [[nodiscard]] const std::string& GetUserName(uint32_t uid); [[nodiscard]] const std::string& GetGroupName(uint32_t gid); + /// @brief Recursive renderer with cycle/depth guards; see RenderDirListing. + Status RenderDirListingImpl(std::ostream& out, entry_id_t dir_id, const std::string& prefix, + OutputMode output_mode, bool human_readable, bool has_header, + std::unordered_set& active, size_t depth) const; + public: /// @brief Scan host filesystem directory, import entries into pack metadata /// @param root_path designated host‑system root directory for scanning @@ -351,6 +357,10 @@ namespace ctar /// @brief Number of directory entries, including the root directory. [[nodiscard]] size_t GetDirectoryCount() const { return pack_file_meta_.dir_entry_records.size(); } + /// @brief Validate the deserialized directory graph before rendering or unpacking. + /// @return Status::Ok when the graph is a tree rooted at kRootDirId; kCorruption otherwise + [[nodiscard]] Status ValidateDirectoryGraph() const; + /// @brief Add entry metadata into map, append name string to data buffer /// @param key unique entry id /// @param name entry dir/file name @@ -545,5 +555,15 @@ namespace ctar /// @return Ok on success, kCorruption otherwise Status ValidateDataBlockMeta(const DataBlockMeta& block_meta, const EntryPathResolver& path_of = {}, uint64_t max_original_size = kDefaultMaxDecompressedFileSize); + + /// @brief Validate the directory graph in a deserialized PackFileMeta. + /// + /// The child maps are untrusted: they must describe a tree rooted at kRootDirId, + /// with exactly one parent for every non-root directory, no cycles or duplicate + /// edges, and every directory reachable from the root. Chains deeper than + /// kMaxDirectoryDepth are rejected so the recursive renderer cannot overflow. + /// @param meta deserialized metadata index + /// @return Ok on success, kCorruption otherwise + Status ValidateDirectoryGraph(const PackFileMeta& meta); }; // namespace ctar #endif // CTAR_FORMAT_H diff --git a/src/core/options.h b/src/core/options.h index 3233ac9..1c7b394 100644 --- a/src/core/options.h +++ b/src/core/options.h @@ -51,6 +51,11 @@ namespace ctar // --max-metadata-size (0 disables the limit). constexpr uint64_t kDefaultMaxMetadataSize = 1ULL * unit::GiB; + // Maximum directory depth accepted by archive readers. Both graph validation and + // the recursive renderer reject deeper trees so a hostile chain cannot overflow + // the render stack. Real filesystem paths are far shallower than this. + constexpr size_t kMaxDirectoryDepth = 1024; + // Thread-local read/block buffers larger than this are trimmed back to this // size after a task, instead of being held until the process exits. constexpr size_t kMaxRetainedBufferBytes = 128UL * unit::MiB; diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index 8fdcef2..b39390a 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -927,6 +927,75 @@ namespace ctar } + TEST(MalformedArchive, RejectsCyclicDirectoryGraph) + { + 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; + constexpr size_t kEntryRecordSize = 2 * sizeof(uint64_t) + 176; + + const size_t metadata_offset = ReadU64At(bytes, kMetadataOffsetField); + const size_t metadata_size = ReadU64At(bytes, kMetadataSizeField); + ASSERT_GT(metadata_size, 0U); + ASSERT_EQ(ReadU64At(bytes, kMetadataTypeField), static_cast(CompressionType::kNone)); + + size_t pos = metadata_offset; + const size_t metadata_end = metadata_offset + metadata_size; + const auto read_u64 = [&]() + { + EXPECT_LE(pos + sizeof(uint64_t), metadata_end); + const uint64_t value = ReadU64At(bytes, pos); + pos += sizeof(uint64_t); + return value; + }; + + // PackFileMeta: four scalars, two name buffers, then the two entry maps. + for (int i = 0; i < 4; ++i) + { + (void)read_u64(); + } + pos += static_cast(read_u64()); // dir_name_data + pos += static_cast(read_u64()); // file_name_data + for (int map = 0; map < 2; ++map) + { + const uint64_t count = read_u64(); + pos += static_cast(count) * (sizeof(uint64_t) + kEntryRecordSize); + } + + // Patch the root's first child into a self-cycle, then make the checksum valid + // so the archive reaches the directory-graph validation. + const uint64_t map_count = read_u64(); + bool patched = false; + for (uint64_t entry = 0; entry < map_count; ++entry) + { + const entry_id_t parent = read_u64(); + const uint64_t child_count = read_u64(); + if (parent == kRootDirId && child_count > 0) + { + WriteU64At(bytes, pos, kRootDirId); + patched = true; + break; + } + pos += static_cast(child_count) * sizeof(uint64_t); + } + ASSERT_TRUE(patched); + + const std::string metadata = bytes.substr(metadata_offset, metadata_size); + WriteU64At(bytes, kMetadataChecksumField, XXH64(metadata.data(), metadata.size(), kHashSeed)); + + const Status status = fixture.Unpack(bytes); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("directory graph"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + namespace { struct UnpackPolicyFixture diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index 0b3fe23..30f4f12 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -925,6 +926,181 @@ namespace ctar } + namespace + { + void AddDirEntry(PackFileMeta& meta, const entry_id_t id) + { + meta.dir_entry_records.put(id, EntryRecord{}); + } + } // namespace + + TEST(DirectoryGraph, AcceptsRootOnly) + { + PackFileMeta meta; + AddDirEntry(meta, kRootDirId); + EXPECT_TRUE(ValidateDirectoryGraph(meta)); + } + + TEST(DirectoryGraph, AcceptsValidTree) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {3}); + EXPECT_TRUE(ValidateDirectoryGraph(meta)); + } + + TEST(DirectoryGraph, RejectsMissingRoot) + { + PackFileMeta meta; + AddDirEntry(meta, 2); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("root"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsSelfCycle) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + meta.dir_id_to_child_dir_ids.put(1, {1}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("lists itself"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsRootAsChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {1}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("root directory"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsMultipleParents) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(3, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("more than one parent"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsDisconnectedCycle) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + AddDirEntry(meta, 4); + meta.dir_id_to_child_dir_ids.put(1, {3}); + meta.dir_id_to_child_dir_ids.put(2, {4}); + meta.dir_id_to_child_dir_ids.put(4, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("unreachable"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsUnknownChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + meta.dir_id_to_child_dir_ids.put(1, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("child 2"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsUnknownParent) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(3, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("parent 3"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsMissingParent) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("directory 2 has no parent"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsDuplicateChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(1, {2, 2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("more than one parent"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsDepthAboveLimit) + { + PackFileMeta meta; + const size_t dir_count = kMaxDirectoryDepth + 2; + for (size_t id = 1; id <= dir_count; ++id) + { + AddDirEntry(meta, static_cast(id)); + } + for (size_t id = 1; id < dir_count; ++id) + { + meta.dir_id_to_child_dir_ids.put(static_cast(id), {static_cast(id + 1)}); + } + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + } + + TEST(DirectoryGraph, RendererRejectsCycle) + { + PackFileMeta meta; + meta.dir_name_data = "rootchild"; + EntryRecord root{}; + root.name_handle.offset = 0; + root.name_handle.len = 4; + root.entry_meta.entry_type = EntryType::DIRECTORY; + EntryRecord child{}; + child.name_handle.offset = 4; + child.name_handle.len = 5; + child.entry_meta.entry_type = EntryType::DIRECTORY; + meta.dir_entry_records.put(1, root); + meta.dir_entry_records.put(2, child); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {1}); + + std::string bytes; + meta.Serialize(&bytes); + PackFileHandle handle; + const char* ptr = bytes.data(); + ASSERT_TRUE(handle.DeserializePackFileMeta(ptr, bytes.data() + bytes.size())); + + std::ostringstream out; + const Status status = handle.RenderDirListing(out); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("cycle"), std::string::npos); + } + } // namespace ctar int main(int argc, char** argv) From b2058d921a91ddd82ae36db886d1019a51124899 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Thu, 26 Nov 2026 22:25:39 +0800 Subject: [PATCH 2/3] fix: cap directory depth at the renderer stack budget DirectoryGraph.RendererRejectsDepth exposed that a 1025-level chain overflows the ASan stack before the depth guard can return. Lower kMaxDirectoryDepth to 128 so both the loader and the recursive renderer stay within realistic stack budgets; real filesystem paths are far shallower. Add the renderer-depth test and remove the duplicated empty-block note from the metadata bullet. Refs #75 --- doc/file_format.md | 4 ++-- doc/file_format_CN.md | 4 ++-- src/core/options.h | 5 +++-- test/cases/test_file_format.cpp | 31 +++++++++++++++++++++++++++++++ 4 files changed, 38 insertions(+), 6 deletions(-) diff --git a/doc/file_format.md b/doc/file_format.md index cd43437..60d4bca 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -166,9 +166,9 @@ The reader rejects archives that violate these cross-field invariants; a writer - 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. - 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, every directory is reachable from the root, and the depth does not exceed 1024. +- 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, every directory is reachable from the root, and the depth does not exceed 128. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). -- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, compressed metadata must be strictly smaller than its original size, and empty data blocks are invalid. +- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, and compressed metadata must be strictly smaller than its original size. ### version encoding and compatibility diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index 13efca9..e3e3dcf 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -164,9 +164,9 @@ data_block_meta[data_block_count] - 对 `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 到达,且深度不超过 1024。空 data block 是非法的。 +- 目录索引必须是以 `kRootDirId`(1)为根的树:每个非 root 目录恰好出现一次作为子节点,任何目录都不是自己的祖先,所有目录都能从 root 到达,且深度不超过 128。空 data block 是非法的。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 -- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小,空 data block 也是非法的。 +- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小。 ### 版本编码与兼容性 diff --git a/src/core/options.h b/src/core/options.h index 1c7b394..a814fbf 100644 --- a/src/core/options.h +++ b/src/core/options.h @@ -53,8 +53,9 @@ namespace ctar // Maximum directory depth accepted by archive readers. Both graph validation and // the recursive renderer reject deeper trees so a hostile chain cannot overflow - // the render stack. Real filesystem paths are far shallower than this. - constexpr size_t kMaxDirectoryDepth = 1024; + // the render stack; 128 still leaves headroom under ASan stack frames, and real + // filesystem paths are far shallower. + constexpr size_t kMaxDirectoryDepth = 128; // Thread-local read/block buffers larger than this are trimmed back to this // size after a task, instead of being held until the process exits. diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index 30f4f12..e0ec930 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -1071,6 +1071,37 @@ namespace ctar EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); } + TEST(DirectoryGraph, RendererRejectsDepth) + { + PackFileMeta meta; + meta.dir_name_data = "d"; + const size_t dir_count = kMaxDirectoryDepth + 2; + for (size_t id = 1; id <= dir_count; ++id) + { + EntryRecord record{}; + record.name_handle.offset = 0; + record.name_handle.len = 1; + record.entry_meta.entry_type = EntryType::DIRECTORY; + meta.dir_entry_records.put(static_cast(id), record); + } + for (size_t id = 1; id < dir_count; ++id) + { + meta.dir_id_to_child_dir_ids.put(static_cast(id), {static_cast(id + 1)}); + } + + std::string bytes; + meta.Serialize(&bytes); + PackFileHandle handle; + const char* ptr = bytes.data(); + ASSERT_TRUE(handle.DeserializePackFileMeta(ptr, bytes.data() + bytes.size())); + + std::ostringstream out; + const Status status = handle.RenderDirListing(out); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + } + TEST(DirectoryGraph, RendererRejectsCycle) { PackFileMeta meta; From 57409f8661795e6481a7d7e6d1074e1fe0462562 Mon Sep 17 00:00:00 2001 From: blocksmith314 Date: Thu, 26 Nov 2026 22:52:28 +0800 Subject: [PATCH 3/3] fix: apply the depth limit only to recursive rendering The depth cap was enforced by ValidateDirectoryGraph, so unpack and stat rejected valid deep trees produced by ctar even though they do not recurse. Keep the acyclic/single-parent/reachability validation for every reader, but move the depth bound to RenderDirListing only; unpack and stat now accept deep valid trees, while tree/ls/dump return kCorruption instead of overflowing the stack. Add a regression test that packs and unpacks a tree deeper than the renderer limit and verifies rendering fails cleanly. Refs #75 --- doc/file_format.md | 2 +- doc/file_format_CN.md | 2 +- src/core/file_format.cpp | 17 ++++++--------- src/core/options.h | 8 +++---- test/cases/test_block_store.cpp | 38 +++++++++++++++++++++++++++++++++ test/cases/test_file_format.cpp | 6 ++---- 6 files changed, 53 insertions(+), 20 deletions(-) diff --git a/doc/file_format.md b/doc/file_format.md index 60d4bca..7bf699c 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -166,7 +166,7 @@ The reader rejects archives that violate these cross-field invariants; a writer - 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. - 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, every directory is reachable from the root, and the depth does not exceed 128. +- 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. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). - All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, and compressed metadata must be strictly smaller than its original size. diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index e3e3dcf..c827c84 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -164,7 +164,7 @@ data_block_meta[data_block_count] - 对 `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 到达,且深度不超过 128。空 data block 是非法的。 +- 目录索引必须是以 `kRootDirId`(1)为根的树:每个非 root 目录恰好出现一次作为子节点,任何目录都不是自己的祖先,所有目录都能从 root 到达。渲染命令(`tree`、`ls`、`dump`)额外拒绝深度超过 128 的树以限制递归;`unpack` 和 `stat` 不施加该限制。空 data block 是非法的。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 - 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小。 diff --git a/src/core/file_format.cpp b/src/core/file_format.cpp index 35e66e1..26213c5 100644 --- a/src/core/file_format.cpp +++ b/src/core/file_format.cpp @@ -536,21 +536,18 @@ namespace } // Breadth-first traversal from the root detects cycles reachable from it and - // directories that are only part of a disconnected cycle. The depth bound - // keeps the recursive renderer's stack safe for an otherwise valid chain. + // directories that are only part of a disconnected cycle. The depth limit is + // a renderer concern, not an archive invariant: unpack and stat must accept + // deeper valid trees, while the recursive renderer rejects them. std::unordered_set visited; visited.reserve(meta.dir_entry_records.size()); - std::vector> queue; + std::vector queue; queue.reserve(meta.dir_entry_records.size()); - queue.emplace_back(kRootDirId, 0); + queue.push_back(kRootDirId); visited.insert(kRootDirId); for (size_t head = 0; head < queue.size(); ++head) { - const auto [dir_id, depth] = queue[head]; - if (depth > kMaxDirectoryDepth) - { - return error_corruption("directory graph: depth exceeds the limit {}", kMaxDirectoryDepth); - } + const entry_id_t dir_id = queue[head]; const auto children = meta.dir_id_to_child_dir_ids.find(dir_id); if (children == meta.dir_id_to_child_dir_ids.end()) { @@ -562,7 +559,7 @@ namespace { return error_corruption("directory graph: cycle detected at directory {}", child_id); } - queue.emplace_back(child_id, depth + 1); + queue.push_back(child_id); } } if (visited.size() != meta.dir_entry_records.size()) diff --git a/src/core/options.h b/src/core/options.h index a814fbf..fb2dbf2 100644 --- a/src/core/options.h +++ b/src/core/options.h @@ -51,10 +51,10 @@ namespace ctar // --max-metadata-size (0 disables the limit). constexpr uint64_t kDefaultMaxMetadataSize = 1ULL * unit::GiB; - // Maximum directory depth accepted by archive readers. Both graph validation and - // the recursive renderer reject deeper trees so a hostile chain cannot overflow - // the render stack; 128 still leaves headroom under ASan stack frames, and real - // filesystem paths are far shallower. + // Maximum depth accepted by the recursive renderer (tree/ls/dump). This is a + // rendering limit, not an archive invariant: unpack and stat accept deeper valid + // trees, while the renderer returns kCorruption instead of overflowing its stack. + // 128 still leaves headroom under ASan stack frames. constexpr size_t kMaxDirectoryDepth = 128; // Thread-local read/block buffers larger than this are trimmed back to this diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index b39390a..ef5e20e 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -996,6 +997,43 @@ namespace ctar fixture.Cleanup(); } + TEST(DirectoryGraph, DeepTreeUnpacksButDoesNotRender) + { + const fs::path root{"deep_directory_graph_test"}; + const fs::path source = root / "source"; + const fs::path archive = root / "deep.ctar"; + const fs::path out = root / "out"; + fs::remove_all(root); + fs::create_directories(source); + fs::path deep = source; + for (size_t i = 0; i < kMaxDirectoryDepth + 2; ++i) + { + deep /= "d"; + fs::create_directory(deep); + } + std::ofstream(deep / "f.txt") << "x"; + + BlockStore packer; + ASSERT_TRUE(packer.Scan(source.string())); + ASSERT_TRUE(packer.PackPipeline(archive.string())); + + // Depth is not an archive invariant: unpack must restore the valid tree. + BlockStore unpacker; + ASSERT_TRUE(unpacker.UnPackPipeline(archive.string(), out.string(), true)); + EXPECT_TRUE(fs::exists(out / source / fs::relative(deep, source) / "f.txt")); + + // The recursive renderer rejects the deep tree instead of overflowing. + BlockStore reader; + ASSERT_TRUE(reader.RestoreBlocksFromPack(archive.string())); + std::ostringstream rendered; + const Status status = reader.RenderDirectoryTree(rendered); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + + fs::remove_all(root); + } + namespace { struct UnpackPolicyFixture diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index e0ec930..f1622ad 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -1054,7 +1054,7 @@ namespace ctar EXPECT_NE(status.error().err_message.find("more than one parent"), std::string::npos); } - TEST(DirectoryGraph, RejectsDepthAboveLimit) + TEST(DirectoryGraph, AcceptsDeepChain) { PackFileMeta meta; const size_t dir_count = kMaxDirectoryDepth + 2; @@ -1066,9 +1066,7 @@ namespace ctar { meta.dir_id_to_child_dir_ids.put(static_cast(id), {static_cast(id + 1)}); } - const Status status = ValidateDirectoryGraph(meta); - ASSERT_FALSE(status); - EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + EXPECT_TRUE(ValidateDirectoryGraph(meta)); } TEST(DirectoryGraph, RendererRejectsDepth)