| 1 |
//! Types for reading ZIP archives |
| 2 |
|
| 3 |
#[cfg(feature = "aes-crypto")] |
| 4 |
use crate::aes::{AesReader, AesReaderValid}; |
| 5 |
use crate::compression::CompressionMethod; |
| 6 |
use crate::cp437::FromCp437; |
| 7 |
use crate::crc32::Crc32Reader; |
| 8 |
use crate::extra_fields::{ExtendedTimestamp, ExtraField}; |
| 9 |
use crate::read::zip_archive::Shared; |
| 10 |
use crate::result::{ZipError, ZipResult}; |
| 11 |
use crate::spec::{self, FixedSizeBlock}; |
| 12 |
use crate::types::{ |
| 13 |
AesMode, AesVendorVersion, DateTime, System, ZipCentralEntryBlock, ZipFileData, |
| 14 |
ZipLocalEntryBlock, |
| 15 |
}; |
| 16 |
use crate::zipcrypto::{ZipCryptoReader, ZipCryptoReaderValid, ZipCryptoValidator}; |
| 17 |
use indexmap::IndexMap; |
| 18 |
use std::borrow::Cow; |
| 19 |
use std::ffi::OsString; |
| 20 |
use std::fs::create_dir_all; |
| 21 |
use std::io::{self, copy, prelude::*, sink}; |
| 22 |
use std::mem; |
| 23 |
use std::ops::Deref; |
| 24 |
use std::path::{Path, PathBuf}; |
| 25 |
use std::sync::{Arc, OnceLock}; |
| 26 |
|
| 27 |
#[cfg(feature = "deflate-flate2")] |
| 28 |
use flate2::read::DeflateDecoder; |
| 29 |
|
| 30 |
#[cfg(feature = "deflate64")] |
| 31 |
use deflate64::Deflate64Decoder; |
| 32 |
|
| 33 |
#[cfg(feature = "bzip2")] |
| 34 |
use bzip2::read::BzDecoder; |
| 35 |
|
| 36 |
#[cfg(feature = "zstd")] |
| 37 |
use zstd::stream::read::Decoder as ZstdDecoder; |
| 38 |
|
| 39 |
mod config; |
| 40 |
|
| 41 |
pub use config::*; |
| 42 |
|
| 43 |
/// Provides high level API for reading from a stream. |
| 44 |
pub(crate) mod stream; |
| 45 |
|
| 46 |
#[cfg(feature = "lzma")] |
| 47 |
pub(crate) mod lzma; |
| 48 |
|
| 49 |
// Put the struct declaration in a private module to convince rustdoc to display ZipArchive nicely |
| 50 |
pub(crate) mod zip_archive { |
| 51 |
use std::sync::Arc; |
| 52 |
|
| 53 |
/// Extract immutable data from `ZipArchive` to make it cheap to clone |
| 54 |
#[derive(Debug)] |
| 55 |
pub(crate) struct Shared { |
| 56 |
pub(crate) files: super::IndexMap<Box<str>, super::ZipFileData>, |
| 57 |
pub(super) offset: u64, |
| 58 |
pub(super) dir_start: u64, |
| 59 |
// This isn't yet used anywhere, but it is here for use cases in the future. |
| 60 |
#[allow(dead_code)] |
| 61 |
pub(super) config: super::Config, |
| 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 |
/// ```no_run |
| 71 |
/// use std::io::prelude::*; |
| 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<Shared>, |
| 88 |
pub(super) comment: Arc<[u8]>, |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
#[cfg(feature = "aes-crypto")] |
| 93 |
use crate::aes::PWD_VERIFY_LENGTH; |
| 94 |
use crate::extra_fields::UnicodeExtraField; |
| 95 |
#[cfg(feature = "lzma")] |
| 96 |
use crate::read::lzma::LzmaDecoder; |
| 97 |
use crate::result::ZipError::{InvalidPassword, UnsupportedArchive}; |
| 98 |
use crate::spec::{is_dir, path_to_string}; |
| 99 |
use crate::types::ffi::S_IFLNK; |
| 100 |
use crate::unstable::LittleEndianReadExt; |
| 101 |
pub use zip_archive::ZipArchive; |
| 102 |
|
| 103 |
#[allow(clippy::large_enum_variant)] |
| 104 |
pub(crate) enum CryptoReader<'a> { |
| 105 |
Plaintext(io::Take<&'a mut dyn Read>), |
| 106 |
ZipCrypto(ZipCryptoReaderValid<io::Take<&'a mut dyn Read>>), |
| 107 |
#[cfg(feature = "aes-crypto")] |
| 108 |
Aes { |
| 109 |
reader: AesReaderValid<io::Take<&'a mut dyn Read>>, |
| 110 |
vendor_version: AesVendorVersion, |
| 111 |
}, |
| 112 |
} |
| 113 |
|
| 114 |
impl<'a> Read for CryptoReader<'a> { |
| 115 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 116 |
match self { |
| 117 |
CryptoReader::Plaintext(r) => r.read(buf), |
| 118 |
CryptoReader::ZipCrypto(r) => r.read(buf), |
| 119 |
#[cfg(feature = "aes-crypto")] |
| 120 |
CryptoReader::Aes { reader: r, .. } => r.read(buf), |
| 121 |
} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
impl<'a> CryptoReader<'a> { |
| 126 |
/// Consumes this decoder, returning the underlying reader. |
| 127 |
pub fn into_inner(self) -> io::Take<&'a mut dyn Read> { |
| 128 |
match self { |
| 129 |
CryptoReader::Plaintext(r) => r, |
| 130 |
CryptoReader::ZipCrypto(r) => r.into_inner(), |
| 131 |
#[cfg(feature = "aes-crypto")] |
| 132 |
CryptoReader::Aes { reader: r, .. } => r.into_inner(), |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
/// Returns `true` if the data is encrypted using AE2. |
| 137 |
pub const fn is_ae2_encrypted(&self) -> bool { |
| 138 |
#[cfg(feature = "aes-crypto")] |
| 139 |
return matches!( |
| 140 |
self, |
| 141 |
CryptoReader::Aes { |
| 142 |
vendor_version: AesVendorVersion::Ae2, |
| 143 |
.. |
| 144 |
} |
| 145 |
); |
| 146 |
#[cfg(not(feature = "aes-crypto"))] |
| 147 |
false |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
pub(crate) enum ZipFileReader<'a> { |
| 152 |
NoReader, |
| 153 |
Raw(io::Take<&'a mut dyn Read>), |
| 154 |
Stored(Crc32Reader<CryptoReader<'a>>), |
| 155 |
#[cfg(feature = "_deflate-any")] |
| 156 |
Deflated(Crc32Reader<DeflateDecoder<CryptoReader<'a>>>), |
| 157 |
#[cfg(feature = "deflate64")] |
| 158 |
Deflate64(Crc32Reader<Deflate64Decoder<io::BufReader<CryptoReader<'a>>>>), |
| 159 |
#[cfg(feature = "bzip2")] |
| 160 |
Bzip2(Crc32Reader<BzDecoder<CryptoReader<'a>>>), |
| 161 |
#[cfg(feature = "zstd")] |
| 162 |
Zstd(Crc32Reader<ZstdDecoder<'a, io::BufReader<CryptoReader<'a>>>>), |
| 163 |
#[cfg(feature = "lzma")] |
| 164 |
Lzma(Crc32Reader<Box<LzmaDecoder<CryptoReader<'a>>>>), |
| 165 |
} |
| 166 |
|
| 167 |
impl<'a> Read for ZipFileReader<'a> { |
| 168 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 169 |
match self { |
| 170 |
ZipFileReader::NoReader => panic!("ZipFileReader was in an invalid state"), |
| 171 |
ZipFileReader::Raw(r) => r.read(buf), |
| 172 |
ZipFileReader::Stored(r) => r.read(buf), |
| 173 |
#[cfg(feature = "_deflate-any")] |
| 174 |
ZipFileReader::Deflated(r) => r.read(buf), |
| 175 |
#[cfg(feature = "deflate64")] |
| 176 |
ZipFileReader::Deflate64(r) => r.read(buf), |
| 177 |
#[cfg(feature = "bzip2")] |
| 178 |
ZipFileReader::Bzip2(r) => r.read(buf), |
| 179 |
#[cfg(feature = "zstd")] |
| 180 |
ZipFileReader::Zstd(r) => r.read(buf), |
| 181 |
#[cfg(feature = "lzma")] |
| 182 |
ZipFileReader::Lzma(r) => r.read(buf), |
| 183 |
} |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
impl<'a> ZipFileReader<'a> { |
| 188 |
/// Consumes this decoder, returning the underlying reader. |
| 189 |
pub fn drain(self) { |
| 190 |
let mut inner = match self { |
| 191 |
ZipFileReader::NoReader => panic!("ZipFileReader was in an invalid state"), |
| 192 |
ZipFileReader::Raw(r) => r, |
| 193 |
ZipFileReader::Stored(r) => r.into_inner().into_inner(), |
| 194 |
#[cfg(feature = "_deflate-any")] |
| 195 |
ZipFileReader::Deflated(r) => r.into_inner().into_inner().into_inner(), |
| 196 |
#[cfg(feature = "deflate64")] |
| 197 |
ZipFileReader::Deflate64(r) => r.into_inner().into_inner().into_inner().into_inner(), |
| 198 |
#[cfg(feature = "bzip2")] |
| 199 |
ZipFileReader::Bzip2(r) => r.into_inner().into_inner().into_inner(), |
| 200 |
#[cfg(feature = "zstd")] |
| 201 |
ZipFileReader::Zstd(r) => r.into_inner().finish().into_inner().into_inner(), |
| 202 |
#[cfg(feature = "lzma")] |
| 203 |
ZipFileReader::Lzma(r) => { |
| 204 |
// Lzma reader owns its buffer rather than mutably borrowing it, so we have to drop |
| 205 |
// it separately |
| 206 |
if let Ok(mut remaining) = r.into_inner().finish() { |
| 207 |
let _ = copy(&mut remaining, &mut sink()); |
| 208 |
} |
| 209 |
return; |
| 210 |
} |
| 211 |
}; |
| 212 |
let _ = copy(&mut inner, &mut sink()); |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
/// A struct for reading a zip file |
| 217 |
pub struct ZipFile<'a> { |
| 218 |
pub(crate) data: Cow<'a, ZipFileData>, |
| 219 |
pub(crate) crypto_reader: Option<CryptoReader<'a>>, |
| 220 |
pub(crate) reader: ZipFileReader<'a>, |
| 221 |
} |
| 222 |
|
| 223 |
pub(crate) fn find_content<'a>( |
| 224 |
data: &ZipFileData, |
| 225 |
reader: &'a mut (impl Read + Seek), |
| 226 |
) -> ZipResult<io::Take<&'a mut dyn Read>> { |
| 227 |
// TODO: use .get_or_try_init() once stabilized to provide a closure returning a Result! |
| 228 |
let data_start = match data.data_start.get() { |
| 229 |
Some(data_start) => *data_start, |
| 230 |
None => { |
| 231 |
// Go to start of data. |
| 232 |
reader.seek(io::SeekFrom::Start(data.header_start))?; |
| 233 |
|
| 234 |
// Parse static-sized fields and check the magic value. |
| 235 |
let block = ZipLocalEntryBlock::parse(reader)?; |
| 236 |
|
| 237 |
// Calculate the end of the local header from the fields we just parsed. |
| 238 |
let variable_fields_len = |
| 239 |
// Each of these fields must be converted to u64 before adding, as the result may |
| 240 |
// easily overflow a u16. |
| 241 |
block.file_name_length as u64 + block.extra_field_length as u64; |
| 242 |
let data_start = data.header_start |
| 243 |
+ mem::size_of::<ZipLocalEntryBlock>() as u64 |
| 244 |
+ variable_fields_len; |
| 245 |
// Set the value so we don't have to read it again. |
| 246 |
match data.data_start.set(data_start) { |
| 247 |
Ok(()) => (), |
| 248 |
// If the value was already set in the meantime, ensure it matches (this is probably |
| 249 |
// unnecessary). |
| 250 |
Err(_) => { |
| 251 |
assert_eq!(*data.data_start.get().unwrap(), data_start); |
| 252 |
} |
| 253 |
} |
| 254 |
data_start |
| 255 |
} |
| 256 |
}; |
| 257 |
|
| 258 |
reader.seek(io::SeekFrom::Start(data_start))?; |
| 259 |
Ok((reader as &mut dyn Read).take(data.compressed_size)) |
| 260 |
} |
| 261 |
|
| 262 |
#[allow(clippy::too_many_arguments)] |
| 263 |
pub(crate) fn make_crypto_reader<'a>( |
| 264 |
compression_method: CompressionMethod, |
| 265 |
crc32: u32, |
| 266 |
mut last_modified_time: Option<DateTime>, |
| 267 |
using_data_descriptor: bool, |
| 268 |
reader: io::Take<&'a mut dyn Read>, |
| 269 |
password: Option<&[u8]>, |
| 270 |
aes_info: Option<(AesMode, AesVendorVersion, CompressionMethod)>, |
| 271 |
#[cfg(feature = "aes-crypto")] compressed_size: u64, |
| 272 |
) -> ZipResult<CryptoReader<'a>> { |
| 273 |
#[allow(deprecated)] |
| 274 |
{ |
| 275 |
if let CompressionMethod::Unsupported(_) = compression_method { |
| 276 |
return unsupported_zip_error("Compression method not supported"); |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
let reader = match (password, aes_info) { |
| 281 |
#[cfg(not(feature = "aes-crypto"))] |
| 282 |
(Some(_), Some(_)) => { |
| 283 |
return Err(ZipError::UnsupportedArchive( |
| 284 |
"AES encrypted files cannot be decrypted without the aes-crypto feature.", |
| 285 |
)) |
| 286 |
} |
| 287 |
#[cfg(feature = "aes-crypto")] |
| 288 |
(Some(password), Some((aes_mode, vendor_version, _))) => CryptoReader::Aes { |
| 289 |
reader: AesReader::new(reader, aes_mode, compressed_size).validate(password)?, |
| 290 |
vendor_version, |
| 291 |
}, |
| 292 |
(Some(password), None) => { |
| 293 |
if !using_data_descriptor { |
| 294 |
last_modified_time = None; |
| 295 |
} |
| 296 |
let validator = if let Some(last_modified_time) = last_modified_time { |
| 297 |
ZipCryptoValidator::InfoZipMsdosTime(last_modified_time.timepart()) |
| 298 |
} else { |
| 299 |
ZipCryptoValidator::PkzipCrc32(crc32) |
| 300 |
}; |
| 301 |
CryptoReader::ZipCrypto(ZipCryptoReader::new(reader, password).validate(validator)?) |
| 302 |
} |
| 303 |
(None, Some(_)) => return Err(InvalidPassword), |
| 304 |
(None, None) => CryptoReader::Plaintext(reader), |
| 305 |
}; |
| 306 |
Ok(reader) |
| 307 |
} |
| 308 |
|
| 309 |
pub(crate) fn make_reader( |
| 310 |
compression_method: CompressionMethod, |
| 311 |
crc32: u32, |
| 312 |
reader: CryptoReader, |
| 313 |
) -> ZipResult<ZipFileReader> { |
| 314 |
let ae2_encrypted = reader.is_ae2_encrypted(); |
| 315 |
|
| 316 |
match compression_method { |
| 317 |
CompressionMethod::Stored => Ok(ZipFileReader::Stored(Crc32Reader::new( |
| 318 |
reader, |
| 319 |
crc32, |
| 320 |
ae2_encrypted, |
| 321 |
))), |
| 322 |
#[cfg(feature = "_deflate-any")] |
| 323 |
CompressionMethod::Deflated => { |
| 324 |
let deflate_reader = DeflateDecoder::new(reader); |
| 325 |
Ok(ZipFileReader::Deflated(Crc32Reader::new( |
| 326 |
deflate_reader, |
| 327 |
crc32, |
| 328 |
ae2_encrypted, |
| 329 |
))) |
| 330 |
} |
| 331 |
#[cfg(feature = "deflate64")] |
| 332 |
CompressionMethod::Deflate64 => { |
| 333 |
let deflate64_reader = Deflate64Decoder::new(reader); |
| 334 |
Ok(ZipFileReader::Deflate64(Crc32Reader::new( |
| 335 |
deflate64_reader, |
| 336 |
crc32, |
| 337 |
ae2_encrypted, |
| 338 |
))) |
| 339 |
} |
| 340 |
#[cfg(feature = "bzip2")] |
| 341 |
CompressionMethod::Bzip2 => { |
| 342 |
let bzip2_reader = BzDecoder::new(reader); |
| 343 |
Ok(ZipFileReader::Bzip2(Crc32Reader::new( |
| 344 |
bzip2_reader, |
| 345 |
crc32, |
| 346 |
ae2_encrypted, |
| 347 |
))) |
| 348 |
} |
| 349 |
#[cfg(feature = "zstd")] |
| 350 |
CompressionMethod::Zstd => { |
| 351 |
let zstd_reader = ZstdDecoder::new(reader).unwrap(); |
| 352 |
Ok(ZipFileReader::Zstd(Crc32Reader::new( |
| 353 |
zstd_reader, |
| 354 |
crc32, |
| 355 |
ae2_encrypted, |
| 356 |
))) |
| 357 |
} |
| 358 |
#[cfg(feature = "lzma")] |
| 359 |
CompressionMethod::Lzma => { |
| 360 |
let reader = LzmaDecoder::new(reader); |
| 361 |
Ok(ZipFileReader::Lzma(Crc32Reader::new( |
| 362 |
Box::new(reader), |
| 363 |
crc32, |
| 364 |
ae2_encrypted, |
| 365 |
))) |
| 366 |
} |
| 367 |
_ => Err(UnsupportedArchive("Compression method not supported")), |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
#[derive(Debug)] |
| 372 |
pub(crate) struct CentralDirectoryInfo { |
| 373 |
pub(crate) archive_offset: u64, |
| 374 |
pub(crate) directory_start: u64, |
| 375 |
pub(crate) number_of_files: usize, |
| 376 |
pub(crate) disk_number: u32, |
| 377 |
pub(crate) disk_with_central_directory: u32, |
| 378 |
} |
| 379 |
|
| 380 |
impl<R> ZipArchive<R> { |
| 381 |
pub(crate) fn from_finalized_writer( |
| 382 |
files: IndexMap<Box<str>, ZipFileData>, |
| 383 |
comment: Box<[u8]>, |
| 384 |
reader: R, |
| 385 |
central_start: u64, |
| 386 |
) -> ZipResult<Self> { |
| 387 |
let initial_offset = match files.first() { |
| 388 |
Some((_, file)) => file.header_start, |
| 389 |
None => central_start, |
| 390 |
}; |
| 391 |
let shared = Arc::new(zip_archive::Shared { |
| 392 |
files, |
| 393 |
offset: initial_offset, |
| 394 |
dir_start: central_start, |
| 395 |
config: Config { |
| 396 |
archive_offset: ArchiveOffset::Known(initial_offset), |
| 397 |
}, |
| 398 |
}); |
| 399 |
Ok(Self { |
| 400 |
reader, |
| 401 |
shared, |
| 402 |
comment: comment.into(), |
| 403 |
}) |
| 404 |
} |
| 405 |
|
| 406 |
/// Total size of the files in the archive, if it can be known. Doesn't include directories or |
| 407 |
/// metadata. |
| 408 |
pub fn decompressed_size(&self) -> Option<u128> { |
| 409 |
let mut total = 0u128; |
| 410 |
for file in self.shared.files.values() { |
| 411 |
if file.using_data_descriptor { |
| 412 |
return None; |
| 413 |
} |
| 414 |
total = total.checked_add(file.uncompressed_size as u128)?; |
| 415 |
} |
| 416 |
Some(total) |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
impl<R: Read + Seek> ZipArchive<R> { |
| 421 |
pub(crate) fn merge_contents<W: Write + io::Seek>( |
| 422 |
&mut self, |
| 423 |
mut w: W, |
| 424 |
) -> ZipResult<IndexMap<Box<str>, ZipFileData>> { |
| 425 |
if self.shared.files.is_empty() { |
| 426 |
return Ok(IndexMap::new()); |
| 427 |
} |
| 428 |
let mut new_files = self.shared.files.clone(); |
| 429 |
/* The first file header will probably start at the beginning of the file, but zip doesn't |
| 430 |
* enforce that, and executable zips like PEX files will have a shebang line so will |
| 431 |
* definitely be greater than 0. |
| 432 |
* |
| 433 |
* assert_eq!(0, new_files[0].header_start); // Avoid this. |
| 434 |
*/ |
| 435 |
|
| 436 |
let new_initial_header_start = w.stream_position()?; |
| 437 |
/* Push back file header starts for all entries in the covered files. */ |
| 438 |
new_files.values_mut().try_for_each(|f| { |
| 439 |
/* This is probably the only really important thing to change. */ |
| 440 |
f.header_start = f.header_start.checked_add(new_initial_header_start).ok_or( |
| 441 |
ZipError::InvalidArchive("new header start from merge would have been too large"), |
| 442 |
)?; |
| 443 |
/* This is only ever used internally to cache metadata lookups (it's not part of the |
| 444 |
* zip spec), and 0 is the sentinel value. */ |
| 445 |
f.central_header_start = 0; |
| 446 |
/* This is an atomic variable so it can be updated from another thread in the |
| 447 |
* implementation (which is good!). */ |
| 448 |
if let Some(old_data_start) = f.data_start.take() { |
| 449 |
let new_data_start = old_data_start.checked_add(new_initial_header_start).ok_or( |
| 450 |
ZipError::InvalidArchive("new data start from merge would have been too large"), |
| 451 |
)?; |
| 452 |
f.data_start.get_or_init(|| new_data_start); |
| 453 |
} |
| 454 |
Ok::<_, ZipError>(()) |
| 455 |
})?; |
| 456 |
|
| 457 |
/* Rewind to the beginning of the file. |
| 458 |
* |
| 459 |
* NB: we *could* decide to start copying from new_files[0].header_start instead, which |
| 460 |
* would avoid copying over e.g. any pex shebangs or other file contents that start before |
| 461 |
* the first zip file entry. However, zip files actually shouldn't care about garbage data |
| 462 |
* in *between* real entries, since the central directory header records the correct start |
| 463 |
* location of each, and keeping track of that math is more complicated logic that will only |
| 464 |
* rarely be used, since most zips that get merged together are likely to be produced |
| 465 |
* specifically for that purpose (and therefore are unlikely to have a shebang or other |
| 466 |
* preface). Finally, this preserves any data that might actually be useful. |
| 467 |
*/ |
| 468 |
self.reader.rewind()?; |
| 469 |
/* Find the end of the file data. */ |
| 470 |
let length_to_read = self.shared.dir_start; |
| 471 |
/* Produce a Read that reads bytes up until the start of the central directory header. |
| 472 |
* This "as &mut dyn Read" trick is used elsewhere to avoid having to clone the underlying |
| 473 |
* handle, which it really shouldn't need to anyway. */ |
| 474 |
let mut limited_raw = (&mut self.reader as &mut dyn Read).take(length_to_read); |
| 475 |
/* Copy over file data from source archive directly. */ |
| 476 |
io::copy(&mut limited_raw, &mut w)?; |
| 477 |
|
| 478 |
/* Return the files we've just written to the data stream. */ |
| 479 |
Ok(new_files) |
| 480 |
} |
| 481 |
|
| 482 |
fn get_directory_info_zip32( |
| 483 |
config: &Config, |
| 484 |
reader: &mut R, |
| 485 |
footer: &spec::Zip32CentralDirectoryEnd, |
| 486 |
cde_start_pos: u64, |
| 487 |
) -> ZipResult<CentralDirectoryInfo> { |
| 488 |
let archive_offset = match config.archive_offset { |
| 489 |
ArchiveOffset::Known(n) => n, |
| 490 |
ArchiveOffset::FromCentralDirectory | ArchiveOffset::Detect => { |
| 491 |
// Some zip files have data prepended to them, resulting in the |
| 492 |
// offsets all being too small. Get the amount of error by comparing |
| 493 |
// the actual file position we found the CDE at with the offset |
| 494 |
// recorded in the CDE. |
| 495 |
let mut offset = cde_start_pos |
| 496 |
.checked_sub(footer.central_directory_size as u64) |
| 497 |
.and_then(|x| x.checked_sub(footer.central_directory_offset as u64)) |
| 498 |
.ok_or(ZipError::InvalidArchive( |
| 499 |
"Invalid central directory size or offset", |
| 500 |
))?; |
| 501 |
|
| 502 |
if config.archive_offset == ArchiveOffset::Detect { |
| 503 |
// Check whether the archive offset makes sense by peeking at the directory start. If it |
| 504 |
// doesn't, fall back to using no archive offset. This supports zips with the central |
| 505 |
// directory entries somewhere other than directly preceding the end of central directory. |
| 506 |
reader.seek(io::SeekFrom::Start( |
| 507 |
offset + footer.central_directory_offset as u64, |
| 508 |
))?; |
| 509 |
let mut buf = [0; 4]; |
| 510 |
reader.read_exact(&mut buf)?; |
| 511 |
if spec::Magic::from_le_bytes(buf) |
| 512 |
!= spec::Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE |
| 513 |
{ |
| 514 |
offset = 0; |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
offset |
| 519 |
} |
| 520 |
}; |
| 521 |
|
| 522 |
let directory_start = footer.central_directory_offset as u64 + archive_offset; |
| 523 |
let number_of_files = footer.number_of_files_on_this_disk as usize; |
| 524 |
Ok(CentralDirectoryInfo { |
| 525 |
archive_offset, |
| 526 |
directory_start, |
| 527 |
number_of_files, |
| 528 |
disk_number: footer.disk_number as u32, |
| 529 |
disk_with_central_directory: footer.disk_with_central_directory as u32, |
| 530 |
}) |
| 531 |
} |
| 532 |
|
| 533 |
const fn zip64_cde_len() -> usize { |
| 534 |
mem::size_of::<spec::Zip64CentralDirectoryEnd>() |
| 535 |
+ mem::size_of::<spec::Zip64CentralDirectoryEndLocator>() |
| 536 |
} |
| 537 |
|
| 538 |
const fn order_lower_upper_bounds(a: u64, b: u64) -> (u64, u64) { |
| 539 |
if a > b { |
| 540 |
(b, a) |
| 541 |
} else { |
| 542 |
(a, b) |
| 543 |
} |
| 544 |
} |
| 545 |
|
| 546 |
fn get_directory_info_zip64( |
| 547 |
config: &Config, |
| 548 |
reader: &mut R, |
| 549 |
footer: &spec::Zip32CentralDirectoryEnd, |
| 550 |
cde_start_pos: u64, |
| 551 |
) -> ZipResult<Vec<ZipResult<CentralDirectoryInfo>>> { |
| 552 |
// See if there's a ZIP64 footer. The ZIP64 locator if present will |
| 553 |
// have its signature 20 bytes in front of the standard footer. The |
| 554 |
// standard footer, in turn, is 22+N bytes large, where N is the |
| 555 |
// comment length. Therefore: |
| 556 |
/* TODO: compute this from constant sizes and offsets! */ |
| 557 |
reader.seek(io::SeekFrom::End( |
| 558 |
-(20 + 22 + footer.zip_file_comment.len() as i64), |
| 559 |
))?; |
| 560 |
let locator64 = spec::Zip64CentralDirectoryEndLocator::parse(reader)?; |
| 561 |
|
| 562 |
// We need to reassess `archive_offset`. We know where the ZIP64 |
| 563 |
// central-directory-end structure *should* be, but unfortunately we |
| 564 |
// don't know how to precisely relate that location to our current |
| 565 |
// actual offset in the file, since there may be junk at its |
| 566 |
// beginning. Therefore we need to perform another search, as in |
| 567 |
// read::Zip32CentralDirectoryEnd::find_and_parse, except now we search |
| 568 |
// forward. There may be multiple results because of Zip64 central-directory signatures in |
| 569 |
// ZIP comment data. |
| 570 |
|
| 571 |
let search_upper_bound = cde_start_pos |
| 572 |
.checked_sub(Self::zip64_cde_len() as u64) |
| 573 |
.ok_or(ZipError::InvalidArchive( |
| 574 |
"File cannot contain ZIP64 central directory end", |
| 575 |
))?; |
| 576 |
|
| 577 |
let (lower, upper) = Self::order_lower_upper_bounds( |
| 578 |
locator64.end_of_central_directory_offset, |
| 579 |
search_upper_bound, |
| 580 |
); |
| 581 |
|
| 582 |
let search_results = spec::Zip64CentralDirectoryEnd::find_and_parse(reader, lower, upper)?; |
| 583 |
let results: Vec<ZipResult<CentralDirectoryInfo>> = |
| 584 |
search_results.into_iter().map(|(footer64, archive_offset)| { |
| 585 |
let archive_offset = match config.archive_offset { |
| 586 |
ArchiveOffset::Known(n) => n, |
| 587 |
ArchiveOffset::FromCentralDirectory => archive_offset, |
| 588 |
ArchiveOffset::Detect => { |
| 589 |
archive_offset.checked_add(footer64.central_directory_offset) |
| 590 |
.and_then(|start| { |
| 591 |
// Check whether the archive offset makes sense by peeking at the directory start. |
| 592 |
// |
| 593 |
// If any errors occur or no header signature is found, fall back to no offset to see if that works. |
| 594 |
reader.seek(io::SeekFrom::Start(start)).ok()?; |
| 595 |
let mut buf = [0; 4]; |
| 596 |
reader.read_exact(&mut buf).ok()?; |
| 597 |
if spec::Magic::from_le_bytes(buf) != spec::Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE { |
| 598 |
None |
| 599 |
} else { |
| 600 |
Some(archive_offset) |
| 601 |
} |
| 602 |
}) |
| 603 |
.unwrap_or(0) |
| 604 |
} |
| 605 |
}; |
| 606 |
let directory_start = footer64 |
| 607 |
.central_directory_offset |
| 608 |
.checked_add(archive_offset) |
| 609 |
.ok_or(ZipError::InvalidArchive( |
| 610 |
"Invalid central directory size or offset", |
| 611 |
))?; |
| 612 |
if directory_start > search_upper_bound { |
| 613 |
Err(ZipError::InvalidArchive( |
| 614 |
"Invalid central directory size or offset", |
| 615 |
)) |
| 616 |
} else if footer64.number_of_files_on_this_disk > footer64.number_of_files { |
| 617 |
Err(ZipError::InvalidArchive( |
| 618 |
"ZIP64 footer indicates more files on this disk than in the whole archive", |
| 619 |
)) |
| 620 |
} else if footer64.version_needed_to_extract > footer64.version_made_by { |
| 621 |
Err(ZipError::InvalidArchive( |
| 622 |
"ZIP64 footer indicates a new version is needed to extract this archive than the \ |
| 623 |
version that wrote it", |
| 624 |
)) |
| 625 |
} else { |
| 626 |
Ok(CentralDirectoryInfo { |
| 627 |
archive_offset, |
| 628 |
directory_start, |
| 629 |
number_of_files: footer64.number_of_files as usize, |
| 630 |
disk_number: footer64.disk_number, |
| 631 |
disk_with_central_directory: footer64.disk_with_central_directory, |
| 632 |
}) |
| 633 |
} |
| 634 |
}).collect(); |
| 635 |
Ok(results) |
| 636 |
} |
| 637 |
|
| 638 |
/// Get the directory start offset and number of files. This is done in a |
| 639 |
/// separate function to ease the control flow design. |
| 640 |
pub(crate) fn get_metadata( |
| 641 |
config: Config, |
| 642 |
reader: &mut R, |
| 643 |
footer: &spec::Zip32CentralDirectoryEnd, |
| 644 |
cde_start_pos: u64, |
| 645 |
) -> ZipResult<Shared> { |
| 646 |
// Check if file has a zip64 footer |
| 647 |
let mut results = Self::get_directory_info_zip64(&config, reader, footer, cde_start_pos) |
| 648 |
.unwrap_or_else(|e| vec![Err(e)]); |
| 649 |
let zip32_result = Self::get_directory_info_zip32(&config, reader, footer, cde_start_pos); |
| 650 |
let mut invalid_errors = Vec::new(); |
| 651 |
let mut unsupported_errors = Vec::new(); |
| 652 |
let mut ok_results = Vec::new(); |
| 653 |
results.iter_mut().for_each(|result| { |
| 654 |
if let Ok(central_dir) = result { |
| 655 |
if let Ok(zip32_central_dir) = &zip32_result { |
| 656 |
// Both zip32 and zip64 footers exist, so check if the zip64 footer is valid; if not, try zip32 |
| 657 |
if central_dir.number_of_files != zip32_central_dir.number_of_files |
| 658 |
&& zip32_central_dir.number_of_files != u16::MAX as usize |
| 659 |
{ |
| 660 |
*result = Err(ZipError::InvalidArchive( |
| 661 |
"ZIP32 and ZIP64 file counts don't match", |
| 662 |
)); |
| 663 |
return; |
| 664 |
} |
| 665 |
if central_dir.disk_number != zip32_central_dir.disk_number |
| 666 |
&& zip32_central_dir.disk_number != u16::MAX as u32 |
| 667 |
{ |
| 668 |
*result = Err(ZipError::InvalidArchive( |
| 669 |
"ZIP32 and ZIP64 disk numbers don't match", |
| 670 |
)); |
| 671 |
return; |
| 672 |
} |
| 673 |
if central_dir.disk_with_central_directory |
| 674 |
!= zip32_central_dir.disk_with_central_directory |
| 675 |
&& zip32_central_dir.disk_with_central_directory != u16::MAX as u32 |
| 676 |
{ |
| 677 |
*result = Err(ZipError::InvalidArchive( |
| 678 |
"ZIP32 and ZIP64 last-disk numbers don't match", |
| 679 |
)); |
| 680 |
} |
| 681 |
} |
| 682 |
} |
| 683 |
}); |
| 684 |
results.push(zip32_result); |
| 685 |
results |
| 686 |
.into_iter() |
| 687 |
.map(|result| { |
| 688 |
result.and_then(|dir_info| { |
| 689 |
// If the parsed number of files is greater than the offset then |
| 690 |
// something fishy is going on and we shouldn't trust number_of_files. |
| 691 |
let file_capacity = |
| 692 |
if dir_info.number_of_files > dir_info.directory_start as usize { |
| 693 |
0 |
| 694 |
} else { |
| 695 |
dir_info.number_of_files |
| 696 |
}; |
| 697 |
let mut files = IndexMap::with_capacity(file_capacity); |
| 698 |
reader.seek(io::SeekFrom::Start(dir_info.directory_start))?; |
| 699 |
for _ in 0..dir_info.number_of_files { |
| 700 |
let file = central_header_to_zip_file(reader, dir_info.archive_offset)?; |
| 701 |
files.insert(file.file_name.clone(), file); |
| 702 |
} |
| 703 |
if dir_info.disk_number != dir_info.disk_with_central_directory { |
| 704 |
unsupported_zip_error("Support for multi-disk files is not implemented") |
| 705 |
} else { |
| 706 |
Ok(Shared { |
| 707 |
files, |
| 708 |
offset: dir_info.archive_offset, |
| 709 |
dir_start: dir_info.directory_start, |
| 710 |
config, |
| 711 |
}) |
| 712 |
} |
| 713 |
}) |
| 714 |
}) |
| 715 |
.for_each(|result| match result { |
| 716 |
Err(ZipError::UnsupportedArchive(e)) => { |
| 717 |
unsupported_errors.push(ZipError::UnsupportedArchive(e)) |
| 718 |
} |
| 719 |
Err(e) => invalid_errors.push(e), |
| 720 |
Ok(o) => ok_results.push(o), |
| 721 |
}); |
| 722 |
if ok_results.is_empty() { |
| 723 |
return Err(unsupported_errors |
| 724 |
.into_iter() |
| 725 |
.next() |
| 726 |
.unwrap_or_else(|| invalid_errors.into_iter().next().unwrap())); |
| 727 |
} |
| 728 |
let shared = ok_results |
| 729 |
.into_iter() |
| 730 |
.max_by_key(|shared| shared.dir_start) |
| 731 |
.unwrap(); |
| 732 |
reader.seek(io::SeekFrom::Start(shared.dir_start))?; |
| 733 |
Ok(shared) |
| 734 |
} |
| 735 |
|
| 736 |
/// Returns the verification value and salt for the AES encryption of the file |
| 737 |
/// |
| 738 |
/// It fails if the file number is invalid. |
| 739 |
/// |
| 740 |
/// # Returns |
| 741 |
/// |
| 742 |
/// - None if the file is not encrypted with AES |
| 743 |
#[cfg(feature = "aes-crypto")] |
| 744 |
pub fn get_aes_verification_key_and_salt( |
| 745 |
&mut self, |
| 746 |
file_number: usize, |
| 747 |
) -> ZipResult<Option<AesInfo>> { |
| 748 |
let (_, data) = self |
| 749 |
.shared |
| 750 |
.files |
| 751 |
.get_index(file_number) |
| 752 |
.ok_or(ZipError::FileNotFound)?; |
| 753 |
|
| 754 |
let limit_reader = find_content(data, &mut self.reader)?; |
| 755 |
match data.aes_mode { |
| 756 |
None => Ok(None), |
| 757 |
Some((aes_mode, _, _)) => { |
| 758 |
let (verification_value, salt) = |
| 759 |
AesReader::new(limit_reader, aes_mode, data.compressed_size) |
| 760 |
.get_verification_value_and_salt()?; |
| 761 |
let aes_info = AesInfo { |
| 762 |
aes_mode, |
| 763 |
verification_value, |
| 764 |
salt, |
| 765 |
}; |
| 766 |
Ok(Some(aes_info)) |
| 767 |
} |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
/// Read a ZIP archive, collecting the files it contains. |
| 772 |
/// |
| 773 |
/// This uses the central directory record of the ZIP file, and ignores local file headers. |
| 774 |
/// |
| 775 |
/// A default [`Config`] is used. |
| 776 |
pub fn new(reader: R) -> ZipResult<ZipArchive<R>> { |
| 777 |
Self::with_config(Default::default(), reader) |
| 778 |
} |
| 779 |
|
| 780 |
/// Read a ZIP archive providing a read configuration, collecting the files it contains. |
| 781 |
/// |
| 782 |
/// This uses the central directory record of the ZIP file, and ignores local file headers. |
| 783 |
pub fn with_config(config: Config, mut reader: R) -> ZipResult<ZipArchive<R>> { |
| 784 |
let (footer, cde_start_pos) = spec::Zip32CentralDirectoryEnd::find_and_parse(&mut reader)?; |
| 785 |
let shared = Self::get_metadata(config, &mut reader, &footer, cde_start_pos)?; |
| 786 |
Ok(ZipArchive { |
| 787 |
reader, |
| 788 |
shared: shared.into(), |
| 789 |
comment: footer.zip_file_comment.into(), |
| 790 |
}) |
| 791 |
} |
| 792 |
|
| 793 |
/// Extract a Zip archive into a directory, overwriting files if they |
| 794 |
/// already exist. Paths are sanitized with [`ZipFile::enclosed_name`]. |
| 795 |
/// |
| 796 |
/// Extraction is not atomic. If an error is encountered, some of the files |
| 797 |
/// may be left on disk. However, on Unix targets, no newly-created directories with part but |
| 798 |
/// not all of their contents extracted will be readable, writable or usable as process working |
| 799 |
/// directories by any non-root user except you. |
| 800 |
/// |
| 801 |
/// On Unix and Windows, symbolic links are extracted correctly. On other platforms such as |
| 802 |
/// WebAssembly, symbolic links aren't supported, so they're extracted as normal files |
| 803 |
/// containing the target path in UTF-8. |
| 804 |
pub fn extract<P: AsRef<Path>>(&mut self, directory: P) -> ZipResult<()> { |
| 805 |
use std::fs; |
| 806 |
#[cfg(unix)] |
| 807 |
let mut files_by_unix_mode = Vec::new(); |
| 808 |
for i in 0..self.len() { |
| 809 |
let mut file = self.by_index(i)?; |
| 810 |
let filepath = file |
| 811 |
.enclosed_name() |
| 812 |
.ok_or(ZipError::InvalidArchive("Invalid file path"))?; |
| 813 |
|
| 814 |
let outpath = directory.as_ref().join(filepath); |
| 815 |
|
| 816 |
if file.is_dir() { |
| 817 |
Self::make_writable_dir_all(&outpath)?; |
| 818 |
continue; |
| 819 |
} |
| 820 |
let symlink_target = if file.is_symlink() && (cfg!(unix) || cfg!(windows)) { |
| 821 |
let mut target = Vec::with_capacity(file.size() as usize); |
| 822 |
file.read_exact(&mut target)?; |
| 823 |
Some(target) |
| 824 |
} else { |
| 825 |
None |
| 826 |
}; |
| 827 |
drop(file); |
| 828 |
if let Some(p) = outpath.parent() { |
| 829 |
Self::make_writable_dir_all(p)?; |
| 830 |
} |
| 831 |
if let Some(target) = symlink_target { |
| 832 |
#[cfg(unix)] |
| 833 |
{ |
| 834 |
use std::os::unix::ffi::OsStringExt; |
| 835 |
let target = OsString::from_vec(target); |
| 836 |
let target_path = directory.as_ref().join(target); |
| 837 |
std::os::unix::fs::symlink(target_path, outpath.as_path())?; |
| 838 |
} |
| 839 |
#[cfg(windows)] |
| 840 |
{ |
| 841 |
let Ok(target) = String::from_utf8(target) else { |
| 842 |
return Err(ZipError::InvalidArchive("Invalid UTF-8 as symlink target")); |
| 843 |
}; |
| 844 |
let target = target.into_boxed_str(); |
| 845 |
let target_is_dir_from_archive = |
| 846 |
self.shared.files.contains_key(&target) && is_dir(&target); |
| 847 |
let target_path = directory.as_ref().join(OsString::from(target.to_string())); |
| 848 |
let target_is_dir = if target_is_dir_from_archive { |
| 849 |
true |
| 850 |
} else if let Ok(meta) = std::fs::metadata(&target_path) { |
| 851 |
meta.is_dir() |
| 852 |
} else { |
| 853 |
false |
| 854 |
}; |
| 855 |
if target_is_dir { |
| 856 |
std::os::windows::fs::symlink_dir(target_path, outpath.as_path())?; |
| 857 |
} else { |
| 858 |
std::os::windows::fs::symlink_file(target_path, outpath.as_path())?; |
| 859 |
} |
| 860 |
} |
| 861 |
continue; |
| 862 |
} |
| 863 |
let mut file = self.by_index(i)?; |
| 864 |
let mut outfile = fs::File::create(&outpath)?; |
| 865 |
io::copy(&mut file, &mut outfile)?; |
| 866 |
#[cfg(unix)] |
| 867 |
{ |
| 868 |
// Check for real permissions, which we'll set in a second pass |
| 869 |
if let Some(mode) = file.unix_mode() { |
| 870 |
files_by_unix_mode.push((outpath.clone(), mode)); |
| 871 |
} |
| 872 |
} |
| 873 |
} |
| 874 |
#[cfg(unix)] |
| 875 |
{ |
| 876 |
use std::cmp::Reverse; |
| 877 |
use std::os::unix::fs::PermissionsExt; |
| 878 |
|
| 879 |
if files_by_unix_mode.len() > 1 { |
| 880 |
// Ensure we update children's permissions before making a parent unwritable |
| 881 |
files_by_unix_mode.sort_by_key(|(path, _)| Reverse(path.clone())); |
| 882 |
} |
| 883 |
for (path, mode) in files_by_unix_mode.into_iter() { |
| 884 |
fs::set_permissions(&path, fs::Permissions::from_mode(mode))?; |
| 885 |
} |
| 886 |
} |
| 887 |
Ok(()) |
| 888 |
} |
| 889 |
|
| 890 |
fn make_writable_dir_all<T: AsRef<Path>>(outpath: T) -> Result<(), ZipError> { |
| 891 |
create_dir_all(outpath.as_ref())?; |
| 892 |
#[cfg(unix)] |
| 893 |
{ |
| 894 |
// Dirs must be writable until all normal files are extracted |
| 895 |
use std::os::unix::fs::PermissionsExt; |
| 896 |
std::fs::set_permissions( |
| 897 |
outpath.as_ref(), |
| 898 |
std::fs::Permissions::from_mode( |
| 899 |
0o700 | std::fs::metadata(outpath.as_ref())?.permissions().mode(), |
| 900 |
), |
| 901 |
)?; |
| 902 |
} |
| 903 |
Ok(()) |
| 904 |
} |
| 905 |
|
| 906 |
/// Number of files contained in this zip. |
| 907 |
pub fn len(&self) -> usize { |
| 908 |
self.shared.files.len() |
| 909 |
} |
| 910 |
|
| 911 |
/// Whether this zip archive contains no files |
| 912 |
pub fn is_empty(&self) -> bool { |
| 913 |
self.len() == 0 |
| 914 |
} |
| 915 |
|
| 916 |
/// Get the offset from the beginning of the underlying reader that this zip begins at, in bytes. |
| 917 |
/// |
| 918 |
/// Normally this value is zero, but if the zip has arbitrary data prepended to it, then this value will be the size |
| 919 |
/// of that prepended data. |
| 920 |
pub fn offset(&self) -> u64 { |
| 921 |
self.shared.offset |
| 922 |
} |
| 923 |
|
| 924 |
/// Get the comment of the zip archive. |
| 925 |
pub fn comment(&self) -> &[u8] { |
| 926 |
&self.comment |
| 927 |
} |
| 928 |
|
| 929 |
/// Returns an iterator over all the file and directory names in this archive. |
| 930 |
pub fn file_names(&self) -> impl Iterator<Item = &str> { |
| 931 |
self.shared.files.keys().map(|s| s.as_ref()) |
| 932 |
} |
| 933 |
|
| 934 |
/// Search for a file entry by name, decrypt with given password |
| 935 |
/// |
| 936 |
/// # Warning |
| 937 |
/// |
| 938 |
/// The implementation of the cryptographic algorithms has not |
| 939 |
/// gone through a correctness review, and you should assume it is insecure: |
| 940 |
/// passwords used with this API may be compromised. |
| 941 |
/// |
| 942 |
/// This function sometimes accepts wrong password. This is because the ZIP spec only allows us |
| 943 |
/// to check for a 1/256 chance that the password is correct. |
| 944 |
/// There are many passwords out there that will also pass the validity checks |
| 945 |
/// we are able to perform. This is a weakness of the ZipCrypto algorithm, |
| 946 |
/// due to its fairly primitive approach to cryptography. |
| 947 |
pub fn by_name_decrypt(&mut self, name: &str, password: &[u8]) -> ZipResult<ZipFile> { |
| 948 |
self.by_name_with_optional_password(name, Some(password)) |
| 949 |
} |
| 950 |
|
| 951 |
/// Search for a file entry by name |
| 952 |
pub fn by_name(&mut self, name: &str) -> ZipResult<ZipFile> { |
| 953 |
self.by_name_with_optional_password(name, None) |
| 954 |
} |
| 955 |
|
| 956 |
/// Get the index of a file entry by name, if it's present. |
| 957 |
#[inline(always)] |
| 958 |
pub fn index_for_name(&self, name: &str) -> Option<usize> { |
| 959 |
self.shared.files.get_index_of(name) |
| 960 |
} |
| 961 |
|
| 962 |
/// Get the index of a file entry by path, if it's present. |
| 963 |
#[inline(always)] |
| 964 |
pub fn index_for_path<T: AsRef<Path>>(&self, path: T) -> Option<usize> { |
| 965 |
self.index_for_name(&path_to_string(path)) |
| 966 |
} |
| 967 |
|
| 968 |
/// Get the name of a file entry, if it's present. |
| 969 |
#[inline(always)] |
| 970 |
pub fn name_for_index(&self, index: usize) -> Option<&str> { |
| 971 |
self.shared |
| 972 |
.files |
| 973 |
.get_index(index) |
| 974 |
.map(|(name, _)| name.as_ref()) |
| 975 |
} |
| 976 |
|
| 977 |
fn by_name_with_optional_password<'a>( |
| 978 |
&'a mut self, |
| 979 |
name: &str, |
| 980 |
password: Option<&[u8]>, |
| 981 |
) -> ZipResult<ZipFile<'a>> { |
| 982 |
let Some(index) = self.shared.files.get_index_of(name) else { |
| 983 |
return Err(ZipError::FileNotFound); |
| 984 |
}; |
| 985 |
self.by_index_with_optional_password(index, password) |
| 986 |
} |
| 987 |
|
| 988 |
/// Get a contained file by index, decrypt with given password |
| 989 |
/// |
| 990 |
/// # Warning |
| 991 |
/// |
| 992 |
/// The implementation of the cryptographic algorithms has not |
| 993 |
/// gone through a correctness review, and you should assume it is insecure: |
| 994 |
/// passwords used with this API may be compromised. |
| 995 |
/// |
| 996 |
/// This function sometimes accepts wrong password. This is because the ZIP spec only allows us |
| 997 |
/// to check for a 1/256 chance that the password is correct. |
| 998 |
/// There are many passwords out there that will also pass the validity checks |
| 999 |
/// we are able to perform. This is a weakness of the ZipCrypto algorithm, |
| 1000 |
/// due to its fairly primitive approach to cryptography. |
| 1001 |
pub fn by_index_decrypt( |
| 1002 |
&mut self, |
| 1003 |
file_number: usize, |
| 1004 |
password: &[u8], |
| 1005 |
) -> ZipResult<ZipFile<'_>> { |
| 1006 |
self.by_index_with_optional_password(file_number, Some(password)) |
| 1007 |
} |
| 1008 |
|
| 1009 |
/// Get a contained file by index |
| 1010 |
pub fn by_index(&mut self, file_number: usize) -> ZipResult<ZipFile<'_>> { |
| 1011 |
self.by_index_with_optional_password(file_number, None) |
| 1012 |
} |
| 1013 |
|
| 1014 |
/// Get a contained file by index without decompressing it |
| 1015 |
pub fn by_index_raw(&mut self, file_number: usize) -> ZipResult<ZipFile<'_>> { |
| 1016 |
let reader = &mut self.reader; |
| 1017 |
let (_, data) = self |
| 1018 |
.shared |
| 1019 |
.files |
| 1020 |
.get_index(file_number) |
| 1021 |
.ok_or(ZipError::FileNotFound)?; |
| 1022 |
Ok(ZipFile { |
| 1023 |
crypto_reader: None, |
| 1024 |
reader: ZipFileReader::Raw(find_content(data, reader)?), |
| 1025 |
data: Cow::Borrowed(data), |
| 1026 |
}) |
| 1027 |
} |
| 1028 |
|
| 1029 |
fn by_index_with_optional_password( |
| 1030 |
&mut self, |
| 1031 |
file_number: usize, |
| 1032 |
mut password: Option<&[u8]>, |
| 1033 |
) -> ZipResult<ZipFile<'_>> { |
| 1034 |
let (_, data) = self |
| 1035 |
.shared |
| 1036 |
.files |
| 1037 |
.get_index(file_number) |
| 1038 |
.ok_or(ZipError::FileNotFound)?; |
| 1039 |
|
| 1040 |
match (password, data.encrypted) { |
| 1041 |
(None, true) => return Err(ZipError::UnsupportedArchive(ZipError::PASSWORD_REQUIRED)), |
| 1042 |
(Some(_), false) => password = None, //Password supplied, but none needed! Discard. |
| 1043 |
_ => {} |
| 1044 |
} |
| 1045 |
let limit_reader = find_content(data, &mut self.reader)?; |
| 1046 |
|
| 1047 |
let crypto_reader = make_crypto_reader( |
| 1048 |
data.compression_method, |
| 1049 |
data.crc32, |
| 1050 |
data.last_modified_time, |
| 1051 |
data.using_data_descriptor, |
| 1052 |
limit_reader, |
| 1053 |
password, |
| 1054 |
data.aes_mode, |
| 1055 |
#[cfg(feature = "aes-crypto")] |
| 1056 |
data.compressed_size, |
| 1057 |
)?; |
| 1058 |
Ok(ZipFile { |
| 1059 |
crypto_reader: Some(crypto_reader), |
| 1060 |
reader: ZipFileReader::NoReader, |
| 1061 |
data: Cow::Borrowed(data), |
| 1062 |
}) |
| 1063 |
} |
| 1064 |
|
| 1065 |
/// Unwrap and return the inner reader object |
| 1066 |
/// |
| 1067 |
/// The position of the reader is undefined. |
| 1068 |
pub fn into_inner(self) -> R { |
| 1069 |
self.reader |
| 1070 |
} |
| 1071 |
} |
| 1072 |
|
| 1073 |
/// Holds the AES information of a file in the zip archive |
| 1074 |
#[derive(Debug)] |
| 1075 |
#[cfg(feature = "aes-crypto")] |
| 1076 |
pub struct AesInfo { |
| 1077 |
/// The AES encryption mode |
| 1078 |
pub aes_mode: AesMode, |
| 1079 |
/// The verification key |
| 1080 |
pub verification_value: [u8; PWD_VERIFY_LENGTH], |
| 1081 |
/// The salt |
| 1082 |
pub salt: Vec<u8>, |
| 1083 |
} |
| 1084 |
|
| 1085 |
const fn unsupported_zip_error<T>(detail: &'static str) -> ZipResult<T> { |
| 1086 |
Err(ZipError::UnsupportedArchive(detail)) |
| 1087 |
} |
| 1088 |
|
| 1089 |
/// Parse a central directory entry to collect the information for the file. |
| 1090 |
pub(crate) fn central_header_to_zip_file<R: Read + Seek>( |
| 1091 |
reader: &mut R, |
| 1092 |
archive_offset: u64, |
| 1093 |
) -> ZipResult<ZipFileData> { |
| 1094 |
let central_header_start = reader.stream_position()?; |
| 1095 |
|
| 1096 |
// Parse central header |
| 1097 |
let block = ZipCentralEntryBlock::parse(reader)?; |
| 1098 |
central_header_to_zip_file_inner(reader, archive_offset, central_header_start, block) |
| 1099 |
} |
| 1100 |
|
| 1101 |
#[inline] |
| 1102 |
fn read_variable_length_byte_field<R: Read>(reader: &mut R, len: usize) -> io::Result<Box<[u8]>> { |
| 1103 |
let mut data = vec![0; len].into_boxed_slice(); |
| 1104 |
reader.read_exact(&mut data)?; |
| 1105 |
Ok(data) |
| 1106 |
} |
| 1107 |
|
| 1108 |
/// Parse a central directory entry to collect the information for the file. |
| 1109 |
fn central_header_to_zip_file_inner<R: Read>( |
| 1110 |
reader: &mut R, |
| 1111 |
archive_offset: u64, |
| 1112 |
central_header_start: u64, |
| 1113 |
block: ZipCentralEntryBlock, |
| 1114 |
) -> ZipResult<ZipFileData> { |
| 1115 |
let ZipCentralEntryBlock { |
| 1116 |
// magic, |
| 1117 |
version_made_by, |
| 1118 |
// version_to_extract, |
| 1119 |
flags, |
| 1120 |
compression_method, |
| 1121 |
last_mod_time, |
| 1122 |
last_mod_date, |
| 1123 |
crc32, |
| 1124 |
compressed_size, |
| 1125 |
uncompressed_size, |
| 1126 |
file_name_length, |
| 1127 |
extra_field_length, |
| 1128 |
file_comment_length, |
| 1129 |
// disk_number, |
| 1130 |
// internal_file_attributes, |
| 1131 |
external_file_attributes, |
| 1132 |
offset, |
| 1133 |
.. |
| 1134 |
} = block; |
| 1135 |
|
| 1136 |
let encrypted = flags & 1 == 1; |
| 1137 |
let is_utf8 = flags & (1 << 11) != 0; |
| 1138 |
let using_data_descriptor = flags & (1 << 3) != 0; |
| 1139 |
|
| 1140 |
let file_name_raw = read_variable_length_byte_field(reader, file_name_length as usize)?; |
| 1141 |
let extra_field = read_variable_length_byte_field(reader, extra_field_length as usize)?; |
| 1142 |
let file_comment_raw = read_variable_length_byte_field(reader, file_comment_length as usize)?; |
| 1143 |
|
| 1144 |
let file_name: Box<str> = match is_utf8 { |
| 1145 |
true => String::from_utf8_lossy(&file_name_raw).into(), |
| 1146 |
false => file_name_raw.clone().from_cp437(), |
| 1147 |
}; |
| 1148 |
let file_comment: Box<str> = match is_utf8 { |
| 1149 |
true => String::from_utf8_lossy(&file_comment_raw).into(), |
| 1150 |
false => file_comment_raw.from_cp437(), |
| 1151 |
}; |
| 1152 |
|
| 1153 |
// Construct the result |
| 1154 |
let mut result = ZipFileData { |
| 1155 |
system: System::from((version_made_by >> 8) as u8), |
| 1156 |
/* NB: this strips the top 8 bits! */ |
| 1157 |
version_made_by: version_made_by as u8, |
| 1158 |
encrypted, |
| 1159 |
using_data_descriptor, |
| 1160 |
is_utf8, |
| 1161 |
compression_method: CompressionMethod::parse_from_u16(compression_method), |
| 1162 |
compression_level: None, |
| 1163 |
last_modified_time: DateTime::try_from_msdos(last_mod_date, last_mod_time).ok(), |
| 1164 |
crc32, |
| 1165 |
compressed_size: compressed_size.into(), |
| 1166 |
uncompressed_size: uncompressed_size.into(), |
| 1167 |
file_name, |
| 1168 |
file_name_raw, |
| 1169 |
extra_field: Some(Arc::new(extra_field.to_vec())), |
| 1170 |
central_extra_field: None, |
| 1171 |
file_comment, |
| 1172 |
header_start: offset.into(), |
| 1173 |
extra_data_start: None, |
| 1174 |
central_header_start, |
| 1175 |
data_start: OnceLock::new(), |
| 1176 |
external_attributes: external_file_attributes, |
| 1177 |
large_file: false, |
| 1178 |
aes_mode: None, |
| 1179 |
aes_extra_data_start: 0, |
| 1180 |
extra_fields: Vec::new(), |
| 1181 |
}; |
| 1182 |
|
| 1183 |
match parse_extra_field(&mut result) { |
| 1184 |
Ok(..) | Err(ZipError::Io(..)) => {} |
| 1185 |
Err(e) => return Err(e), |
| 1186 |
} |
| 1187 |
|
| 1188 |
let aes_enabled = result.compression_method == CompressionMethod::AES; |
| 1189 |
if aes_enabled && result.aes_mode.is_none() { |
| 1190 |
return Err(ZipError::InvalidArchive( |
| 1191 |
"AES encryption without AES extra data field", |
| 1192 |
)); |
| 1193 |
} |
| 1194 |
|
| 1195 |
// Account for shifted zip offsets. |
| 1196 |
result.header_start = result |
| 1197 |
.header_start |
| 1198 |
.checked_add(archive_offset) |
| 1199 |
.ok_or(ZipError::InvalidArchive("Archive header is too large"))?; |
| 1200 |
|
| 1201 |
Ok(result) |
| 1202 |
} |
| 1203 |
|
| 1204 |
fn parse_extra_field(file: &mut ZipFileData) -> ZipResult<()> { |
| 1205 |
let Some(extra_field) = &file.extra_field else { |
| 1206 |
return Ok(()); |
| 1207 |
}; |
| 1208 |
let mut reader = io::Cursor::new(extra_field.as_ref()); |
| 1209 |
|
| 1210 |
/* TODO: codify this structure into Zip64ExtraFieldBlock fields! */ |
| 1211 |
while (reader.position() as usize) < extra_field.len() { |
| 1212 |
let kind = reader.read_u16_le()?; |
| 1213 |
let len = reader.read_u16_le()?; |
| 1214 |
let mut len_left = len as i64; |
| 1215 |
match kind { |
| 1216 |
// Zip64 extended information extra field |
| 1217 |
0x0001 => { |
| 1218 |
if file.uncompressed_size == spec::ZIP64_BYTES_THR { |
| 1219 |
file.large_file = true; |
| 1220 |
file.uncompressed_size = reader.read_u64_le()?; |
| 1221 |
len_left -= 8; |
| 1222 |
} |
| 1223 |
if file.compressed_size == spec::ZIP64_BYTES_THR { |
| 1224 |
file.large_file = true; |
| 1225 |
file.compressed_size = reader.read_u64_le()?; |
| 1226 |
len_left -= 8; |
| 1227 |
} |
| 1228 |
if file.header_start == spec::ZIP64_BYTES_THR { |
| 1229 |
file.header_start = reader.read_u64_le()?; |
| 1230 |
len_left -= 8; |
| 1231 |
} |
| 1232 |
} |
| 1233 |
0x9901 => { |
| 1234 |
// AES |
| 1235 |
if len != 7 { |
| 1236 |
return Err(ZipError::UnsupportedArchive( |
| 1237 |
"AES extra data field has an unsupported length", |
| 1238 |
)); |
| 1239 |
} |
| 1240 |
let vendor_version = reader.read_u16_le()?; |
| 1241 |
let vendor_id = reader.read_u16_le()?; |
| 1242 |
let mut out = [0u8]; |
| 1243 |
reader.read_exact(&mut out)?; |
| 1244 |
let aes_mode = out[0]; |
| 1245 |
let compression_method = CompressionMethod::parse_from_u16(reader.read_u16_le()?); |
| 1246 |
|
| 1247 |
if vendor_id != 0x4541 { |
| 1248 |
return Err(ZipError::InvalidArchive("Invalid AES vendor")); |
| 1249 |
} |
| 1250 |
let vendor_version = match vendor_version { |
| 1251 |
0x0001 => AesVendorVersion::Ae1, |
| 1252 |
0x0002 => AesVendorVersion::Ae2, |
| 1253 |
_ => return Err(ZipError::InvalidArchive("Invalid AES vendor version")), |
| 1254 |
}; |
| 1255 |
match aes_mode { |
| 1256 |
0x01 => { |
| 1257 |
file.aes_mode = Some((AesMode::Aes128, vendor_version, compression_method)) |
| 1258 |
} |
| 1259 |
0x02 => { |
| 1260 |
file.aes_mode = Some((AesMode::Aes192, vendor_version, compression_method)) |
| 1261 |
} |
| 1262 |
0x03 => { |
| 1263 |
file.aes_mode = Some((AesMode::Aes256, vendor_version, compression_method)) |
| 1264 |
} |
| 1265 |
_ => return Err(ZipError::InvalidArchive("Invalid AES encryption strength")), |
| 1266 |
}; |
| 1267 |
file.compression_method = compression_method; |
| 1268 |
} |
| 1269 |
0x5455 => { |
| 1270 |
// extended timestamp |
| 1271 |
// https://libzip.org/specifications/extrafld.txt |
| 1272 |
|
| 1273 |
file.extra_fields.push(ExtraField::ExtendedTimestamp( |
| 1274 |
ExtendedTimestamp::try_from_reader(&mut reader, len)?, |
| 1275 |
)); |
| 1276 |
|
| 1277 |
// the reader for ExtendedTimestamp consumes `len` bytes |
| 1278 |
len_left = 0; |
| 1279 |
} |
| 1280 |
0x6375 => { |
| 1281 |
// Info-ZIP Unicode Comment Extra Field |
| 1282 |
// APPNOTE 4.6.8 and https://libzip.org/specifications/extrafld.txt |
| 1283 |
if !file.is_utf8 { |
| 1284 |
file.file_comment = String::from_utf8( |
| 1285 |
UnicodeExtraField::try_from_reader(&mut reader, len)? |
| 1286 |
.unwrap_valid(file.file_comment.as_bytes())? |
| 1287 |
.into_vec(), |
| 1288 |
)? |
| 1289 |
.into(); |
| 1290 |
} |
| 1291 |
} |
| 1292 |
0x7075 => { |
| 1293 |
// Info-ZIP Unicode Path Extra Field |
| 1294 |
// APPNOTE 4.6.9 and https://libzip.org/specifications/extrafld.txt |
| 1295 |
if !file.is_utf8 { |
| 1296 |
file.file_name_raw = UnicodeExtraField::try_from_reader(&mut reader, len)? |
| 1297 |
.unwrap_valid(&file.file_name_raw)?; |
| 1298 |
file.file_name = |
| 1299 |
String::from_utf8(file.file_name_raw.clone().into_vec())?.into_boxed_str(); |
| 1300 |
file.is_utf8 = true; |
| 1301 |
} |
| 1302 |
} |
| 1303 |
_ => { |
| 1304 |
// Other fields are ignored |
| 1305 |
} |
| 1306 |
} |
| 1307 |
|
| 1308 |
// We could also check for < 0 to check for errors |
| 1309 |
if len_left > 0 { |
| 1310 |
reader.seek(io::SeekFrom::Current(len_left))?; |
| 1311 |
} |
| 1312 |
} |
| 1313 |
Ok(()) |
| 1314 |
} |
| 1315 |
|
| 1316 |
/// Methods for retrieving information on zip files |
| 1317 |
impl<'a> ZipFile<'a> { |
| 1318 |
fn get_reader(&mut self) -> ZipResult<&mut ZipFileReader<'a>> { |
| 1319 |
if let ZipFileReader::NoReader = self.reader { |
| 1320 |
let data = &self.data; |
| 1321 |
let crypto_reader = self.crypto_reader.take().expect("Invalid reader state"); |
| 1322 |
self.reader = make_reader(data.compression_method, data.crc32, crypto_reader)?; |
| 1323 |
} |
| 1324 |
Ok(&mut self.reader) |
| 1325 |
} |
| 1326 |
|
| 1327 |
pub(crate) fn get_raw_reader(&mut self) -> &mut dyn Read { |
| 1328 |
if let ZipFileReader::NoReader = self.reader { |
| 1329 |
let crypto_reader = self.crypto_reader.take().expect("Invalid reader state"); |
| 1330 |
self.reader = ZipFileReader::Raw(crypto_reader.into_inner()) |
| 1331 |
} |
| 1332 |
&mut self.reader |
| 1333 |
} |
| 1334 |
|
| 1335 |
/// Get the version of the file |
| 1336 |
pub fn version_made_by(&self) -> (u8, u8) { |
| 1337 |
( |
| 1338 |
self.data.version_made_by / 10, |
| 1339 |
self.data.version_made_by % 10, |
| 1340 |
) |
| 1341 |
} |
| 1342 |
|
| 1343 |
/// Get the name of the file |
| 1344 |
/// |
| 1345 |
/// # Warnings |
| 1346 |
/// |
| 1347 |
/// It is dangerous to use this name directly when extracting an archive. |
| 1348 |
/// It may contain an absolute path (`/etc/shadow`), or break out of the |
| 1349 |
/// current directory (`../runtime`). Carelessly writing to these paths |
| 1350 |
/// allows an attacker to craft a ZIP archive that will overwrite critical |
| 1351 |
/// files. |
| 1352 |
/// |
| 1353 |
/// You can use the [`ZipFile::enclosed_name`] method to validate the name |
| 1354 |
/// as a safe path. |
| 1355 |
pub fn name(&self) -> &str { |
| 1356 |
&self.data.file_name |
| 1357 |
} |
| 1358 |
|
| 1359 |
/// Get the name of the file, in the raw (internal) byte representation. |
| 1360 |
/// |
| 1361 |
/// The encoding of this data is currently undefined. |
| 1362 |
pub fn name_raw(&self) -> &[u8] { |
| 1363 |
&self.data.file_name_raw |
| 1364 |
} |
| 1365 |
|
| 1366 |
/// Get the name of the file in a sanitized form. It truncates the name to the first NULL byte, |
| 1367 |
/// removes a leading '/' and removes '..' parts. |
| 1368 |
#[deprecated( |
| 1369 |
since = "0.5.7", |
| 1370 |
note = "by stripping `..`s from the path, the meaning of paths can change. |
| 1371 |
`mangled_name` can be used if this behaviour is desirable" |
| 1372 |
)] |
| 1373 |
pub fn sanitized_name(&self) -> PathBuf { |
| 1374 |
self.mangled_name() |
| 1375 |
} |
| 1376 |
|
| 1377 |
/// Rewrite the path, ignoring any path components with special meaning. |
| 1378 |
/// |
| 1379 |
/// - Absolute paths are made relative |
| 1380 |
/// - [`ParentDir`]s are ignored |
| 1381 |
/// - Truncates the filename at a NULL byte |
| 1382 |
/// |
| 1383 |
/// This is appropriate if you need to be able to extract *something* from |
| 1384 |
/// any archive, but will easily misrepresent trivial paths like |
| 1385 |
/// `foo/../bar` as `foo/bar` (instead of `bar`). Because of this, |
| 1386 |
/// [`ZipFile::enclosed_name`] is the better option in most scenarios. |
| 1387 |
/// |
| 1388 |
/// [`ParentDir`]: `Component::ParentDir` |
| 1389 |
pub fn mangled_name(&self) -> PathBuf { |
| 1390 |
self.data.file_name_sanitized() |
| 1391 |
} |
| 1392 |
|
| 1393 |
/// Ensure the file path is safe to use as a [`Path`]. |
| 1394 |
/// |
| 1395 |
/// - It can't contain NULL bytes |
| 1396 |
/// - It can't resolve to a path outside the current directory |
| 1397 |
/// > `foo/../bar` is fine, `foo/../../bar` is not. |
| 1398 |
/// - It can't be an absolute path |
| 1399 |
/// |
| 1400 |
/// This will read well-formed ZIP files correctly, and is resistant |
| 1401 |
/// to path-based exploits. It is recommended over |
| 1402 |
/// [`ZipFile::mangled_name`]. |
| 1403 |
pub fn enclosed_name(&self) -> Option<PathBuf> { |
| 1404 |
self.data.enclosed_name() |
| 1405 |
} |
| 1406 |
|
| 1407 |
/// Get the comment of the file |
| 1408 |
pub fn comment(&self) -> &str { |
| 1409 |
&self.data.file_comment |
| 1410 |
} |
| 1411 |
|
| 1412 |
/// Get the compression method used to store the file |
| 1413 |
pub fn compression(&self) -> CompressionMethod { |
| 1414 |
self.data.compression_method |
| 1415 |
} |
| 1416 |
|
| 1417 |
/// Get the size of the file, in bytes, in the archive |
| 1418 |
pub fn compressed_size(&self) -> u64 { |
| 1419 |
self.data.compressed_size |
| 1420 |
} |
| 1421 |
|
| 1422 |
/// Get the size of the file, in bytes, when uncompressed |
| 1423 |
pub fn size(&self) -> u64 { |
| 1424 |
self.data.uncompressed_size |
| 1425 |
} |
| 1426 |
|
| 1427 |
/// Get the time the file was last modified |
| 1428 |
pub fn last_modified(&self) -> Option<DateTime> { |
| 1429 |
self.data.last_modified_time |
| 1430 |
} |
| 1431 |
/// Returns whether the file is actually a directory |
| 1432 |
pub fn is_dir(&self) -> bool { |
| 1433 |
is_dir(self.name()) |
| 1434 |
} |
| 1435 |
|
| 1436 |
/// Returns whether the file is actually a symbolic link |
| 1437 |
pub fn is_symlink(&self) -> bool { |
| 1438 |
self.unix_mode() |
| 1439 |
.is_some_and(|mode| mode & S_IFLNK == S_IFLNK) |
| 1440 |
} |
| 1441 |
|
| 1442 |
/// Returns whether the file is a normal file (i.e. not a directory or symlink) |
| 1443 |
pub fn is_file(&self) -> bool { |
| 1444 |
!self.is_dir() && !self.is_symlink() |
| 1445 |
} |
| 1446 |
|
| 1447 |
/// Get unix mode for the file |
| 1448 |
pub fn unix_mode(&self) -> Option<u32> { |
| 1449 |
self.data.unix_mode() |
| 1450 |
} |
| 1451 |
|
| 1452 |
/// Get the CRC32 hash of the original file |
| 1453 |
pub fn crc32(&self) -> u32 { |
| 1454 |
self.data.crc32 |
| 1455 |
} |
| 1456 |
|
| 1457 |
/// Get the extra data of the zip header for this file |
| 1458 |
pub fn extra_data(&self) -> Option<&[u8]> { |
| 1459 |
self.data.extra_field.as_ref().map(|v| v.deref().deref()) |
| 1460 |
} |
| 1461 |
|
| 1462 |
/// Get the starting offset of the data of the compressed file |
| 1463 |
pub fn data_start(&self) -> u64 { |
| 1464 |
*self.data.data_start.get().unwrap_or(&0) |
| 1465 |
} |
| 1466 |
|
| 1467 |
/// Get the starting offset of the zip header for this file |
| 1468 |
pub fn header_start(&self) -> u64 { |
| 1469 |
self.data.header_start |
| 1470 |
} |
| 1471 |
/// Get the starting offset of the zip header in the central directory for this file |
| 1472 |
pub fn central_header_start(&self) -> u64 { |
| 1473 |
self.data.central_header_start |
| 1474 |
} |
| 1475 |
|
| 1476 |
/// iterate through all extra fields |
| 1477 |
pub fn extra_data_fields(&self) -> impl Iterator<Item = &ExtraField> { |
| 1478 |
self.data.extra_fields.iter() |
| 1479 |
} |
| 1480 |
} |
| 1481 |
|
| 1482 |
impl<'a> Read for ZipFile<'a> { |
| 1483 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 1484 |
self.get_reader()?.read(buf) |
| 1485 |
} |
| 1486 |
} |
| 1487 |
|
| 1488 |
impl<'a> Drop for ZipFile<'a> { |
| 1489 |
fn drop(&mut self) { |
| 1490 |
// self.data is Owned, this reader is constructed by a streaming reader. |
| 1491 |
// In this case, we want to exhaust the reader so that the next file is accessible. |
| 1492 |
if let Cow::Owned(_) = self.data { |
| 1493 |
// Get the inner `Take` reader so all decryption, decompression and CRC calculation is skipped. |
| 1494 |
match &mut self.reader { |
| 1495 |
ZipFileReader::NoReader => { |
| 1496 |
let innerreader = self.crypto_reader.take(); |
| 1497 |
let _ = copy( |
| 1498 |
&mut innerreader.expect("Invalid reader state").into_inner(), |
| 1499 |
&mut sink(), |
| 1500 |
); |
| 1501 |
} |
| 1502 |
reader => { |
| 1503 |
let innerreader = std::mem::replace(reader, ZipFileReader::NoReader); |
| 1504 |
innerreader.drain(); |
| 1505 |
} |
| 1506 |
}; |
| 1507 |
} |
| 1508 |
} |
| 1509 |
} |
| 1510 |
|
| 1511 |
/// Read ZipFile structures from a non-seekable reader. |
| 1512 |
/// |
| 1513 |
/// This is an alternative method to read a zip file. If possible, use the ZipArchive functions |
| 1514 |
/// as some information will be missing when reading this manner. |
| 1515 |
/// |
| 1516 |
/// Reads a file header from the start of the stream. Will return `Ok(Some(..))` if a file is |
| 1517 |
/// present at the start of the stream. Returns `Ok(None)` if the start of the central directory |
| 1518 |
/// is encountered. No more files should be read after this. |
| 1519 |
/// |
| 1520 |
/// The Drop implementation of ZipFile ensures that the reader will be correctly positioned after |
| 1521 |
/// the structure is done. |
| 1522 |
/// |
| 1523 |
/// Missing fields are: |
| 1524 |
/// * `comment`: set to an empty string |
| 1525 |
/// * `data_start`: set to 0 |
| 1526 |
/// * `external_attributes`: `unix_mode()`: will return None |
| 1527 |
pub fn read_zipfile_from_stream<'a, R: Read>(reader: &'a mut R) -> ZipResult<Option<ZipFile<'_>>> { |
| 1528 |
// We can't use the typical ::parse() method, as we follow separate code paths depending on the |
| 1529 |
// "magic" value (since the magic value will be from the central directory header if we've |
| 1530 |
// finished iterating over all the actual files). |
| 1531 |
/* TODO: smallvec? */ |
| 1532 |
let mut block = [0u8; mem::size_of::<ZipLocalEntryBlock>()]; |
| 1533 |
reader.read_exact(&mut block)?; |
| 1534 |
let block: Box<[u8]> = block.into(); |
| 1535 |
|
| 1536 |
let signature = spec::Magic::from_first_le_bytes(&block); |
| 1537 |
|
| 1538 |
match signature { |
| 1539 |
spec::Magic::LOCAL_FILE_HEADER_SIGNATURE => (), |
| 1540 |
spec::Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE => return Ok(None), |
| 1541 |
_ => return Err(ZipError::InvalidArchive("Invalid local file header")), |
| 1542 |
} |
| 1543 |
|
| 1544 |
let block = ZipLocalEntryBlock::interpret(&block)?; |
| 1545 |
|
| 1546 |
let mut result = ZipFileData::from_local_block(block, reader)?; |
| 1547 |
|
| 1548 |
match parse_extra_field(&mut result) { |
| 1549 |
Ok(..) | Err(ZipError::Io(..)) => {} |
| 1550 |
Err(e) => return Err(e), |
| 1551 |
} |
| 1552 |
|
| 1553 |
let limit_reader = (reader as &'a mut dyn Read).take(result.compressed_size); |
| 1554 |
|
| 1555 |
let result_crc32 = result.crc32; |
| 1556 |
let result_compression_method = result.compression_method; |
| 1557 |
let crypto_reader = make_crypto_reader( |
| 1558 |
result_compression_method, |
| 1559 |
result_crc32, |
| 1560 |
result.last_modified_time, |
| 1561 |
result.using_data_descriptor, |
| 1562 |
limit_reader, |
| 1563 |
None, |
| 1564 |
None, |
| 1565 |
#[cfg(feature = "aes-crypto")] |
| 1566 |
result.compressed_size, |
| 1567 |
)?; |
| 1568 |
|
| 1569 |
Ok(Some(ZipFile { |
| 1570 |
data: Cow::Owned(result), |
| 1571 |
crypto_reader: None, |
| 1572 |
reader: make_reader(result_compression_method, result_crc32, crypto_reader)?, |
| 1573 |
})) |
| 1574 |
} |
| 1575 |
|
| 1576 |
#[cfg(test)] |
| 1577 |
mod test { |
| 1578 |
use crate::ZipArchive; |
| 1579 |
use std::io::Cursor; |
| 1580 |
use tempdir::TempDir; |
| 1581 |
|
| 1582 |
#[test] |
| 1583 |
fn invalid_offset() { |
| 1584 |
use super::ZipArchive; |
| 1585 |
|
| 1586 |
let mut v = Vec::new(); |
| 1587 |
v.extend_from_slice(include_bytes!("../tests/data/invalid_offset.zip")); |
| 1588 |
let reader = ZipArchive::new(Cursor::new(v)); |
| 1589 |
assert!(reader.is_err()); |
| 1590 |
} |
| 1591 |
|
| 1592 |
#[test] |
| 1593 |
fn invalid_offset2() { |
| 1594 |
use super::ZipArchive; |
| 1595 |
|
| 1596 |
let mut v = Vec::new(); |
| 1597 |
v.extend_from_slice(include_bytes!("../tests/data/invalid_offset2.zip")); |
| 1598 |
let reader = ZipArchive::new(Cursor::new(v)); |
| 1599 |
assert!(reader.is_err()); |
| 1600 |
} |
| 1601 |
|
| 1602 |
#[test] |
| 1603 |
fn zip64_with_leading_junk() { |
| 1604 |
use super::ZipArchive; |
| 1605 |
|
| 1606 |
let mut v = Vec::new(); |
| 1607 |
v.extend_from_slice(include_bytes!("../tests/data/zip64_demo.zip")); |
| 1608 |
let reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1609 |
assert_eq!(reader.len(), 1); |
| 1610 |
} |
| 1611 |
|
| 1612 |
#[test] |
| 1613 |
fn zip_contents() { |
| 1614 |
use super::ZipArchive; |
| 1615 |
|
| 1616 |
let mut v = Vec::new(); |
| 1617 |
v.extend_from_slice(include_bytes!("../tests/data/mimetype.zip")); |
| 1618 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1619 |
assert_eq!(reader.comment(), b""); |
| 1620 |
assert_eq!(reader.by_index(0).unwrap().central_header_start(), 77); |
| 1621 |
} |
| 1622 |
|
| 1623 |
#[test] |
| 1624 |
fn zip_read_streaming() { |
| 1625 |
use super::read_zipfile_from_stream; |
| 1626 |
|
| 1627 |
let mut v = Vec::new(); |
| 1628 |
v.extend_from_slice(include_bytes!("../tests/data/mimetype.zip")); |
| 1629 |
let mut reader = Cursor::new(v); |
| 1630 |
loop { |
| 1631 |
if read_zipfile_from_stream(&mut reader).unwrap().is_none() { |
| 1632 |
break; |
| 1633 |
} |
| 1634 |
} |
| 1635 |
} |
| 1636 |
|
| 1637 |
#[test] |
| 1638 |
fn zip_clone() { |
| 1639 |
use super::ZipArchive; |
| 1640 |
use std::io::Read; |
| 1641 |
|
| 1642 |
let mut v = Vec::new(); |
| 1643 |
v.extend_from_slice(include_bytes!("../tests/data/mimetype.zip")); |
| 1644 |
let mut reader1 = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1645 |
let mut reader2 = reader1.clone(); |
| 1646 |
|
| 1647 |
let mut file1 = reader1.by_index(0).unwrap(); |
| 1648 |
let mut file2 = reader2.by_index(0).unwrap(); |
| 1649 |
|
| 1650 |
let t = file1.last_modified().unwrap(); |
| 1651 |
assert_eq!( |
| 1652 |
( |
| 1653 |
t.year(), |
| 1654 |
t.month(), |
| 1655 |
t.day(), |
| 1656 |
t.hour(), |
| 1657 |
t.minute(), |
| 1658 |
t.second() |
| 1659 |
), |
| 1660 |
(1980, 1, 1, 0, 0, 0) |
| 1661 |
); |
| 1662 |
|
| 1663 |
let mut buf1 = [0; 5]; |
| 1664 |
let mut buf2 = [0; 5]; |
| 1665 |
let mut buf3 = [0; 5]; |
| 1666 |
let mut buf4 = [0; 5]; |
| 1667 |
|
| 1668 |
file1.read_exact(&mut buf1).unwrap(); |
| 1669 |
file2.read_exact(&mut buf2).unwrap(); |
| 1670 |
file1.read_exact(&mut buf3).unwrap(); |
| 1671 |
file2.read_exact(&mut buf4).unwrap(); |
| 1672 |
|
| 1673 |
assert_eq!(buf1, buf2); |
| 1674 |
assert_eq!(buf3, buf4); |
| 1675 |
assert_ne!(buf1, buf3); |
| 1676 |
} |
| 1677 |
|
| 1678 |
#[test] |
| 1679 |
fn file_and_dir_predicates() { |
| 1680 |
use super::ZipArchive; |
| 1681 |
|
| 1682 |
let mut v = Vec::new(); |
| 1683 |
v.extend_from_slice(include_bytes!("../tests/data/files_and_dirs.zip")); |
| 1684 |
let mut zip = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1685 |
|
| 1686 |
for i in 0..zip.len() { |
| 1687 |
let zip_file = zip.by_index(i).unwrap(); |
| 1688 |
let full_name = zip_file.enclosed_name().unwrap(); |
| 1689 |
let file_name = full_name.file_name().unwrap().to_str().unwrap(); |
| 1690 |
assert!( |
| 1691 |
(file_name.starts_with("dir") && zip_file.is_dir()) |
| 1692 |
|| (file_name.starts_with("file") && zip_file.is_file()) |
| 1693 |
); |
| 1694 |
} |
| 1695 |
} |
| 1696 |
|
| 1697 |
#[test] |
| 1698 |
fn zip64_magic_in_filenames() { |
| 1699 |
let files = vec![ |
| 1700 |
include_bytes!("../tests/data/zip64_magic_in_filename_1.zip").to_vec(), |
| 1701 |
include_bytes!("../tests/data/zip64_magic_in_filename_2.zip").to_vec(), |
| 1702 |
include_bytes!("../tests/data/zip64_magic_in_filename_3.zip").to_vec(), |
| 1703 |
include_bytes!("../tests/data/zip64_magic_in_filename_4.zip").to_vec(), |
| 1704 |
include_bytes!("../tests/data/zip64_magic_in_filename_5.zip").to_vec(), |
| 1705 |
]; |
| 1706 |
// Although we don't allow adding files whose names contain the ZIP64 CDB-end or |
| 1707 |
// CDB-end-locator signatures, we still read them when they aren't genuinely ambiguous. |
| 1708 |
for file in files { |
| 1709 |
ZipArchive::new(Cursor::new(file)).unwrap(); |
| 1710 |
} |
| 1711 |
} |
| 1712 |
|
| 1713 |
/// test case to ensure we don't preemptively over allocate based on the |
| 1714 |
/// declared number of files in the CDE of an invalid zip when the number of |
| 1715 |
/// files declared is more than the alleged offset in the CDE |
| 1716 |
#[test] |
| 1717 |
fn invalid_cde_number_of_files_allocation_smaller_offset() { |
| 1718 |
use super::ZipArchive; |
| 1719 |
|
| 1720 |
let mut v = Vec::new(); |
| 1721 |
v.extend_from_slice(include_bytes!( |
| 1722 |
"../tests/data/invalid_cde_number_of_files_allocation_smaller_offset.zip" |
| 1723 |
)); |
| 1724 |
let reader = ZipArchive::new(Cursor::new(v)); |
| 1725 |
assert!(reader.is_err() || reader.unwrap().is_empty()); |
| 1726 |
} |
| 1727 |
|
| 1728 |
/// test case to ensure we don't preemptively over allocate based on the |
| 1729 |
/// declared number of files in the CDE of an invalid zip when the number of |
| 1730 |
/// files declared is less than the alleged offset in the CDE |
| 1731 |
#[test] |
| 1732 |
fn invalid_cde_number_of_files_allocation_greater_offset() { |
| 1733 |
use super::ZipArchive; |
| 1734 |
|
| 1735 |
let mut v = Vec::new(); |
| 1736 |
v.extend_from_slice(include_bytes!( |
| 1737 |
"../tests/data/invalid_cde_number_of_files_allocation_greater_offset.zip" |
| 1738 |
)); |
| 1739 |
let reader = ZipArchive::new(Cursor::new(v)); |
| 1740 |
assert!(reader.is_err()); |
| 1741 |
} |
| 1742 |
|
| 1743 |
#[cfg(feature = "deflate64")] |
| 1744 |
#[test] |
| 1745 |
fn deflate64_index_out_of_bounds() -> std::io::Result<()> { |
| 1746 |
let mut v = Vec::new(); |
| 1747 |
v.extend_from_slice(include_bytes!( |
| 1748 |
"../tests/data/raw_deflate64_index_out_of_bounds.zip" |
| 1749 |
)); |
| 1750 |
let mut reader = ZipArchive::new(Cursor::new(v))?; |
| 1751 |
std::io::copy(&mut reader.by_index(0)?, &mut std::io::sink()).expect_err("Invalid file"); |
| 1752 |
Ok(()) |
| 1753 |
} |
| 1754 |
|
| 1755 |
#[cfg(feature = "deflate64")] |
| 1756 |
#[test] |
| 1757 |
fn deflate64_not_enough_space() { |
| 1758 |
let mut v = Vec::new(); |
| 1759 |
v.extend_from_slice(include_bytes!("../tests/data/deflate64_issue_25.zip")); |
| 1760 |
ZipArchive::new(Cursor::new(v)).expect_err("Invalid file"); |
| 1761 |
} |
| 1762 |
|
| 1763 |
#[cfg(feature = "_deflate-any")] |
| 1764 |
#[test] |
| 1765 |
fn test_read_with_data_descriptor() { |
| 1766 |
use std::io::Read; |
| 1767 |
|
| 1768 |
let mut v = Vec::new(); |
| 1769 |
v.extend_from_slice(include_bytes!("../tests/data/data_descriptor.zip")); |
| 1770 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1771 |
let mut decompressed = [0u8; 16]; |
| 1772 |
let mut file = reader.by_index(0).unwrap(); |
| 1773 |
assert_eq!(file.read(&mut decompressed).unwrap(), 12); |
| 1774 |
} |
| 1775 |
|
| 1776 |
#[test] |
| 1777 |
fn test_is_symlink() -> std::io::Result<()> { |
| 1778 |
let mut v = Vec::new(); |
| 1779 |
v.extend_from_slice(include_bytes!("../tests/data/symlink.zip")); |
| 1780 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1781 |
assert!(reader.by_index(0).unwrap().is_symlink()); |
| 1782 |
let tempdir = TempDir::new("test_is_symlink")?; |
| 1783 |
reader.extract(&tempdir).unwrap(); |
| 1784 |
assert!(tempdir.path().join("bar").is_symlink()); |
| 1785 |
Ok(()) |
| 1786 |
} |
| 1787 |
|
| 1788 |
#[test] |
| 1789 |
#[cfg(feature = "_deflate-any")] |
| 1790 |
fn test_utf8_extra_field() { |
| 1791 |
let mut v = Vec::new(); |
| 1792 |
v.extend_from_slice(include_bytes!("../tests/data/chinese.zip")); |
| 1793 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1794 |
reader.by_name("七个房间.txt").unwrap(); |
| 1795 |
} |
| 1796 |
|
| 1797 |
#[test] |
| 1798 |
fn test_utf8() { |
| 1799 |
let mut v = Vec::new(); |
| 1800 |
v.extend_from_slice(include_bytes!("../tests/data/linux-7z.zip")); |
| 1801 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1802 |
reader.by_name("你好.txt").unwrap(); |
| 1803 |
} |
| 1804 |
|
| 1805 |
#[test] |
| 1806 |
fn test_utf8_2() { |
| 1807 |
let mut v = Vec::new(); |
| 1808 |
v.extend_from_slice(include_bytes!("../tests/data/windows-7zip.zip")); |
| 1809 |
let mut reader = ZipArchive::new(Cursor::new(v)).unwrap(); |
| 1810 |
reader.by_name("你好.txt").unwrap(); |
| 1811 |
} |
| 1812 |
} |