zip-framing 0.0.17

Strict, bounded framing for seekable ZIP archives
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
use std::{
    io::{self, SeekFrom},
    str,
};

use memchr::memchr;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt};

use crate::{
    CompressionMethod, Error, IndexPolicyViolation, add, constants::version, invalid,
    policy_violation,
};

/// A bounded read-ahead window that survives absolute seeks within the window.
/// Ordinary buffered readers discard their buffer on those seeks.
pub(crate) struct RecordReader<'a, R> {
    inner: &'a mut R,
    buffer: &'a mut Vec<u8>,
    start: u64,
    capacity: usize,
}

impl<'a, R: AsyncRead + AsyncSeek + Unpin> RecordReader<'a, R> {
    pub(crate) fn new(inner: &'a mut R, capacity: usize, buffer: &'a mut Vec<u8>) -> Self {
        // Reuse allocation, never bytes from a previous reader or operation.
        buffer.clear();
        Self {
            inner,
            buffer,
            start: 0,
            capacity,
        }
    }

    pub(crate) async fn length(&mut self) -> Result<u64, Error> {
        Ok(self.inner.seek(SeekFrom::End(0)).await?)
    }

    /// Returns the buffered bytes starting at `position`, up to `end`.
    pub(crate) fn buffered(&self, position: u64, end: u64) -> &[u8] {
        let window_end = end.min(self.start + self.buffer.len() as u64);
        if position < self.start || position >= window_end {
            return &[];
        }
        &self.buffer[(position - self.start) as usize..(window_end - self.start) as usize]
    }

    /// Borrows a checked span, filling the read-ahead window when necessary.
    pub(crate) async fn read_slice(
        &mut self,
        position: u64,
        length: usize,
        end: u64,
    ) -> Result<&[u8], Error> {
        let requested_end = add(position, length as u64)?;
        if requested_end > end {
            return Err(invalid(position, "record extends beyond its container"));
        }

        if length == 0 {
            return Ok(&[]);
        }

        if position < self.start || requested_end > self.start + self.buffer.len() as u64 {
            self.inner.seek(SeekFrom::Start(position)).await?;
            let read_length = (end - position).min(self.capacity.max(length) as u64) as usize;
            self.fill(read_length).await?;
            self.start = position;
        }

        let offset = (position - self.start) as usize;
        Ok(&self.buffer[offset..offset + length])
    }

    // Every read, including read-ahead, is bounded by its containing record span.
    pub(crate) async fn read_at(
        &mut self,
        position: u64,
        bytes: &mut [u8],
        end: u64,
    ) -> Result<(), Error> {
        let requested_end = add(position, bytes.len() as u64)?;
        if requested_end > end {
            return Err(invalid(position, "record extends beyond its container"));
        }

        if bytes.is_empty() {
            return Ok(());
        }

        if position >= self.start && requested_end <= self.start + self.buffer.len() as u64 {
            let offset = (position - self.start) as usize;
            bytes.copy_from_slice(&self.buffer[offset..offset + bytes.len()]);
            return Ok(());
        }

        self.inner.seek(SeekFrom::Start(position)).await?;
        if bytes.len() >= self.capacity {
            self.inner.read_exact(bytes).await?;
            return Ok(());
        }

        let length = (end - position).min(self.capacity as u64) as usize;
        self.fill(length).await?;
        self.start = position;
        bytes.copy_from_slice(&self.buffer[..bytes.len()]);

        Ok(())
    }

    async fn fill(&mut self, length: usize) -> Result<(), Error> {
        self.buffer.clear();
        self.buffer.reserve(length);
        // Let AsyncRead initialize spare capacity as it fills the window. Take
        // bounds every read even when reused allocation exceeds this span.
        let mut reader = (&mut *self.inner).take(length as u64);
        while reader.limit() != 0 {
            if reader.read_buf(self.buffer).await? == 0 {
                return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
            }
        }
        Ok(())
    }
}

/// Extracts a field from a fixed-size array, checking its bounds at compile time.
pub(crate) fn array_at<const OFFSET: usize, const WIDTH: usize, const LEN: usize>(
    bytes: &[u8; LEN],
) -> [u8; WIDTH] {
    const { assert!(OFFSET <= LEN && WIDTH <= LEN - OFFSET) };
    std::array::from_fn(|index| bytes[OFFSET + index])
}

/// Extracts a fixed-size field after checking its offset and length.
pub(crate) fn bytes_at<const N: usize>(
    bytes: &[u8],
    offset: usize,
    position: u64,
) -> Result<[u8; N], Error> {
    bytes
        .get(offset..)
        .and_then(<[u8]>::first_chunk)
        .copied()
        .ok_or_else(|| invalid(position, "truncated integer field"))
}

#[inline]
pub(crate) fn parse_name(
    bytes: &[u8],
    flags: GeneralPurposeFlags,
    position: u64,
    allow_backslashes: bool,
) -> Result<&str, Error> {
    let name = str::from_utf8(bytes).map_err(|_| invalid(position, "non-UTF-8 filename"))?;
    if !flags.contains(GeneralPurposeFlags::UTF8) && !name.is_ascii() {
        return Err(invalid(position, "non-ASCII filename without UTF-8 flag"));
    }

    validate_name(name, position)?;
    if !allow_backslashes && memchr(b'\\', bytes).is_some() {
        return Err(policy_violation(
            position,
            IndexPolicyViolation::BackslashInName,
        ));
    }
    Ok(name)
}

#[inline]
pub(crate) fn validate_name(name: &str, position: u64) -> Result<(), Error> {
    let bytes = name.as_bytes();
    if name.starts_with('\u{feff}')
        || memchr(0, bytes).is_some()
        || name.starts_with('/')
        || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
    {
        return Err(invalid(position, "invalid ZIP filename"));
    }

    Ok(())
}

/// General-purpose header flags (APPNOTE 4.4.4).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct GeneralPurposeFlags(u16);

impl GeneralPurposeFlags {
    /// Member encryption (bit 0).
    const ENCRYPTED: Self = Self(0x0001);
    /// DEFLATE compression-level bits (1 and 2). Info-ZIP 3.0 can leave these
    /// set on Stored members. Both headers must still agree on their values.
    const DEFLATE_OPTIONS: Self = Self(0x0006);
    /// A descriptor follows the payload; local CRC and sizes are placeholders (bit 3).
    pub(crate) const DATA_DESCRIPTOR: Self = Self(0x0008);
    /// Compressed patched data (bit 5).
    const PATCHED_DATA: Self = Self(0x0020);
    /// Strong encryption (bit 6).
    const STRONG_ENCRYPTION: Self = Self(0x0040);
    /// Names and comments are UTF-8 encoded (bit 11).
    pub(crate) const UTF8: Self = Self(0x0800);
    /// Local header values are masked for central directory encryption (bit 13).
    const MASKED_HEADER: Self = Self(0x2000);

    /// Validates the flags for a Stored or DEFLATE member.
    pub(crate) fn parse(bits: u16, position: u64) -> Result<Self, Error> {
        let flags = Self(bits);
        if flags.contains(Self::ENCRYPTED)
            || flags.contains(Self::STRONG_ENCRYPTION)
            || flags.contains(Self::MASKED_HEADER)
        {
            return Err(Error::Unsupported {
                position,
                feature: "encryption",
            });
        }

        if flags.contains(Self::PATCHED_DATA) {
            return Err(Error::Unsupported {
                position,
                feature: "patched data",
            });
        }

        let allowed = Self::UTF8.0 | Self::DATA_DESCRIPTOR.0 | Self::DEFLATE_OPTIONS.0;
        if bits & !allowed != 0 {
            return Err(invalid(
                position,
                "reserved or inapplicable general-purpose flags",
            ));
        }

        Ok(flags)
    }

    fn bits(self) -> u16 {
        self.0
    }

    pub(crate) fn contains(self, flags: Self) -> bool {
        self.0 & flags.0 == flags.0
    }
}

/// A 32-bit payload-size field (APPNOTE 4.4.8, 4.4.9, and 4.5.3).
///
/// With a data descriptor, zero sizes in a local header or its ZIP64 extra
/// field are placeholders. That interpretation belongs to local resolution.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SizeField {
    /// A value smaller than `u32::MAX` stored directly in the header.
    Value(u32),
    /// The `0xFFFFFFFF` sentinel referring to the ZIP64 extra field.
    Zip64,
}

impl From<u32> for SizeField {
    fn from(value: u32) -> Self {
        match value {
            u32::MAX => Self::Zip64,
            _ => Self::Value(value),
        }
    }
}

impl From<SizeField> for u32 {
    fn from(value: SizeField) -> Self {
        match value {
            SizeField::Value(value) => value,
            SizeField::Zip64 => u32::MAX,
        }
    }
}

/// Fields that must agree verbatim between local and central headers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Common {
    /// The member's general-purpose bit flags.
    pub(crate) flags: GeneralPurposeFlags,
    /// The member's compression method.
    pub(crate) method: CompressionMethod,
}

/// The payload CRC and sizes. Header sizes use [`SizeField`], and resolved sizes use [`u64`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct PayloadFields<S = u64> {
    /// CRC-32 of the uncompressed data, or zero in a local descriptor placeholder.
    pub(crate) crc: u32,
    pub(crate) compressed: S,
    pub(crate) uncompressed: S,
}

/// Payload declarations checked against the compression method and empty-member CRC.
#[derive(Clone, Copy, Debug)]
pub(crate) struct MemberPayload(PayloadFields);

impl PayloadFields {
    pub(crate) fn validate(
        self,
        method: CompressionMethod,
        position: u64,
    ) -> Result<MemberPayload, Error> {
        match method {
            CompressionMethod::Stored if self.compressed != self.uncompressed => {
                return Err(invalid(position, "stored member sizes differ"));
            }
            CompressionMethod::Deflate if self.compressed == 0 && self.uncompressed != 0 => {
                return Err(invalid(
                    position,
                    "nonempty DEFLATE member has zero compressed size",
                ));
            }
            CompressionMethod::Stored | CompressionMethod::Deflate => {}
        }
        if self.uncompressed == 0 && self.crc != 0 {
            return Err(invalid(position, "empty member has nonzero CRC"));
        }
        Ok(MemberPayload(self))
    }
}

impl MemberPayload {
    pub(crate) fn has_empty_deflate_stream(self) -> bool {
        self.0.uncompressed == 0 && self.0.compressed != 0
    }

    pub(crate) fn fields(self) -> PayloadFields {
        self.0
    }
}

/// The fixed fields shared by local and central headers, before resolving ZIP64 sizes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MemberHeader {
    /// The extraction version declared by this header. For example, only the
    /// central header needs version 4.5 for a ZIP64 local-header offset.
    pub(crate) version: u16,
    pub(crate) common: Common,
    /// Packed MS-DOS modification time and date, which may differ between headers.
    pub(crate) time: u16,
    pub(crate) date: u16,
    pub(crate) payload: PayloadFields<SizeField>,
}

impl MemberHeader {
    /// Size of the serialized common fields in bytes.
    pub(crate) const SIZE: usize = 22;

    /// Parse the shared portion of a local or central header.
    #[inline]
    pub(crate) fn parse(bytes: &[u8; Self::SIZE], position: u64) -> Result<Self, Error> {
        let method =
            CompressionMethod::parse(u16::from_le_bytes(array_at::<4, 2, _>(bytes)), position)?;
        let flags =
            GeneralPurposeFlags::parse(u16::from_le_bytes(array_at::<2, 2, _>(bytes)), position)?;

        // p7zip 16.02 on Unix wrote the host system ID into the high byte.
        let version = u16::from(bytes[0]);
        if version > version::ZIP64 {
            return Err(Error::Unsupported {
                position,
                feature: "extraction version",
            });
        }

        Ok(Self {
            version,
            common: Common { flags, method },
            time: u16::from_le_bytes(array_at::<6, 2, _>(bytes)),
            date: u16::from_le_bytes(array_at::<8, 2, _>(bytes)),
            payload: PayloadFields {
                crc: u32::from_le_bytes(array_at::<10, 4, _>(bytes)),
                compressed: SizeField::from(u32::from_le_bytes(array_at::<14, 4, _>(bytes))),
                uncompressed: SizeField::from(u32::from_le_bytes(array_at::<18, 4, _>(bytes))),
            },
        })
    }

    /// Serializes the common header fields in little-endian order.
    pub(crate) fn to_bytes(self) -> [u8; Self::SIZE] {
        let mut bytes = [0; Self::SIZE];
        bytes[0..2].copy_from_slice(&self.version.to_le_bytes());
        bytes[2..4].copy_from_slice(&self.common.flags.bits().to_le_bytes());
        bytes[4..6].copy_from_slice(&(self.common.method as u16).to_le_bytes());
        bytes[6..8].copy_from_slice(&self.time.to_le_bytes());
        bytes[8..10].copy_from_slice(&self.date.to_le_bytes());
        bytes[10..14].copy_from_slice(&self.payload.crc.to_le_bytes());
        bytes[14..18].copy_from_slice(&u32::from(self.payload.compressed).to_le_bytes());
        bytes[18..22].copy_from_slice(&u32::from(self.payload.uncompressed).to_le_bytes());
        bytes
    }

    /// Minimum extraction version for the features used in this header.
    pub(crate) fn minimum_version(self, requires_zip64: bool) -> u16 {
        if requires_zip64 {
            return version::ZIP64;
        }
        match self.common.method {
            CompressionMethod::Stored => version::BASE,
            CompressionMethod::Deflate => version::V2_0,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::{
        Common, GeneralPurposeFlags, MemberHeader, PayloadFields, RecordReader, SizeField,
        array_at, bytes_at,
    };
    use crate::{CompressionMethod, Error};

    #[tokio::test]
    async fn bounds_reads_before_allocation() -> Result<(), Error> {
        let mut source = Cursor::new([1, 2, 3, 4]);
        let mut buffer = Vec::with_capacity(64);
        let mut reader = RecordReader::new(&mut source, 4, &mut buffer);

        // An allocation of this size would fail before any I/O could occur.
        assert!(matches!(
            reader.read_slice(0, usize::MAX, 4).await,
            Err(Error::Invalid {
                position: 0,
                reason: "record extends beyond its container",
            })
        ));
        assert_eq!(reader.read_slice(1, 2, 4).await?, [2, 3]);

        // Spare capacity from a larger window must not cause read-ahead beyond
        // the current container, even though the source has more bytes.
        assert_eq!(reader.read_slice(0, 2, 2).await?, [1, 2]);
        assert_eq!(reader.inner.position(), 2);

        Ok(())
    }

    #[test]
    fn parses_and_serializes_common_header_fields() -> Result<(), Error> {
        let bytes = [
            20, 0, 0x0a, 0x08, 8, 0, 0x34, 0x12, 0x78, 0x56, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
            0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
        ];
        let header = MemberHeader {
            version: 20,
            common: Common {
                flags: GeneralPurposeFlags::parse(0x080a, 42)?,
                method: CompressionMethod::Deflate,
            },
            time: 0x1234,
            date: 0x5678,
            payload: PayloadFields {
                crc: 0x4433_2211,
                compressed: SizeField::Value(0x8877_6655),
                uncompressed: SizeField::Value(0xccbb_aa99),
            },
        };
        assert_eq!(MemberHeader::parse(&bytes, 42)?, header);
        assert_eq!(header.to_bytes(), bytes);

        Ok(())
    }

    #[test]
    fn extracts_fields_from_fixed_arrays() {
        let bytes = [1, 2, 3, 4, 5, 6, 7, 8];

        assert_eq!(array_at::<0, 8, _>(&bytes), bytes);
        assert_eq!(array_at::<1, 2, _>(&bytes), [2, 3]);
        assert_eq!(array_at::<4, 4, _>(&bytes), [5, 6, 7, 8]);
        assert_eq!(array_at::<8, 0, _>(&bytes), []);
    }

    #[test]
    fn reads_fixed_width_fields_and_rejects_out_of_bounds_offsets() -> Result<(), Error> {
        let bytes = [1, 2, 3, 4, 5, 6, 7, 8];

        assert_eq!(u16::from_le_bytes(bytes_at(&bytes, 1, 42)?), 0x0302);
        assert_eq!(u32::from_le_bytes(bytes_at(&bytes, 2, 42)?), 0x0605_0403);
        assert_eq!(
            u64::from_le_bytes(bytes_at(&bytes, 0, 42)?),
            0x0807_0605_0403_0201
        );

        for offset in [7, 8, usize::MAX] {
            assert!(matches!(
                bytes_at::<2>(&bytes, offset, 42),
                Err(Error::Invalid {
                    position: 42,
                    reason: "truncated integer field"
                })
            ));
        }
        assert!(bytes_at::<8>(&bytes, 1, 42).is_err());

        Ok(())
    }
}