zip_framing/lib.rs
1//! Strict ZIP record framing for asynchronous, seekable inputs.
2//!
3//! The core API in this crate is [`Index`], which can be built from a ZIP's
4//! central directory and used to access individual members (after reconciling
5//! their central and local states).
6//!
7//! Potentially relevant internals:
8//!
9//! - [`CentralDirectoryEntry`], [`IndexedEntry`], and [`Entry`] represent a refinement
10//! type hierarchy, i.e. they go from fewest invariants preserved (just parsing
11//! the central directory entry) to the most invariants preserved (a member whose
12//! central and local records have been checked for consistency).
13//!
14//! - Filenames and UNIX extra-field link targets must be UTF-8.
15//!
16//! - zip-framing does not decode or validate member payloads. It exposes their
17//! offsets and compressed sizes so consumers can read and decode them,
18//! then verify their decoded sizes and CRC32s.
19//!
20//! - zip-framing assumes that the ZIP source does not change.
21//!
22//! ## ZIP compatibility
23//!
24//! - zip-framing rejects empty filenames, including unnamed members from
25//! standard input (APPNOTE 4.4.17.1).
26//!
27//! - Directory member names must end in `/` so readers can identify their type
28//! from the filename alone.
29//!
30//! - APPNOTE 4.4.17.1 requires forward slashes as path separators. By default,
31//! zip-framing rejects backslashes in member names. See
32//! [`IndexPolicy::allow_backslashes`].
33//!
34//! - By default, zip-framing rejects stored members that use a data descriptor,
35//! since other streaming ZIP parsers frequently misinterpret them.
36//! See [`IndexPolicy::allow_stored_data_descriptors`].
37//!
38//! - By default, zip-framing does not honor symlink mode bits unless the host
39//! system indicated by the "version made by" field indicates a UNIX host (3).
40//! See [`IndexPolicy::allow_ambiguous_symlink_modes`].
41//!
42//! - zip-framing rejects members that have the "record-oriented" bit set in their
43//! internal file attributes (APPNOTE 4.4.14.2).
44//!
45//! - By default, zip-framing accepts only required ZIP64 extra fields (`0x0001`).
46//! See [`ExtraFieldPolicy`] for options to accept other fields.
47//! Redundant local ZIP64 sizes require a separate opt-in through
48//! [`IndexPolicy::allow_redundant_zip64_sizes`].
49//!
50//! - By default, each member header must declare at least the extraction
51//! version required by its features. See
52//! [`IndexPolicy::allow_incompatible_extraction_versions`].
53//!
54//! - Timestamps may differ between headers and across formats. zip-framing
55//! accepts any packed DOS date and time and checks the layout of supported
56//! timestamp extras. It does not interpret or expose timestamp values.
57//!
58//! - Windows NT security descriptor extras (`0x4453`) may appear in either
59//! header or both. zip-framing checks each layout independently and ignores
60//! the declared size and descriptor contents.
61
62#![forbid(unsafe_code)]
63
64mod budget;
65pub mod constants;
66mod extra;
67mod host;
68mod index;
69mod kind;
70mod record;
71mod wire;
72pub mod write;
73
74use std::io;
75
76use thiserror::Error;
77
78pub use budget::{Budget, BudgetError, LimitExceeded, Limits};
79pub use extra::{ExtraFieldPolicy, ExtraHeaderId, ExtraHeaderIdSet};
80pub use host::HostSystem;
81pub use index::{
82 CentralDirectoryEntry, CommentPolicy, CommentRule, Entry, Index, IndexPolicy, IndexedEntry,
83};
84pub use kind::{DeviceNumbers, EntryKind};
85
86/// A supported ZIP compression method.
87///
88/// Cast to [`u16`] to obtain the APPNOTE method number.
89/// New methods can be added without changing the record or archive APIs.
90#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
91#[non_exhaustive]
92#[repr(u16)]
93pub enum CompressionMethod {
94 /// Uncompressed bytes (method 0).
95 Stored = 0,
96 /// Raw DEFLATE (method 8, the default).
97 #[default]
98 Deflate = 8,
99}
100
101impl CompressionMethod {
102 pub(crate) fn parse(value: u16, position: u64) -> Result<Self, Error> {
103 match value {
104 value if value == Self::Stored as u16 => Ok(Self::Stored),
105 value if value == Self::Deflate as u16 => Ok(Self::Deflate),
106 _ => Err(Error::Unsupported {
107 position,
108 feature: "compression method",
109 }),
110 }
111 }
112}
113
114/// A supported ZIP feature excluded by the selected [`IndexPolicy`].
115#[derive(Clone, Copy, Debug, Eq, PartialEq, Error)]
116#[non_exhaustive]
117pub enum IndexPolicyViolation {
118 /// A known member extra field was excluded by the extra-field policy.
119 #[error("extra field {:#06x}", u16::from(*identifier))]
120 ExtraField {
121 /// The supported extra-field identifier from the member header.
122 identifier: ExtraHeaderId,
123 },
124 /// The archive comment did not meet the configured comment rule.
125 #[error("archive comment rejected by {rule:?}")]
126 ArchiveComment {
127 /// The rule for the end-record comment.
128 rule: CommentRule,
129 },
130 /// A member comment did not meet the configured comment rule.
131 #[error("member comment rejected by {rule:?}")]
132 MemberComment {
133 /// The rule for central-directory comments.
134 rule: CommentRule,
135 },
136 /// A local ZIP64 extra repeats both 32-bit sizes.
137 #[error("redundant local ZIP64 sizes")]
138 RedundantZip64Sizes,
139 /// A Stored member uses a data descriptor.
140 #[error("data descriptor for Stored member")]
141 StoredDataDescriptor,
142 /// A DEFLATE member with zero uncompressed size declares compressed bytes.
143 #[error("empty DEFLATE stream")]
144 EmptyDeflateStream,
145 /// A member header declares an extraction version below the required minimum.
146 #[error("extraction version {}.{} is below the required {}.{}", declared / 10, declared % 10, minimum / 10, minimum % 10)]
147 IncompatibleExtractionVersion {
148 /// The version declared by the header, in tenths.
149 declared: u16,
150 /// The minimum version required by the member's features, in tenths.
151 minimum: u16,
152 },
153 /// A non-Unix creator supplied Unix symlink mode bits.
154 #[error("symlink mode from a non-Unix creator system")]
155 AmbiguousSymlinkMode,
156 /// A member name contains a literal backslash.
157 #[error("backslash in member name")]
158 BackslashInName,
159}
160
161/// A failure while reading or writing ZIP records.
162#[derive(Debug, Error)]
163pub enum Error {
164 /// An input operation failed.
165 #[error("ZIP I/O failed: {0}")]
166 Io(#[from] io::Error),
167 /// Record structure or redundant information was inconsistent.
168 #[error("at byte {position}: invalid ZIP: {reason}")]
169 Invalid {
170 /// Offset of the relevant record.
171 position: u64,
172 /// The violated format requirement.
173 reason: &'static str,
174 },
175 /// The archive uses an excluded feature.
176 #[error("at byte {position}: unsupported ZIP {feature}")]
177 Unsupported {
178 /// Offset of the relevant record.
179 position: u64,
180 /// The unsupported feature.
181 feature: &'static str,
182 },
183 /// A member header contains an extra field that the reader does not support.
184 #[error("at byte {position}: unsupported ZIP extra field {identifier:#06x}")]
185 UnsupportedExtraField {
186 /// Offset of the member header.
187 position: u64,
188 /// Extra-field identifier from the header.
189 identifier: u16,
190 },
191 /// A supported feature was rejected by the index policy.
192 #[error("at byte {position}: index policy rejected input: {violation}")]
193 PolicyViolation {
194 /// Offset of the relevant record.
195 position: u64,
196 /// The policy rule that rejected the feature.
197 violation: IndexPolicyViolation,
198 },
199 /// A configured resource budget was exceeded.
200 #[error(transparent)]
201 Limit(#[from] LimitExceeded),
202}
203
204impl From<BudgetError> for Error {
205 fn from(error: BudgetError) -> Self {
206 match error {
207 BudgetError::Limit(limit) => Self::Limit(limit),
208 BudgetError::Overflow(usage) => invalid(usage, "offset or size overflow"),
209 }
210 }
211}
212
213pub(crate) fn invalid(position: u64, reason: &'static str) -> Error {
214 Error::Invalid { position, reason }
215}
216
217pub(crate) fn policy_violation(position: u64, violation: IndexPolicyViolation) -> Error {
218 Error::PolicyViolation {
219 position,
220 violation,
221 }
222}
223
224pub(crate) fn add(left: u64, right: u64) -> Result<u64, Error> {
225 left.checked_add(right)
226 .ok_or_else(|| invalid(left, "offset or size overflow"))
227}