1use crate::io::{self, BufRead, Read, Seek};
4use alloc::{borrow::Cow, boxed::Box, fmt, string::String, vec::Vec};
5
6use crate::{CompressionMethod, Decompressor, FileType, Timestamp, types, utils};
7
8mod extra_field;
9mod raw;
10
11use extra_field::{ExtraField, ExtraFields};
12
13pub use utils::validate_symlink;
14
15#[cold]
16fn invalid(msg: &str) -> io::Error {
17 io::Error::new(io::ErrorKind::InvalidData, msg)
18}
19
20#[cold]
21fn encrypted_file() -> io::Error {
22 io::Error::new(io::ErrorKind::Unsupported, "encrypted file")
23}
24
25#[cold]
26fn compressed() -> io::Error {
27 io::Error::new(io::ErrorKind::Unsupported, "compressed file")
28}
29
30trait ReadSeek: Read + Seek {}
31impl<R: Read + Seek> ReadSeek for R {}
32
33#[cfg(feature = "std")]
34trait BufReadSeek: BufRead + Seek {}
35#[cfg(feature = "std")]
36impl<R: BufRead + Seek> BufReadSeek for R {}
37
38#[derive(Debug, Clone, Copy)]
46#[non_exhaustive]
47pub enum EncryptionMethod {
48 ZipCrypto,
50 StrongEncrytion,
52 Aes {
57 key_size: u16,
59 check_crc32: bool,
63 },
64}
65
66pub struct RawArchive {
68 entries: Vec<Metadata>,
69 names: utils::NameTable<usize>,
70 comment: Box<[u8]>,
71}
72
73impl fmt::Debug for RawArchive {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("RawArchive")
76 .field("entries", &self.entries)
77 .field("comment", &String::from_utf8_lossy(&self.comment))
78 .finish()
79 }
80}
81
82impl RawArchive {
83 #[inline]
87 pub fn new<R: Read + Seek>(reader: &mut R) -> io::Result<Self> {
88 raw::read_archive(reader)
89 }
90
91 #[inline]
93 pub fn entries(&self) -> &[Metadata] {
94 &self.entries
95 }
96
97 #[inline]
99 pub fn comment(&self) -> &[u8] {
100 &self.comment
101 }
102
103 #[inline]
105 pub fn get_by_name(&mut self, name: &str) -> Option<&Metadata> {
106 let index = self.index_of(name)?;
107 self.entries.get(index)
108 }
109
110 pub fn index_of(&self, name: &str) -> Option<usize> {
112 let stripped_name = name.strip_suffix('/');
113 let name = stripped_name.unwrap_or(name);
114
115 let index = *self
116 .names
117 .get(name.as_bytes(), |i| self.entries[*i].stripped_name())?;
118
119 if self.entries[index].file_type.is_directory() != stripped_name.is_some() {
123 return None;
124 }
125
126 Some(index)
127 }
128
129 #[cfg(feature = "std")]
133 pub fn extract<R: BufRead + Seek>(
134 &self,
135 reader: &mut R,
136 at: &std::path::Path,
137 ) -> io::Result<()> {
138 match std::fs::create_dir(at) {
139 Ok(()) => (),
140 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
141 Err(err) => return Err(err),
142 };
143
144 for entry in &self.entries {
145 entry.extract(reader, at)?;
146 }
147
148 Ok(())
149 }
150
151 #[cfg(feature = "parallel")]
158 pub fn parallel_extract<R: sync_file::ReadAt + sync_file::Size + Sync>(
159 &self,
160 reader: &R,
161 at: &std::path::Path,
162 ) -> io::Result<()> {
163 use rayon::prelude::*;
164
165 match std::fs::create_dir(at) {
166 Ok(()) => (),
167 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
168 Err(err) => return Err(err),
169 };
170
171 self.entries.par_iter().try_for_each_init(
172 || io::BufReader::new(sync_file::Adapter::new(reader)),
173 |reader, entry| entry.extract(reader, at),
174 )?;
175
176 Ok(())
177 }
178}
179
180impl FileType {
181 fn test(attr: u32, name: &str) -> Option<Self> {
182 let dos_attr = attr as u16;
183 let unix_mode = (attr >> 16) as u16;
184 let unix_kind = unix_mode >> 12;
185
186 let is_file = (dos_attr & (1 << 5)) != 0 || unix_kind == 8;
187 let is_dir = (dos_attr & (1 << 4)) != 0 || unix_kind == 4;
188 let is_symlink = unix_kind == 10;
189 let trailing_slash = name.ends_with('/');
190
191 match (is_file, is_dir, trailing_slash, is_symlink) {
192 (_, false, false, false) => Some(FileType::File),
193 (false, _, true, false) => Some(FileType::Directory),
194 (false, false, false, true) => Some(FileType::Symlink),
195 _ => None,
196 }
197 }
198}
199
200fn convert_string(raw: &[u8], force_unicode: bool) -> Option<(Cow<'_, str>, Option<u32>)> {
201 if let Ok(name) = str::from_utf8(raw) {
205 return Some((Cow::Borrowed(name), None));
206 }
207
208 if force_unicode {
210 None
211 } else {
212 let name = utils::cp437::convert(raw);
213 Some((Cow::Owned(name), Some(crc32fast::hash(raw))))
214 }
215}
216
217#[derive(Debug)]
219pub struct Metadata {
220 header_offset: u64,
221 pub data_offset: u64,
222
223 pub compressed_size: u64,
224 pub uncompressed_size: u64,
225 pub compression_method: CompressionMethod,
226 pub crc32: u32,
227 pub file_type: FileType,
228
229 pub unix_mode: u32,
236 pub modification_time: Option<Timestamp>,
237 pub access_time: Option<Timestamp>,
238 pub creation_time: Option<Timestamp>,
239
240 pub encryption: Option<EncryptionMethod>,
241
242 name: Box<str>,
243 comment: Box<str>,
244
245 is_streaming: bool,
246 is_zip64: bool,
247 flags: u16,
248}
249
250impl Metadata {
251 fn from_local_header(
252 header: types::LocalFileHeader,
253 file_name: &[u8],
254 extra_fields: &[u8],
255 ) -> Option<Self> {
256 let flags = header.flags.get();
257 let is_encrypted = flags & (1 << 0) != 0;
258 let is_streaming = flags & (1 << 3) != 0;
259 let strong_encryption = flags & (1 << 6) != 0;
260 let is_unicode = flags & (1 << 11) != 0;
261
262 if { header.signature } != types::LocalFileHeader::SIGNATURE {
263 return None;
264 }
265
266 let (name, name_crc) = convert_string(file_name, is_unicode)?;
267 let name = utils::validate_name(&name)?;
268
269 let encryption = match (is_encrypted, strong_encryption) {
270 (false, false) => None,
271 (false, true) => return None,
272 (true, false) => Some(EncryptionMethod::ZipCrypto),
273 (true, true) => Some(EncryptionMethod::StrongEncrytion),
274 };
275
276 let mut meta = Self {
277 crc32: header.crc32.get(),
278 encryption,
279 header_offset: 0,
280 data_offset: 0,
281
282 compressed_size: header.compressed_size.get() as u64,
283 uncompressed_size: header.uncompressed_size.get() as u64,
284 compression_method: CompressionMethod(header.compression_method.get()),
285 file_type: FileType::File,
286
287 unix_mode: 0,
288 modification_time: None,
289 access_time: None,
290 creation_time: None,
291
292 name,
293 comment: Box::default(),
294
295 is_streaming,
296 is_zip64: false,
297 flags,
298 };
299
300 meta.parse_extra_fields(ExtraFields(extra_fields), name_crc, None)?;
301
302 Some(meta)
303 }
304
305 fn from_central_header(
306 header: types::CentralFileHeader,
307 file_name: &[u8],
308 extra_fields: &[u8],
309 comment: &[u8],
310 ) -> Option<Self> {
311 let flags = header.flags.get();
312 let is_encrypted = flags & (1 << 0) != 0;
313 let is_streaming = flags & (1 << 3) != 0;
314 let strong_encryption = flags & (1 << 6) != 0;
315 let is_unicode = flags & (1 << 11) != 0;
316
317 if { header.signature } != types::CentralFileHeader::SIGNATURE
318 || header.disk_number.get() != 0
319 {
320 return None;
321 }
322
323 let (comment, comment_crc) = convert_string(comment, is_unicode)?;
324 let comment = comment.into_owned().into_boxed_str();
325 let (name, name_crc) = convert_string(file_name, is_unicode)?;
326 let name = utils::validate_name(&name)?;
327 let file_type = FileType::test(header.external_attributes.get(), &name)?;
328
329 let encryption = match (is_encrypted, strong_encryption) {
330 (false, false) => None,
331 (false, true) => return None,
332 (true, false) => Some(EncryptionMethod::ZipCrypto),
333 (true, true) => Some(EncryptionMethod::StrongEncrytion),
334 };
335
336 let mut meta = Self {
337 crc32: header.crc32.get(),
338 encryption,
339 header_offset: header.local_header_offset.get() as u64,
340 data_offset: 0,
341
342 compressed_size: header.compressed_size.get() as u64,
343 uncompressed_size: header.uncompressed_size.get() as u64,
344 compression_method: CompressionMethod(header.compression_method.get()),
345 file_type,
346
347 unix_mode: header.external_attributes.get() >> 16 & 0o7777,
348 modification_time: None,
349 access_time: None,
350 creation_time: None,
351
352 name,
353 comment,
354
355 is_streaming,
356 is_zip64: false,
357 flags,
358 };
359
360 meta.parse_extra_fields(ExtraFields(extra_fields), name_crc, comment_crc)?;
361
362 Some(meta)
363 }
364
365 fn parse_extra_fields(
366 &mut self,
367 extra_fields: ExtraFields,
368 name_crc: Option<u32>,
369 comment_crc: Option<u32>,
370 ) -> Option<()> {
371 for field in extra_fields.iter() {
372 match field {
373 ExtraField::Zip64ExtendedInformation(mut info) => {
374 if self.uncompressed_size == 0xffff_ffff {
375 self.uncompressed_size = info.next()?;
376 }
377 if self.compressed_size == 0xffff_ffff {
378 self.compressed_size = info.next()?;
379 }
380 if self.header_offset == 0xffff_ffff {
381 self.header_offset = info.next()?;
382 }
383 info.end()?;
385 self.is_zip64 = true;
386 }
387 ExtraField::UnicodeComment(unicode) => {
388 if Some(unicode.header_comment_crc32) != comment_crc {
389 return None;
390 }
391 self.comment = unicode.comment.into();
392 }
393
394 ExtraField::UnicodeName(unicode) => {
395 if Some(unicode.header_name_crc32) != name_crc {
396 return None;
397 }
398 self.name = utils::validate_name(unicode.name)?;
399 }
400
401 ExtraField::Ntfs(ntfs) => {
402 self.modification_time = ntfs.times.mtime;
403 self.access_time = ntfs.times.atime;
404 self.creation_time = ntfs.times.ctime;
405 }
406
407 ExtraField::ExtendedTimestamp(ts) => {
408 self.modification_time = ts.modification_time;
409 self.access_time = ts.access_time;
410 self.creation_time = ts.creation_time;
411 }
412
413 ExtraField::Aes(aes) => {
414 if self.compression_method != CompressionMethod::AES
415 || (!aes.check_crc32 && self.crc32 != 0)
416 {
417 return None;
418 }
419 let Some(enc @ EncryptionMethod::ZipCrypto) = &mut self.encryption else {
420 return None;
421 };
422
423 *enc = EncryptionMethod::Aes {
424 key_size: aes.key_size,
425 check_crc32: aes.check_crc32,
426 };
427 self.compression_method = aes.compression;
428 }
429
430 ExtraField::Invalid => return None,
431
432 _ => (),
433 }
434 }
435
436 if self.compression_method == CompressionMethod::AES {
437 return None;
438 }
439
440 Some(())
441 }
442
443 #[inline]
445 pub fn is_encrypted(&self) -> bool {
446 self.encryption.is_some()
447 }
448
449 #[inline]
451 pub fn name(&self) -> &str {
452 &self.name
453 }
454
455 fn stripped_name(&self) -> &[u8] {
456 self.name.strip_suffix('/').unwrap_or(&self.name).as_bytes()
457 }
458
459 #[inline]
461 pub fn comment(&self) -> &str {
462 &self.comment
463 }
464
465 pub fn read<R: BufRead + Seek>(&self, reader: R) -> io::Result<impl Read + use<R>> {
469 if self.encryption.is_some() {
470 return Err(encrypted_file());
471 }
472
473 let reader = Decompressor::new(self.read_raw(reader)?, self.compression_method)?;
474 Ok(self.content_checker(reader))
475 }
476
477 pub fn read_stored<R: Read + Seek>(&self, mut reader: R) -> io::Result<io::Take<R>> {
485 if self.encryption.is_some() {
486 return Err(encrypted_file());
487 }
488 if self.compression_method != CompressionMethod::STORE {
489 return Err(compressed());
490 }
491
492 let mut checker = utils::Crc32Checker::new(self.read_raw(&mut reader)?, self.crc32);
494 io::copy(&mut checker, &mut io::sink())?;
495
496 self.read_raw(reader)
497 }
498
499 pub fn read_raw<R: Read + Seek>(&self, mut reader: R) -> io::Result<io::Take<R>> {
503 reader.seek(io::SeekFrom::Start(self.data_offset))?;
504 Ok(reader.take(self.compressed_size))
505 }
506
507 #[inline]
511 pub fn content_checker<R: Read>(&self, reader: R) -> impl Read + use<R> {
512 utils::Crc32Checker::new(
513 utils::LengthChecker::new(reader, self.uncompressed_size),
514 self.crc32,
515 )
516 }
517
518 #[cfg(feature = "std")]
520 #[inline]
521 pub fn extract<R: BufRead + Seek>(
522 &self,
523 reader: &mut R,
524 root: impl AsRef<std::path::Path>,
525 ) -> io::Result<()> {
526 self._extract(reader, root.as_ref())
527 }
528
529 #[cfg(feature = "std")]
530 fn _extract(&self, reader: &mut dyn BufReadSeek, at: &std::path::Path) -> io::Result<()> {
531 if !std::fs::metadata(at)?.is_dir() {
532 return Err(io::Error::from(io::ErrorKind::NotFound));
533 }
534
535 let path = at.join(&*self.name);
536 std::fs::create_dir_all(path.parent().unwrap())?;
537
538 #[cfg(unix)]
539 let perms = std::os::unix::fs::PermissionsExt::from_mode(self.unix_mode & 0o777);
540
541 match self.file_type {
542 FileType::File => {
543 let mut f = std::fs::File::create_new(&path)?;
544 io::copy(&mut self.read(reader)?, &mut f)?;
545
546 if let Some(mod_time) = self.modification_time {
547 f.set_times(std::fs::FileTimes::new().set_modified(mod_time.to_std()))?;
548 }
549 #[cfg(unix)]
550 if self.unix_mode != 0 {
551 f.set_permissions(perms)?;
552 }
553 }
554 FileType::Directory => {
555 std::fs::create_dir(&path)?;
556
557 #[cfg(unix)]
558 if self.unix_mode != 0 {
559 std::fs::set_permissions(&path, perms)?;
560 }
561 }
562 FileType::Symlink => {
563 let target = io::read_to_string(self.read(reader)?)?;
564 if !validate_symlink(&self.name, &target) {
565 return Err(invalid("invalid symlink target"));
566 }
567
568 #[cfg(unix)]
569 std::os::unix::fs::symlink(target, path)?;
570
571 #[cfg(windows)]
572 if target.ends_with('/') {
573 std::os::windows::fs::symlink_dir(target, path)?;
574 } else {
575 std::os::windows::fs::symlink_file(target, path)?;
576 }
577
578 #[cfg(not(any(unix, windows)))]
579 std::fs::write(path, target.as_bytes())?;
580 }
581 }
582
583 Ok(())
584 }
585}
586
587#[derive(Debug)]
610pub struct ArchiveReader<R> {
611 inner: RawArchive,
612 reader: R,
613}
614
615#[cfg(feature = "std")]
616impl ArchiveReader<io::BufReader<std::fs::File>> {
617 #[inline]
619 pub fn open(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
620 Self::_open(path.as_ref())
621 }
622
623 fn _open(path: &std::path::Path) -> io::Result<Self> {
624 Self::new(io::BufReader::new(std::fs::File::open(path)?))
625 }
626}
627
628#[cfg(feature = "parallel")]
629impl ArchiveReader<io::BufReader<sync_file::SyncFile>> {
630 #[inline]
632 pub fn open_parallel(path: impl AsRef<std::path::Path>) -> io::Result<Self> {
633 Self::_open(path.as_ref())
634 }
635
636 fn _open(path: &std::path::Path) -> io::Result<Self> {
637 Self::new(io::BufReader::new(sync_file::SyncFile::open(path)?))
638 }
639}
640
641impl<R: Read + Seek> ArchiveReader<R> {
642 pub fn new(mut reader: R) -> io::Result<Self> {
654 let inner = RawArchive::new(&mut reader)?;
655 Ok(Self { inner, reader })
656 }
657
658 #[inline]
662 #[allow(clippy::len_without_is_empty)]
663 pub fn len(&self) -> usize {
664 self.inner.entries.len()
665 }
666
667 #[inline]
669 pub fn entries(&self) -> &[Metadata] {
670 &self.inner.entries
671 }
672
673 #[inline]
675 pub fn get_by_index(&mut self, index: usize) -> Option<File<'_, R>> {
676 let metadata = self.inner.entries().get(index)?;
677 Some(File {
678 metadata,
679 reader: &mut self.reader,
680 })
681 }
682
683 pub fn get_by_name(&mut self, name: &str) -> Option<File<'_, R>> {
685 let index = self.index_of(name)?;
686 self.get_by_index(index)
687 }
688
689 pub fn index_of(&self, name: &str) -> Option<usize> {
691 self.inner.index_of(name)
692 }
693
694 #[inline]
696 pub fn commment(&self) -> &[u8] {
697 &self.inner.comment
698 }
699
700 #[cfg(feature = "std")]
704 #[inline]
705 pub fn extract(&mut self, at: impl AsRef<std::path::Path>) -> io::Result<()>
706 where
707 R: BufRead,
708 {
709 self.inner.extract(&mut self.reader, at.as_ref())
710 }
711
712 #[cfg(feature = "parallel")]
719 #[inline]
720 pub fn parallel_extract(&self, at: impl AsRef<std::path::Path>) -> io::Result<()>
721 where
722 R: sync_file::ReadAt + sync_file::Size + Sync,
723 {
724 self.inner.parallel_extract(&self.reader, at.as_ref())
725 }
726
727 #[inline]
729 pub fn get_ref(&self) -> &R {
730 &self.reader
731 }
732
733 #[inline]
735 pub fn get_mut(&mut self) -> &mut R {
736 &mut self.reader
737 }
738}
739
740pub type Archive<R> = ArchiveReader<R>;
742
743#[derive(Debug)]
745pub struct File<'a, R> {
746 metadata: &'a Metadata,
747 reader: &'a mut R,
748}
749
750impl<'a, R: Read + Seek> File<'a, R> {
751 #[inline]
756 pub fn metadata(&self) -> &'a Metadata {
757 self.metadata
758 }
759
760 #[inline]
764 pub fn read(&mut self) -> io::Result<impl Read + '_>
765 where
766 R: BufRead,
767 {
768 self.metadata.read(&mut *self.reader)
769 }
770
771 pub fn read_stored(self) -> io::Result<io::Take<&'a mut R>> {
779 self.metadata.read_stored(self.reader)
780 }
781
782 #[inline]
786 pub fn read_raw(&mut self) -> io::Result<io::Take<&mut R>> {
787 self.metadata.read_raw(self.reader)
788 }
789
790 pub fn into_reader(self) -> &'a mut R {
796 self.reader
797 }
798}