Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions doc/file_format.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -166,8 +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, 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, 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

Expand Down
5 changes: 3 additions & 2 deletions doc/file_format_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -164,8 +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 到达。渲染命令(`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 必须严格小于原始大小,空 data block 也是非法的。
- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小。

### 版本编码与兼容性

Expand Down
4 changes: 4 additions & 0 deletions src/core/block_store.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<size_t>(meta_end - meta_ptr) < sizeof(uint64_t))
{
return error_corruption("corrupt archive '{}': missing data block count", pack_file_path);
Expand Down
123 changes: 120 additions & 3 deletions src/core/file_format.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#include <sys/stat.h>
#include <system_error>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>

#include "file_format.h"
#include "src/utils/coding.h"
Expand Down Expand Up @@ -482,6 +484,92 @@ 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<entry_id_t, entry_id_t> 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 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<entry_id_t> visited;
visited.reserve(meta.dir_entry_records.size());
std::vector<entry_id_t> queue;
queue.reserve(meta.dir_entry_records.size());
queue.push_back(kRootDirId);
visited.insert(kRootDirId);
for (size_t head = 0; head < queue.size(); ++head)
{
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())
{
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.push_back(child_id);
}
}
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);
Expand Down Expand Up @@ -1168,9 +1256,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<entry_id_t> 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<entry_id_t>& 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<entry_id_t>& 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)
{
Expand Down Expand Up @@ -1234,8 +1350,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;
}
Expand Down Expand Up @@ -1277,7 +1393,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;
}
Expand Down
20 changes: 20 additions & 0 deletions src/core/file_format.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <string_view>
#include <sys/stat.h>
#include <unordered_map>
#include <unordered_set>

#include "options.h"
#include "sorted_map.h"
Expand Down Expand Up @@ -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<entry_id_t>& 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
6 changes: 6 additions & 0 deletions src/core/options.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ namespace ctar
// --max-metadata-size (0 disables the limit).
constexpr uint64_t kDefaultMaxMetadataSize = 1ULL * unit::GiB;

// 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
// size after a task, instead of being held until the process exits.
constexpr size_t kMaxRetainedBufferBytes = 128UL * unit::MiB;
Expand Down
Loading
Loading