Skip to main content

hfsplus_core/
lib.rs

1//! HFS+ / HFSX volume-header detection (Apple TN1150).
2//!
3//! Apple optical discs are frequently *hybrids*: an ISO 9660 filesystem and an
4//! HFS/HFS+ volume sharing the same disc, so a Mac and a PC each see their own
5//! filesystem.  The HFS+ volume header sits at a fixed 1024-byte offset from the
6//! volume start (TN1150 §"Volume Header"), with a big-endian `H+` (HFS+) or `HX`
7//! (HFSX) signature.
8//!
9//! This crate reads the volume header (geometry), walks the catalog B-tree to
10//! list directories ([`list_root`], [`list_dir`], recursive [`walk`]), and
11//! extracts file contents ([`read_file`]) — including HFS+/APFS transparently
12//! *compressed* files, which it decodes via the [`decmpfs`] module (zlib / LZVN
13//! / LZFSE, inline xattr or resource fork). Journal replay is out of scope.
14//! Validated against real `hdiutil`/`ditto`-created HFS+ volumes.
15
16// Tests legitimately unwrap/expect; production code must not (enforced by the
17// `unwrap_used`/`expect_used = deny` lints in Cargo.toml).
18#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
19
20pub mod decmpfs;
21#[cfg(feature = "vfs")]
22pub mod vfs;
23
24/// Byte offset of the HFS+ volume header from the start of the volume.
25pub const VOLUME_HEADER_OFFSET: usize = 1024;
26/// HFS+ signature `H+` (TN1150).
27pub(crate) const SIG_HFS_PLUS: u16 = 0x482B;
28/// HFSX signature `HX` (case-sensitive variant).
29pub(crate) const SIG_HFSX: u16 = 0x4858;
30
31/// Which Apple volume signature was found.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum HfsKind {
34    /// `H+` — standard HFS Plus.
35    HfsPlus,
36    /// `HX` — case-sensitive HFSX.
37    Hfsx,
38}
39
40/// Parsed HFS+ volume header fields (geometry only).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct HfsVolume {
43    pub kind: HfsKind,
44    /// Volume format version (4 for HFS+, 5 for HFSX).
45    pub version: u16,
46    /// Number of files in the volume's catalog.
47    pub file_count: u32,
48    /// Number of folders in the volume's catalog.
49    pub folder_count: u32,
50    /// Allocation block size in bytes.
51    pub block_size: u32,
52    /// Total allocation blocks in the volume.
53    pub total_blocks: u32,
54    /// Free allocation blocks.
55    pub free_blocks: u32,
56}
57
58impl HfsVolume {
59    /// Total volume size in bytes (`block_size * total_blocks`).
60    #[must_use]
61    pub fn volume_size(&self) -> u64 {
62        u64::from(self.block_size) * u64::from(self.total_blocks)
63    }
64}
65
66/// Parse the HFS+/HFSX volume header from a buffer that begins at the volume
67/// start (the header is read at offset 1024).  Returns `None` if the buffer is
68/// too short or carries no HFS+ signature.
69#[must_use]
70pub fn parse(volume: &[u8]) -> Option<HfsVolume> {
71    let h = VOLUME_HEADER_OFFSET;
72    if volume.len() < h + 52 {
73        return None;
74    }
75    let hdr = &volume[h..];
76    let kind = match be16(&hdr[0..2]) {
77        SIG_HFS_PLUS => HfsKind::HfsPlus,
78        SIG_HFSX => HfsKind::Hfsx,
79        _ => return None,
80    };
81    Some(HfsVolume {
82        kind,
83        version: be16(&hdr[2..4]),
84        file_count: be32(&hdr[32..36]),
85        folder_count: be32(&hdr[36..40]),
86        block_size: be32(&hdr[40..44]),
87        total_blocks: be32(&hdr[44..48]),
88        free_blocks: be32(&hdr[48..52]),
89    })
90}
91
92/// Catalog node ID of the root folder (TN1150).
93const ROOT_FOLDER_CNID: u32 = 2;
94/// Catalog record types (TN1150): folder / file leaf records.
95const RECORD_FOLDER: i16 = 1;
96const RECORD_FILE: i16 = 2;
97/// Bound on catalog leaf nodes walked, guarding against a corrupt `fLink` chain.
98pub const MAX_LEAF_NODES: u32 = 65536;
99
100/// An entry in an HFS+ directory.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct HfsEntry {
103    /// File or folder name (decoded from UTF-16).
104    pub name: String,
105    /// True for a folder, false for a file.
106    pub is_dir: bool,
107    /// Catalog node ID (CNID) of this entry.
108    pub cnid: u32,
109}
110
111/// Located catalog B-tree geometry within an HFS+ volume.
112pub struct CatalogLoc {
113    pub cat_base: usize,
114    pub node_size: usize,
115    pub first_leaf: u32,
116    pub block_size: usize,
117}
118
119/// Volume-header byte offset of the extentsFile `HFSPlusForkData` (TN1150) —
120/// the extents-overflow B-tree, holding extent records for files whose fork
121/// outgrows its 8 inline extents.
122pub(crate) const EXTENTS_FORK_OFFSET: usize = 192;
123/// Volume-header byte offset of the catalogFile `HFSPlusForkData` (TN1150).
124pub(crate) const CATALOG_FORK_OFFSET: usize = 272;
125/// Volume-header byte offset of the attributesFile `HFSPlusForkData` (the
126/// catalogFile's successor, 80 bytes later) — home of extended attributes,
127/// including `com.apple.decmpfs`.
128pub(crate) const ATTRIBUTES_FORK_OFFSET: usize = 352;
129
130/// Locate the catalog B-tree from the volume header (its first extent).
131pub fn locate_catalog(volume: &[u8]) -> Option<CatalogLoc> {
132    locate_btree(volume, CATALOG_FORK_OFFSET)
133}
134
135/// Locate the attributes B-tree, or `None` when the volume has no attributes
136/// file (its fork holds zero blocks — i.e. no extended attributes anywhere).
137pub(crate) fn locate_attributes(volume: &[u8]) -> Option<CatalogLoc> {
138    locate_btree(volume, ATTRIBUTES_FORK_OFFSET)
139}
140
141/// Locate the extents-overflow B-tree, or `None` when the volume has none.
142pub fn locate_extents(volume: &[u8]) -> Option<CatalogLoc> {
143    locate_btree(volume, EXTENTS_FORK_OFFSET)
144}
145
146/// Locate a B-tree whose first-extent `HFSPlusForkData` sits at
147/// `fork_offset_in_header` bytes into the volume header. The catalog and
148/// attributes files share the identical fork-data + B-tree-header layout.
149pub(crate) fn locate_btree(volume: &[u8], fork_offset_in_header: usize) -> Option<CatalogLoc> {
150    let h = VOLUME_HEADER_OFFSET;
151    let fork = h.checked_add(fork_offset_in_header)?;
152    if volume.len() < fork + 20 {
153        return None;
154    }
155    match be16(&volume[h..h + 2]) {
156        SIG_HFS_PLUS | SIG_HFSX => {}
157        _ => return None,
158    }
159    let block_size = be32(&volume[h + 40..h + 44]) as usize;
160    if block_size == 0 {
161        return None;
162    }
163    // HFSPlusForkData: logicalSize(8) clumpSize(4) totalBlocks(4) extents(...).
164    // A zero totalBlocks means the file does not exist (no attributes B-tree).
165    if be32(&volume[fork + 12..fork + 16]) == 0 {
166        return None;
167    }
168    // First extent's startBlock is at fork+16.
169    let start_block = be32(&volume[fork + 16..fork + 20]) as usize;
170    let cat_base = start_block.checked_mul(block_size)?;
171    // B-tree header record follows the 14-byte node descriptor of node 0.
172    let hdr = cat_base.checked_add(14)?;
173    if volume.len() < hdr + 20 {
174        return None;
175    }
176    let first_leaf = be32(&volume[hdr + 10..hdr + 14]);
177    let node_size = be16(&volume[hdr + 18..hdr + 20]) as usize;
178    if node_size < 14 {
179        return None;
180    }
181    Some(CatalogLoc {
182        cat_base,
183        node_size,
184        first_leaf,
185        block_size,
186    })
187}
188
189/// Walk the catalog leaf-node chain, invoking `f` with each record slice.
190///
191/// Lenient: a node outside the volume or a chain past [`MAX_LEAF_NODES`] ends
192/// the walk, and a record slot outside its node is skipped, all quietly. The
193/// extended-attribute readers use the checked walk instead, which reports each.
194pub fn for_each_record(volume: &[u8], loc: &CatalogLoc, mut f: impl FnMut(&[u8])) {
195    let _ = walk_leaves(volume, loc, false, |rec| {
196        f(rec);
197        Ok(())
198    });
199}
200
201/// The leaf-chain walk behind [`for_each_record`].
202///
203/// A node outside the volume and a chain past [`MAX_LEAF_NODES`] are errors in
204/// both modes (the lenient caller discards them, which is the old quiet stop).
205/// With `strict`, a node declaring more record offsets than it can hold, or a
206/// record offset past its node, is an error too; leniently those are skipped.
207/// `f` stops the walk by returning an error.
208fn walk_leaves(
209    volume: &[u8],
210    loc: &CatalogLoc,
211    strict: bool,
212    mut f: impl FnMut(&[u8]) -> Result<(), HfsXattrError>,
213) -> Result<(), HfsXattrError> {
214    let mut node = loc.first_leaf;
215    let mut walked = 0u32;
216    while node != 0 {
217        if walked >= MAX_LEAF_NODES {
218            return Err(HfsXattrError::LeafChain {
219                node,
220                detail: format!(
221                    "the fLink chain runs past {MAX_LEAF_NODES} leaf nodes, so it loops or is corrupt"
222                ),
223            });
224        }
225        walked += 1;
226        let Some(nd) = (node as usize)
227            .checked_mul(loc.node_size)
228            .and_then(|x| x.checked_add(loc.cat_base))
229            .and_then(|off| volume.get(off..off.checked_add(loc.node_size)?))
230        else {
231            return Err(HfsXattrError::LeafChain {
232                node,
233                detail: format!(
234                    "node {node} ({}-byte nodes from byte {}) lies outside the {}-byte volume",
235                    loc.node_size,
236                    loc.cat_base,
237                    volume.len()
238                ),
239            });
240        };
241        let f_link = be32(&nd[0..4]);
242        let num_records = be16(&nd[10..12]) as usize;
243        for i in 0..num_records {
244            // Record offsets are stored backwards from the node end.
245            let Some(slot) = loc.node_size.checked_sub(2 * (i + 1)) else {
246                if strict {
247                    return Err(HfsXattrError::LeafChain {
248                        node,
249                        detail: format!(
250                            "node {node} declares {num_records} records, more offsets than a {}-byte node holds",
251                            loc.node_size
252                        ),
253                    });
254                }
255                break;
256            };
257            let rec = be16(&nd[slot..slot + 2]) as usize;
258            if rec + 8 <= loc.node_size {
259                f(&nd[rec..])?;
260            } else if strict {
261                return Err(HfsXattrError::LeafChain {
262                    node,
263                    detail: format!(
264                        "record {i} of node {node} starts at byte {rec}, past the {}-byte node",
265                        loc.node_size
266                    ),
267                });
268            }
269        }
270        node = f_link;
271    }
272    Ok(())
273}
274
275/// List the root directory of an HFS+ volume.  See [`list_dir`].
276#[must_use]
277pub fn list_root(volume: &[u8]) -> Option<Vec<HfsEntry>> {
278    list_dir(volume, ROOT_FOLDER_CNID)
279}
280
281/// List the immediate children of the folder `parent_cnid` by walking the HFS+
282/// catalog B-tree.
283///
284/// `volume` must contain the whole HFS+ volume from its first byte (header at
285/// offset 1024).  Entries include HFS+ private metadata directories (real, not
286/// hidden); thread records are skipped.  Returns `None` if this is not an HFS+
287/// volume or the catalog cannot be located.  Assumes the catalog fits in its
288/// first extent (true for typical optical/hybrid volumes).
289#[must_use]
290pub fn list_dir(volume: &[u8], parent_cnid: u32) -> Option<Vec<HfsEntry>> {
291    let loc = locate_catalog(volume)?;
292    let mut entries = Vec::new();
293    for_each_record(volume, &loc, |rec| {
294        if let Some((parent, entry)) = record_entry(rec) {
295            if parent == parent_cnid {
296                entries.push(entry);
297            }
298        }
299    });
300    Some(entries)
301}
302
303/// Read a file's data-fork contents by catalog node ID.
304///
305/// Returns the file's bytes (concatenated from its data-fork extents, truncated
306/// to the logical size), or `None` if `cnid` is not a file in this volume.
307/// Read a file's contents by catalog node ID.
308///
309/// For a normal file this returns the data fork (concatenated extents, truncated
310/// to the logical size). For an HFS+/APFS **transparently-compressed** file —
311/// one carrying a `com.apple.decmpfs` extended attribute — the data fork is
312/// empty and the real bytes are decoded from the xattr (inline) or the resource
313/// fork ([`decmpfs`]). Returns `None` if `cnid` is not a file, or if a
314/// recognised compressed file cannot be decoded (it never returns a misleading
315/// empty or raw data fork in that case).
316#[must_use]
317pub fn read_file(volume: &[u8], cnid: u32) -> Option<Vec<u8>> {
318    let loc = locate_catalog(volume)?;
319    let mut forks: Option<(Fork, Fork)> = None;
320    for_each_record(volume, &loc, |rec| {
321        if forks.is_none() {
322            forks = file_forks(rec, cnid);
323        }
324    });
325    let (data_fork, resource_fork) = forks?;
326
327    if let Some(xattr) = decmpfs_xattr(volume, cnid) {
328        let resource = if resource_fork.logical > 0 {
329            fork_bytes(volume, loc.block_size, &resource_fork)
330        } else {
331            None
332        };
333        // Fail loud: a decmpfs file we cannot decode returns None, never the
334        // empty data fork — silent data loss is the bug this whole path fixes.
335        return decmpfs::decompress(&xattr, resource.as_deref()).ok();
336    }
337
338    fork_bytes(volume, loc.block_size, &data_fork)
339}
340
341/// Per-CNID metadata for one catalog entry: kind, data-fork size, and the three
342/// HFS+ MAC timestamps. Timestamps are raw HFS+ values (`u32` seconds since the
343/// HFS+ epoch, 1904-01-01 UTC) — a consumer converts them.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct HfsStat {
346    /// Catalog node ID this stat describes.
347    pub cnid: u32,
348    /// True for a folder, false for a file.
349    pub is_dir: bool,
350    /// Data-fork logical size in bytes (0 for a folder).
351    pub size: u64,
352    /// Creation time (HFS+ epoch seconds).
353    pub created: u32,
354    /// Content-modification time (HFS+ epoch seconds).
355    pub modified: u32,
356    /// Access time (HFS+ epoch seconds).
357    pub accessed: u32,
358}
359
360/// Look up the [`HfsStat`] of a catalog entry by CNID, walking the catalog B-tree
361/// to its file/folder record. Returns the entry's kind, data-fork logical size
362/// (0 for a folder), and its three HFS+ MAC timestamps (raw, unconverted).
363///
364/// `volume` must contain the whole HFS+ volume from its first byte (header at
365/// offset 1024). Returns `None` if this is not an HFS+ volume or no file/folder
366/// record with `cnid` exists (thread records carry no times and are skipped).
367#[must_use]
368pub fn stat(volume: &[u8], cnid: u32) -> Option<HfsStat> {
369    let loc = locate_catalog(volume)?;
370    let mut found = None;
371    for_each_record(volume, &loc, |rec| {
372        if found.is_none() {
373            found = record_stat(rec, cnid);
374        }
375    });
376    found
377}
378
379/// If `rec` is the file or folder record for `cnid`, return its [`HfsStat`].
380/// Both `HFSPlusCatalogFile` and `HFSPlusCatalogFolder` share createDate@+16,
381/// contentModDate@+20, and accessDate@+28 (relative to the record body); the
382/// file additionally carries its data-fork `HFSPlusForkData` at +88, whose
383/// logicalSize is the first 8 bytes (TN1150).
384fn record_stat(rec: &[u8], cnid: u32) -> Option<HfsStat> {
385    if rec.len() < 8 {
386        return None;
387    }
388    let key_len = be16(&rec[0..2]) as usize;
389    let data = 2 + key_len;
390    // Need through accessDate@+32 at minimum for either record kind.
391    if data + 32 > rec.len() {
392        return None;
393    }
394    let is_dir = match i16::from_be_bytes([rec[data], rec[data + 1]]) {
395        RECORD_FOLDER => true,
396        RECORD_FILE => false,
397        _ => return None, // thread records and anything else carry no times
398    };
399    if be32(&rec[data + 8..data + 12]) != cnid {
400        return None;
401    }
402    let created = be32(&rec[data + 16..data + 20]);
403    let modified = be32(&rec[data + 20..data + 24]);
404    let accessed = be32(&rec[data + 28..data + 32]);
405    // A file record carries its data-fork logicalSize at +88 (8 bytes BE); a
406    // folder has no fork, so its size is 0.
407    let size = if is_dir {
408        0
409    } else if data + 96 <= rec.len() {
410        u64::from_be_bytes(rec[data + 88..data + 96].try_into().ok()?)
411    } else {
412        0
413    };
414    Some(HfsStat {
415        cnid,
416        is_dir,
417        size,
418        created,
419        modified,
420        accessed,
421    })
422}
423
424/// Parse a catalog record into `(parentID, entry)` for file/folder records.
425fn record_entry(rec: &[u8]) -> Option<(u32, HfsEntry)> {
426    if rec.len() < 8 {
427        return None;
428    }
429    let key_len = be16(&rec[0..2]) as usize;
430    let parent_id = be32(&rec[2..6]);
431    let name_len = be16(&rec[6..8]) as usize;
432    let name_end = 8 + name_len * 2;
433    if name_end > rec.len() {
434        return None;
435    }
436    let name = decode_utf16(&rec[8..name_end]);
437    let data = 2 + key_len;
438    if data + 12 > rec.len() {
439        return None;
440    }
441    let is_dir = match i16::from_be_bytes([rec[data], rec[data + 1]]) {
442        RECORD_FOLDER => true,
443        RECORD_FILE => false,
444        _ => return None, // thread records and anything else
445    };
446    // folderID / fileID at offset 8 of the folder/file record.
447    let cnid = be32(&rec[data + 8..data + 12]);
448    Some((parent_id, HfsEntry { name, is_dir, cnid }))
449}
450
451/// A file fork: logical size plus its (`start_block`, `block_count`) extents.
452struct Fork {
453    logical: u64,
454    extents: Vec<(u32, u32)>,
455}
456
457/// `com.apple.decmpfs` extended-attribute name.
458const DECMPFS_XATTR_NAME: &str = "com.apple.decmpfs";
459/// `kHFSPlusAttrInlineData` — the attribute record type whose value is stored
460/// inline (the only form the small decmpfs header ever uses).
461const ATTR_INLINE_DATA: u32 = 0x10;
462
463/// If `rec` is the file record for `cnid`, return its `(data_fork,
464/// resource_fork)`. The file record holds the data fork's `HFSPlusForkData` at
465/// +88 and the resource fork's at +168 (TN1150).
466fn file_forks(rec: &[u8], cnid: u32) -> Option<(Fork, Fork)> {
467    if rec.len() < 8 {
468        return None;
469    }
470    let key_len = be16(&rec[0..2]) as usize;
471    let data = 2 + key_len;
472    if data + 168 > rec.len() {
473        return None;
474    }
475    if i16::from_be_bytes([rec[data], rec[data + 1]]) != RECORD_FILE {
476        return None;
477    }
478    if be32(&rec[data + 8..data + 12]) != cnid {
479        return None;
480    }
481    let data_fork = parse_fork(&rec[data + 88..])?;
482    // The resource fork follows the 80-byte data fork. A record truncated before
483    // it means no resource fork (an empty one is harmless for non-compressed files).
484    let resource_fork = if data + 248 <= rec.len() {
485        parse_fork(&rec[data + 168..])?
486    } else {
487        Fork {
488            logical: 0,
489            extents: Vec::new(),
490        }
491    };
492    Some((data_fork, resource_fork))
493}
494
495/// Parse an 80-byte `HFSPlusForkData`: logical size + up to 8 extents.
496fn parse_fork(fork: &[u8]) -> Option<Fork> {
497    if fork.len() < 80 {
498        return None;
499    }
500    let logical = u64::from_be_bytes(fork[0..8].try_into().ok()?);
501    let mut extents = Vec::new();
502    for i in 0..8 {
503        let e = 16 + i * 8;
504        let start = be32(&fork[e..e + 4]);
505        let count = be32(&fork[e + 4..e + 8]);
506        if count != 0 {
507            extents.push((start, count));
508        }
509    }
510    Some(Fork { logical, extents })
511}
512
513/// Materialize a fork's bytes from `volume`, truncated to its logical size.
514fn fork_bytes(volume: &[u8], block_size: usize, fork: &Fork) -> Option<Vec<u8>> {
515    let logical = fork.logical as usize;
516    let mut data = Vec::with_capacity(logical.min(1 << 20));
517    for &(start, count) in &fork.extents {
518        if data.len() >= logical {
519            break;
520        }
521        let begin = (start as usize).checked_mul(block_size)?;
522        let len = (count as usize).checked_mul(block_size)?;
523        let end = begin.checked_add(len)?.min(volume.len());
524        if begin >= volume.len() {
525            break;
526        }
527        data.extend_from_slice(&volume[begin..end]);
528    }
529    data.truncate(logical);
530    Some(data)
531}
532
533/// Look up the `com.apple.decmpfs` extended attribute for `cnid` by walking the
534/// attributes B-tree. Returns `None` if the volume has no attributes file or the
535/// file carries no such attribute (i.e. it is not transparently compressed).
536pub fn decmpfs_xattr(volume: &[u8], cnid: u32) -> Option<Vec<u8>> {
537    let loc = locate_attributes(volume)?;
538    let mut found = None;
539    for_each_record(volume, &loc, |rec| {
540        if found.is_none() {
541            found = attr_inline_value(rec, cnid, DECMPFS_XATTR_NAME);
542        }
543    });
544    found
545}
546
547/// If `rec` is the inline-data attribute record for `(cnid, want_name)`, return
548/// its value. `HFSPlusAttrKey`: keyLength(2) pad(2) fileID@4 startBlock@8
549/// attrNameLen@12 attrName@14 (UTF-16 BE). `HFSPlusAttrData`: `recordType@key_end`
550/// reserved[2] attrSize@+12 attrData@+16.
551fn attr_inline_value(rec: &[u8], cnid: u32, want_name: &str) -> Option<Vec<u8>> {
552    if rec.len() < 14 {
553        return None;
554    }
555    let key_len = be16(&rec[0..2]) as usize;
556    if be32(&rec[4..8]) != cnid {
557        return None;
558    }
559    let name_len = be16(&rec[12..14]) as usize;
560    let name_end = 14usize.checked_add(name_len.checked_mul(2)?)?;
561    if name_end > rec.len() {
562        return None;
563    }
564    if decode_utf16(&rec[14..name_end]) != want_name {
565        return None;
566    }
567    let body = 2 + key_len;
568    if body + 16 > rec.len() {
569        return None;
570    }
571    if be32(&rec[body..body + 4]) != ATTR_INLINE_DATA {
572        return None;
573    }
574    let attr_size = be32(&rec[body + 12..body + 16]) as usize;
575    let end = body.checked_add(16)?.checked_add(attr_size)?;
576    if end > rec.len() {
577        return None;
578    }
579    Some(rec[body + 16..end].to_vec())
580}
581
582/// `kHFSPlusAttrForkData` — the attribute's value lives out in allocation
583/// blocks rather than in the B-tree record, because it exceeded the inline
584/// ceiling. `kHFSPlusAttrExtents` (0x30) continues such a fork's extent list.
585const ATTR_FORK_DATA: u32 = 0x20;
586
587/// How HFS+ chose to store an extended attribute's value.
588///
589/// This distinction is evidential, not an implementation detail: it says where
590/// the bytes physically are. Collapsing the two would describe the artifact
591/// wrongly, so the reader reports what the volume actually did.
592#[derive(Debug, Clone, PartialEq, Eq)]
593pub enum HfsXattrValue {
594    /// `kHFSPlusAttrInlineData` — the value is in the attributes B-tree record.
595    Inline(Vec<u8>),
596    /// `kHFSPlusAttrForkData` — the value occupies allocation blocks, with the
597    /// given logical length.
598    Fork {
599        /// Logical size in bytes, from the record's `HFSPlusForkData`.
600        logical: u64,
601    },
602}
603
604impl HfsXattrValue {
605    /// The value's length in bytes, whichever way it is stored.
606    #[must_use]
607    pub fn len(&self) -> u64 {
608        match self {
609            Self::Inline(b) => b.len() as u64,
610            Self::Fork { logical } => *logical,
611        }
612    }
613
614    /// True when the attribute carries no bytes. (An attribute may legitimately
615    /// exist with an empty value — its PRESENCE is the evidence.)
616    #[must_use]
617    pub fn is_empty(&self) -> bool {
618        self.len() == 0
619    }
620}
621
622/// One extended attribute: its name and how the volume stored it.
623#[derive(Debug, Clone, PartialEq, Eq)]
624pub struct HfsXattr {
625    /// Attribute name, decoded from the key's big-endian UTF-16.
626    pub name: String,
627    /// The stored value, or its length when it lives in a fork.
628    pub value: HfsXattrValue,
629}
630
631/// Why an extended-attribute question could not be answered.
632///
633/// Each variant is damage or an unread structure, never absence: "no such
634/// attribute" is an `Ok` empty list or `Ok(None)`, and an error here means the
635/// volume could not say.
636#[derive(Debug, Clone, PartialEq, Eq)]
637#[non_exhaustive]
638pub enum HfsXattrError {
639    /// The volume header declares an attributes file (non-zero `totalBlocks`),
640    /// but its B-tree header cannot be used.
641    AttributesBtree {
642        /// What is wrong with it.
643        detail: String,
644    },
645    /// The attributes B-tree's leaf chain could not be walked to its end.
646    LeafChain {
647        /// The node where the walk stopped.
648        node: u32,
649        /// What is wrong with it.
650        detail: String,
651    },
652    /// A record of this file's attributes could not be decoded.
653    Record {
654        /// The attribute's name, when the key was readable enough to give one.
655        name: Option<String>,
656        /// What is wrong with it.
657        detail: String,
658        /// The record's first bytes, as found.
659        bytes: Vec<u8>,
660    },
661}
662
663impl std::fmt::Display for HfsXattrError {
664    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665        match self {
666            Self::AttributesBtree { detail } => write!(f, "attributes B-tree unreadable: {detail}"),
667            Self::LeafChain { node, detail } => {
668                write!(
669                    f,
670                    "attributes B-tree leaf chain broken at node {node}: {detail}"
671                )
672            }
673            Self::Record {
674                name,
675                detail,
676                bytes,
677            } => {
678                let hex = bytes.iter().fold(String::new(), |mut s, b| {
679                    let _ = std::fmt::Write::write_fmt(&mut s, format_args!("{b:02x}"));
680                    s
681                });
682                match name {
683                    Some(n) => write!(f, "attribute {n}: {detail} (record starts {hex})"),
684                    None => write!(f, "attribute record: {detail} (record starts {hex})"),
685                }
686            }
687        }
688    }
689}
690
691impl std::error::Error for HfsXattrError {}
692
693/// The first bytes of a record, for an error that has to show what it found.
694fn record_prefix(rec: &[u8]) -> Vec<u8> {
695    rec[..rec.len().min(32)].to_vec()
696}
697
698/// The attributes B-tree, `Ok(None)` when the volume header says there is no
699/// attributes file, and an error when it says there is one that cannot be used.
700fn attributes_btree(volume: &[u8]) -> Result<Option<CatalogLoc>, HfsXattrError> {
701    let fork = VOLUME_HEADER_OFFSET + ATTRIBUTES_FORK_OFFSET;
702    let Some(total_blocks) = volume.get(fork + 12..fork + 16) else {
703        return Err(HfsXattrError::AttributesBtree {
704            detail: format!(
705                "the {}-byte volume ends before the attributes fork record at byte {fork}",
706                volume.len()
707            ),
708        });
709    };
710    if be32(total_blocks) == 0 {
711        return Ok(None);
712    }
713    locate_attributes(volume)
714        .map(Some)
715        .ok_or_else(|| HfsXattrError::AttributesBtree {
716            detail: format!(
717                "the volume header declares {} attributes-file blocks, but the B-tree header is unusable (bad signature, block size, location or node size)",
718                be32(total_blocks)
719            ),
720        })
721}
722
723/// List every extended attribute attached to `cnid`, in B-tree (name) order.
724///
725/// Returns an empty vector for a file with no attributes and for a volume whose
726/// header declares no attributes file; neither is an error.
727///
728/// `kHFSPlusAttrExtents` (0x30) continuation records are skipped: they carry
729/// further extents for a fork record already listed, so treating one as its own
730/// attribute would report a duplicate under the same name.
731///
732/// # Errors
733///
734/// [`HfsXattrError`] when the attributes B-tree is declared but unusable, its
735/// leaf chain cannot be walked to the end, or a record of this file cannot be
736/// decoded (including a record type this reader does not know). The list would
737/// otherwise be silently incomplete.
738pub fn list_xattrs(volume: &[u8], cnid: u32) -> Result<Vec<HfsXattr>, HfsXattrError> {
739    let Some(loc) = attributes_btree(volume)? else {
740        return Ok(Vec::new());
741    };
742    let mut out = Vec::new();
743    walk_leaves(volume, &loc, true, |rec| {
744        if let Some(x) = parse_attr_record(rec, cnid)? {
745            out.push(x);
746        }
747        Ok(())
748    })?;
749    Ok(out)
750}
751
752/// Read one extended attribute's bytes, materializing a fork-stored value from
753/// its allocation blocks.
754///
755/// Returns `Ok(None)` when no attribute of that name is attached to `cnid`.
756///
757/// # Errors
758///
759/// As [`list_xattrs`], and when a fork-stored value's extents cannot be read
760/// or cover less than its logical length. A short value is never returned as
761/// if it were whole.
762pub fn read_xattr(volume: &[u8], cnid: u32, name: &str) -> Result<Option<Vec<u8>>, HfsXattrError> {
763    let Some(loc) = attributes_btree(volume)? else {
764        return Ok(None);
765    };
766    // The attributes B-tree's own CatalogLoc already carries the volume's
767    // allocation block size; re-deriving it from the header would be a second
768    // source of truth for the same number.
769    let block_size = loc.block_size;
770    let mut found = None;
771    walk_leaves(volume, &loc, true, |rec| {
772        if found.is_some() {
773            return Ok(());
774        }
775        // Re-parse rather than reuse list_xattrs: a fork-stored value needs the
776        // record's extents, which the public type deliberately does not carry.
777        let Some(key) = attr_key(rec, cnid)? else {
778            return Ok(());
779        };
780        if key.name != name || key.start_block != 0 {
781            return Ok(());
782        }
783        let body = key.body;
784        found = Some(match be32(&rec[body..body + 4]) {
785            ATTR_INLINE_DATA => inline_value(rec, &key)?,
786            ATTR_FORK_DATA => {
787                let fork = fork_record(rec, &key)?;
788                let bytes = fork_bytes(volume, block_size, &fork).unwrap_or_default();
789                if (bytes.len() as u64) < fork.logical {
790                    return Err(HfsXattrError::Record {
791                        name: Some(key.name),
792                        detail: format!(
793                            "its extents yield {} of its {} bytes; the rest is in kHFSPlusAttrExtents records or past the volume end, and this reader does not assemble it",
794                            bytes.len(),
795                            fork.logical
796                        ),
797                        bytes: record_prefix(rec),
798                    });
799                }
800                bytes
801            }
802            other => return Err(unknown_record_type(rec, key, other)),
803        });
804        Ok(())
805    })?;
806    Ok(found)
807}
808
809/// The parsed key of an attribute record, when it belongs to `cnid`.
810struct AttrKey {
811    name: String,
812    /// Offset of the record BODY (`recordType`), i.e. just past the key.
813    body: usize,
814    /// First allocation block this record describes. Non-zero only on
815    /// `kHFSPlusAttrExtents` continuation records.
816    start_block: u32,
817}
818
819/// Parse `HFSPlusAttrKey`: keyLength(2) pad(2) fileID@4 startBlock@8
820/// attrNameLen@12 attrName@14 (UTF-16 BE).
821///
822/// `Ok(None)` for a record of another file. A key too short to name its file is
823/// an error: it might be this file's, so skipping it could hide an attribute.
824fn attr_key(rec: &[u8], cnid: u32) -> Result<Option<AttrKey>, HfsXattrError> {
825    let damaged = |name: Option<String>, detail: String| HfsXattrError::Record {
826        name,
827        detail,
828        bytes: record_prefix(rec),
829    };
830    if rec.len() < 14 {
831        return Err(damaged(
832            None,
833            format!(
834                "a {}-byte record is too short for its 14-byte key header",
835                rec.len()
836            ),
837        ));
838    }
839    let key_len = be16(&rec[0..2]) as usize;
840    if be32(&rec[4..8]) != cnid {
841        return Ok(None);
842    }
843    let start_block = be32(&rec[8..12]);
844    let name_len = be16(&rec[12..14]) as usize;
845    let name_end = 14 + name_len * 2;
846    let Some(name_bytes) = rec.get(14..name_end) else {
847        return Err(damaged(
848            None,
849            format!(
850                "its {name_len}-character name runs past the {}-byte record",
851                rec.len()
852            ),
853        ));
854    };
855    let name = decode_utf16(name_bytes);
856    let body = 2 + key_len;
857    // Every record body starts with a 4-byte recordType.
858    if body + 4 > rec.len() {
859        return Err(damaged(
860            Some(name),
861            format!(
862                "keyLength {key_len} puts the record body past the {}-byte record",
863                rec.len()
864            ),
865        ));
866    }
867    Ok(Some(AttrKey {
868        name,
869        body,
870        start_block,
871    }))
872}
873
874/// `HFSPlusAttrData`: recordType@0 reserved[2]@4 attrSize@12 attrData@16.
875fn inline_value(rec: &[u8], key: &AttrKey) -> Result<Vec<u8>, HfsXattrError> {
876    let body = key.body;
877    let size = rec.get(body + 12..body + 16).map(|b| be32(b) as usize);
878    match size.and_then(|n| rec.get(body + 16..body + 16 + n)) {
879        Some(v) => Ok(v.to_vec()),
880        None => Err(HfsXattrError::Record {
881            name: Some(key.name.clone()),
882            detail: match size {
883                Some(n) => format!(
884                    "its inline attrSize {n} runs past the {}-byte record",
885                    rec.len()
886                ),
887                None => format!(
888                    "the {}-byte record ends inside its inline-data header",
889                    rec.len()
890                ),
891            },
892            bytes: record_prefix(rec),
893        }),
894    }
895}
896
897/// `HFSPlusAttrForkData`: recordType(4) reserved(4) theFork(80)@8.
898fn fork_record(rec: &[u8], key: &AttrKey) -> Result<Fork, HfsXattrError> {
899    rec.get(key.body + 8..)
900        .and_then(parse_fork)
901        .ok_or_else(|| HfsXattrError::Record {
902            name: Some(key.name.clone()),
903            detail: format!(
904                "the {}-byte record ends inside its 80-byte fork data",
905                rec.len()
906            ),
907            bytes: record_prefix(rec),
908        })
909}
910
911/// A record type this reader does not decode. Reported with the value found
912/// rather than skipped: skipping would present the attribute as absent.
913fn unknown_record_type(rec: &[u8], key: AttrKey, record_type: u32) -> HfsXattrError {
914    HfsXattrError::Record {
915        name: Some(key.name),
916        detail: format!("record type 0x{record_type:08x} is not one this reader decodes"),
917        bytes: record_prefix(rec),
918    }
919}
920
921/// Turn one attributes-B-tree record into an [`HfsXattr`], if it is a listable
922/// attribute belonging to `cnid`.
923fn parse_attr_record(rec: &[u8], cnid: u32) -> Result<Option<HfsXattr>, HfsXattrError> {
924    let Some(key) = attr_key(rec, cnid)? else {
925        return Ok(None);
926    };
927    // A continuation record describes more extents for a fork already listed.
928    if key.start_block != 0 {
929        return Ok(None);
930    }
931    let body = key.body;
932    let value = match be32(&rec[body..body + 4]) {
933        ATTR_INLINE_DATA => HfsXattrValue::Inline(inline_value(rec, &key)?),
934        ATTR_FORK_DATA => HfsXattrValue::Fork {
935            logical: fork_record(rec, &key)?.logical,
936        },
937        other => return Err(unknown_record_type(rec, key, other)),
938    };
939    Ok(Some(HfsXattr {
940        name: key.name,
941        value,
942    }))
943}
944
945/// Decode a big-endian UTF-16 byte slice to a `String` (lossy).
946pub fn decode_utf16(bytes: &[u8]) -> String {
947    let units: Vec<u16> = bytes
948        .chunks_exact(2)
949        .map(|c| u16::from_be_bytes([c[0], c[1]]))
950        .collect();
951    String::from_utf16_lossy(&units)
952}
953
954pub fn be16(b: &[u8]) -> u16 {
955    u16::from_be_bytes([b[0], b[1]])
956}
957pub fn be32(b: &[u8]) -> u32 {
958    u32::from_be_bytes([b[0], b[1], b[2], b[3]])
959}
960
961/// A path-qualified entry produced by [`walk`].
962#[derive(Debug, Clone, PartialEq, Eq)]
963pub struct HfsPathEntry {
964    /// `/`-joined path from the volume root (e.g. `"SUB/NESTED.TXT"`).
965    pub path: String,
966    /// True for a folder.
967    pub is_dir: bool,
968    /// Catalog node ID (CNID).
969    pub cnid: u32,
970}
971
972/// Recursively list every file and folder in an HFS+ volume, depth-first from
973/// the root, returning `/`-joined paths.
974///
975/// Returns `None` if this is not an HFS+ volume.  A visited-CNID set guards
976/// against cycles in a corrupt catalog.
977#[must_use]
978pub fn walk(volume: &[u8]) -> Option<Vec<HfsPathEntry>> {
979    // Confirm this is an HFS+ volume up front so a non-HFS buffer yields None.
980    list_dir(volume, ROOT_FOLDER_CNID)?;
981    let mut out = Vec::new();
982    let mut visited = std::collections::HashSet::new();
983    visited.insert(ROOT_FOLDER_CNID);
984    let mut stack = vec![(ROOT_FOLDER_CNID, String::new())];
985    while let Some((parent, prefix)) = stack.pop() {
986        let Some(entries) = list_dir(volume, parent) else {
987            continue;
988        };
989        for e in entries {
990            let path = if prefix.is_empty() {
991                e.name.clone()
992            } else {
993                format!("{prefix}/{}", e.name)
994            };
995            if e.is_dir && visited.insert(e.cnid) {
996                stack.push((e.cnid, path.clone()));
997            }
998            out.push(HfsPathEntry {
999                path,
1000                is_dir: e.is_dir,
1001                cnid: e.cnid,
1002            });
1003        }
1004    }
1005    Some(out)
1006}
1007
1008#[cfg(test)]
1009mod xattr_record_tests {
1010    //! Damage the extended-attribute readers can only meet below the VFS layer,
1011    //! on hand-built records and nodes too small to stage in the real fixture.
1012    use super::{parse_attr_record, walk_leaves, CatalogLoc, HfsXattrError};
1013
1014    /// A key for CNID 7, startBlock 0, one-character name "a". keyLength 14
1015    /// puts the body (recordType) at byte 16.
1016    fn key_then(record_type: u32, total_len: usize) -> Vec<u8> {
1017        let mut r = vec![0u8; total_len];
1018        r[0..2].copy_from_slice(&14u16.to_be_bytes());
1019        r[4..8].copy_from_slice(&7u32.to_be_bytes());
1020        r[12..14].copy_from_slice(&1u16.to_be_bytes());
1021        r[14..16].copy_from_slice(&u16::from(b'a').to_be_bytes());
1022        r[16..20].copy_from_slice(&record_type.to_be_bytes());
1023        r
1024    }
1025
1026    #[test]
1027    fn an_inline_record_ending_inside_its_header_is_an_error() {
1028        let err = parse_attr_record(&key_then(0x10, 20), 7).unwrap_err();
1029        assert!(
1030            err.to_string()
1031                .contains("ends inside its inline-data header"),
1032            "{err}"
1033        );
1034    }
1035
1036    #[test]
1037    fn a_fork_record_ending_inside_its_fork_data_is_an_error() {
1038        let err = parse_attr_record(&key_then(0x20, 40), 7).unwrap_err();
1039        assert!(err.to_string().contains("80-byte fork data"), "{err}");
1040    }
1041
1042    /// `kHFSPlusAttrExtents` continuations carry a non-zero startBlock and more
1043    /// extents for a fork already listed; listing one would duplicate it.
1044    #[test]
1045    fn a_continuation_record_is_not_listed_as_its_own_attribute() {
1046        let mut r = key_then(0x30, 40);
1047        r[8..12].copy_from_slice(&5u32.to_be_bytes());
1048        assert_eq!(parse_attr_record(&r, 7), Ok(None));
1049    }
1050
1051    /// An empty value is still an attribute: its presence is the evidence.
1052    #[test]
1053    fn an_attribute_with_an_empty_value_is_listed_and_reports_empty() {
1054        let mut r = key_then(0x10, 40); // attrSize 0
1055        r[28..32].copy_from_slice(&0u32.to_be_bytes());
1056        let x = parse_attr_record(&r, 7).unwrap().unwrap();
1057        assert_eq!(x.name, "a");
1058        assert!(x.value.is_empty());
1059        assert!(!super::HfsXattrValue::Fork { logical: 1 }.is_empty());
1060    }
1061
1062    #[test]
1063    fn a_record_of_another_file_is_not_this_files_business() {
1064        assert_eq!(parse_attr_record(&key_then(0x99, 20), 8), Ok(None));
1065    }
1066
1067    /// A node whose record count needs more offset slots than the node has
1068    /// bytes. Every slot the walk can read points at byte 0 or 40, both inside
1069    /// the node, so the count is what fails.
1070    #[test]
1071    fn a_strict_walk_reports_a_record_count_the_node_cannot_hold() {
1072        let mut vol = vec![0u8; 128];
1073        vol[64 + 10..64 + 12].copy_from_slice(&40u16.to_be_bytes());
1074        let loc = CatalogLoc {
1075            cat_base: 0,
1076            node_size: 64,
1077            first_leaf: 1,
1078            block_size: 512,
1079        };
1080        let err = walk_leaves(&vol, &loc, true, |_| Ok(())).unwrap_err();
1081        assert!(
1082            matches!(&err, HfsXattrError::LeafChain { node: 1, detail } if detail.contains("declares 40 records")),
1083            "{err:?}"
1084        );
1085        // The lenient walk keeps its old contract: it stops quietly.
1086        let mut seen = 0;
1087        super::for_each_record(&vol, &loc, |_| seen += 1);
1088        assert_eq!(seen, 32, "every slot that fits is still visited");
1089    }
1090}