Skip to main content

btrfs_core/
fstree.rs

1//! P2 root-tree navigation + FS-tree inode / directory / path resolution.
2//!
3//! The superblock's `root` logical address names the **`ROOT_TREE`**, which holds
4//! a `ROOT_ITEM` (key type [`ROOT_ITEM_KEY`]) per tree; the one keyed by
5//! objectid [`FS_TREE_OBJECTID`] (5) carries the `FS_TREE`'s own root `bytenr`
6//! (logical) and `level`. The `FS_TREE` then holds, per inode, an `INODE_ITEM`
7//! ([`INODE_ITEM_KEY`], the metadata), `INODE_REF`s ([`INODE_REF_KEY`],
8//! name↔parent links), and `DIR_ITEM`/`DIR_INDEX` entries ([`DIR_ITEM_KEY`] /
9//! [`DIR_INDEX_KEY`], directory children).
10//!
11//! Struct layouts (`btrfs_root_item`, `btrfs_inode_item`, `btrfs_timespec`,
12//! `btrfs_inode_ref`, `btrfs_dir_item`) were transcribed from the on-disk ABI
13//! and **verified byte-for-byte against `btrfs inspect-internal dump-tree`**
14//! plus an independent mount-ro `stat` on the minted oracle (see
15//! `tests/data/README.md`, "P2 ground truth").
16//!
17//! # Scope
18//!
19//! P2 navigates within the `FS_TREE` **leaf** the oracle presents (a single
20//! `nodesize` node). The public `read_inode` / `list_dir` / `read_by_path`
21//! entry points take a parsed [`Node`] so they work on the committed fixture and
22//! on any `FS_TREE` leaf read via `read_node`. Multi-leaf FS trees (interior
23//! descent within the FS tree) arrive with a later phase; here every inode /
24//! directory of the oracle lives in one leaf, matching dump-tree.
25//!
26//! # Safety
27//!
28//! This parses untrusted, attacker-controllable images. Every field is read
29//! through the bounds-checked [`crate::bytes`] helpers, and every `name_len` /
30//! `data_len` is clamped to the item data actually present, so a lying length
31//! yields a truncated name rather than an over-read or panic (the Paranoid
32//! Gatekeeper standard).
33
34use crate::bytes::{le_u16, le_u32, le_u64, u8_at};
35use crate::error::BtrfsError;
36use crate::node::{read_node, ChunkMap, Node};
37use crate::superblock::Superblock;
38
39/// `BTRFS_FS_TREE_OBJECTID` — the default subvolume / FS tree objectid (5).
40pub const FS_TREE_OBJECTID: u64 = 5;
41
42/// `BTRFS_FIRST_FREE_OBJECTID` — the `FS_TREE`'s root directory inode (256); the
43/// first normal (non-reserved) objectid, where path resolution begins.
44pub const FS_TREE_ROOT_DIR_OBJECTID: u64 = 256;
45
46/// `BTRFS_INODE_ITEM_KEY` — a `btrfs_inode_item` (inode metadata).
47pub const INODE_ITEM_KEY: u8 = 1;
48
49/// `BTRFS_INODE_REF_KEY` — a `btrfs_inode_ref` (name + parent-dir link).
50pub const INODE_REF_KEY: u8 = 12;
51
52/// `BTRFS_XATTR_ITEM_KEY` — an extended attribute.
53///
54/// The item body is a `btrfs_dir_item`, the very structure a directory entry
55/// uses: the same 30-byte prefix, the name, and then `data_len` bytes of value.
56/// Btrfs stores the FULL attribute name (`security.selinux`), unlike ext4 and
57/// XFS which store a bare name beside a namespace tag.
58pub const XATTR_ITEM_KEY: u8 = 24;
59
60/// `BTRFS_DIR_ITEM_KEY` — a `btrfs_dir_item` keyed by name hash.
61pub const DIR_ITEM_KEY: u8 = 84;
62
63/// `BTRFS_DIR_INDEX_KEY` — a `btrfs_dir_item` keyed by sequential index.
64pub const DIR_INDEX_KEY: u8 = 96;
65
66/// `BTRFS_ROOT_ITEM_KEY` — a `btrfs_root_item` in the root tree (132).
67pub const ROOT_ITEM_KEY: u8 = 132;
68
69/// `sizeof(btrfs_inode_item)` on disk = 160 bytes: the scalar block (up to
70/// `reserved[4]` = 112 bytes) + four 12-byte [`Timestamp`]s.
71pub const INODE_ITEM_SIZE: usize = 160;
72
73/// `sizeof(btrfs_timespec)` on disk: `sec(u64) + nsec(u32)` = 12 bytes.
74pub const TIMESTAMP_SIZE: usize = 12;
75
76/// The `btrfs_inode_item.size` (logical file size) field offset — exposed so the
77/// `EXTENT_DATA` reader can truncate assembled content to the inode's size without
78/// re-decoding the whole inode.
79pub(crate) const INODE_SIZE_OFFSET: usize = 16;
80
81// `btrfs_inode_item` field offsets (verified vs dump-tree + stat).
82mod inode_off {
83    pub const GENERATION: usize = 0;
84    pub const TRANSID: usize = 8;
85    pub const SIZE: usize = 16;
86    pub const NBYTES: usize = 24;
87    pub const NLINK: usize = 40;
88    pub const UID: usize = 44;
89    pub const GID: usize = 48;
90    pub const MODE: usize = 52;
91    pub const FLAGS: usize = 64;
92    // The four timestamps begin after the 112-byte scalar block.
93    pub const ATIME: usize = 112;
94    pub const CTIME: usize = 124;
95    pub const MTIME: usize = 136;
96    pub const OTIME: usize = 148;
97}
98
99// `btrfs_root_item` field offsets (the leading 160 bytes are an embedded
100// `btrfs_inode_item`, so the root-item scalars start at 160).
101mod root_off {
102    pub const GENERATION: usize = 160;
103    pub const ROOT_DIRID: usize = 168;
104    pub const BYTENR: usize = 176;
105    pub const LEVEL: usize = 238;
106}
107
108// `btrfs_dir_item` field offsets: a 17-byte location key, then `transid(u64)`,
109// `data_len(u16)@25`, `name_len(u16)@27`, `type(u8)@29`, `name[]@30`.
110mod dir_off {
111    /// `data_len` — value length, meaningful for an `XATTR_ITEM` and zero for a
112    /// plain directory entry.
113    pub const DATA_LEN: usize = 25;
114    pub const NAME_LEN: usize = 27;
115    pub const TYPE: usize = 29;
116    pub const NAME: usize = 30;
117}
118
119/// A `btrfs_timespec`: seconds since the Unix epoch + nanoseconds.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121pub struct Timestamp {
122    /// `sec` — signed seconds since 1970-01-01 (stored as `u64` on disk; btrfs
123    /// timestamps are post-epoch on real images).
124    pub sec: u64,
125    /// `nsec` — the nanosecond fraction (`0..1_000_000_000`).
126    pub nsec: u32,
127}
128
129impl Timestamp {
130    /// Decode a 12-byte `btrfs_timespec` at `off` within `data`
131    /// (bounds-checked; out-of-range fields read as 0).
132    #[must_use]
133    fn parse(data: &[u8], off: usize) -> Self {
134        Timestamp {
135            sec: le_u64(data, off),
136            nsec: le_u32(data, off + 8),
137        }
138    }
139}
140
141/// A decoded `btrfs_inode_item`: file/dir metadata + the four timestamps.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143#[non_exhaustive]
144pub struct Inode {
145    /// The inode's own objectid (the `FS_TREE` key objectid it was found under).
146    pub objectid: u64,
147    /// `generation` — the transaction id that created the inode.
148    pub generation: u64,
149    /// `transid` — the transaction id of the last metadata change.
150    pub transid: u64,
151    /// `size` — the logical file size in bytes (directory entry-name bytes for a
152    /// directory).
153    pub size: u64,
154    /// `nbytes` — bytes actually allocated on disk (0 for a hole-only / empty).
155    pub nbytes: u64,
156    /// `nlink` — the hard-link count.
157    pub nlink: u32,
158    /// `uid` — owner user id.
159    pub uid: u32,
160    /// `gid` — owner group id.
161    pub gid: u32,
162    /// `mode` — the POSIX mode bits, including the file-type bits (e.g.
163    /// `0o100644` for a regular file, `0o40755` for a directory).
164    pub mode: u32,
165    /// `flags` — the `BTRFS_INODE_*` flag bits.
166    pub flags: u64,
167    /// `atime` — last access time.
168    pub atime: Timestamp,
169    /// `ctime` — last status-change (inode) time.
170    pub ctime: Timestamp,
171    /// `mtime` — last data-modification time.
172    pub mtime: Timestamp,
173    /// `otime` — creation (birth) time.
174    pub otime: Timestamp,
175}
176
177/// The POSIX file-type mask (`S_IFMT`): the high bits of `mode` selecting the
178/// object kind.
179const S_IFMT: u32 = 0o170_000;
180/// `S_IFDIR` — the mode bits marking a directory.
181const S_IFDIR: u32 = 0o40_000;
182/// `S_IFREG` — the mode bits marking a regular file.
183const S_IFREG: u32 = 0o100_000;
184
185impl Inode {
186    /// Decode a `btrfs_inode_item` (`data`) for objectid `objectid`. All four
187    /// timestamps are decoded; out-of-range fields read as 0 (bounds-checked).
188    #[must_use]
189    fn parse(objectid: u64, data: &[u8]) -> Self {
190        Inode {
191            objectid,
192            generation: le_u64(data, inode_off::GENERATION),
193            transid: le_u64(data, inode_off::TRANSID),
194            size: le_u64(data, inode_off::SIZE),
195            nbytes: le_u64(data, inode_off::NBYTES),
196            nlink: le_u32(data, inode_off::NLINK),
197            uid: le_u32(data, inode_off::UID),
198            gid: le_u32(data, inode_off::GID),
199            mode: le_u32(data, inode_off::MODE),
200            flags: le_u64(data, inode_off::FLAGS),
201            atime: Timestamp::parse(data, inode_off::ATIME),
202            ctime: Timestamp::parse(data, inode_off::CTIME),
203            mtime: Timestamp::parse(data, inode_off::MTIME),
204            otime: Timestamp::parse(data, inode_off::OTIME),
205        }
206    }
207
208    /// `true` if the mode's type bits mark a directory.
209    #[must_use]
210    pub fn is_dir(&self) -> bool {
211        self.mode & S_IFMT == S_IFDIR
212    }
213
214    /// `true` if the mode's type bits mark a regular file.
215    #[must_use]
216    pub fn is_file(&self) -> bool {
217        self.mode & S_IFMT == S_IFREG
218    }
219}
220
221/// The `btrfs_dir_item` `type` byte — the kind of the child a directory entry
222/// points at. Only the members the oracle exercises are named; any other value
223/// is preserved in [`DirItemType::Other`] with its raw byte (fail-loud: the
224/// unknown value is shown, never dropped).
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226#[non_exhaustive]
227pub enum DirItemType {
228    /// A regular file (`BTRFS_FT_REG_FILE` = 1).
229    File,
230    /// A directory (`BTRFS_FT_DIR` = 2).
231    Dir,
232    /// A symbolic link (`BTRFS_FT_SYMLINK` = 7).
233    Symlink,
234    /// Any other `BTRFS_FT_*` value, carrying the raw byte so an "unknown type"
235    /// is identifiable rather than silently dropped.
236    Other(u8),
237}
238
239impl DirItemType {
240    /// Classify a raw `btrfs_dir_item` `type` byte.
241    #[must_use]
242    fn from_byte(b: u8) -> Self {
243        match b {
244            1 => DirItemType::File,
245            2 => DirItemType::Dir,
246            7 => DirItemType::Symlink,
247            other => DirItemType::Other(other),
248        }
249    }
250}
251
252/// One directory entry: a child's name, its inode objectid, and its declared
253/// type.
254#[derive(Debug, Clone, PartialEq, Eq)]
255#[non_exhaustive]
256pub struct DirEntry {
257    /// The entry name (UTF-8 lossy; a directory entry name is raw bytes on disk,
258    /// decoded permissively so a non-UTF-8 name is surfaced, not dropped).
259    pub name: String,
260    /// The child inode's objectid (`location.objectid` of the dir item).
261    pub child: u64,
262    /// The child's declared type.
263    pub item_type: DirItemType,
264}
265
266/// The `FS_TREE` root as located in the root tree: where the FS tree's own root
267/// node lives and how deep it is.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269#[non_exhaustive]
270pub struct FsTreeRoot {
271    /// `bytenr` — the `FS_TREE` root node's **logical** address.
272    pub bytenr: u64,
273    /// `level` — the `FS_TREE` root node's B-tree level (0 = a single leaf).
274    pub level: u8,
275    /// `root_dirid` — the FS tree's root directory objectid (256).
276    pub root_dirid: u64,
277    /// `generation` — the transaction id the FS tree root was written in.
278    pub generation: u64,
279}
280
281/// Locate the `FS_TREE` ([`FS_TREE_OBJECTID`]) `ROOT_ITEM` by walking the root
282/// tree from the superblock's `root` logical address, returning where the FS
283/// tree's own root node lives.
284///
285/// Reads the root-tree node via [`read_node`]; if it is a leaf, scans its
286/// `ROOT_ITEM`s for the `FS_TREE` entry. (The oracle's root tree is a single
287/// leaf; interior root-tree descent is a later phase — an `FS_TREE` `ROOT_ITEM` in
288/// an interior root tree would require following key-pointers, out of P2 scope.)
289///
290/// # Errors
291///
292/// - Any error from [`read_node`] translating/reading `sb.root`.
293/// - [`BtrfsError::Truncated`] naming `FS_TREE ROOT_ITEM` when the root-tree
294///   leaf carries no `FS_TREE` `ROOT_ITEM` (a loud miss, never a silent `None`).
295pub fn fs_tree_root(
296    image: &[u8],
297    sb: &Superblock,
298    chunk_map: &ChunkMap,
299) -> Result<FsTreeRoot, BtrfsError> {
300    let node = read_node(image, sb, chunk_map, sb.root)?;
301    for (key, data) in node.leaf_items() {
302        if key.objectid == FS_TREE_OBJECTID && key.key_type == ROOT_ITEM_KEY {
303            return Ok(FsTreeRoot {
304                bytenr: le_u64(data, root_off::BYTENR),
305                level: u8_at(data, root_off::LEVEL),
306                root_dirid: le_u64(data, root_off::ROOT_DIRID),
307                generation: le_u64(data, root_off::GENERATION),
308            });
309        }
310    }
311    Err(BtrfsError::Truncated {
312        structure: "FS_TREE ROOT_ITEM (objectid 5) in root tree",
313        need: FS_TREE_OBJECTID as usize,
314        have: node.header.nritems as usize,
315    })
316}
317
318/// Read the `INODE_ITEM` for `objectid` from an `FS_TREE` `leaf`, or `None` if the
319/// leaf holds no inode item for it.
320#[must_use]
321pub fn read_inode(leaf: &Node, objectid: u64) -> Option<Inode> {
322    leaf.leaf_items()
323        .find(|(key, _)| key.objectid == objectid && key.key_type == INODE_ITEM_KEY)
324        .map(|(_, data)| Inode::parse(objectid, data))
325}
326
327/// List a directory's entries from an `FS_TREE` `leaf`: every `DIR_ITEM` /
328/// `DIR_INDEX` keyed by `dir_objectid`, deduplicated by name (both a `DIR_ITEM`
329/// and a `DIR_INDEX` name each child; the listing surfaces each name once).
330///
331/// Bounds-checked: an out-of-range `name_len` yields a name clamped to the item
332/// data actually present, never an over-read.
333#[must_use]
334pub fn list_dir(leaf: &Node, dir_objectid: u64) -> Vec<DirEntry> {
335    let mut out: Vec<DirEntry> = Vec::new();
336    for (key, data) in leaf.leaf_items() {
337        if key.objectid != dir_objectid
338            || (key.key_type != DIR_ITEM_KEY && key.key_type != DIR_INDEX_KEY)
339        {
340            continue;
341        }
342        let Some(entry) = parse_dir_item(data) else {
343            continue;
344        };
345        if out
346            .iter()
347            .any(|e| e.name == entry.name && e.child == entry.child)
348        {
349            continue;
350        }
351        out.push(entry);
352    }
353    out
354}
355
356/// Decode a single `btrfs_dir_item` body into a [`DirEntry`], or `None` if the
357/// item is too short to hold even the fixed prefix.
358///
359/// The name is clamped to whatever bytes remain after the fixed prefix, so a
360/// lying `name_len` truncates rather than over-reads.
361#[must_use]
362fn parse_dir_item(data: &[u8]) -> Option<DirEntry> {
363    if data.len() < dir_off::NAME {
364        return None;
365    }
366    let child = le_u64(data, 0); // location.objectid (start of the 17-byte key)
367    let type_byte = u8_at(data, dir_off::TYPE);
368    let name_len = le_u16(data, dir_off::NAME_LEN) as usize;
369
370    // The name occupies `name_len` bytes right after the fixed prefix (the
371    // optional xattr `data_len` bytes follow it). Clamp the name to the bytes
372    // actually present so a hostile `name_len` truncates rather than over-reads.
373    let name_start = dir_off::NAME;
374    let avail = data.len().saturating_sub(name_start);
375    let take = name_len.min(avail);
376    let name_bytes = data.get(name_start..name_start + take).unwrap_or(&[]);
377
378    Some(DirEntry {
379        name: String::from_utf8_lossy(name_bytes).into_owned(),
380        child,
381        item_type: DirItemType::from_byte(type_byte),
382    })
383}
384
385/// One extended attribute: its full name and its value.
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct Xattr {
388    /// The complete attribute name as the system presents it, e.g.
389    /// `security.selinux`. Btrfs stores it whole, so nothing is reconstructed.
390    pub name: String,
391    /// The attribute's value bytes.
392    pub value: Vec<u8>,
393}
394
395/// List every extended attribute attached to `objectid` in this leaf.
396///
397/// An inode with no attributes yields an empty vector; that is not an error.
398///
399/// Only items keyed to `objectid` are returned. A leaf interleaves many inodes'
400/// items, so filtering on `key_type` alone would hand one file's attributes to
401/// another.
402///
403/// **Several attributes can share one item.** The key is a hash of the name, so
404/// a collision chains a second `btrfs_dir_item` immediately after the first —
405/// exactly as `DIR_ITEM` does. The walk below continues through the item body
406/// rather than stopping at the first record, because stopping would silently
407/// drop the colliding attribute.
408#[must_use]
409pub fn list_xattrs(leaf: &Node, objectid: u64) -> Vec<Xattr> {
410    let mut out = Vec::new();
411    for (key, data) in leaf.leaf_items() {
412        if key.objectid != objectid || key.key_type != XATTR_ITEM_KEY {
413            continue;
414        }
415        let mut off = 0usize;
416        // A malformed record ENDS this item's walk: the records are packed with
417        // no terminator, so once one length is untrustworthy there is nowhere
418        // safe to resume, and continuing would emit an attribute assembled from
419        // the wrong bytes.
420        while let Some(rest) = data.get(off..) {
421            let Some((x, consumed)) = parse_xattr_item(rest) else {
422                break;
423            };
424            out.push(x);
425            if consumed == 0 {
426                break; // cov:unreachable: parse_xattr_item rejects name_len == 0, so consumed >= dir_off::NAME + 1
427            }
428            off += consumed;
429        }
430    }
431    out
432}
433
434/// Parse one `btrfs_dir_item` as an extended attribute, returning it and the
435/// number of bytes it occupied.
436///
437/// The 30-byte prefix length is not assumed: for every item in the reference
438/// leaf `itemsize == 30 + name_len + data_len` holds exactly.
439fn parse_xattr_item(data: &[u8]) -> Option<(Xattr, usize)> {
440    if data.len() < dir_off::NAME {
441        return None;
442    }
443    let data_len = le_u16(data, dir_off::DATA_LEN) as usize;
444    let name_len = le_u16(data, dir_off::NAME_LEN) as usize;
445    // A zero-length name is not a valid attribute; treating it as one would
446    // emit a nameless entry and, with a zero data_len, never advance.
447    if name_len == 0 {
448        return None;
449    }
450    let name_end = dir_off::NAME.checked_add(name_len)?;
451    let value_end = name_end.checked_add(data_len)?;
452    // Both the name and the value must be fully present. A truncated record is
453    // refused rather than padded: a short value would be reported as the
454    // attribute's real contents.
455    let name = data.get(dir_off::NAME..name_end)?;
456    let value = data.get(name_end..value_end)?;
457    Some((
458        Xattr {
459            name: String::from_utf8_lossy(name).into_owned(),
460            value: value.to_vec(),
461        },
462        value_end,
463    ))
464}
465
466/// Byte offsets within a `btrfs_inode_ref` record (packed, little-endian).
467mod inode_ref_off {
468    /// `__le64 index` — the directory index this name occupies.
469    pub const INDEX: usize = 0x00;
470    /// `__le16 name_len`.
471    pub const NAME_LEN: usize = 0x08;
472    /// The name bytes begin here; the record is `NAME + name_len` long.
473    pub const NAME: usize = 0x0A;
474}
475
476/// One name an inode is known by, and the directory holding it.
477///
478/// A btrfs inode with `nlink > 1` has one of these per link. This is the
479/// back-reference the filesystem stores deliberately, so the answer is a direct
480/// read rather than a directory walk.
481#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct InodeRef {
483    /// Objectid of the directory containing this name (the item key's offset).
484    pub parent: u64,
485    /// The directory index this name occupies within `parent`.
486    pub index: u64,
487    /// The name itself.
488    pub name: String,
489}
490
491/// List every name `objectid` is known by within this leaf.
492///
493/// An inode the leaf does not describe yields an empty vector; that is not an
494/// error. Only items keyed to `objectid` are returned — a leaf interleaves many
495/// inodes' items, so filtering on `key_type` alone would hand one file's names
496/// to another.
497///
498/// **Several names can share one item.** `INODE_REF` items are keyed by
499/// `(objectid, INODE_REF, parent_dir)`, so every link inside the *same*
500/// directory is packed into one item as consecutive `btrfs_inode_ref` records.
501/// In the reference leaf item 15 is 42 bytes holding both `hardlink.txt`
502/// (10 + 12) and `target.txt` (10 + 10). A walk that stopped at the first
503/// record would report two links where the volume has three.
504#[must_use]
505pub fn list_inode_refs(leaf: &Node, objectid: u64) -> Vec<InodeRef> {
506    let mut out = Vec::new();
507    for (key, data) in leaf.leaf_items() {
508        if key.objectid != objectid || key.key_type != INODE_REF_KEY {
509            continue;
510        }
511        let mut off = 0usize;
512        // A malformed record ENDS this item's walk: the records are packed with
513        // no terminator, so once one length is untrustworthy there is nowhere
514        // safe to resume, and continuing would emit a name assembled from the
515        // wrong bytes.
516        while let Some(rest) = data.get(off..) {
517            let Some((r, consumed)) = parse_inode_ref(rest, key.offset) else {
518                break;
519            };
520            out.push(r);
521            if consumed == 0 {
522                break; // cov:unreachable: parse_inode_ref rejects name_len == 0, so consumed >= inode_ref_off::NAME + 1
523            }
524            off += consumed;
525        }
526    }
527    out
528}
529
530/// Parse one `btrfs_inode_ref`, returning it and the bytes it occupied.
531///
532/// `parent` comes from the item key's `offset` field, not the record: the record
533/// carries only the index and the name.
534fn parse_inode_ref(data: &[u8], parent: u64) -> Option<(InodeRef, usize)> {
535    if data.len() < inode_ref_off::NAME {
536        return None;
537    }
538    let index = le_u64(data, inode_ref_off::INDEX);
539    let name_len = le_u16(data, inode_ref_off::NAME_LEN) as usize;
540    // A zero-length name is not a valid link; emitting one would produce a
541    // nameless entry and never advance the walk.
542    if name_len == 0 {
543        return None;
544    }
545    let name_end = inode_ref_off::NAME.checked_add(name_len)?;
546    // A truncated record is refused rather than padded: a short name would be
547    // reported as the link's real name.
548    let name = data.get(inode_ref_off::NAME..name_end)?;
549    Some((
550        InodeRef {
551            parent,
552            index,
553            name: String::from_utf8_lossy(name).into_owned(),
554        },
555        name_end,
556    ))
557}
558
559/// Resolve a slash-separated `path` to `(objectid, Inode)` within an `FS_TREE`
560/// `leaf`, starting from the `FS_TREE` root directory ([`FS_TREE_ROOT_DIR_OBJECTID`]).
561///
562/// A leading slash is optional and redundant / trailing separators are ignored.
563/// The empty path (`""` or `"/"`) resolves to the root directory itself.
564/// Returns `None` if any component is missing or descends through a non-directory.
565#[must_use]
566pub fn read_by_path(leaf: &Node, path: &str) -> Option<(u64, Inode)> {
567    let mut current = FS_TREE_ROOT_DIR_OBJECTID;
568    let mut inode = read_inode(leaf, current)?;
569
570    for component in path.split('/').filter(|c| !c.is_empty()) {
571        // To descend, the current inode must be a directory.
572        if !inode.is_dir() {
573            return None;
574        }
575        let entry = list_dir(leaf, current)
576            .into_iter()
577            .find(|e| e.name == component)?;
578        current = entry.child;
579        inode = read_inode(leaf, current)?;
580    }
581
582    Some((current, inode))
583}
584
585#[cfg(test)]
586mod unit {
587    use super::{dir_off, inode_ref_off, parse_inode_ref, parse_xattr_item};
588
589    #[test]
590    fn an_xattr_record_with_a_zero_length_name_is_refused() {
591        // A full 30-byte prefix with name_len = 0 and data_len = 4.
592        let mut rec = vec![0u8; dir_off::NAME + 4];
593        rec[dir_off::DATA_LEN..dir_off::DATA_LEN + 2].copy_from_slice(&4u16.to_le_bytes());
594        assert!(parse_xattr_item(&rec).is_none());
595    }
596
597    #[test]
598    fn an_inode_ref_with_a_zero_length_name_is_refused() {
599        let rec = vec![0u8; inode_ref_off::NAME + 4]; // name_len = 0
600        assert!(parse_inode_ref(&rec, 256).is_none());
601    }
602}