hadris-iso 2.0.0

Pure Rust ISO 9660 library with allocation-free reading, Joliet, Rock Ridge, and El Torito
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use super::io::{self, Read, Write};
use bytemuck::Zeroable;

use super::io::LogicalSector;
use crate::types::{U16LsbMsb, U32LsbMsb};

/// The header of a directory record, because the identifier is variable length
/// (ECMA-119 9.1 fixed fields).
///
/// @hadris-spec ECMA-119:9.1
/// @hadris-compliance partial
/// @hadris-note Fixed fields round-trip, but all identifier, flag, and semantic constraints are not yet validated.
/// @hadris-tests directory::tests::directory_record_parse_roundtrip
/// @hadris-fuzz iso_read
#[repr(C)]
#[derive(Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct DirectoryRecordHeader {
    /// The `len` field.
    pub len: u8,
    /// The `extended_attr_record` field.
    pub extended_attr_record: u8,
    /// The LBA of the record
    pub extent: U32LsbMsb,
    /// The length of the data in bytes
    pub data_len: U32LsbMsb,
    /// The `date_time` field.
    pub date_time: DirDateTime,
    /// The `flags` field.
    pub flags: u8,
    /// The `file_unit_size` field.
    pub file_unit_size: u8,
    /// The `interleave_gap_size` field.
    pub interleave_gap_size: u8,
    /// The `volume_sequence_number` field.
    pub volume_sequence_number: U16LsbMsb,
    /// The `file_identifier_len` field.
    pub file_identifier_len: u8,
}

impl Default for DirectoryRecordHeader {
    fn default() -> Self {
        Self {
            len: 0,
            extended_attr_record: 0,
            extent: U32LsbMsb::new(0),
            data_len: U32LsbMsb::new(0),
            date_time: DirDateTime::now(),
            flags: 0,
            file_unit_size: 0,
            interleave_gap_size: 0,
            volume_sequence_number: U16LsbMsb::new(0),
            file_identifier_len: 0,
        }
    }
}

impl DirectoryRecordHeader {
    /// Performs the `from_bytes` operation.
    pub fn from_bytes(bytes: &[u8]) -> &Self {
        bytemuck::from_bytes(bytes)
    }

    /// Performs the `to_bytes` operation.
    pub fn to_bytes(&self) -> &[u8] {
        bytemuck::bytes_of(self)
    }

    /// Performs the `is_directory` operation.
    pub fn is_directory(&self) -> bool {
        FileFlags::from_bits_retain(self.flags).contains(FileFlags::DIRECTORY)
    }
}

/// Directory Record (ECMA-119 9.1) — header plus variable identifier / system use.
///
/// @hadris-spec ECMA-119:9.1
/// @hadris-compliance partial
/// @hadris-tests directory::tests::directory_record_parse_roundtrip
/// @hadris-fuzz iso_read
/// @hadris-note Joliet+RRIP coexistence on read may hide one namespace; see crate Known Limitations
#[repr(transparent)]
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
pub struct DirectoryRecord {
    data: [u8; 256],
}

impl Default for DirectoryRecord {
    fn default() -> Self {
        bytemuck::Zeroable::zeroed()
    }
}

/// Error returned when trying to access a file as a directory
#[derive(Debug, Clone, Copy)]
pub struct NotADirectoryError;

impl core::fmt::Display for NotADirectoryError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "not a directory")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for NotADirectoryError {}

impl DirectoryRecord {
    const DATA_START: usize = size_of::<DirectoryRecordHeader>();

    #[inline]
    /// Performs the `header` operation.
    pub fn header(&self) -> &DirectoryRecordHeader {
        bytemuck::from_bytes(&self.data[0..Self::DATA_START])
    }

    #[inline]
    /// Performs the `header_mut` operation.
    pub fn header_mut(&mut self) -> &mut DirectoryRecordHeader {
        bytemuck::from_bytes_mut(&mut self.data[0..size_of::<DirectoryRecordHeader>()])
    }

    #[inline]
    /// Performs the `name` operation.
    pub fn name(&self) -> &[u8] {
        let len = self.header().file_identifier_len as usize;
        &self.data[Self::DATA_START..Self::DATA_START + len]
    }

    /// Get the filename decoded from Joliet (UTF-16 BE) encoding
    ///
    /// This is useful when reading from a Joliet supplementary volume descriptor.
    /// Returns the decoded Unicode string.
    #[cfg(feature = "alloc")]
    pub fn joliet_name(&self) -> alloc::string::String {
        crate::joliet::decode_joliet_name(self.name())
    }

    /// Check if this entry's name appears to be Joliet-encoded (UTF-16 BE)
    #[cfg(feature = "alloc")]
    pub fn is_joliet_name(&self) -> bool {
        crate::joliet::is_likely_joliet_name(self.name())
    }

    #[inline]
    /// Performs the `system_use` operation.
    pub fn system_use(&self) -> &[u8] {
        let header = self.header();
        // ISO 9660 requires a padding byte after the file identifier when its
        // length is even, so the system use area always starts at an even offset.
        let su_start = (Self::DATA_START + header.file_identifier_len as usize + 1) & !1;
        if su_start >= header.len as usize {
            return &[];
        }
        &self.data[su_start..header.len as usize]
    }

    sync_only! {
        /// Returns the mutable system-use area needed by the synchronous writer.
        #[cfg(feature = "write")]
        pub(crate) fn system_use_mut(&mut self) -> &mut [u8] {
            let name_len = self.header().file_identifier_len as usize;
            let start = (Self::DATA_START + name_len + 1) & !1;
            let end = self.header().len as usize;
            &mut self.data[start..end]
        }
    }

    #[inline]
    /// Performs the `is_special` operation.
    pub fn is_special(&self) -> bool {
        self.name() == b"\x00" || self.name() == b"\x01"
    }

    #[inline]
    /// Performs the `is_directory` operation.
    pub fn is_directory(&self) -> bool {
        self.header().is_directory()
    }

    /// Performs the `is_file` operation.
    pub fn is_file(&self) -> bool {
        !self.header().is_directory()
    }

    /// Performs the `as_dir_ref` operation.
    pub fn as_dir_ref(&self) -> Result<DirectoryRef, NotADirectoryError> {
        if !self.is_directory() {
            return Err(NotADirectoryError);
        }

        let header = self.header();
        Ok(DirectoryRef {
            extent: LogicalSector(header.extent.read() as usize),
            size: header.data_len.read() as usize,
        })
    }

    /// Performs the `size` operation.
    pub fn size(&self) -> usize {
        self.header().len as usize
    }

    /// Performs the `to_bytes` operation.
    pub fn to_bytes(&self) -> &[u8] {
        &self.data[0..self.size()]
    }

    /// Performs the `new` operation.
    pub fn new(name: &[u8], system_use: &[u8], directory: DirectoryRef, flags: FileFlags) -> Self {
        let mut sel = Self::zeroed();
        assert!(
            !name.is_empty() && name.len() <= u8::MAX as usize,
            "ISO directory-record identifier must contain 1..=255 bytes"
        );
        // ISO 9660 (ECMA-119 9.1): a padding byte follows the file identifier
        // when its length is even, so the system use area starts at an even offset.
        let su_start = (Self::DATA_START + name.len() + 1) & !1;
        let total = su_start + system_use.len();
        // Record length must be even (ECMA-119 7.1.1).
        let record_len = (total + 1) & !1;
        assert!(
            record_len <= 255,
            "DirectoryRecord too large: {} bytes (name={}, su={})",
            record_len,
            name.len(),
            system_use.len()
        );
        *sel.header_mut() = DirectoryRecordHeader {
            len: record_len as u8,
            extended_attr_record: 0,
            extent: U32LsbMsb::new(directory.extent.0 as u32),
            data_len: U32LsbMsb::new(directory.size as u32),
            date_time: DirDateTime::now(),
            flags: flags.bits(),
            file_unit_size: 0,
            interleave_gap_size: 0,
            volume_sequence_number: U16LsbMsb::new(1),
            file_identifier_len: name.len() as u8,
        };
        sel.data[Self::DATA_START..Self::DATA_START + name.len()].copy_from_slice(name);
        // Padding byte (if any) is already zero from zeroed().
        sel.data[su_start..su_start + system_use.len()].copy_from_slice(system_use);
        sel
    }

    /// Performs the `with_len` operation.
    pub fn with_len(name_len: usize, su_len: usize) -> Self {
        let mut sel = Self::zeroed();
        assert!(
            (1..=u8::MAX as usize).contains(&name_len),
            "ISO directory-record identifier must contain 1..=255 bytes"
        );
        let su_start = (Self::DATA_START + name_len + 1) & !1;
        let total = su_start + su_len;
        let record_len = (total + 1) & !1;
        assert!(record_len <= u8::MAX as usize, "DirectoryRecord too large");
        sel.header_mut().len = record_len as u8;
        sel
    }
}

io_transform! {
impl DirectoryRecord {
    /// Performs the `parse` operation.
    pub async fn parse<R: Read>(reader: &mut R) -> io::Result<Self> {
        let mut sel = Self::zeroed();
        reader.read_exact(&mut sel.data[0..Self::DATA_START]).await?;
        let size = sel.size();
        if size == 0 {
            return Ok(sel);
        }
        let name_len = sel.header().file_identifier_len as usize;
        if size < Self::DATA_START + 1
            || !size.is_multiple_of(2)
            || Self::DATA_START + name_len > size
            || sel.header().flags & 0b0110_0000 != 0
            || !sel.header().extent.is_consistent()
            || !sel.header().data_len.is_consistent()
            || !sel.header().volume_sequence_number.is_consistent()
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "invalid ISO directory record",
            ));
        }
        if size > Self::DATA_START {
            reader.read_exact(&mut sel.data[Self::DATA_START..size]).await?;
        }
        if name_len.is_multiple_of(2) {
            let padding = Self::DATA_START + name_len;
            if padding >= size || sel.data[padding] != 0 {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid ISO directory-record identifier padding",
                ));
            }
        }
        Ok(sel)
    }

    /// Performs the `write` operation.
    pub async fn write<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
        let size = self.size();
        writer.write_all(&self.data[0..size]).await?;
        Ok(size)
    }
}
} // io_transform!

/// The root directory entry
#[repr(C)]
#[derive(Default, Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct RootDirectoryEntry {
    /// The `header` field.
    pub header: DirectoryRecordHeader,
    /// There is no name on the root directory, so this is always empty
    pub padding: u8,
}

#[repr(C)]
#[derive(Default, Debug, Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
/// Represents DirDateTime.
pub struct DirDateTime {
    /// Number of years since 1900
    year: u8,
    month: u8,
    day: u8,
    hour: u8,
    minute: u8,
    second: u8,
    offset: u8,
}

impl DirDateTime {
    #[cfg(feature = "std")]
    /// Performs the `now` operation.
    pub fn now() -> Self {
        use chrono::{Datelike, Timelike, Utc};
        let now = Utc::now();
        Self {
            year: (now.year() - 1900) as u8,
            month: now.month() as u8,
            day: now.day() as u8,
            hour: now.hour() as u8,
            minute: now.minute() as u8,
            second: now.second() as u8,
            // UTC offset is always 0
            offset: 0,
        }
    }

    /// Creates a zeroed datetime for no-std environments
    #[cfg(not(feature = "std"))]
    pub fn now() -> Self {
        Self::default()
    }
}

#[derive(Default, Debug, Clone, Copy)]
/// Represents DirectoryRef.
pub struct DirectoryRef {
    /// The `extent` field.
    pub extent: LogicalSector,
    /// The `size` field.
    pub size: usize,
}

sync_only! {
#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use alloc::vec::Vec;
    use std::io::Cursor;

    /// Vertical slice for ECMA-119:9.1 — parse `.` / `..` records from a sector.
    #[test]
    fn directory_record_parse_roundtrip() {
        // Minimal root directory sector (same layout as comprehensive_iso helper)
        let mut dir = vec![0u8; 2048];
        let mut offset = 0usize;
        for (id, flags) in [(0x00u8, 0x02u8), (0x01u8, 0x02u8)] {
            dir[offset] = 34;
            dir[offset + 2..offset + 6].copy_from_slice(&20u32.to_le_bytes());
            dir[offset + 6..offset + 10].copy_from_slice(&20u32.to_be_bytes());
            dir[offset + 10..offset + 14].copy_from_slice(&2048u32.to_le_bytes());
            dir[offset + 14..offset + 18].copy_from_slice(&2048u32.to_be_bytes());
            dir[offset + 25] = flags;
            dir[offset + 28..offset + 30].copy_from_slice(&1u16.to_le_bytes());
            dir[offset + 30..offset + 32].copy_from_slice(&1u16.to_be_bytes());
            dir[offset + 32] = 1;
            dir[offset + 33] = id;
            offset += 34;
        }

        let mut cursor = Cursor::new(&dir[..]);
        let dot = DirectoryRecord::parse(&mut cursor).expect("parse .");
        assert_eq!(dot.size(), 34);
        assert_eq!(core::mem::size_of::<DirectoryRecordHeader>(), 33);
        assert!(dot.is_directory());
        assert_eq!(dot.name(), b"\x00");
        assert_eq!(dot.header().extent.read(), 20);
        assert_eq!(dot.header().data_len.read(), 2048);

        let dotdot = DirectoryRecord::parse(&mut cursor).expect("parse ..");
        assert_eq!(dotdot.name(), b"\x01");
        assert!(dotdot.is_special());

        // new() + write/parse roundtrip for a file identifier
        let made = DirectoryRecord::new(
            b"README.;1",
            &[],
            DirectoryRef {
                extent: LogicalSector(42),
                size: 100,
            },
            FileFlags::empty(),
        );
        assert!(made.size() >= 33 + b"README.;1".len());
        assert!(!made.is_directory());
        assert_eq!(made.name(), b"README.;1");
        assert_eq!(made.header().extent.read(), 42);

        let mut out = Vec::new();
        made.write(&mut out).expect("write");
        let mut round = Cursor::new(&out[..]);
        let parsed = DirectoryRecord::parse(&mut round).expect("re-parse");
        assert_eq!(parsed.name(), made.name());
        assert_eq!(parsed.size(), made.size());
        assert_eq!(parsed.header().extent.read(), 42);
    }

    #[test]
    fn directory_record_rejects_invalid_bounds_and_endian_copy() {
        let mut short = vec![0_u8; 33];
        short[0] = 32;
        short[32] = 1;
        assert_eq!(
            DirectoryRecord::parse(&mut Cursor::new(short))
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidData
        );

        let mut mismatched = vec![0_u8; 34];
        mismatched[0] = 34;
        mismatched[2..6].copy_from_slice(&20_u32.to_le_bytes());
        mismatched[6..10].copy_from_slice(&21_u32.to_be_bytes());
        mismatched[28..30].copy_from_slice(&1_u16.to_le_bytes());
        mismatched[30..32].copy_from_slice(&1_u16.to_be_bytes());
        mismatched[32] = 1;
        assert_eq!(
            DirectoryRecord::parse(&mut Cursor::new(mismatched))
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidData
        );
    }
}
}

bitflags::bitflags! {
    /// Flags stored in an ISO 9660 directory record.
    #[derive(Clone, Copy)]
    pub struct FileFlags: u8 {
        /// Entry is hidden from ordinary directory listings.
        const HIDDEN = 0b0000_0001;
        /// Entry identifies a directory.
        const DIRECTORY = 0b0000_0010;
        /// Entry is an associated file.
        const ASSOCIATED_FILE = 0b0000_0100;
        /// Entry includes an extended-attribute record.
        const EXTENDED_ATTRIBUTES = 0b0000_1000;
        /// Entry has extended permission information.
        const EXTENDED_PERMISSIONS = 0b0001_0000;
        /// Entry continues in another directory record.
        const NOT_FINAL = 0b1000_0000;
    }
}