Skip to main content

zip_codec/
decode.rs

1//! ZIP member projection and seekable archive access.
2
3use std::io::{self, SeekFrom};
4
5use archive_trait::{Archive, Member, MemberMetadata, MemberPayload, SpecialKind};
6use thiserror::Error;
7use tokio::io::{AsyncRead, AsyncSeek, AsyncSeekExt};
8use zip_framing::{Entry, EntryKind, Index, IndexPolicy, IndexedEntry, constants::attributes};
9
10pub use zip_framing::{
11    CommentPolicy, CommentRule, ExtraFieldPolicy, ExtraHeaderId, ExtraHeaderIdSet,
12    IndexPolicyViolation, Limits,
13};
14
15use crate::payload::{CHUNK_SIZE, Payload};
16
17/// An indexed ZIP archive over an immutable, seekable source.
18///
19/// If a decoding operation returns an error or is cancelled while in progress,
20/// subsequent decoding operations return [`DecodeError::Poisoned`]. This applies
21/// to member iteration and selection, payload consumption, metadata validation,
22/// and [`Self::reader_mut`].
23pub struct ZipArchive<R> {
24    state: DecoderState<R>,
25    poisoned: bool,
26}
27
28/// Controls resource limits and which ZIP features [`ZipArchive::open_with_policy`] accepts.
29#[derive(Clone, Copy, Debug, Default)]
30#[must_use]
31pub struct DecodePolicy {
32    framing: IndexPolicy,
33}
34
35struct DecoderState<R> {
36    reader: R,
37    index: Index,
38    next: usize,
39    active: Option<Payload>,
40}
41
42impl DecodePolicy {
43    /// Sets the resource limits for this archive.
44    pub fn limits(mut self, limits: Limits) -> Self {
45        self.framing = self.framing.limits(limits);
46        self
47    }
48
49    /// Sets the extra-field policy for both central and local headers.
50    pub fn extra_field_policy(mut self, policy: ExtraFieldPolicy) -> Self {
51        self.framing = self.framing.extra_field_policy(policy);
52        self
53    }
54
55    /// Sets the [`CommentPolicy`] for member and archive comments.
56    pub fn comment_policy(mut self, policy: CommentPolicy) -> Self {
57        self.framing = self.framing.comment_policy(policy);
58        self
59    }
60
61    /// Allows [redundant local ZIP64 sizes](IndexPolicy::allow_redundant_zip64_sizes).
62    /// Disabled by default.
63    pub fn allow_redundant_zip64_sizes(mut self, allow: bool) -> Self {
64        self.framing = self.framing.allow_redundant_zip64_sizes(allow);
65        self
66    }
67
68    /// Allows [Stored members with data descriptors](IndexPolicy::allow_stored_data_descriptors).
69    pub fn allow_stored_data_descriptors(mut self, allow: bool) -> Self {
70        self.framing = self.framing.allow_stored_data_descriptors(allow);
71        self
72    }
73
74    /// Allows [empty DEFLATE streams](IndexPolicy::allow_empty_deflate_streams).
75    ///
76    /// This is **enabled by default** for compatibility with ZIP emitters that
77    /// write a valid DEFLATE stream for an empty member. Disable it to require
78    /// zero compressed bytes for empty DEFLATE members under [APPNOTE §4.3.8].
79    ///
80    /// [APPNOTE §4.3.8]: https://pkwaredownloads.blob.core.windows.net/pkware-general/Documentation/APPNOTE-6.3.9.TXT
81    pub fn allow_empty_deflate_streams(mut self, allow: bool) -> Self {
82        self.framing = self.framing.allow_empty_deflate_streams(allow);
83        self
84    }
85
86    /// Allows member headers to declare an extraction version below the required
87    /// minimum. Disabled by default. Versions above 4.5 remain unsupported.
88    ///
89    /// See [`IndexPolicy::allow_incompatible_extraction_versions`].
90    pub fn allow_incompatible_extraction_versions(mut self, allow: bool) -> Self {
91        self.framing = self.framing.allow_incompatible_extraction_versions(allow);
92        self
93    }
94
95    /// Allows [Unix symlink modes from non-Unix creators](IndexPolicy::allow_ambiguous_symlink_modes).
96    pub fn allow_ambiguous_symlink_modes(mut self, allow: bool) -> Self {
97        self.framing = self.framing.allow_ambiguous_symlink_modes(allow);
98        self
99    }
100
101    /// Allows [literal backslashes in member names](IndexPolicy::allow_backslashes).
102    ///
103    /// Disabled by default. Member names are returned verbatim. The filesystem
104    /// extractor rejects paths containing backslashes.
105    pub fn allow_backslashes(mut self, allow: bool) -> Self {
106        self.framing = self.framing.allow_backslashes(allow);
107        self
108    }
109}
110
111impl<R: AsyncRead + AsyncSeek + Unpin> ZipArchive<R> {
112    /// Opens the archive with the default [`DecodePolicy`].
113    pub async fn open(reader: R) -> Result<Self, DecodeError> {
114        Self::open_with_policy(reader, DecodePolicy::default()).await
115    }
116
117    /// Opens the archive and validates its central directory under the supplied [`DecodePolicy`].
118    /// Local headers are checked on member access or by [`Self::validate_all`].
119    pub async fn open_with_policy(
120        mut reader: R,
121        policy: DecodePolicy,
122    ) -> Result<Self, DecodeError> {
123        let index = Index::read_with_policy(&mut reader, policy.framing).await?;
124
125        Ok(Self {
126            state: DecoderState {
127                reader,
128                index,
129                next: 0,
130                active: None,
131            },
132            poisoned: false,
133        })
134    }
135
136    /// Returns indexed members without fetching local records or payloads.
137    pub fn entries(&self) -> &[IndexedEntry] {
138        self.state.index.entries()
139    }
140
141    /// Returns a previously checked entry by index, without performing I/O.
142    ///
143    /// Returns [`None`] if the index is out of bounds or the member is unresolved.
144    pub fn resolved(&self, index: usize) -> Option<Entry<'_>> {
145        self.state.index.resolved(index)
146    }
147
148    /// Selects a member by central-directory index.
149    ///
150    /// The local header and data descriptor are checked against the directory
151    /// before a member is returned. Timestamps and Windows NT security descriptors
152    /// are neither compared nor exposed. Successful metadata checks are cached.
153    /// An unfinished prior payload is drained and validated first. The next
154    /// sequential read resumes immediately after the selected entry. Repeated
155    /// explicit selections repeat the associated I/O and decompression work.
156    /// Errors and cancellation poison the archive; subsequent operations fail.
157    pub async fn member(
158        &mut self,
159        index: usize,
160    ) -> Result<Option<Member<ZipMemberPayload<'_, R>>>, DecodeError> {
161        let member = self
162            .run(async |state| state.prepare_member(index).await)
163            .await?;
164        Ok(member.map(|member| member.map_payload(|()| ZipMemberPayload { archive: self })))
165    }
166
167    /// Checks metadata for all members, including those never selected.
168    ///
169    /// An active payload is drained first. Other payloads are not decoded;
170    /// their CRCs and decoded sizes are still checked when they are read.
171    pub async fn validate_all(&mut self) -> Result<(), DecodeError> {
172        self.run(DecoderState::validate_all).await
173    }
174
175    /// Borrows the source for operations such as HTTP range prefetching.
176    ///
177    /// Drains and validates an active payload before lending the reader. The
178    /// caller may change its cursor, but must not replace the source or change
179    /// its contents. Subsequent member selection seeks to the checked offset.
180    pub async fn reader_mut(&mut self) -> Result<&mut R, DecodeError> {
181        self.run(DecoderState::drain).await?;
182        Ok(&mut self.state.reader)
183    }
184
185    /// Returns the source without validating any remaining payloads.
186    pub fn into_inner(self) -> R {
187        self.state.reader
188    }
189
190    async fn run<T>(
191        &mut self,
192        operation: impl AsyncFnOnce(&mut DecoderState<R>) -> Result<T, DecodeError>,
193    ) -> Result<T, DecodeError> {
194        if self.poisoned {
195            return Err(DecodeError::Poisoned);
196        }
197
198        // An error or cancellation leaves the archive poisoned.
199        self.poisoned = true;
200        let value = operation(&mut self.state).await?;
201        self.poisoned = false;
202        Ok(value)
203    }
204}
205
206impl<R: AsyncRead + AsyncSeek + Unpin> DecoderState<R> {
207    // Finish all fallible work before lending the archive to a payload.
208    async fn prepare_member(&mut self, index: usize) -> Result<Option<Member<()>>, DecodeError> {
209        self.drain().await?;
210
211        let Some(entry) = self.index.entry(&mut self.reader, index).await? else {
212            return Ok(None);
213        };
214
215        let kind = Kind::try_from(&entry)?;
216        let directory = entry.directory();
217        let metadata = MemberMetadata {
218            path: directory.path().to_owned(),
219            position: directory.position(),
220        };
221        let size = directory.size();
222
223        let previous = self.active.take();
224        let active = self.active.insert(Payload::new(&entry, previous)?);
225        self.reader
226            .seek(SeekFrom::Start(entry.data_offset()))
227            .await?;
228        self.next = index + 1;
229
230        let member = match kind {
231            Kind::File(executable) => Member::File {
232                metadata,
233                size,
234                executable,
235                payload: (),
236            },
237            Kind::Directory => {
238                self.drain().await?;
239                Member::Directory { metadata }
240            }
241            Kind::SymbolicLink(expected) => {
242                let mut target = Vec::new();
243                active.read_to_end(&mut self.reader, &mut target).await?;
244
245                let mut target = String::from_utf8(target).map_err(|_| DecodeError::Integrity {
246                    position: metadata.position,
247                    reason: "non-UTF-8 symbolic-link target",
248                })?;
249                if target.contains('\0') {
250                    return Err(DecodeError::Integrity {
251                        position: metadata.position,
252                        reason: "NUL in symbolic-link target",
253                    });
254                }
255
256                // APPNOTE 4.5.7 defines a symbolic-link target in the optional PKWARE
257                // UNIX extra field (0x000d). Writers including Info-ZIP, libarchive, and
258                // our encoder store the target in the member payload by convention.
259                // If both contain targets, require an exact match to avoid ambiguity.
260                if let Some(expected) = expected {
261                    if size == 0 {
262                        target = expected.to_owned();
263                    } else if target != expected {
264                        return Err(DecodeError::Integrity {
265                            position: metadata.position,
266                            reason: "symbolic-link payload and UNIX extra field disagree",
267                        });
268                    }
269                }
270
271                Member::SymbolicLink { metadata, target }
272            }
273            Kind::Special(kind) => {
274                self.drain().await?;
275                Member::Special { metadata, kind }
276            }
277        };
278
279        Ok(Some(member))
280    }
281
282    async fn validate_all(&mut self) -> Result<(), DecodeError> {
283        self.drain().await?;
284        self.index.validate_all(&mut self.reader).await?;
285
286        for entry in (0..self.index.entries().len()).filter_map(|index| self.index.resolved(index))
287        {
288            Kind::try_from(&entry)?;
289        }
290
291        Ok(())
292    }
293
294    async fn read_chunk(
295        &mut self,
296        buffer: &mut Vec<u8>,
297        target_len: usize,
298    ) -> Result<bool, DecodeError> {
299        let Some(active) = &mut self.active else {
300            return Ok(false);
301        };
302
303        active
304            .next::<false, _>(&mut self.reader, buffer, target_len)
305            .await
306    }
307
308    async fn drain(&mut self) -> Result<(), DecodeError> {
309        let mut buffer = Vec::new();
310        while self.read_chunk(&mut buffer, CHUNK_SIZE).await? {}
311
312        // Keep the completed decoder and its input allocation for the next member.
313        Ok(())
314    }
315}
316
317impl<R: AsyncRead + AsyncSeek + Unpin> Archive for ZipArchive<R> {
318    type Error = DecodeError;
319    type Payload<'a>
320        = ZipMemberPayload<'a, R>
321    where
322        Self: 'a;
323
324    async fn next_member(&mut self) -> Result<Option<Member<Self::Payload<'_>>>, Self::Error> {
325        self.member(self.state.next).await
326    }
327}
328
329/// A lending cursor over one member's decoded, integrity-checked bytes.
330pub struct ZipMemberPayload<'a, R> {
331    archive: &'a mut ZipArchive<R>,
332}
333
334impl<R: AsyncRead + AsyncSeek + Unpin> ZipMemberPayload<'_, R> {
335    /// Appends the remaining decoded payload to `buffer`, returning the number
336    /// of bytes appended after validating the payload's size and CRC.
337    ///
338    /// Existing bytes in `buffer` are preserved. Reads and decompression still
339    /// proceed in bounded chunks, but the buffer grows to hold the whole payload.
340    /// An error or cancellation poisons the archive and may leave partially
341    /// appended data in `buffer`.
342    pub async fn read_to_end(&mut self, buffer: &mut Vec<u8>) -> Result<usize, DecodeError> {
343        self.archive
344            .run(async |state| match &mut state.active {
345                Some(active) => active.read_to_end(&mut state.reader, buffer).await,
346                None => Ok(0),
347            })
348            .await
349    }
350}
351
352impl<R: AsyncRead + AsyncSeek + Unpin> MemberPayload for ZipMemberPayload<'_, R> {
353    type Error = DecodeError;
354
355    async fn next_chunk(
356        &mut self,
357        buffer: &mut Vec<u8>,
358        target_len: usize,
359    ) -> Result<bool, DecodeError> {
360        self.archive
361            .run(async |state| state.read_chunk(buffer, target_len).await)
362            .await
363    }
364
365    async fn skip(self) -> Result<(), DecodeError> {
366        self.archive.run(DecoderState::drain).await
367    }
368}
369
370enum Kind<'a> {
371    File(bool),
372    Directory,
373    SymbolicLink(Option<&'a str>),
374    Special(SpecialKind),
375}
376
377impl<'a> TryFrom<&'a Entry<'_>> for Kind<'a> {
378    type Error = DecodeError;
379
380    fn try_from(entry: &'a Entry<'_>) -> Result<Self, Self::Error> {
381        let directory = entry.directory();
382        match entry.kind() {
383            EntryKind::File => Ok(Self::File(
384                entry.unix_mode() & attributes::UNIX_EXECUTABLE != 0,
385            )),
386            EntryKind::Directory => Ok(Self::Directory),
387            EntryKind::SymbolicLink { unix_target } => {
388                if directory.size() > u64::from(u16::MAX) {
389                    return Err(DecodeError::Integrity {
390                        position: directory.position(),
391                        reason: "oversized symbolic-link target",
392                    });
393                }
394                Ok(Self::SymbolicLink(unix_target.as_deref()))
395            }
396            EntryKind::CharacterDevice { .. } => Ok(Self::Special(SpecialKind::CharacterDevice)),
397            EntryKind::BlockDevice { .. } => Ok(Self::Special(SpecialKind::BlockDevice)),
398            EntryKind::Fifo => Ok(Self::Special(SpecialKind::Fifo)),
399            EntryKind::VolumeLabel => Err(DecodeError::Unsupported {
400                position: directory.position(),
401                feature: "volume label",
402            }),
403            _ => Err(DecodeError::Unsupported {
404                position: directory.position(),
405                feature: "unsupported file attributes",
406            }),
407        }
408    }
409}
410
411/// A ZIP framing, payload, or member-projection failure.
412#[derive(Debug, Error)]
413pub enum DecodeError {
414    /// ZIP framing failed, including rejections by the selected [`DecodePolicy`].
415    #[error(transparent)]
416    Framing(#[from] zip_framing::Error),
417    /// Payload I/O failed.
418    #[error("ZIP payload I/O failed: {0}")]
419    Io(#[from] io::Error),
420    /// Member data did not agree with its declared metadata.
421    #[error("at byte {position}: invalid ZIP payload: {reason}")]
422    Integrity {
423        /// Local-header offset.
424        position: u64,
425        /// Failed integrity requirement.
426        reason: &'static str,
427    },
428    /// A member cannot be represented by this codec.
429    #[error("at byte {position}: unsupported ZIP {feature}")]
430    Unsupported {
431        /// Local-header offset.
432        position: u64,
433        /// The unsupported member feature.
434        feature: &'static str,
435    },
436    /// A prior error or interrupted operation invalidated the cursor.
437    #[error("ZIP reader is poisoned after an error or cancelled operation")]
438    Poisoned,
439}