Skip to main content

zip_framing/index/
entry.rs

1use std::ops::Range;
2
3use tokio::io::{AsyncRead, AsyncSeek};
4
5use crate::{
6    Budget, CompressionMethod, EntryKind, Error, HostSystem, IndexPolicy, IndexPolicyViolation,
7    add,
8    constants::{signature, size},
9    extra::CentralExtras,
10    invalid,
11    kind::{ExternalAttributes, UnixFileType},
12    policy_violation,
13    record::{
14        Common, GeneralPurposeFlags, MemberHeader, MemberPayload, PayloadFields, RecordReader,
15        SizeField, array_at, bytes_at, parse_name,
16    },
17};
18
19/// A member whose local file entry, extras, and optional data descriptor
20/// have been reconciled with the directory and checked for a consistent kind.
21#[derive(Clone, Copy, Debug)]
22pub struct Entry<'a> {
23    /// The indexed member.
24    pub(super) indexed: &'a IndexedEntry,
25    /// The reconciled member state.
26    pub(super) resolved: &'a ResolvedMember,
27}
28
29impl Entry<'_> {
30    /// Returns the member's central directory entry.
31    pub fn directory(&self) -> &CentralDirectoryEntry {
32        &self.indexed.directory
33    }
34
35    /// Returns the member's full byte range, including headers and any descriptor.
36    pub fn record_range(&self) -> Range<u64> {
37        self.indexed.record_range()
38    }
39
40    /// Returns the member's kind, validated during local record resolution.
41    ///
42    /// This does not decode payloads or apply an extraction policy.
43    pub fn kind(&self) -> &EntryKind {
44        &self.resolved.kind
45    }
46
47    /// Returns the UNIX file type and permission bits from external attributes.
48    ///
49    /// This is zero for hosts other than UNIX and Darwin.
50    pub fn unix_mode(&self) -> u16 {
51        self.resolved.unix_mode
52    }
53
54    /// Returns the absolute position of the encoded payload.
55    pub fn data_offset(&self) -> u64 {
56        self.resolved.data_offset
57    }
58
59    /// Returns whether a PKWARE UNIX extra field was present in either header.
60    ///
61    /// A field containing only the timestamp and ownership prefix counts as
62    /// present. Any file-type data is available through [`Self::kind`].
63    pub fn has_unix_extra(&self) -> bool {
64        self.resolved.has_unix_extra
65    }
66}
67
68#[derive(Debug)]
69pub(super) struct ResolvedMember {
70    data_offset: u64,
71    has_unix_extra: bool,
72    kind: EntryKind,
73    unix_mode: u16,
74}
75
76/// Metadata retained from a member's central directory entry.
77#[derive(Debug)]
78pub struct CentralDirectoryEntry {
79    /// The member's path.
80    path: Box<str>,
81    /// The extraction version declared by the central directory entry.
82    version_needed: u16,
83    /// Common (fixed size) metadata in a central directory entry.
84    common: Common,
85    /// The CRC and final sizes after resolving ZIP64 sentinels.
86    payload: MemberPayload,
87    /// An absolute offset to the central directory entry's corresponding
88    /// local file entry.
89    ///
90    /// If the central directory's 32-bit offset is `u32::MAX`, this comes
91    /// from the ZIP64 extra field; otherwise it is that offset widened to `u64`.
92    ///
93    /// Note that our parser is conservative and rejects ZIPs with arbitrary
94    /// prefixed content, so this is always the offset from the start of the
95    /// source.
96    local_offset: u64,
97    /// The "version made by" field in the central directory entry.
98    made_by: u16,
99    /// The central directory entry's raw external file attributes.
100    ///
101    /// The semantics of this field depend on the system identifier
102    /// within [`Self::made_by`].
103    attributes: u32,
104    /// Extra data retained for local/central reconciliation.
105    extra: CentralExtras,
106}
107
108pub(super) enum BufferedEntry {
109    Complete(CentralDirectoryEntry, usize),
110    /// The number of bytes needed from the start of this record.
111    Incomplete(usize),
112}
113
114impl CentralDirectoryEntry {
115    /// Internal file attribute for length-prefixed records (APPNOTE 4.4.14.2).
116    const RECORD_ORIENTED: u16 = 0x0002;
117
118    /// Returns the exact UTF-8 archive path, without filesystem normalization.
119    pub fn path(&self) -> &str {
120        &self.path
121    }
122
123    /// Returns the raw compression method selected by the headers.
124    pub fn method(&self) -> CompressionMethod {
125        self.common.method
126    }
127
128    /// Returns the expected CRC-32 of the decoded payload.
129    pub fn crc32(&self) -> u32 {
130        self.payload.fields().crc
131    }
132
133    /// Returns the decoded payload length.
134    pub fn size(&self) -> u64 {
135        self.payload.fields().uncompressed
136    }
137
138    /// Returns the encoded payload length, excluding headers and descriptors.
139    pub fn compressed_size(&self) -> u64 {
140        self.payload.fields().compressed
141    }
142
143    /// Returns the absolute position of the local header.
144    pub fn position(&self) -> u64 {
145        self.local_offset
146    }
147
148    /// Returns the host-system interpretation of the external attributes.
149    ///
150    /// Unrecognized identifiers are preserved as [`HostSystem::Unknown`].
151    pub fn host_system(&self) -> HostSystem {
152        HostSystem::from((self.made_by >> 8) as u8)
153    }
154
155    /// Returns the raw external file attributes, whose meaning depends on the host.
156    pub fn external_attributes(&self) -> u32 {
157        self.attributes
158    }
159
160    /// Returns the extraction version declared by the central directory entry.
161    pub fn version_needed(&self) -> u16 {
162        self.version_needed
163    }
164
165    /// Parses one complete record in the read-ahead window. If it straddles
166    /// the window, the caller refills it with the requested record length.
167    #[inline]
168    pub(super) fn parse(
169        bytes: &[u8],
170        position: u64,
171        budget: &mut Budget,
172        policy: &IndexPolicy,
173    ) -> Result<BufferedEntry, Error> {
174        let Some((header, rest)) = bytes.split_first_chunk::<{ size::CENTRAL }>() else {
175            return Ok(BufferedEntry::Incomplete(size::CENTRAL));
176        };
177        if u32::from_le_bytes(array_at::<0, 4, _>(header)) != signature::CENTRAL {
178            return Err(invalid(position, "invalid central header signature"));
179        }
180        let name_length = usize::from(u16::from_le_bytes(array_at::<28, 2, _>(header)));
181        if name_length == 0 {
182            return Err(invalid(position, "empty filename"));
183        }
184        let extra_length = usize::from(u16::from_le_bytes(array_at::<30, 2, _>(header)));
185        let comment_length = usize::from(u16::from_le_bytes(array_at::<32, 2, _>(header)));
186        let length = name_length + extra_length + comment_length;
187        let Some(variable) = rest.get(..length) else {
188            return Ok(BufferedEntry::Incomplete(size::CENTRAL + length));
189        };
190
191        let header_fields =
192            MemberHeader::parse(&array_at::<6, { MemberHeader::SIZE }, _>(header), position)?;
193        let common = header_fields.common;
194        let internal_attributes = u16::from_le_bytes(array_at::<36, 2, _>(header));
195        if internal_attributes & Self::RECORD_ORIENTED != 0 {
196            return Err(Error::Unsupported {
197                position,
198                feature: "record-oriented member",
199            });
200        }
201        let offset = u32::from_le_bytes(array_at::<42, 4, _>(header));
202        let disk = u16::from_le_bytes(array_at::<34, 2, _>(header));
203        let (name, rest) = variable.split_at(name_length);
204        let (raw_extra, comment) = rest.split_at(extra_length);
205        let path = parse_name(name, common.flags, position, policy.allow_backslashes)?;
206        let (extra, payload, local_offset) = CentralExtras::parse(
207            raw_extra,
208            header_fields,
209            (offset, disk),
210            path,
211            comment,
212            policy.extra_fields,
213            position,
214        )?;
215        policy.check_version(
216            header_fields.version,
217            header_fields.minimum_version(extra.has_zip64),
218            position,
219        )?;
220        if common.method == CompressionMethod::Stored
221            && common.flags.contains(GeneralPurposeFlags::DATA_DESCRIPTOR)
222            && !policy.allow_stored_data_descriptors
223        {
224            return Err(policy_violation(
225                position,
226                IndexPolicyViolation::StoredDataDescriptor,
227            ));
228        }
229        if !policy.allow_empty_deflate_streams && payload.has_empty_deflate_stream() {
230            return Err(policy_violation(
231                position,
232                IndexPolicyViolation::EmptyDeflateStream,
233            ));
234        }
235        policy
236            .comments
237            .per_member
238            .check(comment, Some(common.flags), position)?;
239        budget.charge_member(payload.fields().uncompressed)?;
240        let entry = Self {
241            path: path.into(),
242            version_needed: header_fields.version,
243            common,
244            payload,
245            local_offset,
246            made_by: u16::from_le_bytes(array_at::<4, 2, _>(header)),
247            attributes: u32::from_le_bytes(array_at::<38, 4, _>(header)),
248            extra,
249        };
250
251        let mode = (entry.attributes >> ExternalAttributes::UNIX_MODE_SHIFT) as u16;
252        if UnixFileType::from_mode(mode) == UnixFileType::SymbolicLink
253            && entry.host_system() != HostSystem::Unix
254            && !policy.allow_ambiguous_symlink_modes
255        {
256            return Err(policy_violation(
257                position,
258                IndexPolicyViolation::AmbiguousSymlinkMode,
259            ));
260        }
261
262        Ok(BufferedEntry::Complete(entry, size::CENTRAL + length))
263    }
264}
265
266/// An indexed ZIP member and its central directory entry.
267///
268/// Its directory metadata is available through [`Self::directory`].
269/// The member's local records are checked on demand by [`super::Index::entry`]
270/// or [`super::Index::validate_all`]. Successful checks are cached by the index
271/// and exposed through [`super::Index::resolved`].
272#[derive(Debug)]
273pub struct IndexedEntry {
274    directory: CentralDirectoryEntry,
275    /// The exclusive end offset of the span assigned to the local header,
276    /// filename, extras, data, and optional data descriptor.
277    boundary: u64,
278}
279
280impl IndexedEntry {
281    /// Returns the member's central directory entry.
282    pub fn directory(&self) -> &CentralDirectoryEntry {
283        &self.directory
284    }
285
286    /// Returns the span assigned to this member by the directory's offsets.
287    ///
288    /// This range can be prefetched before selection. Its local records have
289    /// not necessarily been checked, and it includes headers and any descriptor.
290    pub fn record_range(&self) -> Range<u64> {
291        self.directory.position()..self.boundary
292    }
293
294    #[inline]
295    pub(super) fn new(directory: CentralDirectoryEntry, boundary: u64) -> Result<Self, Error> {
296        let mut entry = Self {
297            directory,
298            boundary,
299        };
300        entry.set_boundary(boundary)?;
301        Ok(entry)
302    }
303
304    #[inline]
305    pub(super) fn set_boundary(&mut self, boundary: u64) -> Result<(), Error> {
306        // Even without a local read, the fixed header, filename and payload
307        // must fit. Exact coverage and descriptor sizes are checked on access.
308        let minimum = add(
309            size::LOCAL as u64 + self.directory.path.len() as u64,
310            self.directory.compressed_size(),
311        )?;
312        let minimum = add(
313            minimum,
314            if self
315                .directory
316                .common
317                .flags
318                .contains(GeneralPurposeFlags::DATA_DESCRIPTOR)
319            {
320                size::DESCRIPTOR as u64
321            } else {
322                0
323            },
324        )?;
325        if add(self.directory.position(), minimum)? > boundary {
326            return Err(invalid(
327                self.directory.position(),
328                "member cannot fit before the next record",
329            ));
330        }
331
332        self.boundary = boundary;
333        Ok(())
334    }
335
336    /// Read and validate an indexed entry's local header, filename, extras, and optional descriptor
337    /// against its corresponding central directory entry.
338    pub(super) async fn read_local<R: AsyncRead + AsyncSeek + Unpin>(
339        &self,
340        reader: &mut RecordReader<'_, R>,
341        budget: &mut Budget,
342        policy: &IndexPolicy,
343    ) -> Result<ResolvedMember, Error> {
344        let directory = &self.directory;
345        let boundary = self.boundary;
346        let position = directory.local_offset;
347        let mut header = [0; size::LOCAL];
348        reader.read_at(position, &mut header, boundary).await?;
349        if u32::from_le_bytes(array_at::<0, 4, _>(&header)) != signature::LOCAL {
350            return Err(invalid(position, "invalid local header signature"));
351        }
352
353        let header_fields =
354            MemberHeader::parse(&array_at::<4, { MemberHeader::SIZE }, _>(&header), position)?;
355        let name_length = usize::from(u16::from_le_bytes(array_at::<26, 2, _>(&header)));
356        let extra_length = usize::from(u16::from_le_bytes(array_at::<28, 2, _>(&header)));
357        budget.charge_metadata((size::LOCAL + name_length + extra_length) as u64)?;
358
359        let variable = reader
360            .read_slice(
361                position + size::LOCAL as u64,
362                name_length + extra_length,
363                boundary,
364            )
365            .await?;
366
367        // Equal bytes inherit the directory's UTF-8 and filename validation.
368        // Header agreement below also requires identical encoding flags.
369        if &variable[..name_length] != directory.path.as_bytes() {
370            return Err(invalid(position, "local and central filenames disagree"));
371        }
372        let (fields, zip64, unix_data) = directory.extra.resolve_local(
373            &variable[name_length..],
374            header_fields,
375            &directory.path,
376            policy.extra_fields,
377            policy.allow_redundant_zip64_sizes,
378            position,
379        )?;
380        if header_fields.common != directory.common {
381            return Err(invalid(position, "local and central headers disagree"));
382        }
383
384        let has_descriptor = directory
385            .common
386            .flags
387            .contains(GeneralPurposeFlags::DATA_DESCRIPTOR);
388        if has_descriptor {
389            if fields != PayloadFields::default() {
390                return Err(invalid(
391                    position,
392                    "descriptor member has nonzero local CRC or sizes",
393                ));
394            }
395        } else if fields != directory.payload.fields() {
396            return Err(invalid(position, "local and central CRC or sizes disagree"));
397        }
398
399        let data_offset = add(position, size::LOCAL as u64 + variable.len() as u64)?;
400        let data_end = add(data_offset, directory.compressed_size())?;
401        if data_end > boundary {
402            return Err(invalid(position, "payload overlaps the next record"));
403        }
404
405        if has_descriptor {
406            self.check_descriptor(reader, data_end, zip64).await?;
407        } else if data_end != boundary {
408            return Err(invalid(data_end, "unaccounted bytes after payload"));
409        }
410
411        let attributes =
412            ExternalAttributes::new(directory.host_system(), directory.external_attributes());
413        let resolved = ResolvedMember {
414            data_offset,
415            has_unix_extra: unix_data.is_some(),
416            kind: EntryKind::resolve(directory, unix_data, &attributes)?,
417            unix_mode: attributes.unix_mode,
418        };
419        let minimum = resolved.kind.minimum_version();
420        policy.check_version(directory.version_needed(), minimum, position)?;
421        // Both local sizes use sentinels or neither does. A redundant pair
422        // or a central-only ZIP64 offset does not raise the local minimum.
423        let local_minimum =
424            header_fields.minimum_version(header_fields.payload.uncompressed == SizeField::Zip64);
425        policy.check_version(header_fields.version, minimum.max(local_minimum), position)?;
426        Ok(resolved)
427    }
428
429    /// Validate a data descriptor after a member's compressed contents.
430    ///
431    /// The data descriptor supplies a local entry's sizes and CRC32 when
432    /// the local header leaves them as placeholders (and the general purpose
433    /// flag indicates that a descriptor follows the contents).
434    async fn check_descriptor<R: AsyncRead + AsyncSeek + Unpin>(
435        &self,
436        reader: &mut RecordReader<'_, R>,
437        position: u64,
438        zip64: bool,
439    ) -> Result<(), Error> {
440        let directory = &self.directory;
441        let unsigned_length = if zip64 {
442            size::ZIP64_DESCRIPTOR as u64
443        } else {
444            size::DESCRIPTOR as u64
445        };
446        let length = self.boundary - position;
447        if length != unsigned_length && length != unsigned_length + size::SIGNATURE as u64 {
448            return Err(invalid(position, "invalid data descriptor length"));
449        }
450
451        let mut bytes = [0; size::SIGNATURE + size::ZIP64_DESCRIPTOR];
452        reader
453            .read_at(position, &mut bytes[..length as usize], self.boundary)
454            .await?;
455
456        // Length disambiguates a signature-less descriptor whose CRC is itself
457        // 0x08074b50. Never search for a descriptor inside compressed data.
458        let offset = if length == unsigned_length + size::SIGNATURE as u64 {
459            if u32::from_le_bytes(array_at::<0, 4, _>(&bytes)) != signature::DESCRIPTOR {
460                return Err(invalid(position, "invalid data descriptor signature"));
461            }
462
463            size::SIGNATURE
464        } else {
465            0
466        };
467
468        let crc = u32::from_le_bytes(bytes_at(&bytes, offset, position)?);
469        let (compressed, uncompressed) = if zip64 {
470            (
471                u64::from_le_bytes(bytes_at(&bytes, offset + 4, position)?),
472                u64::from_le_bytes(bytes_at(&bytes, offset + 12, position)?),
473            )
474        } else {
475            (
476                u64::from(u32::from_le_bytes(bytes_at(&bytes, offset + 4, position)?)),
477                u64::from(u32::from_le_bytes(bytes_at(&bytes, offset + 8, position)?)),
478            )
479        };
480        let fields = PayloadFields {
481            crc,
482            compressed,
483            uncompressed,
484        };
485        if fields != directory.payload.fields() {
486            return Err(invalid(
487                position,
488                "data descriptor disagrees with central header",
489            ));
490        }
491
492        Ok(())
493    }
494}