| 1 |
//! Types for creating ZIP archives |
| 2 |
|
| 3 |
#[cfg(feature = "aes-crypto")] |
| 4 |
use crate::aes::AesWriter; |
| 5 |
use crate::compression::CompressionMethod; |
| 6 |
use crate::read::{find_content, Config, ZipArchive, ZipFile, ZipFileReader}; |
| 7 |
use crate::result::{ZipError, ZipResult}; |
| 8 |
use crate::spec::{self, FixedSizeBlock}; |
| 9 |
#[cfg(feature = "aes-crypto")] |
| 10 |
use crate::types::AesMode; |
| 11 |
use crate::types::{ |
| 12 |
ffi, AesVendorVersion, DateTime, ZipFileData, ZipLocalEntryBlock, ZipRawValues, MIN_VERSION, |
| 13 |
}; |
| 14 |
use crate::write::ffi::S_IFLNK; |
| 15 |
#[cfg(any(feature = "_deflate-any", feature = "bzip2", feature = "zstd",))] |
| 16 |
use core::num::NonZeroU64; |
| 17 |
use crc32fast::Hasher; |
| 18 |
use indexmap::IndexMap; |
| 19 |
use std::borrow::ToOwned; |
| 20 |
use std::default::Default; |
| 21 |
use std::fmt::{Debug, Formatter}; |
| 22 |
use std::io; |
| 23 |
use std::io::prelude::*; |
| 24 |
use std::io::{BufReader, SeekFrom}; |
| 25 |
use std::marker::PhantomData; |
| 26 |
use std::mem; |
| 27 |
use std::str::{from_utf8, Utf8Error}; |
| 28 |
use std::sync::Arc; |
| 29 |
|
| 30 |
#[cfg(feature = "deflate-flate2")] |
| 31 |
use flate2::{write::DeflateEncoder, Compression}; |
| 32 |
|
| 33 |
#[cfg(feature = "bzip2")] |
| 34 |
use bzip2::write::BzEncoder; |
| 35 |
|
| 36 |
#[cfg(feature = "deflate-zopfli")] |
| 37 |
use zopfli::Options; |
| 38 |
|
| 39 |
#[cfg(feature = "deflate-zopfli")] |
| 40 |
use std::io::BufWriter; |
| 41 |
use std::path::Path; |
| 42 |
|
| 43 |
#[cfg(feature = "zstd")] |
| 44 |
use zstd::stream::write::Encoder as ZstdEncoder; |
| 45 |
|
| 46 |
enum MaybeEncrypted<W> { |
| 47 |
Unencrypted(W), |
| 48 |
#[cfg(feature = "aes-crypto")] |
| 49 |
Aes(crate::aes::AesWriter<W>), |
| 50 |
ZipCrypto(crate::zipcrypto::ZipCryptoWriter<W>), |
| 51 |
} |
| 52 |
|
| 53 |
impl<W> Debug for MaybeEncrypted<W> { |
| 54 |
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 55 |
// Don't print W, since it may be a huge Vec<u8> |
| 56 |
f.write_str(match self { |
| 57 |
MaybeEncrypted::Unencrypted(_) => "Unencrypted", |
| 58 |
#[cfg(feature = "aes-crypto")] |
| 59 |
MaybeEncrypted::Aes(_) => "AES", |
| 60 |
MaybeEncrypted::ZipCrypto(_) => "ZipCrypto", |
| 61 |
}) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
impl<W: Write> Write for MaybeEncrypted<W> { |
| 66 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 67 |
match self { |
| 68 |
MaybeEncrypted::Unencrypted(w) => w.write(buf), |
| 69 |
#[cfg(feature = "aes-crypto")] |
| 70 |
MaybeEncrypted::Aes(w) => w.write(buf), |
| 71 |
MaybeEncrypted::ZipCrypto(w) => w.write(buf), |
| 72 |
} |
| 73 |
} |
| 74 |
fn flush(&mut self) -> io::Result<()> { |
| 75 |
match self { |
| 76 |
MaybeEncrypted::Unencrypted(w) => w.flush(), |
| 77 |
#[cfg(feature = "aes-crypto")] |
| 78 |
MaybeEncrypted::Aes(w) => w.flush(), |
| 79 |
MaybeEncrypted::ZipCrypto(w) => w.flush(), |
| 80 |
} |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
enum GenericZipWriter<W: Write + Seek> { |
| 85 |
Closed, |
| 86 |
Storer(MaybeEncrypted<W>), |
| 87 |
#[cfg(feature = "deflate-flate2")] |
| 88 |
Deflater(DeflateEncoder<MaybeEncrypted<W>>), |
| 89 |
#[cfg(feature = "deflate-zopfli")] |
| 90 |
ZopfliDeflater(zopfli::DeflateEncoder<MaybeEncrypted<W>>), |
| 91 |
#[cfg(feature = "deflate-zopfli")] |
| 92 |
BufferedZopfliDeflater(BufWriter<zopfli::DeflateEncoder<MaybeEncrypted<W>>>), |
| 93 |
#[cfg(feature = "bzip2")] |
| 94 |
Bzip2(BzEncoder<MaybeEncrypted<W>>), |
| 95 |
#[cfg(feature = "zstd")] |
| 96 |
Zstd(ZstdEncoder<'static, MaybeEncrypted<W>>), |
| 97 |
} |
| 98 |
|
| 99 |
impl<W: Write + Seek> Debug for GenericZipWriter<W> { |
| 100 |
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { |
| 101 |
match self { |
| 102 |
Closed => f.write_str("Closed"), |
| 103 |
Storer(w) => f.write_fmt(format_args!("Storer({:?})", w)), |
| 104 |
#[cfg(feature = "deflate-flate2")] |
| 105 |
GenericZipWriter::Deflater(w) => { |
| 106 |
f.write_fmt(format_args!("Deflater({:?})", w.get_ref())) |
| 107 |
} |
| 108 |
#[cfg(feature = "deflate-zopfli")] |
| 109 |
GenericZipWriter::ZopfliDeflater(_) => f.write_str("ZopfliDeflater"), |
| 110 |
#[cfg(feature = "deflate-zopfli")] |
| 111 |
GenericZipWriter::BufferedZopfliDeflater(_) => f.write_str("BufferedZopfliDeflater"), |
| 112 |
#[cfg(feature = "bzip2")] |
| 113 |
GenericZipWriter::Bzip2(w) => f.write_fmt(format_args!("Bzip2({:?})", w.get_ref())), |
| 114 |
#[cfg(feature = "zstd")] |
| 115 |
GenericZipWriter::Zstd(w) => f.write_fmt(format_args!("Zstd({:?})", w.get_ref())), |
| 116 |
} |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// Put the struct declaration in a private module to convince rustdoc to display ZipWriter nicely |
| 121 |
pub(crate) mod zip_writer { |
| 122 |
use super::*; |
| 123 |
/// ZIP archive generator |
| 124 |
/// |
| 125 |
/// Handles the bookkeeping involved in building an archive, and provides an |
| 126 |
/// API to edit its contents. |
| 127 |
/// |
| 128 |
/// ``` |
| 129 |
/// # fn doit() -> zip::result::ZipResult<()> |
| 130 |
/// # { |
| 131 |
/// # use zip::ZipWriter; |
| 132 |
/// use std::io::Write; |
| 133 |
/// use zip::write::SimpleFileOptions; |
| 134 |
/// |
| 135 |
/// // We use a buffer here, though you'd normally use a `File` |
| 136 |
/// let mut buf = [0; 65536]; |
| 137 |
/// let mut zip = ZipWriter::new(std::io::Cursor::new(&mut buf[..])); |
| 138 |
/// |
| 139 |
/// let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); |
| 140 |
/// zip.start_file("hello_world.txt", options)?; |
| 141 |
/// zip.write(b"Hello, World!")?; |
| 142 |
/// |
| 143 |
/// // Apply the changes you've made. |
| 144 |
/// // Dropping the `ZipWriter` will have the same effect, but may silently fail |
| 145 |
/// zip.finish()?; |
| 146 |
/// |
| 147 |
/// # Ok(()) |
| 148 |
/// # } |
| 149 |
/// # doit().unwrap(); |
| 150 |
/// ``` |
| 151 |
#[derive(Debug)] |
| 152 |
pub struct ZipWriter<W: Write + Seek> { |
| 153 |
pub(super) inner: GenericZipWriter<W>, |
| 154 |
pub(super) files: IndexMap<Box<str>, ZipFileData>, |
| 155 |
pub(super) stats: ZipWriterStats, |
| 156 |
pub(super) writing_to_file: bool, |
| 157 |
pub(super) writing_raw: bool, |
| 158 |
pub(super) comment: Box<[u8]>, |
| 159 |
pub(super) flush_on_finish_file: bool, |
| 160 |
} |
| 161 |
} |
| 162 |
#[doc(inline)] |
| 163 |
pub use self::sealed::FileOptionExtension; |
| 164 |
use crate::result::ZipError::InvalidArchive; |
| 165 |
#[cfg(feature = "lzma")] |
| 166 |
use crate::result::ZipError::UnsupportedArchive; |
| 167 |
use crate::spec::path_to_string; |
| 168 |
use crate::unstable::LittleEndianWriteExt; |
| 169 |
use crate::write::GenericZipWriter::{Closed, Storer}; |
| 170 |
use crate::zipcrypto::ZipCryptoKeys; |
| 171 |
use crate::CompressionMethod::Stored; |
| 172 |
pub use zip_writer::ZipWriter; |
| 173 |
|
| 174 |
#[derive(Default, Debug)] |
| 175 |
struct ZipWriterStats { |
| 176 |
hasher: Hasher, |
| 177 |
start: u64, |
| 178 |
bytes_written: u64, |
| 179 |
} |
| 180 |
|
| 181 |
mod sealed { |
| 182 |
use std::sync::Arc; |
| 183 |
|
| 184 |
use super::ExtendedFileOptions; |
| 185 |
|
| 186 |
pub trait Sealed {} |
| 187 |
/// File options Extensions |
| 188 |
#[doc(hidden)] |
| 189 |
pub trait FileOptionExtension: Default + Sealed { |
| 190 |
/// Extra Data |
| 191 |
fn extra_data(&self) -> Option<&Arc<Vec<u8>>>; |
| 192 |
/// Central Extra Data |
| 193 |
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>>; |
| 194 |
} |
| 195 |
impl Sealed for () {} |
| 196 |
impl FileOptionExtension for () { |
| 197 |
fn extra_data(&self) -> Option<&Arc<Vec<u8>>> { |
| 198 |
None |
| 199 |
} |
| 200 |
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>> { |
| 201 |
None |
| 202 |
} |
| 203 |
} |
| 204 |
impl Sealed for ExtendedFileOptions {} |
| 205 |
|
| 206 |
impl FileOptionExtension for ExtendedFileOptions { |
| 207 |
fn extra_data(&self) -> Option<&Arc<Vec<u8>>> { |
| 208 |
Some(&self.extra_data) |
| 209 |
} |
| 210 |
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>> { |
| 211 |
Some(&self.central_extra_data) |
| 212 |
} |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
#[derive(Copy, Clone, Debug)] |
| 217 |
pub(crate) enum EncryptWith<'k> { |
| 218 |
#[cfg(feature = "aes-crypto")] |
| 219 |
Aes { |
| 220 |
mode: AesMode, |
| 221 |
password: &'k str, |
| 222 |
}, |
| 223 |
ZipCrypto(ZipCryptoKeys, PhantomData<&'k ()>), |
| 224 |
} |
| 225 |
|
| 226 |
#[cfg(fuzzing)] |
| 227 |
impl<'a> arbitrary::Arbitrary<'a> for EncryptWith<'a> { |
| 228 |
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { |
| 229 |
#[cfg(feature = "aes-crypto")] |
| 230 |
if bool::arbitrary(u)? { |
| 231 |
return Ok(EncryptWith::Aes { |
| 232 |
mode: AesMode::arbitrary(u)?, |
| 233 |
password: u.arbitrary::<&str>()?, |
| 234 |
}); |
| 235 |
} |
| 236 |
|
| 237 |
Ok(EncryptWith::ZipCrypto( |
| 238 |
ZipCryptoKeys::arbitrary(u)?, |
| 239 |
PhantomData, |
| 240 |
)) |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
/// Metadata for a file to be written |
| 245 |
#[derive(Clone, Debug, Copy)] |
| 246 |
pub struct FileOptions<'k, T: FileOptionExtension> { |
| 247 |
pub(crate) compression_method: CompressionMethod, |
| 248 |
pub(crate) compression_level: Option<i64>, |
| 249 |
pub(crate) last_modified_time: DateTime, |
| 250 |
pub(crate) permissions: Option<u32>, |
| 251 |
pub(crate) large_file: bool, |
| 252 |
pub(crate) encrypt_with: Option<EncryptWith<'k>>, |
| 253 |
pub(crate) extended_options: T, |
| 254 |
pub(crate) alignment: u16, |
| 255 |
#[cfg(feature = "deflate-zopfli")] |
| 256 |
pub(super) zopfli_buffer_size: Option<usize>, |
| 257 |
} |
| 258 |
/// Simple File Options. Can be copied and good for simple writing zip files |
| 259 |
pub type SimpleFileOptions = FileOptions<'static, ()>; |
| 260 |
/// Adds Extra Data and Central Extra Data. It does not implement copy. |
| 261 |
pub type FullFileOptions<'k> = FileOptions<'k, ExtendedFileOptions>; |
| 262 |
/// The Extension for Extra Data and Central Extra Data |
| 263 |
#[derive(Clone, Debug, Default)] |
| 264 |
pub struct ExtendedFileOptions { |
| 265 |
extra_data: Arc<Vec<u8>>, |
| 266 |
central_extra_data: Arc<Vec<u8>>, |
| 267 |
} |
| 268 |
|
| 269 |
#[cfg(fuzzing)] |
| 270 |
impl<'a> arbitrary::Arbitrary<'a> for FileOptions<'a, ExtendedFileOptions> { |
| 271 |
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { |
| 272 |
let mut options = FullFileOptions { |
| 273 |
compression_method: CompressionMethod::arbitrary(u)?, |
| 274 |
compression_level: if bool::arbitrary(u)? { |
| 275 |
Some(u.int_in_range(0..=24)?) |
| 276 |
} else { |
| 277 |
None |
| 278 |
}, |
| 279 |
last_modified_time: DateTime::arbitrary(u)?, |
| 280 |
permissions: Option::<u32>::arbitrary(u)?, |
| 281 |
large_file: bool::arbitrary(u)?, |
| 282 |
encrypt_with: Option::<EncryptWith>::arbitrary(u)?, |
| 283 |
alignment: u16::arbitrary(u)?, |
| 284 |
#[cfg(feature = "deflate-zopfli")] |
| 285 |
zopfli_buffer_size: None, |
| 286 |
..Default::default() |
| 287 |
}; |
| 288 |
#[cfg(feature = "deflate-zopfli")] |
| 289 |
if options.compression_method == CompressionMethod::Deflated && bool::arbitrary(u)? { |
| 290 |
options.zopfli_buffer_size = |
| 291 |
Some(if bool::arbitrary(u)? { 2 } else { 3 } << u.int_in_range(8..=20)?); |
| 292 |
} |
| 293 |
u.arbitrary_loop(Some(0), Some((u16::MAX / 4) as u32), |u| { |
| 294 |
options |
| 295 |
.add_extra_data( |
| 296 |
u16::arbitrary(u)?, |
| 297 |
&Vec::<u8>::arbitrary(u)?, |
| 298 |
bool::arbitrary(u)?, |
| 299 |
) |
| 300 |
.map_err(|_| arbitrary::Error::IncorrectFormat)?; |
| 301 |
Ok(core::ops::ControlFlow::Continue(())) |
| 302 |
})?; |
| 303 |
Ok(options) |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
impl<'k, T: FileOptionExtension> FileOptions<'k, T> { |
| 308 |
/// Set the compression method for the new file |
| 309 |
/// |
| 310 |
/// The default is `CompressionMethod::Deflated` if it is enabled. If not, |
| 311 |
/// `CompressionMethod::Bzip2` is the default if it is enabled. If neither `bzip2` nor `deflate` |
| 312 |
/// is enabled, `CompressionMethod::Zlib` is the default. If all else fails, |
| 313 |
/// `CompressionMethod::Stored` becomes the default and files are written uncompressed. |
| 314 |
#[must_use] |
| 315 |
pub const fn compression_method(mut self, method: CompressionMethod) -> Self { |
| 316 |
self.compression_method = method; |
| 317 |
self |
| 318 |
} |
| 319 |
|
| 320 |
/// Set the compression level for the new file |
| 321 |
/// |
| 322 |
/// `None` value specifies default compression level. |
| 323 |
/// |
| 324 |
/// Range of values depends on compression method: |
| 325 |
/// * `Deflated`: 10 - 264 for Zopfli, 0 - 9 for other encoders. Default is 24 if Zopfli is the |
| 326 |
/// only encoder, or 6 otherwise. |
| 327 |
/// * `Bzip2`: 0 - 9. Default is 6 |
| 328 |
/// * `Zstd`: -7 - 22, with zero being mapped to default level. Default is 3 |
| 329 |
/// * others: only `None` is allowed |
| 330 |
#[must_use] |
| 331 |
pub const fn compression_level(mut self, level: Option<i64>) -> Self { |
| 332 |
self.compression_level = level; |
| 333 |
self |
| 334 |
} |
| 335 |
|
| 336 |
/// Set the last modified time |
| 337 |
/// |
| 338 |
/// The default is the current timestamp if the 'time' feature is enabled, and 1980-01-01 |
| 339 |
/// otherwise |
| 340 |
#[must_use] |
| 341 |
pub const fn last_modified_time(mut self, mod_time: DateTime) -> Self { |
| 342 |
self.last_modified_time = mod_time; |
| 343 |
self |
| 344 |
} |
| 345 |
|
| 346 |
/// Set the permissions for the new file. |
| 347 |
/// |
| 348 |
/// The format is represented with unix-style permissions. |
| 349 |
/// The default is `0o644`, which represents `rw-r--r--` for files, |
| 350 |
/// and `0o755`, which represents `rwxr-xr-x` for directories. |
| 351 |
/// |
| 352 |
/// This method only preserves the file permissions bits (via a `& 0o777`) and discards |
| 353 |
/// higher file mode bits. So it cannot be used to denote an entry as a directory, |
| 354 |
/// symlink, or other special file type. |
| 355 |
#[must_use] |
| 356 |
pub const fn unix_permissions(mut self, mode: u32) -> Self { |
| 357 |
self.permissions = Some(mode & 0o777); |
| 358 |
self |
| 359 |
} |
| 360 |
|
| 361 |
/// Set whether the new file's compressed and uncompressed size is less than 4 GiB. |
| 362 |
/// |
| 363 |
/// If set to `false` and the file exceeds the limit, an I/O error is thrown and the file is |
| 364 |
/// aborted. If set to `true`, readers will require ZIP64 support and if the file does not |
| 365 |
/// exceed the limit, 20 B are wasted. The default is `false`. |
| 366 |
#[must_use] |
| 367 |
pub const fn large_file(mut self, large: bool) -> Self { |
| 368 |
self.large_file = large; |
| 369 |
self |
| 370 |
} |
| 371 |
|
| 372 |
pub(crate) fn with_deprecated_encryption(self, password: &[u8]) -> FileOptions<'static, T> { |
| 373 |
FileOptions { |
| 374 |
encrypt_with: Some(EncryptWith::ZipCrypto( |
| 375 |
ZipCryptoKeys::derive(password), |
| 376 |
PhantomData, |
| 377 |
)), |
| 378 |
..self |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
/// Set the AES encryption parameters. |
| 383 |
#[cfg(feature = "aes-crypto")] |
| 384 |
pub fn with_aes_encryption(self, mode: AesMode, password: &str) -> FileOptions<'_, T> { |
| 385 |
FileOptions { |
| 386 |
encrypt_with: Some(EncryptWith::Aes { mode, password }), |
| 387 |
..self |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
/// Sets the size of the buffer used to hold the next block that Zopfli will compress. The |
| 392 |
/// larger the buffer, the more effective the compression, but the more memory is required. |
| 393 |
/// A value of `None` indicates no buffer, which is recommended only when all non-empty writes |
| 394 |
/// are larger than about 32 KiB. |
| 395 |
#[must_use] |
| 396 |
#[cfg(feature = "deflate-zopfli")] |
| 397 |
pub const fn with_zopfli_buffer(mut self, size: Option<usize>) -> Self { |
| 398 |
self.zopfli_buffer_size = size; |
| 399 |
self |
| 400 |
} |
| 401 |
|
| 402 |
/// Returns the compression level currently set. |
| 403 |
pub const fn get_compression_level(&self) -> Option<i64> { |
| 404 |
self.compression_level |
| 405 |
} |
| 406 |
/// Sets the alignment to the given number of bytes. |
| 407 |
#[must_use] |
| 408 |
pub const fn with_alignment(mut self, alignment: u16) -> Self { |
| 409 |
self.alignment = alignment; |
| 410 |
self |
| 411 |
} |
| 412 |
} |
| 413 |
impl<'k> FileOptions<'k, ExtendedFileOptions> { |
| 414 |
/// Adds an extra data field. |
| 415 |
pub fn add_extra_data( |
| 416 |
&mut self, |
| 417 |
header_id: u16, |
| 418 |
data: &[u8], |
| 419 |
central_only: bool, |
| 420 |
) -> ZipResult<()> { |
| 421 |
validate_extra_data(header_id, data)?; |
| 422 |
let len = data.len() + 4; |
| 423 |
if self.extended_options.extra_data.len() |
| 424 |
+ self.extended_options.central_extra_data.len() |
| 425 |
+ len |
| 426 |
> u16::MAX as usize |
| 427 |
{ |
| 428 |
Err(InvalidArchive( |
| 429 |
"Extra data field would be longer than allowed", |
| 430 |
)) |
| 431 |
} else { |
| 432 |
let field = if central_only { |
| 433 |
&mut self.extended_options.central_extra_data |
| 434 |
} else { |
| 435 |
&mut self.extended_options.extra_data |
| 436 |
}; |
| 437 |
let vec = Arc::get_mut(field); |
| 438 |
let vec = match vec { |
| 439 |
Some(exclusive) => exclusive, |
| 440 |
None => { |
| 441 |
*field = Arc::new(field.to_vec()); |
| 442 |
Arc::get_mut(field).unwrap() |
| 443 |
} |
| 444 |
}; |
| 445 |
vec.reserve_exact(data.len() + 4); |
| 446 |
vec.write_u16_le(header_id)?; |
| 447 |
vec.write_u16_le(data.len() as u16)?; |
| 448 |
vec.write_all(data)?; |
| 449 |
Ok(()) |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
/// Removes the extra data fields. |
| 454 |
#[must_use] |
| 455 |
pub fn clear_extra_data(mut self) -> Self { |
| 456 |
if self.extended_options.extra_data.len() > 0 { |
| 457 |
self.extended_options.extra_data = Arc::new(vec![]); |
| 458 |
} |
| 459 |
if self.extended_options.central_extra_data.len() > 0 { |
| 460 |
self.extended_options.central_extra_data = Arc::new(vec![]); |
| 461 |
} |
| 462 |
self |
| 463 |
} |
| 464 |
} |
| 465 |
impl<'k, T: FileOptionExtension> Default for FileOptions<'k, T> { |
| 466 |
/// Construct a new FileOptions object |
| 467 |
fn default() -> Self { |
| 468 |
Self { |
| 469 |
compression_method: Default::default(), |
| 470 |
compression_level: None, |
| 471 |
last_modified_time: DateTime::default_for_write(), |
| 472 |
permissions: None, |
| 473 |
large_file: false, |
| 474 |
encrypt_with: None, |
| 475 |
extended_options: T::default(), |
| 476 |
alignment: 1, |
| 477 |
#[cfg(feature = "deflate-zopfli")] |
| 478 |
zopfli_buffer_size: Some(1 << 15), |
| 479 |
} |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
impl<W: Write + Seek> Write for ZipWriter<W> { |
| 484 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 485 |
if !self.writing_to_file { |
| 486 |
return Err(io::Error::new( |
| 487 |
io::ErrorKind::Other, |
| 488 |
"No file has been started", |
| 489 |
)); |
| 490 |
} |
| 491 |
if buf.is_empty() { |
| 492 |
return Ok(0); |
| 493 |
} |
| 494 |
match self.inner.ref_mut() { |
| 495 |
Some(ref mut w) => { |
| 496 |
let write_result = w.write(buf); |
| 497 |
if let Ok(count) = write_result { |
| 498 |
self.stats.update(&buf[0..count]); |
| 499 |
if self.stats.bytes_written > spec::ZIP64_BYTES_THR |
| 500 |
&& !self.files.last_mut().unwrap().1.large_file |
| 501 |
{ |
| 502 |
self.abort_file().unwrap(); |
| 503 |
return Err(io::Error::new( |
| 504 |
io::ErrorKind::Other, |
| 505 |
"Large file option has not been set", |
| 506 |
)); |
| 507 |
} |
| 508 |
} |
| 509 |
write_result |
| 510 |
} |
| 511 |
None => Err(io::Error::new( |
| 512 |
io::ErrorKind::BrokenPipe, |
| 513 |
"write(): ZipWriter was already closed", |
| 514 |
)), |
| 515 |
} |
| 516 |
} |
| 517 |
|
| 518 |
fn flush(&mut self) -> io::Result<()> { |
| 519 |
match self.inner.ref_mut() { |
| 520 |
Some(ref mut w) => w.flush(), |
| 521 |
None => Err(io::Error::new( |
| 522 |
io::ErrorKind::BrokenPipe, |
| 523 |
"flush(): ZipWriter was already closed", |
| 524 |
)), |
| 525 |
} |
| 526 |
} |
| 527 |
} |
| 528 |
|
| 529 |
impl ZipWriterStats { |
| 530 |
fn update(&mut self, buf: &[u8]) { |
| 531 |
self.hasher.update(buf); |
| 532 |
self.bytes_written += buf.len() as u64; |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
impl<A: Read + Write + Seek> ZipWriter<A> { |
| 537 |
/// Initializes the archive from an existing ZIP archive, making it ready for append. |
| 538 |
/// |
| 539 |
/// This uses a default configuration to initially read the archive. |
| 540 |
pub fn new_append(readwriter: A) -> ZipResult<ZipWriter<A>> { |
| 541 |
Self::new_append_with_config(Default::default(), readwriter) |
| 542 |
} |
| 543 |
|
| 544 |
/// Initializes the archive from an existing ZIP archive, making it ready for append. |
| 545 |
/// |
| 546 |
/// This uses the given read configuration to initially read the archive. |
| 547 |
pub fn new_append_with_config(config: Config, mut readwriter: A) -> ZipResult<ZipWriter<A>> { |
| 548 |
let (footer, cde_start_pos) = |
| 549 |
spec::Zip32CentralDirectoryEnd::find_and_parse(&mut readwriter)?; |
| 550 |
let metadata = ZipArchive::get_metadata(config, &mut readwriter, &footer, cde_start_pos)?; |
| 551 |
|
| 552 |
Ok(ZipWriter { |
| 553 |
inner: Storer(MaybeEncrypted::Unencrypted(readwriter)), |
| 554 |
files: metadata.files, |
| 555 |
stats: Default::default(), |
| 556 |
writing_to_file: false, |
| 557 |
comment: footer.zip_file_comment, |
| 558 |
writing_raw: true, // avoid recomputing the last file's header |
| 559 |
flush_on_finish_file: false, |
| 560 |
}) |
| 561 |
} |
| 562 |
|
| 563 |
/// `flush_on_finish_file` is designed to support a streaming `inner` that may unload flushed |
| 564 |
/// bytes. It flushes a file's header and body once it starts writing another file. A ZipWriter |
| 565 |
/// will not try to seek back into where a previous file was written unless |
| 566 |
/// either [`ZipWriter::abort_file`] is called while [`ZipWriter::is_writing_file`] returns |
| 567 |
/// false, or [`ZipWriter::deep_copy_file`] is called. In the latter case, it will only need to |
| 568 |
/// read previously-written files and not overwrite them. |
| 569 |
/// |
| 570 |
/// Note: when using an `inner` that cannot overwrite flushed bytes, do not wrap it in a |
| 571 |
/// [std::io::BufWriter], because that has a [Seek::seek] method that implicitly calls |
| 572 |
/// [BufWriter::flush], and ZipWriter needs to seek backward to update each file's header with |
| 573 |
/// the size and checksum after writing the body. |
| 574 |
/// |
| 575 |
/// This setting is false by default. |
| 576 |
pub fn set_flush_on_finish_file(&mut self, flush_on_finish_file: bool) { |
| 577 |
self.flush_on_finish_file = flush_on_finish_file; |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
impl<A: Read + Write + Seek> ZipWriter<A> { |
| 582 |
/// Adds another copy of a file already in this archive. This will produce a larger but more |
| 583 |
/// widely-compatible archive compared to [Self::shallow_copy_file]. Does not copy alignment. |
| 584 |
pub fn deep_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()> { |
| 585 |
self.finish_file()?; |
| 586 |
let write_position = self.inner.get_plain().stream_position()?; |
| 587 |
let src_index = self.index_by_name(src_name)?; |
| 588 |
let src_data = &self.files[src_index]; |
| 589 |
let data_start = *src_data.data_start.get().unwrap_or(&0); |
| 590 |
let compressed_size = src_data.compressed_size; |
| 591 |
debug_assert!(compressed_size <= write_position - data_start); |
| 592 |
let uncompressed_size = src_data.uncompressed_size; |
| 593 |
|
| 594 |
let raw_values = ZipRawValues { |
| 595 |
crc32: src_data.crc32, |
| 596 |
compressed_size, |
| 597 |
uncompressed_size, |
| 598 |
}; |
| 599 |
let mut reader = BufReader::new(ZipFileReader::Raw(find_content( |
| 600 |
src_data, |
| 601 |
self.inner.get_plain(), |
| 602 |
)?)); |
| 603 |
let mut copy = Vec::with_capacity(compressed_size as usize); |
| 604 |
reader.read_to_end(&mut copy)?; |
| 605 |
drop(reader); |
| 606 |
self.inner |
| 607 |
.get_plain() |
| 608 |
.seek(SeekFrom::Start(write_position))?; |
| 609 |
if src_data.extra_field.is_some() || src_data.central_extra_field.is_some() { |
| 610 |
let mut options = FileOptions::<ExtendedFileOptions> { |
| 611 |
compression_method: src_data.compression_method, |
| 612 |
compression_level: src_data.compression_level, |
| 613 |
last_modified_time: src_data |
| 614 |
.last_modified_time |
| 615 |
.unwrap_or_else(DateTime::default_for_write), |
| 616 |
permissions: src_data.unix_mode(), |
| 617 |
large_file: src_data.large_file, |
| 618 |
encrypt_with: None, |
| 619 |
extended_options: ExtendedFileOptions { |
| 620 |
extra_data: src_data.extra_field.clone().unwrap_or_default(), |
| 621 |
central_extra_data: src_data.central_extra_field.clone().unwrap_or_default(), |
| 622 |
}, |
| 623 |
alignment: 1, |
| 624 |
#[cfg(feature = "deflate-zopfli")] |
| 625 |
zopfli_buffer_size: None, |
| 626 |
}; |
| 627 |
if let Some(perms) = src_data.unix_mode() { |
| 628 |
options = options.unix_permissions(perms); |
| 629 |
} |
| 630 |
Self::normalize_options(&mut options); |
| 631 |
self.start_entry(dest_name, options, Some(raw_values))?; |
| 632 |
} else { |
| 633 |
let mut options = FileOptions::<()> { |
| 634 |
compression_method: src_data.compression_method, |
| 635 |
compression_level: src_data.compression_level, |
| 636 |
last_modified_time: src_data |
| 637 |
.last_modified_time |
| 638 |
.unwrap_or_else(DateTime::default_for_write), |
| 639 |
permissions: src_data.unix_mode(), |
| 640 |
large_file: src_data.large_file, |
| 641 |
encrypt_with: None, |
| 642 |
extended_options: (), |
| 643 |
alignment: 1, |
| 644 |
#[cfg(feature = "deflate-zopfli")] |
| 645 |
zopfli_buffer_size: None, |
| 646 |
}; |
| 647 |
if let Some(perms) = src_data.unix_mode() { |
| 648 |
options = options.unix_permissions(perms); |
| 649 |
} |
| 650 |
Self::normalize_options(&mut options); |
| 651 |
self.start_entry(dest_name, options, Some(raw_values))?; |
| 652 |
} |
| 653 |
|
| 654 |
self.writing_to_file = true; |
| 655 |
self.writing_raw = true; |
| 656 |
if let Err(e) = self.write_all(©) { |
| 657 |
self.abort_file().unwrap(); |
| 658 |
return Err(e.into()); |
| 659 |
} |
| 660 |
self.finish_file() |
| 661 |
} |
| 662 |
|
| 663 |
/// Like `deep_copy_file`, but uses Path arguments. |
| 664 |
/// |
| 665 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 666 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 667 |
/// root. |
| 668 |
pub fn deep_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>( |
| 669 |
&mut self, |
| 670 |
src_path: T, |
| 671 |
dest_path: U, |
| 672 |
) -> ZipResult<()> { |
| 673 |
self.deep_copy_file(&path_to_string(src_path), &path_to_string(dest_path)) |
| 674 |
} |
| 675 |
|
| 676 |
/// Write the zip file into the backing stream, then produce a readable archive of that data. |
| 677 |
/// |
| 678 |
/// This method avoids parsing the central directory records at the end of the stream for |
| 679 |
/// a slight performance improvement over running [`ZipArchive::new()`] on the output of |
| 680 |
/// [`Self::finish()`]. |
| 681 |
/// |
| 682 |
///``` |
| 683 |
/// # fn main() -> Result<(), zip::result::ZipError> { |
| 684 |
/// use std::io::{Cursor, prelude::*}; |
| 685 |
/// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions}; |
| 686 |
/// |
| 687 |
/// let buf = Cursor::new(Vec::new()); |
| 688 |
/// let mut zip = ZipWriter::new(buf); |
| 689 |
/// let options = SimpleFileOptions::default(); |
| 690 |
/// zip.start_file("a.txt", options)?; |
| 691 |
/// zip.write_all(b"hello\n")?; |
| 692 |
/// |
| 693 |
/// let mut zip = zip.finish_into_readable()?; |
| 694 |
/// let mut s: String = String::new(); |
| 695 |
/// zip.by_name("a.txt")?.read_to_string(&mut s)?; |
| 696 |
/// assert_eq!(s, "hello\n"); |
| 697 |
/// # Ok(()) |
| 698 |
/// # } |
| 699 |
///``` |
| 700 |
pub fn finish_into_readable(mut self) -> ZipResult<ZipArchive<A>> { |
| 701 |
let central_start = self.finalize()?; |
| 702 |
let inner = mem::replace(&mut self.inner, Closed).unwrap(); |
| 703 |
let comment = mem::take(&mut self.comment); |
| 704 |
let files = mem::take(&mut self.files); |
| 705 |
let archive = ZipArchive::from_finalized_writer(files, comment, inner, central_start)?; |
| 706 |
Ok(archive) |
| 707 |
} |
| 708 |
} |
| 709 |
|
| 710 |
impl<W: Write + Seek> ZipWriter<W> { |
| 711 |
/// Initializes the archive. |
| 712 |
/// |
| 713 |
/// Before writing to this object, the [`ZipWriter::start_file`] function should be called. |
| 714 |
/// After a successful write, the file remains open for writing. After a failed write, call |
| 715 |
/// [`ZipWriter::is_writing_file`] to determine if the file remains open. |
| 716 |
pub fn new(inner: W) -> ZipWriter<W> { |
| 717 |
ZipWriter { |
| 718 |
inner: Storer(MaybeEncrypted::Unencrypted(inner)), |
| 719 |
files: IndexMap::new(), |
| 720 |
stats: Default::default(), |
| 721 |
writing_to_file: false, |
| 722 |
writing_raw: false, |
| 723 |
comment: Box::new([]), |
| 724 |
flush_on_finish_file: false, |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
/// Returns true if a file is currently open for writing. |
| 729 |
pub const fn is_writing_file(&self) -> bool { |
| 730 |
self.writing_to_file && !self.inner.is_closed() |
| 731 |
} |
| 732 |
|
| 733 |
/// Set ZIP archive comment. |
| 734 |
pub fn set_comment<S>(&mut self, comment: S) |
| 735 |
where |
| 736 |
S: Into<Box<str>>, |
| 737 |
{ |
| 738 |
self.set_raw_comment(comment.into().into_boxed_bytes()) |
| 739 |
} |
| 740 |
|
| 741 |
/// Set ZIP archive comment. |
| 742 |
/// |
| 743 |
/// This sets the raw bytes of the comment. The comment |
| 744 |
/// is typically expected to be encoded in UTF-8. |
| 745 |
pub fn set_raw_comment(&mut self, comment: Box<[u8]>) { |
| 746 |
self.comment = comment; |
| 747 |
} |
| 748 |
|
| 749 |
/// Get ZIP archive comment. |
| 750 |
pub fn get_comment(&mut self) -> Result<&str, Utf8Error> { |
| 751 |
from_utf8(self.get_raw_comment()) |
| 752 |
} |
| 753 |
|
| 754 |
/// Get ZIP archive comment. |
| 755 |
/// |
| 756 |
/// This returns the raw bytes of the comment. The comment |
| 757 |
/// is typically expected to be encoded in UTF-8. |
| 758 |
pub const fn get_raw_comment(&self) -> &[u8] { |
| 759 |
&self.comment |
| 760 |
} |
| 761 |
|
| 762 |
/// Start a new file for with the requested options. |
| 763 |
fn start_entry<S, SToOwned, T: FileOptionExtension>( |
| 764 |
&mut self, |
| 765 |
name: S, |
| 766 |
options: FileOptions<T>, |
| 767 |
raw_values: Option<ZipRawValues>, |
| 768 |
) -> ZipResult<()> |
| 769 |
where |
| 770 |
S: Into<Box<str>> + ToOwned<Owned = SToOwned>, |
| 771 |
SToOwned: Into<Box<str>>, |
| 772 |
{ |
| 773 |
self.finish_file()?; |
| 774 |
|
| 775 |
let raw_values = raw_values.unwrap_or(ZipRawValues { |
| 776 |
crc32: 0, |
| 777 |
compressed_size: 0, |
| 778 |
uncompressed_size: 0, |
| 779 |
}); |
| 780 |
|
| 781 |
#[allow(unused_mut)] |
| 782 |
let mut extra_field = options.extended_options.extra_data().cloned(); |
| 783 |
|
| 784 |
// Write AES encryption extra data. |
| 785 |
#[allow(unused_mut)] |
| 786 |
let mut aes_extra_data_start = 0; |
| 787 |
#[cfg(feature = "aes-crypto")] |
| 788 |
if let Some(EncryptWith::Aes { .. }) = options.encrypt_with { |
| 789 |
const AES_DUMMY_EXTRA_DATA: [u8; 11] = [ |
| 790 |
0x01, 0x99, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, |
| 791 |
]; |
| 792 |
|
| 793 |
let extra_data = extra_field.get_or_insert_with(Default::default); |
| 794 |
let extra_data = match Arc::get_mut(extra_data) { |
| 795 |
Some(exclusive) => exclusive, |
| 796 |
None => { |
| 797 |
let new = Arc::new(extra_data.to_vec()); |
| 798 |
Arc::get_mut(extra_field.insert(new)).unwrap() |
| 799 |
} |
| 800 |
}; |
| 801 |
|
| 802 |
if extra_data.len() + AES_DUMMY_EXTRA_DATA.len() > u16::MAX as usize { |
| 803 |
let _ = self.abort_file(); |
| 804 |
return Err(InvalidArchive("Extra data field is too large")); |
| 805 |
} |
| 806 |
|
| 807 |
aes_extra_data_start = extra_data.len() as u64; |
| 808 |
|
| 809 |
// We write zero bytes for now since we need to update the data when finishing the |
| 810 |
// file. |
| 811 |
extra_data.write_all(&AES_DUMMY_EXTRA_DATA)?; |
| 812 |
} |
| 813 |
|
| 814 |
{ |
| 815 |
let header_start = self.inner.get_plain().stream_position()?; |
| 816 |
|
| 817 |
let (compression_method, aes_mode) = match options.encrypt_with { |
| 818 |
#[cfg(feature = "aes-crypto")] |
| 819 |
Some(EncryptWith::Aes { mode, .. }) => ( |
| 820 |
CompressionMethod::Aes, |
| 821 |
Some((mode, AesVendorVersion::Ae2, options.compression_method)), |
| 822 |
), |
| 823 |
_ => (options.compression_method, None), |
| 824 |
}; |
| 825 |
|
| 826 |
let mut file = ZipFileData::initialize_local_block( |
| 827 |
name, |
| 828 |
&options, |
| 829 |
raw_values, |
| 830 |
header_start, |
| 831 |
None, |
| 832 |
aes_extra_data_start, |
| 833 |
compression_method, |
| 834 |
aes_mode, |
| 835 |
extra_field, |
| 836 |
); |
| 837 |
file.version_made_by = file.version_made_by.max(file.version_needed() as u8); |
| 838 |
let index = self.insert_file_data(file)?; |
| 839 |
let file = &mut self.files[index]; |
| 840 |
let writer = self.inner.get_plain(); |
| 841 |
|
| 842 |
let block = match file.local_block() { |
| 843 |
Ok(block) => block, |
| 844 |
Err(e) => { |
| 845 |
let _ = self.abort_file(); |
| 846 |
return Err(e); |
| 847 |
} |
| 848 |
}; |
| 849 |
match block.write(writer) { |
| 850 |
Ok(()) => (), |
| 851 |
Err(e) => { |
| 852 |
let _ = self.abort_file(); |
| 853 |
return Err(e); |
| 854 |
} |
| 855 |
} |
| 856 |
// file name |
| 857 |
writer.write_all(&file.file_name_raw)?; |
| 858 |
// zip64 extra field |
| 859 |
if file.large_file { |
| 860 |
write_local_zip64_extra_field(writer, file)?; |
| 861 |
} |
| 862 |
if let Some(extra_field) = &file.extra_field { |
| 863 |
file.extra_data_start = Some(writer.stream_position()?); |
| 864 |
writer.write_all(extra_field)?; |
| 865 |
} |
| 866 |
let mut header_end = writer.stream_position()?; |
| 867 |
if options.alignment > 1 { |
| 868 |
let align = options.alignment as u64; |
| 869 |
let unaligned_header_bytes = header_end % align; |
| 870 |
if unaligned_header_bytes != 0 { |
| 871 |
let pad_length = (align - unaligned_header_bytes) as usize; |
| 872 |
let Some(new_extra_field_length) = |
| 873 |
(pad_length as u16).checked_add(block.extra_field_length) |
| 874 |
else { |
| 875 |
let _ = self.abort_file(); |
| 876 |
return Err(InvalidArchive( |
| 877 |
"Extra data field would be larger than allowed after aligning", |
| 878 |
)); |
| 879 |
}; |
| 880 |
if pad_length >= 4 { |
| 881 |
// Add an extra field to the extra_data, per APPNOTE 4.6.11 |
| 882 |
let mut pad_body = vec![0; pad_length - 4]; |
| 883 |
if pad_body.len() >= 2 { |
| 884 |
[pad_body[0], pad_body[1]] = options.alignment.to_le_bytes(); |
| 885 |
} |
| 886 |
writer.write_u16_le(0xa11e)?; |
| 887 |
writer |
| 888 |
.write_u16_le(pad_body.len() as u16) |
| 889 |
.map_err(ZipError::from)?; |
| 890 |
writer.write_all(&pad_body).map_err(ZipError::from)?; |
| 891 |
} else { |
| 892 |
// extra_data padding is too small for an extra field header, so pad with |
| 893 |
// zeroes |
| 894 |
let pad = vec![0; pad_length]; |
| 895 |
writer.write_all(&pad).map_err(ZipError::from)?; |
| 896 |
} |
| 897 |
header_end = writer.stream_position()?; |
| 898 |
|
| 899 |
// Update extra field length in local file header. |
| 900 |
writer.seek(SeekFrom::Start(file.header_start + 28))?; |
| 901 |
writer.write_u16_le(new_extra_field_length)?; |
| 902 |
writer.seek(SeekFrom::Start(header_end))?; |
| 903 |
debug_assert_eq!(header_end % align, 0); |
| 904 |
} |
| 905 |
} |
| 906 |
match options.encrypt_with { |
| 907 |
#[cfg(feature = "aes-crypto")] |
| 908 |
Some(EncryptWith::Aes { mode, password }) => { |
| 909 |
let aeswriter = AesWriter::new( |
| 910 |
mem::replace(&mut self.inner, GenericZipWriter::Closed).unwrap(), |
| 911 |
mode, |
| 912 |
password.as_bytes(), |
| 913 |
)?; |
| 914 |
self.inner = GenericZipWriter::Storer(MaybeEncrypted::Aes(aeswriter)); |
| 915 |
} |
| 916 |
Some(EncryptWith::ZipCrypto(keys, ..)) => { |
| 917 |
let mut zipwriter = crate::zipcrypto::ZipCryptoWriter { |
| 918 |
writer: mem::replace(&mut self.inner, Closed).unwrap(), |
| 919 |
buffer: vec![], |
| 920 |
keys, |
| 921 |
}; |
| 922 |
let crypto_header = [0u8; 12]; |
| 923 |
|
| 924 |
zipwriter.write_all(&crypto_header)?; |
| 925 |
header_end = zipwriter.writer.stream_position()?; |
| 926 |
self.inner = Storer(MaybeEncrypted::ZipCrypto(zipwriter)); |
| 927 |
} |
| 928 |
None => {} |
| 929 |
} |
| 930 |
self.stats.start = header_end; |
| 931 |
debug_assert!(file.data_start.get().is_none()); |
| 932 |
file.data_start.get_or_init(|| header_end); |
| 933 |
self.writing_to_file = true; |
| 934 |
self.stats.bytes_written = 0; |
| 935 |
self.stats.hasher = Hasher::new(); |
| 936 |
} |
| 937 |
Ok(()) |
| 938 |
} |
| 939 |
|
| 940 |
fn insert_file_data(&mut self, file: ZipFileData) -> ZipResult<usize> { |
| 941 |
if self.files.contains_key(&file.file_name) { |
| 942 |
return Err(InvalidArchive("Duplicate filename")); |
| 943 |
} |
| 944 |
let name = file.file_name.to_owned(); |
| 945 |
self.files.insert(name.clone(), file); |
| 946 |
Ok(self.files.get_index_of(&name).unwrap()) |
| 947 |
} |
| 948 |
|
| 949 |
fn finish_file(&mut self) -> ZipResult<()> { |
| 950 |
if !self.writing_to_file { |
| 951 |
return Ok(()); |
| 952 |
} |
| 953 |
|
| 954 |
let make_plain_writer = self.inner.prepare_next_writer( |
| 955 |
Stored, |
| 956 |
None, |
| 957 |
#[cfg(feature = "deflate-zopfli")] |
| 958 |
None, |
| 959 |
)?; |
| 960 |
self.inner.switch_to(make_plain_writer)?; |
| 961 |
self.switch_to_non_encrypting_writer()?; |
| 962 |
let writer = self.inner.get_plain(); |
| 963 |
|
| 964 |
if !self.writing_raw { |
| 965 |
let file = match self.files.last_mut() { |
| 966 |
None => return Ok(()), |
| 967 |
Some((_, f)) => f, |
| 968 |
}; |
| 969 |
file.uncompressed_size = self.stats.bytes_written; |
| 970 |
|
| 971 |
let file_end = writer.stream_position()?; |
| 972 |
debug_assert!(file_end >= self.stats.start); |
| 973 |
file.compressed_size = file_end - self.stats.start; |
| 974 |
|
| 975 |
file.crc32 = self.stats.hasher.clone().finalize(); |
| 976 |
if let Some(aes_mode) = &mut file.aes_mode { |
| 977 |
// We prefer using AE-1 which provides an extra CRC check, but for small files we |
| 978 |
// switch to AE-2 to prevent being able to use the CRC value to to reconstruct the |
| 979 |
// unencrypted contents. |
| 980 |
// |
| 981 |
// C.f. https://www.winzip.com/en/support/aes-encryption/#crc-faq |
| 982 |
aes_mode.1 = if self.stats.bytes_written < 20 { |
| 983 |
file.crc32 = 0; |
| 984 |
AesVendorVersion::Ae2 |
| 985 |
} else { |
| 986 |
AesVendorVersion::Ae1 |
| 987 |
} |
| 988 |
} |
| 989 |
|
| 990 |
update_aes_extra_data(writer, file)?; |
| 991 |
update_local_file_header(writer, file)?; |
| 992 |
writer.seek(SeekFrom::Start(file_end))?; |
| 993 |
} |
| 994 |
if self.flush_on_finish_file { |
| 995 |
if let Err(e) = writer.flush() { |
| 996 |
self.abort_file()?; |
| 997 |
return Err(e.into()); |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
self.writing_to_file = false; |
| 1002 |
Ok(()) |
| 1003 |
} |
| 1004 |
|
| 1005 |
fn switch_to_non_encrypting_writer(&mut self) -> Result<(), ZipError> { |
| 1006 |
match mem::replace(&mut self.inner, Closed) { |
| 1007 |
#[cfg(feature = "aes-crypto")] |
| 1008 |
Storer(MaybeEncrypted::Aes(writer)) => { |
| 1009 |
self.inner = Storer(MaybeEncrypted::Unencrypted(writer.finish()?)); |
| 1010 |
} |
| 1011 |
Storer(MaybeEncrypted::ZipCrypto(writer)) => { |
| 1012 |
let crc32 = self.stats.hasher.clone().finalize(); |
| 1013 |
self.inner = Storer(MaybeEncrypted::Unencrypted(writer.finish(crc32)?)) |
| 1014 |
} |
| 1015 |
Storer(MaybeEncrypted::Unencrypted(w)) => { |
| 1016 |
self.inner = Storer(MaybeEncrypted::Unencrypted(w)) |
| 1017 |
} |
| 1018 |
_ => unreachable!(), |
| 1019 |
} |
| 1020 |
Ok(()) |
| 1021 |
} |
| 1022 |
|
| 1023 |
/// Removes the file currently being written from the archive if there is one, or else removes |
| 1024 |
/// the file most recently written. |
| 1025 |
pub fn abort_file(&mut self) -> ZipResult<()> { |
| 1026 |
let (_, last_file) = self.files.pop().ok_or(ZipError::FileNotFound)?; |
| 1027 |
let make_plain_writer = self.inner.prepare_next_writer( |
| 1028 |
Stored, |
| 1029 |
None, |
| 1030 |
#[cfg(feature = "deflate-zopfli")] |
| 1031 |
None, |
| 1032 |
)?; |
| 1033 |
self.inner.switch_to(make_plain_writer)?; |
| 1034 |
self.switch_to_non_encrypting_writer()?; |
| 1035 |
// Make sure this is the last file, and that no shallow copies of it remain; otherwise we'd |
| 1036 |
// overwrite a valid file and corrupt the archive |
| 1037 |
let rewind_safe: bool = match last_file.data_start.get() { |
| 1038 |
None => self.files.is_empty(), |
| 1039 |
Some(last_file_start) => self.files.values().all(|file| { |
| 1040 |
file.data_start |
| 1041 |
.get() |
| 1042 |
.is_some_and(|start| start < last_file_start) |
| 1043 |
}), |
| 1044 |
}; |
| 1045 |
if rewind_safe { |
| 1046 |
self.inner |
| 1047 |
.get_plain() |
| 1048 |
.seek(SeekFrom::Start(last_file.header_start))?; |
| 1049 |
} |
| 1050 |
self.writing_to_file = false; |
| 1051 |
Ok(()) |
| 1052 |
} |
| 1053 |
|
| 1054 |
/// Create a file in the archive and start writing its' contents. The file must not have the |
| 1055 |
/// same name as a file already in the archive. |
| 1056 |
/// |
| 1057 |
/// The data should be written using the [`Write`] implementation on this [`ZipWriter`] |
| 1058 |
pub fn start_file<S, T: FileOptionExtension, SToOwned>( |
| 1059 |
&mut self, |
| 1060 |
name: S, |
| 1061 |
mut options: FileOptions<T>, |
| 1062 |
) -> ZipResult<()> |
| 1063 |
where |
| 1064 |
S: Into<Box<str>> + ToOwned<Owned = SToOwned>, |
| 1065 |
SToOwned: Into<Box<str>>, |
| 1066 |
{ |
| 1067 |
Self::normalize_options(&mut options); |
| 1068 |
let make_new_self = self.inner.prepare_next_writer( |
| 1069 |
options.compression_method, |
| 1070 |
options.compression_level, |
| 1071 |
#[cfg(feature = "deflate-zopfli")] |
| 1072 |
options.zopfli_buffer_size, |
| 1073 |
)?; |
| 1074 |
self.start_entry(name, options, None)?; |
| 1075 |
if let Err(e) = self.inner.switch_to(make_new_self) { |
| 1076 |
self.abort_file().unwrap(); |
| 1077 |
return Err(e); |
| 1078 |
} |
| 1079 |
self.writing_raw = false; |
| 1080 |
Ok(()) |
| 1081 |
} |
| 1082 |
|
| 1083 |
/* TODO: link to/use Self::finish_into_readable() from https://github.com/zip-rs/zip/pull/400 in |
| 1084 |
* this docstring. */ |
| 1085 |
/// Copy over the entire contents of another archive verbatim. |
| 1086 |
/// |
| 1087 |
/// This method extracts file metadata from the `source` archive, then simply performs a single |
| 1088 |
/// big [`io::copy()`](io::copy) to transfer all the actual file contents without any |
| 1089 |
/// decompression or decryption. This is more performant than the equivalent operation of |
| 1090 |
/// calling [`Self::raw_copy_file()`] for each entry from the `source` archive in sequence. |
| 1091 |
/// |
| 1092 |
///``` |
| 1093 |
/// # fn main() -> Result<(), zip::result::ZipError> { |
| 1094 |
/// use std::io::{Cursor, prelude::*}; |
| 1095 |
/// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions}; |
| 1096 |
/// |
| 1097 |
/// let buf = Cursor::new(Vec::new()); |
| 1098 |
/// let mut zip = ZipWriter::new(buf); |
| 1099 |
/// zip.start_file("a.txt", SimpleFileOptions::default())?; |
| 1100 |
/// zip.write_all(b"hello\n")?; |
| 1101 |
/// let src = ZipArchive::new(zip.finish()?)?; |
| 1102 |
/// |
| 1103 |
/// let buf = Cursor::new(Vec::new()); |
| 1104 |
/// let mut zip = ZipWriter::new(buf); |
| 1105 |
/// zip.start_file("b.txt", SimpleFileOptions::default())?; |
| 1106 |
/// zip.write_all(b"hey\n")?; |
| 1107 |
/// let src2 = ZipArchive::new(zip.finish()?)?; |
| 1108 |
/// |
| 1109 |
/// let buf = Cursor::new(Vec::new()); |
| 1110 |
/// let mut zip = ZipWriter::new(buf); |
| 1111 |
/// zip.merge_archive(src)?; |
| 1112 |
/// zip.merge_archive(src2)?; |
| 1113 |
/// let mut result = ZipArchive::new(zip.finish()?)?; |
| 1114 |
/// |
| 1115 |
/// let mut s: String = String::new(); |
| 1116 |
/// result.by_name("a.txt")?.read_to_string(&mut s)?; |
| 1117 |
/// assert_eq!(s, "hello\n"); |
| 1118 |
/// s.clear(); |
| 1119 |
/// result.by_name("b.txt")?.read_to_string(&mut s)?; |
| 1120 |
/// assert_eq!(s, "hey\n"); |
| 1121 |
/// # Ok(()) |
| 1122 |
/// # } |
| 1123 |
///``` |
| 1124 |
pub fn merge_archive<R>(&mut self, mut source: ZipArchive<R>) -> ZipResult<()> |
| 1125 |
where |
| 1126 |
R: Read + io::Seek, |
| 1127 |
{ |
| 1128 |
self.finish_file()?; |
| 1129 |
|
| 1130 |
/* Ensure we accept the file contents on faith (and avoid overwriting the data). |
| 1131 |
* See raw_copy_file_rename(). */ |
| 1132 |
self.writing_to_file = true; |
| 1133 |
self.writing_raw = true; |
| 1134 |
|
| 1135 |
let writer = self.inner.get_plain(); |
| 1136 |
/* Get the file entries from the source archive. */ |
| 1137 |
let new_files = source.merge_contents(writer)?; |
| 1138 |
|
| 1139 |
/* These file entries are now ours! */ |
| 1140 |
self.files.extend(new_files); |
| 1141 |
|
| 1142 |
Ok(()) |
| 1143 |
} |
| 1144 |
|
| 1145 |
fn normalize_options<T: FileOptionExtension>(options: &mut FileOptions<T>) { |
| 1146 |
if options.permissions.is_none() { |
| 1147 |
options.permissions = Some(0o644); |
| 1148 |
} |
| 1149 |
if !options.last_modified_time.is_valid() { |
| 1150 |
options.last_modified_time = FileOptions::<T>::default().last_modified_time; |
| 1151 |
} |
| 1152 |
*options.permissions.as_mut().unwrap() |= ffi::S_IFREG; |
| 1153 |
} |
| 1154 |
|
| 1155 |
/// Starts a file, taking a Path as argument. |
| 1156 |
/// |
| 1157 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 1158 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 1159 |
/// root. |
| 1160 |
pub fn start_file_from_path<E: FileOptionExtension, P: AsRef<Path>>( |
| 1161 |
&mut self, |
| 1162 |
path: P, |
| 1163 |
options: FileOptions<E>, |
| 1164 |
) -> ZipResult<()> { |
| 1165 |
self.start_file(path_to_string(path), options) |
| 1166 |
} |
| 1167 |
|
| 1168 |
/// Add a new file using the already compressed data from a ZIP file being read and renames it, this |
| 1169 |
/// allows faster copies of the `ZipFile` since there is no need to decompress and compress it again. |
| 1170 |
/// Any `ZipFile` metadata is copied and not checked, for example the file CRC. |
| 1171 |
|
| 1172 |
/// ```no_run |
| 1173 |
/// use std::fs::File; |
| 1174 |
/// use std::io::{Read, Seek, Write}; |
| 1175 |
/// use zip::{ZipArchive, ZipWriter}; |
| 1176 |
/// |
| 1177 |
/// fn copy_rename<R, W>( |
| 1178 |
/// src: &mut ZipArchive<R>, |
| 1179 |
/// dst: &mut ZipWriter<W>, |
| 1180 |
/// ) -> zip::result::ZipResult<()> |
| 1181 |
/// where |
| 1182 |
/// R: Read + Seek, |
| 1183 |
/// W: Write + Seek, |
| 1184 |
/// { |
| 1185 |
/// // Retrieve file entry by name |
| 1186 |
/// let file = src.by_name("src_file.txt")?; |
| 1187 |
/// |
| 1188 |
/// // Copy and rename the previously obtained file entry to the destination zip archive |
| 1189 |
/// dst.raw_copy_file_rename(file, "new_name.txt")?; |
| 1190 |
/// |
| 1191 |
/// Ok(()) |
| 1192 |
/// } |
| 1193 |
/// ``` |
| 1194 |
pub fn raw_copy_file_rename<S, SToOwned>(&mut self, mut file: ZipFile, name: S) -> ZipResult<()> |
| 1195 |
where |
| 1196 |
S: Into<Box<str>> + ToOwned<Owned = SToOwned>, |
| 1197 |
SToOwned: Into<Box<str>>, |
| 1198 |
{ |
| 1199 |
let mut options = SimpleFileOptions::default() |
| 1200 |
.large_file(file.compressed_size().max(file.size()) > spec::ZIP64_BYTES_THR) |
| 1201 |
.last_modified_time( |
| 1202 |
file.last_modified() |
| 1203 |
.unwrap_or_else(DateTime::default_for_write), |
| 1204 |
) |
| 1205 |
.compression_method(file.compression()); |
| 1206 |
if let Some(perms) = file.unix_mode() { |
| 1207 |
options = options.unix_permissions(perms); |
| 1208 |
} |
| 1209 |
Self::normalize_options(&mut options); |
| 1210 |
|
| 1211 |
let raw_values = ZipRawValues { |
| 1212 |
crc32: file.crc32(), |
| 1213 |
compressed_size: file.compressed_size(), |
| 1214 |
uncompressed_size: file.size(), |
| 1215 |
}; |
| 1216 |
|
| 1217 |
self.start_entry(name, options, Some(raw_values))?; |
| 1218 |
self.writing_to_file = true; |
| 1219 |
self.writing_raw = true; |
| 1220 |
|
| 1221 |
io::copy(file.get_raw_reader(), self)?; |
| 1222 |
|
| 1223 |
Ok(()) |
| 1224 |
} |
| 1225 |
|
| 1226 |
/// Like `raw_copy_file_to_path`, but uses Path arguments. |
| 1227 |
/// |
| 1228 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 1229 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 1230 |
/// root. |
| 1231 |
pub fn raw_copy_file_to_path<P: AsRef<Path>>( |
| 1232 |
&mut self, |
| 1233 |
file: ZipFile, |
| 1234 |
path: P, |
| 1235 |
) -> ZipResult<()> { |
| 1236 |
self.raw_copy_file_rename(file, path_to_string(path)) |
| 1237 |
} |
| 1238 |
|
| 1239 |
/// Add a new file using the already compressed data from a ZIP file being read, this allows faster |
| 1240 |
/// copies of the `ZipFile` since there is no need to decompress and compress it again. Any `ZipFile` |
| 1241 |
/// metadata is copied and not checked, for example the file CRC. |
| 1242 |
/// |
| 1243 |
/// ```no_run |
| 1244 |
/// use std::fs::File; |
| 1245 |
/// use std::io::{Read, Seek, Write}; |
| 1246 |
/// use zip::{ZipArchive, ZipWriter}; |
| 1247 |
/// |
| 1248 |
/// fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()> |
| 1249 |
/// where |
| 1250 |
/// R: Read + Seek, |
| 1251 |
/// W: Write + Seek, |
| 1252 |
/// { |
| 1253 |
/// // Retrieve file entry by name |
| 1254 |
/// let file = src.by_name("src_file.txt")?; |
| 1255 |
/// |
| 1256 |
/// // Copy the previously obtained file entry to the destination zip archive |
| 1257 |
/// dst.raw_copy_file(file)?; |
| 1258 |
/// |
| 1259 |
/// Ok(()) |
| 1260 |
/// } |
| 1261 |
/// ``` |
| 1262 |
pub fn raw_copy_file(&mut self, file: ZipFile) -> ZipResult<()> { |
| 1263 |
let name = file.name().to_owned(); |
| 1264 |
self.raw_copy_file_rename(file, name) |
| 1265 |
} |
| 1266 |
|
| 1267 |
/// Add a directory entry. |
| 1268 |
/// |
| 1269 |
/// As directories have no content, you must not call [`ZipWriter::write`] before adding a new file. |
| 1270 |
pub fn add_directory<S, T: FileOptionExtension>( |
| 1271 |
&mut self, |
| 1272 |
name: S, |
| 1273 |
mut options: FileOptions<T>, |
| 1274 |
) -> ZipResult<()> |
| 1275 |
where |
| 1276 |
S: Into<String>, |
| 1277 |
{ |
| 1278 |
if options.permissions.is_none() { |
| 1279 |
options.permissions = Some(0o755); |
| 1280 |
} |
| 1281 |
*options.permissions.as_mut().unwrap() |= 0o40000; |
| 1282 |
options.compression_method = Stored; |
| 1283 |
options.encrypt_with = None; |
| 1284 |
|
| 1285 |
let name_as_string = name.into(); |
| 1286 |
// Append a slash to the filename if it does not end with it. |
| 1287 |
let name_with_slash = match name_as_string.chars().last() { |
| 1288 |
Some('/') | Some('\\') => name_as_string, |
| 1289 |
_ => name_as_string + "/", |
| 1290 |
}; |
| 1291 |
|
| 1292 |
self.start_entry(name_with_slash, options, None)?; |
| 1293 |
self.writing_to_file = false; |
| 1294 |
self.switch_to_non_encrypting_writer()?; |
| 1295 |
Ok(()) |
| 1296 |
} |
| 1297 |
|
| 1298 |
/// Add a directory entry, taking a Path as argument. |
| 1299 |
/// |
| 1300 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 1301 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 1302 |
/// root. |
| 1303 |
pub fn add_directory_from_path<T: FileOptionExtension, P: AsRef<Path>>( |
| 1304 |
&mut self, |
| 1305 |
path: P, |
| 1306 |
options: FileOptions<T>, |
| 1307 |
) -> ZipResult<()> { |
| 1308 |
self.add_directory(path_to_string(path), options) |
| 1309 |
} |
| 1310 |
|
| 1311 |
/// Finish the last file and write all other zip-structures |
| 1312 |
/// |
| 1313 |
/// This will return the writer, but one should normally not append any data to the end of the file. |
| 1314 |
/// Note that the zipfile will also be finished on drop. |
| 1315 |
pub fn finish(mut self) -> ZipResult<W> { |
| 1316 |
let _central_start = self.finalize()?; |
| 1317 |
let inner = mem::replace(&mut self.inner, Closed); |
| 1318 |
Ok(inner.unwrap()) |
| 1319 |
} |
| 1320 |
|
| 1321 |
/// Add a symlink entry. |
| 1322 |
/// |
| 1323 |
/// The zip archive will contain an entry for path `name` which is a symlink to `target`. |
| 1324 |
/// |
| 1325 |
/// No validation or normalization of the paths is performed. For best results, |
| 1326 |
/// callers should normalize `\` to `/` and ensure symlinks are relative to other |
| 1327 |
/// paths within the zip archive. |
| 1328 |
/// |
| 1329 |
/// WARNING: not all zip implementations preserve symlinks on extract. Some zip |
| 1330 |
/// implementations may materialize a symlink as a regular file, possibly with the |
| 1331 |
/// content incorrectly set to the symlink target. For maximum portability, consider |
| 1332 |
/// storing a regular file instead. |
| 1333 |
pub fn add_symlink<N, NToOwned, T, E: FileOptionExtension>( |
| 1334 |
&mut self, |
| 1335 |
name: N, |
| 1336 |
target: T, |
| 1337 |
mut options: FileOptions<E>, |
| 1338 |
) -> ZipResult<()> |
| 1339 |
where |
| 1340 |
N: Into<Box<str>> + ToOwned<Owned = NToOwned>, |
| 1341 |
NToOwned: Into<Box<str>>, |
| 1342 |
T: Into<Box<str>>, |
| 1343 |
{ |
| 1344 |
if options.permissions.is_none() { |
| 1345 |
options.permissions = Some(0o777); |
| 1346 |
} |
| 1347 |
*options.permissions.as_mut().unwrap() |= S_IFLNK; |
| 1348 |
// The symlink target is stored as file content. And compressing the target path |
| 1349 |
// likely wastes space. So always store. |
| 1350 |
options.compression_method = Stored; |
| 1351 |
|
| 1352 |
self.start_entry(name, options, None)?; |
| 1353 |
self.writing_to_file = true; |
| 1354 |
if let Err(e) = self.write_all(target.into().as_bytes()) { |
| 1355 |
self.abort_file().unwrap(); |
| 1356 |
return Err(e.into()); |
| 1357 |
} |
| 1358 |
self.writing_raw = false; |
| 1359 |
self.finish_file()?; |
| 1360 |
|
| 1361 |
Ok(()) |
| 1362 |
} |
| 1363 |
|
| 1364 |
/// Add a symlink entry, taking Paths to the location and target as arguments. |
| 1365 |
/// |
| 1366 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 1367 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 1368 |
/// root. |
| 1369 |
pub fn add_symlink_from_path<P: AsRef<Path>, T: AsRef<Path>, E: FileOptionExtension>( |
| 1370 |
&mut self, |
| 1371 |
path: P, |
| 1372 |
target: T, |
| 1373 |
options: FileOptions<E>, |
| 1374 |
) -> ZipResult<()> { |
| 1375 |
self.add_symlink(path_to_string(path), path_to_string(target), options) |
| 1376 |
} |
| 1377 |
|
| 1378 |
fn finalize(&mut self) -> ZipResult<u64> { |
| 1379 |
self.finish_file()?; |
| 1380 |
|
| 1381 |
let central_start = { |
| 1382 |
let central_start = self.write_central_and_footer()?; |
| 1383 |
let writer = self.inner.get_plain(); |
| 1384 |
let footer_end = writer.stream_position()?; |
| 1385 |
let file_end = writer.seek(SeekFrom::End(0))?; |
| 1386 |
if footer_end < file_end { |
| 1387 |
// Data from an aborted file is past the end of the footer, so rewrite the footer at |
| 1388 |
// the actual end. |
| 1389 |
let central_and_footer_size = footer_end - central_start; |
| 1390 |
writer.seek(SeekFrom::End(-(central_and_footer_size as i64)))?; |
| 1391 |
self.write_central_and_footer()?; |
| 1392 |
} |
| 1393 |
central_start |
| 1394 |
}; |
| 1395 |
|
| 1396 |
Ok(central_start) |
| 1397 |
} |
| 1398 |
|
| 1399 |
fn write_central_and_footer(&mut self) -> Result<u64, ZipError> { |
| 1400 |
let writer = self.inner.get_plain(); |
| 1401 |
|
| 1402 |
let mut version_needed = MIN_VERSION as u16; |
| 1403 |
let central_start = writer.stream_position()?; |
| 1404 |
for file in self.files.values() { |
| 1405 |
write_central_directory_header(writer, file)?; |
| 1406 |
version_needed = version_needed.max(file.version_needed()); |
| 1407 |
} |
| 1408 |
let central_size = writer.stream_position()? - central_start; |
| 1409 |
|
| 1410 |
if self.files.len() > spec::ZIP64_ENTRY_THR |
| 1411 |
|| central_size.max(central_start) > spec::ZIP64_BYTES_THR |
| 1412 |
{ |
| 1413 |
let zip64_footer = spec::Zip64CentralDirectoryEnd { |
| 1414 |
version_made_by: version_needed, |
| 1415 |
version_needed_to_extract: version_needed, |
| 1416 |
disk_number: 0, |
| 1417 |
disk_with_central_directory: 0, |
| 1418 |
number_of_files_on_this_disk: self.files.len() as u64, |
| 1419 |
number_of_files: self.files.len() as u64, |
| 1420 |
central_directory_size: central_size, |
| 1421 |
central_directory_offset: central_start, |
| 1422 |
}; |
| 1423 |
|
| 1424 |
zip64_footer.write(writer)?; |
| 1425 |
|
| 1426 |
let zip64_footer = spec::Zip64CentralDirectoryEndLocator { |
| 1427 |
disk_with_central_directory: 0, |
| 1428 |
end_of_central_directory_offset: central_start + central_size, |
| 1429 |
number_of_disks: 1, |
| 1430 |
}; |
| 1431 |
|
| 1432 |
zip64_footer.write(writer)?; |
| 1433 |
} |
| 1434 |
|
| 1435 |
let number_of_files = self.files.len().min(spec::ZIP64_ENTRY_THR) as u16; |
| 1436 |
let footer = spec::Zip32CentralDirectoryEnd { |
| 1437 |
disk_number: 0, |
| 1438 |
disk_with_central_directory: 0, |
| 1439 |
zip_file_comment: self.comment.clone(), |
| 1440 |
number_of_files_on_this_disk: number_of_files, |
| 1441 |
number_of_files, |
| 1442 |
central_directory_size: central_size.min(spec::ZIP64_BYTES_THR) as u32, |
| 1443 |
central_directory_offset: central_start.min(spec::ZIP64_BYTES_THR) as u32, |
| 1444 |
}; |
| 1445 |
|
| 1446 |
footer.write(writer)?; |
| 1447 |
Ok(central_start) |
| 1448 |
} |
| 1449 |
|
| 1450 |
fn index_by_name(&self, name: &str) -> ZipResult<usize> { |
| 1451 |
self.files.get_index_of(name).ok_or(ZipError::FileNotFound) |
| 1452 |
} |
| 1453 |
|
| 1454 |
/// Adds another entry to the central directory referring to the same content as an existing |
| 1455 |
/// entry. The file's local-file header will still refer to it by its original name, so |
| 1456 |
/// unzipping the file will technically be unspecified behavior. [ZipArchive] ignores the |
| 1457 |
/// filename in the local-file header and treat the central directory as authoritative. However, |
| 1458 |
/// some other software (e.g. Minecraft) will refuse to extract a file copied this way. |
| 1459 |
pub fn shallow_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()> { |
| 1460 |
self.finish_file()?; |
| 1461 |
let src_index = self.index_by_name(src_name)?; |
| 1462 |
let mut dest_data = self.files[src_index].to_owned(); |
| 1463 |
dest_data.file_name = dest_name.to_string().into(); |
| 1464 |
dest_data.file_name_raw = dest_name.to_string().into_bytes().into(); |
| 1465 |
self.insert_file_data(dest_data)?; |
| 1466 |
Ok(()) |
| 1467 |
} |
| 1468 |
|
| 1469 |
/// Like `shallow_copy_file`, but uses Path arguments. |
| 1470 |
/// |
| 1471 |
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It |
| 1472 |
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's |
| 1473 |
/// root. |
| 1474 |
pub fn shallow_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>( |
| 1475 |
&mut self, |
| 1476 |
src_path: T, |
| 1477 |
dest_path: U, |
| 1478 |
) -> ZipResult<()> { |
| 1479 |
self.shallow_copy_file(&path_to_string(src_path), &path_to_string(dest_path)) |
| 1480 |
} |
| 1481 |
} |
| 1482 |
|
| 1483 |
impl<W: Write + Seek> Drop for ZipWriter<W> { |
| 1484 |
fn drop(&mut self) { |
| 1485 |
if !self.inner.is_closed() { |
| 1486 |
if let Err(e) = self.finalize() { |
| 1487 |
let _ = write!(io::stderr(), "ZipWriter drop failed: {:?}", e); |
| 1488 |
} |
| 1489 |
} |
| 1490 |
} |
| 1491 |
} |
| 1492 |
|
| 1493 |
type SwitchWriterFunction<W> = Box<dyn FnOnce(MaybeEncrypted<W>) -> GenericZipWriter<W>>; |
| 1494 |
|
| 1495 |
impl<W: Write + Seek> GenericZipWriter<W> { |
| 1496 |
fn prepare_next_writer( |
| 1497 |
&self, |
| 1498 |
compression: CompressionMethod, |
| 1499 |
compression_level: Option<i64>, |
| 1500 |
#[cfg(feature = "deflate-zopfli")] zopfli_buffer_size: Option<usize>, |
| 1501 |
) -> ZipResult<SwitchWriterFunction<W>> { |
| 1502 |
if let Closed = self { |
| 1503 |
return Err( |
| 1504 |
io::Error::new(io::ErrorKind::BrokenPipe, "ZipWriter was already closed").into(), |
| 1505 |
); |
| 1506 |
} |
| 1507 |
|
| 1508 |
{ |
| 1509 |
#[allow(deprecated)] |
| 1510 |
#[allow(unreachable_code)] |
| 1511 |
match compression { |
| 1512 |
Stored => { |
| 1513 |
if compression_level.is_some() { |
| 1514 |
Err(ZipError::UnsupportedArchive( |
| 1515 |
"Unsupported compression level", |
| 1516 |
)) |
| 1517 |
} else { |
| 1518 |
Ok(Box::new(|bare| Storer(bare))) |
| 1519 |
} |
| 1520 |
} |
| 1521 |
#[cfg(feature = "_deflate-any")] |
| 1522 |
CompressionMethod::Deflated => { |
| 1523 |
let default = if cfg!(all( |
| 1524 |
feature = "deflate-zopfli", |
| 1525 |
not(feature = "deflate-flate2") |
| 1526 |
)) { |
| 1527 |
24 |
| 1528 |
} else { |
| 1529 |
Compression::default().level() as i64 |
| 1530 |
}; |
| 1531 |
|
| 1532 |
let level = clamp_opt( |
| 1533 |
compression_level.unwrap_or(default), |
| 1534 |
deflate_compression_level_range(), |
| 1535 |
) |
| 1536 |
.ok_or(ZipError::UnsupportedArchive( |
| 1537 |
"Unsupported compression level", |
| 1538 |
))? as u32; |
| 1539 |
|
| 1540 |
#[cfg(feature = "deflate-zopfli")] |
| 1541 |
{ |
| 1542 |
let best_non_zopfli = Compression::best().level(); |
| 1543 |
if level > best_non_zopfli { |
| 1544 |
let options = Options { |
| 1545 |
iteration_count: NonZeroU64::try_from( |
| 1546 |
(level - best_non_zopfli) as u64, |
| 1547 |
) |
| 1548 |
.unwrap(), |
| 1549 |
..Default::default() |
| 1550 |
}; |
| 1551 |
return Ok(Box::new(move |bare| match zopfli_buffer_size { |
| 1552 |
Some(size) => GenericZipWriter::BufferedZopfliDeflater( |
| 1553 |
BufWriter::with_capacity( |
| 1554 |
size, |
| 1555 |
zopfli::DeflateEncoder::new( |
| 1556 |
options, |
| 1557 |
Default::default(), |
| 1558 |
bare, |
| 1559 |
), |
| 1560 |
), |
| 1561 |
), |
| 1562 |
None => GenericZipWriter::ZopfliDeflater( |
| 1563 |
zopfli::DeflateEncoder::new(options, Default::default(), bare), |
| 1564 |
), |
| 1565 |
})); |
| 1566 |
} |
| 1567 |
} |
| 1568 |
|
| 1569 |
#[cfg(feature = "deflate-flate2")] |
| 1570 |
{ |
| 1571 |
Ok(Box::new(move |bare| { |
| 1572 |
GenericZipWriter::Deflater(DeflateEncoder::new( |
| 1573 |
bare, |
| 1574 |
Compression::new(level), |
| 1575 |
)) |
| 1576 |
})) |
| 1577 |
} |
| 1578 |
} |
| 1579 |
#[cfg(feature = "deflate64")] |
| 1580 |
CompressionMethod::Deflate64 => Err(ZipError::UnsupportedArchive( |
| 1581 |
"Compressing Deflate64 is not supported", |
| 1582 |
)), |
| 1583 |
#[cfg(feature = "bzip2")] |
| 1584 |
CompressionMethod::Bzip2 => { |
| 1585 |
let level = clamp_opt( |
| 1586 |
compression_level.unwrap_or(bzip2::Compression::default().level() as i64), |
| 1587 |
bzip2_compression_level_range(), |
| 1588 |
) |
| 1589 |
.ok_or(ZipError::UnsupportedArchive( |
| 1590 |
"Unsupported compression level", |
| 1591 |
))? as u32; |
| 1592 |
Ok(Box::new(move |bare| { |
| 1593 |
GenericZipWriter::Bzip2(BzEncoder::new( |
| 1594 |
bare, |
| 1595 |
bzip2::Compression::new(level), |
| 1596 |
)) |
| 1597 |
})) |
| 1598 |
} |
| 1599 |
CompressionMethod::AES => Err(ZipError::UnsupportedArchive( |
| 1600 |
"AES encryption is enabled through FileOptions::with_aes_encryption", |
| 1601 |
)), |
| 1602 |
#[cfg(feature = "zstd")] |
| 1603 |
CompressionMethod::Zstd => { |
| 1604 |
let level = clamp_opt( |
| 1605 |
compression_level.unwrap_or(zstd::DEFAULT_COMPRESSION_LEVEL as i64), |
| 1606 |
zstd::compression_level_range(), |
| 1607 |
) |
| 1608 |
.ok_or(ZipError::UnsupportedArchive( |
| 1609 |
"Unsupported compression level", |
| 1610 |
))?; |
| 1611 |
Ok(Box::new(move |bare| { |
| 1612 |
GenericZipWriter::Zstd(ZstdEncoder::new(bare, level as i32).unwrap()) |
| 1613 |
})) |
| 1614 |
} |
| 1615 |
#[cfg(feature = "lzma")] |
| 1616 |
CompressionMethod::Lzma => { |
| 1617 |
Err(UnsupportedArchive("LZMA isn't supported for compression")) |
| 1618 |
} |
| 1619 |
CompressionMethod::Unsupported(..) => { |
| 1620 |
Err(ZipError::UnsupportedArchive("Unsupported compression")) |
| 1621 |
} |
| 1622 |
} |
| 1623 |
} |
| 1624 |
} |
| 1625 |
|
| 1626 |
fn switch_to(&mut self, make_new_self: SwitchWriterFunction<W>) -> ZipResult<()> { |
| 1627 |
let bare = match mem::replace(self, Closed) { |
| 1628 |
Storer(w) => w, |
| 1629 |
#[cfg(feature = "deflate-flate2")] |
| 1630 |
GenericZipWriter::Deflater(w) => w.finish()?, |
| 1631 |
#[cfg(feature = "deflate-zopfli")] |
| 1632 |
GenericZipWriter::ZopfliDeflater(w) => w.finish()?, |
| 1633 |
#[cfg(feature = "deflate-zopfli")] |
| 1634 |
GenericZipWriter::BufferedZopfliDeflater(w) => w |
| 1635 |
.into_inner() |
| 1636 |
.map_err(|e| ZipError::Io(e.into_error()))? |
| 1637 |
.finish()?, |
| 1638 |
#[cfg(feature = "bzip2")] |
| 1639 |
GenericZipWriter::Bzip2(w) => w.finish()?, |
| 1640 |
#[cfg(feature = "zstd")] |
| 1641 |
GenericZipWriter::Zstd(w) => w.finish()?, |
| 1642 |
Closed => { |
| 1643 |
return Err(io::Error::new( |
| 1644 |
io::ErrorKind::BrokenPipe, |
| 1645 |
"ZipWriter was already closed", |
| 1646 |
) |
| 1647 |
.into()); |
| 1648 |
} |
| 1649 |
}; |
| 1650 |
*self = make_new_self(bare); |
| 1651 |
Ok(()) |
| 1652 |
} |
| 1653 |
|
| 1654 |
fn ref_mut(&mut self) -> Option<&mut dyn Write> { |
| 1655 |
match self { |
| 1656 |
Storer(ref mut w) => Some(w as &mut dyn Write), |
| 1657 |
#[cfg(feature = "deflate-flate2")] |
| 1658 |
GenericZipWriter::Deflater(ref mut w) => Some(w as &mut dyn Write), |
| 1659 |
#[cfg(feature = "deflate-zopfli")] |
| 1660 |
GenericZipWriter::ZopfliDeflater(w) => Some(w as &mut dyn Write), |
| 1661 |
#[cfg(feature = "deflate-zopfli")] |
| 1662 |
GenericZipWriter::BufferedZopfliDeflater(w) => Some(w as &mut dyn Write), |
| 1663 |
#[cfg(feature = "bzip2")] |
| 1664 |
GenericZipWriter::Bzip2(ref mut w) => Some(w as &mut dyn Write), |
| 1665 |
#[cfg(feature = "zstd")] |
| 1666 |
GenericZipWriter::Zstd(ref mut w) => Some(w as &mut dyn Write), |
| 1667 |
Closed => None, |
| 1668 |
} |
| 1669 |
} |
| 1670 |
|
| 1671 |
const fn is_closed(&self) -> bool { |
| 1672 |
matches!(*self, GenericZipWriter::Closed) |
| 1673 |
} |
| 1674 |
|
| 1675 |
fn get_plain(&mut self) -> &mut W { |
| 1676 |
match *self { |
| 1677 |
Storer(MaybeEncrypted::Unencrypted(ref mut w)) => w, |
| 1678 |
_ => panic!("Should have switched to stored and unencrypted beforehand"), |
| 1679 |
} |
| 1680 |
} |
| 1681 |
|
| 1682 |
fn unwrap(self) -> W { |
| 1683 |
match self { |
| 1684 |
Storer(MaybeEncrypted::Unencrypted(w)) => w, |
| 1685 |
_ => panic!("Should have switched to stored and unencrypted beforehand"), |
| 1686 |
} |
| 1687 |
} |
| 1688 |
} |
| 1689 |
|
| 1690 |
#[cfg(feature = "_deflate-any")] |
| 1691 |
fn deflate_compression_level_range() -> std::ops::RangeInclusive<i64> { |
| 1692 |
let min = if cfg!(feature = "deflate-flate2") { |
| 1693 |
Compression::fast().level() as i64 |
| 1694 |
} else { |
| 1695 |
Compression::best().level() as i64 + 1 |
| 1696 |
}; |
| 1697 |
|
| 1698 |
let max = Compression::best().level() as i64 |
| 1699 |
+ if cfg!(feature = "deflate-zopfli") { |
| 1700 |
u8::MAX as i64 |
| 1701 |
} else { |
| 1702 |
0 |
| 1703 |
}; |
| 1704 |
|
| 1705 |
min..=max |
| 1706 |
} |
| 1707 |
|
| 1708 |
#[cfg(feature = "bzip2")] |
| 1709 |
fn bzip2_compression_level_range() -> std::ops::RangeInclusive<i64> { |
| 1710 |
let min = bzip2::Compression::fast().level() as i64; |
| 1711 |
let max = bzip2::Compression::best().level() as i64; |
| 1712 |
min..=max |
| 1713 |
} |
| 1714 |
|
| 1715 |
#[cfg(any(feature = "_deflate-any", feature = "bzip2", feature = "zstd"))] |
| 1716 |
fn clamp_opt<T: Ord + Copy, U: Ord + Copy + TryFrom<T>>( |
| 1717 |
value: T, |
| 1718 |
range: std::ops::RangeInclusive<U>, |
| 1719 |
) -> Option<T> { |
| 1720 |
if range.contains(&value.try_into().ok()?) { |
| 1721 |
Some(value) |
| 1722 |
} else { |
| 1723 |
None |
| 1724 |
} |
| 1725 |
} |
| 1726 |
|
| 1727 |
fn update_aes_extra_data<W: Write + io::Seek>( |
| 1728 |
writer: &mut W, |
| 1729 |
file: &mut ZipFileData, |
| 1730 |
) -> ZipResult<()> { |
| 1731 |
let Some((aes_mode, version, compression_method)) = file.aes_mode else { |
| 1732 |
return Ok(()); |
| 1733 |
}; |
| 1734 |
|
| 1735 |
let extra_data_start = file.extra_data_start.unwrap(); |
| 1736 |
|
| 1737 |
writer.seek(io::SeekFrom::Start( |
| 1738 |
extra_data_start + file.aes_extra_data_start, |
| 1739 |
))?; |
| 1740 |
|
| 1741 |
let mut buf = Vec::new(); |
| 1742 |
|
| 1743 |
/* TODO: implement this using the Block trait! */ |
| 1744 |
// Extra field header ID. |
| 1745 |
buf.write_u16_le(0x9901)?; |
| 1746 |
// Data size. |
| 1747 |
buf.write_u16_le(7)?; |
| 1748 |
// Integer version number. |
| 1749 |
buf.write_u16_le(version as u16)?; |
| 1750 |
// Vendor ID. |
| 1751 |
buf.write_all(b"AE")?; |
| 1752 |
// AES encryption strength. |
| 1753 |
buf.write_all(&[aes_mode as u8])?; |
| 1754 |
// Real compression method. |
| 1755 |
buf.write_u16_le(compression_method.serialize_to_u16())?; |
| 1756 |
|
| 1757 |
writer.write_all(&buf)?; |
| 1758 |
|
| 1759 |
let aes_extra_data_start = file.aes_extra_data_start as usize; |
| 1760 |
let extra_field = Arc::get_mut(file.extra_field.as_mut().unwrap()).unwrap(); |
| 1761 |
extra_field |
| 1762 |
.splice( |
| 1763 |
aes_extra_data_start..(aes_extra_data_start + buf.len()), |
| 1764 |
buf, |
| 1765 |
) |
| 1766 |
.count(); |
| 1767 |
|
| 1768 |
Ok(()) |
| 1769 |
} |
| 1770 |
|
| 1771 |
fn update_local_file_header<T: Write + Seek>(writer: &mut T, file: &ZipFileData) -> ZipResult<()> { |
| 1772 |
const CRC32_OFFSET: u64 = 14; |
| 1773 |
writer.seek(SeekFrom::Start(file.header_start + CRC32_OFFSET))?; |
| 1774 |
writer.write_u32_le(file.crc32)?; |
| 1775 |
if file.large_file { |
| 1776 |
update_local_zip64_extra_field(writer, file)?; |
| 1777 |
} else { |
| 1778 |
// check compressed size as well as it can also be slightly larger than uncompressed size |
| 1779 |
if file.compressed_size > spec::ZIP64_BYTES_THR { |
| 1780 |
return Err(ZipError::Io(io::Error::new( |
| 1781 |
io::ErrorKind::Other, |
| 1782 |
"Large file option has not been set", |
| 1783 |
))); |
| 1784 |
} |
| 1785 |
writer.write_u32_le(file.compressed_size as u32)?; |
| 1786 |
// uncompressed size is already checked on write to catch it as soon as possible |
| 1787 |
writer.write_u32_le(file.uncompressed_size as u32)?; |
| 1788 |
} |
| 1789 |
Ok(()) |
| 1790 |
} |
| 1791 |
|
| 1792 |
fn write_central_directory_header<T: Write>(writer: &mut T, file: &ZipFileData) -> ZipResult<()> { |
| 1793 |
// buffer zip64 extra field to determine its variable length |
| 1794 |
let mut zip64_extra_field = [0; 28]; |
| 1795 |
let zip64_extra_field_length = |
| 1796 |
write_central_zip64_extra_field(&mut zip64_extra_field.as_mut(), file)?; |
| 1797 |
let block = file.block(zip64_extra_field_length); |
| 1798 |
block.write(writer)?; |
| 1799 |
// file name |
| 1800 |
writer.write_all(&file.file_name_raw)?; |
| 1801 |
// zip64 extra field |
| 1802 |
writer.write_all(&zip64_extra_field[..zip64_extra_field_length as usize])?; |
| 1803 |
// extra field |
| 1804 |
if let Some(extra_field) = &file.extra_field { |
| 1805 |
writer.write_all(extra_field)?; |
| 1806 |
} |
| 1807 |
if let Some(central_extra_field) = &file.central_extra_field { |
| 1808 |
writer.write_all(central_extra_field)?; |
| 1809 |
} |
| 1810 |
// file comment |
| 1811 |
writer.write_all(file.file_comment.as_bytes())?; |
| 1812 |
|
| 1813 |
Ok(()) |
| 1814 |
} |
| 1815 |
|
| 1816 |
fn validate_extra_data(header_id: u16, data: &[u8]) -> ZipResult<()> { |
| 1817 |
if data.len() > u16::MAX as usize { |
| 1818 |
return Err(ZipError::Io(io::Error::new( |
| 1819 |
io::ErrorKind::Other, |
| 1820 |
"Extra-data field can't exceed u16::MAX bytes", |
| 1821 |
))); |
| 1822 |
} |
| 1823 |
if header_id == 0x0001 { |
| 1824 |
return Err(ZipError::Io(io::Error::new( |
| 1825 |
io::ErrorKind::Other, |
| 1826 |
"No custom ZIP64 extra data allowed", |
| 1827 |
))); |
| 1828 |
} |
| 1829 |
|
| 1830 |
#[cfg(not(feature = "unreserved"))] |
| 1831 |
{ |
| 1832 |
if header_id <= 31 |
| 1833 |
|| EXTRA_FIELD_MAPPING |
| 1834 |
.iter() |
| 1835 |
.any(|&mapped| mapped == header_id) |
| 1836 |
{ |
| 1837 |
return Err(ZipError::Io(io::Error::new( |
| 1838 |
io::ErrorKind::Other, |
| 1839 |
format!( |
| 1840 |
"Extra data header ID {header_id:#06} requires crate feature \"unreserved\"", |
| 1841 |
), |
| 1842 |
))); |
| 1843 |
} |
| 1844 |
} |
| 1845 |
|
| 1846 |
Ok(()) |
| 1847 |
} |
| 1848 |
|
| 1849 |
fn write_local_zip64_extra_field<T: Write>(writer: &mut T, file: &ZipFileData) -> ZipResult<()> { |
| 1850 |
// This entry in the Local header MUST include BOTH original |
| 1851 |
// and compressed file size fields. |
| 1852 |
let Some(block) = file.zip64_extra_field_block() else { |
| 1853 |
return Err(ZipError::InvalidArchive( |
| 1854 |
"Attempted to write a ZIP64 extra field for a file that's within zip32 limits", |
| 1855 |
)); |
| 1856 |
}; |
| 1857 |
let block = block.serialize(); |
| 1858 |
writer.write_all(&block)?; |
| 1859 |
Ok(()) |
| 1860 |
} |
| 1861 |
|
| 1862 |
fn update_local_zip64_extra_field<T: Write + Seek>( |
| 1863 |
writer: &mut T, |
| 1864 |
file: &ZipFileData, |
| 1865 |
) -> ZipResult<()> { |
| 1866 |
if !file.large_file { |
| 1867 |
return Err(ZipError::InvalidArchive( |
| 1868 |
"Attempted to update a nonexistent ZIP64 extra field", |
| 1869 |
)); |
| 1870 |
} |
| 1871 |
|
| 1872 |
let zip64_extra_field = file.header_start |
| 1873 |
+ mem::size_of::<ZipLocalEntryBlock>() as u64 |
| 1874 |
+ file.file_name_raw.len() as u64; |
| 1875 |
|
| 1876 |
writer.seek(SeekFrom::Start(zip64_extra_field))?; |
| 1877 |
|
| 1878 |
let block = file.zip64_extra_field_block().unwrap(); |
| 1879 |
let block = block.serialize(); |
| 1880 |
writer.write_all(&block)?; |
| 1881 |
Ok(()) |
| 1882 |
} |
| 1883 |
|
| 1884 |
fn write_central_zip64_extra_field<T: Write>(writer: &mut T, file: &ZipFileData) -> ZipResult<u16> { |
| 1885 |
// The order of the fields in the zip64 extended |
| 1886 |
// information record is fixed, but the fields MUST |
| 1887 |
// only appear if the corresponding Local or Central |
| 1888 |
// directory record field is set to 0xFFFF or 0xFFFFFFFF. |
| 1889 |
match file.zip64_extra_field_block() { |
| 1890 |
None => Ok(0), |
| 1891 |
Some(block) => { |
| 1892 |
let block = block.serialize(); |
| 1893 |
writer.write_all(&block)?; |
| 1894 |
let len: u16 = block.len().try_into().unwrap(); |
| 1895 |
Ok(len) |
| 1896 |
} |
| 1897 |
} |
| 1898 |
} |
| 1899 |
|
| 1900 |
#[cfg(not(feature = "unreserved"))] |
| 1901 |
const EXTRA_FIELD_MAPPING: [u16; 49] = [ |
| 1902 |
0x0001, 0x0007, 0x0008, 0x0009, 0x000a, 0x000c, 0x000d, 0x000e, 0x000f, 0x0014, 0x0015, 0x0016, |
| 1903 |
0x0017, 0x0018, 0x0019, 0x0020, 0x0021, 0x0022, 0x0023, 0x0065, 0x0066, 0x4690, 0x07c8, 0x2605, |
| 1904 |
0x2705, 0x2805, 0x334d, 0x4341, 0x4453, 0x4704, 0x470f, 0x4b46, 0x4c41, 0x4d49, 0x4f4c, 0x5356, |
| 1905 |
0x5455, 0x554e, 0x5855, 0x6375, 0x6542, 0x7075, 0x756e, 0x7855, 0xa11e, 0xa220, 0xfd4a, 0x9901, |
| 1906 |
0x9902, |
| 1907 |
]; |
| 1908 |
|
| 1909 |
#[cfg(test)] |
| 1910 |
mod test { |
| 1911 |
use super::{FileOptions, ZipWriter}; |
| 1912 |
use crate::compression::CompressionMethod; |
| 1913 |
use crate::result::ZipResult; |
| 1914 |
use crate::types::DateTime; |
| 1915 |
use crate::write::SimpleFileOptions; |
| 1916 |
use crate::CompressionMethod::Stored; |
| 1917 |
use crate::ZipArchive; |
| 1918 |
use std::io; |
| 1919 |
use std::io::{Cursor, Read, Write}; |
| 1920 |
use std::path::PathBuf; |
| 1921 |
|
| 1922 |
#[test] |
| 1923 |
fn write_empty_zip() { |
| 1924 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 1925 |
writer.set_comment("ZIP"); |
| 1926 |
let result = writer.finish().unwrap(); |
| 1927 |
assert_eq!(result.get_ref().len(), 25); |
| 1928 |
assert_eq!( |
| 1929 |
*result.get_ref(), |
| 1930 |
[80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 90, 73, 80] |
| 1931 |
); |
| 1932 |
} |
| 1933 |
|
| 1934 |
#[test] |
| 1935 |
fn unix_permissions_bitmask() { |
| 1936 |
// unix_permissions() throws away upper bits. |
| 1937 |
let options = SimpleFileOptions::default().unix_permissions(0o120777); |
| 1938 |
assert_eq!(options.permissions, Some(0o777)); |
| 1939 |
} |
| 1940 |
|
| 1941 |
#[test] |
| 1942 |
fn write_zip_dir() { |
| 1943 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 1944 |
writer |
| 1945 |
.add_directory( |
| 1946 |
"test", |
| 1947 |
SimpleFileOptions::default().last_modified_time( |
| 1948 |
DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(), |
| 1949 |
), |
| 1950 |
) |
| 1951 |
.unwrap(); |
| 1952 |
assert!(writer |
| 1953 |
.write(b"writing to a directory is not allowed, and will not write any data") |
| 1954 |
.is_err()); |
| 1955 |
let result = writer.finish().unwrap(); |
| 1956 |
assert_eq!(result.get_ref().len(), 108); |
| 1957 |
assert_eq!( |
| 1958 |
*result.get_ref(), |
| 1959 |
&[ |
| 1960 |
80u8, 75, 3, 4, 20, 0, 0, 0, 0, 0, 163, 165, 15, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 1961 |
0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 47, 80, 75, 1, 2, 20, 3, 20, 0, 0, 0, 0, 0, |
| 1962 |
163, 165, 15, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 1963 |
0, 0, 237, 65, 0, 0, 0, 0, 116, 101, 115, 116, 47, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0, |
| 1964 |
1, 0, 51, 0, 0, 0, 35, 0, 0, 0, 0, 0, |
| 1965 |
] as &[u8] |
| 1966 |
); |
| 1967 |
} |
| 1968 |
|
| 1969 |
#[test] |
| 1970 |
fn write_symlink_simple() { |
| 1971 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 1972 |
writer |
| 1973 |
.add_symlink( |
| 1974 |
"name", |
| 1975 |
"target", |
| 1976 |
SimpleFileOptions::default().last_modified_time( |
| 1977 |
DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(), |
| 1978 |
), |
| 1979 |
) |
| 1980 |
.unwrap(); |
| 1981 |
assert!(writer |
| 1982 |
.write(b"writing to a symlink is not allowed and will not write any data") |
| 1983 |
.is_err()); |
| 1984 |
let result = writer.finish().unwrap(); |
| 1985 |
assert_eq!(result.get_ref().len(), 112); |
| 1986 |
assert_eq!( |
| 1987 |
*result.get_ref(), |
| 1988 |
&[ |
| 1989 |
80u8, 75, 3, 4, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 252, 47, 111, 70, 6, 0, 0, 0, |
| 1990 |
6, 0, 0, 0, 4, 0, 0, 0, 110, 97, 109, 101, 116, 97, 114, 103, 101, 116, 80, 75, 1, |
| 1991 |
2, 10, 3, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 252, 47, 111, 70, 6, 0, 0, 0, 6, 0, |
| 1992 |
0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 161, 0, 0, 0, 0, 110, 97, 109, 101, |
| 1993 |
80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 50, 0, 0, 0, 40, 0, 0, 0, 0, 0 |
| 1994 |
] as &[u8], |
| 1995 |
); |
| 1996 |
} |
| 1997 |
|
| 1998 |
#[test] |
| 1999 |
fn test_path_normalization() { |
| 2000 |
let mut path = PathBuf::new(); |
| 2001 |
path.push("foo"); |
| 2002 |
path.push("bar"); |
| 2003 |
path.push(".."); |
| 2004 |
path.push("."); |
| 2005 |
path.push("example.txt"); |
| 2006 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2007 |
writer |
| 2008 |
.start_file_from_path(path, SimpleFileOptions::default()) |
| 2009 |
.unwrap(); |
| 2010 |
let archive = writer.finish_into_readable().unwrap(); |
| 2011 |
assert_eq!(Some("foo/example.txt"), archive.name_for_index(0)); |
| 2012 |
} |
| 2013 |
|
| 2014 |
#[test] |
| 2015 |
fn write_symlink_wonky_paths() { |
| 2016 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2017 |
writer |
| 2018 |
.add_symlink( |
| 2019 |
"directory\\link", |
| 2020 |
"/absolute/symlink\\with\\mixed/slashes", |
| 2021 |
SimpleFileOptions::default().last_modified_time( |
| 2022 |
DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(), |
| 2023 |
), |
| 2024 |
) |
| 2025 |
.unwrap(); |
| 2026 |
assert!(writer |
| 2027 |
.write(b"writing to a symlink is not allowed and will not write any data") |
| 2028 |
.is_err()); |
| 2029 |
let result = writer.finish().unwrap(); |
| 2030 |
assert_eq!(result.get_ref().len(), 162); |
| 2031 |
assert_eq!( |
| 2032 |
*result.get_ref(), |
| 2033 |
&[ |
| 2034 |
80u8, 75, 3, 4, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 95, 41, 81, 245, 36, 0, 0, 0, |
| 2035 |
36, 0, 0, 0, 14, 0, 0, 0, 100, 105, 114, 101, 99, 116, 111, 114, 121, 92, 108, 105, |
| 2036 |
110, 107, 47, 97, 98, 115, 111, 108, 117, 116, 101, 47, 115, 121, 109, 108, 105, |
| 2037 |
110, 107, 92, 119, 105, 116, 104, 92, 109, 105, 120, 101, 100, 47, 115, 108, 97, |
| 2038 |
115, 104, 101, 115, 80, 75, 1, 2, 10, 3, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 95, |
| 2039 |
41, 81, 245, 36, 0, 0, 0, 36, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, |
| 2040 |
161, 0, 0, 0, 0, 100, 105, 114, 101, 99, 116, 111, 114, 121, 92, 108, 105, 110, |
| 2041 |
107, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 60, 0, 0, 0, 80, 0, 0, 0, 0, 0 |
| 2042 |
] as &[u8], |
| 2043 |
); |
| 2044 |
} |
| 2045 |
|
| 2046 |
#[test] |
| 2047 |
fn write_mimetype_zip() { |
| 2048 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2049 |
let options = FileOptions { |
| 2050 |
compression_method: CompressionMethod::Stored, |
| 2051 |
compression_level: None, |
| 2052 |
last_modified_time: DateTime::default(), |
| 2053 |
permissions: Some(33188), |
| 2054 |
large_file: false, |
| 2055 |
encrypt_with: None, |
| 2056 |
extended_options: (), |
| 2057 |
alignment: 1, |
| 2058 |
#[cfg(feature = "deflate-zopfli")] |
| 2059 |
zopfli_buffer_size: None, |
| 2060 |
}; |
| 2061 |
writer.start_file("mimetype", options).unwrap(); |
| 2062 |
writer |
| 2063 |
.write_all(b"application/vnd.oasis.opendocument.text") |
| 2064 |
.unwrap(); |
| 2065 |
let result = writer.finish().unwrap(); |
| 2066 |
|
| 2067 |
assert_eq!(result.get_ref().len(), 153); |
| 2068 |
let mut v = Vec::new(); |
| 2069 |
v.extend_from_slice(include_bytes!("../tests/data/mimetype.zip")); |
| 2070 |
assert_eq!(result.get_ref(), &v); |
| 2071 |
} |
| 2072 |
|
| 2073 |
const RT_TEST_TEXT: &str = "And I can't stop thinking about the moments that I lost to you\ |
| 2074 |
And I can't stop thinking of things I used to do\ |
| 2075 |
And I can't stop making bad decisions\ |
| 2076 |
And I can't stop eating stuff you make me chew\ |
| 2077 |
I put on a smile like you wanna see\ |
| 2078 |
Another day goes by that I long to be like you"; |
| 2079 |
const RT_TEST_FILENAME: &str = "subfolder/sub-subfolder/can't_stop.txt"; |
| 2080 |
const SECOND_FILENAME: &str = "different_name.xyz"; |
| 2081 |
const THIRD_FILENAME: &str = "third_name.xyz"; |
| 2082 |
|
| 2083 |
#[test] |
| 2084 |
fn write_non_utf8() { |
| 2085 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2086 |
let options = FileOptions { |
| 2087 |
compression_method: CompressionMethod::Stored, |
| 2088 |
compression_level: None, |
| 2089 |
last_modified_time: DateTime::default(), |
| 2090 |
permissions: Some(33188), |
| 2091 |
large_file: false, |
| 2092 |
encrypt_with: None, |
| 2093 |
extended_options: (), |
| 2094 |
alignment: 1, |
| 2095 |
#[cfg(feature = "deflate-zopfli")] |
| 2096 |
zopfli_buffer_size: None, |
| 2097 |
}; |
| 2098 |
|
| 2099 |
// GB18030 |
| 2100 |
// "δΈζ" = [214, 208, 206, 196] |
| 2101 |
let filename = unsafe { String::from_utf8_unchecked(vec![214, 208, 206, 196]) }; |
| 2102 |
writer.start_file(filename, options).unwrap(); |
| 2103 |
writer.write_all(b"encoding GB18030").unwrap(); |
| 2104 |
|
| 2105 |
// SHIFT_JIS |
| 2106 |
// "ζ₯ζ" = [147, 250, 149, 182] |
| 2107 |
let filename = unsafe { String::from_utf8_unchecked(vec![147, 250, 149, 182]) }; |
| 2108 |
writer.start_file(filename, options).unwrap(); |
| 2109 |
writer.write_all(b"encoding SHIFT_JIS").unwrap(); |
| 2110 |
let result = writer.finish().unwrap(); |
| 2111 |
|
| 2112 |
assert_eq!(result.get_ref().len(), 224); |
| 2113 |
|
| 2114 |
let mut v = Vec::new(); |
| 2115 |
v.extend_from_slice(include_bytes!("../tests/data/non_utf8.zip")); |
| 2116 |
|
| 2117 |
assert_eq!(result.get_ref(), &v); |
| 2118 |
} |
| 2119 |
|
| 2120 |
#[test] |
| 2121 |
fn path_to_string() { |
| 2122 |
let mut path = std::path::PathBuf::new(); |
| 2123 |
#[cfg(windows)] |
| 2124 |
path.push(r"C:\"); |
| 2125 |
#[cfg(unix)] |
| 2126 |
path.push("/"); |
| 2127 |
path.push("windows"); |
| 2128 |
path.push(".."); |
| 2129 |
path.push("."); |
| 2130 |
path.push("system32"); |
| 2131 |
let path_str = super::path_to_string(&path); |
| 2132 |
assert_eq!(&*path_str, "system32"); |
| 2133 |
} |
| 2134 |
|
| 2135 |
#[test] |
| 2136 |
fn test_shallow_copy() { |
| 2137 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2138 |
let options = FileOptions { |
| 2139 |
compression_method: CompressionMethod::default(), |
| 2140 |
compression_level: None, |
| 2141 |
last_modified_time: DateTime::default(), |
| 2142 |
permissions: Some(33188), |
| 2143 |
large_file: false, |
| 2144 |
encrypt_with: None, |
| 2145 |
extended_options: (), |
| 2146 |
alignment: 0, |
| 2147 |
#[cfg(feature = "deflate-zopfli")] |
| 2148 |
zopfli_buffer_size: None, |
| 2149 |
}; |
| 2150 |
writer.start_file(RT_TEST_FILENAME, options).unwrap(); |
| 2151 |
writer.write_all(RT_TEST_TEXT.as_ref()).unwrap(); |
| 2152 |
writer |
| 2153 |
.shallow_copy_file(RT_TEST_FILENAME, SECOND_FILENAME) |
| 2154 |
.unwrap(); |
| 2155 |
writer |
| 2156 |
.shallow_copy_file(RT_TEST_FILENAME, SECOND_FILENAME) |
| 2157 |
.expect_err("Duplicate filename"); |
| 2158 |
let zip = writer.finish().unwrap(); |
| 2159 |
let mut writer = ZipWriter::new_append(zip).unwrap(); |
| 2160 |
writer |
| 2161 |
.shallow_copy_file(SECOND_FILENAME, SECOND_FILENAME) |
| 2162 |
.expect_err("Duplicate filename"); |
| 2163 |
let mut reader = writer.finish_into_readable().unwrap(); |
| 2164 |
let mut file_names: Vec<&str> = reader.file_names().collect(); |
| 2165 |
file_names.sort(); |
| 2166 |
let mut expected_file_names = vec![RT_TEST_FILENAME, SECOND_FILENAME]; |
| 2167 |
expected_file_names.sort(); |
| 2168 |
assert_eq!(file_names, expected_file_names); |
| 2169 |
let mut first_file_content = String::new(); |
| 2170 |
reader |
| 2171 |
.by_name(RT_TEST_FILENAME) |
| 2172 |
.unwrap() |
| 2173 |
.read_to_string(&mut first_file_content) |
| 2174 |
.unwrap(); |
| 2175 |
assert_eq!(first_file_content, RT_TEST_TEXT); |
| 2176 |
let mut second_file_content = String::new(); |
| 2177 |
reader |
| 2178 |
.by_name(SECOND_FILENAME) |
| 2179 |
.unwrap() |
| 2180 |
.read_to_string(&mut second_file_content) |
| 2181 |
.unwrap(); |
| 2182 |
assert_eq!(second_file_content, RT_TEST_TEXT); |
| 2183 |
} |
| 2184 |
|
| 2185 |
#[test] |
| 2186 |
fn test_deep_copy() { |
| 2187 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2188 |
let options = FileOptions { |
| 2189 |
compression_method: CompressionMethod::default(), |
| 2190 |
compression_level: None, |
| 2191 |
last_modified_time: DateTime::default(), |
| 2192 |
permissions: Some(33188), |
| 2193 |
large_file: false, |
| 2194 |
encrypt_with: None, |
| 2195 |
extended_options: (), |
| 2196 |
alignment: 0, |
| 2197 |
#[cfg(feature = "deflate-zopfli")] |
| 2198 |
zopfli_buffer_size: None, |
| 2199 |
}; |
| 2200 |
writer.start_file(RT_TEST_FILENAME, options).unwrap(); |
| 2201 |
writer.write_all(RT_TEST_TEXT.as_ref()).unwrap(); |
| 2202 |
writer |
| 2203 |
.deep_copy_file(RT_TEST_FILENAME, SECOND_FILENAME) |
| 2204 |
.unwrap(); |
| 2205 |
let zip = writer.finish().unwrap(); |
| 2206 |
let mut writer = ZipWriter::new_append(zip).unwrap(); |
| 2207 |
writer |
| 2208 |
.deep_copy_file(RT_TEST_FILENAME, THIRD_FILENAME) |
| 2209 |
.unwrap(); |
| 2210 |
let zip = writer.finish().unwrap(); |
| 2211 |
let mut reader = ZipArchive::new(zip).unwrap(); |
| 2212 |
let mut file_names: Vec<&str> = reader.file_names().collect(); |
| 2213 |
file_names.sort(); |
| 2214 |
let mut expected_file_names = vec![RT_TEST_FILENAME, SECOND_FILENAME, THIRD_FILENAME]; |
| 2215 |
expected_file_names.sort(); |
| 2216 |
assert_eq!(file_names, expected_file_names); |
| 2217 |
let mut first_file_content = String::new(); |
| 2218 |
reader |
| 2219 |
.by_name(RT_TEST_FILENAME) |
| 2220 |
.unwrap() |
| 2221 |
.read_to_string(&mut first_file_content) |
| 2222 |
.unwrap(); |
| 2223 |
assert_eq!(first_file_content, RT_TEST_TEXT); |
| 2224 |
let mut second_file_content = String::new(); |
| 2225 |
reader |
| 2226 |
.by_name(SECOND_FILENAME) |
| 2227 |
.unwrap() |
| 2228 |
.read_to_string(&mut second_file_content) |
| 2229 |
.unwrap(); |
| 2230 |
assert_eq!(second_file_content, RT_TEST_TEXT); |
| 2231 |
} |
| 2232 |
|
| 2233 |
#[test] |
| 2234 |
fn duplicate_filenames() { |
| 2235 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2236 |
writer |
| 2237 |
.start_file("foo/bar/test", SimpleFileOptions::default()) |
| 2238 |
.unwrap(); |
| 2239 |
writer |
| 2240 |
.write_all("The quick brown π¦ jumps over the lazy π".as_bytes()) |
| 2241 |
.unwrap(); |
| 2242 |
writer |
| 2243 |
.start_file("foo/bar/test", SimpleFileOptions::default()) |
| 2244 |
.expect_err("Expected duplicate filename not to be allowed"); |
| 2245 |
} |
| 2246 |
|
| 2247 |
#[test] |
| 2248 |
fn test_filename_looks_like_zip64_locator() { |
| 2249 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2250 |
writer |
| 2251 |
.start_file( |
| 2252 |
"PK\u{6}\u{7}\0\0\0\u{11}\0\0\0\0\0\0\0\0\0\0\0\0", |
| 2253 |
SimpleFileOptions::default(), |
| 2254 |
) |
| 2255 |
.unwrap(); |
| 2256 |
let zip = writer.finish().unwrap(); |
| 2257 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2258 |
} |
| 2259 |
|
| 2260 |
#[test] |
| 2261 |
fn test_filename_looks_like_zip64_locator_2() { |
| 2262 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2263 |
writer |
| 2264 |
.start_file( |
| 2265 |
"PK\u{6}\u{6}\0\0\0\0\0\0\0\0\0\0PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", |
| 2266 |
SimpleFileOptions::default(), |
| 2267 |
) |
| 2268 |
.unwrap(); |
| 2269 |
let zip = writer.finish().unwrap(); |
| 2270 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2271 |
} |
| 2272 |
|
| 2273 |
#[test] |
| 2274 |
fn test_filename_looks_like_zip64_locator_2a() { |
| 2275 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2276 |
writer |
| 2277 |
.start_file( |
| 2278 |
"PK\u{6}\u{6}PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", |
| 2279 |
SimpleFileOptions::default(), |
| 2280 |
) |
| 2281 |
.unwrap(); |
| 2282 |
let zip = writer.finish().unwrap(); |
| 2283 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2284 |
} |
| 2285 |
|
| 2286 |
#[test] |
| 2287 |
fn test_filename_looks_like_zip64_locator_3() { |
| 2288 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2289 |
writer |
| 2290 |
.start_file("\0PK\u{6}\u{6}", SimpleFileOptions::default()) |
| 2291 |
.unwrap(); |
| 2292 |
writer |
| 2293 |
.start_file( |
| 2294 |
"\0\u{4}\0\0PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\u{3}", |
| 2295 |
SimpleFileOptions::default(), |
| 2296 |
) |
| 2297 |
.unwrap(); |
| 2298 |
let zip = writer.finish().unwrap(); |
| 2299 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2300 |
} |
| 2301 |
|
| 2302 |
#[test] |
| 2303 |
fn test_filename_looks_like_zip64_locator_4() { |
| 2304 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2305 |
writer |
| 2306 |
.start_file("PK\u{6}\u{6}", SimpleFileOptions::default()) |
| 2307 |
.unwrap(); |
| 2308 |
writer |
| 2309 |
.start_file("\0\0\0\0\0\0", SimpleFileOptions::default()) |
| 2310 |
.unwrap(); |
| 2311 |
writer |
| 2312 |
.start_file("\0", SimpleFileOptions::default()) |
| 2313 |
.unwrap(); |
| 2314 |
writer.start_file("", SimpleFileOptions::default()).unwrap(); |
| 2315 |
writer |
| 2316 |
.start_file("\0\0", SimpleFileOptions::default()) |
| 2317 |
.unwrap(); |
| 2318 |
writer |
| 2319 |
.start_file( |
| 2320 |
"\0\0\0PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", |
| 2321 |
SimpleFileOptions::default(), |
| 2322 |
) |
| 2323 |
.unwrap(); |
| 2324 |
let zip = writer.finish().unwrap(); |
| 2325 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2326 |
} |
| 2327 |
|
| 2328 |
#[test] |
| 2329 |
fn test_filename_looks_like_zip64_locator_5() -> ZipResult<()> { |
| 2330 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2331 |
writer |
| 2332 |
.add_directory("", SimpleFileOptions::default().with_alignment(21)) |
| 2333 |
.unwrap(); |
| 2334 |
let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap(); |
| 2335 |
writer.shallow_copy_file("/", "").unwrap(); |
| 2336 |
writer.shallow_copy_file("", "\0").unwrap(); |
| 2337 |
writer.shallow_copy_file("\0", "PK\u{6}\u{6}").unwrap(); |
| 2338 |
let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap(); |
| 2339 |
writer |
| 2340 |
.start_file("\0\0\0\0\0\0", SimpleFileOptions::default()) |
| 2341 |
.unwrap(); |
| 2342 |
let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap(); |
| 2343 |
writer |
| 2344 |
.start_file( |
| 2345 |
"#PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", |
| 2346 |
SimpleFileOptions::default(), |
| 2347 |
) |
| 2348 |
.unwrap(); |
| 2349 |
let zip = writer.finish().unwrap(); |
| 2350 |
let _ = ZipArchive::new(zip).unwrap(); |
| 2351 |
Ok(()) |
| 2352 |
} |
| 2353 |
|
| 2354 |
#[test] |
| 2355 |
fn remove_shallow_copy_keeps_original() -> ZipResult<()> { |
| 2356 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2357 |
writer |
| 2358 |
.start_file("original", SimpleFileOptions::default()) |
| 2359 |
.unwrap(); |
| 2360 |
writer.write_all(RT_TEST_TEXT.as_bytes()).unwrap(); |
| 2361 |
writer |
| 2362 |
.shallow_copy_file("original", "shallow_copy") |
| 2363 |
.unwrap(); |
| 2364 |
writer.abort_file().unwrap(); |
| 2365 |
let mut zip = ZipArchive::new(writer.finish().unwrap()).unwrap(); |
| 2366 |
let mut file = zip.by_name("original").unwrap(); |
| 2367 |
let mut contents = Vec::new(); |
| 2368 |
file.read_to_end(&mut contents).unwrap(); |
| 2369 |
assert_eq!(RT_TEST_TEXT.as_bytes(), contents); |
| 2370 |
Ok(()) |
| 2371 |
} |
| 2372 |
|
| 2373 |
#[test] |
| 2374 |
fn remove_encrypted_file() -> ZipResult<()> { |
| 2375 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2376 |
let first_file_options = SimpleFileOptions::default() |
| 2377 |
.with_alignment(65535) |
| 2378 |
.with_deprecated_encryption(b"Password"); |
| 2379 |
writer.start_file("", first_file_options).unwrap(); |
| 2380 |
writer.abort_file().unwrap(); |
| 2381 |
let zip = writer.finish().unwrap(); |
| 2382 |
let mut writer = ZipWriter::new(zip); |
| 2383 |
writer.start_file("", SimpleFileOptions::default()).unwrap(); |
| 2384 |
Ok(()) |
| 2385 |
} |
| 2386 |
|
| 2387 |
#[test] |
| 2388 |
fn remove_encrypted_aligned_symlink() -> ZipResult<()> { |
| 2389 |
let mut options = SimpleFileOptions::default(); |
| 2390 |
options = options.with_deprecated_encryption(b"Password"); |
| 2391 |
options.alignment = 65535; |
| 2392 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2393 |
writer.add_symlink("", "s\t\0\0ggggg\0\0", options).unwrap(); |
| 2394 |
writer.abort_file().unwrap(); |
| 2395 |
let zip = writer.finish().unwrap(); |
| 2396 |
let mut writer = ZipWriter::new_append(zip).unwrap(); |
| 2397 |
writer.start_file("", SimpleFileOptions::default()).unwrap(); |
| 2398 |
Ok(()) |
| 2399 |
} |
| 2400 |
|
| 2401 |
#[cfg(feature = "deflate-zopfli")] |
| 2402 |
#[test] |
| 2403 |
fn zopfli_empty_write() -> ZipResult<()> { |
| 2404 |
let mut options = SimpleFileOptions::default(); |
| 2405 |
options = options |
| 2406 |
.compression_method(CompressionMethod::default()) |
| 2407 |
.compression_level(Some(264)); |
| 2408 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2409 |
writer.start_file("", options).unwrap(); |
| 2410 |
writer.write_all(&[]).unwrap(); |
| 2411 |
writer.write_all(&[]).unwrap(); |
| 2412 |
Ok(()) |
| 2413 |
} |
| 2414 |
|
| 2415 |
#[test] |
| 2416 |
fn crash_with_no_features() -> ZipResult<()> { |
| 2417 |
const ORIGINAL_FILE_NAME: &str = "PK\u{6}\u{6}\0\0\0\0\0\0\0\0\0\u{2}g\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\u{1}\0\0\0\0\0\0\0\0\0\0PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\u{7}\0\t'"; |
| 2418 |
let mut writer = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2419 |
let mut options = SimpleFileOptions::default(); |
| 2420 |
options = options |
| 2421 |
.with_alignment(3584) |
| 2422 |
.compression_method(CompressionMethod::Stored); |
| 2423 |
writer.start_file(ORIGINAL_FILE_NAME, options)?; |
| 2424 |
let archive = writer.finish()?; |
| 2425 |
let mut writer = ZipWriter::new_append(archive)?; |
| 2426 |
writer.shallow_copy_file(ORIGINAL_FILE_NAME, "\u{6}\\")?; |
| 2427 |
writer.finish()?; |
| 2428 |
Ok(()) |
| 2429 |
} |
| 2430 |
|
| 2431 |
#[test] |
| 2432 |
fn test_alignment() { |
| 2433 |
let page_size = 4096; |
| 2434 |
let options = SimpleFileOptions::default() |
| 2435 |
.compression_method(CompressionMethod::Stored) |
| 2436 |
.with_alignment(page_size); |
| 2437 |
let mut zip = ZipWriter::new(io::Cursor::new(Vec::new())); |
| 2438 |
let contents = b"sleeping"; |
| 2439 |
let () = zip.start_file("sleep", options).unwrap(); |
| 2440 |
let _count = zip.write(&contents[..]).unwrap(); |
| 2441 |
let mut zip = zip.finish_into_readable().unwrap(); |
| 2442 |
let file = zip.by_index(0).unwrap(); |
| 2443 |
assert_eq!(file.name(), "sleep"); |
| 2444 |
assert_eq!(file.data_start(), page_size.into()); |
| 2445 |
} |
| 2446 |
|
| 2447 |
#[test] |
| 2448 |
fn test_crash_short_read() { |
| 2449 |
let mut writer = ZipWriter::new(Cursor::new(Vec::new())); |
| 2450 |
let comment = vec![ |
| 2451 |
1, 80, 75, 5, 6, 237, 237, 237, 237, 237, 237, 237, 237, 44, 255, 191, 255, 255, 255, |
| 2452 |
255, 255, 255, 255, 255, 16, |
| 2453 |
] |
| 2454 |
.into_boxed_slice(); |
| 2455 |
writer.set_raw_comment(comment); |
| 2456 |
let options = SimpleFileOptions::default() |
| 2457 |
.compression_method(Stored) |
| 2458 |
.with_alignment(11823); |
| 2459 |
writer.start_file("", options).unwrap(); |
| 2460 |
writer.write_all(&[255, 255, 44, 255, 0]).unwrap(); |
| 2461 |
let written = writer.finish().unwrap(); |
| 2462 |
let _ = ZipWriter::new_append(written).unwrap(); |
| 2463 |
} |
| 2464 |
|
| 2465 |
#[cfg(all(feature = "_deflate-any", feature = "aes-crypto"))] |
| 2466 |
#[test] |
| 2467 |
fn test_fuzz_failure_2024_05_08() -> ZipResult<()> { |
| 2468 |
let mut first_writer = ZipWriter::new(Cursor::new(Vec::new())); |
| 2469 |
let mut second_writer = ZipWriter::new(Cursor::new(Vec::new())); |
| 2470 |
let options = SimpleFileOptions::default() |
| 2471 |
.compression_method(Stored) |
| 2472 |
.with_alignment(46036); |
| 2473 |
second_writer.add_symlink("\0", "", options)?; |
| 2474 |
let second_archive = second_writer.finish_into_readable()?.into_inner(); |
| 2475 |
let mut second_writer = ZipWriter::new_append(second_archive)?; |
| 2476 |
let options = SimpleFileOptions::default() |
| 2477 |
.compression_method(CompressionMethod::Deflated) |
| 2478 |
.large_file(true) |
| 2479 |
.with_alignment(46036) |
| 2480 |
.with_aes_encryption(crate::AesMode::Aes128, "\0\0"); |
| 2481 |
second_writer.add_symlink("", "", options)?; |
| 2482 |
let second_archive = second_writer.finish_into_readable()?.into_inner(); |
| 2483 |
let mut second_writer = ZipWriter::new_append(second_archive)?; |
| 2484 |
let options = SimpleFileOptions::default().compression_method(Stored); |
| 2485 |
second_writer.start_file(" ", options)?; |
| 2486 |
let second_archive = second_writer.finish_into_readable()?; |
| 2487 |
first_writer.merge_archive(second_archive)?; |
| 2488 |
let _ = ZipArchive::new(first_writer.finish()?)?; |
| 2489 |
Ok(()) |
| 2490 |
} |
| 2491 |
} |