pub struct ZipArchive<R> { /* private fields */ }Expand description
ZIP archive reader
At the moment, this type is cheap to clone if this is the case for the reader it uses. However, this is not guaranteed by this crate and it may change in the future.
use std::io::{Read, Seek};
fn list_zip_contents(reader: impl Read + Seek) -> zip::result::ZipResult<()> {
let mut zip = zip::ZipArchive::new(reader)?;
for i in 0..zip.len() {
let mut file = zip.by_index(i)?;
let name = file.name()?;
println!("Filename: {}", name);
std::io::copy(&mut file, &mut std::io::stdout())?;
}
Ok(())
}Implementations§
Source§impl<R: Read + Seek> ZipArchive<R>
impl<R: Read + Seek> ZipArchive<R>
Sourcepub fn extract<P: AsRef<Path>>(&mut self, directory: P) -> ZipResult<()>
pub fn extract<P: AsRef<Path>>(&mut self, directory: P) -> ZipResult<()>
Extract a Zip archive into a directory, overwriting files if they
already exist. Paths are sanitized with ZipFile::enclosed_name.
Symbolic links are only created, and only followed, if their target resolves to a path inside the destination directory. Paths are resolved one component at a time, and the target of every symlink encountered is resolved in the same way, so a symlink cannot be used as an intermediate component to reach outside the destination directory. Note that this does not protect against another process concurrently modifying the destination directory during extraction.
Extraction is not atomic. If an error is encountered, some of the files may be left on disk. However, on Unix targets, no newly-created directories with part but not all of their contents extracted will be readable, writable or usable as process working directories by any non-root user except you.
Extraction is also not atomic in term of permissions. Permissions are applied after the extraction (because some folder have stricter permissions when we cannot access it). That means, for a moment, a file could be created with default permissions (and then changed to the correct one). On Unix this only applies to directories and symlinks.
On Unix and Windows, symbolic links are extracted correctly. On other platforms such as WebAssembly, symbolic links aren’t supported, so they’re extracted as normal files containing the target path in UTF-8.
Sourcepub fn extract_with_options<P: AsRef<Path>>(
&mut self,
directory: P,
extract_options: ExtractOptions<impl RootDirFilter>,
) -> ZipResult<()>
pub fn extract_with_options<P: AsRef<Path>>( &mut self, directory: P, extract_options: ExtractOptions<impl RootDirFilter>, ) -> ZipResult<()>
Same as ZipArchive::extract, but with custom ExtractOptions.
To unwrap a root directory, set a filter with ExtractOptions::with_root_dir_filter;
see ZipArchive::extract_unwrapped_root_dir for the semantics.
Sourcepub fn extract_unwrapped_root_dir<P: AsRef<Path>>(
&mut self,
directory: P,
root_dir_filter: impl RootDirFilter,
) -> ZipResult<()>
pub fn extract_unwrapped_root_dir<P: AsRef<Path>>( &mut self, directory: P, root_dir_filter: impl RootDirFilter, ) -> ZipResult<()>
Extracts a Zip archive into a directory in the same fashion as
ZipArchive::extract, but detects a “root” directory in the archive
(a single top-level directory that contains the rest of the archive’s
entries) and extracts its contents directly.
For a sensible default filter, you can use crate::read::root_dir_common_filter.
For a custom filter, see RootDirFilter.
See ZipArchive::root_dir for more information on how the root
directory is detected and the meaning of the filter parameter.
To combine unwrapping with other options, use ZipArchive::extract_with_options
with ExtractOptions::with_root_dir_filter.
§Example
Imagine a Zip archive with the following structure:
root/file1.txt
root/file2.txt
root/sub/file3.txt
root/sub/subsub/file4.txtIf the archive is extracted to foo using ZipArchive::extract,
the resulting directory structure will be:
foo/root/file1.txt
foo/root/file2.txt
foo/root/sub/file3.txt
foo/root/sub/subsub/file4.txtIf the archive is extracted to foo using
ZipArchive::extract_unwrapped_root_dir, the resulting directory
structure will be:
foo/file1.txt
foo/file2.txt
foo/sub/file3.txt
foo/sub/subsub/file4.txt§Example - No Root Directory
Imagine a Zip archive with the following structure:
root/file1.txt
root/file2.txt
root/sub/file3.txt
root/sub/subsub/file4.txt
other/file5.txtDue to the presence of the other directory,
ZipArchive::extract_unwrapped_root_dir will extract this in the same
fashion as ZipArchive::extract as there is now no “root directory.”
Source§impl<R: Read + Seek + Send> ZipArchive<R>
impl<R: Read + Seek + Send> ZipArchive<R>
Sourcepub fn par_extract_with_reader_factory<P, F>(
&mut self,
directory: P,
reader_factory: F,
) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract_with_reader_factory<P, F>( &mut self, directory: P, reader_factory: F, ) -> ZipResult<()>
rayon only.Extracts archive contents in parallel across available CPU cores using a reader factory.
The reader_factory closure is called to produce an independent reader instance
for each worker thread, ensuring independent file offsets and preventing concurrent seek collisions.
§Common reader_factory Implementations
Parallel extraction requires that each worker thread possesses an independent seek position into the archive stream. Common implementations include:
-
In-memory slice (
Cursor<&[u8]>): Allows all worker threads to safely share an immutable buffer in memory without reallocation:archive.par_extract_with_reader_factory("destination", || Ok(Cursor::new(&slice)))?; -
Cloned file descriptor (
File::try_clone): Duplicates the file handle so that each worker thread maintains an independent file pointer:archive.par_extract_with_reader_factory("destination", || file.try_clone())?; -
Positional / Random-access cursor (
positioned_io::Cursor): Enables positional reads without duplicating kernel file handles:ⓘarchive.par_extract_with_reader_factory("destination", || { Ok(positioned_io::Cursor::new(random_access_file)) })?;
Sourcepub fn par_extract_with_reader_factory_and_options<P, F, Filter>(
&mut self,
directory: P,
reader_factory: F,
extract_options: ExtractOptions<impl RootDirFilter>,
root_dir_filter: Option<Filter>,
) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract_with_reader_factory_and_options<P, F, Filter>( &mut self, directory: P, reader_factory: F, extract_options: ExtractOptions<impl RootDirFilter>, root_dir_filter: Option<Filter>, ) -> ZipResult<()>
rayon only.Extracts archive contents in parallel using a reader factory, custom ExtractOptions,
and an optional RootDirFilter.
If root_dir_filter is Some, it takes precedence over any filter set with
ExtractOptions::with_root_dir_filter.
See ZipArchive::par_extract_with_reader_factory for common reader_factory implementations.
Source§impl ZipArchive<File>
impl ZipArchive<File>
Sourcepub fn par_extract_from_path<P: AsRef<Path>, Q: AsRef<Path>>(
&mut self,
archive_path: P,
destination: Q,
) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract_from_path<P: AsRef<Path>, Q: AsRef<Path>>( &mut self, archive_path: P, destination: Q, ) -> ZipResult<()>
rayon only.Extracts a filesystem-backed archive in parallel across available CPU cores.
Requires the path to the original archive file (archive_path) so that each
worker thread can open its own independent kernel file handle via File::open.
Sourcepub fn par_extract_from_path_with_options<P: AsRef<Path>, Q: AsRef<Path>>(
&mut self,
archive_path: P,
destination: Q,
options: ExtractOptions<impl RootDirFilter>,
) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract_from_path_with_options<P: AsRef<Path>, Q: AsRef<Path>>( &mut self, archive_path: P, destination: Q, options: ExtractOptions<impl RootDirFilter>, ) -> ZipResult<()>
rayon only.Extracts a filesystem-backed archive in parallel with custom ExtractOptions.
Root-directory unwrapping can be enabled with ExtractOptions::with_root_dir_filter.
Source§impl<T: AsRef<[u8]> + Sync + Send + Clone> ZipArchive<Cursor<T>>
impl<T: AsRef<[u8]> + Sync + Send + Clone> ZipArchive<Cursor<T>>
Sourcepub fn par_extract<P: AsRef<Path>>(&mut self, directory: P) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract<P: AsRef<Path>>(&mut self, directory: P) -> ZipResult<()>
rayon only.Extracts an in-memory archive in parallel across available CPU cores.
Sourcepub fn par_extract_with_options<P: AsRef<Path>>(
&mut self,
directory: P,
options: ExtractOptions<impl RootDirFilter>,
) -> ZipResult<()>
Available on crate feature rayon only.
pub fn par_extract_with_options<P: AsRef<Path>>( &mut self, directory: P, options: ExtractOptions<impl RootDirFilter>, ) -> ZipResult<()>
rayon only.Extracts an in-memory archive in parallel with custom ExtractOptions.
Root-directory unwrapping can be enabled with ExtractOptions::with_root_dir_filter.
Source§impl<R> ZipArchive<R>
impl<R> ZipArchive<R>
Sourcepub fn decompressed_size(&self) -> Option<u128>
pub fn decompressed_size(&self) -> Option<u128>
Total size of the files in the archive, if it can be known. Doesn’t include directories or metadata.
Source§impl<R: Read + Seek> ZipArchive<R>
impl<R: Read + Seek> ZipArchive<R>
Sourcepub fn get_aes_verification_key_and_salt(
&mut self,
file_number: usize,
) -> ZipResult<Option<AesInfo>>
Available on crate feature aes-crypto only.
pub fn get_aes_verification_key_and_salt( &mut self, file_number: usize, ) -> ZipResult<Option<AesInfo>>
aes-crypto only.Returns the verification value and salt for the AES encryption of the file
It fails if the file number is invalid.
§Returns
- None if the file is not encrypted with AES
Sourcepub fn new(reader: R) -> ZipResult<ZipArchive<R>>
pub fn new(reader: R) -> ZipResult<ZipArchive<R>>
Read a ZIP archive, collecting the files it contains.
This uses the central directory record of the ZIP file, and ignores local file headers.
A default Config is used.
Sourcepub fn metadata(&self) -> Arc<ZipArchiveMetadata> ⓘ
pub fn metadata(&self) -> Arc<ZipArchiveMetadata> ⓘ
Get the metadata associated with the ZIP archive.
This can be used with Self::unsafe_new_with_metadata to create a new reader over the
same file without needing to reparse the metadata.
Sourcepub unsafe fn unsafe_new_with_metadata(
reader: R,
metadata: Arc<ZipArchiveMetadata>,
) -> Self
pub unsafe fn unsafe_new_with_metadata( reader: R, metadata: Arc<ZipArchiveMetadata>, ) -> Self
Read a ZIP archive using the given metadata.
This is useful for creating multiple readers over the same file without needing to reparse the metadata.
§Safety
unsafe is used here to indicate that reader and metadata could
potentially be incompatible, and it is left to the user to ensure they are.
§Example
use rayon::prelude::*;
const FILE_NAME: &str = "my_data.zip";
let file = fs::File::open(FILE_NAME).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
let file_names = (0..archive.len())
.into_par_iter()
.map_init({
let metadata = archive.metadata();
move || {
let file = fs::File::open(FILE_NAME).unwrap();
unsafe { zip::ZipArchive::unsafe_new_with_metadata(file, metadata.clone()) }
}},
|archive, i| {
let mut file = archive.by_index(i).unwrap();
file.enclosed_name()
}
)
.filter_map(|name| name)
.collect::<Vec<_>>();Sourcepub fn with_config(config: Config, reader: R) -> ZipResult<ZipArchive<R>>
pub fn with_config(config: Config, reader: R) -> ZipResult<ZipArchive<R>>
Read a ZIP archive providing a read configuration, collecting the files it contains.
This uses the central directory record of the ZIP file, and ignores local file headers.
Sourcepub fn central_directory_start(&self) -> u64
pub fn central_directory_start(&self) -> u64
Get the starting offset of the zip central directory.
Sourcepub fn has_duplicate_names(&self) -> bool
pub fn has_duplicate_names(&self) -> bool
Whether this zip archive contains duplicate file names in its central directory.
Sourcepub fn offset(&self) -> u64
pub fn offset(&self) -> u64
Get the offset from the beginning of the underlying reader that this zip begins at, in bytes.
Normally this value is zero, but if the zip has arbitrary data prepended to it, then this value will be the size of that prepended data.
Sourcepub fn raw_zip64_extensible_data_sector(&self) -> Option<&[u8]>
pub fn raw_zip64_extensible_data_sector(&self) -> Option<&[u8]>
Get the ZIP64 extensible_data of the zip archive, if it is ZIP64.
Sourcepub fn file_names(&self) -> impl Iterator<Item = ZipResult<Cow<'_, str>>>
pub fn file_names(&self) -> impl Iterator<Item = ZipResult<Cow<'_, str>>>
Returns an iterator over all the file and directory names in this archive.
Sourcepub fn file_names_raw(&self) -> impl Iterator<Item = &[u8]>
pub fn file_names_raw(&self) -> impl Iterator<Item = &[u8]>
Returns an iterator over all the raw file and directory names in this archive.
Sourcepub fn has_overlapping_files(&mut self) -> ZipResult<bool>
pub fn has_overlapping_files(&mut self) -> ZipResult<bool>
Returns Ok(true) if any compressed data in this archive belongs to more than one file. This
doesn’t make the archive invalid, but some programs will refuse to decompress it because m
copies of a block that decompresses to length n would occupy m*n bytes in the destination
but require only an archive size of O(m + n) bytes.
This will return true on an archive where zip::write::shallow_copy_file has been used,
unless the file being copied has a compressed size of zero.
Doesn’t count cases where one file entry’s header overlaps with another’s header or data. To include those cases, use ZipArchive::has_overlapping_entries instead.
Sourcepub fn has_overlapping_entries(&mut self) -> ZipResult<bool>
pub fn has_overlapping_entries(&mut self) -> ZipResult<bool>
Returns Ok(true) if any byte in this archive belongs to more than one file entry, including the header. Similar to ZipArchive::has_overlapping_files except that it also checks for header-with-header and header-with-data overlaps. These can be used to increase the number of files in a ZIP archive so that the extracted files’ metadata takes up a larger multiple of the archive’s size (but still a constant multiple, since seeking readers require a central-directory entry for each file and streaming readers process one entry at a time).
This will return true on an archive where zip::write::shallow_copy_file has been used,
even when the file being copied has a size of zero.
Sourcepub fn by_name_decrypt(
&mut self,
name: &str,
password: &[u8],
) -> ZipResult<ZipFile<'_, R>>
pub fn by_name_decrypt( &mut self, name: &str, password: &[u8], ) -> ZipResult<ZipFile<'_, R>>
Search for a file entry by name, decrypt with given password
§Warning
The implementation of the cryptographic algorithms has not gone through a correctness review, and you should assume it is insecure: passwords used with this API may be compromised.
This function sometimes accepts wrong password. This is because the ZIP spec only allows us
to check for a 1/256 chance that the password is correct.
There are many passwords out there that will also pass the validity checks
we are able to perform. This is a weakness of the ZipCrypto algorithm,
due to its fairly primitive approach to cryptography.
Sourcepub fn by_name(&mut self, name: &str) -> ZipResult<ZipFile<'_, R>>
pub fn by_name(&mut self, name: &str) -> ZipResult<ZipFile<'_, R>>
Search for a file entry by name First try to get the index by the name as a binary representation of the name. If not found, try to find the name with the decoded version of the name. This is a fallback for name encoded with CP437.
Sourcepub fn by_name_raw(&mut self, name: &[u8]) -> ZipResult<ZipFile<'_, R>>
pub fn by_name_raw(&mut self, name: &[u8]) -> ZipResult<ZipFile<'_, R>>
Search for a file entry by its raw name bytes, without decoding the name. The running time of this operation doesn’t scale with the number of files in the archive, only with the length of the name being looked up (since it is hashed).
Sourcepub fn index_for_name(&self, name: &str) -> Option<usize>
pub fn index_for_name(&self, name: &str) -> Option<usize>
Get the index of a file entry by name, if it’s present.
First try to get the index by the name as a binary representation of the name. If not found,
try to find the name with the decoded version of the name. This is a fallback for name
encoded with CP437.
If you don’t need to use the fallback, consider using Self::index_for_name_raw which doesn’t
have the fallback.
Sourcepub fn index_for_name_raw(&self, name: &[u8]) -> Option<usize>
pub fn index_for_name_raw(&self, name: &[u8]) -> Option<usize>
Get the index of a file entry by the raw name, if it’s present. The running time of this operation doesn’t scale with the number of files in the archive, only with the length of the name being looked up (since it is hashed).
Sourcepub fn by_index_with_data_descriptor(
&mut self,
index: usize,
) -> ZipResult<ZipFileEntryWithDataDescriptor<'_>>
pub fn by_index_with_data_descriptor( &mut self, index: usize, ) -> ZipResult<ZipFileEntryWithDataDescriptor<'_>>
Get data and the data descriptor of the file
This method will work if the zip is using the data descriptor signature (see 4.3.9.3)
To access the data descriptor, the ZipFileData needs to have a correct compressed_size and
the Data Descriptor should follow the data
Sourcepub fn by_path_decrypt<T: AsRef<Path>>(
&mut self,
path: T,
password: &[u8],
) -> ZipResult<ZipFile<'_, R>>
pub fn by_path_decrypt<T: AsRef<Path>>( &mut self, path: T, password: &[u8], ) -> ZipResult<ZipFile<'_, R>>
Search for a file entry by path, decrypt with given password
§Warning
The implementation of the cryptographic algorithms has not gone through a correctness review, and you should assume it is insecure: passwords used with this API may be compromised.
This function sometimes accepts wrong password. This is because the ZIP spec only allows us
to check for a 1/256 chance that the password is correct.
There are many passwords out there that will also pass the validity checks
we are able to perform. This is a weakness of the ZipCrypto algorithm,
due to its fairly primitive approach to cryptography.
Sourcepub fn by_path<T: AsRef<Path>>(&mut self, path: T) -> ZipResult<ZipFile<'_, R>>
pub fn by_path<T: AsRef<Path>>(&mut self, path: T) -> ZipResult<ZipFile<'_, R>>
Search for a file entry by path
Sourcepub fn index_for_path<T: AsRef<Path>>(&self, path: T) -> Option<usize>
pub fn index_for_path<T: AsRef<Path>>(&self, path: T) -> Option<usize>
Get the index of a file entry by path, if it’s present.
Sourcepub fn name_for_index(&self, index: usize) -> Option<ZipResult<Cow<'_, str>>>
pub fn name_for_index(&self, index: usize) -> Option<ZipResult<Cow<'_, str>>>
Get the name of a file entry, if it’s present.
Sourcepub fn by_name_seek(&mut self, name: &str) -> ZipResult<ZipFileSeek<'_, R>>
pub fn by_name_seek(&mut self, name: &str) -> ZipResult<ZipFileSeek<'_, R>>
Search for a file entry by name and return a seekable object.
Sourcepub fn by_index_seek(&mut self, index: usize) -> ZipResult<ZipFileSeek<'_, R>>
pub fn by_index_seek(&mut self, index: usize) -> ZipResult<ZipFileSeek<'_, R>>
Search for a file entry by index and return a seekable object.
Sourcepub fn by_index_decrypt(
&mut self,
file_number: usize,
password: &[u8],
) -> ZipResult<ZipFile<'_, R>>
pub fn by_index_decrypt( &mut self, file_number: usize, password: &[u8], ) -> ZipResult<ZipFile<'_, R>>
Get a contained file by index, decrypt with given password
§Warning
The implementation of the cryptographic algorithms has not gone through a correctness review, and you should assume it is insecure: passwords used with this API may be compromised.
This function sometimes accepts wrong password. This is because the ZIP spec only allows us
to check for a 1/256 chance that the password is correct.
There are many passwords out there that will also pass the validity checks
we are able to perform. This is a weakness of the ZipCrypto algorithm,
due to its fairly primitive approach to cryptography.
AES HMAC authentication is only performed once the end of the file is read. If any read
method returns an error, the file may have been tampered with. ZipCrypto provides no
authentication at all.
Sourcepub fn by_index(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>>
pub fn by_index(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>>
Get a contained file by index
Sourcepub fn by_index_data(&self, file_number: usize) -> ZipResult<ZipFileEntry<'_>>
pub fn by_index_data(&self, file_number: usize) -> ZipResult<ZipFileEntry<'_>>
Get a contained file by index
Sourcepub fn by_index_raw(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>>
pub fn by_index_raw(&mut self, file_number: usize) -> ZipResult<ZipFile<'_, R>>
Get a contained file by index without decompressing it
Sourcepub fn by_name_with_options<'a>(
&'a mut self,
name: &str,
options: ZipReadOptions<'_>,
) -> ZipResult<ZipFile<'a, R>>
pub fn by_name_with_options<'a>( &'a mut self, name: &str, options: ZipReadOptions<'_>, ) -> ZipResult<ZipFile<'a, R>>
Search for a file entry by name with options.
Sourcepub fn by_index_with_options(
&mut self,
file_number: usize,
options: ZipReadOptions<'_>,
) -> ZipResult<ZipFile<'_, R>>
pub fn by_index_with_options( &mut self, file_number: usize, options: ZipReadOptions<'_>, ) -> ZipResult<ZipFile<'_, R>>
Get a contained file by index with options.
Sourcepub fn validate_header_consistency(&mut self) -> ZipResult<()>
pub fn validate_header_consistency(&mut self) -> ZipResult<()>
Validates that local file headers match their corresponding central directory headers and that no local file headers are missing from the central directory.
Sourcepub fn root_dir(&self, filter: impl RootDirFilter) -> ZipResult<Option<PathBuf>>
pub fn root_dir(&self, filter: impl RootDirFilter) -> ZipResult<Option<PathBuf>>
Find the “root directory” of an archive if it exists, filtering out irrelevant entries when searching.
Our definition of a “root directory” is a single top-level directory that contains the rest of the archive’s entries. This is useful for extracting archives that contain a single top-level directory that you want to “unwrap” and extract directly.
For a sensible default filter, you can use crate::read::root_dir_common_filter.
For a custom filter, see RootDirFilter.
Sourcepub fn into_inner(self) -> R
pub fn into_inner(self) -> R
Unwrap and return the inner reader object
The position of the reader is undefined.
Trait Implementations§
Source§impl<R: Clone> Clone for ZipArchive<R>
impl<R: Clone> Clone for ZipArchive<R>
Auto Trait Implementations§
impl<R> Forget for ZipArchive<R>
impl<R> Freeze for ZipArchive<R>where
R: Freeze,
impl<R> Move for ZipArchive<R>
impl<R> RefUnwindSafe for ZipArchive<R>where
R: RefUnwindSafe,
impl<R> Send for ZipArchive<R>where
R: Send,
impl<R> Sync for ZipArchive<R>where
R: Sync,
impl<R> Unpin for ZipArchive<R>where
R: Unpin,
impl<R> UnsafeUnpin for ZipArchive<R>where
R: UnsafeUnpin,
impl<R> UnwindSafe for ZipArchive<R>where
R: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more