Skip to main content

eazip/read/
mod.rs

1//! Utilities to read an archive.
2
3use 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/// The method used to encrypt a file.
39///
40/// `eazip` does not provide the tools to decrypt these files, but provides the
41/// required metadata if you really need to.
42///
43/// This is only provided for completeness, please don't use this in scenarios
44/// where security actually matters and use proper tools (eg `age`).
45#[derive(Debug, Clone, Copy)]
46#[non_exhaustive]
47pub enum EncryptionMethod {
48    /// Legacy ZipCrypto encryption.
49    ZipCrypto,
50    /// PKWARE proprietary "Strong Encryption".
51    StrongEncrytion,
52    /// The file is encrypted using AES in CTR mode.
53    ///
54    /// See [the specification](https://www.winzip.com/en/support/aes-encryption/#file-format1)
55    /// for the format of the encrypted files.
56    Aes {
57        /// The size of the AES key. This may be 128, 192 or 256 bytes.
58        key_size: u16,
59        /// Whether to check the CRC32 of the decypted content.
60        ///
61        /// If `true`, this will lead to data leak.
62        check_crc32: bool,
63    },
64}
65
66/// An open ZIP archive without a reader
67pub 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    /// Creates a `RawArchive` from a reader.
84    ///
85    /// The same reader should be used for other methods.
86    #[inline]
87    pub fn new<R: Read + Seek>(reader: &mut R) -> io::Result<Self> {
88        raw::read_archive(reader)
89    }
90
91    /// Gets the list of entries in this archive.
92    #[inline]
93    pub fn entries(&self) -> &[Metadata] {
94        &self.entries
95    }
96
97    /// Gets the comment of the archive.
98    #[inline]
99    pub fn comment(&self) -> &[u8] {
100        &self.comment
101    }
102
103    /// Gets a file by its name.
104    #[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    /// Gets the index of a file in [`Self::entries`] by its name.
111    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        // To avoid duplicated names, directory names are stored without a
120        // trailing '/' in the map, but this implementation detail should not
121        // leak.
122        if self.entries[index].file_type.is_directory() != stripped_name.is_some() {
123            return None;
124        }
125
126        Some(index)
127    }
128
129    /// Extracts the archive to the given directory.
130    ///
131    /// The directory will be created if needed, but *not* its parent.
132    #[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    /// Extracts the archive to the given directory in parallel.
152    ///
153    /// The directory will be created if needed, but *not* its parent.
154    ///
155    /// The reader should implement [`sync_file::ReadAt`], like [`io::Cursor`]
156    /// or [`sync_file::RandomAccessFile`].
157    #[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    // MacOS stores the file name as UTF8, but does not use the unicode flag,
202    // and everyone seems fine with that, so if we meet UTF8 we'll just pretend
203    // that everything is fine.
204    if let Ok(name) = str::from_utf8(raw) {
205        return Some((Cow::Borrowed(name), None));
206    }
207
208    // If we didn't find UTF8 and it wasn't expected, handle it as CP437.
209    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/// The metadata of a ZIP entry.
218#[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    /// Unix permissions for this file. Only the first 12 bits is exposed, which
230    /// matches the `0o7777` mask. May be `0` if unspecified.
231    ///
232    /// **Warning**: When using this value on a real filesystem, make sure that
233    /// the sticky bit and the set-user-ID bit match what you expect.
234    /// These special bits are ignored by the `extract` method family.
235    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                    // Disk number must be 0
384                    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    /// Returns `true` if this file is encrypted.
444    #[inline]
445    pub fn is_encrypted(&self) -> bool {
446        self.encryption.is_some()
447    }
448
449    /// Gets the name of this entry.
450    #[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    /// Gets the comment of this entry.
460    #[inline]
461    pub fn comment(&self) -> &str {
462        &self.comment
463    }
464
465    /// Returns a reader with the content of the file.
466    ///
467    /// Unsupported compression methods and encrypted files will return an error.
468    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    /// Returns a reader with the content of the file.
478    ///
479    /// Errors if the file is compressed, encrypted or corrupted. Is is not
480    /// necessary to use `Metadata::content_checker` on the result.
481    ///
482    /// It is useful if you know that the file is stored as-is and you want to
483    /// take advantage of the `BufReader` or the `Seek` implementation.
484    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        // Check CRC beforehand. Length has already been checked.
493        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    /// Returns a reader with the raw, uncompressed, content of the file.
500    ///
501    /// The uncompressed content should be checked with `content_checker`.
502    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    /// Wraps a reader to check that its content matches this metadata.
508    ///
509    /// It is particularly  useful in combinaison of `read_raw`.
510    #[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    /// Extracts this entry as if the root of the archive was at `root`.
519    #[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/// An open ZIP archive.
588///
589/// This type owns the reader. If you need something more flexible, use
590/// [`RawArchive`] instead.
591///
592/// # Example
593///
594/// Print the name and content of each file in the archive:
595///
596/// ```no_run
597/// let mut archive = eazip::ArchiveReader::open("example.zip")?;
598///
599/// for i in 0..archive.entries().len() {
600///     let mut entry = archive.get_by_index(i).unwrap();
601///     let name = entry.metadata().name();
602///     let content = std::io::read_to_string(entry.read()?)?;
603///
604///     println!("{name}: {content}");
605/// }
606///
607/// # Ok::<(), std::io::Error>(())
608/// ```
609#[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    /// Opens the given file as a ZIP archive.
618    #[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    /// Opens the given file as a ZIP archive ready for parallel extract.
631    #[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    /// Opens a ZIP archive from a reader.
643    ///
644    /// This also perform many validation checks on the archive to make sure
645    /// that is it well-formed and does not have dangerous or duplicated paths.
646    /// The validity of file contents is checked lazily when reading them.
647    ///
648    /// The exact rules around validation are not part of semver guaranties and
649    /// may change at every release.
650    ///
651    /// **The targets of symlinks are not checked yet here**, though they are
652    /// through `extract` and `extract_parallel`.
653    pub fn new(mut reader: R) -> io::Result<Self> {
654        let inner = RawArchive::new(&mut reader)?;
655        Ok(Self { inner, reader })
656    }
657
658    /// Gets the number of entries in the archive.
659    ///
660    /// This is a shorthand for `self.entries().len()`.
661    #[inline]
662    #[allow(clippy::len_without_is_empty)]
663    pub fn len(&self) -> usize {
664        self.inner.entries.len()
665    }
666
667    /// Gets the list of entries in the archive.
668    #[inline]
669    pub fn entries(&self) -> &[Metadata] {
670        &self.inner.entries
671    }
672
673    /// Gets a file by its index.
674    #[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    /// Gets a file by its name.
684    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    /// Gets the index of a file in [`Self::entries`] by its name.
690    pub fn index_of(&self, name: &str) -> Option<usize> {
691        self.inner.index_of(name)
692    }
693
694    /// Gets the comment of the archive.
695    #[inline]
696    pub fn commment(&self) -> &[u8] {
697        &self.inner.comment
698    }
699
700    /// Extracts the archive to the given directory.
701    ///
702    /// The directory will be created if needed, but *not* its parent.
703    #[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    /// Extracts the archive to the given directory in parallel.
713    ///
714    /// The directory will be created if needed, but *not* its parent.
715    ///
716    /// The reader should implement [`sync_file::ReadAt`], like [`io::Cursor`]
717    /// or [`sync_file::SyncFile`].
718    #[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    /// Gets a shared reference to the underlying reader.
728    #[inline]
729    pub fn get_ref(&self) -> &R {
730        &self.reader
731    }
732
733    /// Gets a mutable reference to the underlying reader.
734    #[inline]
735    pub fn get_mut(&mut self) -> &mut R {
736        &mut self.reader
737    }
738}
739
740/// Type alias to [`ArchiveReader`] for compatibility.
741pub type Archive<R> = ArchiveReader<R>;
742
743/// A file in a ZIP archive.
744#[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    /// Gets the metadata of the file.
752    ///
753    /// The lifetime of the returned reference is bound to the `ArchiveReader`,
754    /// so it can outlive `self`.
755    #[inline]
756    pub fn metadata(&self) -> &'a Metadata {
757        self.metadata
758    }
759
760    /// Returns a reader with the content of the file.
761    ///
762    /// Unsupported compression methods will return an error.
763    #[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    /// Returns a reader with the content of the file.
772    ///
773    /// Errors if the file is compressed, encrypted or corrupted. Is is not
774    /// necessary to use `Metadata::content_checker` on the result.
775    ///
776    /// It is useful if you know that the file is stored as-is and you want to
777    /// take advantage of the `BufReader` or the `Seek` implementation.
778    pub fn read_stored(self) -> io::Result<io::Take<&'a mut R>> {
779        self.metadata.read_stored(self.reader)
780    }
781
782    /// Returns a reader with the raw, compressed, content of the file.
783    ///
784    /// The uncompressed content should be checked with [`Metadata::content_checker`].
785    #[inline]
786    pub fn read_raw(&mut self) -> io::Result<io::Take<&mut R>> {
787        self.metadata.read_raw(self.reader)
788    }
789
790    /// Consumes self, returning the underlying reader.
791    ///
792    /// This reader can be used with [`Metadata::read_raw`] to read the raw,
793    /// compressed content of the file. The uncompressed content should then be
794    /// checked with [`Metadata::content_checker`].
795    pub fn into_reader(self) -> &'a mut R {
796        self.reader
797    }
798}