| 1 |
//! Code related to `ZipArchive` |
| 2 |
|
| 3 |
use crate::compression::CompressionMethod; |
| 4 |
use crate::read::config::Config; |
| 5 |
use crate::read::readers::{ZipFileReader, ZipFileSeekReader, make_crypto_reader, make_reader}; |
| 6 |
use crate::read::{ |
| 7 |
ArchiveOffset, CentralDirectoryInfo, RootDirFilter, ZipFile, ZipFileSeek, ZipReadOptions, |
| 8 |
central_header_to_zip_file, |
| 9 |
}; |
| 10 |
use crate::result::{ZipError, ZipResult}; |
| 11 |
use crate::spec; |
| 12 |
use crate::types::ZipFileData; |
| 13 |
use crate::unstable::path_to_string; |
| 14 |
use core::ops::Range; |
| 15 |
use indexmap::IndexMap; |
| 16 |
use std::borrow::Cow; |
| 17 |
use std::io::{Read, Seek, SeekFrom}; |
| 18 |
use std::path::{Path, PathBuf}; |
| 19 |
use std::sync::Arc; |
| 20 |
/// Immutable metadata about a `ZipArchive`. |
| 21 |
#[derive(Debug)] |
| 22 |
pub struct ZipArchiveMetadata { |
| 23 |
pub(crate) files: IndexMap<Box<[u8]>, ZipFileData>, |
| 24 |
pub(crate) offset: u64, |
| 25 |
pub(crate) dir_start: u64, |
| 26 |
// This isn't yet used anywhere, but it is here for use cases in the future. |
| 27 |
#[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)] |
| 34 |
pub(crate) struct SharedBuilder { |
| 35 |
pub(crate) files: Vec<super::ZipFileData>, |
| 36 |
pub(super) offset: u64, |
| 37 |
pub(super) dir_start: u64, |
| 38 |
// This isn't yet used anywhere, but it is here for use cases in the future. |
| 39 |
#[allow(dead_code)] |
| 40 |
pub(super) config: super::Config, |
| 41 |
} |
| 42 |
|
| 43 |
impl 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 |
/// ZIP archive reader |
| 65 |
/// |
| 66 |
/// At the moment, this type is cheap to clone if this is the case for the |
| 67 |
/// reader it uses. However, this is not guaranteed by this crate and it may |
| 68 |
/// change in the future. |
| 69 |
/// |
| 70 |
/// ``` |
| 71 |
/// use std::io::{Read, Seek}; |
| 72 |
/// fn list_zip_contents(reader: impl Read + Seek) -> zip::result::ZipResult<()> { |
| 73 |
/// let mut zip = zip::ZipArchive::new(reader)?; |
| 74 |
/// |
| 75 |
/// for i in 0..zip.len() { |
| 76 |
/// let mut file = zip.by_index(i)?; |
| 77 |
/// println!("Filename: {}", file.name()); |
| 78 |
/// std::io::copy(&mut file, &mut std::io::stdout())?; |
| 79 |
/// } |
| 80 |
/// |
| 81 |
/// Ok(()) |
| 82 |
/// } |
| 83 |
/// ``` |
| 84 |
#[derive(Clone, Debug)] |
| 85 |
pub struct ZipArchive<R> { |
| 86 |
pub(super) reader: R, |
| 87 |
pub(super) shared: Arc<ZipArchiveMetadata>, |
| 88 |
} |
| 89 |
|
| 90 |
impl<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 |
/// Total size of the files in the archive, if it can be known. Doesn't include directories or |
| 116 |
/// metadata. |
| 117 |
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 |
|
| 129 |
impl<R: Read + Seek> ZipArchive<R> { |
| 130 |
/// Get the directory start offset and number of files. This is done in a |
| 131 |
/// separate function to ease the control flow design. |
| 132 |
pub(crate) fn get_metadata(config: Config, reader: &mut R) -> ZipResult<ZipArchiveMetadata> { |
| 133 |
// End of the probed region, initially set to the end of the file |
| 134 |
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 |
// Find the EOCD and possibly EOCD64 entries and determine the archive offset. |
| 140 |
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 the previous error first (if there is) |
| 149 |
return Err(last_err.unwrap_or(e)); |
| 150 |
} |
| 151 |
}; |
| 152 |
|
| 153 |
// Turn EOCD into internal representation. |
| 154 |
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 |
// Something went wrong while decoding the cde, try to find a new one |
| 172 |
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 |
// If the parsed number of files is greater than the offset then |
| 183 |
// something fishy is going on and we shouldn't trust number_of_files. |
| 184 |
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 |
/// Returns the verification value and salt for the AES encryption of the file |
| 216 |
/// |
| 217 |
/// It fails if the file number is invalid. |
| 218 |
/// |
| 219 |
/// # Returns |
| 220 |
/// |
| 221 |
/// - None if the file is not encrypted with AES |
| 222 |
#[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 |
/// Read a ZIP archive, collecting the files it contains. |
| 251 |
/// |
| 252 |
/// This uses the central directory record of the ZIP file, and ignores local file headers. |
| 253 |
/// |
| 254 |
/// A default [`Config`] is used. |
| 255 |
pub fn new(reader: R) -> ZipResult<ZipArchive<R>> { |
| 256 |
Self::with_config(Config::default(), reader) |
| 257 |
} |
| 258 |
|
| 259 |
/// Get the metadata associated with the ZIP archive. |
| 260 |
/// |
| 261 |
/// This can be used with [`Self::unsafe_new_with_metadata`] to create a new reader over the |
| 262 |
/// same file without needing to reparse the metadata. |
| 263 |
pub fn metadata(&self) -> Arc<ZipArchiveMetadata> { |
| 264 |
self.shared.clone() |
| 265 |
} |
| 266 |
|
| 267 |
/// Read a ZIP archive using the given `metadata`. |
| 268 |
/// |
| 269 |
/// This is useful for creating multiple readers over the same file without |
| 270 |
/// needing to reparse the metadata. |
| 271 |
/// |
| 272 |
/// # Safety |
| 273 |
/// `unsafe` is used here to indicate that `reader` and `metadata` could |
| 274 |
/// potentially be incompatible, and it is left to the user to ensure they are. |
| 275 |
/// |
| 276 |
/// # Example |
| 277 |
/// |
| 278 |
/// ```no_run |
| 279 |
/// # use std::fs; |
| 280 |
/// use rayon::prelude::*; |
| 281 |
/// |
| 282 |
/// const FILE_NAME: &str = "my_data.zip"; |
| 283 |
/// |
| 284 |
/// let file = fs::File::open(FILE_NAME).unwrap(); |
| 285 |
/// let mut archive = zip::ZipArchive::new(file).unwrap(); |
| 286 |
/// |
| 287 |
/// let file_names = (0..archive.len()) |
| 288 |
/// .into_par_iter() |
| 289 |
/// .map_init({ |
| 290 |
/// let metadata = archive.metadata().clone(); |
| 291 |
/// move || { |
| 292 |
/// let file = fs::File::open(FILE_NAME).unwrap(); |
| 293 |
/// unsafe { zip::ZipArchive::unsafe_new_with_metadata(file, metadata.clone()) } |
| 294 |
/// }}, |
| 295 |
/// |archive, i| { |
| 296 |
/// let mut file = archive.by_index(i).unwrap(); |
| 297 |
/// file.enclosed_name() |
| 298 |
/// } |
| 299 |
/// ) |
| 300 |
/// .filter_map(|name| name) |
| 301 |
/// .collect::<Vec<_>>(); |
| 302 |
/// ``` |
| 303 |
pub unsafe fn unsafe_new_with_metadata(reader: R, metadata: Arc<ZipArchiveMetadata>) -> Self { |
| 304 |
Self { |
| 305 |
reader, |
| 306 |
shared: metadata, |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
/// Read a ZIP archive providing a read configuration, collecting the files it contains. |
| 311 |
/// |
| 312 |
/// This uses the central directory record of the ZIP file, and ignores local file headers. |
| 313 |
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 |
/// Number of files contained in this zip. |
| 323 |
pub fn len(&self) -> usize { |
| 324 |
self.shared.files.len() |
| 325 |
} |
| 326 |
|
| 327 |
/// Get the starting offset of the zip central directory. |
| 328 |
pub fn central_directory_start(&self) -> u64 { |
| 329 |
self.shared.dir_start |
| 330 |
} |
| 331 |
|
| 332 |
/// Whether this zip archive contains no files |
| 333 |
pub fn is_empty(&self) -> bool { |
| 334 |
self.len() == 0 |
| 335 |
} |
| 336 |
|
| 337 |
/// Get the offset from the beginning of the underlying reader that this zip begins at, in bytes. |
| 338 |
/// |
| 339 |
/// Normally this value is zero, but if the zip has arbitrary data prepended to it, then this value will be the size |
| 340 |
/// of that prepended data. |
| 341 |
pub fn offset(&self) -> u64 { |
| 342 |
self.shared.offset |
| 343 |
} |
| 344 |
|
| 345 |
/// Get the comment of the zip archive. |
| 346 |
pub fn comment(&self) -> &[u8] { |
| 347 |
&self.shared.comment |
| 348 |
} |
| 349 |
|
| 350 |
/// Get the ZIP64 comment of the zip archive, if it is ZIP64. |
| 351 |
#[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 |
// no-op since deprecated |
| 356 |
None |
| 357 |
} |
| 358 |
|
| 359 |
/// Get the ZIP64 extensible_data of the zip archive, if it is ZIP64. |
| 360 |
pub fn raw_zip64_extensible_data_sector(&self) -> Option<&[u8]> { |
| 361 |
self.shared.zip64_extensible_data_sector.as_deref() |
| 362 |
} |
| 363 |
|
| 364 |
/// Returns an iterator over all the file and directory names in this archive. |
| 365 |
pub fn file_names(&self) -> impl Iterator<Item = &str> { |
| 366 |
self.shared.files.values().map(|f| f.file_name.as_ref()) |
| 367 |
} |
| 368 |
|
| 369 |
/// Returns Ok(true) if any compressed data in this archive belongs to more than one file. This |
| 370 |
/// doesn't make the archive invalid, but some programs will refuse to decompress it because the |
| 371 |
/// copies would take up space independently in the destination. |
| 372 |
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 |
/// Search for a file entry by name, decrypt with given password |
| 392 |
/// |
| 393 |
/// # Warning |
| 394 |
/// |
| 395 |
/// The implementation of the cryptographic algorithms has not |
| 396 |
/// gone through a correctness review, and you should assume it is insecure: |
| 397 |
/// passwords used with this API may be compromised. |
| 398 |
/// |
| 399 |
/// This function sometimes accepts wrong password. This is because the ZIP spec only allows us |
| 400 |
/// to check for a 1/256 chance that the password is correct. |
| 401 |
/// There are many passwords out there that will also pass the validity checks |
| 402 |
/// we are able to perform. This is a weakness of the `ZipCrypto` algorithm, |
| 403 |
/// due to its fairly primitive approach to cryptography. |
| 404 |
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 |
/// Search for a file entry by name |
| 409 |
pub fn by_name(&mut self, name: &str) -> ZipResult<ZipFile<'_, R>> { |
| 410 |
self.by_name_with_optional_password(name, None) |
| 411 |
} |
| 412 |
|
| 413 |
/// Get the index of a file entry by name, if it's present. |
| 414 |
#[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 |
/// Search for a file entry by path, decrypt with given password |
| 420 |
/// |
| 421 |
/// # Warning |
| 422 |
/// |
| 423 |
/// The implementation of the cryptographic algorithms has not |
| 424 |
/// gone through a correctness review, and you should assume it is insecure: |
| 425 |
/// passwords used with this API may be compromised. |
| 426 |
/// |
| 427 |
/// This function sometimes accepts wrong password. This is because the ZIP spec only allows us |
| 428 |
/// to check for a 1/256 chance that the password is correct. |
| 429 |
/// There are many passwords out there that will also pass the validity checks |
| 430 |
/// we are able to perform. This is a weakness of the `ZipCrypto` algorithm, |
| 431 |
/// due to its fairly primitive approach to cryptography. |
| 432 |
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 |
/// Search for a file entry by path |
| 445 |
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 |
/// Get the index of a file entry by path, if it's present. |
| 452 |
#[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 |
/// Get the name of a file entry, if it's present. |
| 459 |
#[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 |
/// Search for a file entry by name and return a seekable object. |
| 468 |
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 |
/// Search for a file entry by index and return a seekable object. |
| 473 |
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 |
/// Get a contained file by index, decrypt with given password |
| 509 |
/// |
| 510 |
/// # Warning |
| 511 |
/// |
| 512 |
/// The implementation of the cryptographic algorithms has not |
| 513 |
/// gone through a correctness review, and you should assume it is insecure: |
| 514 |
/// passwords used with this API may be compromised. |
| 515 |
/// |
| 516 |
/// This function sometimes accepts wrong password. This is because the ZIP spec only allows us |
| 517 |
/// to check for a 1/256 chance that the password is correct. |
| 518 |
/// There are many passwords out there that will also pass the validity checks |
| 519 |
/// we are able to perform. This is a weakness of the `ZipCrypto` algorithm, |
| 520 |
/// due to its fairly primitive approach to cryptography. |
| 521 |
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 |
/// Get a contained file by index |
| 530 |
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 |
/// Get a contained file by index without decompressing it |
| 535 |
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 |
/// Get a contained file by index with options. |
| 549 |
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 |
// Always use no password when we're ignoring the encryption flag. |
| 562 |
options.password = None; |
| 563 |
} else { |
| 564 |
// Require and use the password only if the file is encrypted. |
| 565 |
match (options.password, data.encrypted) { |
| 566 |
(None, true) => { |
| 567 |
return Err(ZipError::UnsupportedArchive(ZipError::PASSWORD_REQUIRED)); |
| 568 |
} |
| 569 |
// Password supplied, but none needed! Discard. |
| 570 |
(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 |
/// Find the "root directory" of an archive if it exists, filtering out |
| 599 |
/// irrelevant entries when searching. |
| 600 |
/// |
| 601 |
/// Our definition of a "root directory" is a single top-level directory |
| 602 |
/// that contains the rest of the archive's entries. This is useful for |
| 603 |
/// extracting archives that contain a single top-level directory that |
| 604 |
/// you want to "unwrap" and extract directly. |
| 605 |
/// |
| 606 |
/// For a sensible default filter, you can use [`root_dir_common_filter`]. |
| 607 |
/// For a custom filter, see [`RootDirFilter`]. |
| 608 |
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 |
// We've found multiple root directories, |
| 633 |
// abort. |
| 634 |
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 this entry is located at the root of the archive... |
| 648 |
if path.components().count() == 1 { |
| 649 |
if file.is_dir() { |
| 650 |
// If it's a directory, it could be the root directory. |
| 651 |
replace_root_dir!(path); |
| 652 |
} |
| 653 |
// If it's anything else, this archive does not have a |
| 654 |
// root directory. |
| 655 |
return Ok(None); |
| 656 |
} |
| 657 |
|
| 658 |
// Find the root directory for this entry. |
| 659 |
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 |
/// Unwrap and return the inner reader object |
| 671 |
/// |
| 672 |
/// The position of the reader is undefined. |
| 673 |
pub fn into_inner(self) -> R { |
| 674 |
self.reader |
| 675 |
} |
| 676 |
} |
| 677 |
|
| 678 |
#[cfg(test)] |
| 679 |
mod 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 |
// Although we don't allow adding files whose names contain the ZIP64 CDB-end or |
| 800 |
// CDB-end-locator signatures, we still read them when they aren't genuinely ambiguous. |
| 801 |
for file in files { |
| 802 |
ZipArchive::new(Cursor::new(file)).unwrap(); |
| 803 |
} |
| 804 |
} |
| 805 |
|
| 806 |
/// test case to ensure we don't preemptively over allocate based on the |
| 807 |
/// declared number of files in the CDE of an invalid zip when the number of |
| 808 |
/// files declared is more than the alleged offset in the CDE |
| 809 |
#[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 case to ensure we don't preemptively over allocate based on the |
| 821 |
/// declared number of files in the CDE of an invalid zip when the number of |
| 822 |
/// files declared is less than the alleged offset in the CDE |
| 823 |
#[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 |
/// Only on little endian because we cannot use fs with miri CI |
| 877 |
#[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(); // ensures valid UTF-8 |
| 889 |
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 |
// Attempt to read a small portion or all of each file to ensure it's accessible |
| 894 |
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 |
// Get the file entry by ignoring its encryption flag. |
| 918 |
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 |
// The file claims it is encrypted, but it is not. |
| 925 |
assert!(file.encrypted()); |
| 926 |
file.read_to_string(&mut contents).unwrap(); // ensures valid UTF-8 |
| 927 |
assert_eq!(contents, "This file is not encrypted.\n"); |
| 928 |
} |
| 929 |
} |