Skip to main content

powerio_archive/
end_records.rs

1//! Compatibility preflight for adapters using ZIP reader fallback.
2//! This bounds metadata allocation; it does not validate payloads or names.
3
4use memchr::memmem;
5
6const END_RECORD: &[u8] = b"PK\x05\x06";
7const ZIP64_END_LOCATOR: &[u8] = b"PK\x06\x07";
8const ZIP64_END_RECORD: &[u8] = b"PK\x06\x06";
9
10/// The entry counts an archive's end records declare.
11#[derive(Debug, PartialEq, Eq)]
12pub struct DeclaredEntries {
13    /// The count of the end record zip 8.6 examines first: the last end
14    /// record signature whose comment fits in the archive, or the Zip64
15    /// record its locator names when a 16 bit field is saturated.
16    pub first: u64,
17    /// The largest count of any Zip64 record an end record's locator names,
18    /// zero when there is none.
19    pub largest_zip64: u64,
20}
21
22/// Why an archive's end records were refused before opening it.
23#[derive(Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum EndRecordRefusal {
26    /// The reader would accept no end record.
27    Missing,
28    /// The archive holds more than `max_end_records` end records.
29    TooMany,
30}
31
32/// What one end record declares.
33enum EndCount {
34    /// The record's own 16 bit count.
35    Zip32(u64),
36    /// The largest count of the Zip64 records its locator names.
37    Zip64(u64),
38}
39
40/// Read every end record zip 8.6 may examine, last first.
41///
42/// These checks are a subset of those the reader applies before it reserves
43/// a table, so it may reject a record accepted here and fall back to an
44/// earlier one. The count comparison in the adapter then refuses the
45/// archive unless the counts agree, and every Zip64 count the reader could
46/// reach that way is in `largest_zip64`.
47pub fn declared_entries(
48    bytes: &[u8],
49    max_end_records: usize,
50) -> std::result::Result<DeclaredEntries, EndRecordRefusal> {
51    // memchr searches forward several times faster than in reverse.
52    let signatures: Vec<usize> = memmem::find_iter(bytes, END_RECORD)
53        .take(max_end_records.saturating_add(1))
54        .collect();
55    let mut examined = signatures.len();
56    if examined > max_end_records {
57        return Err(EndRecordRefusal::TooMany);
58    }
59    let mut first = None;
60    let mut largest_zip64 = 0;
61    for &at in signatures.iter().rev() {
62        let count = end_record_count(bytes, at, &mut examined, max_end_records);
63        if examined > max_end_records {
64            return Err(EndRecordRefusal::TooMany);
65        }
66        let count = match count {
67            Some(EndCount::Zip32(count)) => count,
68            Some(EndCount::Zip64(count)) => {
69                largest_zip64 = largest_zip64.max(count);
70                count
71            }
72            None => continue,
73        };
74        first.get_or_insert(count);
75    }
76    let first = first.ok_or(EndRecordRefusal::Missing)?;
77    Ok(DeclaredEntries {
78        first,
79        largest_zip64,
80    })
81}
82
83fn end_record_count(
84    bytes: &[u8],
85    at: usize,
86    examined: &mut usize,
87    max_end_records: usize,
88) -> Option<EndCount> {
89    let record = bytes.get(at..at.checked_add(22)?)?;
90    let comment = usize::from(u16::from_le_bytes([record[20], record[21]]));
91    if at + 22 + comment > bytes.len() {
92        return None;
93    }
94    let on_disk = le_u16(record, 8);
95    let total = le_u16(record, 10);
96    let directory_offset = le_u32(record, 16);
97    let saturated = total == u64::from(u16::MAX)
98        || le_u32(record, 12) == u64::from(u32::MAX)
99        || directory_offset == u64::from(u32::MAX);
100    let locator = at
101        .checked_sub(20)
102        .filter(|&locator| saturated && bytes[locator..].starts_with(ZIP64_END_LOCATOR));
103    if let Some(locator) = locator {
104        return zip64_entry_count(bytes, locator, examined, max_end_records).map(EndCount::Zip64);
105    }
106    (total == 0 || directory_offset < at as u64).then_some(EndCount::Zip32(on_disk))
107}
108
109/// The largest count among the Zip64 records the reader may accept for the
110/// locator at `locator`, adding to `examined` each record it would read.
111fn zip64_entry_count(
112    bytes: &[u8],
113    locator: usize,
114    examined: &mut usize,
115    max_end_records: usize,
116) -> Option<u64> {
117    let fields = &bytes[locator..locator + 20];
118    let disk_with_directory = le_u32(fields, 4);
119    let declared_at = le_u64(fields, 8);
120    if declared_at >= locator as u64 || le_u32(fields, 16) > 1 {
121        return None;
122    }
123    // Prepended bytes move the record forward, so the reader searches forward
124    // from the declared offset up to the locator and takes the first
125    // consistent record. The largest count is kept here, so that order never
126    // matters.
127    let from = usize::try_from(declared_at).ok()?;
128    let mut largest = None;
129    for found in memmem::find_iter(&bytes[from..locator], ZIP64_END_RECORD) {
130        let at = from + found;
131        let Some(record) = bytes.get(at..at + 56) else {
132            continue;
133        };
134        // The reader reads a record whole, extensible data included, once
135        // its stated size fits before the locator.
136        let record_size = le_u64(record, 4);
137        let room = (locator - at) as u64;
138        if record_size < 40 || record_size.saturating_add(12) > room {
139            continue;
140        }
141        *examined += 1;
142        if *examined > max_end_records {
143            return None;
144        }
145        let total = le_u64(record, 32);
146        if record_size + 12 == room
147            && le_u32(record, 20) == disk_with_directory
148            && total.saturating_mul(46).saturating_add(le_u64(record, 48)) <= at as u64
149            && le_u64(record, 24) <= total
150        {
151            largest = largest.max(Some(total));
152        }
153    }
154    largest
155}
156
157// Record fields widened to the u64 the entry arithmetic uses.
158fn le_u16(bytes: &[u8], at: usize) -> u64 {
159    u64::from(crate::preflight::u16_at(bytes, at))
160}
161
162fn le_u32(bytes: &[u8], at: usize) -> u64 {
163    u64::from(crate::preflight::u32_at(bytes, at))
164}
165
166fn le_u64(bytes: &[u8], at: usize) -> u64 {
167    crate::preflight::u64_at(bytes, at)
168}
169
170#[cfg(test)]
171mod tests {
172    #[test]
173    fn maximum_caller_budget_does_not_overflow() {
174        assert!(super::declared_entries(b"", usize::MAX).is_err());
175    }
176}