1use crate::compression::CompressionMethod;
4use crate::read::config::Config;
5use crate::read::readers::{ZipFileReader, ZipFileSeekReader, make_crypto_reader, make_reader};
6use crate::read::{
7 ArchiveOffset, CentralDirectoryInfo, RootDirFilter, ZipFile, ZipFileSeek, ZipReadOptions,
8 central_header_to_zip_file,
9};
10use crate::result::{ZipError, ZipResult};
11use crate::spec;
12use crate::types::ZipFileData;
13use crate::unstable::path_to_string;
14use core::ops::Range;
15use indexmap::IndexMap;
16use std::borrow::Cow;
17use std::io::{Read, Seek, SeekFrom};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20#[derive(Debug)]
22pub struct ZipArchiveMetadata {
23 pub(crate) files: IndexMap<Box<[u8]>, ZipFileData>,
24 pub(crate) offset: u64,
25 pub(crate) dir_start: u64,
26 #[allow(dead_code)]
28 pub(crate) config: Config,
29 pub(crate) comment: Box<[u8]>,
30 pub(crate) zip64_extensible_data_sector: Option<Box<[u8]>>,
31}
32
33#[derive(Debug)]
34pub(crate) struct SharedBuilder {
35 pub(crate) files: Vec<super::ZipFileData>,
36 pub(super) offset: u64,
37 pub(super) dir_start: u64,
38 #[allow(dead_code)]
40 pub(super) config: super::Config,
41}
42
43impl SharedBuilder {
44 pub(crate) fn build(
45 self,
46 comment: Box<[u8]>,
47 zip64_extensible_data_sector: Option<Box<[u8]>>,
48 ) -> ZipArchiveMetadata {
49 let mut index_map = IndexMap::with_capacity(self.files.len());
50 self.files.into_iter().for_each(|file| {
51 index_map.insert(file.file_name_raw.clone(), file);
52 });
53 ZipArchiveMetadata {
54 files: index_map,
55 offset: self.offset,
56 dir_start: self.dir_start,
57 config: self.config,
58 comment,
59 zip64_extensible_data_sector,
60 }
61 }
62}
63
64#[derive(Clone, Debug)]
85pub struct ZipArchive<R> {
86 pub(super) reader: R,
87 pub(super) shared: Arc<ZipArchiveMetadata>,
88}
89
90impl<R> ZipArchive<R> {
91 pub(crate) fn from_finalized_writer(
92 files: IndexMap<Box<[u8]>, ZipFileData>,
93 comment: Box<[u8]>,
94 zip64_extensible_data_sector: Option<Box<[u8]>>,
95 reader: R,
96 central_start: u64,
97 ) -> Self {
98 let initial_offset = match files.first() {
99 Some((_, file)) => file.header_start,
100 None => central_start,
101 };
102 let shared = Arc::new(ZipArchiveMetadata {
103 files,
104 offset: initial_offset,
105 dir_start: central_start,
106 config: Config {
107 archive_offset: ArchiveOffset::Known(initial_offset),
108 },
109 comment,
110 zip64_extensible_data_sector,
111 });
112 Self { reader, shared }
113 }
114
115 pub fn decompressed_size(&self) -> Option<u128> {
118 let mut total = 0u128;
119 for file in self.shared.files.values() {
120 if file.using_data_descriptor {
121 return None;
122 }
123 total = total.checked_add(u128::from(file.uncompressed_size))?;
124 }
125 Some(total)
126 }
127}
128
129impl<R: Read + Seek> ZipArchive<R> {
130 pub(crate) fn get_metadata(config: Config, reader: &mut R) -> ZipResult<ZipArchiveMetadata> {
133 let file_len = reader.seek(SeekFrom::End(0))?;
135 let mut end_exclusive = file_len;
136 let mut last_err = None;
137
138 loop {
139 let cde = match spec::find_central_directory(
141 reader,
142 config.archive_offset,
143 end_exclusive,
144 file_len,
145 ) {
146 Ok(cde) => cde,
147 Err(e) => {
148 return Err(last_err.unwrap_or(e));
150 }
151 };
152
153 match CentralDirectoryInfo::try_from(&cde)
155 .and_then(|info| Self::read_central_header(&info, config, reader))
156 {
157 Ok(shared) => {
158 let zip64_extensible_data_sector = if let Some(eocd64) = cde.eocd64 {
159 eocd64.data.zip64_extensible_data_sector
160 } else {
161 None
162 };
163 return Ok(
164 shared.build(cde.eocd.data.zip_file_comment, zip64_extensible_data_sector)
165 );
166 }
167 Err(e) => {
168 last_err = Some(e);
169 }
170 }
171 end_exclusive = cde.eocd.position;
173 continue;
174 }
175 }
176
177 fn read_central_header(
178 dir_info: &CentralDirectoryInfo,
179 config: Config,
180 reader: &mut R,
181 ) -> Result<SharedBuilder, ZipError> {
182 let file_capacity = if dir_info.number_of_files > dir_info.directory_start as usize {
185 0
186 } else {
187 dir_info.number_of_files
188 };
189
190 if dir_info.disk_number != dir_info.disk_with_central_directory {
191 return Err(ZipError::UnsupportedArchive(
192 "Support for multi-disk files is not implemented",
193 ));
194 }
195
196 if file_capacity.saturating_mul(size_of::<ZipFileData>()) > isize::MAX as usize {
197 return Err(ZipError::UnsupportedArchive("Oversized central directory"));
198 }
199
200 let mut files = Vec::with_capacity(file_capacity);
201 reader.seek(SeekFrom::Start(dir_info.directory_start))?;
202 for _ in 0..dir_info.number_of_files {
203 let file = central_header_to_zip_file(reader, dir_info)?;
204 files.push(file);
205 }
206
207 Ok(SharedBuilder {
208 files,
209 offset: dir_info.archive_offset,
210 dir_start: dir_info.directory_start,
211 config,
212 })
213 }
214
215 #[cfg(feature = "aes-crypto")]
223 pub fn get_aes_verification_key_and_salt(
224 &mut self,
225 file_number: usize,
226 ) -> ZipResult<Option<crate::aes::AesInfo>> {
227 let (_, data) = self
228 .shared
229 .files
230 .get_index(file_number)
231 .ok_or(ZipError::FileNotFound)?;
232
233 let limit_reader = data.find_content(&mut self.reader)?;
234 match data.aes_mode {
235 None => Ok(None),
236 Some((aes_mode, _, _)) => {
237 let (verification_value, salt) =
238 crate::aes::AesReader::new(limit_reader, aes_mode, data.compressed_size)
239 .get_verification_value_and_salt()?;
240 let aes_info = crate::aes::AesInfo {
241 aes_mode,
242 verification_value,
243 salt,
244 };
245 Ok(Some(aes_info))
246 }
247 }
248 }
249
250 pub fn new(reader: R) -> ZipResult<ZipArchive<R>> {
256 Self::with_config(Config::default(), reader)
257 }
258
259 pub fn metadata(&self) -> Arc<ZipArchiveMetadata> {
264 self.shared.clone()
265 }
266
267 pub unsafe fn unsafe_new_with_metadata(reader: R, metadata: Arc<ZipArchiveMetadata>) -> Self {
304 Self {
305 reader,
306 shared: metadata,
307 }
308 }
309
310 pub fn with_config(config: Config, mut reader: R) -> ZipResult<ZipArchive<R>> {
314 let shared = Self::get_metadata(config, &mut reader)?;
315
316 Ok(ZipArchive {
317 reader,
318 shared: shared.into(),
319 })
320 }
321
322 pub fn len(&self) -> usize {
324 self.shared.files.len()
325 }
326
327 pub fn central_directory_start(&self) -> u64 {
329 self.shared.dir_start
330 }
331
332 pub fn is_empty(&self) -> bool {
334 self.len() == 0
335 }
336
337 pub fn offset(&self) -> u64 {
342 self.shared.offset
343 }
344
345 pub fn comment(&self) -> &[u8] {
347 &self.shared.comment
348 }
349
350 #[deprecated(
352 note = "Zip64 comment is not part of the zip specification - see https://github.com/zip-rs/zip2/pull/747"
353 )]
354 pub fn zip64_comment(&self) -> Option<&[u8]> {
355 None
357 }
358
359 pub fn raw_zip64_extensible_data_sector(&self) -> Option<&[u8]> {
361 self.shared.zip64_extensible_data_sector.as_deref()
362 }
363
364 pub fn file_names(&self) -> impl Iterator<Item = &str> {
366 self.shared.files.values().map(|f| f.file_name.as_ref())
367 }
368
369 pub fn has_overlapping_files(&mut self) -> ZipResult<bool> {
373 let mut ranges = Vec::<Range<u64>>::with_capacity(self.shared.files.len());
374 for file in self.shared.files.values() {
375 if file.compressed_size == 0 {
376 continue;
377 }
378 let start = file.data_start(&mut self.reader)?;
379 let end = start + file.compressed_size;
380 if ranges
381 .iter()
382 .any(|range| range.start <= end && start <= range.end)
383 {
384 return Ok(true);
385 }
386 ranges.push(start..end);
387 }
388 Ok(false)
389 }
390
391 pub fn by_name_decrypt(&mut self, name: &str, password: &[u8]) -> ZipResult<ZipFile<'_, R>> {
405 self.by_name_with_optional_password(name, Some(password))
406 }
407
408 pub fn by_name(&mut self, name: &str) -> ZipResult<ZipFile<'_, R>> {
410 self.by_name_with_optional_password(name, None)
411 }
412
413 #[inline]
415 pub fn index_for_name(&self, name: &str) -> Option<usize> {
416 self.shared.files.get_index_of(name.as_bytes())
417 }
418
419 pub fn by_path_decrypt<T: AsRef<Path>>(
433 &mut self,
434 path: T,
435 password: &[u8],
436 ) -> ZipResult<ZipFile<'_, R>> {
437 self.index_for_path(path)
438 .ok_or(ZipError::FileNotFound)
439 .and_then(|index| {
440 self.by_index_with_options(index, ZipReadOptions::new().password(Some(password)))
441 })
442 }
443
444 pub fn by_path<T: AsRef<Path>>(&mut self, path: T) -> ZipResult<ZipFile<'_, R>> {
446 self.index_for_path(path)
447 .ok_or(ZipError::FileNotFound)
448 .and_then(|index| self.by_index_with_options(index, ZipReadOptions::new()))
449 }
450
451 #[inline(always)]
453 pub fn index_for_path<T: AsRef<Path>>(&self, path: T) -> Option<usize> {
454 let path_as_string = &path_to_string(path).ok()?;
455 self.index_for_name(path_as_string)
456 }
457
458 #[inline(always)]
460 pub fn name_for_index(&self, index: usize) -> Option<&str> {
461 self.shared
462 .files
463 .get_index(index)
464 .map(|(_, file)| file.file_name.as_ref())
465 }
466
467 pub fn by_name_seek(&mut self, name: &str) -> ZipResult<ZipFileSeek<'_, R>> {
469 self.by_index_seek(self.index_for_name(name).ok_or(ZipError::FileNotFound)?)
470 }
471
472 pub fn by_index_seek(&mut self, index: usize) -> ZipResult<ZipFileSeek<'_, R>> {
474 let reader = &mut self.reader;
475 self.shared
476 .files
477 .get_index(index)
478 .ok_or(ZipError::FileNotFound)
479 .and_then(move |(_, data)| {
480 let seek_reader = match data.compression_method {
481 CompressionMethod::Stored => {
482 ZipFileSeekReader::Raw(data.find_content_seek(reader)?)
483 }
484 _ => {
485 return Err(ZipError::UnsupportedArchive(
486 "Seekable compressed files are not yet supported",
487 ));
488 }
489 };
490 Ok(ZipFileSeek {
491 reader: seek_reader,
492 data: Cow::Borrowed(data),
493 })
494 })
495 }
496
497 fn by_name_with_optional_password<'a>(
498 &'a mut self,
499 name: &str,
500 password: Option<&[u8]>,
501 ) -> ZipResult<ZipFile<'a, R>> {
502 let Some(index) = self.shared.files.get_index_of(name.as_bytes()) else {
503 return Err(ZipError::FileNotFound);
504 };
505 self.by_index_with_options(index, ZipReadOptions::new().password(password))
506 }
507
508 pub fn by_index_decrypt(
522 &mut self,
523 file_number: usize,
524 password: &[u8],
525 ) -> ZipResult<ZipFile<'_, R>> {
526 self.by_index_with_options(file_number, ZipReadOptions::new().password(Some(password)))
527 }
528
529 pub fn by_index(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>> {
531 self.by_index_with_options(file_number, ZipReadOptions::new())
532 }
533
534 pub fn by_index_raw(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>> {
536 let reader = &mut self.reader;
537 let (_, data) = self
538 .shared
539 .files
540 .get_index(file_number)
541 .ok_or(ZipError::FileNotFound)?;
542 Ok(ZipFile {
543 reader: ZipFileReader::Raw(data.find_content(reader)?),
544 data: Cow::Borrowed(data),
545 })
546 }
547
548 pub fn by_index_with_options(
550 &mut self,
551 file_number: usize,
552 mut options: ZipReadOptions<'_>,
553 ) -> ZipResult<ZipFile<'_, R>> {
554 let (_, data) = self
555 .shared
556 .files
557 .get_index(file_number)
558 .ok_or(ZipError::FileNotFound)?;
559
560 if options.ignore_encryption_flag {
561 options.password = None;
563 } else {
564 match (options.password, data.encrypted) {
566 (None, true) => {
567 return Err(ZipError::UnsupportedArchive(ZipError::PASSWORD_REQUIRED));
568 }
569 (Some(_), false) => options.password = None,
571 _ => {}
572 }
573 }
574 let limit_reader = data.find_content(&mut self.reader)?;
575
576 let crypto_reader =
577 make_crypto_reader(data, limit_reader, options.password, data.aes_mode)?;
578
579 let crc32 = if options.ignore_crc {
580 None
581 } else {
582 Some(data.crc32)
583 };
584
585 Ok(ZipFile {
586 data: Cow::Borrowed(data),
587 reader: make_reader(
588 data.compression_method,
589 data.uncompressed_size,
590 crc32,
591 crypto_reader,
592 #[cfg(feature = "legacy-zip")]
593 data.flags,
594 )?,
595 })
596 }
597
598 pub fn root_dir(&self, filter: impl RootDirFilter) -> ZipResult<Option<PathBuf>> {
609 let mut root_dir: Option<PathBuf> = None;
610
611 for i in 0..self.len() {
612 let (_, file) = self
613 .shared
614 .files
615 .get_index(i)
616 .ok_or(ZipError::FileNotFound)?;
617
618 let path = match file.enclosed_name() {
619 Some(path) => path,
620 None => return Ok(None),
621 };
622
623 if !filter(&path) {
624 continue;
625 }
626
627 macro_rules! replace_root_dir {
628 ($path:ident) => {
629 match &mut root_dir {
630 Some(root_dir) => {
631 if *root_dir != $path {
632 return Ok(None);
635 }
636 continue;
637 }
638
639 None => {
640 root_dir = Some($path.into());
641 continue;
642 }
643 }
644 };
645 }
646
647 if path.components().count() == 1 {
649 if file.is_dir() {
650 replace_root_dir!(path);
652 }
653 return Ok(None);
656 }
657
658 let mut path = path.as_path();
660 while let Some(parent) = path.parent().filter(|path| *path != Path::new("")) {
661 path = parent;
662 }
663
664 replace_root_dir!(path);
665 }
666
667 Ok(root_dir)
668 }
669
670 pub fn into_inner(self) -> R {
674 self.reader
675 }
676}
677
678#[cfg(test)]
679mod tests {
680 #[test]
681 fn invalid_offset() {
682 use super::ZipArchive;
683 use std::io::Cursor;
684
685 let reader = ZipArchive::new(Cursor::new(include_bytes!(
686 "../../tests/data/invalid_offset.zip"
687 )));
688 assert!(reader.is_err());
689 }
690
691 #[test]
692 fn invalid_offset2() {
693 use super::ZipArchive;
694 use std::io::Cursor;
695
696 let reader = ZipArchive::new(Cursor::new(include_bytes!(
697 "../../tests/data/invalid_offset2.zip"
698 )));
699 assert!(reader.is_err());
700 }
701
702 #[test]
703 fn zip64_with_leading_junk() {
704 use super::ZipArchive;
705 use std::io::Cursor;
706
707 let reader = ZipArchive::new(Cursor::new(include_bytes!(
708 "../../tests/data/zip64_demo.zip"
709 )))
710 .unwrap();
711 assert_eq!(reader.len(), 1);
712 }
713
714 #[test]
715 fn zip_contents() {
716 use super::ZipArchive;
717 use std::io::Cursor;
718
719 let mut reader =
720 ZipArchive::new(Cursor::new(include_bytes!("../../tests/data/mimetype.zip"))).unwrap();
721 assert_eq!(reader.comment(), b"");
722 assert_eq!(reader.by_index(0).unwrap().central_header_start(), 77);
723 }
724
725 #[test]
726 fn zip_clone() {
727 use super::ZipArchive;
728 use std::io::Cursor;
729 use std::io::Read;
730
731 let mut reader1 =
732 ZipArchive::new(Cursor::new(include_bytes!("../../tests/data/mimetype.zip"))).unwrap();
733 let mut reader2 = reader1.clone();
734
735 let mut file1 = reader1.by_index(0).unwrap();
736 let mut file2 = reader2.by_index(0).unwrap();
737
738 let t = file1.last_modified().unwrap();
739 assert_eq!(
740 (
741 t.year(),
742 t.month(),
743 t.day(),
744 t.hour(),
745 t.minute(),
746 t.second()
747 ),
748 (1980, 1, 1, 0, 0, 0)
749 );
750
751 let mut buf1 = [0; 5];
752 let mut buf2 = [0; 5];
753 let mut buf3 = [0; 5];
754 let mut buf4 = [0; 5];
755
756 file1.read_exact(&mut buf1).unwrap();
757 file2.read_exact(&mut buf2).unwrap();
758 file1.read_exact(&mut buf3).unwrap();
759 file2.read_exact(&mut buf4).unwrap();
760
761 assert_eq!(buf1, buf2);
762 assert_eq!(buf3, buf4);
763 assert_ne!(buf1, buf3);
764 }
765
766 #[test]
767 fn file_and_dir_predicates() {
768 use super::ZipArchive;
769 use std::io::Cursor;
770
771 let mut zip = ZipArchive::new(Cursor::new(include_bytes!(
772 "../../tests/data/files_and_dirs.zip"
773 )))
774 .unwrap();
775
776 for i in 0..zip.len() {
777 let zip_file = zip.by_index(i).unwrap();
778 let full_name = zip_file.enclosed_name().unwrap();
779 let file_name = full_name.file_name().unwrap().to_str().unwrap();
780 assert!(
781 (file_name.starts_with("dir") && zip_file.is_dir())
782 || (file_name.starts_with("file") && zip_file.is_file())
783 );
784 }
785 }
786
787 #[test]
788 fn zip64_magic_in_filenames() {
789 use super::ZipArchive;
790 use std::io::Cursor;
791
792 let files = vec![
793 include_bytes!("../../tests/data/zip64_magic_in_filename_1.zip").to_vec(),
794 include_bytes!("../../tests/data/zip64_magic_in_filename_2.zip").to_vec(),
795 include_bytes!("../../tests/data/zip64_magic_in_filename_3.zip").to_vec(),
796 include_bytes!("../../tests/data/zip64_magic_in_filename_4.zip").to_vec(),
797 include_bytes!("../../tests/data/zip64_magic_in_filename_5.zip").to_vec(),
798 ];
799 for file in files {
802 ZipArchive::new(Cursor::new(file)).unwrap();
803 }
804 }
805
806 #[test]
810 fn invalid_cde_number_of_files_allocation_smaller_offset() {
811 use super::ZipArchive;
812 use std::io::Cursor;
813
814 let reader = ZipArchive::new(Cursor::new(include_bytes!(
815 "../../tests/data/invalid_cde_number_of_files_allocation_smaller_offset.zip"
816 )));
817 assert!(reader.is_err() || reader.unwrap().is_empty());
818 }
819
820 #[test]
824 fn invalid_cde_number_of_files_allocation_greater_offset() {
825 use super::ZipArchive;
826 use std::io::Cursor;
827
828 let reader = ZipArchive::new(Cursor::new(include_bytes!(
829 "../../tests/data/invalid_cde_number_of_files_allocation_greater_offset.zip"
830 )));
831 assert!(reader.is_err());
832 }
833
834 #[cfg(feature = "deflate64")]
835 #[test]
836 fn deflate64_index_out_of_bounds() {
837 use super::ZipArchive;
838 use std::io::Cursor;
839
840 let mut reader = ZipArchive::new(Cursor::new(include_bytes!(
841 "../../tests/data/raw_deflate64_index_out_of_bounds.zip"
842 )))
843 .unwrap();
844 let mut file = reader.by_index(0).unwrap();
845 std::io::copy(&mut file, &mut std::io::sink()).expect_err("Invalid file");
846 }
847
848 #[cfg(feature = "deflate64")]
849 #[test]
850 fn deflate64_not_enough_space() {
851 use super::ZipArchive;
852 use std::io::Cursor;
853
854 ZipArchive::new(Cursor::new(include_bytes!(
855 "../../tests/data/deflate64_issue_25.zip"
856 )))
857 .expect_err("Invalid file");
858 }
859
860 #[cfg(feature = "deflate-flate2")]
861 #[test]
862 fn test_read_with_data_descriptor() {
863 use super::ZipArchive;
864 use std::io::Cursor;
865 use std::io::Read;
866
867 let mut reader = ZipArchive::new(Cursor::new(include_bytes!(
868 "../../tests/data/data_descriptor.zip"
869 )))
870 .unwrap();
871 let mut decompressed = [0u8; 16];
872 let mut file = reader.by_index(0).unwrap();
873 assert_eq!(file.read(&mut decompressed).unwrap(), 12);
874 }
875
876 #[cfg(all(target_endian = "little", not(miri)))]
878 #[test]
879 fn test_central_directory_not_at_end() {
880 use super::ZipArchive;
881 use std::io::Cursor;
882 use std::io::Read;
883
884 let mut reader =
885 ZipArchive::new(Cursor::new(include_bytes!("../../tests/data/omni.ja"))).unwrap();
886 let mut file = reader.by_name("chrome.manifest").unwrap();
887 let mut contents = String::new();
888 file.read_to_string(&mut contents).unwrap(); assert!(!contents.is_empty(), "chrome.manifest should not be empty");
890 drop(file);
891 for i in 0..reader.len() {
892 let mut file = reader.by_index(i).unwrap();
893 let mut buffer = Vec::new();
895 file.read_to_end(&mut buffer).unwrap();
896 assert_eq!(
897 buffer.len(),
898 file.size() as usize,
899 "File size mismatch for {}",
900 file.name()
901 );
902 }
903 }
904
905 #[test]
906 fn test_ignore_encryption_flag() {
907 use super::ZipArchive;
908 use crate::ZipReadOptions;
909 use std::io::Cursor;
910 use std::io::Read;
911
912 let mut reader = ZipArchive::new(Cursor::new(include_bytes!(
913 "../../tests/data/ignore_encryption_flag.zip"
914 )))
915 .unwrap();
916
917 let mut file = reader
919 .by_index_with_options(0, ZipReadOptions::new().ignore_encryption_flag(true))
920 .unwrap();
921 let mut contents = String::new();
922 assert_eq!(file.name(), "plaintext.txt");
923
924 assert!(file.encrypted());
926 file.read_to_string(&mut contents).unwrap(); assert_eq!(contents, "This file is not encrypted.\n");
928 }
929}