chdlady-core 0.1.0

Core container manipulation for CHD v5 format
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
//! CHD v3/v4/v5 header parsing, validation, and serialization.
use crate::error::ChdError;
use std::io::{Read, Seek, SeekFrom, Write};

/// Expected magic header signature for CHD containers.
pub const CHD_V5_SIGNATURE: &[u8; 8] = b"MComprHD";

/// Standard header length for CHD v3 (120 bytes).
pub const CHD_V3_HEADER_SIZE: u32 = 120;

/// Standard format version 3.
pub const CHD_V3_VERSION: u32 = 3;

/// Standard header length for CHD v4 (108 bytes).
pub const CHD_V4_HEADER_SIZE: u32 = 108;

/// Standard format version 4.
pub const CHD_V4_VERSION: u32 = 4;

/// Standard header length for CHD v5 (124 bytes).
pub const CHD_V5_HEADER_SIZE: u32 = 124;

/// Standard format version 5.
pub const CHD_V5_VERSION: u32 = 5;

/// Parsed CHD v5 header (124 bytes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChdHeader {
    /// Magic signature, must be b"MComprHD".
    pub tag: [u8; 8],
    /// Length of the header in bytes (always 124 for v5).
    pub length: u32,
    /// Version number (always 5 for v5).
    pub version: u32,
    /// FourCC compression codecs configured for this container.
    pub compressors: [u32; 4],
    /// Total logical uncompressed bytes.
    pub logical_bytes: u64,
    /// Absolute file offset to the hunk map.
    pub map_offset: u64,
    /// Absolute file offset to the first metadata header (or 0 if none).
    pub meta_offset: u64,
    /// Size of each uncompressed hunk in bytes.
    pub hunk_bytes: u32,
    /// Size of internal units in bytes.
    pub unit_bytes: u32,
    /// SHA-1 hash of the raw uncompressed data.
    pub raw_sha1: [u8; 20],
    /// Overall SHA-1 hash (raw data + checksummed metadata).
    pub sha1: [u8; 20],
    /// SHA-1 hash of parent CHD container (zeros if standalone).
    pub parent_sha1: [u8; 20],
}

impl ChdHeader {
    /// Returns the total number of hunks in the container.
    pub fn hunk_count(&self) -> u64 {
        if self.hunk_bytes == 0 {
            0
        } else {
            self.logical_bytes.div_ceil(self.hunk_bytes as u64)
        }
    }

    /// Returns the total number of units in the container.
    pub fn unit_count(&self) -> u64 {
        if self.unit_bytes == 0 {
            0
        } else {
            self.logical_bytes.div_ceil(self.unit_bytes as u64)
        }
    }

    /// Returns true if at least one compression codec is configured.
    pub fn is_compressed(&self) -> bool {
        self.compressors.iter().any(|&c| c != 0)
    }

    /// Returns the absolute file offset where raw SHA-1 is stored in the header.
    pub fn raw_sha1_offset(&self) -> u64 {
        match self.version {
            3 => 80,
            4 => 88,
            _ => 64,
        }
    }

    /// Returns the absolute file offset where overall SHA-1 is stored in the header.
    pub fn sha1_offset(&self) -> u64 {
        match self.version {
            3 => 80,
            4 => 48,
            _ => 84,
        }
    }

    /// Reads and parses any supported CHD header (v3, v4, or v5) from the reader.
    pub fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, ChdError> {
        reader.seek(SeekFrom::Start(0))?;
        let mut magic = [0u8; 16];
        reader.read_exact(&mut magic)?;
        if &magic[0..8] != CHD_V5_SIGNATURE {
            return Err(ChdError::InvalidMagic);
        }
        let length = u32::from_be_bytes([magic[8], magic[9], magic[10], magic[11]]);
        let version = u32::from_be_bytes([magic[12], magic[13], magic[14], magic[15]]);
        match version {
            3 => Self::read_v3(reader, length),
            4 => Self::read_v4(reader, length),
            5 => Self::read_v5(reader),
            _ => Err(ChdError::UnsupportedVersion(version)),
        }
    }

    /// Reads and parses a CHD v3 header from the reader.
    pub fn read_v3<R: Read + Seek>(reader: &mut R, length: u32) -> Result<Self, ChdError> {
        if length != CHD_V3_HEADER_SIZE {
            return Err(ChdError::InvalidHeaderSize(length));
        }
        reader.seek(SeekFrom::Start(0))?;
        let mut buf = [0u8; CHD_V3_HEADER_SIZE as usize];
        reader.read_exact(&mut buf)?;

        let flags = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);
        let comp_type = u32::from_be_bytes([buf[20], buf[21], buf[22], buf[23]]);
        let logical_bytes = u64::from_be_bytes([
            buf[28], buf[29], buf[30], buf[31], buf[32], buf[33], buf[34], buf[35],
        ]);
        let meta_offset = u64::from_be_bytes([
            buf[36], buf[37], buf[38], buf[39], buf[40], buf[41], buf[42], buf[43],
        ]);
        let hunk_bytes = u32::from_be_bytes([buf[76], buf[77], buf[78], buf[79]]);
        if hunk_bytes == 0 || hunk_bytes > crate::MAX_HUNK_BYTES {
            return Err(ChdError::InvalidData(format!(
                "invalid hunk_bytes: {}",
                hunk_bytes
            )));
        }

        let mut sha1 = [0u8; 20];
        sha1.copy_from_slice(&buf[80..100]);

        let mut parent_sha1 = [0u8; 20];
        if (flags & 1) != 0 {
            parent_sha1.copy_from_slice(&buf[100..120]);
        }

        let mut compressors = [0u32; 4];
        match comp_type {
            0 => {}
            1 | 2 => compressors[0] = u32::from_be_bytes(*b"zlib"),
            3 => compressors[0] = u32::from_be_bytes(*b"avhu"),
            _ => {
                return Err(ChdError::Codec(format!(
                    "unknown v3 compression type {}",
                    comp_type
                )))
            }
        }

        let mut unit_bytes = hunk_bytes;
        if meta_offset != 0 {
            if let Ok(metadata_list) = crate::metadata::read_all_metadata(reader, meta_offset) {
                for meta in &metadata_list {
                    if meta.metatag == u32::from_be_bytes(*b"GDDD")
                        || meta.metatag == u32::from_be_bytes(*b"CDTR")
                        || meta.metatag == u32::from_be_bytes(*b"CDRM")
                    {
                        unit_bytes = 2448;
                        break;
                    } else if meta.metatag == u32::from_be_bytes(*b"GDSY") {
                        if let Ok(text) = std::str::from_utf8(&meta.value) {
                            if let Some(pos) = text.find("BPS:") {
                                if let Ok(bps) = text[pos + 4..]
                                    .trim()
                                    .split(',')
                                    .next()
                                    .unwrap_or("")
                                    .parse::<u32>()
                                {
                                    if bps > 0 {
                                        unit_bytes = bps;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(Self {
            tag: *CHD_V5_SIGNATURE,
            length: CHD_V3_HEADER_SIZE,
            version: CHD_V3_VERSION,
            compressors,
            logical_bytes,
            map_offset: CHD_V3_HEADER_SIZE as u64,
            meta_offset,
            hunk_bytes,
            unit_bytes,
            raw_sha1: sha1,
            sha1,
            parent_sha1,
        })
    }

    /// Reads and parses a CHD v4 header from the reader.
    pub fn read_v4<R: Read + Seek>(reader: &mut R, length: u32) -> Result<Self, ChdError> {
        if length != CHD_V4_HEADER_SIZE {
            return Err(ChdError::InvalidHeaderSize(length));
        }
        reader.seek(SeekFrom::Start(0))?;
        let mut buf = [0u8; CHD_V4_HEADER_SIZE as usize];
        reader.read_exact(&mut buf)?;

        let flags = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);
        let comp_type = u32::from_be_bytes([buf[20], buf[21], buf[22], buf[23]]);
        let logical_bytes = u64::from_be_bytes([
            buf[28], buf[29], buf[30], buf[31], buf[32], buf[33], buf[34], buf[35],
        ]);
        let meta_offset = u64::from_be_bytes([
            buf[36], buf[37], buf[38], buf[39], buf[40], buf[41], buf[42], buf[43],
        ]);
        let hunk_bytes = u32::from_be_bytes([buf[44], buf[45], buf[46], buf[47]]);
        if hunk_bytes == 0 || hunk_bytes > crate::MAX_HUNK_BYTES {
            return Err(ChdError::InvalidData(format!(
                "invalid hunk_bytes: {}",
                hunk_bytes
            )));
        }

        let mut sha1 = [0u8; 20];
        sha1.copy_from_slice(&buf[48..68]);

        let mut parent_sha1 = [0u8; 20];
        if (flags & 1) != 0 {
            parent_sha1.copy_from_slice(&buf[68..88]);
        }

        let mut raw_sha1 = [0u8; 20];
        raw_sha1.copy_from_slice(&buf[88..108]);

        let mut compressors = [0u32; 4];
        match comp_type {
            0 => {}
            1 | 2 => compressors[0] = u32::from_be_bytes(*b"zlib"),
            3 => compressors[0] = u32::from_be_bytes(*b"avhu"),
            _ => {
                return Err(ChdError::Codec(format!(
                    "unknown v4 compression type {}",
                    comp_type
                )))
            }
        }

        let mut unit_bytes = hunk_bytes;
        if meta_offset != 0 {
            if let Ok(metadata_list) = crate::metadata::read_all_metadata(reader, meta_offset) {
                for meta in &metadata_list {
                    if meta.metatag == u32::from_be_bytes(*b"GDDD")
                        || meta.metatag == u32::from_be_bytes(*b"CDTR")
                        || meta.metatag == u32::from_be_bytes(*b"CDRM")
                    {
                        unit_bytes = 2448;
                        break;
                    } else if meta.metatag == u32::from_be_bytes(*b"GDSY") {
                        if let Ok(text) = std::str::from_utf8(&meta.value) {
                            if let Some(pos) = text.find("BPS:") {
                                if let Ok(bps) = text[pos + 4..]
                                    .trim()
                                    .split(',')
                                    .next()
                                    .unwrap_or("")
                                    .parse::<u32>()
                                {
                                    if bps > 0 {
                                        unit_bytes = bps;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok(Self {
            tag: *CHD_V5_SIGNATURE,
            length: CHD_V4_HEADER_SIZE,
            version: CHD_V4_VERSION,
            compressors,
            logical_bytes,
            map_offset: CHD_V4_HEADER_SIZE as u64,
            meta_offset,
            hunk_bytes,
            unit_bytes,
            raw_sha1,
            sha1,
            parent_sha1,
        })
    }

    /// Reads and parses a CHD v5 header from the provided reader.
    pub fn read_v5<R: Read + Seek>(reader: &mut R) -> Result<Self, ChdError> {
        reader.seek(SeekFrom::Start(0))?;
        let mut buf = [0u8; CHD_V5_HEADER_SIZE as usize];
        reader.read_exact(&mut buf)?;

        if &buf[0..8] != CHD_V5_SIGNATURE {
            return Err(ChdError::InvalidMagic);
        }

        let length = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]);
        if length != CHD_V5_HEADER_SIZE {
            return Err(ChdError::InvalidHeaderSize(length));
        }

        let version = u32::from_be_bytes([buf[12], buf[13], buf[14], buf[15]]);
        if version != CHD_V5_VERSION {
            return Err(ChdError::UnsupportedVersion(version));
        }

        let mut compressors = [0u32; 4];
        for (i, item) in compressors.iter_mut().enumerate() {
            let start = 16 + i * 4;
            *item =
                u32::from_be_bytes([buf[start], buf[start + 1], buf[start + 2], buf[start + 3]]);
        }

        let logical_bytes = u64::from_be_bytes([
            buf[32], buf[33], buf[34], buf[35], buf[36], buf[37], buf[38], buf[39],
        ]);
        let map_offset = u64::from_be_bytes([
            buf[40], buf[41], buf[42], buf[43], buf[44], buf[45], buf[46], buf[47],
        ]);
        let meta_offset = u64::from_be_bytes([
            buf[48], buf[49], buf[50], buf[51], buf[52], buf[53], buf[54], buf[55],
        ]);
        let hunk_bytes = u32::from_be_bytes([buf[56], buf[57], buf[58], buf[59]]);
        let unit_bytes = u32::from_be_bytes([buf[60], buf[61], buf[62], buf[63]]);

        if hunk_bytes == 0 || unit_bytes == 0 {
            return Err(ChdError::InvalidData(
                "hunk_bytes and unit_bytes must be non-zero".into(),
            ));
        }
        if hunk_bytes > crate::MAX_HUNK_BYTES {
            return Err(ChdError::InvalidData(format!(
                "hunk_bytes ({}) exceeds maximum allowed ({})",
                hunk_bytes,
                crate::MAX_HUNK_BYTES
            )));
        }
        if !hunk_bytes.is_multiple_of(unit_bytes) {
            return Err(ChdError::InvalidData(format!(
                "hunk_bytes ({}) must be a multiple of unit_bytes ({})",
                hunk_bytes, unit_bytes
            )));
        }

        let mut raw_sha1 = [0u8; 20];
        raw_sha1.copy_from_slice(&buf[64..84]);

        let mut sha1 = [0u8; 20];
        sha1.copy_from_slice(&buf[84..104]);

        let mut parent_sha1 = [0u8; 20];
        parent_sha1.copy_from_slice(&buf[104..124]);

        Ok(Self {
            tag: *CHD_V5_SIGNATURE,
            length,
            version,
            compressors,
            logical_bytes,
            map_offset,
            meta_offset,
            hunk_bytes,
            unit_bytes,
            raw_sha1,
            sha1,
            parent_sha1,
        })
    }

    /// Serializes this CHD v5 header to the provided writer.
    pub fn write_v5<W: Write + Seek>(&self, writer: &mut W) -> Result<(), ChdError> {
        writer.seek(SeekFrom::Start(0))?;
        let mut buf = [0u8; CHD_V5_HEADER_SIZE as usize];

        buf[0..8].copy_from_slice(&self.tag);
        buf[8..12].copy_from_slice(&self.length.to_be_bytes());
        buf[12..16].copy_from_slice(&self.version.to_be_bytes());

        for (i, &comp) in self.compressors.iter().enumerate() {
            let start = 16 + i * 4;
            buf[start..start + 4].copy_from_slice(&comp.to_be_bytes());
        }

        buf[32..40].copy_from_slice(&self.logical_bytes.to_be_bytes());
        buf[40..48].copy_from_slice(&self.map_offset.to_be_bytes());
        buf[48..56].copy_from_slice(&self.meta_offset.to_be_bytes());
        buf[56..60].copy_from_slice(&self.hunk_bytes.to_be_bytes());
        buf[60..64].copy_from_slice(&self.unit_bytes.to_be_bytes());
        buf[64..84].copy_from_slice(&self.raw_sha1);
        buf[84..104].copy_from_slice(&self.sha1);
        buf[104..124].copy_from_slice(&self.parent_sha1);

        writer.write_all(&buf)?;
        Ok(())
    }
}