Skip to main content

zip_framing/
extra.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    str,
4};
5
6use crc32fast::hash as crc32;
7
8use crate::{
9    Error, IndexPolicyViolation,
10    constants::extra,
11    invalid, policy_violation,
12    record::{
13        GeneralPurposeFlags, MemberHeader, MemberPayload, PayloadFields, SizeField, bytes_at,
14    },
15};
16
17/// Version of the Info-ZIP Unicode path and comment fields.
18const UNICODE_VERSION: u8 = 1;
19
20/// Which extra fields a reader accepts in local and central member headers.
21///
22/// All policies accept required ZIP64 values. Redundant local sizes require
23/// [a separate opt-in](crate::IndexPolicy::allow_redundant_zip64_sizes).
24/// Known fields must pass the same layout and agreement checks under
25/// every policy. Timestamps and Windows NT security descriptor sizes need
26/// not agree between headers.
27#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
28#[non_exhaustive]
29pub enum ExtraFieldPolicy {
30    /// Accept only ZIP64 extra fields.
31    #[default]
32    Zip64Only,
33    /// Accept only the optional fields in the set. An empty set is equivalent
34    /// to [`Self::Zip64Only`].
35    AllowListed(ExtraHeaderIdSet),
36    /// Accept all fields in [`ExtraHeaderId`].
37    AllowKnown,
38    /// Accept known fields and skip unknown fields without interpreting or
39    /// comparing their contents. Truncation and duplicate identifiers are errors.
40    ///
41    /// Other ZIP readers may interpret the skipped fields and report different
42    /// metadata for the same member.
43    Permissive,
44}
45
46/// A supported ZIP member extra-field identifier. The discriminant is the wire value.
47#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
48#[non_exhaustive]
49#[repr(u16)]
50pub enum ExtraHeaderId {
51    /// ZIP64 sizes, local offset, and disk number.
52    Zip64 = 0x0001,
53    /// NTFS timestamps (attribute tag `0x0001` only).
54    Ntfs = 0x000a,
55    /// PKWARE UNIX metadata.
56    Unix = 0x000d,
57    /// Windows NT security descriptor (version 0). The descriptor is ignored.
58    NtfsSecurityDescriptor = 0x4453,
59    /// Info-ZIP extended timestamps.
60    ExtendedTimestamp = 0x5455,
61    /// Original Info-ZIP UNIX timestamps and optional ownership.
62    InfoZipUnix = 0x5855,
63    /// Info-ZIP Unicode comment.
64    UnicodeComment = 0x6375,
65    /// Info-ZIP Unicode path.
66    UnicodePath = 0x7075,
67    /// Info-ZIP 16-bit UID and GID.
68    InfoZipOwnership16 = 0x7855,
69    /// Info-ZIP variable-width UID and GID.
70    InfoZipOwnership = 0x7875,
71    /// Empty marker written by Java's `JarOutputStream`.
72    JarMagic = 0xcafe,
73}
74
75impl TryFrom<u16> for ExtraHeaderId {
76    type Error = u16;
77
78    fn try_from(identifier: u16) -> Result<Self, Self::Error> {
79        [
80            Self::Zip64,
81            Self::Ntfs,
82            Self::Unix,
83            Self::NtfsSecurityDescriptor,
84            Self::ExtendedTimestamp,
85            Self::InfoZipUnix,
86            Self::UnicodeComment,
87            Self::UnicodePath,
88            Self::InfoZipOwnership16,
89            Self::InfoZipOwnership,
90            Self::JarMagic,
91        ]
92        .into_iter()
93        .find(|&field| field as u16 == identifier)
94        .ok_or(identifier)
95    }
96}
97
98impl From<ExtraHeaderId> for u16 {
99    fn from(value: ExtraHeaderId) -> Self {
100        value as Self
101    }
102}
103
104/// A set of known ZIP extra-field identifiers for [`ExtraFieldPolicy::AllowListed`].
105///
106/// ```
107/// use zip_framing::{ExtraFieldPolicy, ExtraHeaderId};
108///
109/// let policy = ExtraFieldPolicy::AllowListed([ExtraHeaderId::ExtendedTimestamp].into());
110/// ```
111#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
112pub struct ExtraHeaderIdSet(u16);
113
114impl ExtraHeaderIdSet {
115    /// Returns whether the set contains the given identifier.
116    pub fn contains(self, identifier: ExtraHeaderId) -> bool {
117        self.0 & identifier.bit() != 0
118    }
119}
120
121impl FromIterator<ExtraHeaderId> for ExtraHeaderIdSet {
122    fn from_iter<T: IntoIterator<Item = ExtraHeaderId>>(iter: T) -> Self {
123        Self(iter.into_iter().fold(0, |bits, id| bits | id.bit()))
124    }
125}
126
127impl<const N: usize> From<[ExtraHeaderId; N]> for ExtraHeaderIdSet {
128    fn from(identifiers: [ExtraHeaderId; N]) -> Self {
129        identifiers.into_iter().collect()
130    }
131}
132
133struct Extras<'a> {
134    // ZIP64 sizes are reconciled separately and need no map allocation.
135    zip64: Option<&'a [u8]>,
136    fields: BTreeMap<ExtraHeaderId, &'a [u8]>,
137    owner: Option<UnixOwner<'a>>,
138}
139
140/// Checked central extra fields retained for reconciliation with the local header.
141#[derive(Debug)]
142pub(crate) struct CentralExtras {
143    /// ZIP64 alone needs no copy once its values have been resolved.
144    bytes: Box<[u8]>,
145    pub(crate) has_zip64: bool,
146}
147
148#[derive(Clone, Copy)]
149enum Header {
150    Local,
151    Central,
152}
153
154impl CentralExtras {
155    pub(crate) fn parse(
156        bytes: &[u8],
157        header: MemberHeader,
158        location: (u32, u16),
159        path: &str,
160        comment: &[u8],
161        policy: ExtraFieldPolicy,
162        position: u64,
163    ) -> Result<(Self, MemberPayload, u64), Error> {
164        let extras = Extras::parse(bytes, Header::Central, policy, position)?;
165        let (offset, disk) = location;
166        let (fields, local_offset) = extras.central_payload(header, offset, disk, position)?;
167        let payload = fields.validate(header.common.method, position)?;
168        extras.validate(path, Some(comment), policy, position)?;
169        let central = Self {
170            bytes: if extras.fields.is_empty() {
171                Box::default()
172            } else {
173                bytes.into()
174            },
175            has_zip64: extras.zip64.is_some(),
176        };
177        Ok((central, payload, local_offset))
178    }
179
180    /// Checks local extras under the same policy and reconciles them with this header.
181    pub(crate) fn resolve_local(
182        &self,
183        bytes: &[u8],
184        header: MemberHeader,
185        path: &str,
186        policy: ExtraFieldPolicy,
187        allow_redundant_zip64_sizes: bool,
188        position: u64,
189    ) -> Result<(PayloadFields, bool, Option<Vec<u8>>), Error> {
190        let extras = Extras::parse(bytes, Header::Local, policy, position)?;
191        let payload = extras.local_payload(header, allow_redundant_zip64_sizes, position)?;
192        extras.validate(path, None, policy, position)?;
193        // A descriptor uses ZIP64 widths if either header has ZIP64 extra values.
194        let zip64 = extras.zip64.is_some() || self.has_zip64;
195        let unix_data = extras.resolve(self, policy, position)?;
196        Ok((payload, zip64, unix_data))
197    }
198}
199
200impl<'a> Extras<'a> {
201    fn validate(
202        &self,
203        path: &str,
204        comment: Option<&[u8]>,
205        policy: ExtraFieldPolicy,
206        position: u64,
207    ) -> Result<(), Error> {
208        if self.fields.is_empty() {
209            return Ok(());
210        }
211        self.check_name(path, position)?;
212        if let Some(comment) = comment {
213            self.check_comment(comment, position)?;
214        }
215        let allowed = match policy {
216            ExtraFieldPolicy::Zip64Only => ExtraHeaderIdSet::default(),
217            ExtraFieldPolicy::AllowListed(allowed) => allowed,
218            ExtraFieldPolicy::AllowKnown | ExtraFieldPolicy::Permissive => return Ok(()),
219        };
220        if let Some(&identifier) = self.fields.keys().find(|&&id| !allowed.contains(id)) {
221            return Err(policy_violation(
222                position,
223                IndexPolicyViolation::ExtraField { identifier },
224            ));
225        }
226        Ok(())
227    }
228
229    fn parse(
230        mut bytes: &'a [u8],
231        header: Header,
232        policy: ExtraFieldPolicy,
233        position: u64,
234    ) -> Result<Self, Error> {
235        let mut extras = Self {
236            zip64: None,
237            fields: BTreeMap::new(),
238            owner: None,
239        };
240
241        let mut unknown = BTreeSet::new();
242        let duplicate = || invalid(position, "duplicate extra-field identifier");
243        while !bytes.is_empty() {
244            let Some((prefix, remaining)) = bytes.split_first_chunk::<{ extra::HEADER_SIZE }>()
245            else {
246                return Err(invalid(position, "truncated extra-field header"));
247            };
248
249            let [identifier_low, identifier_high, length_low, length_high] = *prefix;
250            let length = usize::from(u16::from_le_bytes([length_low, length_high]));
251            let Some((data, remaining)) = remaining.split_at_checked(length) else {
252                return Err(invalid(position, "truncated extra-field data"));
253            };
254
255            let raw_id = u16::from_le_bytes([identifier_low, identifier_high]);
256            match ExtraHeaderId::try_from(raw_id) {
257                Ok(ExtraHeaderId::Zip64) => {
258                    if extras.zip64.replace(data).is_some() {
259                        return Err(duplicate());
260                    }
261                }
262                Ok(identifier) => {
263                    if extras.fields.insert(identifier, data).is_some() {
264                        return Err(duplicate());
265                    }
266                    let owner = identifier.validate_layout(header, data, position)?;
267                    extras.owner = merge_owners(extras.owner, owner, position)?;
268                }
269                Err(identifier) if policy == ExtraFieldPolicy::Permissive => {
270                    if !unknown.insert(identifier) {
271                        return Err(duplicate());
272                    }
273                }
274                Err(identifier) => {
275                    return Err(Error::UnsupportedExtraField {
276                        position,
277                        identifier,
278                    });
279                }
280            }
281            bytes = remaining;
282        }
283
284        Ok(extras)
285    }
286
287    fn local_payload(
288        &self,
289        header: MemberHeader,
290        allow_redundant_zip64_sizes: bool,
291        position: u64,
292    ) -> Result<PayloadFields, Error> {
293        let required = header.payload.uncompressed == SizeField::Zip64;
294        if required != (header.payload.compressed == SizeField::Zip64) {
295            return Err(invalid(position, "local ZIP64 must contain both sizes"));
296        }
297
298        // Older CPython repeated the 32-bit sizes without declaring version 4.5.
299        // Set aside that pair and check it against the resolved sizes below.
300        let mut field = self.zip64;
301        let redundant = field.take_if(|data| {
302            !required
303                && data.len() == extra::ZIP64_LOCAL_SIZE
304                && !header
305                    .common
306                    .flags
307                    .contains(GeneralPurposeFlags::DATA_DESCRIPTOR)
308        });
309        let (payload, _) = Self::resolve_payload(field, header, 0, position)?;
310        if let Some(data) = redundant {
311            if data[..8] != payload.uncompressed.to_le_bytes()
312                || data[8..] != payload.compressed.to_le_bytes()
313            {
314                return Err(invalid(position, "redundant local ZIP64 sizes disagree"));
315            }
316            if !allow_redundant_zip64_sizes {
317                return Err(policy_violation(
318                    position,
319                    IndexPolicyViolation::RedundantZip64Sizes,
320                ));
321            }
322        }
323        Ok(payload)
324    }
325
326    #[inline]
327    fn central_payload(
328        &self,
329        header: MemberHeader,
330        offset: u32,
331        disk: u16,
332        position: u64,
333    ) -> Result<(PayloadFields, u64), Error> {
334        let (payload, bytes) = Self::resolve_payload(
335            self.zip64,
336            header,
337            usize::from(offset == u32::MAX) * 8 + usize::from(disk == u16::MAX) * 4,
338            position,
339        )?;
340        let (offset, bytes) = if offset == u32::MAX {
341            let (offset, bytes) = bytes
342                .split_first_chunk::<8>()
343                .ok_or_else(|| invalid(position, "missing or superfluous ZIP64 values"))?;
344            (u64::from_le_bytes(*offset), bytes)
345        } else {
346            (u64::from(offset), bytes)
347        };
348        let disk = if disk == u16::MAX {
349            u32::from_le_bytes(bytes_at(bytes, 0, position)?)
350        } else {
351            u32::from(disk)
352        };
353        if disk != 0 {
354            return Err(Error::Unsupported {
355                position,
356                feature: "multiple volumes",
357            });
358        }
359
360        Ok((payload, offset))
361    }
362
363    #[inline]
364    fn resolve_payload(
365        field: Option<&[u8]>,
366        header: MemberHeader,
367        location_size: usize,
368        position: u64,
369    ) -> Result<(PayloadFields, &[u8]), Error> {
370        let expected = usize::from(header.payload.uncompressed == SizeField::Zip64) * 8
371            + usize::from(header.payload.compressed == SizeField::Zip64) * 8
372            + location_size;
373        if field.map(<[u8]>::len) != (expected != 0).then_some(expected) {
374            return Err(invalid(position, "missing or superfluous ZIP64 values"));
375        }
376
377        let mut bytes = field.unwrap_or_default();
378        let mut take_size = |size: SizeField| -> Result<u64, Error> {
379            match size {
380                SizeField::Value(size) => Ok(u64::from(size)),
381                SizeField::Zip64 => {
382                    let (value, remaining) = bytes
383                        .split_first_chunk::<8>()
384                        .ok_or_else(|| invalid(position, "missing or superfluous ZIP64 values"))?;
385                    bytes = remaining;
386                    Ok(u64::from_le_bytes(*value))
387                }
388            }
389        };
390
391        let uncompressed = take_size(header.payload.uncompressed)?;
392        let compressed = take_size(header.payload.compressed)?;
393        Ok((
394            PayloadFields {
395                crc: header.payload.crc,
396                uncompressed,
397                compressed,
398            },
399            bytes,
400        ))
401    }
402
403    /// Checks Unicode metadata against an already validated filename.
404    fn check_name(&self, name: &str, position: u64) -> Result<(), Error> {
405        if let Some(field) = self.fields.get(&ExtraHeaderId::UnicodePath) {
406            let unicode = unicode_field(field, name.as_bytes(), position)?;
407            if unicode != name {
408                return Err(invalid(
409                    position,
410                    "Unicode path extra field disagrees with filename",
411                ));
412            }
413        }
414
415        Ok(())
416    }
417
418    fn check_comment(&self, bytes: &[u8], position: u64) -> Result<(), Error> {
419        if let Some(field) = self.fields.get(&ExtraHeaderId::UnicodeComment)
420            && unicode_field(field, bytes, position)?.as_bytes() != bytes
421        {
422            return Err(invalid(
423                position,
424                "Unicode comment disagrees with member comment",
425            ));
426        }
427
428        Ok(())
429    }
430
431    /// Reconciles extra fields and returns the UNIX file-type bytes, if present.
432    fn resolve(
433        self,
434        central: &'a CentralExtras,
435        policy: ExtraFieldPolicy,
436        position: u64,
437    ) -> Result<Option<Vec<u8>>, Error> {
438        if self.fields.is_empty() && central.bytes.is_empty() {
439            return Ok(None);
440        }
441        let central = Self::parse(&central.bytes, Header::Central, policy, position)?;
442        let has = |id| self.fields.contains_key(&id) || central.fields.contains_key(&id);
443        let ownership = has(ExtraHeaderId::InfoZipOwnership);
444        let ownership16 = has(ExtraHeaderId::InfoZipOwnership16);
445        if (has(ExtraHeaderId::InfoZipUnix) && (ownership16 || ownership))
446            || (ownership16 && ownership)
447        {
448            return Err(invalid(
449                position,
450                "mixed old and new Info-ZIP UNIX metadata",
451            ));
452        }
453
454        // The empty central marker refers to ownership stored in the local header.
455        if ownership16 && !self.fields.contains_key(&ExtraHeaderId::InfoZipOwnership16) {
456            return Err(invalid(
457                position,
458                "central Info-ZIP field has no local copy",
459            ));
460        }
461
462        for (identifier, local) in &self.fields {
463            let Some(other) = central.fields.get(identifier) else {
464                // Only the central header has the original member comment.
465                if *identifier == ExtraHeaderId::UnicodeComment {
466                    return Err(invalid(
467                        position,
468                        "local Unicode comment has no central copy",
469                    ));
470                }
471                continue;
472            };
473
474            let equal = match *identifier {
475                // These central forms contain only timestamps, a security
476                // descriptor size, or an empty ownership marker.
477                ExtraHeaderId::Ntfs
478                | ExtraHeaderId::NtfsSecurityDescriptor
479                | ExtraHeaderId::ExtendedTimestamp
480                | ExtraHeaderId::InfoZipUnix
481                | ExtraHeaderId::InfoZipOwnership16 => continue,
482                // Skip atime and mtime, preserving ownership and file-type data.
483                ExtraHeaderId::Unix => local[8..] == other[8..],
484                _ => local == other,
485            };
486            if !equal {
487                return Err(invalid(position, "local and central extra fields disagree"));
488            }
489        }
490
491        merge_owners(self.owner, central.owner, position)?;
492        Ok(self
493            .fields
494            .get(&ExtraHeaderId::Unix)
495            .or_else(|| central.fields.get(&ExtraHeaderId::Unix))
496            .map(|unix| unix[extra::UNIX_PREFIX_SIZE..].to_vec()))
497    }
498}
499
500/// UID and GID, with high zero bytes removed for comparison across formats.
501type UnixOwner<'a> = (&'a [u8], &'a [u8]);
502
503impl ExtraHeaderId {
504    /// A dense bit assignment independent of the ZIP wire values.
505    fn bit(self) -> u16 {
506        match self {
507            Self::Zip64 => 1 << 0,
508            Self::Unix => 1 << 1,
509            Self::ExtendedTimestamp => 1 << 2,
510            Self::InfoZipUnix => 1 << 3,
511            Self::UnicodeComment => 1 << 4,
512            Self::UnicodePath => 1 << 5,
513            Self::InfoZipOwnership16 => 1 << 6,
514            Self::InfoZipOwnership => 1 << 7,
515            Self::JarMagic => 1 << 8,
516            Self::Ntfs => 1 << 9,
517            Self::NtfsSecurityDescriptor => 1 << 10,
518        }
519    }
520
521    /// Checks the field layout and returns any UNIX ownership for reconciliation.
522    fn validate_layout(
523        self,
524        header: Header,
525        data: &[u8],
526        position: u64,
527    ) -> Result<Option<UnixOwner<'_>>, Error> {
528        let invalid_layout = || invalid(position, "invalid Info-ZIP extra field layout");
529        let owner = match (self, header, data.len()) {
530            // Four reserved bytes precede tag 1, size 24, and three FILETIMEs (APPNOTE 4.5.5).
531            (Self::Ntfs, _, 32) if data[4..8] == [1, 0, 24, 0] => None,
532            (Self::Ntfs, _, _) => return Err(invalid(position, "invalid NTFS extra field layout")),
533            // Info-ZIP's SD field stores the uncompressed size in both headers.
534            // Only the local form adds a version, method, CRC32, and descriptor.
535            (Self::NtfsSecurityDescriptor, Header::Central, 4) => None,
536            (Self::NtfsSecurityDescriptor, Header::Local, 11..) if data[4] == 0 => None,
537            (Self::NtfsSecurityDescriptor, _, _) => {
538                return Err(invalid(
539                    position,
540                    "invalid NT security descriptor extra field layout",
541                ));
542            }
543            (Self::Unix, _, 0..extra::UNIX_PREFIX_SIZE) => {
544                return Err(invalid(position, "truncated UNIX extra field"));
545            }
546            (Self::InfoZipUnix, _, 8) => None,
547            (Self::Unix, _, _) | (Self::InfoZipUnix, Header::Local, 12) => {
548                Some(data[8..12].split_at(2))
549            }
550            (Self::ExtendedTimestamp, _, _) => {
551                let Some((&flags, times)) = data.split_first() else {
552                    return Err(invalid(position, "missing Info-ZIP timestamp flags"));
553                };
554                let stored = match header {
555                    Header::Local => flags,
556                    Header::Central => flags & 1,
557                };
558                if flags & !0b111 != 0 || times.len() != 4 * stored.count_ones() as usize {
559                    return Err(invalid_layout());
560                }
561                None
562            }
563            (Self::InfoZipOwnership16, Header::Local, 4) => Some(data.split_at(2)),
564            (Self::InfoZipOwnership16, Header::Central, 0) => None,
565            (Self::InfoZipOwnership, _, _) => Some(ownership_ids(data).ok_or_else(invalid_layout)?),
566            (Self::JarMagic, _, 1..) => return Err(invalid(position, "JAR marker must be empty")),
567            (Self::Zip64 | Self::UnicodePath | Self::UnicodeComment | Self::JarMagic, _, _) => None,
568            (Self::InfoZipUnix | Self::InfoZipOwnership16, _, _) => {
569                return Err(invalid_layout());
570            }
571        };
572        Ok(owner.map(|(uid, gid)| (significant_bytes(uid), significant_bytes(gid))))
573    }
574}
575
576fn merge_owners<'a>(
577    left: Option<UnixOwner<'a>>,
578    right: Option<UnixOwner<'a>>,
579    position: u64,
580) -> Result<Option<UnixOwner<'a>>, Error> {
581    match (left, right) {
582        (Some(left), Some(right)) if left != right => Err(invalid(
583            position,
584            "conflicting UNIX metadata in extra fields",
585        )),
586        (left, right) => Ok(left.or(right)),
587    }
588}
589
590/// Version 1 stores two length-prefixed integers: UID, then GID.
591fn ownership_ids(data: &[u8]) -> Option<(&[u8], &[u8])> {
592    let mut data = data.strip_prefix(&[1])?;
593    let mut next_id = || {
594        let length = usize::from(*data.split_off_first()?);
595        data.split_off(..length).filter(|id| !id.is_empty())
596    };
597    let owner = (next_id()?, next_id()?);
598    data.is_empty().then_some(owner)
599}
600
601/// Ignore high zero bytes when comparing unsigned little-endian IDs of different widths.
602fn significant_bytes(mut bytes: &[u8]) -> &[u8] {
603    while let [rest @ .., 0] = bytes {
604        bytes = rest;
605    }
606    bytes
607}
608
609fn unicode_field<'a>(field: &'a [u8], original: &[u8], position: u64) -> Result<&'a str, Error> {
610    let Some((&UNICODE_VERSION, field)) = field.split_first() else {
611        return Err(invalid(position, "invalid Unicode extra field"));
612    };
613    let Some((expected_crc, value)) = field.split_first_chunk::<4>() else {
614        return Err(invalid(position, "invalid Unicode extra field"));
615    };
616
617    if u32::from_le_bytes(*expected_crc) != crc32(original) {
618        return Err(invalid(position, "Unicode extra field CRC mismatch"));
619    }
620
621    let value =
622        str::from_utf8(value).map_err(|_| invalid(position, "non-UTF-8 Unicode extra field"))?;
623    if value.starts_with('\u{feff}') {
624        return Err(invalid(position, "Unicode extra field contains a BOM"));
625    }
626
627    Ok(value)
628}