archmeld 1.3.0

Secure, memory-safe, type-safe CLI for multi-format archive extraction, inspection and decompression
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
//! `StuffIt` archive reading (inspired by `sit-rs` / `StuffIt` format).
//!
//! Parses `StuffIt` (`.sit`) archive headers and entry metadata.
//! `StuffIt` is a classic Mac OS archive format using proprietary compression.
//! This module provides read-only inspection and metadata extraction.
//!
// Binary parser: indexing, arithmetic, and numeric casts are
// fundamental to format parsing. Safety is ensured by fuzzing.
#![allow(clippy::indexing_slicing)]
#![allow(clippy::arithmetic_side_effects)]
#![allow(clippy::as_conversions)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::cast_sign_loss)]

use crate::error::{Error, Result};

/// `StuffIt` archive header.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StuffItHeader {
    /// Magic signature identifier.
    pub signature: String,
    /// Archive version.
    pub version: u8,
    /// Number of root-level entries.
    pub num_entries: u16,
    /// Total archive size as reported in header.
    pub archive_size: u32,
    /// Whether this is a `StuffIt` 5+ (`StuffIt` X) archive.
    pub is_stuffit5: bool,
}

/// A single entry in a `StuffIt` archive.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StuffItEntry {
    /// Entry name.
    pub name: String,
    /// Whether this entry is a directory.
    pub is_directory: bool,
    /// Compression method code.
    pub compression_method: u8,
    /// Compression method name.
    pub compression_method_name: String,
    /// Data fork compressed size.
    pub data_compressed_size: u32,
    /// Data fork uncompressed size.
    pub data_uncompressed_size: u32,
    /// Resource fork compressed size.
    pub rsrc_compressed_size: u32,
    /// Resource fork uncompressed size.
    pub rsrc_uncompressed_size: u32,
    /// Mac OS file type (4-char code).
    pub file_type: String,
    /// Mac OS creator code (4-char code).
    pub creator_code: String,
    /// Whether the entry is encrypted.
    pub is_encrypted: bool,
}

/// `StuffIt` archive analysis result.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StuffItAnalysis {
    /// Parsed archive header.
    pub header: StuffItHeader,
    /// Entries in the order the archive lists them.
    pub entries: Vec<StuffItEntry>,
}

/// Classic `StuffIt` magic: "SIT!" at offset 0.
const SIT_MAGIC: &[u8; 4] = b"SIT!";

/// `StuffIt` 5.x magic: "`StuffIt`" at offset 0.
const SIT5_MAGIC: &[u8; 7] = b"StuffIt";

/// SIT header size for classic format.
const SIT_HEADER_SIZE: usize = 22;

/// Probe whether data looks like a `StuffIt` archive.
#[must_use]
pub fn probe(data: &[u8]) -> bool {
    if data.len() < 4 {
        return false;
    }
    data.starts_with(SIT_MAGIC) || (data.len() >= 7 && data.starts_with(SIT5_MAGIC))
}

/// Parse a `StuffIt` archive and extract metadata.
///
/// # Errors
///
/// Returns error if the archive header is invalid.
pub fn analyze(data: &[u8]) -> Result<StuffItAnalysis> {
    if !probe(data) {
        return Err(Error::InvalidStuffIt("not a StuffIt archive".into()));
    }

    let is_stuffit5 = data.len() >= 7 && data.starts_with(SIT5_MAGIC);

    if is_stuffit5 {
        analyze_stuffit5(data)
    } else {
        analyze_classic(data)
    }
}

/// Parse classic `StuffIt` (v1-v4) archive.
fn analyze_classic(data: &[u8]) -> Result<StuffItAnalysis> {
    if data.len() < SIT_HEADER_SIZE {
        return Err(Error::InvalidStuffIt("header too short".into()));
    }

    let signature = String::from_utf8_lossy(&data[0..4]).into_owned();

    // Classic SIT header layout:
    // 0-3: "SIT!" magic
    // 4: number of entries (root level)
    // 5-8: total archive length
    // 9: version?
    let num_entries = u16::from(data[4]);
    let archive_size = u32::from_be_bytes([data[5], data[6], data[7], data[8]]);
    let version = data[9];

    let header = StuffItHeader {
        signature,
        version,
        num_entries,
        archive_size,
        is_stuffit5: false,
    };

    let entries = parse_classic_entries(data, SIT_HEADER_SIZE, num_entries)?;

    Ok(StuffItAnalysis { header, entries })
}

/// Parse classic `StuffIt` entries.
fn parse_classic_entries(data: &[u8], start: usize, count: u16) -> Result<Vec<StuffItEntry>> {
    let mut entries = Vec::new();
    let mut offset = start;

    for _ in 0..count {
        if offset + 4 >= data.len() {
            break;
        }

        // Classic SIT entry: variable-length name followed by fixed fields.
        // Simplified parsing—real SIT has complex entry layouts.
        let rsrc_compressed = read_u32_be(data, offset);
        offset += 4;
        let rsrc_uncompressed = read_u32_be(data, offset);
        offset += 4;
        let data_compressed = read_u32_be(data, offset);
        offset += 4;
        let data_uncompressed = read_u32_be(data, offset);
        offset += 4;

        // Resource compression method + data compression method
        let rsrc_method = if offset < data.len() {
            let m = data[offset];
            offset += 1;
            m
        } else {
            0
        };
        let data_method = if offset < data.len() {
            let m = data[offset];
            offset += 1;
            m
        } else {
            0
        };

        // Encrypted flag
        let is_encrypted = if offset < data.len() {
            let e = data[offset] & 0x10 != 0;
            offset += 1;
            e
        } else {
            false
        };

        // File type + creator (8 bytes)
        let file_type = if offset + 4 <= data.len() {
            let ft = String::from_utf8_lossy(&data[offset..offset + 4]).into_owned();
            offset += 4;
            ft
        } else {
            "????".into()
        };

        let creator_code = if offset + 4 <= data.len() {
            let cc = String::from_utf8_lossy(&data[offset..offset + 4]).into_owned();
            offset += 4;
            cc
        } else {
            "????".into()
        };

        // Name length + name
        let name_len = if offset < data.len() {
            let l = data[offset] as usize;
            offset += 1;
            l
        } else {
            0
        };

        let name = if offset + name_len <= data.len() {
            let n = String::from_utf8_lossy(&data[offset..offset + name_len]).into_owned();
            offset += name_len;
            n
        } else {
            format!("entry_{}", entries.len())
        };

        let method = data_method.max(rsrc_method);
        entries.push(StuffItEntry {
            name,
            is_directory: false,
            compression_method: method,
            compression_method_name: sit_method_name(method),
            data_compressed_size: data_compressed,
            data_uncompressed_size: data_uncompressed,
            rsrc_compressed_size: rsrc_compressed,
            rsrc_uncompressed_size: rsrc_uncompressed,
            file_type,
            creator_code,
            is_encrypted,
        });
    }

    Ok(entries)
}

/// Parse `StuffIt` 5.x (`StuffIt` X) archive.
fn analyze_stuffit5(data: &[u8]) -> Result<StuffItAnalysis> {
    if data.len() < 100 {
        return Err(Error::InvalidStuffIt("StuffIt 5 header too short".into()));
    }

    let signature = String::from_utf8_lossy(&data[0..7]).into_owned();

    // StuffIt 5 has a more complex header; extract what we safely can.
    let version = data[7];
    let header_size = read_u32_be(data, 14) as usize;

    // Total archive size
    let archive_size = if data.len() >= 86 {
        read_u32_be(data, 82)
    } else {
        data.len() as u32
    };

    // Number of top-level items
    let num_entries = if data.len() >= 90 {
        read_u16_be(data, 88)
    } else {
        0
    };

    let header = StuffItHeader {
        signature,
        version,
        num_entries,
        archive_size,
        is_stuffit5: true,
    };

    // StuffIt 5 entry parsing is complex and proprietary.
    // We report the header info and note that entries require
    // the proprietary decompression algorithms.
    let entries = if header_size < data.len() {
        parse_stuffit5_entries(data, header_size, num_entries)
    } else {
        Vec::new()
    };

    Ok(StuffItAnalysis { header, entries })
}

/// Attempt to parse `StuffIt` 5 entries (best-effort).
fn parse_stuffit5_entries(data: &[u8], start: usize, _count: u16) -> Vec<StuffItEntry> {
    let mut entries = Vec::new();
    let mut offset = start;

    // StuffIt 5 entries have a 50-byte fixed header followed by a variable name.
    while offset + 50 < data.len() && entries.len() < 1000 {
        // Heuristic: check for reasonable name length
        let name_len = if offset + 50 < data.len() {
            data[offset + 49] as usize
        } else {
            break;
        };

        if name_len == 0 || name_len > 255 || offset + 50 + name_len > data.len() {
            break;
        }

        let name = String::from_utf8_lossy(&data[offset + 50..offset + 50 + name_len]).into_owned();

        // Check for non-printable characters as a validity heuristic
        if name.chars().any(|c| c.is_control() && c != '\t') {
            break;
        }

        let is_directory = data[offset] & 0x40 != 0;
        let compression_method = data[offset + 3];
        let data_compressed = read_u32_be(data, offset + 8);
        let data_uncompressed = read_u32_be(data, offset + 12);
        let rsrc_compressed = read_u32_be(data, offset + 16);
        let rsrc_uncompressed = read_u32_be(data, offset + 20);
        let is_encrypted = data[offset + 4] & 0x10 != 0;

        let file_type = if offset + 28 <= data.len() {
            String::from_utf8_lossy(&data[offset + 24..offset + 28]).into_owned()
        } else {
            "????".into()
        };

        let creator_code = if offset + 32 <= data.len() {
            String::from_utf8_lossy(&data[offset + 28..offset + 32]).into_owned()
        } else {
            "????".into()
        };

        entries.push(StuffItEntry {
            name,
            is_directory,
            compression_method,
            compression_method_name: sit_method_name(compression_method),
            data_compressed_size: data_compressed,
            data_uncompressed_size: data_uncompressed,
            rsrc_compressed_size: rsrc_compressed,
            rsrc_uncompressed_size: rsrc_uncompressed,
            file_type,
            creator_code,
            is_encrypted,
        });

        offset += 50 + name_len;
    }

    entries
}

/// Map `StuffIt` compression method code to name.
fn sit_method_name(method: u8) -> String {
    match method {
        0 => "none (stored)".into(),
        1 => "RLE".into(),
        2 => "LZC (Lempel-Ziv)".into(),
        3 => "Huffman".into(),
        5 => "LZAH".into(),
        6 => "fixedHuffman".into(),
        8 => "MW (Miller-Wegman)".into(),
        13 => "LZ+Huffman (method 13)".into(),
        14 => "Installer".into(),
        15 => "Arsenic".into(),
        _ => format!("unknown ({method})"),
    }
}

fn read_u32_be(data: &[u8], offset: usize) -> u32 {
    if offset + 4 <= data.len() {
        u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ])
    } else {
        0
    }
}

fn read_u16_be(data: &[u8], offset: usize) -> u16 {
    if offset + 2 <= data.len() {
        u16::from_be_bytes([data[offset], data[offset + 1]])
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_probe_classic() {
        let data = b"SIT!\x05\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
        assert!(probe(data));
    }

    #[test]
    fn test_probe_stuffit5() {
        let mut data = vec![0u8; 100];
        data[..7].copy_from_slice(b"StuffIt");
        assert!(probe(&data));
    }

    #[test]
    fn test_probe_not_stuffit() {
        let data = b"PK\x03\x04extra";
        assert!(!probe(data));
    }

    #[test]
    fn test_analyze_classic_header() {
        let mut data = vec![0u8; 100];
        data[0..4].copy_from_slice(b"SIT!");
        data[4] = 2; // 2 entries
        data[5..9].copy_from_slice(&100u32.to_be_bytes()); // archive size
        data[9] = 1; // version

        let result = analyze(&data);
        assert!(result.is_ok());
        let analysis = result.expect("analysis should succeed");
        assert_eq!(analysis.header.signature, "SIT!");
        assert_eq!(analysis.header.num_entries, 2);
        assert!(!analysis.header.is_stuffit5);
    }

    #[test]
    fn test_analyze_not_stuffit() {
        let data = b"NOT_A_SIT_ARCHIVE";
        assert!(analyze(data).is_err());
    }

    #[test]
    fn test_method_names() {
        assert_eq!(sit_method_name(0), "none (stored)");
        assert_eq!(sit_method_name(1), "RLE");
        assert_eq!(sit_method_name(15), "Arsenic");
        assert!(sit_method_name(99).contains("unknown"));
    }
}