1use std::{borrow::Cow, cell::RefCell, collections::HashMap, mem};
2
3use memchr::memmem;
4use tokio::io::{AsyncRead, AsyncSeek};
5
6use crate::{
7 Budget, Error, ExtraFieldPolicy, IndexPolicyViolation, Limits, add,
8 constants::{extra, signature, size, version},
9 invalid, policy_violation,
10 record::{GeneralPurposeFlags, RecordReader, array_at},
11};
12
13mod entry;
14
15use entry::{BufferedEntry, ResolvedMember};
16pub use entry::{CentralDirectoryEntry, Entry, IndexedEntry};
17
18thread_local! {
19 static DIRECTORY_WINDOW: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
20}
21
22struct DirectoryWindow(Vec<u8>);
24
25impl DirectoryWindow {
26 fn take() -> Self {
27 Self(
28 DIRECTORY_WINDOW
29 .try_with(|window| {
30 window
31 .try_borrow_mut()
32 .map(|mut window| mem::take(&mut *window))
33 .unwrap_or_default()
34 })
35 .unwrap_or_default(),
36 )
37 }
38}
39
40impl Drop for DirectoryWindow {
41 fn drop(&mut self) {
42 if self.0.capacity() <= size::END + usize::from(u16::MAX) {
45 self.0.clear();
46 let _ = DIRECTORY_WINDOW.try_with(|window| {
47 if let Ok(mut window) = window.try_borrow_mut()
48 && window.capacity() < self.0.capacity()
49 {
50 *window = mem::take(&mut self.0);
51 }
52 });
53 }
54 }
55}
56
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59#[non_exhaustive]
60pub enum CommentRule {
61 Reject,
63 AllowAscii,
65 AllowUtf8,
67 AllowAll,
69}
70
71impl CommentRule {
72 fn check(
73 self,
74 bytes: &[u8],
75 member_flags: Option<GeneralPurposeFlags>,
76 position: u64,
77 ) -> Result<(), Error> {
78 if bytes.is_empty() {
79 return Ok(());
80 }
81 let utf8 = member_flags.map(|flags| flags.contains(GeneralPurposeFlags::UTF8));
82 if utf8 == Some(true) && str::from_utf8(bytes).is_err() {
83 return Err(invalid(position, "non-UTF-8 comment"));
84 }
85
86 let accepted = match (self, utf8) {
87 (Self::Reject, _) => false,
88 (Self::AllowAscii, _) | (Self::AllowUtf8, Some(false)) => bytes.is_ascii(),
89 (Self::AllowUtf8, None) => str::from_utf8(bytes).is_ok(),
90 (Self::AllowUtf8, Some(true)) | (Self::AllowAll, _) => true,
91 };
92 if accepted {
93 return Ok(());
94 }
95
96 let violation = if member_flags.is_some() {
97 IndexPolicyViolation::MemberComment { rule: self }
98 } else {
99 IndexPolicyViolation::ArchiveComment { rule: self }
100 };
101 Err(policy_violation(position, violation))
102 }
103}
104
105#[derive(Clone, Copy, Debug, Eq, PartialEq)]
107pub struct CommentPolicy {
108 pub per_member: CommentRule,
110 pub archive: CommentRule,
112}
113
114impl Default for CommentPolicy {
115 fn default() -> Self {
116 Self {
117 per_member: CommentRule::Reject,
118 archive: CommentRule::AllowAscii,
119 }
120 }
121}
122
123#[derive(Clone, Copy, Debug)]
125#[must_use]
126pub struct IndexPolicy {
127 limits: Limits,
128 extra_fields: ExtraFieldPolicy,
129 comments: CommentPolicy,
130 allow_redundant_zip64_sizes: bool,
131 allow_stored_data_descriptors: bool,
132 allow_empty_deflate_streams: bool,
133 allow_incompatible_extraction_versions: bool,
134 allow_ambiguous_symlink_modes: bool,
135 allow_backslashes: bool,
136}
137
138impl Default for IndexPolicy {
139 fn default() -> Self {
140 Self {
141 limits: Limits::default(),
142 extra_fields: ExtraFieldPolicy::default(),
143 comments: CommentPolicy::default(),
144 allow_redundant_zip64_sizes: false,
145 allow_stored_data_descriptors: false,
146 allow_empty_deflate_streams: true,
147 allow_incompatible_extraction_versions: false,
148 allow_ambiguous_symlink_modes: false,
149 allow_backslashes: false,
150 }
151 }
152}
153
154impl IndexPolicy {
155 pub fn limits(mut self, limits: Limits) -> Self {
157 self.limits = limits;
158 self
159 }
160
161 pub fn extra_field_policy(mut self, policy: ExtraFieldPolicy) -> Self {
163 self.extra_fields = policy;
164 self
165 }
166
167 pub fn comment_policy(mut self, policy: CommentPolicy) -> Self {
169 self.comments = policy;
170 self
171 }
172
173 pub fn allow_redundant_zip64_sizes(mut self, allow: bool) -> Self {
182 self.allow_redundant_zip64_sizes = allow;
183 self
184 }
185
186 pub fn allow_stored_data_descriptors(mut self, allow: bool) -> Self {
188 self.allow_stored_data_descriptors = allow;
189 self
190 }
191
192 pub fn allow_empty_deflate_streams(mut self, allow: bool) -> Self {
199 self.allow_empty_deflate_streams = allow;
200 self
201 }
202
203 pub fn allow_incompatible_extraction_versions(mut self, allow: bool) -> Self {
212 self.allow_incompatible_extraction_versions = allow;
213 self
214 }
215
216 pub fn allow_ambiguous_symlink_modes(mut self, allow: bool) -> Self {
219 self.allow_ambiguous_symlink_modes = allow;
220 self
221 }
222
223 pub fn allow_backslashes(mut self, allow: bool) -> Self {
227 self.allow_backslashes = allow;
228 self
229 }
230
231 fn check_version(&self, declared: u16, minimum: u16, position: u64) -> Result<(), Error> {
232 if declared < minimum && !self.allow_incompatible_extraction_versions {
233 return Err(policy_violation(
234 position,
235 IndexPolicyViolation::IncompatibleExtractionVersion { declared, minimum },
236 ));
237 }
238 Ok(())
239 }
240}
241
242#[derive(Debug)]
248pub struct Index {
249 entries: Vec<IndexedEntry>,
251 resolved: Vec<Option<ResolvedMember>>,
253 policy: IndexPolicy,
255 budget: Budget,
258 buffer: Vec<u8>,
260}
261
262impl Index {
263 pub fn entries(&self) -> &[IndexedEntry] {
265 &self.entries
266 }
267
268 pub fn resolved(&self, index: usize) -> Option<Entry<'_>> {
272 Some(Entry {
273 indexed: self.entries.get(index)?,
274 resolved: self.resolved.get(index)?.as_ref()?,
275 })
276 }
277
278 pub async fn read<R: AsyncRead + AsyncSeek + Unpin>(reader: &mut R) -> Result<Self, Error> {
285 Self::read_with_policy(reader, IndexPolicy::default()).await
286 }
287
288 pub async fn read_with_policy<R: AsyncRead + AsyncSeek + Unpin>(
293 reader: &mut R,
294 policy: IndexPolicy,
295 ) -> Result<Self, Error> {
296 let mut budget = Budget::new(policy.limits);
299 let mut buffer = DirectoryWindow::take();
300 let mut buffered = RecordReader::new(reader, 64 * 1024, &mut buffer.0);
301 let end =
302 CentralDirectory::read(&mut buffered, &mut budget, policy.comments.archive).await?;
303 let mut entries = end
304 .read_entries(&mut buffered, &mut budget, &policy)
305 .await?;
306
307 if entries.is_sorted_by_key(|entry| entry.directory().position()) {
308 if entries
309 .first()
310 .map_or(end.offset, |entry| entry.directory().position())
311 != 0
312 {
313 return Err(invalid(0, "unaccounted bytes before the first member"));
314 }
315
316 let mut directory = entries.iter_mut().peekable();
319 while let Some(entry) = directory.next() {
320 entry.set_boundary(
321 directory
322 .peek()
323 .map_or(end.offset, |next| next.directory().position()),
324 )?;
325 }
326 } else {
327 let mut order: Vec<_> = (0..entries.len()).collect();
331 order.sort_unstable_by_key(|&index| entries[index].directory().position());
332 if order
333 .first()
334 .map_or(end.offset, |&index| entries[index].directory().position())
335 != 0
336 {
337 return Err(invalid(0, "unaccounted bytes before the first member"));
338 }
339
340 let mut first_error = None;
344 for (&index, &next) in order.iter().zip(order.iter().skip(1)) {
345 let boundary = entries[next].directory().position();
346 if let Err(error) = entries[index].set_boundary(boundary)
347 && first_error.as_ref().is_none_or(|(first, _)| index < *first)
348 {
349 first_error = Some((index, error));
350 }
351 }
352 if let Some((_, error)) = first_error {
353 return Err(error);
354 }
355
356 check_destination_order(&entries).await?;
357 }
358
359 Ok(Self {
360 resolved: Vec::new(),
361 policy,
362 entries,
363 budget,
364 buffer: Vec::new(),
365 })
366 }
367
368 pub async fn entry<R: AsyncRead + AsyncSeek + Unpin>(
373 &mut self,
374 reader: &mut R,
375 index: usize,
376 ) -> Result<Option<Entry<'_>>, Error> {
377 let Some(indexed) = self.entries.get(index) else {
378 return Ok(None);
379 };
380
381 if self.resolved.is_empty() {
382 self.resolved.resize_with(self.entries.len(), || None);
383 }
384
385 let resolved = match &mut self.resolved[index] {
386 Some(resolved) => resolved,
387 slot => {
388 let capacity = (size::LOCAL
391 + indexed.directory().path().len()
392 + extra::HEADER_SIZE
393 + extra::ZIP64_LOCAL_SIZE)
394 .min(4096);
395 let mut buffered = RecordReader::new(reader, capacity, &mut self.buffer);
396 let mut pending_budget = self.budget;
399 let resolved = indexed
400 .read_local(&mut buffered, &mut pending_budget, &self.policy)
401 .await?;
402 self.budget = pending_budget;
403 slot.insert(resolved)
404 }
405 };
406
407 Ok(Some(Entry { indexed, resolved }))
408 }
409
410 pub async fn validate_all<R: AsyncRead + AsyncSeek + Unpin>(
418 &mut self,
419 reader: &mut R,
420 ) -> Result<(), Error> {
421 for index in 0..self.entries.len() {
422 self.entry(reader, index).await?;
423 tokio::task::consume_budget().await;
424 }
425
426 Ok(())
427 }
428}
429
430struct CentralDirectory {
432 offset: u64,
435 size: u64,
440 count: u64,
442}
443
444impl CentralDirectory {
445 async fn read<R: AsyncRead + AsyncSeek + Unpin>(
450 reader: &mut RecordReader<'_, R>,
451 budget: &mut Budget,
452 archive_comment: CommentRule,
453 ) -> Result<Self, Error> {
454 let length = reader.length().await?;
455 budget.check_archive_size(length)?;
456 if length < size::END as u64 {
457 return Err(invalid(0, "missing end of central directory"));
458 }
459
460 let tail_size = length.min(size::END as u64 + u64::from(u16::MAX)) as usize;
462 let tail_start = length - tail_size as u64;
463 let tail = reader.read_slice(tail_start, tail_size, length).await?;
464
465 let (offset, end) = find_end(tail, tail_start)?;
466 let position = tail_start + offset as u64;
467 let comment = &tail[offset + size::END..];
468 if !comment.is_empty()
471 && let Some(shadow) = memmem::find(
472 &tail[offset + size::SIGNATURE..],
473 &signature::END.to_le_bytes(),
474 )
475 {
476 return Err(invalid(
477 position + (size::SIGNATURE + shadow) as u64,
478 "ambiguous end records",
479 ));
480 }
481 archive_comment.check(comment, None, position)?;
482
483 let disk = u16::from_le_bytes(array_at::<4, 2, _>(&end));
484 let directory_disk = u16::from_le_bytes(array_at::<6, 2, _>(&end));
485 let disk_count = u16::from_le_bytes(array_at::<8, 2, _>(&end));
486 let count = u16::from_le_bytes(array_at::<10, 2, _>(&end));
487 let size = u32::from_le_bytes(array_at::<12, 4, _>(&end));
488 let offset = u32::from_le_bytes(array_at::<16, 4, _>(&end));
489
490 let (directory, boundary) = if let Some((directory, boundary)) =
491 Self::read_zip64(reader, position, budget).await?
492 {
493 let agrees16 = |field: u16, value| field == u16::MAX || u64::from(field) == value;
495 let agrees32 = |field: u32, value| field == u32::MAX || u64::from(field) == value;
496 if !agrees16(disk, 0)
497 || !agrees16(directory_disk, 0)
498 || !agrees16(disk_count, directory.count)
499 || !agrees16(count, directory.count)
500 || !agrees32(size, directory.size)
501 || !agrees32(offset, directory.offset)
502 {
503 return Err(invalid(position, "classic and ZIP64 end records disagree"));
504 }
505 (directory, boundary)
506 } else {
507 if disk != 0 || directory_disk != 0 {
508 return Err(Error::Unsupported {
509 position,
510 feature: "multiple volumes",
511 });
512 }
513 if disk_count != count {
514 return Err(invalid(position, "entry counts disagree"));
515 }
516 if size == u32::MAX || offset == u32::MAX {
519 return Err(invalid(position, "ZIP64 sentinel without locator"));
520 }
521
522 let directory = Self {
523 offset: u64::from(offset),
524 size: u64::from(size),
525 count: u64::from(count),
526 };
527 budget.check_entry_count(directory.count)?;
528 budget.charge_metadata(directory.size)?;
529 (directory, position)
530 };
531
532 if add(directory.offset, directory.size)? != boundary {
533 return Err(invalid(
534 directory.offset,
535 "central directory boundary mismatch",
536 ));
537 }
538
539 if directory.count > directory.size / size::CENTRAL as u64 {
540 return Err(invalid(
541 directory.offset,
542 "entry count exceeds directory capacity",
543 ));
544 }
545
546 Ok(directory)
547 }
548
549 async fn read_entries<R: AsyncRead + AsyncSeek + Unpin>(
551 &self,
552 reader: &mut RecordReader<'_, R>,
553 budget: &mut Budget,
554 policy: &IndexPolicy,
555 ) -> Result<Vec<IndexedEntry>, Error> {
556 let end = add(self.offset, self.size)?;
557 let mut position = self.offset;
558 let mut entries = Vec::with_capacity(self.count as usize);
560
561 if self.size >= size::SIGNATURE as u64 {
562 let mut signature = [0; size::SIGNATURE];
563 reader.read_at(position, &mut signature, end).await?;
564 if u32::from_le_bytes(signature) == signature::ARCHIVE_EXTRA {
565 return Err(Error::Unsupported {
566 position,
567 feature: "archive extra data record",
568 });
569 }
570 }
571
572 let mut bytes = reader.buffered(position, end);
573 while entries.len() < self.count as usize {
574 match CentralDirectoryEntry::parse(bytes, position, budget, policy)? {
575 BufferedEntry::Complete(entry, length) => {
576 entries.push(IndexedEntry::new(entry, self.offset)?);
577 position += length as u64;
578 bytes = &bytes[length..];
579 }
580 BufferedEntry::Incomplete(needed) => {
581 tokio::task::yield_now().await;
583 reader.read_slice(position, needed, end).await?;
584 bytes = reader.buffered(position, end);
585 }
586 }
587 }
588
589 if position != end {
590 return Err(invalid(
591 position,
592 "unaccounted directory bytes or digital signature",
593 ));
594 }
595
596 Ok(entries)
597 }
598}
599
600async fn check_destination_order(entries: &[IndexedEntry]) -> Result<(), Error> {
603 let mut last_offsets = HashMap::with_capacity(entries.len());
604 for entry in entries {
605 let directory = entry.directory();
606 let offset = directory.position();
607 if last_offsets
608 .insert(member_destination(directory.path()), offset)
609 .is_some_and(|previous| previous > offset)
610 {
611 return Err(invalid(
612 offset,
613 "duplicate destination order disagrees with local headers",
614 ));
615 }
616 tokio::task::consume_budget().await;
617 }
618 Ok(())
619}
620
621fn member_destination(path: &str) -> Cow<'_, str> {
623 let path = path.trim_end_matches('/');
624 if !path.split('/').any(|part| matches!(part, "" | ".")) {
625 return Cow::Borrowed(path);
626 }
627 let mut destination = String::with_capacity(path.len());
628 for part in path.split('/').filter(|part| !matches!(*part, "" | ".")) {
629 if !destination.is_empty() {
630 destination.push('/');
631 }
632 destination.push_str(part);
633 }
634 Cow::Owned(destination)
635}
636
637fn find_end(tail: &[u8], tail_start: u64) -> Result<(usize, [u8; size::END]), Error> {
640 const SIGNATURE: [u8; 4] = signature::END.to_le_bytes();
641 let mut candidate = None;
642 let mut scan = |bytes: &[u8], start: usize| {
643 for offset in memmem::find_iter(bytes, &SIGNATURE).map(|offset| start + offset) {
644 if let Some(header) = tail[offset..].first_chunk::<{ size::END }>()
645 && offset
646 + size::END
647 + usize::from(u16::from_le_bytes(array_at::<20, 2, _>(header)))
648 == tail.len()
649 && candidate.replace((offset, *header)).is_some()
650 {
651 return Err(invalid(tail_start + offset as u64, "ambiguous end records"));
652 }
653 }
654 Ok(())
655 };
656
657 let candidates = tail.len() - (size::END - 1);
660 let (blocks, remainder) = tail[2..2 + candidates].as_chunks::<64>();
661 for (ordinal, first) in blocks.iter().enumerate() {
662 let start = ordinal * 64;
663 let second = &tail[start + 3..start + 3 + 64];
664 let candidate = first
665 .iter()
666 .zip(second)
667 .fold(0, |found, (&first, &second)| {
668 found | (u8::from(first == SIGNATURE[2]) & u8::from(second == SIGNATURE[3]))
669 });
670 if candidate != 0 {
671 scan(&tail[start..start + 64 + 3], start)?;
674 }
675 }
676 let start = blocks.len() * 64;
677 scan(&tail[start..start + remainder.len() + 3], start)?;
678
679 candidate.ok_or_else(|| {
680 invalid(
681 tail_start + tail.len() as u64,
682 "missing end record or trailing bytes",
683 )
684 })
685}
686
687impl CentralDirectory {
688 async fn read_zip64<R: AsyncRead + AsyncSeek + Unpin>(
692 reader: &mut RecordReader<'_, R>,
693 end_position: u64,
694 budget: &mut Budget,
695 ) -> Result<Option<(Self, u64)>, Error> {
696 let Some(locator_position) = end_position.checked_sub(size::ZIP64_LOCATOR as u64) else {
697 return Ok(None);
698 };
699 let mut locator = [0; size::ZIP64_LOCATOR];
700 reader
701 .read_at(locator_position, &mut locator, end_position)
702 .await?;
703 if u32::from_le_bytes(array_at::<0, 4, _>(&locator)) != signature::ZIP64_LOCATOR {
704 return Ok(None);
705 }
706
707 if u32::from_le_bytes(array_at::<4, 4, _>(&locator)) != 0
708 || u32::from_le_bytes(array_at::<16, 4, _>(&locator)) != 1
709 {
710 return Err(Error::Unsupported {
711 position: locator_position,
712 feature: "multiple volumes",
713 });
714 }
715
716 let position = u64::from_le_bytes(array_at::<8, 8, _>(&locator));
717 let mut header = [0; size::ZIP64_END];
718 reader
719 .read_at(position, &mut header, locator_position)
720 .await?;
721 if u32::from_le_bytes(array_at::<0, 4, _>(&header)) != signature::ZIP64_END {
722 return Err(invalid(position, "invalid ZIP64 end signature"));
723 }
724
725 let end_size = u64::from_le_bytes(array_at::<4, 8, _>(&header));
726 if end_size < size::ZIP64_END_BODY as u64
727 || add(position, add(size::ZIP64_END_PREFIX as u64, end_size)?)? != locator_position
728 {
729 return Err(invalid(position, "invalid ZIP64 end length"));
730 }
731
732 let version_needed = u16::from_le_bytes(array_at::<14, 2, _>(&header));
733 if version_needed >= version::ZIP64_V2 {
734 return Err(Error::Unsupported {
735 position,
736 feature: "ZIP64 version-2 directory",
737 });
738 }
739 if version_needed != version::ZIP64 {
740 return Err(invalid(position, "invalid ZIP64 extraction version"));
741 }
742 if end_size != size::ZIP64_END_BODY as u64 {
743 return Err(Error::Unsupported {
744 position,
745 feature: "ZIP64 extensible data sector",
746 });
747 }
748
749 if u32::from_le_bytes(array_at::<16, 4, _>(&header)) != 0
750 || u32::from_le_bytes(array_at::<20, 4, _>(&header)) != 0
751 {
752 return Err(Error::Unsupported {
753 position,
754 feature: "multiple volumes",
755 });
756 }
757
758 let count = u64::from_le_bytes(array_at::<32, 8, _>(&header));
759 if u64::from_le_bytes(array_at::<24, 8, _>(&header)) != count {
760 return Err(invalid(position, "ZIP64 entry counts disagree"));
761 }
762
763 let directory = Self {
764 offset: u64::from_le_bytes(array_at::<48, 8, _>(&header)),
765 size: u64::from_le_bytes(array_at::<40, 8, _>(&header)),
766 count,
767 };
768 budget.check_entry_count(count)?;
769 budget.charge_metadata(directory.size)?;
770 budget.charge_metadata(locator_position - position)?;
771
772 Ok(Some((directory, position)))
773 }
774}