xfs/dir.rs
1//! Directory parsing — short-form, block, leaf/node, and btree directories.
2//!
3//! This module turns every XFS directory format into a flat `Vec<DirEntry>` and
4//! composes them into the real forensic entrypoint, [`read_by_path`]:
5//! short-form (P4), single-block (P4), and — added in P5 — the multi-block
6//! leaf/node directories (walk the `XDD3`/`XD2D` DATA blocks) and btree-format
7//! directories (collect the dir-block map from a bmap B+tree, then walk its data
8//! blocks). A directory whose data-fork format is not a real directory layout
9//! (`Dev`/`Other`) fails LOUD with [`XfsError::UnsupportedDir`] naming the
10//! format, never a silent empty listing.
11//!
12//! ## The two formats
13//!
14//! **Short-form** ([`crate::InodeFormat::Local`] on a directory inode) — packed
15//! inline in the inode data fork (`xfs_dir2_sf_hdr` + entries). Layout, verbatim
16//! from `fs/xfs/libxfs/xfs_format.h` and confirmed against raw `xfs_db` byte
17//! dumps of the minted images:
18//!
19//! ```text
20//! count : u8 number of entries
21//! i8count : u8 entries needing a 64-bit inode number
22//! parent : u32|u64 (BE) parent inode (4 bytes if i8count==0 else 8)
23//! per entry:
24//! namelen : u8
25//! offset : u16 (BE) dir2 data offset — not needed for listing
26//! name : [u8; namelen]
27//! ftype : u8 ONLY when the fs ftype feature is on (see below)
28//! inumber : u32|u64 (BE) 4 bytes if i8count==0 else 8
29//! ```
30//!
31//! `.`/`..` are implicit in short-form (`.` = the dir's own inode, `..` = the
32//! header `parent`); the entry list holds only the named children.
33//!
34//! **Block directory** ([`crate::InodeFormat::Extents`] with `size == blocksize`,
35//! i.e. a single directory block). The block opens with a data-block header
36//! (`xfs_dir3_data_hdr` on v5, magic **`XDB3`**; `xfs_dir2_data_hdr` on v4, magic
37//! **`XD2B`**), followed by `xfs_dir2_data_entry` records interleaved with
38//! `xfs_dir2_data_unused` free records (freetag `0xFFFF` — skipped), and a
39//! leaf/hash array + `xfs_dir2_block_tail` at the block tail. Each data entry is:
40//!
41//! ```text
42//! inumber : u64 (BE)
43//! namelen : u8
44//! name : [u8; namelen]
45//! ftype : u8 ONLY when the fs ftype feature is on
46//! tag : u16 (BE) back-pointer; ignored for listing
47//! (padded up to an 8-byte boundary)
48//! ```
49//!
50//! The data-entry region ends where the leaf array begins, computed structurally
51//! from the block tail: `leaf_start = blocksize - 8 - count*8`.
52//!
53//! ## The ftype byte is a FEATURE bit, not a version bit
54//!
55//! Both formats carry a trailing `ftype` byte per entry **iff the filesystem's
56//! ftype feature is enabled** ([`Superblock::has_ftype`]). Modern `mkfs.xfs`
57//! enables it by default even on v4, so this reader branches on the feature bit,
58//! never on the v4/v5 version — the classic off-by-one this module guards.
59
60use crate::btree::read_btree_extents;
61use crate::bytes::{be_u16, be_u32, be_u64, u8_at};
62use crate::crc::{verify_crc, DA3_BLKINFO_CRC_OFF, DIR3_DATA_CRC_OFF};
63use crate::error::XfsError;
64use crate::extent::{read_extents, BmbtRec};
65use crate::inode::{Inode, InodeFormat};
66use crate::superblock::Superblock;
67
68/// The v5 single-block directory data-block magic (`XFS_DIR3_BLOCK_MAGIC`,
69/// `"XDB3"`).
70pub const XFS_DIR3_BLOCK_MAGIC: u32 = 0x5844_4233;
71/// The v4 single-block directory data-block magic (`XFS_DIR2_BLOCK_MAGIC`,
72/// `"XD2B"`).
73pub const XFS_DIR2_BLOCK_MAGIC: u32 = 0x5844_3242;
74/// The v5 multi-block directory data-block magic (`XFS_DIR3_DATA_MAGIC`,
75/// `"XDD3"`). A leaf/node directory's DATA blocks carry this (distinct from the
76/// single-block `XDB3`) and, unlike a single block, have NO block tail.
77pub const XFS_DIR3_DATA_MAGIC: u32 = 0x5844_4433;
78/// The v4 multi-block directory data-block magic (`XFS_DIR2_DATA_MAGIC`,
79/// `"XD2D"`).
80pub const XFS_DIR2_DATA_MAGIC: u32 = 0x5844_3244;
81
82/// v5 dir single-block leaf magic (`XFS_DIR3_LEAF1_MAGIC`) — the 16-bit
83/// `xfs_da_blkinfo.magic` at block offset 8 of a v5 leaf/node block.
84const XFS_DIR3_LEAF1_MAGIC: u16 = 0x3df1;
85/// v5 dir multi-block leaf magic (`XFS_DIR3_LEAFN_MAGIC`).
86const XFS_DIR3_LEAFN_MAGIC: u16 = 0x3dff;
87/// v5 da-btree node magic (`XFS_DA3_NODE_MAGIC`). (The v4 leaf/node magics
88/// `XFS_DIR2_LEAF1_MAGIC` 0xd2f1 / `XFS_DIR2_LEAFN_MAGIC` 0xd2ff /
89/// `XFS_DA_NODE_MAGIC` 0xfebe carry no CRC and need no constant — they fall
90/// through to the `None` arm alongside every unrecognized block.)
91const XFS_DA3_NODE_MAGIC: u16 = 0x3ebe;
92
93/// The `xfs_dir3_data_hdr` (v5) header length preceding the first data entry.
94const DIR3_DATA_HDR_LEN: usize = 64;
95/// The `xfs_dir2_data_hdr` (v4) header length preceding the first data entry.
96const DIR2_DATA_HDR_LEN: usize = 16;
97
98/// The directory-block byte offset at which the leaf/hash address space begins
99/// (`XFS_DIR2_LEAF_OFFSET = 1 << (32 + XFS_DIR2_DATA_ALIGN_LOG=3) = 1 << 35`).
100/// A directory's DATA blocks live in the byte range `[0, this)`; leaf and
101/// freeindex blocks live at or above it, so an extent whose logical (directory)
102/// byte offset is below this boundary holds file entries, and one at/above it
103/// is a hash/index block skipped when listing.
104const XFS_DIR2_LEAF_OFFSET: u64 = 1 << 35;
105/// The `xfs_dir2_block_tail` size (`count: u32`, `stale: u32`) at the block end.
106const BLOCK_TAIL_LEN: usize = 8;
107/// Each `xfs_dir2_leaf_entry` in the block tail's leaf array is 8 bytes.
108const LEAF_ENTRY_LEN: usize = 8;
109/// The `xfs_dir2_data_unused` freetag marking a free (deleted/hole) record.
110const DATA_FREE_TAG: u16 = 0xffff;
111
112/// A single directory entry: a name, the inode it points at, and — when the
113/// filesystem's ftype feature is on — the on-disk file-type byte.
114///
115/// `.` and `..` are not surfaced for short-form directories (they are implicit);
116/// a block directory carries them explicitly and they appear verbatim.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct DirEntry {
119 /// The entry name, raw bytes (XFS names are not guaranteed UTF-8).
120 pub name: Vec<u8>,
121 /// The inode number this entry points at.
122 pub inode: u64,
123 /// The on-disk `ftype` byte, or `None` when the filesystem has no ftype
124 /// feature (a no-ftype short-form/block directory omits the byte entirely).
125 pub ftype: Option<u8>,
126}
127
128/// Round `n` up to the next multiple of 8 (XFS directory entries are 8-byte
129/// aligned). Saturating so a hostile length can never overflow.
130#[inline]
131const fn align8(n: usize) -> usize {
132 n.saturating_add(7) & !7
133}
134
135/// Parse a short-form directory from its inode data fork.
136///
137/// `has_ftype` selects whether each entry carries a trailing `ftype` byte (see
138/// the module docs — it tracks the fs feature bit, not the version). Bounds-
139/// stopping: a truncated fork yields only the entries that fully fit, never an
140/// over-read or panic.
141#[must_use]
142pub fn read_shortform_dir(fork: &[u8], has_ftype: bool) -> Vec<DirEntry> {
143 let count = usize::from(u8_at(fork, 0));
144 let i8count = u8_at(fork, 1);
145 // i8count==0 -> 4-byte inode numbers (incl. parent); else 8-byte.
146 let inum_width = if i8count == 0 { 4 } else { 8 };
147
148 // Header: count(1) + i8count(1) + parent(inum_width). Parent is `..`, not a
149 // listed child, so we skip it and start the entry cursor after it.
150 let mut off = 2 + inum_width;
151
152 let mut entries = Vec::with_capacity(count);
153 for _ in 0..count {
154 // namelen(1) + offset(2) then the name.
155 let namelen = usize::from(u8_at(fork, off));
156 let name_start = off + 3;
157 let name_end = name_start + namelen;
158 let Some(name) = fork.get(name_start..name_end) else {
159 break; // fork ends inside this entry -> stop (bounds-stopping)
160 };
161
162 // Optional ftype byte, then the inode number.
163 let ftype_off = name_end;
164 let (ftype, inum_off) = if has_ftype {
165 (Some(u8_at(fork, ftype_off)), ftype_off + 1)
166 } else {
167 (None, ftype_off)
168 };
169
170 let inum_end = inum_off + inum_width;
171 let Some(inum_bytes) = fork.get(inum_off..inum_end) else {
172 break; // no room for the inode number -> stop
173 };
174 let inode = read_inum(inum_bytes);
175
176 entries.push(DirEntry {
177 name: name.to_vec(),
178 inode,
179 ftype,
180 });
181 off = inum_end;
182 }
183 entries
184}
185
186/// Read a big-endian directory inode number from a 4- or 8-byte slice.
187#[inline]
188fn read_inum(bytes: &[u8]) -> u64 {
189 match bytes.len() {
190 4 => u64::from(be_u32(bytes, 0)),
191 _ => be_u64(bytes, 0),
192 }
193}
194
195/// Parse a single-block (block-format) directory from its raw data-block bytes.
196///
197/// `has_ftype` selects the per-entry ftype byte. Walks `xfs_dir2_data_entry`
198/// records from the header end up to the leaf array (bounded structurally by the
199/// block tail), skipping `xfs_dir2_data_unused` (freetag `0xFFFF`) records.
200///
201/// # Errors
202///
203/// [`XfsError::UnsupportedDir`] if the block magic is neither `XDB3` (v5) nor
204/// `XD2B` (v4) — the offending magic bytes are named in the error.
205pub fn read_block_dir(block: &[u8], has_ftype: bool) -> Result<Vec<DirEntry>, XfsError> {
206 let magic = be_u32(block, 0);
207 let hdr_len = match magic {
208 XFS_DIR3_BLOCK_MAGIC => DIR3_DATA_HDR_LEN,
209 XFS_DIR2_BLOCK_MAGIC => DIR2_DATA_HDR_LEN,
210 other => {
211 return Err(XfsError::UnsupportedDir {
212 detail: format!(
213 "block directory: unrecognized data-block magic {other:#010x} \
214 (bytes {:02x?}), expected XDB3 (0x58444233) or XD2B (0x58443242)",
215 &block.get(0..4).unwrap_or(&[])
216 ),
217 });
218 }
219 };
220
221 // The block tail (`count: u32, stale: u32`) is the last 8 bytes; the leaf
222 // array of `count` 8-byte entries sits immediately before it. Data entries
223 // occupy `[hdr_len .. leaf_start)`. Deriving the stop structurally (not from
224 // bestfree) means a lying/free record can't run the walk into the leaf area.
225 let blocksize = block.len();
226 let leaf_start = if blocksize >= BLOCK_TAIL_LEN {
227 let count = usize::try_from(be_u32(block, blocksize - BLOCK_TAIL_LEN)).unwrap_or(0);
228 let leaf_bytes = count.saturating_mul(LEAF_ENTRY_LEN);
229 blocksize
230 .saturating_sub(BLOCK_TAIL_LEN)
231 .saturating_sub(leaf_bytes)
232 } else {
233 0
234 };
235 // A malformed count could push leaf_start below hdr_len; clamp so the walk
236 // range is never inverted (yielding an empty listing, not a panic).
237 let region_end = leaf_start.max(hdr_len).min(blocksize);
238
239 Ok(walk_data_entries(block, hdr_len, region_end, has_ftype))
240}
241
242/// Parse a MULTI-block directory data block (`XDD3` v5 / `XD2D` v4) from its raw
243/// bytes.
244///
245/// Unlike a single block, a multi-block data block has **no block tail** — the
246/// leaf/hash index lives in separate blocks (above the crate-private
247/// `XFS_DIR2_LEAF_OFFSET`), so the data entries run from the header end to the
248/// end of the block. The entry records are identical to the single-block format
249/// (`xfs_dir2_data_entry`), so the same crate-private `walk_data_entries` walker
250/// is reused with the region end set to the full block length.
251///
252/// `has_ftype` selects the per-entry ftype byte. Bounds-stopping and panic-free.
253///
254/// # Errors
255///
256/// [`XfsError::UnsupportedDir`] if the magic is neither `XDD3` (v5) nor `XD2D`
257/// (v4) — the offending magic bytes are named in the error. (The single-block
258/// magics `XDB3`/`XD2B` are handled by [`read_block_dir`], not here.)
259pub fn read_data_dir_block(block: &[u8], has_ftype: bool) -> Result<Vec<DirEntry>, XfsError> {
260 let magic = be_u32(block, 0);
261 let hdr_len = match magic {
262 XFS_DIR3_DATA_MAGIC => DIR3_DATA_HDR_LEN,
263 XFS_DIR2_DATA_MAGIC => DIR2_DATA_HDR_LEN,
264 other => {
265 return Err(XfsError::UnsupportedDir {
266 detail: format!(
267 "leaf/node directory data block: unrecognized data-block magic \
268 {other:#010x} (bytes {:02x?}), expected XDD3 (0x58444433) or \
269 XD2D (0x58443244)",
270 &block.get(0..4).unwrap_or(&[])
271 ),
272 });
273 }
274 };
275 // No block tail: entries fill `[hdr_len .. blocksize)`. A block shorter than
276 // the header yields an empty walk (start > end), never a panic.
277 Ok(walk_data_entries(block, hdr_len, block.len(), has_ftype))
278}
279
280/// Verify the v5 CRC32c of a directory `block` (data, single-block, leaf, node,
281/// or freeindex), returning `Some(true/false)` on a v5 block and `None` on a v4
282/// block (which carries no CRC).
283///
284/// The CRC field position depends on the block's header kind, detected from its
285/// magic (all VERBATIM from `xfs_da_format.h`):
286///
287/// - **data / single-block** blocks (`xfs_dir3_blk_hdr`) carry a 32-bit magic at
288/// offset 0 — `XDB3`/`XDD3` (v5) → CRC at offset 4; `XD2B`/`XD2D` (v4) → `None`.
289/// - **leaf / node / freeindex** blocks (`xfs_da3_blkinfo`) carry a 16-bit magic
290/// at offset 8 — `0x3df1`/`0x3dff`/`0x3ebe` (v5) → CRC at offset 12; the v4
291/// magics (`0xd2f1`/`0xd2ff`/`0xfebe`) → `None`.
292///
293/// A block whose magic matches none of these is not a directory block this
294/// reader recognizes, so it returns `None` (no CRC claim — never a false
295/// mismatch). **Non-fatal and panic-free**: a short/hostile block that claims a
296/// v5 magic but cannot hold the CRC field verifies as `Some(false)`.
297#[must_use]
298pub fn verify_dir_block_crc(block: &[u8]) -> Option<bool> {
299 // Data / single-block header: 32-bit magic at offset 0.
300 match be_u32(block, 0) {
301 XFS_DIR3_BLOCK_MAGIC | XFS_DIR3_DATA_MAGIC => {
302 return Some(verify_crc(block, DIR3_DATA_CRC_OFF));
303 }
304 XFS_DIR2_BLOCK_MAGIC | XFS_DIR2_DATA_MAGIC => return None,
305 _ => {}
306 }
307 // Leaf / node / freeindex header (`xfs_da_blkinfo`): 16-bit magic at offset 8.
308 // v5 magics carry a CRC at offset 12; the v4 leaf/node magics
309 // (0xd2f1 / 0xd2ff / 0xfebe) have none, and neither does any unrecognized
310 // block — all fall through to `None` (no CRC claim, never a false mismatch).
311 match be_u16(block, 8) {
312 XFS_DIR3_LEAF1_MAGIC | XFS_DIR3_LEAFN_MAGIC | XFS_DA3_NODE_MAGIC => {
313 Some(verify_crc(block, DA3_BLKINFO_CRC_OFF))
314 }
315 _ => None,
316 }
317}
318
319/// Walk `xfs_dir2_data_entry` records in `[start .. end)` of a directory data
320/// block, skipping `xfs_dir2_data_unused` (freetag `0xFFFF`) records.
321///
322/// Shared by the single-block ([`read_block_dir`], `end` = the tail's leaf
323/// boundary) and multi-block ([`read_data_dir_block`], `end` = block length)
324/// data-block readers — the entry layout is identical; only the stop boundary
325/// differs. Bounds-stopping: an entry running past `end`/the block, or a zero
326/// namelen (zero padding), ends the walk. `align8` guarantees forward progress.
327fn walk_data_entries(block: &[u8], start: usize, end: usize, has_ftype: bool) -> Vec<DirEntry> {
328 let mut entries = Vec::new();
329 let mut off = start;
330 while off + 3 <= end {
331 // A data-unused record starts with the freetag 0xFFFF in the first two
332 // bytes (the inumber's high half can never be 0xFFFF for a real entry).
333 if be_u16(block, off) == DATA_FREE_TAG {
334 let free_len = usize::from(be_u16(block, off + 2));
335 // A zero/insane free length would stall or run backwards: enforce
336 // forward progress of at least 8 bytes (the minimum record grain).
337 off = off.saturating_add(free_len.max(align8(1)));
338 continue;
339 }
340
341 // A real data entry: inumber(8) namelen(1) name[] [ftype(1)] tag(2).
342 let inode = be_u64(block, off);
343 let namelen = usize::from(u8_at(block, off + 8));
344 // A dirent always has a non-empty name; a zero namelen means we have run
345 // off the end of the real entries into zero padding (or a malformed
346 // record). Stop rather than fabricate phantom empty-name entries.
347 if namelen == 0 {
348 break;
349 }
350 let name_start = off + 9;
351 let name_end = name_start + namelen;
352 let Some(name) = block.get(name_start..name_end) else {
353 break; // entry runs past the block -> stop (bounds-stopping)
354 };
355 let ftype = if has_ftype {
356 Some(u8_at(block, name_end))
357 } else {
358 None
359 };
360 entries.push(DirEntry {
361 name: name.to_vec(),
362 inode,
363 ftype,
364 });
365
366 // Advance past this record: inumber(8)+namelen(1)+name+ftype?+tag(2),
367 // aligned up to 8. `align8` guarantees forward progress.
368 let ftype_len = usize::from(has_ftype);
369 let raw = 8 + 1 + namelen + ftype_len + 2;
370 off = off.saturating_add(align8(raw));
371 }
372 entries
373}
374
375impl Superblock {
376 /// List a directory inode's entries, dispatching on its on-disk format.
377 ///
378 /// Handles every directory format XFS uses:
379 /// - **short-form** ([`InodeFormat::Local`]) — parsed from the inode's inline
380 /// data fork;
381 /// - **block** ([`InodeFormat::Extents`] with `size == blocksize`) — the
382 /// single directory block (`XDB3`/`XD2B`) read via the inode's one extent;
383 /// - **leaf / node** ([`InodeFormat::Extents`] with `size > blocksize`) —
384 /// the multiple `XDD3`/`XD2D` DATA blocks are walked and concatenated; the
385 /// leaf/hash + freeindex index blocks (above the `XFS_DIR2_LEAF_OFFSET`
386 /// address-space boundary) are skipped, since listing needs only the data;
387 /// - **btree** ([`InodeFormat::Btree`]) — the dir-block map itself is a bmap
388 /// B+tree; its extents are collected ([`read_btree_extents`]) and the data
389 /// blocks walked exactly as the leaf/node case.
390 ///
391 /// # Errors
392 ///
393 /// - [`XfsError::UnsupportedDir`] — a directory inode whose data-fork format
394 /// is `Dev`/`Other` (not a real directory layout), or a block whose magic
395 /// is unrecognized. The error NAMES the format/value (fail loud).
396 /// - [`XfsError::Truncated`] — the single directory block extent lies outside
397 /// the image (propagated from the file read).
398 pub fn read_dir(&self, image: &[u8], inode: &Inode) -> Result<Vec<DirEntry>, XfsError> {
399 match inode.format {
400 InodeFormat::Local => Ok(read_shortform_dir(&inode.data_fork, self.has_ftype())),
401 InodeFormat::Extents => {
402 let blocksize = u64::from(self.blocksize);
403 if inode.size == blocksize {
404 // Single-block (block) directory: read the one extent and
405 // walk the data block. read_file gives exactly `size` bytes.
406 let block = self.read_file(image, inode)?;
407 read_block_dir(&block, self.has_ftype())
408 } else {
409 // Multi-block (leaf / node) directory: the data entries are
410 // spread across the DATA blocks (logical dir offset below
411 // XFS_DIR2_LEAF_OFFSET); the leaf/hash + freeindex blocks
412 // (above the boundary) are a lookup index, not needed to
413 // list. Decode the inline extent map and walk the data
414 // blocks. `size == 0` is not a valid directory (every dir
415 // has at least `.`/`..`), so it falls through to an empty
416 // listing here rather than a crash.
417 let recs = read_extents(&inode.data_fork, inode.nextents);
418 Ok(self.read_multiblock_dir(image, &recs))
419 }
420 }
421 InodeFormat::Btree => {
422 // A directory large enough that its dir-block map itself needs a
423 // bmap B+tree: walk the tree (P5 Part 1) for the extent map, then
424 // walk its data blocks exactly as the leaf/node case.
425 let recs = read_btree_extents(image, self, &inode.data_fork)?;
426 Ok(self.read_multiblock_dir(image, &recs))
427 }
428 other => Err(XfsError::UnsupportedDir {
429 detail: format!("directory format {other:?} not yet supported (dev/other)"),
430 }),
431 }
432 }
433
434 /// Walk the DATA blocks of a leaf/node/btree directory given its extent map,
435 /// concatenating every data-block's entries in extent (`startoff`) order.
436 ///
437 /// Only extents whose logical directory byte offset lies below
438 /// [`XFS_DIR2_LEAF_OFFSET`] hold file entries; extents at/above it are the
439 /// leaf/hash and freeindex index blocks, which are skipped when listing.
440 /// Each data extent covers `blockcount` directory blocks (one per filesystem
441 /// block here); each block is read and walked with [`read_data_dir_block`].
442 /// A block whose magic is not a multi-block DATA magic is skipped (an index
443 /// block that happened to fall below the boundary, or slack) rather than
444 /// failing the whole listing — so this collection is infallible (an
445 /// out-of-image or wrong-magic block contributes nothing).
446 fn read_multiblock_dir(&self, image: &[u8], recs: &[BmbtRec]) -> Vec<DirEntry> {
447 let blocksize = self.blocksize as usize;
448 let has_ftype = self.has_ftype();
449 // Logical dir-block boundary: data blocks have startoff below this.
450 let leaf_boundary_block = XFS_DIR2_LEAF_OFFSET / u64::from(self.blocksize).max(1);
451
452 let mut entries = Vec::new();
453 for rec in recs {
454 // Skip leaf/hash/freeindex extents (logical offset at/above the
455 // boundary): they hold no file entries.
456 if rec.startoff >= leaf_boundary_block {
457 continue;
458 }
459 // Each block of this data extent is a directory data block.
460 for b in 0..rec.blockcount {
461 let fsblock = rec.startblock.saturating_add(b);
462 let Some(start) = (fsblock as usize).checked_mul(blocksize) else {
463 continue; // cov:unreachable: fsblock*blocksize fits usize on 64-bit
464 };
465 let Some(block) = image.get(start..start.saturating_add(blocksize)) else {
466 continue; // block outside image (corrupt/truncated) — skip
467 };
468 // A DATA block carries a multi-block DATA magic; anything else
469 // (an index block below the boundary, or slack) contributes no
470 // entries.
471 if let Ok(mut es) = read_data_dir_block(block, has_ftype) {
472 entries.append(&mut es);
473 }
474 }
475 }
476 entries
477 }
478}
479
480/// List a directory inode's entries (free-function form of
481/// [`Superblock::read_dir`]).
482///
483/// # Errors
484///
485/// See [`Superblock::read_dir`].
486pub fn read_dir(image: &[u8], sb: &Superblock, inode: &Inode) -> Result<Vec<DirEntry>, XfsError> {
487 sb.read_dir(image, inode)
488}
489
490/// Read a file by its absolute path, navigating the directory tree from the root.
491///
492/// The capstone entrypoint: starting at [`Superblock::rootino`], split `path` on
493/// `/`, and for each component [`Superblock::read_dir`] the current directory and
494/// name-match to descend to the component's inode; the final inode's bytes are
495/// reconstructed with [`Superblock::read_file`]. This composes P1 (inode-number
496/// decode) + P2 (inode core) + P3 (extent-list read) + P4 (directory listing)
497/// into the real read-file-by-path forensic operation.
498///
499/// # Errors
500///
501/// - [`XfsError::PathNotFound`] — a component was not found in its parent, or a
502/// non-final component was not a directory.
503/// - [`XfsError::UnsupportedDir`] — a directory along the path uses a format not
504/// yet handled (fail loud, never a silent miss).
505/// - Any error from [`Superblock::read_inode`] / [`Superblock::read_file`].
506pub fn read_by_path(image: &[u8], sb: &Superblock, path: &str) -> Result<Vec<u8>, XfsError> {
507 let components: Vec<&str> = path.split('/').filter(|c| !c.is_empty()).collect();
508
509 let mut current = sb.read_inode(image, sb.rootino)?;
510 for (idx, comp) in components.iter().enumerate() {
511 // The current inode must be a directory to descend into it.
512 let entries = sb.read_dir(image, ¤t)?;
513 let Some(entry) = entries.iter().find(|e| e.name == comp.as_bytes()) else {
514 return Err(XfsError::PathNotFound {
515 path: path.to_string(),
516 component: (*comp).to_string(),
517 });
518 };
519 let next = sb.read_inode(image, entry.inode)?;
520
521 let is_last = idx + 1 == components.len();
522 if is_last {
523 return sb.read_file(image, &next);
524 }
525 // A non-final component must itself be a directory to continue.
526 if !next.is_dir() {
527 return Err(XfsError::PathNotFound {
528 path: path.to_string(),
529 component: (*comp).to_string(),
530 });
531 }
532 current = next;
533 }
534
535 // An empty path (no components) resolves to the root, which is a directory,
536 // not a file — read_file on it would be meaningless. Report it as not found.
537 Err(XfsError::PathNotFound {
538 path: path.to_string(),
539 component: String::new(),
540 })
541}