sit-rs 0.3.0

Rust-native extraction for StuffIt Expander archive files
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use std::{
    fmt::Debug,
    fs,
    io::{self},
    path::{self},
    rc::Rc,
};

use binrw::BinReaderExt;
use macintosh_utils::Fork;

use crate::{
    Entry, Error, VerifyingEntryReader,
    structs::{
        Algorithm, ArchiveHeader, File, Version, v1,
        v5::{self, EntryBinReadArgs},
    },
    verify::VerifyingIterator,
};

pub struct EntryReader<'a, T: io::Read + io::Seek>(crate::algos::EntryReader<'a, T>, u16);

impl<'a, T: io::Read + io::Seek> EntryReader<'a, T> {
    #[inline]
    pub(crate) fn try_from(
        reader: &'a mut Rc<T>,
        algo: Algorithm,
        uncompressed_size: u64,
        compressed_size: usize,
        offset: u64,
        checksum: u16,
    ) -> Result<Self, Error> {
        Ok(Self(
            crate::algos::EntryReader::try_from(
                reader,
                algo,
                uncompressed_size,
                compressed_size,
                offset,
            )?,
            checksum,
        ))
    }

    pub fn verifying(self) -> VerifyingEntryReader<'a, T> {
        self.0.verifying(self.1)
    }

    pub fn verify(self) -> Result<(), Error> {
        // Arsenic compression uses 32-bit checksums interleaved with the compressed blocks
        // so it get's special treatment
        let is_arsenic = matches!(self.0, crate::algos::EntryReader::Arsenic { .. });

        VerifyingEntryReader::new(self.0, self.1, is_arsenic).slurp()
    }
}

impl<'a, T: io::Read + io::Seek> io::Read for EntryReader<'a, T> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<'a, T: io::Read + io::Seek> io::Seek for EntryReader<'a, T> {
    #[inline]
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        self.0.seek(pos)
    }

    #[inline]
    fn stream_len(&mut self) -> io::Result<u64> {
        self.0.stream_len()
    }

    #[inline]
    fn stream_position(&mut self) -> io::Result<u64> {
        self.0.stream_position()
    }
}

#[derive(Debug)]
pub struct Archive<R> {
    header_location: u64,
    header: ArchiveHeader,
    inner: Rc<R>,
}

impl Archive<fs::File> {
    pub fn open_path<P: AsRef<path::Path>>(p: P) -> Result<Self, Error> {
        Archive::try_from(fs::File::open(p.as_ref())?)
    }
}

impl<R: io::Seek + io::Read> Archive<R> {
    pub fn try_from(mut inner: R) -> Result<Self, Error> {
        let header_location = inner.stream_position()?;

        match inner.read_be() {
            Ok(header) => Ok(Self {
                inner: Rc::new(inner),
                header_location,
                header,
            }),
            Err(binrw::Error::AssertFail { .. }) => Err(Error::InvalidFile(
                crate::error::InvalidFileReason::InvalidHeader,
            )),
            Err(e) => Err(e.into()),
        }
    }

    pub fn version(&self) -> Version {
        self.header.version()
    }

    pub fn header(&self) -> &ArchiveHeader {
        &self.header
    }

    /// Verify the archive's integrity by validating all checksums
    pub fn verify(&mut self) -> Result<(), Error> {
        if !self.header.checksum_valid() {
            return Err(Error::ChecksumMismatch(
                crate::error::ChecksumLocation::ArchiveHeader,
            ));
        }

        self.iter().try_for_each(|e| self.verify_entry(e))
    }

    /// Open an archive entry for reading
    pub fn open_fork<'a, E: ReadableEntry>(
        &'a mut self,
        entry: &E,
        fork: Fork,
    ) -> Result<EntryReader<'a, R>, Error> {
        let algo = entry.algorithm(fork);
        let compressed_size = entry.compressed_size(fork);
        let uncompressed_size = entry.uncompressed_size(fork);
        let offset = entry.offset(fork);
        let checksum = entry.checksum(fork);

        if entry.encrypted(fork) {
            return Err(Error::UnsupportedFeature(
                crate::error::UnsupportedFeature::Encryption,
            ));
        }

        EntryReader::try_from(
            &mut self.inner,
            algo,
            uncompressed_size as u64,
            compressed_size,
            offset,
            checksum,
        )
    }

    /// Iterate through all archive entries
    pub fn iter(&self) -> EntryIterator<R> {
        // SAFETY: Archives can only be iterated once, and opening an entry locks the archive until
        // the handle is released. That ensures we don't modify the underlying reader concurrently
        self.ensure_not_iterating();

        let catalog_offset = match &self.header {
            ArchiveHeader::V1(hdr) => self.header_location + hdr.first_entry_offset(),
            ArchiveHeader::V5(hdr) => self.header_location + hdr.first_entry_offset(),
        };

        EntryIterator::new(
            self.inner.clone(),
            self.header.entry_count(),
            catalog_offset,
            matches!(self.header, ArchiveHeader::V1(_)),
        )
    }

    /// Returns the underlying reader
    pub fn into_inner(self) -> R {
        self.ensure_not_iterating();

        // SAFETY: Since no one is iterating, and any open entry would borrow the archive mutably
        // this is safe
        let Archive { inner, .. } = self;
        unsafe { Rc::try_unwrap(inner).unwrap_unchecked() }
    }

    pub fn reset(&mut self) -> Result<(), Error> {
        self.ensure_not_iterating();

        // SAFETY: Since no one is iterating, and any open entry would borrow the archive mutably,
        // this is safe
        unsafe {
            Rc::get_mut_unchecked(&mut self.inner)
                .seek(io::SeekFrom::Start(self.header_location))?;
        }

        Ok(())
    }

    fn ensure_not_iterating(&self) {
        if Rc::strong_count(&self.inner) != 1 || Rc::weak_count(&self.inner) != 0 {
            panic!("Can not modify archive while an iterator is runnning")
        }
    }

    /// Verify integrity of an entry
    pub fn verify_entry(&mut self, e: Entry) -> Result<(), Error> {
        if let Entry::Directory(crate::structs::Directory::V5(dir)) = &e
            && dir.marks_end()
        {
            return Ok(());
        }

        if !e.is_file() {
            return Ok(());
        }

        if e.has(Fork::Resource) {
            self.open_fork(&e, Fork::Resource)?.verifying().slurp()?;
        }

        if e.has(Fork::Data) {
            self.open_fork(&e, Fork::Data)?.verifying().slurp()?;
        }

        Ok(())
    }
}

/// Trait implemented by archive entries to create a decompression stream
pub trait ReadableEntry {
    /// Algorithm used to compress the entry's data or resource fork
    fn algorithm(&self, fork: Fork) -> Algorithm;
    /// Amount of bytes occupied by the specified fork
    fn compressed_size(&self, fork: Fork) -> usize;
    /// Size of the fork in bytes after decompression
    fn uncompressed_size(&self, fork: Fork) -> usize;
    fn encrypted(&self, fork: Fork) -> bool;
    /// Offset from start of the archive header to beginning of the compressed data
    fn offset(&self, fork: Fork) -> u64;
    /// Checksum of the uncompressed data
    fn checksum(&self, fork: Fork) -> u16;
}

impl ReadableEntry for Entry {
    fn encrypted(&self, fork: Fork) -> bool {
        match self {
            Entry::File(e) => e.encrypted(fork),
            Entry::Directory(_) => false,
            Entry::DirectoryEnd(_) => false,
        }
    }

    fn algorithm(&self, fork: Fork) -> Algorithm {
        match self {
            Entry::File(e) => e.algorithm(fork),
            Entry::Directory(e) => e.algorithm(fork),
            Entry::DirectoryEnd(_) => Algorithm::None,
        }
    }

    fn compressed_size(&self, fork: Fork) -> usize {
        match self {
            Entry::File(e) => e.compressed_size(fork),
            Entry::Directory(e) => e.compressed_size(fork),
            Entry::DirectoryEnd(_) => 0,
        }
    }

    fn uncompressed_size(&self, fork: Fork) -> usize {
        match self {
            Entry::File(e) => e.uncompressed_size(fork),
            Entry::Directory(e) => e.uncompressed_size(fork),
            Entry::DirectoryEnd(_) => 0,
        }
    }

    fn offset(&self, fork: Fork) -> u64 {
        match self {
            Entry::File(e) => e.offset(fork),
            Entry::Directory(e) => e.offset(fork),
            Entry::DirectoryEnd(off) => *off,
        }
    }

    fn checksum(&self, fork: Fork) -> u16 {
        match self {
            Entry::File(file) => file.checksum(fork),
            Entry::Directory(_) => 0,
            Entry::DirectoryEnd(_) => 0,
        }
    }
}

impl ReadableEntry for File {
    #[inline]
    fn algorithm(&self, fork: Fork) -> Algorithm {
        File::compression_method(self, fork)
    }

    #[inline]
    fn compressed_size(&self, fork: Fork) -> usize {
        File::compressed_size(self, fork)
    }

    #[inline]
    fn uncompressed_size(&self, fork: Fork) -> usize {
        File::uncompressed_size(self, fork)
    }

    #[inline]
    fn encrypted(&self, fork: Fork) -> bool {
        File::encrypted(self, fork)
    }

    #[inline]
    fn offset(&self, fork: Fork) -> u64 {
        File::offset(self, fork)
    }

    #[inline]
    fn checksum(&self, fork: Fork) -> u16 {
        File::checksum(self, fork)
    }
}

impl ReadableEntry for v5::File {
    #[inline]
    fn algorithm(&self, fork: Fork) -> Algorithm {
        v5::File::compression_method(self, fork)
    }

    #[inline]
    fn compressed_size(&self, fork: Fork) -> usize {
        v5::File::compressed_size(self, fork)
    }

    #[inline]
    fn uncompressed_size(&self, fork: Fork) -> usize {
        v5::File::uncompressed_size(self, fork)
    }

    #[inline]
    fn encrypted(&self, fork: Fork) -> bool {
        v5::File::encrypted(self, fork)
    }

    #[inline]
    fn offset(&self, fork: Fork) -> u64 {
        v5::File::offset(self, fork)
    }

    #[inline]
    fn checksum(&self, fork: Fork) -> u16 {
        v5::File::checksum(self, fork)
    }
}

impl ReadableEntry for v1::File {
    #[inline]
    fn algorithm(&self, fork: Fork) -> Algorithm {
        v1::File::compression_method(self, fork)
    }

    #[inline]
    fn compressed_size(&self, fork: Fork) -> usize {
        v1::File::compressed_size(self, fork)
    }

    #[inline]
    fn uncompressed_size(&self, fork: Fork) -> usize {
        v1::File::uncompressed_size(self, fork)
    }

    #[inline]
    fn encrypted(&self, fork: Fork) -> bool {
        v1::File::encrypted(self, fork)
    }

    #[inline]
    fn offset(&self, fork: Fork) -> u64 {
        v1::File::offset(self, fork)
    }

    #[inline]
    fn checksum(&self, fork: Fork) -> u16 {
        v1::File::checksum(self, fork)
    }
}

pub struct EntryIterator<R: io::Read + io::Seek> {
    next_offset: u64,
    next_file_index: usize,
    stack: Vec<u32>,
    v1: bool,

    pub(crate) reader: Rc<R>,
}

impl<R: io::Read + io::Seek> EntryIterator<R> {
    fn new(reader: Rc<R>, entry_count: usize, offset: u64, v1: bool) -> Self {
        Self {
            next_offset: offset,
            next_file_index: 0,
            stack: vec![entry_count as u32],
            reader,
            v1,
        }
    }

    pub fn verifying(self) -> VerifyingIterator<R> {
        let Self {
            next_offset,
            stack,
            reader,
            v1,
            next_file_index,
        } = self;

        VerifyingIterator {
            next_offset,
            stack,
            reader,
            v1,
            _next_file_index: next_file_index,
        }
    }
}

impl<R: io::Read + io::Seek> Iterator for EntryIterator<R> {
    type Item = Entry;

    fn next(&mut self) -> Option<Self::Item> {
        let reader = unsafe { Rc::get_mut_unchecked(&mut self.reader) };

        match self.stack.last_mut() {
            None => return None,
            Some(0) => {
                self.stack.pop();

                // Don't send directory end marker for the root catalog
                return if self.stack.is_empty() {
                    None
                } else {
                    Some(Entry::DirectoryEnd(self.next_offset))
                };
            }
            Some(d) => *d -= 1,
        }

        let Ok(entry_offset) = reader.seek(io::SeekFrom::Start(self.next_offset)) else {
            log::warn!("Failed seeking to next archive entry");
            return None;
        };

        if self.v1 {
            let Ok(entry) = reader.read_be::<v1::Entry>() else {
                return None;
            };

            let Ok(payload_offset) = reader.stream_position() else {
                return None;
            };

            match entry {
                v1::Entry::Directory(dir) => {
                    self.next_offset = payload_offset;
                    self.stack.push(u32::MAX);

                    Some(Entry::Directory(dir.into()))
                }
                v1::Entry::DirectoryEnd => {
                    self.next_offset = payload_offset;
                    self.stack.pop();

                    Some(Entry::DirectoryEnd(payload_offset))
                }
                v1::Entry::File(mut file) => {
                    self.next_offset = payload_offset
                        + file.data_compressed_size as u64
                        + file.rsrc_compressed_size as u64;
                    log::debug!(
                        "Entry: {}, {:?} {} 0x{:04x}",
                        file.file_name,
                        file.data_compression,
                        file.data_compressed_size,
                        file.checksum(Fork::Data)
                    );

                    file.index = self.next_file_index;
                    self.next_file_index += 1;

                    Some(Entry::File(file.into()))
                }
            }
        } else {
            let Ok(entry) = reader.read_be_args::<v5::Entry>(
                EntryBinReadArgs::builder().offset(entry_offset).finalize(),
            ) else {
                return None;
            };

            let Ok(payload_offset) = reader.stream_position() else {
                return None;
            };

            match entry {
                v5::Entry::Directory(dir) => {
                    if dir.marks_end() {
                        self.next_offset = payload_offset;
                        return self.next();
                    }

                    self.stack.push(dir.child_count);
                    self.next_offset = dir.first_child_offset;

                    Some(Entry::Directory(dir.into()))
                }
                v5::Entry::File(mut file) => {
                    self.next_offset = file.next_entry_offset as u64;
                    file.payload_offset = payload_offset;

                    file.index = self.next_file_index;
                    self.next_file_index += 1;

                    Some(Entry::File(file.into()))
                }
            }
        }
    }
}