Skip to main content

udf_core/
lib.rs

1//! UDF (Universal Disk Format) — detection and file-entry traversal.
2//!
3//! UDF bridge discs carry both ISO 9660 and UDF structures on the same sectors.
4//! The UDF recognition sequence starts at sector 16: each Volume Structure
5//! Descriptor is 2048 bytes with a 5-byte identifier at bytes 1-5.
6//!
7//! Identifiers: "BEA01" (Extended Area Descriptor), "NSR02" or "NSR03"
8//! (OSTA CS0 UDF mark), "TEA01" (Terminating Extended Area Descriptor).
9//! NSR02/NSR03 presence is the definitive UDF indicator.
10//!
11//! # Full UDF traversal
12//!
13//! Descriptor chain: AVDP (LBA 256) → VDS → Partition Descriptor (partition
14//! start LBA) + Logical Volume Descriptor (FSD location) → File Set Descriptor
15//! (root dir FE LBA) → File Entry → File Identifier Descriptors.
16//!
17//! All physical LBAs satisfy: `phys_lba = partition_start + logical_block_num`.
18
19// Tests deliberately unwrap/expect on known-good fixtures; the panic-free denies
20// apply only to production code that parses untrusted images.
21#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
22
23use safe_read::{le_u32, le_u64};
24use std::io::{self, Read, Seek, SeekFrom};
25
26#[cfg(feature = "vfs")]
27pub mod vfs;
28pub mod xattr;
29pub use xattr::{parse_extended_attributes, UdfEaKind, UdfExtendedAttribute};
30
31#[cfg(test)]
32pub(crate) mod test_support;
33
34// ── ECMA-167 / UDF tag identifiers ───────────────────────────────────────────
35
36pub const TAG_AVDP: u16 = 2;
37pub const TAG_PD: u16 = 5;
38pub const TAG_LVD: u16 = 6;
39pub const TAG_TERM: u16 = 8;
40pub const TAG_FSD: u16 = 256;
41pub const TAG_FID: u16 = 257;
42pub const TAG_FE: u16 = 260;
43/// Some UDF implementations (e.g. older genisoimage) write 261 for File Entry.
44pub const TAG_FE_ALT: u16 = 261;
45pub const TAG_EFE: u16 = 266;
46
47// FID File Characteristics bits
48const FC_DIRECTORY: u8 = 0x02;
49const FC_PARENT: u8 = 0x08;
50
51// ICB allocation type (FE flags bits 0-2)
52const ALLOC_SHORT: u16 = 0;
53const ALLOC_LONG: u16 = 1;
54const ALLOC_INLINE: u16 = 3;
55
56// Extent type bits 30-31 of extent_length field
57const EXTENT_RECORDED: u32 = 0x0000_0000; // 0b00 in bits 30-31
58
59// ── Logical block size ────────────────────────────────────────────────────────
60
61/// Largest logical block size we read into a stack sector buffer.
62pub const MAX_BLOCK_SIZE: usize = 4096;
63
64/// Candidate UDF logical block sizes, most-common first. Optical media (CD/DVD/
65/// BD) use 2048; hard-disk and USB UDF use 512; Advanced-Format media use 4096.
66const BLOCK_SIZE_CANDIDATES: [u32; 4] = [2048, 512, 1024, 4096];
67
68// ── Public types ──────────────────────────────────────────────────────────────
69
70/// A single entry returned by UDF directory traversal.
71#[derive(Debug, Clone)]
72pub struct UdfFileEntry {
73    /// Decoded filename (OSTA CS0: UTF-8 or UTF-16BE).
74    pub name: String,
75    /// True if this entry is a directory.
76    pub is_dir: bool,
77    /// File size in bytes (Information Length from FE).
78    pub size: u64,
79    /// Physical LBA of the File Entry descriptor sector.
80    pub fe_lba: u32,
81}
82
83// ── Partition map kinds (ECMA-167 §10.7, OSTA UDF §2.2.8) ────────────────────
84
85/// The kind of partition referenced by the UDF logical volume's file set.
86///
87/// `Physical` (Type 1) partitions resolve as `partition_start + logical_block`.
88/// `Virtual` (VAT), `Sparable` (defect-managed), and `Metadata` (UDF 2.50+,
89/// used by Blu-ray) are Type 2 partitions whose block resolution requires
90/// additional structures this crate does not yet follow — they are detected
91/// and reported so a forensic tool fails loudly rather than mis-reading.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94pub enum UdfPartitionKind {
95    /// Type 1 physical partition.
96    Physical,
97    /// Type 2 `*UDF Virtual Partition` (VAT-mapped, packet-written media).
98    Virtual,
99    /// Type 2 `*UDF Sparable Partition` (defect management).
100    Sparable,
101    /// Type 2 `*UDF Metadata Partition` (UDF 2.50+, Blu-ray).
102    Metadata,
103    /// Type 2 partition with an unrecognised identifier.
104    Unknown,
105}
106
107// ── Internal UDF state ────────────────────────────────────────────────────────
108
109#[derive(Debug)]
110pub struct UdfState {
111    pub partition_start: u32,
112    pub root_fe_lba: u32,
113    pub partition_kind: UdfPartitionKind,
114    pub partition_map_count: u32,
115    /// The medium's logical block size in bytes (512, 1024, 2048, or 4096),
116    /// detected from the Anchor Volume Descriptor Pointer location rather than
117    /// assumed — optical UDF is 2048-byte, but hard-disk media is 512-byte.
118    pub block_size: u32,
119    /// Physical LBA of the File Set Descriptor (`partition_start` + its logical
120    /// block). The findings analyzer reads its recording time and validates its
121    /// descriptor tag.
122    pub fsd_lba: u32,
123    /// Logical sector where the Volume Descriptor Sequence begins (from the
124    /// AVDP). The findings analyzer re-walks the VDS to validate each
125    /// descriptor's tag.
126    pub vds_loc: u32,
127    /// Length of the Volume Descriptor Sequence in whole logical blocks.
128    pub vds_len_sectors: u32,
129}
130
131// ── UDF detection (existing public API) ──────────────────────────────────────
132
133/// True if the image has a UDF recognition sequence (NSR02 or NSR03).
134///
135/// Scans volume structure descriptors starting at LBA 16, up to LBA 32.
136pub fn detect_udf<R: Read + Seek>(reader: &mut R) -> bool {
137    let mut buf = [0u8; 6];
138    for lba in 16u64..32 {
139        let pos = lba * 2048 + 1;
140        if reader.seek(SeekFrom::Start(pos)).is_err() {
141            break;
142        }
143        if reader.read_exact(&mut buf).is_err() {
144            break;
145        }
146        let id = &buf[..5];
147        if id == b"NSR02" || id == b"NSR03" {
148            return true;
149        }
150        if id == b"TEA01" {
151            break;
152        }
153    }
154    false
155}
156
157// ── UDF traversal (new internal API) ─────────────────────────────────────────
158
159/// Try to parse the AVDP → VDS → FSD chain, returning state needed for
160/// directory traversal. Returns `None` if the image lacks a valid UDF structure.
161///
162/// Lenient wrapper over [`parse_udf_state_checked`]: a real seek/read I/O error
163/// reading the anchor/VDS/FSD is folded into `None`, indistinguishable from a
164/// structural "not UDF". Use [`parse_udf_state_checked`] when a truncated or
165/// unreadable image must be told apart from a genuine non-UDF source.
166pub fn parse_udf_state<R: Read + Seek>(reader: &mut R) -> Option<UdfState> {
167    parse_udf_state_checked(reader).ok().flatten()
168}
169
170/// Parse the AVDP → VDS → FSD bootstrap chain, distinguishing a real read
171/// failure from a structural negative.
172///
173/// - `Err(io)` — a seek/read I/O error reading the anchor (LBA 256), the Volume
174///   Descriptor Sequence, or the File Set Descriptor. This includes
175///   [`io::ErrorKind::UnexpectedEof`] when the image is truncated before the
176///   anchor, which is itself forensically suspicious and must surface rather
177///   than masquerade as "not UDF".
178/// - `Ok(None)` — every read succeeded but the structure is not valid UDF (the
179///   anchor tag is not an AVDP, or the descriptor chain is absent/incoherent).
180///   This is the legitimate "not UDF" case.
181/// - `Ok(Some(state))` — a valid UDF structure.
182pub fn parse_udf_state_checked<R: Read + Seek>(
183    reader: &mut R,
184) -> Result<Option<UdfState>, io::Error> {
185    let Some(block_size) = detect_block_size(reader)? else {
186        return Ok(None);
187    };
188    let Some((vds_loc, vds_len)) = read_avdp_checked(reader, block_size)? else {
189        return Ok(None); // cov:unreachable: detect_block_size already validated the AVDP tag at LBA 256
190    };
191    let Some(vds) = read_vds_checked(reader, block_size, vds_loc, vds_len)? else {
192        return Ok(None);
193    };
194    let Some(root_fe_lba) = read_fsd_checked(reader, block_size, vds.fsd_lba, vds.partition_start)?
195    else {
196        return Ok(None);
197    };
198    Ok(Some(UdfState {
199        partition_start: vds.partition_start,
200        root_fe_lba,
201        partition_kind: vds.partition_kind,
202        partition_map_count: vds.map_count,
203        block_size,
204        fsd_lba: vds.fsd_lba,
205        vds_loc,
206        vds_len_sectors: (vds_len as usize).div_ceil(block_size as usize) as u32,
207    }))
208}
209
210/// Resolved Volume Descriptor Sequence information.
211struct VdsInfo {
212    partition_start: u32,
213    fsd_lba: u32,
214    partition_kind: UdfPartitionKind,
215    map_count: u32,
216}
217
218/// A parsed partition map entry from the Logical Volume Descriptor.
219struct PartitionMap {
220    kind: UdfPartitionKind,
221    /// Partition number (Type 1 only); `None` for Type 2 maps.
222    partition_number: Option<u16>,
223}
224
225/// Classify a Type 2 partition map by scanning its identifier region for the
226/// OSTA UDF entity strings.
227fn classify_type2(map: &[u8]) -> UdfPartitionKind {
228    let scan = |needle: &[u8]| map.windows(needle.len()).any(|w| w == needle);
229    if scan(b"*UDF Metadata Partition") {
230        UdfPartitionKind::Metadata
231    } else if scan(b"*UDF Virtual Partition") {
232        UdfPartitionKind::Virtual
233    } else if scan(b"*UDF Sparable Partition") {
234        UdfPartitionKind::Sparable
235    } else {
236        UdfPartitionKind::Unknown
237    }
238}
239
240/// Parse the partition maps from a Logical Volume Descriptor sector.
241///
242/// LVD (ECMA-167 §10.6): `N_PM` at BP 268, Map Table Length at BP 264, maps at
243/// BP 440.  Each map: `[type(1)][length(1)]…`; Type 1 carries the partition
244/// number at RBP 4; Type 2 is identified by its embedded entity string.
245fn parse_partition_maps(lvd: &[u8]) -> Vec<PartitionMap> {
246    let n_pm = le_u32(lvd, 268) as usize;
247    let mt_l = le_u32(lvd, 264) as usize;
248    let maps_end = (440 + mt_l).min(lvd.len());
249    let mut out = Vec::new();
250    let mut off = 440;
251    while out.len() < n_pm && off + 2 <= maps_end {
252        let map_type = lvd[off];
253        let map_len = lvd[off + 1] as usize;
254        if map_len < 2 || off + map_len > maps_end {
255            break;
256        }
257        let map = &lvd[off..off + map_len];
258        let pm = match map_type {
259            1 if map_len >= 6 => PartitionMap {
260                kind: UdfPartitionKind::Physical,
261                partition_number: Some(u16::from_le_bytes([map[4], map[5]])),
262            },
263            2 => PartitionMap {
264                kind: classify_type2(map),
265                partition_number: None,
266            },
267            _ => PartitionMap {
268                kind: UdfPartitionKind::Unknown,
269                partition_number: None,
270            },
271        };
272        out.push(pm);
273        off += map_len;
274    }
275    out
276}
277
278/// Read all non-parent File Identifier Descriptors from the directory whose
279/// File Entry resides at `dir_fe_lba`, returning one `UdfFileEntry` per child.
280pub fn read_dir_at_lba<R: Read + Seek>(
281    reader: &mut R,
282    block_size: u32,
283    partition_start: u32,
284    dir_fe_lba: u32,
285) -> Option<Vec<UdfFileEntry>> {
286    let dir_data = read_fe_data(reader, block_size, partition_start, dir_fe_lba)?;
287    Some(parse_fids(reader, block_size, partition_start, &dir_data))
288}
289
290/// Read the extended attributes of the File Entry at `fe_lba`.
291///
292/// Returns `None` when the LBA is not a File Entry or its EA space is
293/// malformed; an empty vector when the entry simply has none (`L_EA == 0`),
294/// which is the ordinary case.
295///
296/// The EA area's offset depends on the entry form, exactly as in
297/// [`read_fe_data`]: a base File Entry puts `L_EA` at +168 and the area at
298/// +176, while an Extended File Entry's extra 40 bytes move them to +208 and
299/// +216. Reusing the wrong pair silently reads allocation descriptors as
300/// attributes.
301pub fn read_fe_extended_attributes<R: Read + Seek>(
302    reader: &mut R,
303    block_size: u32,
304    fe_lba: u32,
305) -> Option<Vec<xattr::UdfExtendedAttribute>> {
306    let mut sector = [0u8; MAX_BLOCK_SIZE];
307    let sector = &mut sector[..block_size as usize];
308    seek_read(reader, u64::from(fe_lba) * u64::from(block_size), sector)?;
309
310    let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
311    let is_efe = tag_ident == TAG_EFE;
312    if tag_ident != TAG_FE && tag_ident != TAG_FE_ALT && !is_efe {
313        return None;
314    }
315    let (ea_off, header) = if is_efe {
316        (208usize, 216usize)
317    } else {
318        (168usize, 176usize)
319    };
320    let ea_len = le_u32(sector, ea_off) as usize;
321    if ea_len == 0 {
322        return Some(Vec::new());
323    }
324    let ea = sector.get(header..header.checked_add(ea_len)?)?;
325    xattr::parse_extended_attributes(ea)
326}
327
328/// Read the data extent of the File Entry at `fe_lba`.
329pub fn read_fe_data<R: Read + Seek>(
330    reader: &mut R,
331    block_size: u32,
332    partition_start: u32,
333    fe_lba: u32,
334) -> Option<Vec<u8>> {
335    let mut sector = [0u8; MAX_BLOCK_SIZE];
336    let sector = &mut sector[..block_size as usize];
337    seek_read(reader, u64::from(fe_lba) * u64::from(block_size), sector)?;
338
339    let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
340    let is_efe = tag_ident == TAG_EFE;
341    if tag_ident != TAG_FE && tag_ident != TAG_FE_ALT && !is_efe {
342        return None;
343    }
344
345    let icb_flags = u16::from_le_bytes([sector[34], sector[35]]);
346    let alloc_type = icb_flags & 0x0007;
347    let info_len = le_u64(sector, 56);
348
349    // Base File Entry (ECMA-167 4/14.9): L_EA @168, L_AD @172, area @176.
350    // Extended File Entry (4/14.17) inserts ObjectSize(8), CreationTime(12),
351    // StreamDirectoryICB(16), and Reserved(4) — 40 bytes total — ahead of the
352    // extended-attr / alloc-descriptor lengths, so L_EA @208, L_AD @212, area
353    // @216. (The pre-EFE value 176/180/184 assumed only the 8-byte ObjectSize
354    // insertion and is wrong for a real EFE — verified against a real mkudffs
355    // Extended-File-Entry root directory.)
356    let (ea_off, ad_off, header) = if is_efe {
357        (208usize, 212usize, 216usize)
358    } else {
359        (168usize, 172usize, 176usize)
360    };
361
362    if ad_off + 4 > sector.len() {
363        return None; // cov:unreachable: ea/ad offsets (<=216) fit any supported block (>=512)
364    }
365    let ea_len = le_u32(sector, ea_off) as usize;
366    let ad_len = le_u32(sector, ad_off) as usize;
367
368    let ad_start = header + ea_len;
369    let ad_end = ad_start + ad_len;
370    if ad_end > sector.len() {
371        return None;
372    }
373    let ad_area = sector[ad_start..ad_end].to_vec();
374
375    match alloc_type {
376        ALLOC_INLINE => Some(ad_area[..info_len.min(ad_area.len() as u64) as usize].to_vec()),
377        ALLOC_SHORT => read_extents_short(reader, block_size, partition_start, &ad_area, info_len),
378        ALLOC_LONG => read_extents_long(reader, block_size, partition_start, &ad_area, info_len),
379        _ => None,
380    }
381}
382
383// ── Private helpers ───────────────────────────────────────────────────────────
384
385/// Detect the medium's logical block size by locating the Anchor Volume
386/// Descriptor Pointer (ECMA-167 §3 / OSTA UDF §2.2.3): the AVDP sits at logical
387/// sector 256, so for each candidate block size `bs` the anchor is at byte
388/// `256 * bs`. A candidate is accepted when that sector carries the AVDP tag
389/// identifier (2) AND the descriptor tag's recorded location field equals 256 —
390/// the location check rules out a stray `0x0002` at the wrong probe offset.
391///
392/// Truncation handling mirrors [`read_avdp_checked`]: if *no* candidate's anchor
393/// was even large enough to read (every probe hit `UnexpectedEof`), the image is
394/// truncated before any possible AVDP and that surfaces as `Err`; if some probe
395/// read but none matched, the source is readable-but-not-UDF (`Ok(None)`).
396fn detect_block_size<R: Read + Seek>(reader: &mut R) -> Result<Option<u32>, io::Error> {
397    let mut tag = [0u8; 16];
398    let mut last_eof: Option<io::Error> = None;
399    let mut any_read_ok = false;
400    for bs in BLOCK_SIZE_CANDIDATES {
401        match seek_read_checked(reader, 256 * u64::from(bs), &mut tag) {
402            Ok(()) => {
403                any_read_ok = true;
404                let tag_ident = u16::from_le_bytes([tag[0], tag[1]]);
405                let tag_location = le_u32(&tag, 12);
406                if tag_ident == TAG_AVDP && tag_location == 256 {
407                    return Ok(Some(bs));
408                }
409            }
410            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => last_eof = Some(e),
411            Err(e) => return Err(e),
412        }
413    }
414    if !any_read_ok {
415        if let Some(e) = last_eof {
416            return Err(e);
417        }
418    }
419    Ok(None)
420}
421
422/// Parse the AVDP at logical sector 256 (`256 * block_size` bytes). `Err` on a
423/// read I/O failure, `Ok(None)` when the anchor read succeeds but is not an
424/// AVDP, `Ok(Some((vds_loc, vds_len)))` when the anchor is valid.
425fn read_avdp_checked<R: Read + Seek>(
426    reader: &mut R,
427    block_size: u32,
428) -> Result<Option<(u32, u32)>, io::Error> {
429    let mut sector = [0u8; MAX_BLOCK_SIZE];
430    let sector = &mut sector[..block_size as usize];
431    seek_read_checked(reader, 256 * u64::from(block_size), sector)?;
432    if u16::from_le_bytes([sector[0], sector[1]]) != TAG_AVDP {
433        return Ok(None);
434    }
435    let vds_len = le_u32(sector, 16);
436    let vds_loc = le_u32(sector, 20);
437    Ok(Some((vds_loc, vds_len)))
438}
439
440/// Scan the Volume Descriptor Sequence: collect every Partition Descriptor
441/// (partition number → starting location) and the Logical Volume Descriptor
442/// (file-set location, partition reference, and partition maps), then resolve
443/// the file set's partition through its map.
444fn read_vds_checked<R: Read + Seek>(
445    reader: &mut R,
446    block_size: u32,
447    vds_loc: u32,
448    vds_len: u32,
449) -> Result<Option<VdsInfo>, io::Error> {
450    use std::collections::HashMap;
451    let sectors = (vds_len as usize).div_ceil(block_size as usize);
452
453    // partition number → starting location (physical LBA).
454    let mut pd_start: HashMap<u16, u32> = HashMap::new();
455    let mut fsd_lbn: Option<u32> = None;
456    let mut fsd_part_ref: u16 = 0;
457    let mut maps: Vec<PartitionMap> = Vec::new();
458
459    for i in 0..sectors {
460        let mut sector = [0u8; MAX_BLOCK_SIZE];
461        let sector = &mut sector[..block_size as usize];
462        seek_read_checked(
463            reader,
464            (u64::from(vds_loc) + i as u64) * u64::from(block_size),
465            sector,
466        )?;
467        let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
468        match tag_ident {
469            TAG_PD => {
470                let part_num = u16::from_le_bytes([sector[22], sector[23]]);
471                let psl = le_u32(sector, 188);
472                pd_start.insert(part_num, psl);
473            }
474            TAG_LVD => {
475                // LV Contents Use long_ad at offset 248: extent_length [248..252],
476                // logical_block_num [252..256], partition_reference [256..258].
477                fsd_lbn = Some(le_u32(sector, 252));
478                fsd_part_ref = u16::from_le_bytes([sector[256], sector[257]]);
479                maps = parse_partition_maps(sector);
480            }
481            TAG_TERM | 0 => break,
482            _ => {}
483        }
484    }
485
486    // Reads all succeeded; a missing LVD / unresolvable partition is structural.
487    let Some(fsd) = fsd_lbn else {
488        return Ok(None);
489    };
490    let map_count = maps.len() as u32;
491
492    // Resolve the file set's partition via the referenced partition map.
493    let referenced = maps.get(fsd_part_ref as usize);
494    let kind = referenced.map_or(UdfPartitionKind::Unknown, |m| m.kind);
495
496    // Type 1: resolve the partition start from the map's partition number.
497    // Type 2 (Virtual/Sparable/Metadata): block resolution needs structures we
498    // do not yet follow — fall back to the first physical partition so detection
499    // still works, and report the kind so callers know reads may be incomplete.
500    let partition_start = referenced
501        .and_then(|m| m.partition_number)
502        .and_then(|pn| pd_start.get(&pn).copied())
503        .or_else(|| pd_start.values().min().copied());
504    let Some(partition_start) = partition_start else {
505        return Ok(None);
506    };
507
508    // Both operands are u32 fields from the descriptors, so their sum can leave
509    // the address space. A wrapped LBA would point at a real but wrong block --
510    // a confidently incorrect File Set Descriptor -- so an overflow means the
511    // descriptor pair does not describe a location and there is nothing to
512    // report.
513    let Some(fsd_lba) = partition_start.checked_add(fsd) else {
514        return Ok(None);
515    };
516
517    Ok(Some(VdsInfo {
518        partition_start,
519        fsd_lba,
520        partition_kind: kind,
521        map_count,
522    }))
523}
524
525/// Parse FSD at `fsd_lba` to find the root directory FE logical block number.
526/// `Err` on a read I/O failure, `Ok(None)` when the FSD read succeeds but its
527/// tag is not an FSD, `Ok(Some(root_fe_lba))` when the FSD is valid.
528fn read_fsd_checked<R: Read + Seek>(
529    reader: &mut R,
530    block_size: u32,
531    fsd_lba: u32,
532    partition_start: u32,
533) -> Result<Option<u32>, io::Error> {
534    let mut sector = [0u8; MAX_BLOCK_SIZE];
535    let sector = &mut sector[..block_size as usize];
536    seek_read_checked(reader, u64::from(fsd_lba) * u64::from(block_size), sector)?;
537    if u16::from_le_bytes([sector[0], sector[1]]) != TAG_FSD {
538        return Ok(None);
539    }
540    // FSD field sizes (ECMA-167 Table 20):
541    //   Tag(16) + RecordingDate(12) + Interchange/Charset fields(28) +
542    //   LV Ident CharSet(64) + LV Identifier(128) + FS CharSet(64) +
543    //   FS Identifier(32) + Copyright FI(32) + Abstract FI(32) = 408 bytes.
544    // Root Directory ICB (long_ad) starts at offset 400:
545    //   extent_length [400..404], logical_block_num [404..408]
546    let lbn = le_u32(sector, 404);
547    Ok(Some(partition_start + lbn))
548}
549
550/// Detect whether FIDs in this directory data use a standard 16-byte ECMA-167 tag
551/// or an extended 18-byte tag written by some UDF tools.
552///
553/// Some implementations append 2 extra bytes after the standard tag before the
554/// FID body, making all field offsets shift by 2. Detection heuristic: read the
555/// ICB logical block number at both candidate positions and use whichever gives a
556/// plausible value (< 65536, fitting discs up to ~128 GB).
557fn detect_fid_tag_size(data: &[u8]) -> usize {
558    let mut off = 0;
559    while off + 28 <= data.len() {
560        let ti = u16::from_le_bytes([data[off], data[off + 1]]);
561        if ti == TAG_FID {
562            // Keep the length guards: the "too short" fallback is `u32::MAX`
563            // (which fails the `< 0x10000` plausibility test), NOT 0 — a bare
564            // 0-returning read would wrongly make a truncated tail look valid.
565            let lbn16 = if off + 26 <= data.len() {
566                le_u32(data, off + 22)
567            } else {
568                u32::MAX
569            };
570            let lbn18 = if off + 28 <= data.len() {
571                le_u32(data, off + 24)
572            } else {
573                u32::MAX
574            };
575            if lbn16 < 0x10000 {
576                return 16;
577            }
578            if lbn18 < 0x10000 {
579                return 18;
580            }
581            return 16; // can't determine; fall back to standard
582        }
583        off += 4;
584    }
585    16
586}
587
588/// Parse File Identifier Descriptors from raw directory data.
589fn parse_fids<R: Read + Seek>(
590    reader: &mut R,
591    block_size: u32,
592    partition_start: u32,
593    data: &[u8],
594) -> Vec<UdfFileEntry> {
595    // Some UDF tools write an extra 2 bytes after the standard 16-byte tag.
596    // tag_size is 16 (standard) or 18 (extended); body fields follow at tag_size.
597    let tag_size = detect_fid_tag_size(data);
598    let min_fid = tag_size + 20; // tag + chars(1)+L_FI(1)+ICB(16)+L_IU(2)
599
600    let mut entries = Vec::new();
601    let mut off = 0;
602
603    while off + min_fid <= data.len() {
604        let tag_ident = u16::from_le_bytes([data[off], data[off + 1]]);
605        if tag_ident != TAG_FID {
606            // Advance 4 bytes to stay aligned; skip padding or unknown tags.
607            off += 4;
608            continue;
609        }
610
611        // CRC_len (at tag[10..12]) gives the true body extent from byte 16.
612        let crc_len = u16::from_le_bytes([data[off + 10], data[off + 11]]) as usize;
613        let fid_advance = ((16 + crc_len + 3) & !3).max(min_fid);
614        if off + fid_advance > data.len() {
615            break;
616        }
617
618        let file_chars = data[off + tag_size];
619        let file_id_len = data[off + tag_size + 1] as usize;
620        // ICB long_ad: extent_length at body[2..6], lbn at body[6..10]
621        let icb_lbn = if off + tag_size + 10 <= data.len() {
622            le_u32(data, off + tag_size + 6)
623        } else {
624            // cov:unreachable: loop guard `off + min_fid <= len` with min_fid = tag_size + 20
625            off += fid_advance.max(4);
626            continue;
627        };
628        let impl_use_len = if off + tag_size + 20 <= data.len() {
629            u16::from_le_bytes([data[off + tag_size + 18], data[off + tag_size + 19]]) as usize
630        } else {
631            // cov:unreachable: loop guard `off + min_fid <= len` with min_fid = tag_size + 20
632            off += fid_advance.max(4);
633            continue;
634        };
635
636        if file_chars & FC_PARENT == 0 {
637            let is_dir = file_chars & FC_DIRECTORY != 0;
638            // The name-field bounds are header-derived too. Saturating is right
639            // here rather than skipping: an out-of-range span clamps to the end
640            // of the buffer, and the `id_end > id_start` test below then leaves
641            // the name empty instead of decoding anything.
642            let id_start = off
643                .saturating_add(tag_size)
644                .saturating_add(20)
645                .saturating_add(impl_use_len);
646            let id_end = id_start.saturating_add(file_id_len).min(data.len());
647            let name = if id_end > id_start {
648                decode_osta_cs0(&data[id_start..id_end])
649            } else {
650                String::new()
651            };
652
653            // Same hazard as the FSD address above, per directory entry. Both
654            // operands are u32 from the image, so their sum can leave the
655            // address space; a wrapped LBA would send the File Entry read at a
656            // real but wrong block and report a confidently incorrect size.
657            //
658            // Dropping the entry rather than `continue`-ing is deliberate: the
659            // loop advances `off` below this block, so skipping the iteration
660            // would leave the cursor where it was and spin forever on the same
661            // descriptor.
662            if let Some(fe_lba) = partition_start.checked_add(icb_lbn) {
663                // Read the FE to get the canonical file size.
664                let size = read_fe_info_len(reader, block_size, fe_lba).unwrap_or(0);
665
666                entries.push(UdfFileEntry {
667                    name,
668                    is_dir,
669                    size,
670                    fe_lba,
671                });
672            }
673        }
674
675        off += fid_advance.max(4);
676    }
677    entries
678}
679
680/// Read the Information Length (file size) from a File Entry at `fe_lba`.
681fn read_fe_info_len<R: Read + Seek>(reader: &mut R, block_size: u32, fe_lba: u32) -> Option<u64> {
682    let mut sector = [0u8; MAX_BLOCK_SIZE];
683    let sector = &mut sector[..block_size as usize];
684    seek_read(reader, u64::from(fe_lba) * u64::from(block_size), sector)?;
685    let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
686    if tag_ident != TAG_FE && tag_ident != TAG_FE_ALT && tag_ident != TAG_EFE {
687        return None;
688    }
689    Some(le_u64(sector, 56))
690}
691
692/// Read the ICB Tag File Type of the File Entry at `fe_lba` (ECMA-167 4/14.6.6):
693/// the descriptor tag is 16 bytes, the ICB Tag follows it, and its File Type
694/// field sits at ICB-Tag offset 11 (FE offset 27). `4` = directory, `5` = a
695/// regular file. `None` when the sector is not a File Entry / Extended File
696/// Entry, so a non-FE LBA passed to a directory op is told apart from a file.
697///
698/// Used by the `vfs` adapter to classify an arbitrary File Entry LBA.
699#[cfg(feature = "vfs")]
700pub(crate) fn read_fe_file_type<R: Read + Seek>(
701    reader: &mut R,
702    block_size: u32,
703    fe_lba: u32,
704) -> Option<u8> {
705    let mut sector = [0u8; MAX_BLOCK_SIZE];
706    let sector = &mut sector[..block_size as usize];
707    seek_read(reader, u64::from(fe_lba) * u64::from(block_size), sector)?;
708    let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
709    if tag_ident != TAG_FE && tag_ident != TAG_FE_ALT && tag_ident != TAG_EFE {
710        return None;
711    }
712    sector.get(27).copied()
713}
714
715/// ECMA-167 ICB Tag File Type for a directory (4/14.6.6).
716#[cfg(feature = "vfs")]
717pub(crate) const FILE_TYPE_DIRECTORY: u8 = 4;
718
719/// ECMA-167 ICB Tag File Type for a regular file — a random-access byte
720/// sequence (4/14.6.6).
721#[cfg(feature = "vfs")]
722pub(crate) const FILE_TYPE_REGULAR: u8 = 0x05;
723
724/// ECMA-167 ICB Tag File Type for a symbolic link (4/14.6.6).
725#[cfg(feature = "vfs")]
726pub(crate) const FILE_TYPE_LINK: u8 = 0x0c;
727
728/// ECMA-167 ICB Tag File Type for a block special device (4/14.6.6).
729#[cfg(feature = "vfs")]
730pub(crate) const FILE_TYPE_BLOCK_DEVICE: u8 = 0x06;
731
732/// ECMA-167 ICB Tag File Type for a character special device (4/14.6.6).
733#[cfg(feature = "vfs")]
734pub(crate) const FILE_TYPE_CHAR_DEVICE: u8 = 0x07;
735
736/// ECMA-167 ICB Tag File Type for a FIFO / named pipe (4/14.6.6).
737#[cfg(feature = "vfs")]
738pub(crate) const FILE_TYPE_FIFO: u8 = 0x09;
739
740/// ECMA-167 ICB Tag File Type for a socket (4/14.6.6).
741#[cfg(feature = "vfs")]
742pub(crate) const FILE_TYPE_SOCKET: u8 = 0x0a;
743
744/// Collect data from short allocation descriptors (8 bytes each).
745fn read_extents_short<R: Read + Seek>(
746    reader: &mut R,
747    block_size: u32,
748    partition_start: u32,
749    ad_area: &[u8],
750    total_len: u64,
751) -> Option<Vec<u8>> {
752    let mut data = Vec::new();
753    let mut pos = 0;
754    while pos + 8 <= ad_area.len() && (data.len() as u64) < total_len {
755        let len_raw = le_u32(ad_area, pos);
756        let ext_pos = le_u32(ad_area, pos + 4);
757        let ext_type = len_raw >> 30;
758        let ext_len = (len_raw & 0x3FFF_FFFF) as usize;
759        if ext_type == (EXTENT_RECORDED >> 30) && ext_len > 0 {
760            let phys = (u64::from(partition_start) + u64::from(ext_pos)) * u64::from(block_size);
761            read_extent(reader, block_size, phys, ext_len, total_len, &mut data)?;
762        }
763        pos += 8;
764    }
765    data.truncate(total_len as usize);
766    Some(data)
767}
768
769/// Collect data from long allocation descriptors (16 bytes each).
770fn read_extents_long<R: Read + Seek>(
771    reader: &mut R,
772    block_size: u32,
773    partition_start: u32,
774    ad_area: &[u8],
775    total_len: u64,
776) -> Option<Vec<u8>> {
777    let mut data = Vec::new();
778    let mut pos = 0;
779    while pos + 16 <= ad_area.len() && (data.len() as u64) < total_len {
780        let len_raw = le_u32(ad_area, pos);
781        let lbn = le_u32(ad_area, pos + 4);
782        let ext_type = len_raw >> 30;
783        let ext_len = (len_raw & 0x3FFF_FFFF) as usize;
784        if ext_type == (EXTENT_RECORDED >> 30) && ext_len > 0 {
785            let phys = (u64::from(partition_start) + u64::from(lbn)) * u64::from(block_size);
786            read_extent(reader, block_size, phys, ext_len, total_len, &mut data)?;
787        }
788        pos += 16;
789    }
790    data.truncate(total_len as usize);
791    Some(data)
792}
793
794/// Read `ext_len` bytes from `byte_pos`, appending to `data` up to `total_len`.
795fn read_extent<R: Read + Seek>(
796    reader: &mut R,
797    block_size: u32,
798    byte_pos: u64,
799    ext_len: usize,
800    total_len: u64,
801    data: &mut Vec<u8>,
802) -> Option<()> {
803    let bs = block_size as usize;
804    let sectors = ext_len.div_ceil(bs);
805    for i in 0..sectors {
806        // `ext_len` is image-controlled and may run far past the recorded data
807        // (up to 1 GiB per descriptor); stop once `total_len` is satisfied.
808        let remaining = total_len.saturating_sub(data.len() as u64) as usize;
809        if remaining == 0 {
810            break;
811        }
812        let mut sector = [0u8; MAX_BLOCK_SIZE];
813        let sector = &mut sector[..bs];
814        seek_read(reader, byte_pos + i as u64 * u64::from(block_size), sector)?;
815        let sector_bytes = (ext_len - i * bs).min(bs);
816        let take = sector_bytes.min(remaining);
817        data.extend_from_slice(&sector[..take]);
818    }
819    Some(())
820}
821
822/// Decode an OSTA CS0 encoded identifier: first byte is compression ID
823/// (8 = UTF-8, 16 = UTF-16BE), remainder is character data.
824fn decode_osta_cs0(bytes: &[u8]) -> String {
825    if bytes.is_empty() {
826        return String::new();
827    }
828    let comp_id = bytes[0];
829    let payload = &bytes[1..];
830    // 16 = UTF-16BE; compression ID 8 (UTF-8) and any other value decode as
831    // UTF-8 lossy (the OSTA CS0 default path).
832    if comp_id == 16 {
833        let pairs: Vec<u16> = payload
834            .chunks_exact(2)
835            .map(|c| u16::from_be_bytes([c[0], c[1]]))
836            .collect();
837        String::from_utf16_lossy(&pairs)
838    } else {
839        String::from_utf8_lossy(payload).into_owned()
840    }
841}
842
843/// Decode a UDF symbolic link's `PATH_COMPONENT` record chain (ECMA-167
844/// 4/14.16.2, OSTA UDF 2.01 §2.2.8) into its target path, following the Linux
845/// kernel's `udf_pc_to_char` semantics (fs/udf/symlink.c):
846///
847/// - Record: `[componentType: u8, lengthComponentIdent: u8,
848///   componentFileVersionNum: u16le, componentIdent[length]]` — a 4-byte
849///   header (the kernel's `__le16 componentFileVersionNum`).
850/// - Type 1 (root): a non-empty record is a media-specific agreed location
851///   the originator and receiver must interpret. The kernel's `break` leaves
852///   the `switch`, not the loop, so it steps over the identifier and keeps
853///   walking; an empty record falls through to type 2 and writes `/`.
854/// - Type 2 (parent): resets the target to the root (`/`).
855/// - Type 3 (`..`): writes `../`.
856/// - Type 4 (`.`): writes `./`.
857/// - Type 5 (name): an OSTA CS0-encoded identifier (compression ID 8 or 16),
858///   followed by `/`.
859/// - Unknown types: the kernel's `switch` has no `default:` arm, so only the
860///   4-byte header is consumed and the identifier bytes are read as the next
861///   record header. Skipping the identifier too would resynchronize the walk
862///   differently from the mount, which is the ground truth to reproduce.
863///
864/// The trailing separator is trimmed (the kernel's `p[-1] = '\0'`), so
865/// `..` + `README.txt` yields `../README.txt`. Hostile record chains cannot
866/// panic: out-of-range lengths stop the walk at the buffer end.
867pub fn decode_symlink_target(data: &[u8]) -> String {
868    let mut out = String::new();
869    let mut elen = 0usize;
870    while elen + 4 <= data.len() {
871        let component_type = data[elen];
872        let length = data[elen + 1] as usize;
873        let ident_start = elen + 4;
874        elen += 4;
875        match component_type {
876            // Root: an agreed media-specific location carries a non-empty
877            // identifier that the originator/receiver must interpret. The
878            // kernel steps over that identifier and continues the walk (its
879            // `break` exits the switch, not the loop), so the components that
880            // follow are still decoded. An empty root record falls through to
881            // the parent semantics (`case 1` falls into `case 2`): the output
882            // resets to an absolute root.
883            1 if length > 0 => {
884                elen += length;
885            }
886            // Parent: reset to the root (an empty root record falls through to
887            // the same behavior in the kernel).
888            1 | 2 => {
889                out.clear();
890                out.push('/');
891            }
892            3 => out.push_str("../"),
893            4 => out.push_str("./"),
894            5 => {
895                if length > 0 && ident_start + length <= data.len() {
896                    out.push_str(&decode_osta_cs0(&data[ident_start..ident_start + length]));
897                }
898                out.push('/');
899                elen += length;
900            }
901            // An unrecognized type matches no arm of the kernel's switch, and
902            // it has no `default:`, so the cursor advances by the header
903            // alone — the identifier bytes become the next record header.
904            _ => {}
905        }
906        if elen > data.len() {
907            break;
908        }
909    }
910    if out.len() > 1 && out.ends_with('/') {
911        out.pop();
912    }
913    out
914}
915
916/// Seek to `byte_pos` and read exactly `buf.len()` bytes; returns `None` on any error.
917fn seek_read<R: Read + Seek>(reader: &mut R, byte_pos: u64, buf: &mut [u8]) -> Option<()> {
918    seek_read_checked(reader, byte_pos, buf).ok()
919}
920
921/// Seek to `byte_pos` and read exactly `buf.len()` bytes, propagating the real
922/// [`io::Error`] (a truncated image yields [`io::ErrorKind::UnexpectedEof`]).
923pub fn seek_read_checked<R: Read + Seek>(
924    reader: &mut R,
925    byte_pos: u64,
926    buf: &mut [u8],
927) -> Result<(), io::Error> {
928    reader.seek(SeekFrom::Start(byte_pos))?;
929    reader.read_exact(buf)?;
930    Ok(())
931}
932
933// ── Forensic-findings support (used by `findings`) ───────────────────────────
934
935/// The ECMA-167 descriptor-tag checksum (3/7.2): the mod-256 sum of the 16 tag
936/// bytes excluding byte 4 (the checksum field itself).
937pub fn tag_checksum(tag: &[u8]) -> u8 {
938    let mut sum: u32 = 0;
939    for (i, &b) in tag.iter().take(16).enumerate() {
940        if i == 4 {
941            continue;
942        }
943        sum = sum.wrapping_add(u32::from(b));
944    }
945    (sum & 0xFF) as u8
946}
947
948/// The ECMA-167 descriptor CRC (3/7.2): CRC-CCITT with polynomial `0x1021`,
949/// initial value `0x0000`, no input/output reflection and no final XOR,
950/// computed over the descriptor body (the bytes after the 16-byte tag).
951pub fn ecma167_crc(body: &[u8]) -> u16 {
952    let mut crc: u16 = 0;
953    for &b in body {
954        crc ^= u16::from(b) << 8;
955        for _ in 0..8 {
956            if crc & 0x8000 != 0 {
957                crc = (crc << 1) ^ 0x1021;
958            } else {
959                crc <<= 1;
960            }
961        }
962    }
963    crc
964}
965
966/// Human-readable label for a descriptor tag identifier, or `None` for an
967/// identifier this crate does not recognise (so the caller does not validate a
968/// non-descriptor sector).
969pub fn descriptor_label(tag_ident: u16) -> Option<&'static str> {
970    Some(match tag_ident {
971        TAG_AVDP => "AVDP",
972        TAG_PD => "PartitionDescriptor",
973        TAG_LVD => "LogicalVolumeDescriptor",
974        TAG_TERM => "TerminatingDescriptor",
975        TAG_FSD => "FileSetDescriptor",
976        TAG_FID => "FileIdentifierDescriptor",
977        TAG_FE | TAG_FE_ALT => "FileEntry",
978        TAG_EFE => "ExtendedFileEntry",
979        1 => "PrimaryVolumeDescriptor",
980        3 => "VolumeDescriptorPointer",
981        4 => "ImplementationUseVolumeDescriptor",
982        7 => "UnallocatedSpaceDescriptor",
983        9 => "LogicalVolumeIntegrityDescriptor",
984        258 => "AllocationExtentDescriptor",
985        259 => "IndirectEntry",
986        262 => "SpaceBitmapDescriptor",
987        263 => "PartitionIntegrityEntry",
988        264 => "ExtendedAttributeHeaderDescriptor",
989        265 => "UnallocatedSpaceEntry",
990        _ => return None,
991    })
992}
993
994/// Decode an ECMA-167 `timestamp` (1/7.3, 12 bytes) to `YYYY-MM-DD HH:MM:SS`,
995/// or `None` when the year is implausible (0 / out of the 1970..=2200 range),
996/// which marks an unset or non-timestamp field rather than a real time.
997pub(crate) fn decode_timestamp(b: &[u8]) -> Option<String> {
998    if b.len() < 12 {
999        return None;
1000    }
1001    let year = i16::from_le_bytes([b[2], b[3]]);
1002    if !(1970..=2200).contains(&year) {
1003        return None;
1004    }
1005    let (month, day, hour, minute, second) = (b[4], b[5], b[6], b[7], b[8]);
1006    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
1007        return None;
1008    }
1009    Some(format!(
1010        "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}"
1011    ))
1012}
1013
1014/// Read the File Set Descriptor's recording time (4/14.1, offset 16) from the
1015/// FSD at `fsd_lba`. `Ok(None)` when the sector is not an FSD or the time is
1016/// unset.
1017pub fn fsd_recording_time<R: Read + Seek>(
1018    reader: &mut R,
1019    block_size: u32,
1020    fsd_lba: u32,
1021) -> Result<Option<String>, io::Error> {
1022    let mut buf = [0u8; MAX_BLOCK_SIZE];
1023    let sector = &mut buf[..block_size as usize];
1024    seek_read_checked(reader, u64::from(fsd_lba) * u64::from(block_size), sector)?;
1025    if u16::from_le_bytes([sector[0], sector[1]]) != TAG_FSD {
1026        return Ok(None);
1027    }
1028    Ok(decode_timestamp(&sector[16..28]))
1029}
1030
1031/// The Modification Time of a File Entry sector (`is_efe` selects the Extended
1032/// File Entry layout, whose extra Object Size + Creation Time fields shift the
1033/// timestamps): base FE modification time is at offset 84, EFE at offset 92.
1034pub fn fe_modification_time(sector: &[u8], is_efe: bool) -> Option<String> {
1035    let off = if is_efe { 92 } else { 84 };
1036    decode_timestamp(sector.get(off..off + 12)?)
1037}
1038
1039/// Count the non-zero bytes in a File Entry's final-block slack — the unused
1040/// tail of the last logical block after `InformationLength`, since a file
1041/// occupies whole logical blocks.
1042///
1043/// Returns `(nonzero_bytes, slack_bytes)`, or `None` when the file has no
1044/// trailing slack (size is a whole-block multiple), is zero-length, has its data
1045/// stored inline in the File Entry (no allocated block to hold slack), or its
1046/// final block cannot be located/read.
1047pub fn fe_slack_nonzero<R: Read + Seek>(
1048    reader: &mut R,
1049    block_size: u32,
1050    partition_start: u32,
1051    fe_lba: u32,
1052) -> Option<(u32, u32)> {
1053    let info_len = read_fe_info_len(reader, block_size, fe_lba)?;
1054    let bs = u64::from(block_size);
1055    let slack = (bs - info_len % bs) % bs;
1056    if info_len == 0 || slack == 0 {
1057        return None;
1058    }
1059    // Physical byte position of the file's last allocated block, walked through
1060    // the FE's allocation descriptors so the slack inspected is the true final
1061    // block (not a guess). Inline-stored files have no allocated block and so no
1062    // slack to inspect.
1063    let last_block_pos = fe_last_block_pos(reader, block_size, partition_start, fe_lba)?;
1064    let mut buf = [0u8; MAX_BLOCK_SIZE];
1065    let block = &mut buf[..block_size as usize];
1066    seek_read_checked(reader, last_block_pos, block).ok()?;
1067
1068    let slack_start = (info_len % bs) as usize;
1069    let nonzero = block[slack_start..].iter().filter(|&&b| b != 0).count() as u32;
1070    Some((nonzero, slack as u32))
1071}
1072
1073/// Physical byte position of the *last* logical block holding a File Entry's
1074/// data, resolved by walking its allocation descriptors. `None` for inline
1075/// (in-ICB) data, an unreadable FE, or an FE with no recorded extent.
1076fn fe_last_block_pos<R: Read + Seek>(
1077    reader: &mut R,
1078    block_size: u32,
1079    partition_start: u32,
1080    fe_lba: u32,
1081) -> Option<u64> {
1082    let mut buf = [0u8; MAX_BLOCK_SIZE];
1083    let sector = &mut buf[..block_size as usize];
1084    seek_read_checked(reader, u64::from(fe_lba) * u64::from(block_size), sector).ok()?;
1085
1086    let tag_ident = u16::from_le_bytes([sector[0], sector[1]]);
1087    let is_efe = tag_ident == TAG_EFE;
1088    if tag_ident != TAG_FE && tag_ident != TAG_FE_ALT && !is_efe {
1089        return None;
1090    }
1091
1092    let icb_flags = u16::from_le_bytes([sector[34], sector[35]]);
1093    let alloc_type = icb_flags & 0x0007;
1094    // See `read_fe_data`: EFE shifts L_EA/L_AD/area to 208/212/216 (40 bytes of
1095    // extra fields), not the 176/180/184 an 8-byte-only shift would give.
1096    let (ea_off, ad_off, header) = if is_efe {
1097        (208usize, 212usize, 216usize)
1098    } else {
1099        (168usize, 172usize, 176usize)
1100    };
1101    if ad_off + 4 > sector.len() {
1102        return None; // cov:unreachable: header offsets fit a >=512-byte block
1103    }
1104    let ea_len = u32::from_le_bytes(sector[ea_off..ea_off + 4].try_into().ok()?) as usize;
1105    let ad_len = u32::from_le_bytes(sector[ad_off..ad_off + 4].try_into().ok()?) as usize;
1106    let ad_start = header + ea_len;
1107    let ad_end = ad_start.checked_add(ad_len)?;
1108    if ad_end > sector.len() {
1109        return None;
1110    }
1111    let ad_area = &sector[ad_start..ad_end];
1112
1113    // Both short_ad (8 bytes) and long_ad (16 bytes) record the extent length at
1114    // bytes 0..4 and the logical block number at bytes 4..8; only the stride to
1115    // the next descriptor differs. Inline (in-ICB) data has no allocated block.
1116    let stride = match alloc_type {
1117        ALLOC_SHORT => 8,
1118        ALLOC_LONG => 16,
1119        _ => return None,
1120    };
1121    let mut last: Option<u64> = None;
1122    let mut pos = 0;
1123    while pos + stride <= ad_area.len() {
1124        let len_raw = le_u32(ad_area, pos);
1125        let ext_type = len_raw >> 30;
1126        let ext_len = (len_raw & 0x3FFF_FFFF) as usize;
1127        if ext_type == (EXTENT_RECORDED >> 30) && ext_len > 0 {
1128            let lbn = le_u32(ad_area, pos + 4);
1129            let blocks_in_ext = ext_len.div_ceil(block_size as usize) as u64;
1130            let last_lbn = u64::from(partition_start) + u64::from(lbn) + (blocks_in_ext - 1);
1131            last = Some(last_lbn * u64::from(block_size));
1132        }
1133        pos += stride;
1134    }
1135    last
1136}
1137
1138#[cfg(test)]
1139mod real_media_tests {
1140    //! Validate partition-map classification against real mkudffs-authored
1141    //! pure-UDF images, cross-checked against the independent `udfinfo`
1142    //! (udftools) oracle. The images and the verbatim `mkudffs` commands that
1143    //! produced them are documented in `tests/data/README.md`; they are
1144    //! committed, so these tests run (the skip-if-missing arm is a defensive
1145    //! fallback for a checkout where the fixtures were stripped).
1146    use super::{parse_udf_state, UdfPartitionKind};
1147    use std::fs::File;
1148
1149    fn state(name: &str) -> Option<super::UdfState> {
1150        let path = format!("{}/../tests/data/{}", env!("CARGO_MANIFEST_DIR"), name);
1151        let mut f = File::open(&path).ok()?;
1152        parse_udf_state(&mut f)
1153    }
1154
1155    #[test]
1156    fn vat_image_classified_virtual() {
1157        let Some(st) = state("udf_vat.img") else {
1158            eprintln!("skip: udf_vat.img");
1159            return;
1160        };
1161        assert_eq!(
1162            st.partition_kind,
1163            UdfPartitionKind::Virtual,
1164            "mkudffs cdr/1.50 image must classify as Virtual (VAT)"
1165        );
1166    }
1167
1168    #[test]
1169    fn sparable_image_classified_sparable() {
1170        let Some(st) = state("udf_spar.img") else {
1171            eprintln!("skip: udf_spar.img");
1172            return;
1173        };
1174        assert_eq!(
1175            st.partition_kind,
1176            UdfPartitionKind::Sparable,
1177            "mkudffs dvdrw/2.01 image must classify as Sparable"
1178        );
1179    }
1180
1181    /// Differential reconciliation against the independent `udfinfo` oracle
1182    /// (udftools 2.3, a separate codebase from this crate). The expected values
1183    /// below are the *oracle's* reported ground truth — partition-space start
1184    /// and partition-map shape derived from `udfinfo`'s output, NOT recomputed
1185    /// by this crate. See `tests/data/README.md` for the captured oracle output.
1186    ///
1187    /// `udfinfo udf_vat.img` reports `udfrev=1.50`, `accesstype=writeonce`, and
1188    /// `start=257, blocks=3839, type=PSPACE`; the cdr/1.50 layout carries a
1189    /// physical map plus a Type-2 `*UDF Virtual Partition` map (VAT), so the
1190    /// file-set partition resolves to physical start 257 and two partition maps.
1191    #[test]
1192    fn vat_image_matches_udfinfo_oracle() {
1193        let Some(st) = state("udf_vat.img") else {
1194            eprintln!("skip: udf_vat.img");
1195            return;
1196        };
1197        assert_eq!(st.partition_kind, UdfPartitionKind::Virtual);
1198        // udfinfo PSPACE start block.
1199        assert_eq!(
1200            st.partition_start, 257,
1201            "partition start must match udfinfo PSPACE start=257"
1202        );
1203        // Physical + Virtual (VAT) Type-2 map.
1204        assert_eq!(
1205            st.partition_map_count, 2,
1206            "cdr/1.50 carries a physical map plus the VAT Type-2 map"
1207        );
1208    }
1209
1210    /// `udfinfo udf_spar.img` reports `udfrev=2.01`, `accesstype=overwritable`,
1211    /// a `type=SSPACE` (sparing) region, and `start=1296, blocks=2528,
1212    /// type=PSPACE`; the dvdrw/2.01 layout uses a single Type-2 `*UDF Sparable
1213    /// Partition` map, so the file-set partition resolves to physical start 1296
1214    /// with one partition map.
1215    #[test]
1216    fn sparable_image_matches_udfinfo_oracle() {
1217        let Some(st) = state("udf_spar.img") else {
1218            eprintln!("skip: udf_spar.img");
1219            return;
1220        };
1221        assert_eq!(st.partition_kind, UdfPartitionKind::Sparable);
1222        // udfinfo PSPACE start block.
1223        assert_eq!(
1224            st.partition_start, 1296,
1225            "partition start must match udfinfo PSPACE start=1296"
1226        );
1227        assert_eq!(
1228            st.partition_map_count, 1,
1229            "dvdrw/2.01 carries a single Sparable Type-2 map"
1230        );
1231    }
1232
1233    /// `udfinfo udf_plain.img` reports `udfrev=2.01`, `blocksize=512`, and a
1234    /// single physical partition at `start=257, type=PSPACE`. The mkudffs `hd`
1235    /// profile writes 512-byte logical blocks, so the AVDP lives at byte
1236    /// 256×512, not 256×2048 — this image only parses once the block size is
1237    /// detected from the medium rather than assumed to be 2048.
1238    #[test]
1239    fn plain_512_block_image_parses_via_detected_block_size() {
1240        let path = format!("{}/../tests/data/udf_plain.img", env!("CARGO_MANIFEST_DIR"));
1241        let mut f = File::open(&path).expect("udf_plain.img fixture must be present");
1242        let st = super::parse_udf_state(&mut f)
1243            .expect("512-byte-block UDF must parse once the block size is detected from the AVDP");
1244        assert_eq!(st.block_size, 512, "udfinfo reports blocksize=512");
1245        assert_eq!(
1246            st.partition_kind,
1247            UdfPartitionKind::Physical,
1248            "mkudffs hd image is a Type-1 physical partition"
1249        );
1250        assert_eq!(
1251            st.partition_start, 257,
1252            "partition start must match udfinfo PSPACE start=257"
1253        );
1254        assert_eq!(
1255            st.partition_map_count, 1,
1256            "hd/2.01 carries a single physical map"
1257        );
1258    }
1259}
1260
1261#[cfg(test)]
1262mod checked_bootstrap_tests {
1263    //! `parse_udf_state_checked` must distinguish a real seek/read I/O failure
1264    //! (a bootstrap read failure — truncated/unreadable image) from a structural
1265    //! negative (reads succeeded but the anchor is not a valid AVDP → not UDF).
1266    use super::parse_udf_state_checked;
1267    use std::io::{self, Cursor, Read, Seek, SeekFrom};
1268
1269    /// A `Read + Seek` whose seeks always succeed but whose reads always fail
1270    /// with a non-EOF I/O error — models an unreadable image / device fault.
1271    struct FaultyReader;
1272
1273    impl Read for FaultyReader {
1274        fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
1275            Err(io::Error::other("device read fault"))
1276        }
1277    }
1278    impl Seek for FaultyReader {
1279        fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
1280            Ok(0)
1281        }
1282    }
1283
1284    #[test]
1285    fn io_error_at_anchor_surfaces_as_err() {
1286        let mut r = FaultyReader;
1287        let res = parse_udf_state_checked(&mut r);
1288        assert!(
1289            res.is_err(),
1290            "a device read fault reading the anchor must surface as Err, not Ok(None)"
1291        );
1292    }
1293
1294    #[test]
1295    fn truncated_before_anchor_surfaces_as_err() {
1296        // A buffer too short to reach LBA 256 (256 * 2048 = 524288 bytes) — the
1297        // read_exact at the anchor hits UnexpectedEof, which is a truncated-image
1298        // bootstrap failure and must surface, not be swallowed into Ok(None).
1299        let buf = vec![0u8; 4096];
1300        let mut r = Cursor::new(buf);
1301        let res = parse_udf_state_checked(&mut r);
1302        assert!(
1303            res.is_err(),
1304            "truncation before the AVDP anchor must surface as Err (UnexpectedEof)"
1305        );
1306        let err = res.err().unwrap();
1307        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
1308    }
1309
1310    #[test]
1311    fn full_size_but_wrong_anchor_is_ok_none() {
1312        // A buffer large enough to reach and read LBA 256, but whose sector 256 is
1313        // all zeros (tag identifier 0, not TAG_AVDP=2) — reads succeed, the
1314        // structure is simply not UDF. This is the legitimate "not UDF" case.
1315        let buf = vec![0u8; 257 * 2048];
1316        let mut r = Cursor::new(buf);
1317        let res = parse_udf_state_checked(&mut r);
1318        assert!(
1319            matches!(res, Ok(None)),
1320            "a readable image with a non-AVDP anchor must be Ok(None), got {res:?}"
1321        );
1322    }
1323}
1324
1325#[cfg(test)]
1326mod findings_support_tests {
1327    //! Unit coverage for the findings-support primitives. The CRC/checksum
1328    //! implementations are additionally validated against the real `mkudffs`
1329    //! corpus by the `findings` integration tests (a clean image's descriptors
1330    //! must all verify — a true negative); these tests cover the pure helpers
1331    //! and the allocated-extent slack path the inline-data corpus cannot reach.
1332    use super::*;
1333    use std::io::Cursor;
1334
1335    #[test]
1336    fn crc_ccitt_matches_known_vectors() {
1337        // CRC-CCITT (poly 0x1021, init 0x0000): "123456789" → 0x31C3 is the
1338        // standard published vector for this parameterisation.
1339        assert_eq!(ecma167_crc(b"123456789"), 0x31C3);
1340        assert_eq!(ecma167_crc(&[]), 0x0000);
1341    }
1342
1343    #[test]
1344    fn tag_checksum_skips_byte_4() {
1345        let mut tag = [0u8; 16];
1346        tag[0] = 2; // contributes
1347        tag[4] = 0xFF; // the checksum byte itself — must be excluded
1348        tag[6] = 3; // contributes
1349        assert_eq!(tag_checksum(&tag), 5);
1350    }
1351
1352    #[test]
1353    fn descriptor_label_known_and_unknown() {
1354        // Every mapped ECMA-167 / UDF descriptor identifier resolves to a name
1355        // so a walked descriptor of any type is reported by name, not a number.
1356        for (id, name) in [
1357            (TAG_FSD, "FileSetDescriptor"),
1358            (TAG_EFE, "ExtendedFileEntry"),
1359            (TAG_FID, "FileIdentifierDescriptor"),
1360            (TAG_FE, "FileEntry"),
1361            (TAG_FE_ALT, "FileEntry"),
1362            (1, "PrimaryVolumeDescriptor"),
1363            (3, "VolumeDescriptorPointer"),
1364            (4, "ImplementationUseVolumeDescriptor"),
1365            (7, "UnallocatedSpaceDescriptor"),
1366            (9, "LogicalVolumeIntegrityDescriptor"),
1367            (258, "AllocationExtentDescriptor"),
1368            (259, "IndirectEntry"),
1369            (262, "SpaceBitmapDescriptor"),
1370            (263, "PartitionIntegrityEntry"),
1371            (264, "ExtendedAttributeHeaderDescriptor"),
1372            (265, "UnallocatedSpaceEntry"),
1373        ] {
1374            assert_eq!(descriptor_label(id), Some(name), "tag {id}");
1375        }
1376        assert_eq!(descriptor_label(0xFFFF), None);
1377    }
1378
1379    #[test]
1380    fn fsd_recording_time_none_for_non_fsd() {
1381        let img = vec![0u8; 512];
1382        let mut r = Cursor::new(img);
1383        assert_eq!(fsd_recording_time(&mut r, 512, 0).unwrap(), None);
1384    }
1385
1386    #[test]
1387    fn last_block_pos_none_for_non_file_entry() {
1388        let img = vec![0u8; 512];
1389        let mut r = Cursor::new(img);
1390        assert_eq!(fe_last_block_pos(&mut r, 512, 0, 0), None);
1391    }
1392
1393    #[test]
1394    fn slack_via_long_allocation_descriptor() {
1395        // A 16-byte long_ad (alloc type 1) exercises the ALLOC_LONG stride.
1396        let bs = 512usize;
1397        let mut img = vec![0u8; bs * 8];
1398        let fe = 4 * bs;
1399        img[fe..fe + 2].copy_from_slice(&TAG_FE.to_le_bytes());
1400        img[fe + 34..fe + 36].copy_from_slice(&1u16.to_le_bytes()); // long_ad alloc
1401        img[fe + 56..fe + 64].copy_from_slice(&100u64.to_le_bytes());
1402        img[fe + 168..fe + 172].copy_from_slice(&0u32.to_le_bytes()); // L_EA
1403        img[fe + 172..fe + 176].copy_from_slice(&16u32.to_le_bytes()); // L_AD = one long_ad
1404        img[fe + 176..fe + 180].copy_from_slice(&100u32.to_le_bytes()); // extent_length
1405        img[fe + 180..fe + 184].copy_from_slice(&5u32.to_le_bytes()); // logical block num
1406        let data = 5 * bs + 100;
1407        img[data] = 0x7F;
1408        let mut r = Cursor::new(img);
1409        let (nonzero, slack) = fe_slack_nonzero(&mut r, 512, 0, 4).expect("slack present");
1410        assert_eq!(slack, 412);
1411        assert_eq!(nonzero, 1);
1412    }
1413
1414    #[test]
1415    fn timestamp_decodes_and_rejects_implausible() {
1416        let mut t = [0u8; 12];
1417        t[2..4].copy_from_slice(&2026i16.to_le_bytes());
1418        t[4] = 6; // month
1419        t[5] = 21; // day
1420        t[6] = 8; // hour
1421        t[7] = 46; // minute
1422        t[8] = 57; // second
1423        assert_eq!(decode_timestamp(&t).as_deref(), Some("2026-06-21 08:46:57"));
1424
1425        // Year out of range → None (unset/garbage field).
1426        let mut bad = t;
1427        bad[2..4].copy_from_slice(&0i16.to_le_bytes());
1428        assert_eq!(decode_timestamp(&bad), None);
1429
1430        // Month out of range → None.
1431        let mut badmon = t;
1432        badmon[4] = 0;
1433        assert_eq!(decode_timestamp(&badmon), None);
1434
1435        // Short buffer → None.
1436        assert_eq!(decode_timestamp(&[0u8; 4]), None);
1437    }
1438
1439    #[test]
1440    fn fe_modification_time_offset_differs_for_efe() {
1441        // Base FE: mtime at offset 84; EFE: mtime at offset 92.
1442        let mut fe = vec![0u8; 512];
1443        let stamp = |buf: &mut [u8], off: usize, year: i16| {
1444            buf[off + 2..off + 4].copy_from_slice(&year.to_le_bytes());
1445            buf[off + 4] = 1; // month
1446            buf[off + 5] = 1; // day
1447        };
1448        stamp(&mut fe, 84, 2030);
1449        assert_eq!(
1450            fe_modification_time(&fe, false).as_deref(),
1451            Some("2030-01-01 00:00:00")
1452        );
1453        let mut efe = vec![0u8; 512];
1454        stamp(&mut efe, 92, 2031);
1455        assert_eq!(
1456            fe_modification_time(&efe, true).as_deref(),
1457            Some("2031-01-01 00:00:00")
1458        );
1459    }
1460
1461    /// Build a minimal 512-byte-block image with a base File Entry that points,
1462    /// via a short allocation descriptor, to a single data block whose tail
1463    /// (past `InformationLength`) holds non-zero slack — the allocated-extent
1464    /// path the inline-data `mkudffs` corpus cannot exercise.
1465    fn image_with_slack(info_len: u64, slack_fill: &[u8]) -> (Vec<u8>, u32, u32) {
1466        let bs = 512usize;
1467        let part_start = 0u32;
1468        let fe_lba = 4u32;
1469        let data_lbn = 5u32; // physical = part_start + 5
1470        let mut img = vec![0u8; bs * 8];
1471
1472        let fe = fe_lba as usize * bs;
1473        // Tag identifier = File Entry (260).
1474        img[fe..fe + 2].copy_from_slice(&TAG_FE.to_le_bytes());
1475        // ICB flags: allocation type 0 (short_ad).
1476        img[fe + 34..fe + 36].copy_from_slice(&0u16.to_le_bytes());
1477        // InformationLength.
1478        img[fe + 56..fe + 64].copy_from_slice(&info_len.to_le_bytes());
1479        // Base-FE header offsets: L_EA @168, L_AD @172, AD area @176.
1480        img[fe + 168..fe + 172].copy_from_slice(&0u32.to_le_bytes()); // L_EA = 0
1481        img[fe + 172..fe + 176].copy_from_slice(&8u32.to_le_bytes()); // L_AD = 8 (one short_ad)
1482                                                                      // short_ad: extent_length (recorded, type 0) = info_len, position = data_lbn.
1483        let ad = fe + 176;
1484        img[ad..ad + 4].copy_from_slice(&(info_len as u32).to_le_bytes());
1485        img[ad + 4..ad + 8].copy_from_slice(&data_lbn.to_le_bytes());
1486
1487        // Data block: fill the slack region (past info_len within the block).
1488        let data = (part_start + data_lbn) as usize * bs;
1489        let slack_start = data + (info_len as usize % bs);
1490        for (i, &b) in slack_fill.iter().enumerate() {
1491            img[slack_start + i] = b;
1492        }
1493        (img, part_start, fe_lba)
1494    }
1495
1496    #[test]
1497    fn slack_counts_nonzero_tail_bytes() {
1498        // info_len 100 in a 512-byte block → 412 slack bytes; place 3 non-zero.
1499        let (img, ps, fe) = image_with_slack(100, &[0xAA, 0x00, 0xBB, 0xCC]);
1500        let mut r = Cursor::new(img);
1501        let (nonzero, slack) = fe_slack_nonzero(&mut r, 512, ps, fe).expect("slack present");
1502        assert_eq!(slack, 412);
1503        assert_eq!(nonzero, 3);
1504    }
1505
1506    #[test]
1507    fn slack_none_when_block_aligned() {
1508        // info_len exactly one block → no slack.
1509        let (img, ps, fe) = image_with_slack(512, &[0xFF]);
1510        let mut r = Cursor::new(img);
1511        assert_eq!(fe_slack_nonzero(&mut r, 512, ps, fe), None);
1512    }
1513
1514    #[test]
1515    fn slack_none_when_zero_length() {
1516        let (img, ps, fe) = image_with_slack(0, &[]);
1517        let mut r = Cursor::new(img);
1518        assert_eq!(fe_slack_nonzero(&mut r, 512, ps, fe), None);
1519    }
1520
1521    #[test]
1522    fn slack_none_for_inline_data() {
1523        // Allocation type 3 (inline) has no allocated block to inspect.
1524        let (mut img, ps, fe) = image_with_slack(100, &[0xAA]);
1525        let fe_off = fe as usize * 512;
1526        img[fe_off + 34..fe_off + 36].copy_from_slice(&3u16.to_le_bytes());
1527        let mut r = Cursor::new(img);
1528        assert_eq!(fe_slack_nonzero(&mut r, 512, ps, fe), None);
1529    }
1530}
1531
1532#[cfg(test)]
1533mod synth_traversal_tests {
1534    //! Directory (FID) traversal, filename decoding, and the short/long
1535    //! allocation extent readers, driven over the hand-built populated UDF image
1536    //! in `test_support` (the committed `mkudffs` corpus has empty roots and
1537    //! inline-only data, so it cannot reach these paths). Expected values are
1538    //! derived from the documented ECMA-167 construction of the fixture.
1539    use super::*;
1540    use crate::test_support as ts;
1541    use std::io::Cursor;
1542
1543    #[test]
1544    fn read_dir_lists_children_with_decoded_names_and_sizes() {
1545        let mut r = Cursor::new(ts::image());
1546        let st = parse_udf_state(&mut r).expect("synthetic UDF parses");
1547        assert_eq!(st.block_size, 512);
1548        assert_eq!(st.partition_kind, UdfPartitionKind::Physical);
1549
1550        let entries = read_dir_at_lba(&mut r, st.block_size, st.partition_start, st.root_fe_lba)
1551            .expect("root directory reads");
1552        // The parent FID is skipped; the seven real children are surfaced
1553        // (including the synthetic symlink).
1554        assert_eq!(entries.len(), 7, "entries: {entries:?}");
1555        let by_name = |n: &str| entries.iter().find(|e| e.name == n);
1556
1557        assert!(by_name("sub").expect("sub").is_dir);
1558        assert!(by_name("bd").expect("bd").is_dir);
1559        let inline = by_name("inline.txt").expect("inline.txt");
1560        assert!(!inline.is_dir);
1561        assert_eq!(inline.size, 4);
1562        assert_eq!(
1563            by_name("short.bin").expect("short.bin").size,
1564            ts::SHORT_FILE_LEN
1565        );
1566        assert_eq!(
1567            by_name("long.bin").expect("long.bin").size,
1568            ts::LONG_FILE_LEN
1569        );
1570        // OSTA CS0 compression id 16 (UTF-16BE) decodes to "U".
1571        assert!(by_name("U").is_some(), "utf-16 name decoded: {entries:?}");
1572    }
1573
1574    #[test]
1575    fn read_fe_data_reads_short_extents() {
1576        let mut r = Cursor::new(ts::image());
1577        let st = parse_udf_state(&mut r).unwrap();
1578        let data = read_fe_data(&mut r, st.block_size, st.partition_start, ts::SHORT_FILE_FE)
1579            .expect("short-extent file data");
1580        assert_eq!(data.len() as u64, ts::SHORT_FILE_LEN);
1581        assert!(data[..512].iter().all(|&b| b == 0x41));
1582        assert!(data[512..].iter().all(|&b| b == 0x42));
1583    }
1584
1585    #[test]
1586    fn read_fe_data_stops_reading_once_the_information_length_is_met() {
1587        // An extent's recorded length is image-controlled and may exceed the
1588        // data it holds; here it is the 30-bit maximum (1 GiB), far past the end
1589        // of the 135 KB image. The 600 bytes the File Entry records all sit in
1590        // its first two blocks, so the reader must stop there rather than keep
1591        // seeking through the rest of the extent and fail at end of image.
1592        let mut img = ts::image();
1593        let ad = ts::SHORT_FILE_FE as usize * ts::BS + 176;
1594        img[ad..ad + 4].copy_from_slice(&0x3FFF_FFFFu32.to_le_bytes());
1595        let mut r = Cursor::new(img);
1596        let st = parse_udf_state(&mut r).unwrap();
1597        let data = read_fe_data(&mut r, st.block_size, st.partition_start, ts::SHORT_FILE_FE)
1598            .expect("the 600 recorded bytes are readable");
1599        assert_eq!(data.len() as u64, ts::SHORT_FILE_LEN);
1600        assert!(data[..512].iter().all(|&b| b == 0x41));
1601        assert!(data[512..].iter().all(|&b| b == 0x42));
1602    }
1603
1604    #[test]
1605    fn read_fe_data_reads_long_extents() {
1606        let mut r = Cursor::new(ts::image());
1607        let st = parse_udf_state(&mut r).unwrap();
1608        let data = read_fe_data(&mut r, st.block_size, st.partition_start, ts::LONG_FILE_FE)
1609            .expect("long-extent file data");
1610        assert_eq!(data.len() as u64, ts::LONG_FILE_LEN);
1611        assert!(data.iter().all(|&b| b == 0x43));
1612    }
1613
1614    #[test]
1615    fn read_fe_data_reads_inline() {
1616        let mut r = Cursor::new(ts::image());
1617        let st = parse_udf_state(&mut r).unwrap();
1618        let data = read_fe_data(
1619            &mut r,
1620            st.block_size,
1621            st.partition_start,
1622            ts::INLINE_FILE_FE,
1623        )
1624        .expect("inline file data");
1625        assert_eq!(data, b"abcd");
1626    }
1627
1628    #[test]
1629    fn read_fe_data_none_for_non_file_entry() {
1630        let mut r = Cursor::new(vec![0u8; 4096]);
1631        assert!(read_fe_data(&mut r, 512, 0, 0).is_none());
1632    }
1633
1634    #[test]
1635    fn read_fe_data_none_for_broken_directory() {
1636        // L_AD overruns the block, so the allocation area cannot be sliced.
1637        let mut r = Cursor::new(ts::image());
1638        let st = parse_udf_state(&mut r).unwrap();
1639        assert!(
1640            read_fe_data(&mut r, st.block_size, st.partition_start, ts::BROKEN_DIR_FE).is_none()
1641        );
1642    }
1643
1644    #[test]
1645    fn read_fe_data_none_for_unsupported_alloc_type() {
1646        // Allocation type 2 (extended alloc descriptors) is not resolved here.
1647        let mut img = vec![0u8; 1024];
1648        img[0..2].copy_from_slice(&TAG_FE.to_le_bytes());
1649        img[34..36].copy_from_slice(&2u16.to_le_bytes()); // alloc type 2
1650        let mut r = Cursor::new(img);
1651        assert!(read_fe_data(&mut r, 512, 0, 0).is_none());
1652    }
1653
1654    #[test]
1655    fn decode_osta_cs0_utf8_utf16_and_empty() {
1656        assert_eq!(decode_osta_cs0(&[]), "");
1657        assert_eq!(decode_osta_cs0(b"\x08hello"), "hello");
1658        // Compression id 16 = UTF-16BE.
1659        assert_eq!(decode_osta_cs0(&[16, 0x00, 0x41, 0x00, 0x42]), "AB");
1660    }
1661
1662    #[test]
1663    fn decode_symlink_target_relative_parent_and_name() {
1664        // The exact bytes a Linux kernel (6.8) UDF driver wrote for a symlink
1665        // whose target is "../README.txt" on a mkudffs 2.01 volume: a type-3
1666        // ("..") record with an empty identifier, then a type-5 record holding
1667        // an 11-byte CS0 name (compression id 8 + "README.txt"). Verified
1668        // against `hdiutil attach` (macOS resolves it to "../README.txt").
1669        let data = [
1670            0x03, 0x00, 0x00, 0x00, // type 3 (".."), len 0, version 0
1671            0x05, 0x0b, 0x00, 0x00, // type 5 (name), len 11, version 0
1672            0x08, b'R', b'E', b'A', b'D', b'M', b'E', b'.', b't', b'x', b't',
1673        ];
1674        assert_eq!(decode_symlink_target(&data), "../README.txt");
1675    }
1676
1677    #[test]
1678    fn decode_symlink_target_absolute_utf16_and_empty() {
1679        // Absolute: root (type 1) + UTF-16BE name (compression id 16).
1680        let mut data = vec![
1681            0x01, 0x00, 0x00, 0x00, 0x05, 0x05, 0x00, 0x00, 0x10, 0x00, 0x41, 0x00, 0x42,
1682        ];
1683        assert_eq!(decode_symlink_target(&data), "/AB");
1684        // Empty chain and an all-garbage chain decode to empty, never panic.
1685        assert_eq!(decode_symlink_target(&[]), "");
1686        assert_eq!(decode_symlink_target(&[0x99, 0xff, 0x00, 0x00, 0x00]), "");
1687        // A name record whose length overruns the buffer stops the walk.
1688        data[5] = 0x7f;
1689        assert_eq!(decode_symlink_target(&data), "/");
1690    }
1691
1692    #[test]
1693    fn decode_symlink_target_agreed_location_skips_ident_and_continues() {
1694        // Type 1 with a non-empty identifier is a media-specific agreed
1695        // location. The kernel's `break` leaves the *switch*, not the *while*:
1696        //
1697        //     case 1:
1698        //         if (pc->lengthComponentIdent > 0) {
1699        //             elen += pc->lengthComponentIdent;
1700        //             break;          /* switch, not the loop */
1701        //         }
1702        //         fallthrough;
1703        //
1704        // so it steps over the identifier and keeps walking the chain
1705        // (fs/udf/symlink.c). Aborting the whole walk would silently drop
1706        // every component that follows — under-reporting a target rather than
1707        // surfacing an error.
1708        //
1709        // Here: type 1 ident "AB", then a type-5 name "ab".
1710        let data = [
1711            0x01, 0x02, 0x00, 0x00, b'A', b'B', 0x05, 0x03, 0x00, 0x00, 0x08, b'a', b'b',
1712        ];
1713        assert_eq!(decode_symlink_target(&data), "ab");
1714        // Type 4 (".") writes "./"; the trailing slash is trimmed.
1715        let data = [
1716            0x04, 0x00, 0x00, 0x00, 0x05, 0x03, 0x00, 0x00, 0x08, b'a', b'b',
1717        ];
1718        assert_eq!(decode_symlink_target(&data), "./ab");
1719        // A lone current-directory record trims to ".".
1720        let data = [0x04, 0x00, 0x00, 0x00];
1721        assert_eq!(decode_symlink_target(&data), ".");
1722    }
1723
1724    #[test]
1725    fn decode_symlink_target_unknown_type_advances_only_the_header() {
1726        // The kernel's switch has no `default:` arm, so an unrecognized
1727        // component type consumes only `sizeof(struct pathComponent)` (4
1728        // bytes) and its identifier bytes are then read as the next record
1729        // header. Skipping `lengthComponentIdent` as well would resynchronize
1730        // the walk differently from the kernel, and the mount is the ground
1731        // truth a forensic reader has to reproduce.
1732        //
1733        // Type 9 (unknown) declaring a 4-byte identifier whose bytes are
1734        // themselves a well-formed type-4 (".") record.
1735        let data = [0x09, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00];
1736        assert_eq!(
1737            decode_symlink_target(&data),
1738            ".",
1739            "an unknown record advances four bytes, so its payload is the next header"
1740        );
1741    }
1742
1743    #[test]
1744    fn decode_symlink_target_parent_resets_to_root() {
1745        // Type 2 (parent) clears prior output and writes "/".
1746        let data = [
1747            0x05, 0x03, 0x00, 0x00, 0x08, b'a', b'b', 0x02, 0x00, 0x00, 0x00,
1748        ];
1749        assert_eq!(decode_symlink_target(&data), "/");
1750    }
1751
1752    #[cfg(feature = "vfs")]
1753    #[test]
1754    fn read_fe_file_type_classifies_and_rejects() {
1755        let mut r = Cursor::new(ts::image());
1756        let st = parse_udf_state(&mut r).unwrap();
1757        assert_eq!(
1758            read_fe_file_type(&mut r, st.block_size, ts::SUBDIR_FE),
1759            Some(FILE_TYPE_DIRECTORY)
1760        );
1761        assert_eq!(
1762            read_fe_file_type(&mut r, st.block_size, ts::INLINE_FILE_FE),
1763            Some(5)
1764        );
1765        let mut z = Cursor::new(vec![0u8; 4096]);
1766        assert_eq!(read_fe_file_type(&mut z, 512, 0), None);
1767    }
1768
1769    #[test]
1770    fn parse_fids_skips_padding_and_stops_on_overflow() {
1771        // All-zero directory data: every 4-byte step sees a non-FID tag.
1772        let mut r = Cursor::new(vec![0u8; 64]);
1773        assert!(parse_fids(&mut r, 512, 0, &[0u8; 64]).is_empty());
1774        // A FID whose DescriptorCRCLength drives fid_advance past the buffer end
1775        // must break the loop rather than read out of bounds.
1776        let mut data = vec![0u8; 40];
1777        data[0..2].copy_from_slice(&TAG_FID.to_le_bytes());
1778        data[10..12].copy_from_slice(&0xFFFFu16.to_le_bytes());
1779        assert!(parse_fids(&mut r, 512, 0, &data).is_empty());
1780    }
1781
1782    #[test]
1783    fn parse_state_none_when_vds_has_no_lvd() {
1784        // Valid AVDP + detectable block size, but the VDS carries no Logical
1785        // Volume Descriptor → a structural "not UDF" (Ok(None)), never an error.
1786        let mut img = vec![0u8; 512 * 264];
1787        let avdp = 256 * 512;
1788        img[avdp..avdp + 2].copy_from_slice(&2u16.to_le_bytes()); // TAG_AVDP
1789        img[avdp + 12..avdp + 16].copy_from_slice(&256u32.to_le_bytes()); // tag location
1790        img[avdp + 16..avdp + 20].copy_from_slice(&512u32.to_le_bytes()); // VDS length: 1 block
1791        img[avdp + 20..avdp + 24].copy_from_slice(&260u32.to_le_bytes()); // VDS location
1792                                                                          // LBA 260 left zero → no PD/LVD.
1793        let mut r = Cursor::new(img);
1794        assert!(parse_udf_state_checked(&mut r).unwrap().is_none());
1795    }
1796
1797    #[test]
1798    fn parse_state_none_when_fsd_tag_wrong() {
1799        // Valid AVDP + VDS(PD+LVD) but the FSD sector is not an FSD → Ok(None).
1800        let mut img = ts::image();
1801        img[3 * 512..3 * 512 + 2].copy_from_slice(&0u16.to_le_bytes());
1802        let mut r = Cursor::new(img);
1803        assert!(parse_udf_state_checked(&mut r).unwrap().is_none());
1804    }
1805
1806    #[test]
1807    fn descriptor_label_terminating() {
1808        assert_eq!(descriptor_label(TAG_TERM), Some("TerminatingDescriptor"));
1809    }
1810
1811    #[test]
1812    fn detect_udf_recognises_nsr_and_stops_on_terminator() {
1813        // NSR03 in the volume recognition sequence (LBA 16) → recognised.
1814        let mut img = vec![0u8; 20 * 2048];
1815        img[16 * 2048 + 1..16 * 2048 + 6].copy_from_slice(b"NSR03");
1816        assert!(detect_udf(&mut Cursor::new(img)));
1817        // A TEA01 terminator with no NSR → not UDF (the scan stops at TEA01).
1818        let mut tea = vec![0u8; 20 * 2048];
1819        tea[16 * 2048 + 1..16 * 2048 + 6].copy_from_slice(b"TEA01");
1820        assert!(!detect_udf(&mut Cursor::new(tea)));
1821        // A source too short to reach LBA 16 breaks out and reports false.
1822        assert!(!detect_udf(&mut Cursor::new(vec![0u8; 100])));
1823    }
1824
1825    #[test]
1826    fn classify_type2_maps_entity_strings() {
1827        assert_eq!(
1828            classify_type2(b"....*UDF Metadata Partition...."),
1829            UdfPartitionKind::Metadata
1830        );
1831        assert_eq!(
1832            classify_type2(b"....*UDF Virtual Partition...."),
1833            UdfPartitionKind::Virtual
1834        );
1835        assert_eq!(
1836            classify_type2(b"....*UDF Sparable Partition...."),
1837            UdfPartitionKind::Sparable
1838        );
1839        assert_eq!(
1840            classify_type2(b"no entity string"),
1841            UdfPartitionKind::Unknown
1842        );
1843    }
1844
1845    #[test]
1846    fn parse_partition_maps_type1_type2_and_unknown() {
1847        let mut lvd = vec![0u8; 512];
1848        lvd[268..272].copy_from_slice(&3u32.to_le_bytes()); // N_PM = 3
1849        let mut off = 440usize;
1850        // Type-1 physical map (length 6) carrying partition number 2.
1851        lvd[off] = 1;
1852        lvd[off + 1] = 6;
1853        lvd[off + 4..off + 6].copy_from_slice(&2u16.to_le_bytes());
1854        off += 6;
1855        // Type-2 map (length 40) carrying the Metadata entity string.
1856        lvd[off] = 2;
1857        lvd[off + 1] = 40;
1858        lvd[off + 4..off + 4 + 23].copy_from_slice(b"*UDF Metadata Partition");
1859        off += 40;
1860        // An unrecognised map type (length 4).
1861        lvd[off] = 9;
1862        lvd[off + 1] = 4;
1863        off += 4;
1864        lvd[264..268].copy_from_slice(&((off - 440) as u32).to_le_bytes()); // Map Table Length
1865
1866        let maps = parse_partition_maps(&lvd);
1867        assert_eq!(maps.len(), 3);
1868        assert_eq!(maps[0].kind, UdfPartitionKind::Physical);
1869        assert_eq!(maps[0].partition_number, Some(2));
1870        assert_eq!(maps[1].kind, UdfPartitionKind::Metadata);
1871        assert_eq!(maps[2].kind, UdfPartitionKind::Unknown);
1872    }
1873}