Skip to main content

exarch_core/error/
zip_inconsistency.rs

1//! Typed findings for ZIP archives whose structure is read differently by
2//! different ZIP readers.
3
4use crate::closed_enum::closed_enum;
5
6macro_rules! index_newtype {
7    ($(#[$meta:meta])* $name:ident) => {
8        $(#[$meta])*
9        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10        pub struct $name(usize);
11
12        impl $name {
13            /// Wraps a raw index.
14            #[must_use]
15            pub const fn new(index: usize) -> Self {
16                Self(index)
17            }
18
19            /// Returns the raw index.
20            #[must_use]
21            pub const fn get(self) -> usize {
22                self.0
23            }
24        }
25
26        impl ::std::fmt::Display for $name {
27            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
28                ::std::fmt::Display::fmt(&self.0, f)
29            }
30        }
31    };
32}
33
34index_newtype! {
35    /// Index of an entry in the `zip` crate's entry map, which equals its
36    /// position in the manifest listing.
37    ///
38    /// # Examples
39    ///
40    /// ```
41    /// use exarch_core::ZipEntryIndex;
42    ///
43    /// assert_eq!(ZipEntryIndex::new(3).get(), 3);
44    /// ```
45    ZipEntryIndex
46}
47
48index_newtype! {
49    /// Position of a record in the raw central directory, counting records
50    /// that the `zip` crate collapsed because they share a name.
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// use exarch_core::CentralRecordOrdinal;
56    ///
57    /// assert_eq!(CentralRecordOrdinal::new(1).to_string(), "1");
58    /// ```
59    CentralRecordOrdinal
60}
61
62closed_enum! {
63    /// Header field in which a ZIP local header disagrees with its central
64    /// directory record.
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// use exarch_core::ZipHeaderField;
70    ///
71    /// assert_eq!(ZipHeaderField::FileName.to_string(), "file name");
72    /// ```
73    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
74    #[non_exhaustive]
75    pub enum ZipHeaderField {
76        /// File name
77        FileName => "file name",
78
79        /// Unicode Path extra field
80        UnicodePath => "unicode path",
81
82        /// Compression method
83        CompressionMethod => "compression method",
84
85        /// Encryption flag
86        EncryptionFlag => "encryption flag",
87
88        /// Data descriptor flag
89        DataDescriptorFlag => "data descriptor flag",
90
91        /// Modification time
92        ModifiedTime => "modification time",
93
94        /// CRC-32
95        Crc32 => "crc32",
96
97        /// Compressed size
98        CompressedSize => "compressed size",
99
100        /// Uncompressed size
101        UncompressedSize => "uncompressed size",
102    }
103}
104
105closed_enum! {
106    /// Why a ZIP local header could not be compared with its central
107    /// directory record.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// use exarch_core::ZipUncomparable;
113    ///
114    /// assert_eq!(ZipUncomparable::Unparseable.to_string(), "unparseable local header");
115    /// ```
116    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117    #[non_exhaustive]
118    pub enum ZipUncomparable {
119        /// The `zip` crate reported a failed check this version does not know
120        Unrecognized => "unrecognized field",
121
122        /// The local header could not be parsed
123        Unparseable => "unparseable local header",
124    }
125}
126
127closed_enum! {
128    /// Part of a ZIP file in which an unmapped local header was found.
129    ///
130    /// # Examples
131    ///
132    /// ```
133    /// use exarch_core::HiddenRegion;
134    ///
135    /// assert_eq!(HiddenRegion::Prefix.to_string(), "before the archive start");
136    /// ```
137    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
138    #[non_exhaustive]
139    pub enum HiddenRegion {
140        /// Bytes before the archive start, such as a self-extractor stub
141        Prefix => "before the archive start",
142
143        /// Bytes between entries or before the central directory
144        Gap => "between entries",
145
146        /// Bytes behind the end of the compressed stream of a data-descriptor
147        /// entry, inside the range its central directory record declares
148        DescriptorTail => "inside the range of a data-descriptor entry",
149
150        /// Bytes behind the end of the compressed stream of an entry whose
151        /// sizes the local header states, inside the range its central
152        /// directory record declares
153        StreamTail => "behind the compressed stream of an entry",
154    }
155}
156
157closed_enum! {
158    /// Why the end of an entry's compressed stream could not be established.
159    ///
160    /// # Examples
161    ///
162    /// ```
163    /// use exarch_core::ZipStreamUndecided;
164    ///
165    /// assert_eq!(
166    ///     ZipStreamUndecided::Rejected.to_string(),
167    ///     "the decoder does not accept the stream within the declared range"
168    /// );
169    /// ```
170    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
171    #[non_exhaustive]
172    pub enum ZipStreamUndecided {
173        /// The decoder rejects the bytes, or the stream does not end inside
174        /// the declared range
175        Rejected => "the decoder does not accept the stream within the declared range",
176
177        /// Decoding the entry would exceed the budget the check may decode per
178        /// archive, and its bytes hold a record a streaming reader acts on
179        BudgetExhausted => "decoding it exceeds the decode budget and its bytes hold a record",
180    }
181}
182
183closed_enum! {
184    /// Kind of entry that is not a regular file but declares a payload.
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use exarch_core::ZipNonRegularKind;
190    ///
191    /// assert_eq!(ZipNonRegularKind::Directory.to_string(), "directory");
192    /// ```
193    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
194    #[non_exhaustive]
195    pub enum ZipNonRegularKind {
196        /// Directory
197        Directory => "directory",
198
199        /// Device node, socket or other special file
200        Special => "special file",
201    }
202}
203
204closed_enum! {
205    /// Kind of end record found before an entry.
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// use exarch_core::EndRecordKind;
211    ///
212    /// assert_eq!(
213    ///     EndRecordKind::Zip64.to_string(),
214    ///     "ZIP64 end of central directory record"
215    /// );
216    /// ```
217    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
218    #[non_exhaustive]
219    pub enum EndRecordKind {
220        /// End of central directory record
221        Classic => "end of central directory record",
222
223        /// ZIP64 end of central directory record
224        Zip64 => "ZIP64 end of central directory record",
225    }
226}
227
228/// A structural finding that makes a ZIP archive ambiguous between readers.
229///
230/// Names are the raw central directory bytes decoded lossily; the `zip`
231/// crate's own key can differ after Unicode Path substitution.
232///
233/// # Examples
234///
235/// ```
236/// use exarch_core::CentralRecordOrdinal;
237/// use exarch_core::ZipInconsistency;
238///
239/// let finding = ZipInconsistency::DuplicateName {
240///     record: CentralRecordOrdinal::new(1),
241///     name: "a.txt".to_string(),
242/// };
243/// assert_eq!(
244///     finding.to_string(),
245///     "duplicate entry name \"a.txt\" (record 1)"
246/// );
247/// ```
248#[derive(Debug, Clone, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum ZipInconsistency {
251    /// A local header disagrees with its central directory record.
252    HeaderMismatch {
253        /// Entry in the crate's entry map.
254        entry: ZipEntryIndex,
255        /// Field that differs.
256        field: ZipHeaderField,
257        /// Central directory name of the entry.
258        name: String,
259    },
260
261    /// Two or more central directory records share a name.
262    DuplicateName {
263        /// Position in the raw central directory of a record that the `zip`
264        /// crate collapsed into a later record with the same name.
265        record: CentralRecordOrdinal,
266        /// Shared name.
267        name: String,
268    },
269
270    /// Entry data ranges intersect.
271    OverlappingEntries,
272
273    /// A local header exists that no central directory record maps.
274    HiddenLocalHeader {
275        /// Absolute offset of the unmapped header.
276        offset: u64,
277        /// Part of the file the header was found in.
278        region: HiddenRegion,
279    },
280
281    /// An end of central directory record other than the one the reader used
282    /// follows it, so a reader that picks another candidate sees another
283    /// directory.
284    IgnoredEndRecord {
285        /// Absolute offset of the ignored record.
286        offset: u64,
287    },
288
289    /// A central directory record sits outside the central directory, in the
290    /// bytes before the first entry or between entries, so a streaming reader
291    /// that stops listing at the first central record never sees the entries
292    /// after it.
293    StrayCentralRecord {
294        /// Absolute offset of the stray record.
295        offset: u64,
296    },
297
298    /// An end record signature sits in the bytes before the first entry or
299    /// between entries, so a streaming reader that stops listing at it never
300    /// sees the entries after it.
301    StrayEndRecord {
302        /// Absolute offset of the stray record.
303        offset: u64,
304        /// Kind of end record the signature starts.
305        kind: EndRecordKind,
306    },
307
308    /// A data descriptor makes a streaming reader resume past the next entry
309    /// header, so it skips or misreads that entry.
310    DescriptorOverrun {
311        /// Entry whose descriptor is misread.
312        entry: ZipEntryIndex,
313        /// Absolute offset where the entry's data ends and the descriptor
314        /// starts.
315        offset: u64,
316    },
317
318    /// An `xl` extra field, in the local header or the central record, gives
319    /// an entry a file type that differs from the one its central attributes
320    /// give, so a reader that honours the field extracts another kind of entry
321    /// than one that follows the attributes.
322    XlTypeDivergence {
323        /// Entry whose types differ.
324        entry: ZipEntryIndex,
325        /// Absolute offset of the entry's local header.
326        offset: u64,
327    },
328
329    /// A directory or special file entry declares a payload, which readers
330    /// disagree on whether to skip or to read on as further records.
331    NonRegularPayload {
332        /// Entry that declares the payload.
333        entry: ZipEntryIndex,
334        /// What the entry is.
335        kind: ZipNonRegularKind,
336        /// Compressed size the central directory declares.
337        compressed_size: u64,
338    },
339
340    /// The end of an entry's compressed stream cannot be established inside
341    /// its declared range, so a reader that ends the entry where the stream
342    /// ends resumes at an unknown position.
343    StreamEndUnknown {
344        /// Entry whose stream end is unknown.
345        entry: ZipEntryIndex,
346        /// Absolute offset where the entry's declared range ends.
347        offset: u64,
348        /// Why the end could not be established.
349        reason: ZipStreamUndecided,
350    },
351
352    /// The central directory holds more records than its end record counts.
353    UncountedCentralRecords {
354        /// Count claimed by the end of central directory record.
355        counted: usize,
356        /// Records actually present.
357        found: usize,
358    },
359
360    /// A local header could not be compared with its central directory
361    /// record, so a disagreement between them cannot be ruled out.
362    HeaderUncomparable {
363        /// Entry in the crate's entry map.
364        entry: ZipEntryIndex,
365        /// Central directory name of the entry.
366        name: String,
367        /// Why the comparison was not possible.
368        reason: ZipUncomparable,
369    },
370}
371
372impl std::fmt::Display for ZipInconsistency {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        match self {
375            Self::HeaderMismatch { entry, field, name } => write!(
376                f,
377                "local header disagrees with central directory on {field} for entry {entry} \
378                 ({name:?})"
379            ),
380            Self::HeaderUncomparable {
381                entry,
382                name,
383                reason,
384            } => match reason {
385                ZipUncomparable::Unparseable => write!(
386                    f,
387                    "local header of entry {entry} ({name:?}) cannot be parsed, so it cannot be \
388                     compared with the central directory"
389                ),
390                ZipUncomparable::Unrecognized => write!(
391                    f,
392                    "local header of entry {entry} ({name:?}) fails the header consistency check \
393                     in a way this version does not recognize"
394                ),
395            },
396            Self::DuplicateName { record, name } => {
397                write!(f, "duplicate entry name {name:?} (record {record})")
398            }
399            Self::OverlappingEntries => f.write_str("entry data ranges overlap"),
400            Self::HiddenLocalHeader { offset, region } => write!(
401                f,
402                "local header at offset {offset} ({region}) is not in the central directory"
403            ),
404            Self::IgnoredEndRecord { offset } => write!(
405                f,
406                "end of central directory record at offset {offset} is ignored by the reader"
407            ),
408            Self::StrayCentralRecord { offset } => write!(
409                f,
410                "central directory record outside the central directory at offset {offset}"
411            ),
412            Self::StrayEndRecord { offset, kind } => {
413                write!(f, "{kind} before an entry, at offset {offset}")
414            }
415            Self::DescriptorOverrun { entry, offset } => write!(
416                f,
417                "data descriptor of entry {entry} at offset {offset} makes a streaming reader \
418                 resume past the next entry"
419            ),
420            Self::NonRegularPayload {
421                entry,
422                kind,
423                compressed_size,
424            } => write!(
425                f,
426                "{kind} entry {entry} declares a payload of {compressed_size} bytes"
427            ),
428            Self::StreamEndUnknown {
429                entry,
430                offset,
431                reason,
432            } => write!(
433                f,
434                "the end of the compressed stream of entry {entry} cannot be established \
435                 ({reason}) in its declared range ending at offset {offset}, so a streaming \
436                 reader may resume elsewhere"
437            ),
438            Self::XlTypeDivergence { entry, offset } => write!(
439                f,
440                "an xl extra field of entry {entry} (local header at offset {offset}) gives it a \
441                 file type that the central directory attributes do not"
442            ),
443            Self::UncountedCentralRecords { counted, found } => write!(
444                f,
445                "central directory holds {found} records but the end record counts {counted}"
446            ),
447        }
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    fn mismatch(field: ZipHeaderField) -> String {
456        ZipInconsistency::HeaderMismatch {
457            entry: ZipEntryIndex::new(2),
458            field,
459            name: "a.txt".into(),
460        }
461        .to_string()
462    }
463
464    #[test]
465    fn mismatch_message_names_the_field() {
466        assert_eq!(
467            mismatch(ZipHeaderField::Crc32),
468            "local header disagrees with central directory on crc32 for entry 2 (\"a.txt\")"
469        );
470    }
471
472    #[test]
473    fn unparseable_and_unrecognized_get_their_own_wording() {
474        let uncomparable = |reason| {
475            ZipInconsistency::HeaderUncomparable {
476                entry: ZipEntryIndex::new(2),
477                name: "a.txt".into(),
478                reason,
479            }
480            .to_string()
481        };
482        assert_eq!(
483            uncomparable(ZipUncomparable::Unparseable),
484            "local header of entry 2 (\"a.txt\") cannot be parsed, so it cannot be compared \
485             with the central directory"
486        );
487        assert_eq!(
488            uncomparable(ZipUncomparable::Unrecognized),
489            "local header of entry 2 (\"a.txt\") fails the header consistency check in a way \
490             this version does not recognize"
491        );
492    }
493
494    #[test]
495    fn findings_render_their_positions() {
496        assert_eq!(
497            ZipInconsistency::HiddenLocalHeader {
498                offset: 45,
499                region: HiddenRegion::Gap
500            }
501            .to_string(),
502            "local header at offset 45 (between entries) is not in the central directory"
503        );
504        assert_eq!(
505            ZipInconsistency::IgnoredEndRecord { offset: 7 }.to_string(),
506            "end of central directory record at offset 7 is ignored by the reader"
507        );
508        assert_eq!(
509            ZipInconsistency::StrayCentralRecord { offset: 9 }.to_string(),
510            "central directory record outside the central directory at offset 9"
511        );
512        assert_eq!(
513            ZipInconsistency::StrayEndRecord {
514                offset: 11,
515                kind: EndRecordKind::Zip64
516            }
517            .to_string(),
518            "ZIP64 end of central directory record before an entry, at offset 11"
519        );
520        assert_eq!(
521            ZipInconsistency::DescriptorOverrun {
522                entry: ZipEntryIndex::new(2),
523                offset: 70
524            }
525            .to_string(),
526            "data descriptor of entry 2 at offset 70 makes a streaming reader resume past the \
527             next entry"
528        );
529        assert_eq!(
530            ZipInconsistency::NonRegularPayload {
531                entry: ZipEntryIndex::new(2),
532                kind: ZipNonRegularKind::Directory,
533                compressed_size: 9
534            }
535            .to_string(),
536            "directory entry 2 declares a payload of 9 bytes"
537        );
538        assert_eq!(
539            ZipInconsistency::StreamEndUnknown {
540                entry: ZipEntryIndex::new(2),
541                offset: 70,
542                reason: ZipStreamUndecided::BudgetExhausted
543            }
544            .to_string(),
545            "the end of the compressed stream of entry 2 cannot be established (decoding it \
546             exceeds the decode budget and its bytes hold a record) in its declared range \
547             ending at offset 70, so a streaming reader may resume elsewhere"
548        );
549        assert_eq!(
550            ZipInconsistency::XlTypeDivergence {
551                entry: ZipEntryIndex::new(2),
552                offset: 70
553            }
554            .to_string(),
555            "an xl extra field of entry 2 (local header at offset 70) gives it a file type \
556             that the central directory attributes do not"
557        );
558        assert_eq!(
559            ZipInconsistency::UncountedCentralRecords {
560                counted: 1,
561                found: 2
562            }
563            .to_string(),
564            "central directory holds 2 records but the end record counts 1"
565        );
566    }
567}