1use 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
17pub struct ZipArchive<R> {
24 state: DecoderState<R>,
25 poisoned: bool,
26}
27
28#[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 pub fn limits(mut self, limits: Limits) -> Self {
45 self.framing = self.framing.limits(limits);
46 self
47 }
48
49 pub fn extra_field_policy(mut self, policy: ExtraFieldPolicy) -> Self {
51 self.framing = self.framing.extra_field_policy(policy);
52 self
53 }
54
55 pub fn comment_policy(mut self, policy: CommentPolicy) -> Self {
57 self.framing = self.framing.comment_policy(policy);
58 self
59 }
60
61 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 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 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 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 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 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 pub async fn open(reader: R) -> Result<Self, DecodeError> {
114 Self::open_with_policy(reader, DecodePolicy::default()).await
115 }
116
117 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 pub fn entries(&self) -> &[IndexedEntry] {
138 self.state.index.entries()
139 }
140
141 pub fn resolved(&self, index: usize) -> Option<Entry<'_>> {
145 self.state.index.resolved(index)
146 }
147
148 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 pub async fn validate_all(&mut self) -> Result<(), DecodeError> {
172 self.run(DecoderState::validate_all).await
173 }
174
175 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 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 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 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 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 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
329pub struct ZipMemberPayload<'a, R> {
331 archive: &'a mut ZipArchive<R>,
332}
333
334impl<R: AsyncRead + AsyncSeek + Unpin> ZipMemberPayload<'_, R> {
335 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#[derive(Debug, Error)]
413pub enum DecodeError {
414 #[error(transparent)]
416 Framing(#[from] zip_framing::Error),
417 #[error("ZIP payload I/O failed: {0}")]
419 Io(#[from] io::Error),
420 #[error("at byte {position}: invalid ZIP payload: {reason}")]
422 Integrity {
423 position: u64,
425 reason: &'static str,
427 },
428 #[error("at byte {position}: unsupported ZIP {feature}")]
430 Unsupported {
431 position: u64,
433 feature: &'static str,
435 },
436 #[error("ZIP reader is poisoned after an error or cancelled operation")]
438 Poisoned,
439}