1#![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
34pub 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;
43pub const TAG_FE_ALT: u16 = 261;
45pub const TAG_EFE: u16 = 266;
46
47const FC_DIRECTORY: u8 = 0x02;
49const FC_PARENT: u8 = 0x08;
50
51const ALLOC_SHORT: u16 = 0;
53const ALLOC_LONG: u16 = 1;
54const ALLOC_INLINE: u16 = 3;
55
56const EXTENT_RECORDED: u32 = 0x0000_0000; pub const MAX_BLOCK_SIZE: usize = 4096;
63
64const BLOCK_SIZE_CANDIDATES: [u32; 4] = [2048, 512, 1024, 4096];
67
68#[derive(Debug, Clone)]
72pub struct UdfFileEntry {
73 pub name: String,
75 pub is_dir: bool,
77 pub size: u64,
79 pub fe_lba: u32,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94pub enum UdfPartitionKind {
95 Physical,
97 Virtual,
99 Sparable,
101 Metadata,
103 Unknown,
105}
106
107#[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 pub block_size: u32,
119 pub fsd_lba: u32,
123 pub vds_loc: u32,
127 pub vds_len_sectors: u32,
129}
130
131pub 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
157pub fn parse_udf_state<R: Read + Seek>(reader: &mut R) -> Option<UdfState> {
167 parse_udf_state_checked(reader).ok().flatten()
168}
169
170pub 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); };
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
210struct VdsInfo {
212 partition_start: u32,
213 fsd_lba: u32,
214 partition_kind: UdfPartitionKind,
215 map_count: u32,
216}
217
218struct PartitionMap {
220 kind: UdfPartitionKind,
221 partition_number: Option<u16>,
223}
224
225fn 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
240fn 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
278pub 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
290pub 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
328pub 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 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; }
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
383fn 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
422fn 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
440fn 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 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 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 let Some(fsd) = fsd_lbn else {
488 return Ok(None);
489 };
490 let map_count = maps.len() as u32;
491
492 let referenced = maps.get(fsd_part_ref as usize);
494 let kind = referenced.map_or(UdfPartitionKind::Unknown, |m| m.kind);
495
496 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 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
525fn 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 let lbn = le_u32(sector, 404);
547 Ok(Some(partition_start + lbn))
548}
549
550fn 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 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; }
583 off += 4;
584 }
585 16
586}
587
588fn parse_fids<R: Read + Seek>(
590 reader: &mut R,
591 block_size: u32,
592 partition_start: u32,
593 data: &[u8],
594) -> Vec<UdfFileEntry> {
595 let tag_size = detect_fid_tag_size(data);
598 let min_fid = tag_size + 20; 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 off += 4;
608 continue;
609 }
610
611 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 let icb_lbn = if off + tag_size + 10 <= data.len() {
622 le_u32(data, off + tag_size + 6)
623 } else {
624 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 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 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 if let Some(fe_lba) = partition_start.checked_add(icb_lbn) {
663 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
680fn 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#[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#[cfg(feature = "vfs")]
717pub(crate) const FILE_TYPE_DIRECTORY: u8 = 4;
718
719#[cfg(feature = "vfs")]
722pub(crate) const FILE_TYPE_REGULAR: u8 = 0x05;
723
724#[cfg(feature = "vfs")]
726pub(crate) const FILE_TYPE_LINK: u8 = 0x0c;
727
728#[cfg(feature = "vfs")]
730pub(crate) const FILE_TYPE_BLOCK_DEVICE: u8 = 0x06;
731
732#[cfg(feature = "vfs")]
734pub(crate) const FILE_TYPE_CHAR_DEVICE: u8 = 0x07;
735
736#[cfg(feature = "vfs")]
738pub(crate) const FILE_TYPE_FIFO: u8 = 0x09;
739
740#[cfg(feature = "vfs")]
742pub(crate) const FILE_TYPE_SOCKET: u8 = 0x0a;
743
744fn 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
769fn 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
794fn 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 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(§or[..take]);
818 }
819 Some(())
820}
821
822fn 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 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
843pub 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 1 if length > 0 => {
884 elen += length;
885 }
886 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 _ => {}
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
916fn 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
921pub 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
933pub 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
948pub 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
966pub 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
994pub(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
1014pub 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(§or[16..28]))
1029}
1030
1031pub 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
1039pub 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 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
1073fn 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 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; }
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 = §or[ad_start..ad_end];
1112
1113 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 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 #[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 assert_eq!(
1200 st.partition_start, 257,
1201 "partition start must match udfinfo PSPACE start=257"
1202 );
1203 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 #[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 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 #[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 use super::parse_udf_state_checked;
1267 use std::io::{self, Cursor, Read, Seek, SeekFrom};
1268
1269 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 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 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 use super::*;
1333 use std::io::Cursor;
1334
1335 #[test]
1336 fn crc_ccitt_matches_known_vectors() {
1337 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; tag[4] = 0xFF; tag[6] = 3; assert_eq!(tag_checksum(&tag), 5);
1350 }
1351
1352 #[test]
1353 fn descriptor_label_known_and_unknown() {
1354 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 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()); 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()); img[fe + 172..fe + 176].copy_from_slice(&16u32.to_le_bytes()); img[fe + 176..fe + 180].copy_from_slice(&100u32.to_le_bytes()); img[fe + 180..fe + 184].copy_from_slice(&5u32.to_le_bytes()); 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; t[5] = 21; t[6] = 8; t[7] = 46; t[8] = 57; assert_eq!(decode_timestamp(&t).as_deref(), Some("2026-06-21 08:46:57"));
1424
1425 let mut bad = t;
1427 bad[2..4].copy_from_slice(&0i16.to_le_bytes());
1428 assert_eq!(decode_timestamp(&bad), None);
1429
1430 let mut badmon = t;
1432 badmon[4] = 0;
1433 assert_eq!(decode_timestamp(&badmon), None);
1434
1435 assert_eq!(decode_timestamp(&[0u8; 4]), None);
1437 }
1438
1439 #[test]
1440 fn fe_modification_time_offset_differs_for_efe() {
1441 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; buf[off + 5] = 1; };
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 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; let mut img = vec![0u8; bs * 8];
1471
1472 let fe = fe_lba as usize * bs;
1473 img[fe..fe + 2].copy_from_slice(&TAG_FE.to_le_bytes());
1475 img[fe + 34..fe + 36].copy_from_slice(&0u16.to_le_bytes());
1477 img[fe + 56..fe + 64].copy_from_slice(&info_len.to_le_bytes());
1479 img[fe + 168..fe + 172].copy_from_slice(&0u32.to_le_bytes()); img[fe + 172..fe + 176].copy_from_slice(&8u32.to_le_bytes()); 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 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 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 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 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 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 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 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 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 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 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()); 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 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 let data = [
1670 0x03, 0x00, 0x00, 0x00, 0x05, 0x0b, 0x00, 0x00, 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 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 assert_eq!(decode_symlink_target(&[]), "");
1686 assert_eq!(decode_symlink_target(&[0x99, 0xff, 0x00, 0x00, 0x00]), "");
1687 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 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 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 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 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 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 let mut r = Cursor::new(vec![0u8; 64]);
1773 assert!(parse_fids(&mut r, 512, 0, &[0u8; 64]).is_empty());
1774 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 let mut img = vec![0u8; 512 * 264];
1787 let avdp = 256 * 512;
1788 img[avdp..avdp + 2].copy_from_slice(&2u16.to_le_bytes()); img[avdp + 12..avdp + 16].copy_from_slice(&256u32.to_le_bytes()); img[avdp + 16..avdp + 20].copy_from_slice(&512u32.to_le_bytes()); img[avdp + 20..avdp + 24].copy_from_slice(&260u32.to_le_bytes()); 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 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 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 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 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()); let mut off = 440usize;
1850 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 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 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()); 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}