Skip to main content

zip/
write.rs

1//! Writing a ZIP archive
2
3use crate::ExtraField;
4use crate::compression::CompressionMethod;
5use crate::datetime::DateTime;
6use crate::extra_fields::DataStreamAlignment;
7use crate::extra_fields::Zip64ExtendedInformation;
8use crate::format::blocks::{
9    FixedSizeBlock, Zip32CDEBlock, Zip32CentralDirectoryEnd, Zip64CentralDirectoryEnd,
10    Zip64CentralDirectoryEndLocator, ZipCentralEntryBlock, ZipLocalEntryBlock,
11};
12use crate::format::ffi;
13use crate::format::flags::ZipFlags;
14use crate::format::magic::Magic;
15use crate::format::{ZIP64_BYTES_THR, ZIP64_BYTES_THR_U32, ZIP64_ENTRY_THR};
16use crate::read::{Config, ZipArchive, ZipFile};
17use crate::result::{ZipError, ZipResult, invalid};
18use crate::types::{MIN_VERSION, ZipFileData, ZipRawValues};
19use crate::write::options::EncryptWith;
20
21use core::default::Default;
22use core::fmt::{Debug, Formatter};
23use core::mem::{self, offset_of, replace, size_of, take};
24#[cfg(feature = "rayon")]
25use core::num::NonZeroUsize;
26use core::str::{Utf8Error, from_utf8};
27use crc32fast::Hasher;
28use indexmap::IndexMap;
29use std::io::Cursor;
30use std::io::ErrorKind;
31use std::io::SeekFrom;
32use std::io::{self, Read, Seek, Write};
33use std::path::Path;
34
35pub(crate) mod options;
36
37// re-export from types
38pub use crate::write::options::{
39    ExtendedFileOptions, FileOptions, FullFileOptions, SimpleFileOptions,
40};
41
42#[allow(clippy::large_enum_variant)]
43enum MaybeEncrypted<W> {
44    Unencrypted(W),
45    #[cfg(feature = "aes-crypto")]
46    Aes(crate::aes::AesWriter<W>),
47    ZipCrypto(crate::zipcrypto::ZipCryptoWriter<W>),
48    /// Placeholder parked inside an idle, cached `flate2::write::DeflateEncoder` between DEFLATE
49    /// entries (see [`DeflateCache`]). It discards anything written to it; the only bytes it can
50    /// ever receive are the empty final block flate2's `Drop` emits when an idle encoder is
51    /// dropped.
52    #[cfg(feature = "deflate-flate2")]
53    Closed {
54        bytes_written: usize,
55    },
56}
57
58impl<W: Write> MaybeEncrypted<W> {
59    fn get_ref(&self) -> Option<&W> {
60        match self {
61            MaybeEncrypted::Unencrypted(w) => Some(w),
62            #[cfg(feature = "aes-crypto")]
63            MaybeEncrypted::Aes(w) => Some(w.get_ref()),
64            MaybeEncrypted::ZipCrypto(w) => Some(w.get_ref()),
65            #[cfg(feature = "deflate-flate2")]
66            MaybeEncrypted::Closed { .. } => None,
67        }
68    }
69    /// Returns a mutable reference to the underlying writer.
70    ///
71    /// # Safety
72    /// The caller must preserve all invariants expected by the active wrapper
73    /// (`Unencrypted`, `Aes`, or `ZipCrypto`):
74    /// - Do not mutate the writer in a way that desynchronizes ZIP/encryption state.
75    /// - Do not seek/write behind the wrapper's back such that subsequent writes
76    ///   produce an invalid archive.
77    /// - Ensure normal `&mut` exclusivity guarantees are upheld for the returned reference.
78    unsafe fn get_mut(&mut self) -> Option<&mut W> {
79        match self {
80            MaybeEncrypted::Unencrypted(w) => Some(w),
81            #[cfg(feature = "aes-crypto")]
82            MaybeEncrypted::Aes(w) => Some(unsafe { w.get_mut() }),
83            MaybeEncrypted::ZipCrypto(w) => Some(w.get_mut()),
84            #[cfg(feature = "deflate-flate2")]
85            MaybeEncrypted::Closed { .. } => None,
86        }
87    }
88}
89
90impl<W> Debug for MaybeEncrypted<W> {
91    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
92        // Don't print W, since it may be a huge Vec<u8>
93        f.write_str(match self {
94            MaybeEncrypted::Unencrypted(_) => "Unencrypted",
95            #[cfg(feature = "aes-crypto")]
96            MaybeEncrypted::Aes(_) => "AES",
97            MaybeEncrypted::ZipCrypto(_) => "ZipCrypto",
98            #[cfg(feature = "deflate-flate2")]
99            MaybeEncrypted::Closed { .. } => "Closed",
100        })
101    }
102}
103
104impl<W: Write> Write for MaybeEncrypted<W> {
105    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
106        match self {
107            MaybeEncrypted::Unencrypted(w) => w.write(buf),
108            #[cfg(feature = "aes-crypto")]
109            MaybeEncrypted::Aes(w) => w.write(buf),
110            MaybeEncrypted::ZipCrypto(w) => w.write(buf),
111            #[cfg(feature = "deflate-flate2")]
112            MaybeEncrypted::Closed { bytes_written } => {
113                *bytes_written = (*bytes_written).saturating_add(buf.len());
114                if *bytes_written > 2 {
115                    Err(io::Error::new(
116                        ErrorKind::FileTooLarge,
117                        "More than 2 bytes unexpectedly written to Deflate encoder's closed internal writer",
118                    ))
119                } else {
120                    Ok(buf.len())
121                }
122            }
123        }
124    }
125    fn flush(&mut self) -> io::Result<()> {
126        match self {
127            MaybeEncrypted::Unencrypted(w) => w.flush(),
128            #[cfg(feature = "aes-crypto")]
129            MaybeEncrypted::Aes(w) => w.flush(),
130            MaybeEncrypted::ZipCrypto(w) => w.flush(),
131            #[cfg(feature = "deflate-flate2")]
132            MaybeEncrypted::Closed { .. } => Ok(()),
133        }
134    }
135}
136
137#[allow(clippy::large_enum_variant)]
138enum GenericZipWriter<W: Write + Seek> {
139    Closed,
140    Storer(MaybeEncrypted<W>),
141    #[cfg(feature = "deflate-flate2")]
142    Deflater(flate2::write::DeflateEncoder<MaybeEncrypted<W>>),
143    #[cfg(feature = "deflate-zopfli")]
144    ZopfliDeflater(zopfli::DeflateEncoder<MaybeEncrypted<W>>),
145    #[cfg(feature = "deflate-zopfli")]
146    BufferedZopfliDeflater(std::io::BufWriter<zopfli::DeflateEncoder<MaybeEncrypted<W>>>),
147    #[cfg(feature = "_bzip2_any")]
148    Bzip2(bzip2::write::BzEncoder<MaybeEncrypted<W>>),
149    #[cfg(feature = "zstd")]
150    Zstd(zstd::stream::write::Encoder<'static, MaybeEncrypted<W>>),
151    #[cfg(feature = "xz")]
152    Xz(Box<lzma_rust2::XzWriter<MaybeEncrypted<W>>>),
153    #[cfg(feature = "ppmd")]
154    Ppmd(Box<ppmd_rust::Ppmd8Encoder<MaybeEncrypted<W>>>),
155}
156
157enum NextWriter {
158    Stored,
159    #[cfg(feature = "deflate-flate2")]
160    Deflate(u32),
161    #[cfg(feature = "deflate-zopfli")]
162    Zopfli {
163        options: zopfli::Options,
164        buffer_size: Option<usize>,
165    },
166    #[cfg(feature = "_bzip2_any")]
167    Bzip2(u32),
168    #[cfg(feature = "zstd")]
169    Zstd(i32),
170    #[cfg(feature = "xz")]
171    Xz(u32),
172    #[cfg(feature = "ppmd")]
173    Ppmd {
174        order: u32,
175        memory_size: u32,
176    },
177}
178
179impl<W: Write + Seek> Debug for GenericZipWriter<W> {
180    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
181        match self {
182            Self::Closed => f.write_str("Closed"),
183            Self::Storer(w) => f.write_fmt(format_args!("Storer({w:?})")),
184            #[cfg(feature = "deflate-flate2")]
185            Self::Deflater(w) => f.write_fmt(format_args!("Deflater({:?})", w.get_ref())),
186            #[cfg(feature = "deflate-zopfli")]
187            Self::ZopfliDeflater(_) => f.write_str("ZopfliDeflater"),
188            #[cfg(feature = "deflate-zopfli")]
189            Self::BufferedZopfliDeflater(_) => f.write_str("BufferedZopfliDeflater"),
190            #[cfg(feature = "_bzip2_any")]
191            Self::Bzip2(w) => f.write_fmt(format_args!("Bzip2({:?})", w.get_ref())),
192            #[cfg(feature = "zstd")]
193            Self::Zstd(w) => f.write_fmt(format_args!("Zstd({:?})", w.get_ref())),
194            #[cfg(feature = "xz")]
195            Self::Xz(w) => f.write_fmt(format_args!("Xz({:?})", w.inner())),
196            #[cfg(feature = "ppmd")]
197            Self::Ppmd(_) => f.write_fmt(format_args!("Ppmd8Encoder")),
198        }
199    }
200}
201
202// Put the struct declaration in a private module to convince rustdoc to display ZipWriter nicely
203pub(crate) mod zip_writer {
204    #[cfg(feature = "deflate-flate2")]
205    use super::DeflateCache;
206    use crate::types::FilesByNameMap;
207    use crate::write::{GenericZipWriter, ZipWriterStats};
208    use core::fmt::{Debug, Formatter};
209    use std::io::{Seek, Write};
210
211    /// ZIP archive generator
212    ///
213    /// Handles the bookkeeping involved in building an archive, and provides an
214    /// API to edit its contents.
215    ///
216    /// ```
217    /// # fn doit() -> zip::result::ZipResult<()>
218    /// # {
219    /// use zip::ZipWriter;
220    /// use std::io::Write;
221    /// use zip::write::SimpleFileOptions;
222    ///
223    /// // We use a cursor + vec here, though you'd normally use a `File`
224    /// let mut cursor = std::io::Cursor::new(Vec::new());
225    /// let mut archive = ZipWriter::new(&mut cursor);
226    ///
227    /// let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
228    /// archive.start_file("hello_world.txt", options)?;
229    /// archive.write(b"Hello, World!")?;
230    /// // also direct write with
231    /// // std::io::copy(&mut file, &mut zip)?;
232    ///
233    /// // Apply the changes you've made.
234    /// // Dropping the `ZipWriter` will have the same effect, but may silently fail
235    /// archive.finish()?;
236    ///
237    /// // raw zip data is available as a Vec<u8>
238    /// let zip_bytes = cursor.into_inner();
239    ///
240    /// # Ok(())
241    /// # }
242    /// # doit().unwrap();
243    /// ```
244    pub struct ZipWriter<W: Write + Seek> {
245        pub(super) inner: GenericZipWriter<W>,
246        pub(super) files: FilesByNameMap,
247        pub(super) stats: ZipWriterStats,
248        pub(super) writing_to_file: bool,
249        pub(super) writing_raw: bool,
250        pub(super) comment: Box<[u8]>,
251        pub(super) zip64_extensible_data_sector: Option<Box<[u8]>>,
252        pub(super) flush_on_finish_file: bool,
253        pub(super) seek_possible: bool,
254        pub(crate) auto_large_file: bool,
255        /// Idle DEFLATE compressor kept between entries to avoid reallocating it (#633).
256        #[cfg(feature = "deflate-flate2")]
257        pub(super) deflate_cache: DeflateCache<W>,
258    }
259
260    impl<W: Write + Seek> Debug for ZipWriter<W> {
261        fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
262            f.write_fmt(format_args!(
263                "ZipWriter {{files: {:?}, stats: {:?}, writing_to_file: {}, writing_raw: {}, comment: {:?}, flush_on_finish_file: {}}}",
264                self.files, self.stats, self.writing_to_file, self.writing_raw,
265                self.comment, self.flush_on_finish_file))
266        }
267    }
268
269    impl<W: Write + Seek> ZipWriter<W> {
270        /// Gets a reference to the underlying writer in this `ZipWriter`.
271        pub fn get_ref(&self) -> Option<&W> {
272            match &self.inner {
273                GenericZipWriter::Closed => None,
274                GenericZipWriter::Storer(w) => w.get_ref(),
275                #[cfg(feature = "deflate-flate2")]
276                GenericZipWriter::Deflater(w) => w.get_ref().get_ref(),
277                #[cfg(feature = "deflate-zopfli")]
278                GenericZipWriter::ZopfliDeflater(w) => w.get_ref().get_ref(),
279                #[cfg(feature = "deflate-zopfli")]
280                GenericZipWriter::BufferedZopfliDeflater(w) => w.get_ref().get_ref().get_ref(),
281                #[cfg(feature = "_bzip2_any")]
282                GenericZipWriter::Bzip2(w) => w.get_ref().get_ref(),
283                #[cfg(feature = "zstd")]
284                GenericZipWriter::Zstd(w) => w.get_ref().get_ref(),
285                #[cfg(feature = "xz")]
286                GenericZipWriter::Xz(w) => w.inner().get_ref(),
287                #[cfg(feature = "ppmd")]
288                GenericZipWriter::Ppmd(w) => w.get_ref().get_ref(),
289            }
290        }
291
292        /// Gets a reference to the underlying writer in this `ZipWriter`.
293        ///
294        /// # Safety
295        ///
296        /// Caller must not corrupt the archive, and must seek back to the current position
297        /// before continuing to write to the `ZipWriter`.
298        pub unsafe fn get_mut(&mut self) -> Option<&mut W> {
299            unsafe {
300                match &mut self.inner {
301                    GenericZipWriter::Closed => None,
302                    GenericZipWriter::Storer(w) => w.get_mut(),
303                    #[cfg(feature = "deflate-flate2")]
304                    GenericZipWriter::Deflater(w) => w.get_mut().get_mut(),
305                    #[cfg(feature = "deflate-zopfli")]
306                    GenericZipWriter::ZopfliDeflater(w) => w.get_mut().get_mut(),
307                    #[cfg(feature = "deflate-zopfli")]
308                    GenericZipWriter::BufferedZopfliDeflater(w) => w.get_mut().get_mut().get_mut(),
309                    #[cfg(feature = "_bzip2_any")]
310                    GenericZipWriter::Bzip2(w) => w.get_mut().get_mut(),
311                    #[cfg(feature = "zstd")]
312                    GenericZipWriter::Zstd(w) => w.get_mut().get_mut(),
313                    #[cfg(feature = "xz")]
314                    GenericZipWriter::Xz(w) => w.inner_mut().get_mut(),
315                    #[cfg(feature = "ppmd")]
316                    GenericZipWriter::Ppmd(w) => w.get_mut().get_mut(),
317                }
318            }
319        }
320    }
321}
322#[doc(inline)]
323pub use self::options::sealed::FileOptionExtension;
324use crate::CompressionMethod::Stored;
325use crate::result::ZipError::UnsupportedArchive;
326use crate::unstable::path_to_string;
327use crate::zipcrypto::CHUNK_SIZE;
328pub use zip_writer::ZipWriter;
329
330#[derive(Default, Debug)]
331struct ZipWriterStats {
332    hasher: Hasher,
333    start: u64,
334    bytes_written: u64,
335}
336
337impl<W: Write + Seek> Write for ZipWriter<W> {
338    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
339        if !self.writing_to_file {
340            return Err(io::Error::other("No file has been started"));
341        }
342        if buf.is_empty() {
343            return Ok(0);
344        }
345        match self.inner.ref_mut() {
346            Some(ref mut w) => {
347                let write_result = w.write(buf);
348                if let Ok(count) = write_result {
349                    self.stats.update(&buf[..count]);
350                    // Only perform the expensive large-file check when we first cross the threshold.
351                    if self.stats.bytes_written >= ZIP64_BYTES_THR {
352                        let is_large_file = self
353                            .files
354                            .last()
355                            .ok_or_else(|| std::io::Error::other("Cannot get last file"))?
356                            .1
357                            .large_file;
358                        if !is_large_file {
359                            return Err(if let Err(e) = self.abort_file() {
360                                let abort_io_err: io::Error = e.into();
361                                io::Error::new(
362                                    abort_io_err.kind(),
363                                    format!(
364                                        "Large file option has not been set and abort_file() failed: {abort_io_err}"
365                                    ),
366                                )
367                            } else {
368                                io::Error::other("Large file option has not been set")
369                            });
370                        }
371                    }
372                }
373                write_result
374            }
375            None => Err(io::Error::new(
376                io::ErrorKind::BrokenPipe,
377                "write(): ZipWriter was already closed",
378            )),
379        }
380    }
381
382    fn flush(&mut self) -> io::Result<()> {
383        match self.inner.ref_mut() {
384            Some(ref mut w) => w.flush(),
385            None => Err(io::Error::new(
386                io::ErrorKind::BrokenPipe,
387                "flush(): ZipWriter was already closed",
388            )),
389        }
390    }
391}
392
393impl ZipWriterStats {
394    fn update(&mut self, buf: &[u8]) {
395        self.hasher.update(buf);
396        self.bytes_written += buf.len() as u64;
397    }
398}
399
400impl<A: Read + Write + Seek> ZipWriter<A> {
401    /// Initializes the archive from an existing ZIP archive, making it ready for append.
402    ///
403    /// This uses a default configuration to initially read the archive.
404    pub fn new_append(readwriter: A) -> ZipResult<ZipWriter<A>> {
405        Self::new_append_with_config(Config::default(), readwriter)
406    }
407
408    /// Initializes the archive from an existing ZIP archive, making it ready for append.
409    ///
410    /// This uses the given read configuration to initially read the archive.
411    pub fn new_append_with_config(config: Config, mut readwriter: A) -> ZipResult<ZipWriter<A>> {
412        readwriter.seek(SeekFrom::Start(0))?;
413        let metadata = ZipArchive::get_metadata(config, &mut readwriter)?;
414        // `ZipArchive::get_metadata` leaves `readwriter` at the end of the central directory;
415        // seek back to its start so appended entries overwrite it instead of leaving a second one.
416        readwriter.seek(SeekFrom::Start(metadata.shared.dir_start))?;
417        Ok(ZipWriter {
418            inner: GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(readwriter)),
419            files: metadata.shared.files,
420            stats: ZipWriterStats::default(),
421            writing_to_file: false,
422            comment: metadata.comment,
423            zip64_extensible_data_sector: metadata.zip64_extensible_data_sector,
424            writing_raw: true, // avoid recomputing the last file's header
425            flush_on_finish_file: false,
426            seek_possible: true,
427            auto_large_file: false,
428            #[cfg(feature = "deflate-flate2")]
429            deflate_cache: DeflateCache::default(),
430        })
431    }
432
433    /// `flush_on_finish_file` is designed to support a streaming `inner` that may unload flushed
434    /// bytes. It flushes a file's header and body once it starts writing another file. A `ZipWriter`
435    /// will not try to seek back into where a previous file was written unless
436    /// either [`ZipWriter::abort_file`] is called while [`ZipWriter::is_writing_file`] returns
437    /// false, or [`ZipWriter::deep_copy_file`] is called. In the latter case, it will only need to
438    /// read previously-written files and not overwrite them.
439    ///
440    /// Note: when using an `inner` that cannot overwrite flushed bytes, do not wrap it in a
441    /// [`std::io::BufWriter`], because that has a [`Seek::seek`] method that implicitly calls
442    /// [`std::io::BufWriter::flush`], and `ZipWriter` needs to seek backward to update each file's header with
443    /// the size and checksum after writing the body.
444    ///
445    /// This setting is false by default.
446    pub fn set_flush_on_finish_file(&mut self, flush_on_finish_file: bool) {
447        self.flush_on_finish_file = flush_on_finish_file;
448    }
449}
450
451impl<A: Read + Write + Seek> ZipWriter<A> {
452    /// Adds another copy of a file already in this archive. This will produce a larger but more
453    /// widely-compatible archive compared to [`Self::shallow_copy_file`]. Does not copy alignment.
454    pub fn deep_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()> {
455        self.finish_file()?;
456        if src_name == dest_name || self.files.contains_key(dest_name.as_bytes()) {
457            return Err(invalid!("That file already exists"));
458        }
459        let write_position = self.inner.try_inner_mut()?.stream_position()?;
460        let src_index = self.index_by_name(src_name.as_bytes())?;
461        let src_data = &mut self.files[src_index];
462        let src_data_start = src_data.data_start(self.inner.try_inner_mut()?)?;
463        // `src_data_start` comes from the local header, which may be untrusted (e.g. after
464        // `new_append`); it can point past the current end of the archive.
465        let available = write_position
466            .checked_sub(src_data_start)
467            .ok_or(invalid!("File data starts past the end of the archive"))?;
468        let mut compressed_size = src_data.compressed_size;
469        if compressed_size > available {
470            compressed_size = available;
471            src_data.compressed_size = compressed_size;
472        }
473        self.inner
474            .try_inner_mut()?
475            .seek(SeekFrom::Start(write_position))?;
476        let mut new_data = src_data.clone();
477        let dest_name_raw = dest_name.as_bytes();
478        new_data.header_start = write_position;
479        new_data.central_header_start = 0;
480        new_data.set_language_encoding_for(dest_name_raw);
481        new_data.drop_unicode_path_renaming(dest_name_raw);
482        let index = self.insert_file_data(dest_name_raw, new_data)?;
483        let new_data = &mut self.files[index];
484        let result: io::Result<()> = {
485            let plain_writer = self.inner.try_inner_mut()?;
486            new_data.write_local_header(write_position, plain_writer, dest_name_raw, None)?;
487            debug_assert_eq!(
488                new_data.data_start.get(),
489                Some(&plain_writer.stream_position()?)
490            );
491            self.writing_to_file = true;
492            // Both entries live in `self.inner`: `src_name` was resolved from this
493            // writer's file table, including when the writer was opened by `new_append`.
494            // The source ends at or before `write_position`, so a bounded buffer can
495            // copy it into the new entry without overwriting unread source bytes.
496            let mut buffer = [0u8; 64 * 1024];
497            let mut src_pos = src_data_start;
498            let mut dst_pos = plain_writer.stream_position()?;
499            let mut remaining = compressed_size;
500            while remaining != 0 {
501                let n = remaining.min(buffer.len() as u64) as usize;
502                plain_writer.seek(SeekFrom::Start(src_pos))?;
503                plain_writer.read_exact(&mut buffer[..n])?;
504                plain_writer.seek(SeekFrom::Start(dst_pos))?;
505                plain_writer.write_all(&buffer[..n])?;
506                src_pos = src_pos
507                    .checked_add(n as u64)
508                    .ok_or_else(|| io::Error::other("source offset overflows u64"))?;
509                dst_pos = dst_pos
510                    .checked_add(n as u64)
511                    .ok_or_else(|| io::Error::other("destination offset overflows u64"))?;
512                remaining -= n as u64;
513            }
514            if self.flush_on_finish_file {
515                plain_writer.flush()?;
516            }
517            Ok(())
518        };
519        self.ok_or_abort_file(result)?;
520        self.writing_to_file = false;
521        Ok(())
522    }
523
524    /// Like `deep_copy_file`, but uses Path arguments.
525    ///
526    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
527    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
528    /// root.
529    pub fn deep_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>(
530        &mut self,
531        src_path: T,
532        dest_path: U,
533    ) -> ZipResult<()> {
534        let src = path_to_string(src_path)?;
535        let dest = path_to_string(dest_path)?;
536        self.deep_copy_file(&src, &dest)
537    }
538
539    /// Write the zip file into the backing stream, then produce a readable archive of that data.
540    ///
541    /// This method avoids parsing the central directory records at the end of the stream for
542    /// a slight performance improvement over running [`ZipArchive::new()`] on the output of
543    /// [`Self::finish()`].
544    ///
545    ///```
546    /// # fn main() -> Result<(), zip::result::ZipError> {
547    /// # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
548    /// # {
549    /// use std::io::{Cursor, Read, Write};
550    /// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};
551    ///
552    /// let buf = Cursor::new(Vec::new());
553    /// let mut zip = ZipWriter::new(buf);
554    /// let options = SimpleFileOptions::default();
555    /// zip.start_file("a.txt", options)?;
556    /// zip.write_all(b"hello\n")?;
557    ///
558    /// let mut zip = zip.finish_into_readable()?;
559    /// let mut s: String = String::new();
560    /// zip.by_name("a.txt")?.read_to_string(&mut s)?;
561    /// assert_eq!(s, "hello\n");
562    /// # }
563    /// # Ok(())
564    /// # }
565    ///```
566    pub fn finish_into_readable(mut self) -> ZipResult<ZipArchive<A>> {
567        let (last_file_end, central_start) = self.finalize()?;
568        let inner = self.close_writer()?;
569        let comment = mem::take(&mut self.comment);
570        let zip64_extensible_data_sector = mem::take(&mut self.zip64_extensible_data_sector);
571        let files = mem::take(&mut self.files);
572        Ok(ZipArchive::from_finalized_writer(
573            files,
574            comment,
575            zip64_extensible_data_sector,
576            inner,
577            last_file_end,
578            central_start,
579        ))
580    }
581}
582
583#[cfg(not(feature = "unreserved"))]
584fn validate_extra_fields(extra_fields: &[crate::extra_fields::CustomExtraField]) -> ZipResult<()> {
585    use crate::extra_fields::EXTRA_FIELD_MAPPING;
586    use crate::extra_fields::UsedExtraField;
587    for x in extra_fields.iter() {
588        let header_id = x.header_id;
589        if UsedExtraField::try_from(header_id).is_err() && EXTRA_FIELD_MAPPING.contains(&header_id)
590        {
591            return Err(ZipError::Io(io::Error::other(format!(
592                "Extra data header ID {header_id:#06} (0x{header_id:x}) \
593                        requires crate feature \"unreserved\"",
594            ))));
595        }
596    }
597    Ok(())
598}
599
600impl<W: Write + Seek> ZipWriter<W> {
601    /// Initializes the archive.
602    ///
603    /// Before writing to this object, the [`ZipWriter::start_file`] function should be called.
604    /// After a successful write, the file remains open for writing. After a failed write, call
605    /// [`ZipWriter::is_writing_file`] to determine if the file remains open.
606    pub fn new(inner: W) -> ZipWriter<W> {
607        ZipWriter {
608            inner: GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(inner)),
609            files: IndexMap::new(),
610            stats: ZipWriterStats::default(),
611            writing_to_file: false,
612            writing_raw: false,
613            comment: Box::new([]),
614            zip64_extensible_data_sector: None,
615            flush_on_finish_file: false,
616            seek_possible: true,
617            auto_large_file: false,
618            #[cfg(feature = "deflate-flate2")]
619            deflate_cache: DeflateCache::default(),
620        }
621    }
622
623    /// Set automatically large file to true if needed
624    #[must_use]
625    pub fn set_auto_large_file(mut self) -> Self {
626        self.auto_large_file = true;
627        self
628    }
629
630    /// Returns true if a file is currently open for writing.
631    pub const fn is_writing_file(&self) -> bool {
632        self.writing_to_file && !self.inner.is_closed()
633    }
634
635    /// Set ZIP archive comment.
636    pub fn set_comment<S>(&mut self, comment: S) -> ZipResult<()>
637    where
638        S: Into<Box<str>>,
639    {
640        self.set_raw_comment(comment.into().into_boxed_bytes())
641    }
642
643    /// Set raw ZIP archive comment.
644    ///
645    /// This sets the raw bytes of the comment.
646    /// The comment is typically expected to be encoded in UTF-8.
647    /// If the comment is more than `u16::MAX` it will be truncated
648    pub fn set_raw_comment(&mut self, comment: Box<[u8]>) -> ZipResult<()> {
649        let max_comment_len = u16::MAX as usize; // 65,535
650        if comment.len() <= max_comment_len {
651            self.comment = comment;
652            return Ok(());
653        }
654        let (allowed, rest) = comment.split_at(max_comment_len);
655        self.comment = allowed.into();
656        Err(ZipError::Io(std::io::Error::new(
657            std::io::ErrorKind::InvalidData,
658            format!("Unexpected data comment - {} bytes too long", rest.len()),
659        )))
660    }
661
662    /// Get ZIP archive comment.
663    pub fn get_comment(&self) -> Result<&str, Utf8Error> {
664        from_utf8(self.get_raw_comment())
665    }
666
667    /// Get raw ZIP archive comment.
668    ///
669    /// This returns the raw bytes of the comment. The comment
670    /// is typically expected to be encoded in UTF-8.
671    pub const fn get_raw_comment(&self) -> &[u8] {
672        &self.comment
673    }
674
675    /// Get the zip64 extensible data. Use at your own risk
676    /// See 4.3.14.3, 4.3.14.4, 4.4.27 and APPENDIX C of the specification
677    pub fn set_raw_zip64_extensible_data_sector(&mut self, extensible_data: Box<[u8]>) {
678        self.zip64_extensible_data_sector = Some(extensible_data);
679    }
680
681    /// Get raw ZIP64 archive comment.
682    ///
683    /// This returns the raw bytes of the comment. The comment
684    /// is typically expected to be encoded in UTF-8.
685    #[deprecated(
686        note = "Zip64 comment is not part of the zip specification - see https://github.com/zip-rs/zip2/pull/747"
687    )]
688    pub fn get_raw_zip64_comment(&self) -> Option<&[u8]> {
689        // no-op since deprecated
690        None
691    }
692
693    /// Set the file length and crc32 manually.
694    ///
695    /// # Safety
696    ///
697    /// This function assumes that `length` and `crc32` accurately describe the data that has
698    /// been (or will be) written for the currently open file entry.
699    ///
700    /// The caller must ensure that:
701    /// - A file entry is currently being written (that is, [`Self::start_file`] or equivalent has
702    ///   been called successfully and `abort_file` has not been called since).
703    /// - `length` is the exact uncompressed size, in bytes, of the file data written to the
704    ///   underlying [`Write`] implementation for this entry.
705    /// - `crc32` is the correct CRC-32 checksum for that same data, in the format expected by
706    ///   the ZIP specification.
707    ///
708    /// If these requirements are not met, the generated ZIP archive may contain inconsistent
709    /// or corrupt metadata, which can cause readers to report errors, skip data, or accept
710    /// data whose integrity cannot be verified.
711    ///
712    /// This overwrites the internal crc32 calculation. It should only be used in case
713    /// the underlying [Write] is written independently and you need to adjust the zip metadata.
714    pub unsafe fn set_file_metadata(&mut self, length: u64, crc32: u32) -> ZipResult<()> {
715        if !self.writing_to_file {
716            return Err(ZipError::Io(io::Error::other("No file has been started")));
717        }
718        self.stats.hasher = Hasher::new_with_initial_len(crc32, length);
719        self.stats.bytes_written = length;
720        Ok(())
721    }
722
723    fn ok_or_abort_file<T, E: Into<ZipError>>(&mut self, result: Result<T, E>) -> ZipResult<T> {
724        match result {
725            Err(e) => {
726                let _ = self.abort_file();
727                Err(e.into())
728            }
729            Ok(t) => Ok(t),
730        }
731    }
732
733    /// Start a new file for with the requested options.
734    fn start_entry<T: FileOptionExtension>(
735        &mut self,
736        file_name_raw: &[u8],
737        mut options: FileOptions<'_, '_, T>,
738        raw_values: Option<ZipRawValues>,
739    ) -> ZipResult<()> {
740        self.finish_file()?;
741
742        let header_start = self.inner.try_inner_mut()?.stream_position()?;
743        #[cfg(not(feature = "unreserved"))]
744        {
745            if raw_values.is_none()
746                && let Some(extra_fields) = options.extended_options.extra_fields()
747            {
748                validate_extra_fields(extra_fields)?;
749            }
750        }
751        let raw_values = raw_values.unwrap_or(ZipRawValues {
752            crc32: 0,
753            compressed_size: 0,
754            uncompressed_size: 0,
755            language_encoding: None,
756            encrypted_with_descriptor: None,
757            file_comment_raw: None,
758        });
759        if options.extended_options.validate_extra_fields()
760            && let Some(extra_fields) = options.extended_options.extra_fields()
761        {
762            for x in extra_fields.iter() {
763                if !ExtendedFileOptions::extra_field_parses(x.header_id, &x.data, x.central_only) {
764                    return Err(invalid!(
765                        "Extra field {:#06x} would not be readable: malformed data",
766                        x.header_id
767                    ));
768                }
769                // A reader replaces the entry name with a valid Info-ZIP Unicode Path field's
770                // content (APPNOTE 4.6.9), so it must not name a different file than this one.
771                if x.header_id == crate::format::extra_fields::ExtraFieldId::UnicodePath.as_u16()
772                    && let Some(content) = x.data.get(5..)
773                    && x.data[1..5] == crc32fast::hash(file_name_raw).to_le_bytes()
774                    && core::str::from_utf8(content).is_ok()
775                    && content != file_name_raw
776                {
777                    return Err(invalid!(
778                        "Extra field {:#06x} would not be readable: renames the entry",
779                        x.header_id
780                    ));
781                }
782            }
783        }
784        let extra_fields = match options.extended_options.extra_fields() {
785            Some(data) => data.iter().map(|x| ExtraField::Custom(x.clone())).collect(),
786            None => vec![],
787        };
788        let entry_len: usize = mem::size_of::<Magic>()
789            + mem::size_of::<ZipLocalEntryBlock>()
790            + file_name_raw.len()
791            + extra_fields.iter().map(|x| x.size(false)).sum::<usize>();
792        if entry_len > (u16::MAX as usize) {
793            return Err(invalid!(
794                "ZipLocalBlock + filename + extra fields must be less than 64KiB when combined"
795            ));
796        }
797
798        let mut file = ZipFileData::initialize_local_block(
799            file_name_raw,
800            &options,
801            &raw_values,
802            header_start,
803            extra_fields,
804        );
805        if let Some(comment) = options.extended_options.take_file_comment() {
806            if comment.len() > u16::MAX as usize {
807                return Err(invalid!("File comment must be less than 64KiB"));
808            }
809            if !comment.is_ascii() {
810                file.flags |= ZipFlags::LanguageEncoding.as_u16();
811            }
812            file.file_comment = comment;
813        }
814        file.file_comment_raw = raw_values.file_comment_raw;
815        if let Some(language_encoding) = raw_values.language_encoding {
816            file.flags
817                .set(ZipFlags::LanguageEncoding, language_encoding);
818        }
819        if (!self.seek_possible || matches!(options.encrypt_with, Some(EncryptWith::ZipCrypto(..))))
820            && file.is_non_dir_based_on_unix_mode()
821        {
822            file.flags |= ZipFlags::UsingDataDescriptor.as_u16();
823        }
824        // A raw copy of an encrypted entry keeps the encrypted and data descriptor
825        // flags it was read with, whatever the default above picked.
826        if let Some(descriptor) = raw_values.encrypted_with_descriptor {
827            file.flags.set(ZipFlags::Encrypted, true);
828            file.flags.set(ZipFlags::UsingDataDescriptor, descriptor);
829        }
830        file.version_made_by = file.version_made_by.max(file.version_needed() as u8);
831        let index = self.insert_file_data(file_name_raw, file)?;
832        self.writing_to_file = true;
833        let result: ZipResult<()> = {
834            let file = &mut self.files[index];
835            let writer = self.inner.try_inner_mut()?;
836            file.write_local_header(
837                header_start,
838                writer,
839                file_name_raw,
840                Some((options.alignment, options.alignment_header_id)),
841            )?;
842            Ok(())
843        };
844        self.ok_or_abort_file(result)?;
845        self.stats.start = self.inner.try_inner_mut()?.stream_position()?;
846        match options.encrypt_with {
847            #[cfg(feature = "aes-crypto")]
848            Some(EncryptWith::Aes {
849                mode,
850                // If the password is None (when we use the `options()` method)
851                // we re-use the same encryption
852                password: Some(password),
853                salt,
854                ..
855            }) => {
856                let writer = self.close_writer()?;
857                let aeswriter =
858                    crate::aes::AesWriter::new_with_options(writer, mode, password, salt)?;
859                self.inner = GenericZipWriter::Storer(MaybeEncrypted::Aes(aeswriter));
860            }
861            Some(EncryptWith::ZipCrypto(keys, ..)) => {
862                let writer = self.close_writer()?;
863                // With ZipCrypto, we _need_ to use a data descriptor so that
864                // we can initialize the stream properly.
865                let mut zipwriter = crate::zipcrypto::ZipCryptoWriter {
866                    writer,
867                    keys,
868                    buffer: [0u8; CHUNK_SIZE],
869                };
870                self.stats.start = zipwriter.writer.stream_position()?;
871                // crypto_header is counted as part of the data
872                let mut crypto_header = [0u8; 12];
873                let rand_result = getrandom::fill(&mut crypto_header[0..10])
874                    .map_err(|e| invalid!("getrandom returned error: {}", e));
875                self.ok_or_abort_file(rand_result)?;
876                let file = &mut self.files[index];
877                // The last two bytes of the header should either be the CRC of
878                // the file _OR_ the last timepart of the last modified time if
879                // a data descriptor is used.
880                //
881                // However, this header is encrypted, and ZipCrypto is not a
882                // seekable encryption algorithm - an earlier plaintext byte
883                // will have an impact on the later values.
884                //
885                // This makes it impossible to write the file without first
886                // calculating its CRC. To avoid having to read the file twice
887                // or keeping the entire file in memory, we force all ZipCrypto
888                // files to use a data descriptor. This way, we can use the
889                // local_modified_time as a password check byte instead of the
890                // CRC.
891                crypto_header[10..=11].copy_from_slice(
892                    &file
893                        .last_modified_time
894                        .unwrap_or_else(DateTime::default_for_write)
895                        .timepart()
896                        .to_le_bytes(),
897                );
898                let result = zipwriter.write_all(&crypto_header);
899                self.ok_or_abort_file(result)?;
900                self.inner = GenericZipWriter::Storer(MaybeEncrypted::ZipCrypto(zipwriter));
901            }
902            _ => {}
903        }
904        let file = &mut self.files[index];
905        //debug_assert!(file.data_start.get().is_none());
906        file.data_start.get_or_init(|| self.stats.start);
907        self.stats.bytes_written = 0;
908        self.stats.hasher = Hasher::new();
909        Ok(())
910    }
911
912    fn insert_file_data(
913        &mut self,
914        file_name_raw: &[u8],
915        mut file: ZipFileData,
916    ) -> ZipResult<usize> {
917        if self.files.contains_key(file_name_raw) {
918            return Err(invalid!(
919                "Duplicate filename: {:?}",
920                file_name_raw.escape_ascii()
921            ));
922        }
923        file.overridden_header_name = None;
924        let (index, _) = self.files.insert_full(file_name_raw.into(), file);
925        Ok(index)
926    }
927
928    /// [`GenericZipWriter::switch_to`] with this writer's DEFLATE encoder cache.
929    fn switch_inner(&mut self, next_writer: NextWriter) -> ZipResult<()> {
930        #[cfg(feature = "deflate-flate2")]
931        let cache = &mut self.deflate_cache;
932        #[cfg(not(feature = "deflate-flate2"))]
933        let cache = &mut DeflateCache::default();
934        self.inner.switch_to(cache, next_writer)
935    }
936
937    fn finish_file(&mut self) -> ZipResult<()> {
938        if !self.writing_to_file {
939            return Ok(());
940        }
941
942        let make_plain_writer = self.inner.prepare_next_writer(
943            Stored,
944            None,
945            #[cfg(feature = "deflate-zopfli")]
946            None,
947        )?;
948        self.switch_inner(make_plain_writer)?;
949        self.switch_to_non_encrypting_writer()?;
950        let writer = self.inner.try_inner_mut()?;
951
952        if !self.writing_raw {
953            let Some((file_name_raw, file)) = self.files.last_mut() else {
954                return Ok(());
955            };
956            file.uncompressed_size = self.stats.bytes_written;
957
958            let file_end = writer.stream_position()?;
959            debug_assert!(file_end >= self.stats.start);
960            file.compressed_size = file_end - self.stats.start;
961
962            if !file.is_using_data_descriptor() {
963                // Not using a data descriptor means the underlying writer
964                // supports seeking, so we can go back and update the AES Extra
965                // Data header to use AE1 for large files.
966                #[cfg(feature = "aes-crypto")]
967                update_aes_extra_field(writer, file, self.stats.bytes_written)?;
968            }
969
970            file.crc32 = if file
971                .aes_settings()
972                .is_some_and(|(_, vendor_version)| vendor_version.is_ae2_encrypted())
973            {
974                // AE2 disables CRC32 in the local file header
975                0
976            } else {
977                self.stats.hasher.clone().finalize()
978            };
979
980            if file.is_using_data_descriptor() {
981                file.write_data_descriptor(writer, self.auto_large_file)?;
982            } else {
983                file.update_local_file_header(writer, file_name_raw)?;
984                writer.seek(SeekFrom::Start(file_end))?;
985            }
986        }
987        if self.flush_on_finish_file {
988            let result = writer.flush();
989            self.ok_or_abort_file(result)?;
990        }
991
992        self.writing_to_file = false;
993        Ok(())
994    }
995
996    fn switch_to_non_encrypting_writer(&mut self) -> Result<(), ZipError> {
997        self.inner = GenericZipWriter::Storer(
998            match mem::replace(&mut self.inner, GenericZipWriter::Closed) {
999                #[cfg(feature = "aes-crypto")]
1000                GenericZipWriter::Storer(MaybeEncrypted::Aes(writer)) => {
1001                    MaybeEncrypted::Unencrypted(writer.finish()?)
1002                }
1003                GenericZipWriter::Storer(MaybeEncrypted::ZipCrypto(writer)) => {
1004                    MaybeEncrypted::Unencrypted(writer.finish()?)
1005                }
1006                GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(w)) => {
1007                    MaybeEncrypted::Unencrypted(w)
1008                }
1009                #[cfg(feature = "deflate-flate2")]
1010                GenericZipWriter::Storer(MaybeEncrypted::Closed { .. }) => {
1011                    return Err(io::Error::new(
1012                        io::ErrorKind::BrokenPipe,
1013                        "ZipWriter's inner writer is not available",
1014                    )
1015                    .into());
1016                }
1017                _ => unreachable!(
1018                    "switch_to_non_encrypting_writer called with incompatible GenericZipWriter variant"
1019                ),
1020            },
1021        );
1022        Ok(())
1023    }
1024
1025    /// Removes an entry from the archive's directory without rewriting the
1026    /// archive.
1027    ///
1028    /// The entry stops appearing in the archive: it is dropped from the central
1029    /// directory written by [`ZipWriter::finish`], so readers no longer see it.
1030    /// Its local header and file data are **left in place** as unreferenced
1031    /// bytes, which is what makes this cheap — nothing after the removed entry
1032    /// is moved or rewritten, so the cost does not scale with the size of the
1033    /// archive.
1034    ///
1035    /// The file therefore does not shrink. Reclaiming the space needs a
1036    /// rewrite, which a caller can do when it is worth doing (for example by
1037    /// copying the surviving entries into a fresh archive with
1038    /// [`ZipWriter::merge_archive`]) rather than on every removal.
1039    ///
1040    /// Any entry that shares data with the removed one — see
1041    /// [`ZipWriter::shallow_copy_file`] — keeps working, because the bytes it
1042    /// points at are untouched.
1043    ///
1044    /// If a file is currently being written, it is finished first, exactly as
1045    /// [`ZipWriter::start_file`] does.
1046    ///
1047    /// # Safety
1048    ///
1049    ///.This function only deletes the file entry from the archive's central
1050    /// directory. The file's content remains untouched.
1051    ///
1052    /// # Errors
1053    ///
1054    /// Returns [`ZipError::FileNotFound`] if `name` does not match an entry.
1055    ///
1056    /// ```
1057    /// # fn main() -> Result<(), zip::result::ZipError> {
1058    /// # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
1059    /// # {
1060    /// use std::io::{Cursor, Write};
1061    /// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};
1062    ///
1063    /// let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1064    /// zip.start_file("keep.txt", SimpleFileOptions::default())?;
1065    /// zip.write_all(b"kept")?;
1066    /// zip.start_file("drop.txt", SimpleFileOptions::default())?;
1067    /// zip.write_all(b"dropped")?;
1068    /// zip.hide_file("drop.txt")?;
1069    ///
1070    /// let mut archive = ZipArchive::new(zip.finish()?)?;
1071    /// assert_eq!(archive.len(), 1);
1072    /// assert!(archive.by_name("keep.txt").is_ok());
1073    /// assert!(archive.by_name("drop.txt").is_err());
1074    /// # }
1075    /// # Ok(())
1076    /// # }
1077    /// ```
1078    pub fn hide_file(&mut self, name: &str) -> ZipResult<()> {
1079        self.finish_file()?;
1080        // `shift_remove` rather than `swap_remove`: the central directory is
1081        // written in `files` order, and reordering the surviving entries on
1082        // every removal would be a surprising side effect.
1083        self.files
1084            .shift_remove(name.as_bytes())
1085            .map(|_| ())
1086            .ok_or(ZipError::FileNotFound)
1087    }
1088
1089    /// Removes the file currently being written from the archive if there is one, or else removes
1090    /// the file most recently written.
1091    pub fn abort_file(&mut self) -> ZipResult<()> {
1092        let (_, last_file) = self.files.pop().ok_or(ZipError::FileNotFound)?;
1093        let make_plain_writer = self.inner.prepare_next_writer(
1094            Stored,
1095            None,
1096            #[cfg(feature = "deflate-zopfli")]
1097            None,
1098        )?;
1099        self.switch_inner(make_plain_writer)?;
1100        self.switch_to_non_encrypting_writer()?;
1101        // Make sure this is the last file, and that no shallow copies of it remain; otherwise we'd
1102        // overwrite a valid file and corrupt the archive
1103        let last_file_start = last_file
1104            .data_start
1105            .get()
1106            .copied()
1107            .unwrap_or(last_file.header_start);
1108        let writer = self.inner.try_inner_mut()?;
1109        let current_position = writer.stream_position()?;
1110        let rewind_safe = last_file.header_start <= current_position
1111            && last_file_start <= current_position
1112            && self.files.values().all(|file| {
1113                file.data_start.get().copied().unwrap_or(file.header_start) < last_file_start
1114            });
1115        if rewind_safe {
1116            writer.seek(SeekFrom::Start(last_file.header_start))?;
1117        }
1118        self.writing_to_file = false;
1119        Ok(())
1120    }
1121
1122    /// Create a file in the archive and start writing its contents. The file must not have the
1123    /// same name as a file already in the archive.
1124    ///
1125    /// The data should be written using the [`Write`] implementation on this [`ZipWriter`]
1126    pub fn start_file<S: ToString, T: FileOptionExtension>(
1127        &mut self,
1128        name: S,
1129        options: FileOptions<'_, '_, T>,
1130    ) -> ZipResult<()> {
1131        let name = name.to_string();
1132        let options = FileOptions {
1133            name: Some(name.as_bytes()),
1134            ..options
1135        };
1136        self.start_file_with_options(options)
1137    }
1138
1139    /// Create a file in the archive and start writing its contents. The file must not have the
1140    /// same name as a file already in the archive. The name need not be UTF-8.
1141    ///
1142    /// The data should be written using the [`Write`] implementation on this [`ZipWriter`]
1143    pub fn start_file_with_options<T: FileOptionExtension>(
1144        &mut self,
1145        mut options: FileOptions<'_, '_, T>,
1146    ) -> ZipResult<()> {
1147        let Some(name) = options.name else {
1148            return Err(invalid!("File name must be specified"));
1149        };
1150        options.normalize();
1151        let make_new_self = self.inner.prepare_next_writer(
1152            options.compression_method,
1153            options.compression_level,
1154            #[cfg(feature = "deflate-zopfli")]
1155            options.zopfli_buffer_size,
1156        )?;
1157        self.start_entry(name, options, None)?;
1158        let result = self.switch_inner(make_new_self);
1159        self.ok_or_abort_file(result)?;
1160        self.writing_raw = false;
1161        Ok(())
1162    }
1163
1164    /// Copy over the entire contents of another archive verbatim.
1165    ///
1166    /// This method extracts file metadata from the `source` archive, then simply performs a single
1167    /// big [`io::copy()`](io::copy) to transfer all the actual file contents without any
1168    /// decompression or decryption. This is more performant than the equivalent operation of
1169    /// calling [`Self::raw_copy_file()`] for each entry from the `source` archive in sequence.
1170    ///
1171    ///```
1172    /// # fn main() -> Result<(), zip::result::ZipError> {
1173    /// # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
1174    /// # {
1175    /// use std::io::{Cursor, Write, Read};
1176    /// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};
1177    ///
1178    /// let buf = Cursor::new(Vec::new());
1179    /// let mut zip = ZipWriter::new(buf);
1180    /// zip.start_file("a.txt", SimpleFileOptions::default())?;
1181    /// zip.write_all(b"hello\n")?;
1182    /// let src = ZipArchive::new(zip.finish()?)?;
1183    ///
1184    /// let buf = Cursor::new(Vec::new());
1185    /// let mut zip = ZipWriter::new(buf);
1186    /// zip.start_file("b.txt", SimpleFileOptions::default())?;
1187    /// zip.write_all(b"hey\n")?;
1188    /// let src2 = ZipArchive::new(zip.finish()?)?;
1189    ///
1190    /// let buf = Cursor::new(Vec::new());
1191    ///
1192    /// let mut zip = ZipWriter::new(buf);
1193    /// zip.merge_archive(src)?;
1194    /// zip.merge_archive(src2)?;
1195    /// let mut result = ZipArchive::new(zip.finish()?)?;
1196    ///
1197    /// let mut s: String = String::new();
1198    /// result.by_name("a.txt")?.read_to_string(&mut s)?;
1199    /// assert_eq!(s, "hello\n");
1200    /// s.clear();
1201    /// result.by_name("b.txt")?.read_to_string(&mut s)?;
1202    /// assert_eq!(s, "hey\n");
1203    /// # }
1204    /// # Ok(())
1205    /// # }
1206    ///```
1207    pub fn merge_archive<R>(&mut self, source: ZipArchive<R>) -> ZipResult<()>
1208    where
1209        R: Read + Seek,
1210    {
1211        self.finish_file()?;
1212
1213        /* `self.files` is keyed by name, so a duplicate would silently replace our existing entry
1214         * while its data stayed in the archive. Reject it before writing anything. */
1215        if let Some(name) = source
1216            .file_names_raw()
1217            .find(|name| self.files.contains_key(*name))
1218        {
1219            return Err(invalid!("Duplicate filename: {:?}", name.escape_ascii()));
1220        }
1221
1222        /* Ensure we accept the file contents on faith (and avoid overwriting the data).
1223         * See raw_copy_file_rename(). */
1224        self.writing_to_file = true;
1225        self.writing_raw = true;
1226
1227        let writer = self.inner.try_inner_mut()?;
1228        /* Get the file entries from the source archive. */
1229        let new_files = source.merge_contents(writer)?;
1230
1231        /* These file entries are now ours! */
1232        self.files.extend(new_files);
1233
1234        Ok(())
1235    }
1236
1237    /// Starts a file, taking a Path as argument.
1238    ///
1239    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
1240    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
1241    /// root.
1242    pub fn start_file_from_path<E: FileOptionExtension, P: AsRef<Path>>(
1243        &mut self,
1244        path: P,
1245        options: FileOptions<'_, '_, E>,
1246    ) -> ZipResult<()> {
1247        self.start_file(path_to_string(path)?, options)
1248    }
1249
1250    /// Add a new file using the already compressed data from a ZIP file being read and renames it, this
1251    /// allows faster copies of the `ZipFile` since there is no need to decompress and compress it again.
1252    /// Any `ZipFile` metadata is copied and not checked, for example the file CRC.
1253    ///
1254    /// ```no_run
1255    /// use std::fs::File;
1256    /// use std::io::{Read, Seek, Write};
1257    /// use zip::{ZipArchive, ZipWriter};
1258    ///
1259    /// fn copy_rename<R, W>(
1260    ///     src: &mut ZipArchive<R>,
1261    ///     dst: &mut ZipWriter<W>,
1262    /// ) -> zip::result::ZipResult<()>
1263    /// where
1264    ///     R: Read + Seek,
1265    ///     W: Write + Seek,
1266    /// {
1267    ///     // Retrieve file entry by name
1268    ///     let file = src.by_name("src_file.txt")?;
1269    ///
1270    ///     // Copy and rename the previously obtained file entry to the destination zip archive
1271    ///     dst.raw_copy_file_rename(file, "new_name.txt")?;
1272    ///
1273    ///     Ok(())
1274    /// }
1275    /// ```
1276    pub fn raw_copy_file_rename<R: Read, S: ToString>(
1277        &mut self,
1278        file: ZipFile<'_, R>,
1279        name: S,
1280    ) -> ZipResult<()> {
1281        let options = Self::raw_copy_options(&file, true)?;
1282        let file_name = name.to_string();
1283        self.raw_copy_file_rename_internal(file, file_name.as_bytes(), options, None)
1284    }
1285
1286    /// The options a raw copy writes `file` with: its own, plus its comment and extra fields.
1287    fn raw_copy_options<R: Read>(
1288        file: &ZipFile<'_, R>,
1289        preserve_timestamp: bool,
1290    ) -> ZipResult<FullFileOptions<'static, 'static>> {
1291        let mut options = file.options().into_full_options();
1292        if !file.comment().is_empty() {
1293            options = options.with_file_comment(file.comment());
1294        }
1295        for one_extra in file.extra_data_fields() {
1296            if let ExtraField::ExtendedTimestamp(timestamp) = one_extra {
1297                if preserve_timestamp {
1298                    options = options.with_extended_timestamp(timestamp.mod_time(), None, None)?;
1299                }
1300                continue;
1301            }
1302            let mut buff = Cursor::new(Vec::new());
1303            one_extra.write(&mut buff, false)?;
1304            let buff = buff.into_inner();
1305            if buff.len() >= 4 {
1306                let header_id = u16::from_le_bytes([buff[0], buff[1]]);
1307                #[cfg(feature = "aes-crypto")]
1308                if header_id == 0x9901 {
1309                    continue;
1310                }
1311                options.add_extra_field(header_id, &buff[4..], false)?;
1312            }
1313        }
1314        Ok(options)
1315    }
1316
1317    /// `language_encoding` is the copied entry's own flag when `name` is its
1318    /// stored name, which keeps its comment as stored too, or `None` for a new
1319    /// name, which derives the flag from it and writes the comment as UTF-8.
1320    ///
1321    /// An encrypted entry keeps its encrypted and data descriptor flags, and
1322    /// gets a data descriptor after its bytes when it had one, so it decrypts as
1323    /// before: the ZipCrypto header (or AES salt, verifier, and MAC) is in those
1324    /// bytes, and neither scheme binds the name.
1325    fn raw_copy_file_rename_internal<R: Read, T: FileOptionExtension>(
1326        &mut self,
1327        mut file: ZipFile<'_, R>,
1328        name: &[u8],
1329        options: FileOptions<'_, '_, T>,
1330        language_encoding: Option<bool>,
1331    ) -> ZipResult<()> {
1332        let raw_values = ZipRawValues {
1333            crc32: file.crc32(),
1334            compressed_size: file.compressed_size(),
1335            uncompressed_size: file.size(),
1336            language_encoding,
1337            encrypted_with_descriptor: file
1338                .encrypted()
1339                .then(|| file.flags().is_using_data_descriptor()),
1340            file_comment_raw: language_encoding.and_then(|_| file.data.file_comment_raw.clone()),
1341        };
1342
1343        self.start_entry(name, options, Some(raw_values))?;
1344        self.writing_to_file = true;
1345        self.writing_raw = true;
1346
1347        io::copy(&mut file.take_raw_reader()?, self)?;
1348        // `finish_file` writes no data descriptor for a raw entry.
1349        let auto_large_file = self.auto_large_file;
1350        let result = (|| -> ZipResult<()> {
1351            let writer = self.inner.try_inner_mut()?;
1352            if let Some((_, file)) = self.files.last()
1353                && file.is_using_data_descriptor()
1354            {
1355                file.write_data_descriptor(writer, auto_large_file)?;
1356            }
1357            Ok(())
1358        })();
1359        self.ok_or_abort_file(result)?;
1360        self.finish_file()
1361    }
1362
1363    /// Like `raw_copy_file_to_path`, but uses Path arguments.
1364    ///
1365    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
1366    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
1367    /// root.
1368    pub fn raw_copy_file_to_path<R: Read, P: AsRef<Path>>(
1369        &mut self,
1370        file: ZipFile<'_, R>,
1371        path: P,
1372    ) -> ZipResult<()> {
1373        self.raw_copy_file_rename(file, path_to_string(path)?)
1374    }
1375
1376    /// Add a new file using the already compressed data from a ZIP file being read, this allows faster
1377    /// copies of the `ZipFile` since there is no need to decompress and compress it again. Any `ZipFile`
1378    /// metadata is copied and not checked, for example the file CRC.
1379    ///
1380    /// The name is copied as stored: the same bytes, under the same language encoding flag. So a
1381    /// name in a legacy code page (Shift-JIS, GBK, CP866, ...) stays readable by tools that decode
1382    /// it, where re-encoding the CP437 reading of [`ZipFile::name`] as UTF-8 would garble it. The
1383    /// comment is copied as stored too (see [`ZipFile::comment_raw`]).
1384    ///
1385    /// ```no_run
1386    /// use std::fs::File;
1387    /// use std::io::{Read, Seek, Write};
1388    /// use zip::{ZipArchive, ZipWriter};
1389    ///
1390    /// fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()>
1391    /// where
1392    ///     R: Read + Seek,
1393    ///     W: Write + Seek,
1394    /// {
1395    ///     // Retrieve file entry by name
1396    ///     let file = src.by_name("src_file.txt")?;
1397    ///
1398    ///     // Copy the previously obtained file entry to the destination zip archive
1399    ///     dst.raw_copy_file(file)?;
1400    ///
1401    ///     Ok(())
1402    /// }
1403    /// ```
1404    pub fn raw_copy_file<R: Read>(&mut self, file: ZipFile<'_, R>) -> ZipResult<()> {
1405        let options = Self::raw_copy_options(&file, true)?;
1406        let file_name_raw = file.name_raw().to_owned();
1407        let language_encoding = file.flags().matching(ZipFlags::LanguageEncoding);
1408        self.raw_copy_file_rename_internal(file, &file_name_raw, options, Some(language_encoding))
1409    }
1410
1411    /// Add a new file using the already compressed data from a ZIP file being read and set the last
1412    /// modified date and unix mode. This allows faster copies of the `ZipFile` since there is no need
1413    /// to decompress and compress it again. Any `ZipFile` metadata other than the last modified date
1414    /// and the unix mode is copied and not checked, for example the file CRC.
1415    ///
1416    /// A ZipCrypto entry with a data descriptor checks its password against the high byte of its
1417    /// last modified time, so a new time with a different high byte makes the password look wrong.
1418    ///
1419    /// ```no_run
1420    /// use std::io::{Read, Seek, Write};
1421    /// use zip::{DateTime, ZipArchive, ZipWriter};
1422    ///
1423    /// fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()>
1424    /// where
1425    ///     R: Read + Seek,
1426    ///     W: Write + Seek,
1427    /// {
1428    ///     // Retrieve file entry by name
1429    ///     let file = src.by_name("src_file.txt")?;
1430    ///
1431    ///     // Copy the previously obtained file entry to the destination zip archive
1432    ///     dst.raw_copy_file_touch(file, DateTime::default(), Some(0o644))?;
1433    ///
1434    ///     Ok(())
1435    /// }
1436    /// ```
1437    pub fn raw_copy_file_touch<R: Read>(
1438        &mut self,
1439        file: ZipFile<'_, R>,
1440        last_modified_time: DateTime,
1441        unix_mode: Option<u32>,
1442    ) -> ZipResult<()> {
1443        // Do not let the old extended timestamp override the requested modification time.
1444        let mut options = Self::raw_copy_options(&file, false)?;
1445
1446        options = options.last_modified_time(last_modified_time);
1447
1448        if let Some(perms) = unix_mode {
1449            // `unix_permissions` keeps only the permission bits: add the entry's own file type
1450            // back, as `add_symlink` and `add_directory` do.
1451            let file_type = file.unix_mode().map_or(0, |mode| mode & !0o7777);
1452            options.external_attributes = None;
1453            options = options.unix_permissions(perms);
1454            options.permissions = options.permissions.map(|perms| perms | file_type);
1455        }
1456
1457        options.normalize();
1458        let file_name_raw = file.name_raw().to_owned();
1459        let language_encoding = file.flags().matching(ZipFlags::LanguageEncoding);
1460        self.raw_copy_file_rename_internal(file, &file_name_raw, options, Some(language_encoding))
1461    }
1462
1463    /// Add a directory entry.
1464    ///
1465    /// As directories have no content, you must not call [`ZipWriter::write`] before adding a new file.
1466    pub fn add_directory<S, T: FileOptionExtension>(
1467        &mut self,
1468        name: S,
1469        mut options: FileOptions<'_, '_, T>,
1470    ) -> ZipResult<()>
1471    where
1472        S: Into<String>,
1473    {
1474        let permissions = options
1475            .permissions
1476            .get_or_insert(FileOptions::DEFAULT_DIR_PERMISSIONS);
1477        *permissions |= ffi::S_IFDIR; // if permissions are already set by user
1478        options.compression_method = Stored;
1479        options.encrypt_with = None;
1480
1481        let name_as_string = name.into();
1482        // Append a slash to the filename if it does not end with it.
1483        let name_with_slash = match name_as_string.chars().last() {
1484            Some('/' | '\\') => name_as_string,
1485            _ => name_as_string + "/",
1486        };
1487
1488        self.start_entry(name_with_slash.as_bytes(), options, None)?;
1489        self.writing_to_file = false;
1490        self.switch_to_non_encrypting_writer()?;
1491        Ok(())
1492    }
1493
1494    /// Add a directory entry, taking a Path as argument.
1495    ///
1496    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
1497    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
1498    /// root.
1499    pub fn add_directory_from_path<T: FileOptionExtension, P: AsRef<Path>>(
1500        &mut self,
1501        path: P,
1502        options: FileOptions<'_, '_, T>,
1503    ) -> ZipResult<()> {
1504        self.add_directory(path_to_string(path)?, options)
1505    }
1506
1507    /// Finish the last file and write all other zip-structures
1508    ///
1509    /// This will return the writer, but one should normally not append any data to the end of the file.
1510    /// Note that the zipfile will also be finished on drop.
1511    pub fn finish(mut self) -> ZipResult<W> {
1512        let _central_start = self.finalize()?;
1513        self.close_writer()
1514    }
1515
1516    fn close_writer(&mut self) -> ZipResult<W> {
1517        let inner = mem::replace(&mut self.inner, GenericZipWriter::Closed);
1518        match inner {
1519            GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(w)) => Ok(w),
1520            _ => Err(invalid!(
1521                "Should have switched to stored and unencrypted beforehand",
1522            )),
1523        }
1524    }
1525
1526    /// Add a symlink entry.
1527    ///
1528    /// The zip archive will contain an entry for path `name` which is a symlink to `target`.
1529    ///
1530    /// No validation or normalization of the paths is performed. For best results,
1531    /// callers should normalize `\` to `/` and ensure symlinks are relative to other
1532    /// paths within the zip archive.
1533    ///
1534    /// WARNING: not all zip implementations preserve symlinks on extract. Some zip
1535    /// implementations may materialize a symlink as a regular file, possibly with the
1536    /// content incorrectly set to the symlink target. For maximum portability, consider
1537    /// storing a regular file instead.
1538    pub fn add_symlink<N: ToString, T: ToString, E: FileOptionExtension>(
1539        &mut self,
1540        name: N,
1541        target: T,
1542        mut options: FileOptions<'_, '_, E>,
1543    ) -> ZipResult<()> {
1544        let permissions = options
1545            .permissions
1546            .get_or_insert(FileOptions::DEFAULT_SYMLINK_PERMISSIONS);
1547        *permissions |= ffi::S_IFLNK; // if permissions are already set by user
1548        // The symlink target is stored as file content. And compressing the target path
1549        // likely wastes space. So always store.
1550        options.compression_method = Stored;
1551
1552        let file_name = name.to_string();
1553        self.start_entry(file_name.as_bytes(), options, None)?;
1554        self.writing_to_file = true;
1555        let result = self.write_all(target.to_string().as_bytes());
1556        self.ok_or_abort_file(result)?;
1557        self.writing_raw = false;
1558        self.finish_file()?;
1559
1560        Ok(())
1561    }
1562
1563    /// Add a symlink entry, taking Paths to the location and target as arguments.
1564    ///
1565    /// This function sanitizes both the path and the target. If you don't want to sanitize the
1566    /// path, it's recommended to use the normal [`Self::add_symlink`]
1567    ///
1568    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
1569    /// ignores any `..` or Windows drive letter
1570    pub fn add_symlink_from_path<P: AsRef<Path>, T: AsRef<Path>, E: FileOptionExtension>(
1571        &mut self,
1572        path: P,
1573        target: T,
1574        options: FileOptions<'_, '_, E>,
1575    ) -> ZipResult<()> {
1576        let path = path_to_string(path)?;
1577        let target = path_to_string(target)?;
1578        self.add_symlink(path, target, options)
1579    }
1580
1581    /// Add a file whose contents were already compressed by a [`ZipFileBuilder`].
1582    ///
1583    /// The compressed data is copied into the archive verbatim, so the compression work can be
1584    /// done ahead of time, possibly on another thread. See [`ZipFileBuilder`] for an example of
1585    /// parallelizing compression this way. The file must not have the same name as a file already
1586    /// in the archive.
1587    pub fn add_prepared_file(&mut self, file: PreparedZipFile) -> ZipResult<()> {
1588        let PreparedZipFile {
1589            file_name,
1590            options,
1591            crc32,
1592            uncompressed_size,
1593            compressed_size,
1594            data,
1595        } = file;
1596        let raw_values = ZipRawValues {
1597            crc32,
1598            compressed_size,
1599            uncompressed_size,
1600            language_encoding: None,
1601            encrypted_with_descriptor: None,
1602            file_comment_raw: None,
1603        };
1604
1605        self.start_entry(&file_name, options, Some(raw_values))?;
1606        self.writing_raw = true;
1607
1608        // start_entry leaves the inner writer as a bare Storer (a compression encoder is only
1609        // installed by start_file*), so the already-compressed bytes pass through unchanged.
1610        // Write directly to the inner writer rather than through ZipWriter::write, whose stats
1611        // bookkeeping (CRC-32 hashing and the large-file size check) is redundant here: the CRC
1612        // and sizes are already known, and large_file was set from them in finish().
1613        let result = self
1614            .inner
1615            .try_inner_mut()
1616            .and_then(|writer| writer.write_all(&data));
1617        self.ok_or_abort_file(result)?;
1618
1619        // The local file header was written from the raw values, but for large files it contains
1620        // a ZIP64 extra field with placeholder sizes; go back and patch it now. When the
1621        // underlying writer doesn't support seeking, the entry uses a data descriptor instead,
1622        // which finish_file() skips for raw entries, so write it here.
1623        let auto_large_file = self.auto_large_file;
1624        let result = (|| -> ZipResult<()> {
1625            let writer = self.inner.try_inner_mut()?;
1626            let Some((file_name_raw, file)) = self.files.last_mut() else {
1627                debug_assert!(
1628                    false,
1629                    "Newly added file not found while finishing it in add_prepared_file"
1630                );
1631                return Err(ZipError::FileNotFound);
1632            };
1633            if file.is_using_data_descriptor() {
1634                file.write_data_descriptor(writer, auto_large_file)?;
1635            } else if file.large_file {
1636                let file_end = writer.stream_position()?;
1637                file.update_local_file_header(writer, file_name_raw)?;
1638                writer.seek(SeekFrom::Start(file_end))?;
1639            }
1640            Ok(())
1641        })();
1642        self.ok_or_abort_file(result)?;
1643
1644        self.finish_file()
1645    }
1646
1647    /// Appends multiple pre-compressed [`PreparedZipFile`] entries into the archive.
1648    ///
1649    /// # Errors
1650    ///
1651    /// Returns an error if appending any prepared file fails.
1652    pub fn add_prepared_files(
1653        &mut self,
1654        files: impl IntoIterator<Item = PreparedZipFile>,
1655    ) -> ZipResult<()> {
1656        for file in files {
1657            self.add_prepared_file(file)?;
1658        }
1659        Ok(())
1660    }
1661
1662    fn finalize(&mut self) -> ZipResult<(u64, u64)> {
1663        /// Longest stale tail that [`Self::finalize`] blanks in place rather than moving the footer.
1664        const STALE_FILL_MAX_LEN: u64 = 0xFF00;
1665        self.finish_file()?;
1666
1667        let (last_file_end, is_zip64) = self.write_central_and_footer()?;
1668        let mut central_start = last_file_end;
1669        if self.seek_possible {
1670            let writer = self.inner.try_inner_mut()?;
1671            let footer_end = writer.stream_position()?;
1672            let stream_end = writer.seek(SeekFrom::End(0))?;
1673            let archive_end = stream_end - self.comment.len() as u64;
1674            if archive_end <= footer_end
1675                && footer_end < stream_end
1676                && stream_end - footer_end < STALE_FILL_MAX_LEN
1677            {
1678                // Stale bytes no longer than the comment are left after it (we can't truncate), but
1679                // blank them: they may hold an old footer that a reader would find instead of ours.
1680                // Use 0xFF, not 0: if the comment ends with part of an EOCD, a fill of zeros would
1681                // complete it into a valid empty EOCD that readers would pick instead of ours,
1682                // whereas 0xFF gives any such EOCD a comment length of at least 0xFF00, which can't
1683                // fit in fewer than STALE_FILL_MAX_LEN trailing bytes.
1684                writer.seek(SeekFrom::Start(footer_end))?;
1685                io::copy(&mut io::repeat(0xFF).take(stream_end - footer_end), writer)?;
1686            } else if footer_end < stream_end {
1687                // Data from an aborted file is past the end of the footer.
1688
1689                // Overwrite the magic so the footer is no longer valid.
1690                writer.seek(SeekFrom::Start(last_file_end))?;
1691                writer.write_all(&0_u32.to_le_bytes())?;
1692                let start_zip32_cde = footer_end
1693                    - (size_of::<Magic>() + size_of::<Zip32CDEBlock>()) as u64
1694                    - self.comment.len() as u64;
1695                writer.seek(SeekFrom::Start(start_zip32_cde))?;
1696                writer.write_all(&0_u32.to_le_bytes())?;
1697                let zip64_extensible_len = self
1698                    .zip64_extensible_data_sector
1699                    .as_ref()
1700                    .map(|e| e.len() as u64)
1701                    .unwrap_or(0);
1702                if is_zip64 {
1703                    let start_zip64_locator = start_zip32_cde
1704                        - (size_of::<Magic>() + size_of::<Zip64CentralDirectoryEndLocator>())
1705                            as u64;
1706                    writer.seek(SeekFrom::Start(start_zip64_locator))?;
1707                    writer.write_all(&0_u32.to_le_bytes())?;
1708                    let start_zip64_cde = start_zip64_locator
1709                        - (size_of::<Magic>() + Zip64CentralDirectoryEnd::MIN_FULL_SIZE) as u64
1710                        - zip64_extensible_len;
1711                    writer.seek(SeekFrom::Start(start_zip64_cde))?;
1712                    writer.write_all(&0_u32.to_le_bytes())?;
1713                }
1714
1715                // Rewrite the footer at the actual end.
1716                let central_and_footer_size = footer_end - central_start;
1717                writer.seek(SeekFrom::End(-(central_and_footer_size as i64)))?;
1718                #[cfg_attr(not(debug_assertions), allow(unused_variables))]
1719                let (new_central_start, new_is_zip64) = self.write_central_and_footer()?;
1720                central_start = new_central_start;
1721                #[cfg(debug_assertions)]
1722                {
1723                    let archive_end = if new_is_zip64 && new_is_zip64 != is_zip64 {
1724                        let new_size = (size_of::<Magic>()
1725                            + Zip64CentralDirectoryEnd::MIN_FULL_SIZE)
1726                            as u64
1727                            + zip64_extensible_len
1728                            + (size_of::<Magic>() + size_of::<Zip64CentralDirectoryEndLocator>())
1729                                as u64;
1730                        archive_end + new_size
1731                    } else {
1732                        archive_end
1733                    };
1734                    debug_assert!(
1735                        self.inner.try_inner_mut()?.stream_position()?
1736                            == archive_end + self.comment.len() as u64
1737                    );
1738                }
1739            } else {
1740                writer.seek(SeekFrom::Start(footer_end))?;
1741            }
1742        }
1743
1744        Ok((last_file_end, central_start))
1745    }
1746
1747    fn write_central_and_footer(&mut self) -> Result<(u64, bool), ZipError> {
1748        let writer = self.inner.try_inner_mut()?;
1749
1750        let mut version_needed = u16::from(MIN_VERSION);
1751        let central_start = writer.stream_position()?;
1752        for (filename_raw, file) in &mut self.files {
1753            file.write_central_directory_header(writer, filename_raw)?;
1754            version_needed = version_needed.max(file.version_needed());
1755        }
1756        let central_size = writer.stream_position()? - central_start;
1757        let is64 = self.files.len() > ZIP64_ENTRY_THR
1758            || central_size.max(central_start) > ZIP64_BYTES_THR
1759            || self.zip64_extensible_data_sector.is_some();
1760
1761        if is64 {
1762            let zip64_extensible_data_sector = self.zip64_extensible_data_sector.clone();
1763            let extensible_len = zip64_extensible_data_sector
1764                .as_ref()
1765                .map(|e| e.len() as u64)
1766                .unwrap_or(0);
1767
1768            let zip64_footer = Zip64CentralDirectoryEnd {
1769                record_size: extensible_len + 44,
1770                version_made_by: version_needed,
1771                version_needed_to_extract: version_needed,
1772                disk_number: 0,
1773                disk_with_central_directory: 0,
1774                number_of_files_on_this_disk: self.files.len() as u64,
1775                number_of_files: self.files.len() as u64,
1776                central_directory_size: central_size,
1777                central_directory_offset: central_start,
1778                zip64_extensible_data_sector,
1779            };
1780
1781            zip64_footer.write(writer)?;
1782
1783            let zip64_footer = Zip64CentralDirectoryEndLocator {
1784                disk_with_central_directory: 0,
1785                end_of_central_directory_offset: central_start + central_size,
1786                number_of_disks: 1,
1787            };
1788
1789            zip64_footer.write(writer)?;
1790        }
1791
1792        let central_directory_size = if is64 {
1793            ZIP64_BYTES_THR_U32
1794        } else {
1795            central_size.min(ZIP64_BYTES_THR) as u32
1796        };
1797
1798        let number_of_files = self.files.len().min(ZIP64_ENTRY_THR) as u16;
1799        let footer = Zip32CentralDirectoryEnd {
1800            disk_number: 0,
1801            disk_with_central_directory: 0,
1802            zip_file_comment: self.comment.clone(),
1803            number_of_files_on_this_disk: number_of_files,
1804            number_of_files,
1805            central_directory_size,
1806            central_directory_offset: central_start.min(ZIP64_BYTES_THR) as u32,
1807        };
1808        footer.write(writer)?;
1809        Ok((central_start, is64))
1810    }
1811
1812    fn index_by_name(&self, name: &[u8]) -> ZipResult<usize> {
1813        self.files.get_index_of(name).ok_or(ZipError::FileNotFound)
1814    }
1815
1816    /// Adds another entry to the central directory referring to the same content as an existing
1817    /// entry. The file's local-file header will still refer to it by its original name, so
1818    /// unzipping the file will technically be unspecified behavior. [`ZipArchive`] ignores the
1819    /// filename in the local-file header and treat the central directory as authoritative. However,
1820    /// some other software (e.g. Minecraft) will refuse to extract a file copied this way.
1821    pub fn shallow_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()> {
1822        self.finish_file()?;
1823        if src_name == dest_name {
1824            return Err(invalid!("Trying to copy a file to itself"));
1825        }
1826        let src_index = self.index_by_name(src_name.as_bytes())?;
1827        let mut dest_data = self.files[src_index].clone();
1828        let file_name_raw = dest_name.as_bytes();
1829        dest_data.central_header_start = 0;
1830        dest_data.set_language_encoding_for(file_name_raw);
1831        dest_data.drop_unicode_path_renaming(file_name_raw);
1832        self.insert_file_data(file_name_raw, dest_data)?;
1833        Ok(())
1834    }
1835
1836    /// Like `shallow_copy_file`, but uses Path arguments.
1837    ///
1838    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
1839    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
1840    /// root.
1841    pub fn shallow_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>(
1842        &mut self,
1843        src_path: T,
1844        dest_path: U,
1845    ) -> ZipResult<()> {
1846        let src = path_to_string(src_path)?;
1847        let dest = path_to_string(dest_path)?;
1848        self.shallow_copy_file(&src, &dest)
1849    }
1850}
1851
1852#[cfg(feature = "rayon")]
1853#[inline]
1854fn default_data_channel_capacity() -> NonZeroUsize {
1855    NonZeroUsize::new(rayon::current_num_threads()).unwrap_or(NonZeroUsize::MIN)
1856}
1857
1858#[cfg(feature = "rayon")]
1859#[inline]
1860fn default_paths_channel_capacity() -> NonZeroUsize {
1861    NonZeroUsize::new(rayon::current_num_threads().saturating_mul(2)).unwrap_or(NonZeroUsize::MIN)
1862}
1863
1864#[cfg(feature = "rayon")]
1865impl<W: Write + Seek + Send> ZipWriter<W> {
1866    /// Compresses a collection of in-memory data entries in parallel using Rayon
1867    /// and streams them to the archive via a zero-mutex bounded channel pipeline.
1868    ///
1869    /// Compression occurs concurrently across available Rayon worker threads. Finished files
1870    /// are streamed into a bounded channel and written sequentially by the calling thread.
1871    /// Memory consumption is naturally bounded to `num_threads * file_size` via channel
1872    /// backpressure.
1873    ///
1874    /// Duplicate filenames (including CP437 raw byte overrides) are checked before compression
1875    /// begins to eliminate wasted CPU work.
1876    ///
1877    /// # Errors
1878    ///
1879    /// Returns an error if any entry fails compression, if duplicate filenames are detected,
1880    /// or if appending to the archive fails.
1881    pub fn par_append_data<'a, I, N, T, D>(&mut self, entries: I) -> ZipResult<()>
1882    where
1883        I: rayon::iter::IntoParallelIterator<Item = (N, FileOptions<'a, 'a, T>, D)>,
1884        N: AsRef<str> + Send,
1885        T: FileOptionExtension + Send + Sync + 'a,
1886        D: AsRef<[u8]> + Send,
1887    {
1888        self.par_append_data_with_capacity(entries, default_data_channel_capacity())
1889    }
1890
1891    /// Compresses a collection of in-memory data entries in parallel using Rayon
1892    /// and streams them to the archive with a user-specified channel buffer capacity.
1893    ///
1894    /// `channel_capacity` bounds the maximum number of compressed files held in memory
1895    /// waiting for sequential I/O commit. Rayon worker threads automatically stall when
1896    /// the channel fills, providing hardware-level backpressure tailored to your storage
1897    /// throughput and memory budget.
1898    ///
1899    /// # Errors
1900    ///
1901    /// Returns an error if any entry fails compression, if duplicate filenames are detected,
1902    /// or if appending to the archive fails.
1903    pub fn par_append_data_with_capacity<'a, I, N, T, D>(
1904        &mut self,
1905        entries: I,
1906        channel_capacity: NonZeroUsize,
1907    ) -> ZipResult<()>
1908    where
1909        I: rayon::iter::IntoParallelIterator<Item = (N, FileOptions<'a, 'a, T>, D)>,
1910        N: AsRef<str> + Send,
1911        T: FileOptionExtension + Send + Sync + 'a,
1912        D: AsRef<[u8]> + Send,
1913    {
1914        use rayon::prelude::*;
1915        use std::collections::HashSet;
1916        use std::sync::Mutex;
1917        use std::sync::mpsc::sync_channel;
1918
1919        let par_iter = entries.into_par_iter();
1920        let additional = par_iter.opt_len().unwrap_or(0);
1921        let mut initial_seen = HashSet::with_capacity(self.files.len().saturating_add(additional));
1922        for key in self.files.keys() {
1923            initial_seen.insert(key.clone());
1924        }
1925        let seen = Mutex::new(initial_seen);
1926        let (tx, rx) = sync_channel(channel_capacity.get());
1927        let mut write_err = None;
1928
1929        std::thread::scope(|s| {
1930            let consumer_handle = s.spawn(|| -> ZipResult<()> {
1931                for item in rx {
1932                    self.add_prepared_file(item?)?;
1933                }
1934                Ok(())
1935            });
1936
1937            let _ = par_iter.try_for_each(|(name, options, data)| -> Result<(), ()> {
1938                let name_str = name.as_ref();
1939                let name_bytes: Box<[u8]> = options.name.unwrap_or(name_str.as_bytes()).into();
1940
1941                // Fast pre-check: verify uniqueness before starting expensive compression
1942                {
1943                    let mut seen_guard = match seen.lock() {
1944                        Ok(g) => g,
1945                        Err(_) => return Err(()),
1946                    };
1947                    if !seen_guard.insert(name_bytes) {
1948                        let err = invalid!("Duplicate filename: {:?}", name_str);
1949                        let _ = tx.send(Err(err));
1950                        return Err(());
1951                    }
1952                }
1953
1954                // Compress concurrently on worker threads without holding any writer locks
1955                let prepared = match PreparedZipFile::from_data(name, options, data.as_ref()) {
1956                    Ok(p) => p,
1957                    Err(err) => {
1958                        let _ = tx.send(Err(err));
1959                        return Err(());
1960                    }
1961                };
1962
1963                // Send to bounded channel; if receiver disconnected, abort immediately
1964                if tx.send(Ok(prepared)).is_err() {
1965                    return Err(());
1966                }
1967
1968                Ok(())
1969            });
1970
1971            drop(tx);
1972
1973            if let Ok(res) = consumer_handle.join() {
1974                write_err = res.err();
1975            }
1976        });
1977
1978        if let Some(err) = write_err {
1979            return Err(err);
1980        }
1981        Ok(())
1982    }
1983
1984    /// Compresses files from disk paths in parallel using Rayon and streams them to the archive
1985    /// via a zero-mutex bounded channel pipeline.
1986    ///
1987    /// Each file is opened, read, and compressed concurrently on worker threads. Finished files
1988    /// are streamed into a bounded channel and written sequentially by the calling thread,
1989    /// achieving maximum sequential storage bandwidth with zero writer lock contention.
1990    ///
1991    /// Duplicate filenames (including CP437 raw byte overrides) are checked before disk reading
1992    /// begins to eliminate wasted I/O and CPU work.
1993    ///
1994    /// # Errors
1995    ///
1996    /// Returns an error if opening/reading any path fails, if compression fails, if duplicate
1997    /// filenames are detected, or if writing fails.
1998    pub fn par_append_from_paths<'a, I, N, P, T>(&mut self, entries: I) -> ZipResult<()>
1999    where
2000        I: rayon::iter::IntoParallelIterator<Item = (N, P, FileOptions<'a, 'a, T>)>,
2001        N: AsRef<str> + Send,
2002        P: AsRef<Path> + Send,
2003        T: FileOptionExtension + Send + Sync + 'a,
2004    {
2005        self.par_append_from_paths_with_capacity(entries, default_paths_channel_capacity())
2006    }
2007
2008    /// Compresses files from disk paths in parallel using Rayon and streams them to the archive
2009    /// with a user-specified channel buffer capacity.
2010    ///
2011    /// `channel_capacity` bounds the maximum number of compressed files held in memory
2012    /// waiting for sequential I/O commit. Rayon worker threads automatically stall when
2013    /// the channel fills, providing hardware-level backpressure tailored to your storage
2014    /// throughput and memory budget.
2015    ///
2016    /// # Errors
2017    ///
2018    /// Returns an error if opening/reading any path fails, if compression fails, if duplicate
2019    /// filenames are detected, or if writing fails.
2020    pub fn par_append_from_paths_with_capacity<'a, I, N, P, T>(
2021        &mut self,
2022        entries: I,
2023        channel_capacity: NonZeroUsize,
2024    ) -> ZipResult<()>
2025    where
2026        I: rayon::iter::IntoParallelIterator<Item = (N, P, FileOptions<'a, 'a, T>)>,
2027        N: AsRef<str> + Send,
2028        P: AsRef<Path> + Send,
2029        T: FileOptionExtension + Send + Sync + 'a,
2030    {
2031        use rayon::prelude::*;
2032        use std::collections::HashSet;
2033        use std::sync::Mutex;
2034        use std::sync::mpsc::sync_channel;
2035
2036        let par_iter = entries.into_par_iter();
2037        let additional = par_iter.opt_len().unwrap_or(0);
2038        let mut initial_seen = HashSet::with_capacity(self.files.len().saturating_add(additional));
2039        for key in self.files.keys() {
2040            initial_seen.insert(key.clone());
2041        }
2042        let seen = Mutex::new(initial_seen);
2043        let (tx, rx) = sync_channel(channel_capacity.get());
2044        let mut write_err = None;
2045
2046        std::thread::scope(|s| {
2047            let consumer_handle = s.spawn(|| -> ZipResult<()> {
2048                for item in rx {
2049                    self.add_prepared_file(item?)?;
2050                }
2051                Ok(())
2052            });
2053
2054            let _ = par_iter.try_for_each(|(name, path, options)| -> Result<(), ()> {
2055                let name_str = name.as_ref();
2056                let name_bytes: Box<[u8]> = options.name.unwrap_or(name_str.as_bytes()).into();
2057
2058                // Fast pre-check: verify uniqueness before disk I/O and compression
2059                {
2060                    let mut seen_guard = match seen.lock() {
2061                        Ok(g) => g,
2062                        Err(_) => return Err(()),
2063                    };
2064                    if !seen_guard.insert(name_bytes) {
2065                        let err = invalid!("Duplicate filename: {:?}", name_str);
2066                        let _ = tx.send(Err(err));
2067                        return Err(());
2068                    }
2069                }
2070
2071                // Read from disk and compress concurrently without holding any writer locks
2072                let prepared = match PreparedZipFile::from_path(name, path, options) {
2073                    Ok(p) => p,
2074                    Err(err) => {
2075                        let _ = tx.send(Err(err));
2076                        return Err(());
2077                    }
2078                };
2079
2080                // Send to bounded channel; if receiver disconnected, abort immediately
2081                if tx.send(Ok(prepared)).is_err() {
2082                    return Err(());
2083                }
2084
2085                Ok(())
2086            });
2087
2088            drop(tx);
2089
2090            if let Ok(res) = consumer_handle.join() {
2091                write_err = res.err();
2092            }
2093        });
2094
2095        if let Some(err) = write_err {
2096            return Err(err);
2097        }
2098        Ok(())
2099    }
2100
2101    /// Compresses a collection of in-memory data entries in parallel with atomic all-or-nothing guarantee.
2102    ///
2103    /// All entries are compressed into memory and validated before any files are appended to the archive.
2104    /// If any entry fails compression or if duplicate filenames are detected, no files are committed.
2105    ///
2106    /// # Errors
2107    ///
2108    /// Returns an error if any entry fails compression, if duplicates are found, or if writing fails.
2109    pub fn par_append_data_atomic<'a, I, N, T, D>(&mut self, entries: I) -> ZipResult<()>
2110    where
2111        I: rayon::iter::IntoParallelIterator<Item = (N, FileOptions<'a, 'a, T>, D)>,
2112        N: AsRef<str> + Send,
2113        T: FileOptionExtension + Send + Sync + 'a,
2114        D: AsRef<[u8]> + Send,
2115    {
2116        use rayon::prelude::*;
2117        let prepared_files: ZipResult<Vec<PreparedZipFile>> = entries
2118            .into_par_iter()
2119            .map(|(name, options, data)| PreparedZipFile::from_data(name, options, data.as_ref()))
2120            .collect();
2121
2122        let prepared_files = prepared_files?;
2123
2124        let mut seen = std::collections::HashSet::with_capacity(prepared_files.len());
2125        for file in &prepared_files {
2126            let name = file.file_name_raw();
2127            if self.files.contains_key(name) || !seen.insert(name) {
2128                return Err(invalid!("Duplicate filename: {:?}", name.escape_ascii()));
2129            }
2130        }
2131
2132        for file in prepared_files {
2133            self.add_prepared_file(file)?;
2134        }
2135        Ok(())
2136    }
2137
2138    /// Compresses disk files in parallel with atomic all-or-nothing guarantee.
2139    ///
2140    /// All files are read and compressed before any files are appended to the archive.
2141    /// If any file fails to open, read, or compress, no changes are committed to the archive.
2142    ///
2143    /// # Errors
2144    ///
2145    /// Returns an error if opening/reading any path fails, if compression fails, or if writing fails.
2146    pub fn par_append_from_paths_atomic<'a, I, N, P, T>(&mut self, entries: I) -> ZipResult<()>
2147    where
2148        I: rayon::iter::IntoParallelIterator<Item = (N, P, FileOptions<'a, 'a, T>)>,
2149        N: AsRef<str> + Send,
2150        P: AsRef<Path> + Send,
2151        T: FileOptionExtension + Send + Sync + 'a,
2152    {
2153        use rayon::prelude::*;
2154        let prepared_files: ZipResult<Vec<PreparedZipFile>> = entries
2155            .into_par_iter()
2156            .map(|(name, path, options)| PreparedZipFile::from_path(name, path, options))
2157            .collect();
2158
2159        let prepared_files = prepared_files?;
2160
2161        let mut seen = std::collections::HashSet::with_capacity(prepared_files.len());
2162        for file in &prepared_files {
2163            let name = file.file_name_raw();
2164            if self.files.contains_key(name) || !seen.insert(name) {
2165                return Err(invalid!("Duplicate filename: {:?}", name.escape_ascii()));
2166            }
2167        }
2168
2169        for file in prepared_files {
2170            self.add_prepared_file(file)?;
2171        }
2172        Ok(())
2173    }
2174}
2175
2176impl<W: Write> ZipWriter<StreamWriter<W>> {
2177    /// Creates a writer that doesn't require the inner writer to implement [Seek], but where
2178    /// operations that would overwrite previously-written bytes or cause subsequent operations to
2179    /// do so (such as `abort_file`) will always return an error.
2180    ///
2181    /// To use this writer from an async runtime, run it on a dedicated thread and forward its
2182    /// output through a bounded channel. See `examples/async_bridge.rs`.
2183    pub fn new_stream(inner: W) -> ZipWriter<StreamWriter<W>> {
2184        ZipWriter {
2185            inner: GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(StreamWriter::new(inner))),
2186            files: IndexMap::new(),
2187            stats: ZipWriterStats::default(),
2188            writing_to_file: false,
2189            writing_raw: false,
2190            comment: Box::new([]),
2191            zip64_extensible_data_sector: None,
2192            flush_on_finish_file: false,
2193            seek_possible: false,
2194            auto_large_file: false,
2195            #[cfg(feature = "deflate-flate2")]
2196            deflate_cache: DeflateCache::default(),
2197        }
2198    }
2199}
2200
2201impl<W: Write + Seek> Drop for ZipWriter<W> {
2202    fn drop(&mut self) {
2203        if !self.inner.is_closed()
2204            && let Err(e) = self.finalize()
2205        {
2206            let _ = write!(
2207                io::stderr(),
2208                "ZipWriter::drop: failed to finalize archive: {e:?}"
2209            );
2210        }
2211    }
2212}
2213
2214/// Keeps the `flate2` DEFLATE encoder alive between entries, so that consecutive Deflated entries
2215/// at the same level reuse its compressor state (several hundred KiB) and output buffer instead of
2216/// reallocating them (#633).
2217///
2218/// While idle, the cached encoder wraps [`MaybeEncrypted::Closed`]:
2219/// - at the end of an entry, [`DeflateCache::park`] calls `DeflateEncoder::reset(Closed)`,
2220///   which finishes the entry's stream into the real writer, resets the `Compress`, clears the
2221///   encoder's output buffer and hands the real writer back;
2222/// - at the start of the next entry at the same level, [`DeflateCache::encoder`] swaps the real
2223///   writer back in through `DeflateEncoder::get_mut`. The compressor is already in its initial
2224///   state, so nothing is ever written to `Closed` in normal operation.
2225/// - if the cache is dropped while holding an idle encoder, flate2's `Drop` finishes the empty,
2226///   reset stream into `Closed`, which discards it.
2227#[cfg(feature = "deflate-flate2")]
2228pub(crate) struct DeflateCache<W: Write> {
2229    /// Level of the encoder most recently handed out. At most one `Deflater` is alive per cache,
2230    /// so this is also the level of the encoder handed back to [`DeflateCache::park`].
2231    level: u32,
2232    idle: Option<flate2::write::DeflateEncoder<MaybeEncrypted<W>>>,
2233}
2234
2235#[cfg(feature = "deflate-flate2")]
2236impl<W: Write> Default for DeflateCache<W> {
2237    fn default() -> Self {
2238        Self {
2239            level: 0,
2240            idle: None,
2241        }
2242    }
2243}
2244
2245#[cfg(feature = "deflate-flate2")]
2246impl<W: Write> Debug for DeflateCache<W> {
2247    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
2248        match &self.idle {
2249            Some(_) => write!(f, "DeflateCache(level {})", self.level),
2250            None => f.write_str("DeflateCache(empty)"),
2251        }
2252    }
2253}
2254
2255#[cfg(feature = "deflate-flate2")]
2256impl<W: Write> DeflateCache<W> {
2257    /// Returns an encoder at `level`, writing to `bare`, in the state of a fresh encoder.
2258    fn encoder(
2259        &mut self,
2260        bare: MaybeEncrypted<W>,
2261        level: u32,
2262    ) -> io::Result<flate2::write::DeflateEncoder<MaybeEncrypted<W>>> {
2263        let cached_level = mem::replace(&mut self.level, level);
2264        match self.idle.take() {
2265            Some(mut encoder) if cached_level == level => {
2266                // `park` already finished the previous stream and reset the compressor (and
2267                // cleared the encoder's output buffer), so only the writer needs swapping.
2268                // Using `reset(bare)` here instead would "finish" the empty stream into
2269                // `Closed` and reset the compressor a second time, which costs more than it
2270                // saves (see #1119).
2271                match mem::replace(encoder.get_mut(), bare) {
2272                    MaybeEncrypted::Closed { .. } => Ok(encoder),
2273                    other => {
2274                        // Unreachable by construction; don't lose the caller's writer.
2275                        let bare = mem::replace(encoder.get_mut(), other);
2276                        Ok(flate2::write::DeflateEncoder::new(
2277                            bare,
2278                            flate2::Compression::new(level),
2279                        ))
2280                    }
2281                }
2282            }
2283            _ => Ok(flate2::write::DeflateEncoder::new(
2284                bare,
2285                flate2::Compression::new(level),
2286            )),
2287        }
2288    }
2289
2290    /// Finishes the entry's DEFLATE stream, returns the real writer and keeps the encoder.
2291    fn park(
2292        &mut self,
2293        mut encoder: flate2::write::DeflateEncoder<MaybeEncrypted<W>>,
2294    ) -> io::Result<MaybeEncrypted<W>> {
2295        let bare = encoder.reset(MaybeEncrypted::Closed { bytes_written: 0 })?;
2296        self.idle = Some(encoder);
2297        Ok(bare)
2298    }
2299}
2300
2301/// Stand-in so that signatures don't depend on whether flate2 is enabled.
2302#[cfg(not(feature = "deflate-flate2"))]
2303pub(crate) struct DeflateCache<W>(core::marker::PhantomData<fn() -> W>);
2304
2305#[cfg(not(feature = "deflate-flate2"))]
2306impl<W> Default for DeflateCache<W> {
2307    fn default() -> Self {
2308        Self(core::marker::PhantomData)
2309    }
2310}
2311
2312#[cfg(not(feature = "deflate-flate2"))]
2313impl<W> Debug for DeflateCache<W> {
2314    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
2315        f.write_str("DeflateCache")
2316    }
2317}
2318
2319impl<W: Write + Seek> GenericZipWriter<W> {
2320    fn prepare_next_writer(
2321        &self,
2322        compression: CompressionMethod,
2323        compression_level: Option<i64>,
2324        #[cfg(feature = "deflate-zopfli")] zopfli_buffer_size: Option<usize>,
2325    ) -> ZipResult<NextWriter> {
2326        if let GenericZipWriter::Closed = self {
2327            return Err(
2328                io::Error::new(io::ErrorKind::BrokenPipe, "ZipWriter was already closed").into(),
2329            );
2330        }
2331
2332        match compression {
2333            Stored => {
2334                if compression_level.is_some() {
2335                    Err(UnsupportedArchive("Unsupported compression level"))
2336                } else {
2337                    Ok(NextWriter::Stored)
2338                }
2339            }
2340            #[allow(unreachable_code)]
2341            #[cfg(feature = "_deflate-any")]
2342            CompressionMethod::Deflated => {
2343                let default = {
2344                    #[cfg(feature = "deflate-flate2")]
2345                    {
2346                        i64::from(flate2::Compression::default().level())
2347                    }
2348                    #[cfg(all(not(feature = "deflate-flate2"), feature = "deflate-zopfli"))]
2349                    {
2350                        24
2351                    }
2352                    #[cfg(not(any(feature = "deflate-zopfli", feature = "deflate-flate2")))]
2353                    {
2354                        compile_error!("could not calculate default: unknown deflate variant")
2355                    }
2356                };
2357
2358                let level = validate_value_in_range(
2359                    compression_level.unwrap_or(default),
2360                    deflate_compression_level_range(),
2361                )
2362                .ok_or(UnsupportedArchive("Unsupported compression level"))?;
2363
2364                #[cfg(feature = "deflate-zopfli")]
2365                {
2366                    macro_rules! deflate_zopfli_and_return {
2367                        ($bare:expr, $best_non_zopfli:expr) => {{
2368                            let options = zopfli::Options {
2369                                iteration_count: core::num::NonZeroU64::try_from(u64::from(
2370                                    level - $best_non_zopfli,
2371                                ))
2372                                .map_err(|e| {
2373                                    std::io::Error::other(format!(
2374                                        "Failed to get the iteration count for zopfli : {e}"
2375                                    ))
2376                                })?,
2377                                ..Default::default()
2378                            };
2379                            Ok(NextWriter::Zopfli {
2380                                options,
2381                                buffer_size: zopfli_buffer_size,
2382                            })
2383                        }};
2384                    }
2385
2386                    #[cfg(feature = "deflate-flate2")]
2387                    {
2388                        let best_non_zopfli = flate2::Compression::best().level();
2389                        if level > best_non_zopfli {
2390                            return deflate_zopfli_and_return!(bare, best_non_zopfli);
2391                        }
2392                    }
2393                    #[cfg(not(feature = "deflate-flate2"))]
2394                    {
2395                        let best_non_zopfli = 9;
2396                        return deflate_zopfli_and_return!(bare, best_non_zopfli);
2397                    }
2398                }
2399                #[cfg(feature = "deflate-flate2")]
2400                {
2401                    Ok(NextWriter::Deflate(level))
2402                }
2403                #[cfg(not(feature = "deflate-flate2"))]
2404                {
2405                    unreachable!("deflate writer: have no fallback for this case")
2406                }
2407            }
2408            #[cfg(feature = "deflate64")]
2409            CompressionMethod::Deflate64 => {
2410                Err(UnsupportedArchive("Compressing Deflate64 is not supported"))
2411            }
2412            #[cfg(feature = "_bzip2_any")]
2413            CompressionMethod::Bzip2 => {
2414                let level: u32 = validate_value_in_range(
2415                    compression_level.unwrap_or(i64::from(bzip2::Compression::default().level())),
2416                    bzip2_compression_level_range(),
2417                )
2418                .ok_or(UnsupportedArchive("Unsupported compression level"))?;
2419                Ok(NextWriter::Bzip2(level))
2420            }
2421            CompressionMethod::AES => Err(UnsupportedArchive(
2422                "AES encryption is enabled through FileOptions::with_aes_encryption",
2423            )),
2424            #[cfg(feature = "zstd")]
2425            CompressionMethod::Zstd => {
2426                let level = validate_value_in_range(
2427                    compression_level.unwrap_or(i64::from(zstd::DEFAULT_COMPRESSION_LEVEL)),
2428                    zstd::compression_level_range(),
2429                )
2430                .ok_or(UnsupportedArchive("Unsupported compression level"))?;
2431                Ok(NextWriter::Zstd(level as i32))
2432            }
2433            #[cfg(feature = "legacy-zip")]
2434            CompressionMethod::Shrink => Err(ZipError::UnsupportedArchive(
2435                "Shrink compression unsupported",
2436            )),
2437            #[cfg(feature = "legacy-zip")]
2438            CompressionMethod::Reduce(_) => Err(ZipError::UnsupportedArchive(
2439                "Reduce compression unsupported",
2440            )),
2441            #[cfg(feature = "legacy-zip")]
2442            CompressionMethod::Implode => Err(ZipError::UnsupportedArchive(
2443                "Implode compression unsupported",
2444            )),
2445            #[cfg(feature = "lzma")]
2446            CompressionMethod::Lzma => {
2447                Err(UnsupportedArchive("LZMA isn't supported for compression"))
2448            }
2449            #[cfg(feature = "xz")]
2450            CompressionMethod::Xz => {
2451                let level = validate_value_in_range(compression_level.unwrap_or(6), 0_u32..=9_u32)
2452                    .ok_or(UnsupportedArchive("Unsupported compression level"))?;
2453                Ok(NextWriter::Xz(level))
2454            }
2455            #[cfg(feature = "ppmd")]
2456            CompressionMethod::Ppmd => {
2457                const ORDERS: [u32; 10] = [0, 4, 5, 6, 7, 8, 9, 10, 11, 12];
2458
2459                let level = validate_value_in_range(compression_level.unwrap_or(7), 1_u32..=9_u32)
2460                    .ok_or(UnsupportedArchive("Unsupported compression level"))?;
2461
2462                let order = ORDERS[level as usize];
2463                let memory_size = 1 << (level + 19);
2464
2465                Ok(NextWriter::Ppmd { order, memory_size })
2466            }
2467            #[allow(deprecated)]
2468            CompressionMethod::Unsupported(..) => {
2469                Err(UnsupportedArchive("Unsupported compression"))
2470            }
2471        }
2472    }
2473
2474    fn switch_to(
2475        &mut self,
2476        deflate_cache: &mut DeflateCache<W>,
2477        next_writer: NextWriter,
2478    ) -> ZipResult<()> {
2479        #[cfg(not(feature = "deflate-flate2"))]
2480        let _ = deflate_cache;
2481        let bare = match mem::replace(self, GenericZipWriter::Closed) {
2482            GenericZipWriter::Storer(w) => w,
2483            #[cfg(feature = "deflate-flate2")]
2484            GenericZipWriter::Deflater(w) => deflate_cache.park(w)?,
2485            #[cfg(feature = "deflate-zopfli")]
2486            GenericZipWriter::ZopfliDeflater(w) => w.finish()?,
2487            #[cfg(feature = "deflate-zopfli")]
2488            GenericZipWriter::BufferedZopfliDeflater(w) => w
2489                .into_inner()
2490                .map_err(|e| ZipError::Io(e.into_error()))?
2491                .finish()?,
2492            #[cfg(feature = "_bzip2_any")]
2493            GenericZipWriter::Bzip2(w) => w.finish()?,
2494            #[cfg(feature = "zstd")]
2495            GenericZipWriter::Zstd(w) => w.finish()?,
2496            #[cfg(feature = "xz")]
2497            GenericZipWriter::Xz(w) => w.finish()?,
2498            #[cfg(feature = "ppmd")]
2499            GenericZipWriter::Ppmd(w) => {
2500                // ZIP needs to encode an end marker (7z for example doesn't encode one).
2501                w.finish(true)?
2502            }
2503            GenericZipWriter::Closed => {
2504                return Err(io::Error::new(
2505                    io::ErrorKind::BrokenPipe,
2506                    "ZipWriter was already closed",
2507                )
2508                .into());
2509            }
2510        };
2511        *self = match next_writer {
2512            NextWriter::Stored => GenericZipWriter::Storer(bare),
2513            #[cfg(feature = "deflate-flate2")]
2514            NextWriter::Deflate(level) => {
2515                GenericZipWriter::Deflater(deflate_cache.encoder(bare, level)?)
2516            }
2517            #[cfg(feature = "deflate-zopfli")]
2518            NextWriter::Zopfli {
2519                options,
2520                buffer_size,
2521            } => match buffer_size {
2522                Some(size) => {
2523                    GenericZipWriter::BufferedZopfliDeflater(std::io::BufWriter::with_capacity(
2524                        size,
2525                        zopfli::DeflateEncoder::new(options, Default::default(), bare),
2526                    ))
2527                }
2528                None => GenericZipWriter::ZopfliDeflater(zopfli::DeflateEncoder::new(
2529                    options,
2530                    Default::default(),
2531                    bare,
2532                )),
2533            },
2534            #[cfg(feature = "_bzip2_any")]
2535            NextWriter::Bzip2(level) => GenericZipWriter::Bzip2(bzip2::write::BzEncoder::new(
2536                bare,
2537                bzip2::Compression::new(level),
2538            )),
2539            #[cfg(feature = "zstd")]
2540            NextWriter::Zstd(level) => GenericZipWriter::Zstd(
2541                zstd::stream::write::Encoder::new(bare, level).map_err(ZipError::Io)?,
2542            ),
2543            #[cfg(feature = "xz")]
2544            NextWriter::Xz(level) => GenericZipWriter::Xz(Box::new(
2545                lzma_rust2::XzWriter::new(bare, lzma_rust2::XzOptions::with_preset(level))
2546                    .map_err(ZipError::Io)?,
2547            )),
2548            #[cfg(feature = "ppmd")]
2549            NextWriter::Ppmd { order, memory_size } => {
2550                let memory_size_mb = memory_size / 1024 / 1024;
2551                let parameter: u16 = (order as u16 - 1)
2552                    + ((memory_size_mb - 1) << 4) as u16
2553                    + ((ppmd_rust::RestoreMethod::Restart as u16) << 12);
2554
2555                let mut bare = bare;
2556                bare.write_all(&parameter.to_le_bytes())
2557                    .map_err(ZipError::Io)?;
2558
2559                let encoder = ppmd_rust::Ppmd8Encoder::new(
2560                    bare,
2561                    order,
2562                    memory_size,
2563                    ppmd_rust::RestoreMethod::Restart,
2564                )
2565                .map_err(|error| match error {
2566                    ppmd_rust::Error::RangeDecoderInitialization => {
2567                        ZipError::InvalidArchive("PPMd range coder initialization failed".into())
2568                    }
2569                    ppmd_rust::Error::InvalidParameter => {
2570                        ZipError::InvalidArchive("Invalid PPMd parameter".into())
2571                    }
2572                    ppmd_rust::Error::IoError(io_error) => ZipError::Io(io_error),
2573                    ppmd_rust::Error::MemoryAllocation => ZipError::Io(io::Error::new(
2574                        ErrorKind::OutOfMemory,
2575                        "PPMd could not allocate memory",
2576                    )),
2577                })?;
2578                GenericZipWriter::Ppmd(Box::new(encoder))
2579            }
2580        };
2581        Ok(())
2582    }
2583
2584    fn ref_mut(&mut self) -> Option<&mut dyn Write> {
2585        match self {
2586            GenericZipWriter::Storer(w) => Some(w as &mut dyn Write),
2587            #[cfg(feature = "deflate-flate2")]
2588            GenericZipWriter::Deflater(w) => Some(w as &mut dyn Write),
2589            #[cfg(feature = "deflate-zopfli")]
2590            GenericZipWriter::ZopfliDeflater(w) => Some(w as &mut dyn Write),
2591            #[cfg(feature = "deflate-zopfli")]
2592            GenericZipWriter::BufferedZopfliDeflater(w) => Some(w as &mut dyn Write),
2593            #[cfg(feature = "_bzip2_any")]
2594            GenericZipWriter::Bzip2(w) => Some(w as &mut dyn Write),
2595            #[cfg(feature = "zstd")]
2596            GenericZipWriter::Zstd(w) => Some(w as &mut dyn Write),
2597            #[cfg(feature = "xz")]
2598            GenericZipWriter::Xz(w) => Some(w as &mut dyn Write),
2599            #[cfg(feature = "ppmd")]
2600            GenericZipWriter::Ppmd(w) => Some(w as &mut dyn Write),
2601            GenericZipWriter::Closed => None,
2602        }
2603    }
2604
2605    const fn is_closed(&self) -> bool {
2606        matches!(*self, GenericZipWriter::Closed)
2607    }
2608
2609    fn try_inner_mut(&mut self) -> Result<&mut W, std::io::Error> {
2610        match *self {
2611            GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(ref mut w)) => Ok(w),
2612            _ => Err(std::io::Error::other(
2613                "Should have switched to stored and unencrypted beforehand",
2614            )),
2615        }
2616    }
2617}
2618
2619/// Compresses the contents of a single file entry independently of any [`ZipWriter`], so that
2620/// the CPU-intensive part of adding files to an archive can be parallelized.
2621///
2622/// The builder compresses the data written to it into memory as it arrives, while tracking the
2623/// metadata (CRC-32 and sizes) that the archive will need. Once [`ZipFileBuilder::finish`] has
2624/// been called, the resulting [`PreparedZipFile`] can be appended to an archive with
2625/// [`ZipWriter::add_prepared_file`], which copies the already-compressed bytes without
2626/// recompressing them.
2627///
2628/// Builders are self-contained: they can be created, written to and finished on other threads
2629/// while a `ZipWriter` is in use, and the prepared files appended to the archive as they become
2630/// ready.
2631///
2632/// Encryption is not supported; pass options without encryption or creation will fail.
2633///
2634/// ```
2635/// use std::io::{Cursor, Write};
2636/// use zip::ZipWriter;
2637/// use zip::write::{SimpleFileOptions, ZipFileBuilder};
2638///
2639/// # fn main() -> zip::result::ZipResult<()> {
2640/// let options = SimpleFileOptions::default();
2641///
2642/// // Compress each file on its own thread...
2643/// let handles = ["first.txt", "second.txt"].map(|name| {
2644///     std::thread::spawn(move || -> zip::result::ZipResult<_> {
2645///         let mut builder = ZipFileBuilder::new(name, options)?;
2646///         builder.write_all(b"Contents compressed off-thread")?;
2647///         builder.finish()
2648///     })
2649/// });
2650///
2651/// // ...then append them to the archive serially.
2652/// let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
2653/// for handle in handles {
2654///     zip.add_prepared_file(handle.join().unwrap()?)?;
2655/// }
2656/// let zip_bytes = zip.finish()?.into_inner();
2657/// # let mut archive = zip::ZipArchive::new(Cursor::new(zip_bytes))?;
2658/// # assert_eq!(archive.len(), 2);
2659/// # Ok(())
2660/// # }
2661/// ```
2662pub struct ZipFileBuilder {
2663    compressor: GenericZipWriter<Cursor<Vec<u8>>>,
2664    file_name: Box<[u8]>,
2665    options: FullFileOptions<'static, 'static>,
2666    hasher: Hasher,
2667    uncompressed_size: u64,
2668}
2669
2670impl Debug for ZipFileBuilder {
2671    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
2672        f.write_fmt(format_args!(
2673            "ZipFileBuilder {{file_name: {:?}, uncompressed_size: {}}}",
2674            self.file_name.escape_ascii().to_string(),
2675            self.uncompressed_size
2676        ))
2677    }
2678}
2679
2680impl ZipFileBuilder {
2681    /// Creates a builder that compresses a file's contents using the compression settings from
2682    /// `options`.
2683    ///
2684    /// Fails if `options` requests encryption or an unsupported compression method or level.
2685    pub fn new<N: AsRef<str>, T: FileOptionExtension>(
2686        name: N,
2687        mut options: FileOptions<'_, '_, T>,
2688    ) -> ZipResult<Self> {
2689        if options.encrypt_with.is_some() {
2690            return Err(UnsupportedArchive(
2691                "Encrypted files cannot be compressed outside of a ZipWriter",
2692            ));
2693        }
2694        options.normalize();
2695        #[cfg(not(feature = "unreserved"))]
2696        {
2697            if let Some(extra_fields) = options.extended_options.extra_fields() {
2698                validate_extra_fields(extra_fields)?;
2699            }
2700        }
2701        let owned_options = FullFileOptions {
2702            compression_method: options.compression_method,
2703            compression_level: options.compression_level,
2704            external_attributes: options.external_attributes,
2705            last_modified_time: options.last_modified_time,
2706            permissions: options.permissions,
2707            large_file: options.large_file,
2708            encrypt_with: None,
2709            extended_options: ExtendedFileOptions {
2710                extra_fields: options
2711                    .extended_options
2712                    .extra_fields()
2713                    .cloned()
2714                    .unwrap_or_default(),
2715                file_comment: options.extended_options.take_file_comment(),
2716                validate_extra_fields: options.extended_options.validate_extra_fields(),
2717            },
2718            alignment: options.alignment,
2719            alignment_header_id: options.alignment_header_id,
2720            #[cfg(feature = "deflate-zopfli")]
2721            zopfli_buffer_size: options.zopfli_buffer_size,
2722            system: options.system,
2723            name: None,
2724        };
2725        let mut compressor =
2726            GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(Cursor::new(Vec::new())));
2727        let make_compressor = compressor.prepare_next_writer(
2728            owned_options.compression_method,
2729            owned_options.compression_level,
2730            #[cfg(feature = "deflate-zopfli")]
2731            owned_options.zopfli_buffer_size,
2732        )?;
2733        compressor.switch_to(&mut DeflateCache::default(), make_compressor)?;
2734        Ok(Self {
2735            compressor,
2736            file_name: name.as_ref().as_bytes().into(),
2737            options: owned_options,
2738            hasher: Hasher::new(),
2739            uncompressed_size: 0,
2740        })
2741    }
2742
2743    /// Like [`ZipFileBuilder::new`], but takes a [`Path`] as the file name.
2744    ///
2745    /// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
2746    /// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
2747    /// root.
2748    pub fn new_from_path<T: FileOptionExtension, P: AsRef<Path>>(
2749        path: P,
2750        options: FileOptions<'_, '_, T>,
2751    ) -> ZipResult<Self> {
2752        Self::new(path_to_string(path)?, options)
2753    }
2754
2755    /// Finishes compressing the file, and returns a [`PreparedZipFile`] that can be appended to
2756    /// an archive with [`ZipWriter::add_prepared_file`].
2757    pub fn finish(mut self) -> ZipResult<PreparedZipFile> {
2758        self.compressor
2759            .switch_to(&mut DeflateCache::default(), NextWriter::Stored)?;
2760        let GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(cursor)) = self.compressor else {
2761            return Err(ZipError::Io(io::Error::other(
2762                "Compressor was in an unexpected state",
2763            )));
2764        };
2765        let data = cursor.into_inner().into_boxed_slice();
2766        let compressed_size = data.len() as u64;
2767        let mut options = self.options;
2768        if compressed_size >= ZIP64_BYTES_THR || self.uncompressed_size >= ZIP64_BYTES_THR {
2769            options.large_file = true;
2770        }
2771        Ok(PreparedZipFile {
2772            file_name: self.file_name,
2773            options,
2774            crc32: self.hasher.finalize(),
2775            uncompressed_size: self.uncompressed_size,
2776            compressed_size,
2777            data,
2778        })
2779    }
2780}
2781
2782impl Write for ZipFileBuilder {
2783    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2784        if buf.is_empty() {
2785            return Ok(0);
2786        }
2787        let Some(w) = self.compressor.ref_mut() else {
2788            return Err(io::Error::new(
2789                io::ErrorKind::BrokenPipe,
2790                "write(): ZipFileBuilder was already closed",
2791            ));
2792        };
2793        let count = w.write(buf)?;
2794        self.hasher.update(&buf[..count]);
2795        self.uncompressed_size += count as u64;
2796        Ok(count)
2797    }
2798
2799    fn flush(&mut self) -> io::Result<()> {
2800        match self.compressor.ref_mut() {
2801            Some(w) => w.flush(),
2802            None => Err(io::Error::new(
2803                io::ErrorKind::BrokenPipe,
2804                "flush(): ZipFileBuilder was already closed",
2805            )),
2806        }
2807    }
2808}
2809
2810/// A file entry whose contents have already been compressed by a [`ZipFileBuilder`], ready to be
2811/// appended to an archive with [`ZipWriter::add_prepared_file`].
2812pub struct PreparedZipFile {
2813    file_name: Box<[u8]>,
2814    options: FullFileOptions<'static, 'static>,
2815    crc32: u32,
2816    uncompressed_size: u64,
2817    compressed_size: u64,
2818    data: Box<[u8]>,
2819}
2820
2821impl Debug for PreparedZipFile {
2822    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
2823        f.write_fmt(format_args!(
2824            "PreparedZipFile {{file_name: {:?}, crc32: {}, uncompressed_size: {}, compressed_size: {}}}",
2825            self.file_name.escape_ascii().to_string(),
2826            self.crc32,
2827            self.uncompressed_size,
2828            self.compressed_size
2829        ))
2830    }
2831}
2832
2833impl PreparedZipFile {
2834    /// Compresses `data` in memory and prepares it as a [`PreparedZipFile`].
2835    ///
2836    /// # Errors
2837    ///
2838    /// Returns an error if compression fails or options are invalid.
2839    pub fn from_data<N: AsRef<str>, T: FileOptionExtension>(
2840        name: N,
2841        options: FileOptions<'_, '_, T>,
2842        data: &[u8],
2843    ) -> ZipResult<Self> {
2844        let mut builder = ZipFileBuilder::new(name, options)?;
2845        builder.write_all(data)?;
2846        builder.finish()
2847    }
2848
2849    /// Compresses a file from `path` on disk and prepares it as a [`PreparedZipFile`].
2850    ///
2851    /// # Errors
2852    ///
2853    /// Returns an error if opening `disk_path` fails, if reading fails, or if compression fails.
2854    pub fn from_path<N: AsRef<str>, P: AsRef<Path>, T: FileOptionExtension>(
2855        archive_name: N,
2856        disk_path: P,
2857        options: FileOptions<'_, '_, T>,
2858    ) -> ZipResult<Self> {
2859        let mut file = std::fs::File::open(disk_path)?;
2860        let mut builder = ZipFileBuilder::new(archive_name, options)?;
2861        std::io::copy(&mut file, &mut builder)?;
2862        builder.finish()
2863    }
2864
2865    /// Returns the file name of this prepared file as a byte slice.
2866    #[must_use]
2867    pub fn file_name_raw(&self) -> &[u8] {
2868        &self.file_name
2869    }
2870
2871    /// Returns the CRC-32 checksum of the uncompressed data.
2872    #[must_use]
2873    pub const fn crc32(&self) -> u32 {
2874        self.crc32
2875    }
2876
2877    /// Returns the uncompressed size in bytes.
2878    #[must_use]
2879    pub const fn uncompressed_size(&self) -> u64 {
2880        self.uncompressed_size
2881    }
2882
2883    /// Returns the compressed size in bytes.
2884    #[must_use]
2885    pub const fn compressed_size(&self) -> u64 {
2886        self.compressed_size
2887    }
2888}
2889
2890impl TryFrom<ZipFileBuilder> for PreparedZipFile {
2891    type Error = ZipError;
2892
2893    /// Converts a [`ZipFileBuilder`] into a [`PreparedZipFile`] by finishing compression.
2894    ///
2895    /// This is equivalent to calling [`ZipFileBuilder::finish`].
2896    #[inline]
2897    fn try_from(builder: ZipFileBuilder) -> Result<Self, Self::Error> {
2898        builder.finish()
2899    }
2900}
2901
2902#[cfg(feature = "_deflate-any")]
2903fn deflate_compression_level_range() -> std::ops::RangeInclusive<u32> {
2904    #[cfg(not(any(feature = "deflate-zopfli", feature = "deflate-flate2")))]
2905    {
2906        compile_error!("min: unknown deflate variant - enable deflate-zopfli or deflate-flate2")
2907    }
2908
2909    let min = {
2910        #[cfg(feature = "deflate-flate2")]
2911        {
2912            flate2::Compression::fast().level()
2913        }
2914        #[cfg(all(not(feature = "deflate-flate2"), feature = "deflate-zopfli"))]
2915        {
2916            // Zopfli starts after the best flate2 level, 9
2917            10
2918        }
2919    };
2920
2921    let max = {
2922        #[cfg(feature = "deflate-zopfli")]
2923        {
2924            264
2925        }
2926        #[cfg(all(not(feature = "deflate-zopfli"), feature = "deflate-flate2"))]
2927        {
2928            flate2::Compression::best().level()
2929        }
2930    };
2931
2932    min..=max
2933}
2934
2935#[cfg(feature = "_bzip2_any")]
2936fn bzip2_compression_level_range() -> std::ops::RangeInclusive<u32> {
2937    let min = bzip2::Compression::fast().level();
2938    let max = bzip2::Compression::best().level();
2939    min..=max
2940}
2941
2942#[cfg(any(
2943    feature = "_deflate-any",
2944    feature = "_bzip2_any",
2945    feature = "ppmd",
2946    feature = "xz",
2947    feature = "zstd",
2948))]
2949fn validate_value_in_range<T: Ord + Copy, U: Ord + Copy + TryFrom<T>>(
2950    value: T,
2951    range: std::ops::RangeInclusive<U>,
2952) -> Option<U> {
2953    let value: U = value.try_into().ok()?;
2954    if range.contains(&value) {
2955        Some(value)
2956    } else {
2957        None
2958    }
2959}
2960
2961#[cfg(feature = "aes-crypto")]
2962fn update_aes_extra_field<W: Write + Seek>(
2963    writer: &mut W,
2964    file: &mut ZipFileData,
2965    bytes_written: u64,
2966) -> ZipResult<()> {
2967    use crate::extra_fields::AexEncryption;
2968    use crate::format::aes::AesVendorVersion;
2969
2970    let inner_compression_method = file.compression_method;
2971
2972    // We prefer using AE-1 which provides an extra CRC check, but for small files we
2973    // switch to AE-2 to prevent being able to use the CRC value to to reconstruct the
2974    // unencrypted contents.
2975    //
2976    // We can only do this when the underlying writer supports
2977    // seek operations, so we gate this behind using_data_descriptor.
2978    //
2979    // C.f. https://www.winzip.com/en/support/aes-encryption/#crc-faq
2980    let new_version = if bytes_written < 20 {
2981        AesVendorVersion::Ae2
2982    } else {
2983        AesVendorVersion::Ae1
2984    };
2985
2986    // edit the extra field
2987    if let Some(ExtraField::AeXEncryption(AexEncryption {
2988        aes_mode,
2989        aes_vendor_version,
2990        aes_extra_field_start,
2991        ..
2992    })) = &mut file
2993        .extra_fields
2994        .inner
2995        .iter_mut()
2996        .find(|f| matches!(f, ExtraField::AeXEncryption(_)))
2997    {
2998        *aes_vendor_version = new_version;
2999
3000        if let Some(aes_start) = aes_extra_field_start {
3001            writer.seek(SeekFrom::Start(*aes_start as u64))?;
3002        } else {
3003            return Err(invalid!("The AES extra field should have a known start"));
3004        }
3005
3006        let aes_extra_field =
3007            AexEncryption::new(*aes_vendor_version, *aes_mode, inner_compression_method);
3008        let mut buf = [0u8; AexEncryption::FULL_SIZE];
3009        aes_extra_field.write(&mut buf.as_mut_slice())?;
3010        writer.write_all(&buf)?;
3011    }
3012
3013    Ok(())
3014}
3015
3016impl ZipFileData {
3017    fn replace_zip64_extra_field(&mut self, zip64: Option<ExtraField>) {
3018        if let Some(ExtraField::Zip64ExtendedInformation(new_zip64)) = zip64.as_ref() {
3019            let new_zip64 = *new_zip64;
3020            if self.extra_fields.inner.is_empty() {
3021                self.extra_fields.inner =
3022                    Box::new([ExtraField::Zip64ExtendedInformation(new_zip64)]);
3023                return;
3024            }
3025            if let Some(ExtraField::Zip64ExtendedInformation(old_zip64)) =
3026                self.extra_fields.inner.first_mut()
3027            {
3028                *old_zip64 = new_zip64;
3029                return;
3030            }
3031            if let Some(zip64_index) =
3032                self.extra_fields
3033                    .inner
3034                    .iter()
3035                    .enumerate()
3036                    .skip(1)
3037                    .find_map(|(index, field)| {
3038                        matches!(field, ExtraField::Zip64ExtendedInformation(_)).then_some(index)
3039                    })
3040            {
3041                let moved_field = replace(
3042                    &mut self.extra_fields.inner[0],
3043                    ExtraField::Zip64ExtendedInformation(new_zip64),
3044                );
3045                self.extra_fields.inner[zip64_index] = moved_field;
3046                return;
3047            }
3048        }
3049
3050        if zip64.is_none()
3051            && !self
3052                .extra_fields
3053                .inner
3054                .iter()
3055                .any(|field| matches!(field, ExtraField::Zip64ExtendedInformation(_)))
3056        {
3057            return;
3058        }
3059
3060        let mut inner = take(&mut self.extra_fields.inner).into_vec();
3061        inner.retain(|field| !matches!(field, ExtraField::Zip64ExtendedInformation(_)));
3062        if let Some(zip64) = zip64 {
3063            inner.insert(0, zip64);
3064        }
3065        self.extra_fields.inner = inner.into_boxed_slice();
3066    }
3067
3068    pub(crate) fn update_local_file_header<T: Write + Seek>(
3069        &mut self,
3070        writer: &mut T,
3071        file_name_raw: &[u8],
3072    ) -> ZipResult<()> {
3073        writer.seek(SeekFrom::Start(
3074            self.header_start + (size_of::<Magic>() + offset_of!(ZipLocalEntryBlock, crc32)) as u64,
3075        ))?;
3076        writer.write_all(&self.crc32.to_le_bytes())?;
3077        if self.large_file {
3078            debug_assert!(matches!(
3079                self.extra_fields.local_extra_fields().next(),
3080                Some(ExtraField::Zip64ExtendedInformation(_))
3081            ));
3082            writer.write_all(&ZIP64_BYTES_THR_U32.to_le_bytes())?;
3083            writer.write_all(&ZIP64_BYTES_THR_U32.to_le_bytes())?;
3084            self.update_local_zip64_extra_field(writer, file_name_raw)?;
3085        } else {
3086            // check compressed size as well as it can also be slightly larger than uncompressed size
3087            if self.compressed_size >= ZIP64_BYTES_THR {
3088                return Err(ZipError::Io(std::io::Error::other(
3089                    "large_file(true) option has not been set",
3090                )));
3091            }
3092            debug_assert!(
3093                !self
3094                    .extra_fields
3095                    .local_extra_fields()
3096                    .any(|field| matches!(field, ExtraField::Zip64ExtendedInformation(_)))
3097            );
3098            writer.write_all(&(self.compressed_size as u32).to_le_bytes())?;
3099            // uncompressed size is already checked on write to catch it as soon as possible
3100            writer.write_all(&(self.uncompressed_size as u32).to_le_bytes())?;
3101        }
3102        Ok(())
3103    }
3104
3105    fn update_local_zip64_extra_field<T: Write + Seek>(
3106        &mut self,
3107        writer: &mut T,
3108        file_name_raw: &[u8],
3109    ) -> ZipResult<()> {
3110        let zip64_block = Zip64ExtendedInformation::local_header(
3111            self.large_file,
3112            self.uncompressed_size,
3113            self.compressed_size,
3114        )
3115        .ok_or(invalid!(
3116            "Attempted to update a nonexistent ZIP64 extra field"
3117        ))?;
3118
3119        let zip64_extra_field_start = self.header_start
3120            + (size_of::<Magic>() + size_of::<ZipLocalEntryBlock>()) as u64
3121            + file_name_raw.len() as u64;
3122
3123        writer.seek(SeekFrom::Start(zip64_extra_field_start))?;
3124        zip64_block.write(writer, true)?;
3125        Ok(())
3126    }
3127
3128    pub(crate) fn write_central_directory_header<T: Write>(
3129        &mut self,
3130        writer: &mut T,
3131        file_name_raw: &[u8],
3132    ) -> ZipResult<()> {
3133        // Rebuild the ZIP64 extra field from the entry's current sizes and offset so it carries
3134        // exactly the values the central header marks with the 0xFFFFFFFF sentinel (APPNOTE
3135        // 4.5.3), and nothing more. The previous code edited an existing field in place and set
3136        // both sizes unconditionally, so an entry whose offset alone needed ZIP64 got a field
3137        // with size values the header did not mark; a reader that follows the spec then takes the
3138        // first stored value (a size) as the offset. Recomputing (instead of editing in place)
3139        // also makes repeated writes of this header identical, which `finalize` relies on when it
3140        // writes the central directory and then rewrites it at the end of the file.
3141        let zip64 = Zip64ExtendedInformation::central_header(
3142            self.large_file,
3143            self.uncompressed_size,
3144            self.compressed_size,
3145            self.header_start,
3146        )
3147        .map(ExtraField::Zip64ExtendedInformation);
3148        self.replace_zip64_extra_field(zip64);
3149        // The ZIP64 field stores the two sizes together, so when it carries them both size
3150        // fields of the header must hold the sentinel, not only the one that overflowed;
3151        // otherwise the field has one more value than the header marks.
3152        let sizes_in_zip64 = self.extra_fields.inner.iter().any(
3153            |field| matches!(field, ExtraField::Zip64ExtendedInformation(z) if z.sizes.is_some()),
3154        );
3155        let central_extra_fields = self.extra_fields.central_extra_fields();
3156        let extra_field_len: usize = self
3157            .extra_fields
3158            .central_extra_fields()
3159            .map(|x| x.size(false))
3160            .sum::<usize>();
3161        let extra_field_length = u16::try_from(extra_field_len)
3162            .map_err(|_| invalid!("Extra field length in central directory exceeds 64KiB"))?;
3163        let file_comment_length = u16::try_from(self.file_comment_raw().len())
3164            .map_err(|_| invalid!("File comment length exceeds 64KiB"))?;
3165        let header_size = size_of::<Magic>()
3166            + size_of::<ZipCentralEntryBlock>()
3167            + file_name_raw.len()
3168            + extra_field_length as usize
3169            + file_comment_length as usize;
3170        // APPNOTE 4.4.10: central directory entry must not exceed 65535 bytes
3171        if header_size > u16::MAX as usize {
3172            return Err(invalid!(
3173                "Central directory header size exceeds 64KiB: {}",
3174                header_size
3175            ));
3176        }
3177        let compressed_size = if self.large_file || sizes_in_zip64 {
3178            ZIP64_BYTES_THR as u32
3179        } else {
3180            self.compressed_size
3181                .min(ZIP64_BYTES_THR)
3182                .try_into()
3183                .map_err(std::io::Error::other)?
3184        };
3185        let uncompressed_size = if self.large_file || sizes_in_zip64 {
3186            ZIP64_BYTES_THR as u32
3187        } else {
3188            self.uncompressed_size
3189                .min(ZIP64_BYTES_THR)
3190                .try_into()
3191                .map_err(std::io::Error::other)?
3192        };
3193        let offset = self
3194            .header_start
3195            .min(ZIP64_BYTES_THR)
3196            .try_into()
3197            .map_err(std::io::Error::other)?;
3198        let last_modified_time = self
3199            .last_modified_time
3200            .unwrap_or_else(DateTime::default_for_write);
3201        let version_to_extract = self.version_needed();
3202        let version_made_by = u16::from(self.version_made_by).max(version_to_extract);
3203        let compression_method = self.extern_compression();
3204        let block = ZipCentralEntryBlock {
3205            version_made_by: ((self.system as u16) << 8) | version_made_by,
3206            version_to_extract,
3207            flags: self.flags(file_name_raw),
3208            compression_method,
3209            last_mod_time: last_modified_time.timepart(),
3210            last_mod_date: last_modified_time.datepart(),
3211            crc32: self.crc32,
3212            compressed_size,
3213            uncompressed_size,
3214            file_name_length: file_name_raw
3215                .len()
3216                .try_into()
3217                .map_err(std::io::Error::other)?,
3218            extra_field_length,
3219            file_comment_length,
3220            disk_number: 0,
3221            internal_file_attributes: 0,
3222            external_file_attributes: self.external_attributes,
3223            offset,
3224        };
3225
3226        block.write(writer)?;
3227        // file name
3228        writer.write_all(file_name_raw)?;
3229        // extra field
3230        for one_extra_field in central_extra_fields {
3231            one_extra_field.write(writer, false)?;
3232        }
3233        // file comment
3234        writer.write_all(self.file_comment_raw())?;
3235        Ok(())
3236    }
3237
3238    pub(crate) fn write_local_header<T: Write>(
3239        &mut self,
3240        header_start: u64,
3241        writer: &mut T,
3242        file_name_raw: &[u8],
3243        alignment_opt: Option<(u16, u16)>,
3244    ) -> ZipResult<()> {
3245        let zip64 = Zip64ExtendedInformation::local_header(
3246            self.large_file,
3247            self.uncompressed_size,
3248            self.compressed_size,
3249        )
3250        .map(ExtraField::Zip64ExtendedInformation);
3251        self.replace_zip64_extra_field(zip64);
3252        let (compressed_size, uncompressed_size) = if self.is_using_data_descriptor() {
3253            (0, 0)
3254        } else {
3255            (
3256                self.clamp_size_field(self.compressed_size)?,
3257                self.clamp_size_field(self.uncompressed_size)?,
3258            )
3259        };
3260        let mut extra_field_len: usize = self
3261            .extra_fields
3262            .local_extra_fields()
3263            .map(|x| x.size(true))
3264            .sum();
3265        let last_modified_time = self
3266            .last_modified_time
3267            .unwrap_or_else(DateTime::default_for_write);
3268        let compression_method = self.extern_compression();
3269        let header_end = header_start
3270            + (size_of::<Magic>() + size_of::<ZipLocalEntryBlock>()) as u64
3271            + file_name_raw.len() as u64;
3272        let opt_alignment_field = if let Some((alignment, header_id)) = alignment_opt
3273            && alignment > 1
3274        {
3275            let extra_field_end = header_end + extra_field_len as u64;
3276            let align = u64::from(alignment);
3277            let unaligned_header_bytes = extra_field_end % align;
3278            if unaligned_header_bytes != 0 {
3279                let mut pad_length = (align - unaligned_header_bytes) as usize;
3280                while pad_length < 6 {
3281                    pad_length += align as usize;
3282                }
3283                extra_field_len = self
3284                    .extra_fields
3285                    .local_extra_fields()
3286                    .map(|x| x.size(true))
3287                    .sum();
3288                let new_len = extra_field_len + pad_length;
3289                if new_len > u16::MAX as usize {
3290                    // Alignment is impossible without exceeding extra field size limits.
3291                    // Skip alignment.
3292                    None
3293                } else {
3294                    let pad_length_u16: Result<u16, core::num::TryFromIntError> =
3295                        pad_length.try_into();
3296                    if let Ok(pad_length) = pad_length_u16
3297                        && let Some(alignment_extra_field) = DataStreamAlignment::new_with_header_id(
3298                            header_id, pad_length, alignment,
3299                        )
3300                    {
3301                        // Add an extra field to the extra_field, per APPNOTE 4.6.11
3302                        extra_field_len = self
3303                            .extra_fields
3304                            .local_extra_fields()
3305                            .map(|x| x.size(true))
3306                            .sum::<usize>()
3307                            + alignment_extra_field.full_size(true);
3308                        debug_assert_eq!((extra_field_len as u64 + header_end) % align, 0);
3309                        Some(alignment_extra_field)
3310                    } else {
3311                        // Alignment is impossible with this length
3312                        None
3313                    }
3314                }
3315            } else {
3316                None
3317            }
3318        } else {
3319            None
3320        };
3321        let data_start = header_end + extra_field_len as u64;
3322        self.data_start.take();
3323        self.data_start.get_or_init(|| data_start);
3324        let block = ZipLocalEntryBlock {
3325            version_made_by: self.version_needed(),
3326            flags: self.flags(file_name_raw),
3327            compression_method,
3328            last_mod_time: last_modified_time.timepart(),
3329            last_mod_date: last_modified_time.datepart(),
3330            crc32: self.crc32,
3331            compressed_size,
3332            uncompressed_size,
3333            file_name_length: file_name_raw
3334                .len()
3335                .try_into()
3336                .map_err(std::io::Error::other)?,
3337            extra_field_length: extra_field_len
3338                .try_into()
3339                .map_err(|_| invalid!("Extra data field is too large"))?,
3340        };
3341        block.write(writer)?;
3342        writer.write_all(file_name_raw)?;
3343        let local_extra_fields = self.extra_fields.local_extra_fields_mut();
3344        #[cfg(feature = "aes-crypto")]
3345        let mut bytes_written = 0;
3346        for one_extra_field in local_extra_fields {
3347            if let ExtraField::ExtendedTimestamp(timestamp) = one_extra_field {
3348                // The central flags must describe this new local header, including on deep copies.
3349                timestamp.update_local_header_flags();
3350            }
3351            one_extra_field.write(&mut *writer, true)?;
3352            #[cfg(feature = "aes-crypto")]
3353            {
3354                use crate::extra_fields::AexEncryption;
3355
3356                if let ExtraField::AeXEncryption(AexEncryption {
3357                    aes_extra_field_start,
3358                    ..
3359                }) = one_extra_field
3360                {
3361                    *aes_extra_field_start = Some(header_end as usize + bytes_written);
3362                }
3363                bytes_written += one_extra_field.size(true);
3364            }
3365        }
3366        if let Some(alignment_extra_field) = opt_alignment_field {
3367            alignment_extra_field.write(writer, true)?;
3368        }
3369        Ok(())
3370    }
3371}
3372
3373/// Wrapper around a [Write] implementation that implements the [Seek] trait, but where seeking
3374/// returns an error unless it's a no-op.
3375pub struct StreamWriter<W: Write> {
3376    inner: W,
3377    bytes_written: u64,
3378}
3379
3380impl<W: Write> StreamWriter<W> {
3381    /// Creates an instance wrapping the provided inner writer.
3382    pub fn new(inner: W) -> StreamWriter<W> {
3383        Self {
3384            inner,
3385            bytes_written: 0,
3386        }
3387    }
3388
3389    /// Gets a reference to the underlying writer.
3390    pub fn get_ref(&self) -> &W {
3391        &self.inner
3392    }
3393
3394    /// Gets a mutable reference to the underlying writer.
3395    pub fn get_mut(&mut self) -> &mut W {
3396        &mut self.inner
3397    }
3398
3399    /// Consumes this wrapper, returning the underlying writer.
3400    pub fn into_inner(self) -> W {
3401        self.inner
3402    }
3403}
3404
3405impl<W: Write> Write for StreamWriter<W> {
3406    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
3407        let bytes_written = self.inner.write(buf)?;
3408        self.bytes_written += bytes_written as u64;
3409        Ok(bytes_written)
3410    }
3411
3412    fn flush(&mut self) -> io::Result<()> {
3413        self.inner.flush()
3414    }
3415}
3416
3417impl<W: Write> Seek for StreamWriter<W> {
3418    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
3419        match pos {
3420            SeekFrom::Current(0) | SeekFrom::End(0) => return Ok(self.bytes_written),
3421            SeekFrom::Start(x) if x == self.bytes_written => {
3422                return Ok(self.bytes_written);
3423            }
3424            _ => {}
3425        }
3426        Err(io::Error::new(
3427            ErrorKind::Unsupported,
3428            "seek is not supported",
3429        ))
3430    }
3431}
3432
3433#[cfg(test)]
3434#[allow(unknown_lints)] // needless_update is new in clippy pre 1.29.0
3435#[allow(clippy::needless_update)] // So we can use the same FileOptions decls with and without zopfli_buffer_size
3436#[allow(clippy::octal_escapes)] // many false positives in converted fuzz cases
3437mod tests {
3438    use super::{ExtendedFileOptions, FileOptions, FullFileOptions, ZipWriter};
3439    use crate::CompressionMethod::Stored;
3440    use crate::ZipArchive;
3441    use crate::compression::CompressionMethod;
3442    use crate::datetime::DateTime;
3443    use crate::format::system::System;
3444    use crate::result::ZipResult;
3445    use crate::write::EncryptWith::ZipCrypto;
3446    use crate::write::SimpleFileOptions;
3447    use crate::zipcrypto::ZipCryptoKeys;
3448    use core::marker::PhantomData;
3449    #[cfg(feature = "deflate-flate2")]
3450    use std::io::Read;
3451    use std::io::{Cursor, Write};
3452    use std::path::PathBuf;
3453
3454    const SYSTEM_BYTE: u8 = if cfg!(windows) {
3455        System::Dos
3456    } else {
3457        System::Unix
3458    } as u8;
3459
3460    #[test]
3461    fn write_empty_zip() {
3462        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3463        writer.set_comment("ZIP").unwrap();
3464        let result = writer.finish().unwrap();
3465        assert_eq!(result.get_ref().len(), 25);
3466        assert_eq!(
3467            *result.get_ref(),
3468            [
3469                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
3470            ]
3471        );
3472    }
3473
3474    #[test]
3475    fn write_file_comment_roundtrip() -> ZipResult<()> {
3476        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3477        // let options = SimpleFileOptions::default().compression_method(Stored);
3478        let options = FileOptions {
3479            extended_options: ExtendedFileOptions {
3480                file_comment: Some("file comment".into()),
3481                validate_extra_fields: false,
3482                ..Default::default()
3483            },
3484
3485            // won't work with zopfli and no flate2, because DEFLATE is write-only in that cfg
3486            #[cfg(all(feature = "deflate-zopfli", not(feature = "deflate-flate2")))]
3487            compression_method: crate::CompressionMethod::Stored,
3488            ..Default::default()
3489        };
3490        writer.start_file("foo.txt", options)?;
3491        writer.write_all(b"data")?;
3492        let options2 = FileOptions {
3493            extended_options: ExtendedFileOptions {
3494                file_comment: Some("file2 comment".into()),
3495                validate_extra_fields: false,
3496                ..Default::default()
3497            },
3498            // won't work with zopfli and no flate2, because DEFLATE is write-only in that cfg
3499            #[cfg(all(feature = "deflate-zopfli", not(feature = "deflate-flate2")))]
3500            compression_method: crate::CompressionMethod::Stored,
3501            ..Default::default()
3502        };
3503        writer.start_file("foo2.txt", options2)?;
3504        writer.write_all(b"data2")?;
3505
3506        let bytes = writer.finish()?.into_inner();
3507        let mut archive = ZipArchive::new(Cursor::new(bytes))?;
3508        {
3509            let file = archive.by_name("foo.txt")?;
3510            assert_eq!(file.comment(), "file comment");
3511        }
3512        let file2 = archive.by_name("foo2.txt")?;
3513        assert_eq!(file2.comment(), "file2 comment");
3514        Ok(())
3515    }
3516
3517    fn writer_with_file_comment_len(comment_len: usize) -> ZipResult<ZipWriter<Cursor<Vec<u8>>>> {
3518        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3519        let options = FileOptions {
3520            extended_options: ExtendedFileOptions {
3521                file_comment: Some("c".repeat(comment_len).into()),
3522                validate_extra_fields: false,
3523                ..Default::default()
3524            },
3525            #[cfg(all(feature = "deflate-zopfli", not(feature = "deflate-flate2")))]
3526            compression_method: Stored,
3527            ..Default::default()
3528        };
3529        writer.start_file("a", options)?;
3530        Ok(writer)
3531    }
3532
3533    #[test]
3534    fn central_directory_header_accepts_maximum_size() -> ZipResult<()> {
3535        let fixed_header_size = core::mem::size_of::<crate::format::magic::Magic>()
3536            + core::mem::size_of::<crate::format::blocks::ZipCentralEntryBlock>();
3537        let comment_len = u16::MAX as usize - fixed_header_size - 1;
3538        let mut writer = writer_with_file_comment_len(comment_len)?;
3539        let result = {
3540            let (file_name, file) = writer.files.last_mut().unwrap();
3541            file.write_central_directory_header(&mut Vec::new(), file_name)
3542        };
3543        writer.abort_file()?;
3544        result?;
3545        Ok(())
3546    }
3547
3548    #[test]
3549    fn central_directory_header_rejects_size_over_u16() -> ZipResult<()> {
3550        let fixed_header_size = core::mem::size_of::<crate::format::magic::Magic>()
3551            + core::mem::size_of::<crate::format::blocks::ZipCentralEntryBlock>();
3552        let comment_len = u16::MAX as usize - fixed_header_size;
3553        let mut writer = writer_with_file_comment_len(comment_len)?;
3554        let result = {
3555            let (file_name, file) = writer.files.last_mut().unwrap();
3556            file.write_central_directory_header(&mut Vec::new(), file_name)
3557        };
3558        writer.abort_file()?;
3559        let error = result.unwrap_err();
3560        assert!(matches!(
3561            error,
3562            crate::result::ZipError::InvalidArchive(message)
3563                if message.starts_with("Central directory header size exceeds 64KiB:")
3564        ));
3565        Ok(())
3566    }
3567
3568    #[test]
3569    fn central_directory_header_rejects_large_file_name() -> ZipResult<()> {
3570        let local_header_size = size_of::<crate::format::magic::Magic>()
3571            + size_of::<crate::format::blocks::ZipLocalEntryBlock>();
3572        let file_name = "n".repeat(u16::MAX as usize - local_header_size);
3573        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3574        writer.start_file(file_name, SimpleFileOptions::default())?;
3575        let result = {
3576            let (file_name, file) = writer.files.last_mut().unwrap();
3577            file.write_central_directory_header(&mut Vec::new(), file_name)
3578        };
3579        writer.abort_file()?;
3580        let error = result.unwrap_err();
3581        assert!(matches!(
3582            error,
3583            crate::result::ZipError::InvalidArchive(message)
3584                if message.starts_with("Central directory header size exceeds 64KiB:")
3585        ));
3586        Ok(())
3587    }
3588
3589    #[test]
3590    fn central_directory_header_size_uses_central_extra_fields() -> ZipResult<()> {
3591        let mut extended_options = ExtendedFileOptions::default();
3592        extended_options.add_extended_timestamp(Some(1), Some(2), Some(3))?;
3593
3594        // The local timestamp takes 17 bytes, but only 9 bytes in the central directory.
3595        // Alignment is local-only; the comment is central-only.
3596        let central_fixed_size = size_of::<crate::format::magic::Magic>()
3597            + size_of::<crate::format::blocks::ZipCentralEntryBlock>();
3598        let filename = "ab";
3599        let central_timestamp_size = 9;
3600        let comment_len =
3601            u16::MAX as usize - central_fixed_size - filename.len() - central_timestamp_size;
3602        let options = FileOptions {
3603            extended_options,
3604            #[cfg(all(feature = "deflate-zopfli", not(feature = "deflate-flate2")))]
3605            compression_method: Stored,
3606            ..Default::default()
3607        }
3608        .with_alignment(16)
3609        .with_file_comment("c".repeat(comment_len));
3610
3611        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3612        writer.start_file(filename, options)?;
3613
3614        let local_bytes = writer.get_ref().unwrap().get_ref();
3615        let local_extra_size = u16::from_le_bytes([local_bytes[28], local_bytes[29]]) as usize;
3616        let local_header_size = 30 + filename.len() + local_extra_size;
3617        assert!(
3618            local_extra_size > 17,
3619            "local-only alignment field is present"
3620        );
3621        assert!(local_header_size <= u16::MAX as usize);
3622        assert!(
3623            central_fixed_size + filename.len() + local_extra_size + comment_len
3624                > u16::MAX as usize,
3625            "combining local extras with the central-only comment would exceed the limit"
3626        );
3627
3628        let mut central_bytes = Vec::new();
3629        let result = {
3630            let (file_name, file) = writer.files.last_mut().unwrap();
3631            file.write_central_directory_header(&mut central_bytes, file_name)
3632        };
3633        writer.abort_file()?;
3634        result?;
3635
3636        assert_eq!(central_bytes.len(), u16::MAX as usize);
3637        Ok(())
3638    }
3639
3640    #[test]
3641    fn unix_permissions_bitmask() {
3642        // unix_permissions() throws away upper bits.
3643        let options = SimpleFileOptions::default().unix_permissions(0o120777);
3644        assert_eq!(options.permissions, Some(0o777));
3645    }
3646
3647    #[test]
3648    fn write_zip_dir() {
3649        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3650        writer
3651            .add_directory(
3652                "test",
3653                SimpleFileOptions::default().last_modified_time(
3654                    DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(),
3655                ),
3656            )
3657            .unwrap();
3658        assert!(
3659            writer
3660                .write(b"writing to a directory is not allowed, and will not write any data")
3661                .is_err()
3662        );
3663        let result = writer.finish().unwrap();
3664        assert_eq!(result.get_ref().len(), 108);
3665        const DOS_DIR_ATTRIBUTES_BYTE: u8 = if cfg!(windows) { 0x10 } else { 0 };
3666        #[rustfmt::skip]
3667        assert_eq!(
3668            *result.get_ref(),
3669            &[
3670                80u8, 75, 3, 4, 20, 0, 0, 0, 0, 0, 163, 165, 15, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3671                0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 47, 80, 75, 1, 2, 20, SYSTEM_BYTE, 20, 0, 0, 0, 0, 0,
3672                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,
3673                DOS_DIR_ATTRIBUTES_BYTE, 0, 237, 65, 0, 0, 0, 0, 116, 101, 115, 116, 47, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0,
3674                1, 0, 51, 0, 0, 0, 35, 0, 0, 0, 0, 0,
3675            ] as &[u8]
3676        );
3677    }
3678
3679    #[test]
3680    fn write_symlink_simple() {
3681        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3682        writer
3683            .add_symlink(
3684                "name",
3685                "target",
3686                SimpleFileOptions::default().last_modified_time(
3687                    DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(),
3688                ),
3689            )
3690            .unwrap();
3691        assert!(
3692            writer
3693                .write(b"writing to a symlink is not allowed and will not write any data")
3694                .is_err()
3695        );
3696        let result = writer.finish().unwrap();
3697        assert_eq!(result.get_ref().len(), 112);
3698        #[rustfmt::skip]
3699        assert_eq!(
3700            *result.get_ref(),
3701            &[
3702                80u8, 75, 3, 4, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 252, 47, 111, 70, 6, 0, 0, 0,
3703                6, 0, 0, 0, 4, 0, 0, 0, 110, 97, 109, 101, 116, 97, 114, 103, 101, 116, 80, 75, 1,
3704                2, 10, System::Unix as u8, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 252, 47, 111, 70, 6, 0, 0, 0, 6, 0,
3705                0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 161, 0, 0, 0, 0, 110, 97, 109, 101,
3706                80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 50, 0, 0, 0, 40, 0, 0, 0, 0, 0
3707            ] as &[u8],
3708        );
3709    }
3710
3711    #[test]
3712    fn test_path_normalization() {
3713        let mut path = PathBuf::new();
3714        path.push("foo");
3715        path.push("bar");
3716        path.push("..");
3717        path.push(".");
3718        path.push("example.txt");
3719        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3720        writer
3721            .start_file_from_path(path, SimpleFileOptions::default())
3722            .unwrap();
3723        let archive = writer.finish_into_readable().unwrap();
3724        assert_eq!(
3725            "foo/example.txt",
3726            archive.name_for_index(0).unwrap().unwrap()
3727        );
3728    }
3729
3730    #[test]
3731    fn write_symlink_wonky_paths() {
3732        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3733        writer
3734            .add_symlink(
3735                "directory\\link",
3736                "/absolute/symlink\\with\\mixed/slashes",
3737                SimpleFileOptions::default().last_modified_time(
3738                    DateTime::from_date_and_time(2018, 8, 15, 20, 45, 6).unwrap(),
3739                ),
3740            )
3741            .unwrap();
3742        assert!(
3743            writer
3744                .write(b"writing to a symlink is not allowed and will not write any data")
3745                .is_err()
3746        );
3747        let result = writer.finish().unwrap();
3748        assert_eq!(result.get_ref().len(), 162);
3749        #[rustfmt::skip]
3750        assert_eq!(
3751            *result.get_ref(),
3752            &[
3753                80u8, 75, 3, 4, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 95, 41, 81, 245, 36, 0, 0, 0,
3754                36, 0, 0, 0, 14, 0, 0, 0, 100, 105, 114, 101, 99, 116, 111, 114, 121, 92, 108, 105,
3755                110, 107, 47, 97, 98, 115, 111, 108, 117, 116, 101, 47, 115, 121, 109, 108, 105,
3756                110, 107, 92, 119, 105, 116, 104, 92, 109, 105, 120, 101, 100, 47, 115, 108, 97,
3757                115, 104, 101, 115, 80, 75, 1, 2, 10, System::Unix as u8, 10, 0, 0, 0, 0, 0, 163, 165, 15, 77, 95,
3758                41, 81, 245, 36, 0, 0, 0, 36, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
3759                161, 0, 0, 0, 0, 100, 105, 114, 101, 99, 116, 111, 114, 121, 92, 108, 105, 110,
3760                107, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 60, 0, 0, 0, 80, 0, 0, 0, 0, 0
3761            ] as &[u8],
3762        );
3763    }
3764
3765    #[test]
3766    fn write_mimetype_zip() {
3767        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3768        let options = FileOptions {
3769            compression_method: Stored,
3770            compression_level: None,
3771            last_modified_time: DateTime::default(),
3772            permissions: Some(33188),
3773            large_file: false,
3774            encrypt_with: None,
3775            extended_options: (),
3776            alignment: 1,
3777            ..FileOptions::default()
3778        };
3779        writer.start_file("mimetype", options).unwrap();
3780        writer
3781            .write_all(b"application/vnd.oasis.opendocument.text")
3782            .unwrap();
3783        let result = writer.finish().unwrap();
3784
3785        assert_eq!(result.get_ref().len(), 153);
3786        #[rustfmt::skip]
3787        assert_eq!(result.get_ref(), &[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0, 33, 0, 94, 198, 50,
3788            12, 39, 0, 0, 0, 39, 0, 0, 0, 8, 0, 0, 0, 109, 105, 109, 101, 116, 121, 112, 101, 97,
3789            112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 47, 118, 110, 100, 46, 111, 97, 115,
3790            105, 115, 46, 111, 112, 101, 110, 100, 111, 99, 117, 109, 101, 110, 116, 46, 116, 101,
3791            120, 116, 80, 75, 1, 2, 10, SYSTEM_BYTE, 10, 0, 0, 0, 0, 0, 0, 0, 33, 0, 94, 198, 50,
3792            12, 39, 0, 0, 0, 39, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 164, 129, 0, 0, 0, 0,
3793            109, 105, 109, 101, 116, 121, 112, 101, 80, 75, 5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 54, 0, 0,
3794            0, 77, 0, 0, 0, 0, 0]);
3795    }
3796
3797    #[cfg(feature = "deflate-flate2")]
3798    const RT_TEST_TEXT: &str = "And I can't stop thinking about the moments that I lost to you\
3799                            And I can't stop thinking of things I used to do\
3800                            And I can't stop making bad decisions\
3801                            And I can't stop eating stuff you make me chew\
3802                            I put on a smile like you wanna see\
3803                            Another day goes by that I long to be like you";
3804    #[cfg(feature = "deflate-flate2")]
3805    const RT_TEST_FILENAME: &str = "subfolder/sub-subfolder/can't_stop.txt";
3806    #[cfg(feature = "deflate-flate2")]
3807    const SECOND_FILENAME: &str = "different_name.xyz";
3808    #[cfg(feature = "deflate-flate2")]
3809    const THIRD_FILENAME: &str = "third_name.xyz";
3810
3811    #[test]
3812    fn write_non_utf8() {
3813        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3814        let mut options = FileOptions {
3815            compression_method: Stored,
3816            compression_level: None,
3817            last_modified_time: DateTime::default(),
3818            permissions: Some(33188),
3819            large_file: false,
3820            encrypt_with: None,
3821            extended_options: (),
3822            alignment: 1,
3823            ..FileOptions::default()
3824        };
3825
3826        // GB18030
3827        // "中文" = [214, 208, 206, 196]
3828        options.name = Some(&[214, 208, 206, 196]);
3829        writer.start_file_with_options(options).unwrap();
3830        writer.write_all(b"encoding GB18030").unwrap();
3831
3832        // SHIFT_JIS
3833        // "日文" = [147, 250, 149, 182]
3834        options.name = Some(&[147, 250, 149, 182]);
3835        writer.start_file_with_options(options).unwrap();
3836        writer.write_all(b"encoding SHIFT_JIS").unwrap();
3837        let result = writer.finish().unwrap();
3838
3839        assert_eq!(result.get_ref().len(), 224);
3840        #[rustfmt::skip]
3841        assert_eq!(result.get_ref(), &[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0, 33, 0, 29, 183, 125,
3842            75, 16, 0, 0, 0, 16, 0, 0, 0, 4, 0, 0, 0, 214, 208, 206, 196, 101, 110, 99, 111, 100,
3843            105, 110, 103, 32, 71, 66, 49, 56, 48, 51, 48, 80, 75, 3, 4, 10, 0, 0, 0, 0, 0, 0, 0,
3844            33, 0, 75, 110, 14, 242, 18, 0, 0, 0, 18, 0, 0, 0, 4, 0, 0, 0, 147, 250, 149, 182, 101,
3845            110, 99, 111, 100, 105, 110, 103, 32, 83, 72, 73, 70, 84, 95, 74, 73, 83, 80, 75, 1, 2,
3846            10, SYSTEM_BYTE, 10, 0, 0, 0, 0, 0, 0, 0, 33, 0, 29, 183, 125, 75, 16, 0, 0, 0, 16, 0,
3847            0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 164, 129, 0, 0, 0, 0, 214, 208, 206, 196, 80,
3848            75, 1, 2, 10, SYSTEM_BYTE, 10, 0, 0, 0, 0, 0, 0, 0, 33, 0, 75, 110, 14, 242, 18, 0, 0, 0, 18, 0,
3849            0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 164, 129, 50, 0, 0, 0, 147, 250, 149, 182, 80,
3850            75, 5, 6, 0, 0, 0, 0, 2, 0, 2, 0, 100, 0, 0, 0, 102, 0, 0, 0, 0, 0]);
3851    }
3852
3853    #[test]
3854    fn path_to_string() {
3855        let mut path = PathBuf::new();
3856        #[cfg(windows)]
3857        path.push(r"C:\");
3858        #[cfg(unix)]
3859        path.push("/");
3860        path.push("windows");
3861        path.push("..");
3862        path.push(".");
3863        path.push("system32");
3864        let path_str = super::path_to_string(&path).unwrap();
3865        assert_eq!(&*path_str, "system32");
3866    }
3867
3868    /// After an `abort_file` that rewinds, `finish` must not leave an old footer past the new one,
3869    /// even when the stale tail is no longer than the (new) archive comment. Otherwise the stale
3870    /// EOCD at the end is the one a reader finds.
3871    #[test]
3872    fn reopening_keeps_a_unicode_comment_extra_field_comment_unchanged() -> ZipResult<()> {
3873        // An Info-ZIP Unicode Comment extra field (0x6375) whose CRC matches the (empty) stored
3874        // comment makes the reader take its UTF-8 content as the comment, while the language
3875        // encoding flag stays clear. Writing that comment back must not let a reader decode it
3876        // as CP437, or every reopen grows it until it overflows the 16-bit length field.
3877        let mut data = vec![1u8];
3878        data.extend_from_slice(&crc32fast::hash(b"").to_le_bytes());
3879        data.extend_from_slice("é".as_bytes());
3880        let mut options = FullFileOptions::default();
3881        options.add_extra_field(0x6375, data.into_boxed_slice(), true)?;
3882        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3883        writer.start_file("a", options)?;
3884        let mut bytes = writer.finish()?.into_inner();
3885        for round in 0..8 {
3886            let mut archive = ZipArchive::new(Cursor::new(bytes.clone()))?;
3887            assert_eq!(archive.by_index(0)?.comment(), "é", "round {round}");
3888            bytes = ZipWriter::new_append(Cursor::new(bytes))?
3889                .finish()?
3890                .into_inner();
3891        }
3892        Ok(())
3893    }
3894
3895    #[test]
3896    fn finish_after_abort_leaves_no_stale_footer_in_tail_shorter_than_comment() -> ZipResult<()> {
3897        #[cfg(miri)]
3898        let options = SimpleFileOptions {
3899            compression_method: Stored,
3900            ..Default::default()
3901        };
3902        #[cfg(not(miri))]
3903        let options = SimpleFileOptions::default();
3904
3905        fn build(comment_len: usize, options: SimpleFileOptions) -> ZipResult<Vec<u8>> {
3906            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3907            writer.start_file("a", options)?;
3908            writer.write_all(b"aaaa")?;
3909            writer.start_file("b", options)?;
3910            writer.write_all(b"bbbb")?;
3911            let mut writer = ZipWriter::new_append(writer.finish()?)?;
3912            writer.set_raw_comment(vec![b'c'; comment_len].into_boxed_slice())?;
3913            writer.abort_file()?;
3914            Ok(writer.finish()?.into_inner())
3915        }
3916        let old_len = {
3917            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3918            writer.start_file("a", options)?;
3919            writer.write_all(b"aaaa")?;
3920            writer.start_file("b", options)?;
3921            writer.write_all(b"bbbb")?;
3922            writer.finish()?.into_inner().len()
3923        };
3924        let only_a_len = {
3925            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3926            writer.start_file("a", options)?;
3927            writer.write_all(b"aaaa")?;
3928            writer.finish()?.into_inner().len()
3929        };
3930        let stale = old_len - only_a_len;
3931        for comment_len in 1..=stale {
3932            let bytes = build(comment_len, options)?;
3933            let eocds = bytes.windows(4).filter(|w| *w == b"PK\x05\x06").count();
3934            assert_eq!(eocds, 1, "comment_len {comment_len}");
3935            let archive = ZipArchive::new(Cursor::new(bytes))?;
3936            assert_eq!(archive.len(), 1, "comment_len {comment_len}");
3937            assert_eq!(archive.comment().len(), comment_len);
3938        }
3939        Ok(())
3940    }
3941
3942    #[test]
3943    fn finish_into_readable_reports_relocated_central_directory_start() -> ZipResult<()> {
3944        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3945        for name in ["a", "b"] {
3946            writer.start_file(
3947                name,
3948                SimpleFileOptions {
3949                    compression_method: Stored,
3950                    ..Default::default()
3951                },
3952            )?;
3953            writer.write_all(name.as_bytes())?;
3954        }
3955
3956        let mut writer = ZipWriter::new_append(writer.finish()?)?;
3957        writer.abort_file()?;
3958        let archive = writer.finish_into_readable()?;
3959        let central_start = archive.central_directory_start();
3960        let bytes = archive.into_inner().into_inner();
3961        let parsed = ZipArchive::new(Cursor::new(bytes))?;
3962
3963        assert_eq!(central_start, parsed.central_directory_start());
3964        Ok(())
3965    }
3966
3967    #[test]
3968    fn merge_archive_rejects_duplicate_filename() -> ZipResult<()> {
3969        let mut source = ZipWriter::new(Cursor::new(Vec::new()));
3970        source.start_file("a.txt", SimpleFileOptions::default())?;
3971        source.write_all(b"from source")?;
3972        let source = source.finish_into_readable()?;
3973
3974        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
3975        writer.start_file("a.txt", SimpleFileOptions::default())?;
3976        writer.write_all(b"original")?;
3977        let err = writer.merge_archive(source).unwrap_err();
3978        assert!(
3979            matches!(err, crate::result::ZipError::InvalidArchive(ref msg) if msg.starts_with("Duplicate filename: "))
3980        );
3981
3982        // The writer is still usable and the original entry is intact.
3983        writer.abort_file()?;
3984        assert!(matches!(
3985            writer.abort_file(),
3986            Err(crate::result::ZipError::FileNotFound)
3987        ));
3988        writer.start_file("b.txt", SimpleFileOptions::default())?;
3989        writer.write_all(b"b")?;
3990        let archive = writer.finish_into_readable()?;
3991        assert_eq!(archive.len(), 1);
3992        Ok(())
3993    }
3994
3995    #[test]
3996    #[cfg(feature = "deflate-flate2")]
3997    fn test_shallow_copy() {
3998        use std::borrow::Cow;
3999
4000        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4001        let options = FileOptions {
4002            compression_method: CompressionMethod::default(),
4003            compression_level: None,
4004            last_modified_time: DateTime::default(),
4005            permissions: Some(33188),
4006            large_file: false,
4007            encrypt_with: None,
4008            extended_options: (),
4009            alignment: 0,
4010            ..FileOptions::default()
4011        };
4012        writer.start_file(RT_TEST_FILENAME, options).unwrap();
4013        writer.write_all(RT_TEST_TEXT.as_ref()).unwrap();
4014        writer
4015            .shallow_copy_file(RT_TEST_FILENAME, SECOND_FILENAME)
4016            .unwrap();
4017        writer
4018            .shallow_copy_file(RT_TEST_FILENAME, SECOND_FILENAME)
4019            .expect_err("Duplicate filename");
4020        let zip = writer.finish().unwrap();
4021        let mut writer = ZipWriter::new_append(zip).unwrap();
4022        writer
4023            .shallow_copy_file(SECOND_FILENAME, SECOND_FILENAME)
4024            .expect_err("Duplicate filename");
4025        let mut reader = writer.finish_into_readable().unwrap();
4026        let mut file_names: Vec<Cow<'_, str>> = reader.file_names().map(|f| f.unwrap()).collect();
4027        file_names.sort();
4028        let mut expected_file_names = vec![RT_TEST_FILENAME, SECOND_FILENAME];
4029        expected_file_names.sort();
4030        assert_eq!(file_names, expected_file_names);
4031        let mut first_file_content = String::new();
4032        reader
4033            .by_name(RT_TEST_FILENAME)
4034            .unwrap()
4035            .read_to_string(&mut first_file_content)
4036            .unwrap();
4037        assert_eq!(first_file_content, RT_TEST_TEXT);
4038        let mut second_file_content = String::new();
4039        reader
4040            .by_name(SECOND_FILENAME)
4041            .unwrap()
4042            .read_to_string(&mut second_file_content)
4043            .unwrap();
4044        assert_eq!(second_file_content, RT_TEST_TEXT);
4045    }
4046
4047    #[test]
4048    #[cfg(feature = "deflate-flate2")]
4049    fn test_deep_copy() {
4050        use std::borrow::Cow;
4051
4052        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4053        let options = FileOptions {
4054            compression_method: CompressionMethod::default(),
4055            compression_level: None,
4056            last_modified_time: DateTime::default(),
4057            permissions: Some(33188),
4058            large_file: false,
4059            encrypt_with: None,
4060            extended_options: (),
4061            alignment: 0,
4062            ..FileOptions::default()
4063        };
4064        writer.start_file(RT_TEST_FILENAME, options).unwrap();
4065        writer.write_all(RT_TEST_TEXT.as_ref()).unwrap();
4066        writer
4067            .deep_copy_file(RT_TEST_FILENAME, SECOND_FILENAME)
4068            .unwrap();
4069        let zip = writer.finish().unwrap().into_inner();
4070        zip.iter().copied().for_each(|x| print!("{x:02x}"));
4071        println!();
4072        let mut writer = ZipWriter::new_append(Cursor::new(zip)).unwrap();
4073        writer
4074            .deep_copy_file(RT_TEST_FILENAME, THIRD_FILENAME)
4075            .unwrap();
4076        let zip = writer.finish().unwrap();
4077        let mut reader = ZipArchive::new(zip).unwrap();
4078        let mut file_names: Vec<Cow<'_, str>> = reader.file_names().map(|f| f.unwrap()).collect();
4079        file_names.sort();
4080        let mut expected_file_names = vec![RT_TEST_FILENAME, SECOND_FILENAME, THIRD_FILENAME];
4081        expected_file_names.sort();
4082        assert_eq!(file_names, expected_file_names);
4083        let mut first_file_content = String::new();
4084        reader
4085            .by_name(RT_TEST_FILENAME)
4086            .unwrap()
4087            .read_to_string(&mut first_file_content)
4088            .unwrap();
4089        assert_eq!(first_file_content, RT_TEST_TEXT);
4090        let mut second_file_content = String::new();
4091        reader
4092            .by_name(SECOND_FILENAME)
4093            .unwrap()
4094            .read_to_string(&mut second_file_content)
4095            .unwrap();
4096        assert_eq!(second_file_content, RT_TEST_TEXT);
4097    }
4098
4099    #[test]
4100    fn duplicate_filenames() {
4101        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4102        writer
4103            .start_file("foo/bar/test", SimpleFileOptions::default())
4104            .unwrap();
4105        writer
4106            .write_all("The quick brown 🦊 jumps over the lazy 🐕".as_bytes())
4107            .unwrap();
4108        writer
4109            .start_file("foo/bar/test", SimpleFileOptions::default())
4110            .expect_err("Expected duplicate filename not to be allowed");
4111    }
4112
4113    #[test]
4114    fn test_filename_looks_like_zip64_locator() {
4115        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4116        writer
4117            .start_file(
4118                "PK\u{6}\u{7}\0\0\0\u{11}\0\0\0\0\0\0\0\0\0\0\0\0",
4119                SimpleFileOptions::default(),
4120            )
4121            .unwrap();
4122        let zip = writer.finish().unwrap();
4123        let _ = ZipArchive::new(zip).unwrap();
4124    }
4125
4126    #[test]
4127    fn test_filename_looks_like_zip64_locator_2() {
4128        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4129        writer
4130            .start_file(
4131                "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",
4132                SimpleFileOptions::default(),
4133            )
4134            .unwrap();
4135        let zip = writer.finish().unwrap();
4136        let _ = ZipArchive::new(zip).unwrap();
4137    }
4138
4139    #[test]
4140    fn test_filename_looks_like_zip64_locator_2a() {
4141        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4142        writer
4143            .start_file(
4144                "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",
4145                SimpleFileOptions::default(),
4146            )
4147            .unwrap();
4148        let zip = writer.finish().unwrap();
4149        let _ = ZipArchive::new(zip).unwrap();
4150    }
4151
4152    #[test]
4153    fn test_filename_looks_like_zip64_locator_3() {
4154        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4155        writer
4156            .start_file("\0PK\u{6}\u{6}", SimpleFileOptions::default())
4157            .unwrap();
4158        writer
4159            .start_file(
4160                "\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}",
4161                SimpleFileOptions::default(),
4162            )
4163            .unwrap();
4164        let zip = writer.finish().unwrap();
4165        let _ = ZipArchive::new(zip).unwrap();
4166    }
4167
4168    #[test]
4169    fn test_filename_looks_like_zip64_locator_4() {
4170        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4171        writer
4172            .start_file("PK\u{6}\u{6}", SimpleFileOptions::default())
4173            .unwrap();
4174        writer
4175            .start_file("\0\0\0\0\0\0", SimpleFileOptions::default())
4176            .unwrap();
4177        writer
4178            .start_file("\0", SimpleFileOptions::default())
4179            .unwrap();
4180        writer.start_file("", SimpleFileOptions::default()).unwrap();
4181        writer
4182            .start_file("\0\0", SimpleFileOptions::default())
4183            .unwrap();
4184        writer
4185            .start_file(
4186                "\0\0\0PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
4187                SimpleFileOptions::default(),
4188            )
4189            .unwrap();
4190        let zip = writer.finish().unwrap();
4191        let _ = ZipArchive::new(zip).unwrap();
4192    }
4193
4194    #[test]
4195    fn test_filename_looks_like_zip64_locator_5() -> ZipResult<()> {
4196        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4197        writer
4198            .add_directory("", SimpleFileOptions::default().with_alignment(21))
4199            .unwrap();
4200        let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap();
4201        writer.shallow_copy_file("/", "").unwrap();
4202        writer.shallow_copy_file("", "\0").unwrap();
4203        writer.shallow_copy_file("\0", "PK\u{6}\u{6}").unwrap();
4204        let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap();
4205        writer
4206            .start_file("\0\0\0\0\0\0", SimpleFileOptions::default())
4207            .unwrap();
4208        let mut writer = ZipWriter::new_append(writer.finish().unwrap()).unwrap();
4209        writer
4210            .start_file(
4211                "#PK\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",
4212                SimpleFileOptions::default(),
4213            )
4214            .unwrap();
4215        let zip = writer.finish().unwrap();
4216        let _ = ZipArchive::new(zip).unwrap();
4217        Ok(())
4218    }
4219
4220    #[test]
4221    #[cfg(feature = "deflate-flate2")]
4222    fn remove_shallow_copy_keeps_original() -> ZipResult<()> {
4223        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4224        writer
4225            .start_file("original", SimpleFileOptions::default())
4226            .unwrap();
4227        writer.write_all(RT_TEST_TEXT.as_bytes()).unwrap();
4228        writer
4229            .shallow_copy_file("original", "shallow_copy")
4230            .unwrap();
4231        writer.abort_file().unwrap();
4232        let mut zip = ZipArchive::new(writer.finish().unwrap()).unwrap();
4233        let mut file = zip.by_name("original").unwrap();
4234        let mut contents = Vec::new();
4235        file.read_to_end(&mut contents).unwrap();
4236        assert_eq!(RT_TEST_TEXT.as_bytes(), contents);
4237        Ok(())
4238    }
4239
4240    #[test]
4241    fn remove_encrypted_file() -> ZipResult<()> {
4242        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4243        let first_file_options = SimpleFileOptions::default()
4244            .with_alignment(0xFFFF)
4245            .with_deprecated_encryption(b"Password");
4246        writer.start_file("", first_file_options).unwrap();
4247        writer.abort_file().unwrap();
4248        let zip = writer.finish().unwrap();
4249        let mut writer = ZipWriter::new(zip);
4250        writer.start_file("", SimpleFileOptions::default()).unwrap();
4251        Ok(())
4252    }
4253
4254    #[test]
4255    fn remove_encrypted_aligned_symlink() -> ZipResult<()> {
4256        let mut options = SimpleFileOptions::default();
4257        options = options.with_deprecated_encryption(b"Password");
4258        options.alignment = 0xFFFF;
4259        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4260        writer.add_symlink("", "s\t\0\0ggggg\0\0", options).unwrap();
4261        writer.abort_file().unwrap();
4262        let zip = writer.finish().unwrap();
4263        let mut writer = ZipWriter::new_append(zip).unwrap();
4264        writer.start_file("", SimpleFileOptions::default()).unwrap();
4265        Ok(())
4266    }
4267
4268    #[cfg(feature = "deflate-zopfli")]
4269    #[test]
4270    fn zopfli_empty_write() -> ZipResult<()> {
4271        #[cfg(not(miri))]
4272        const LEVEL: i64 = 264;
4273        #[cfg(miri)]
4274        const LEVEL: i64 = 12;
4275
4276        let mut options = SimpleFileOptions::default();
4277        options = options
4278            .compression_method(CompressionMethod::default())
4279            .compression_level(Some(LEVEL));
4280        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4281        writer.start_file("", options).unwrap();
4282        writer.write_all(&[]).unwrap();
4283        writer.write_all(&[]).unwrap();
4284        Ok(())
4285    }
4286
4287    #[cfg(all(feature = "deflate-zopfli", not(feature = "deflate-flate2")))]
4288    #[test]
4289    fn zopfli_only_level_range() -> ZipResult<()> {
4290        use crate::result::ZipError::UnsupportedArchive;
4291
4292        let options = |level| {
4293            SimpleFileOptions::default()
4294                .compression_method(CompressionMethod::Deflated)
4295                .compression_level(Some(level))
4296        };
4297
4298        // Zopfli levels start at 10; 1-9 belong to flate2, which is not enabled here
4299        for level in 0..10 {
4300            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4301            assert!(
4302                matches!(
4303                    writer.start_file("below", options(level)),
4304                    Err(UnsupportedArchive("Unsupported compression level"))
4305                ),
4306                "level {level}"
4307            );
4308        }
4309
4310        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4311        writer.start_file("first", options(10))?;
4312        writer.write_all(b"data")?;
4313        writer.finish()?;
4314        Ok(())
4315    }
4316
4317    #[test]
4318    fn crash_with_no_features() -> ZipResult<()> {
4319        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'";
4320        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4321        let mut options = SimpleFileOptions::default();
4322        options = options.with_alignment(3584).compression_method(Stored);
4323        writer.start_file(ORIGINAL_FILE_NAME, options)?;
4324        let archive = writer.finish()?;
4325        let mut writer = ZipWriter::new_append(archive)?;
4326        writer.shallow_copy_file(ORIGINAL_FILE_NAME, "\u{6}\\")?;
4327        writer.finish()?;
4328        Ok(())
4329    }
4330
4331    #[test]
4332    fn test_alignment() {
4333        let page_size = 4096;
4334        let options = SimpleFileOptions::default()
4335            .compression_method(Stored)
4336            .with_alignment(page_size);
4337        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
4338        let contents = b"sleeping";
4339        let () = zip.start_file("sleep", options).unwrap();
4340        let _count = zip.write(&contents[..]).unwrap();
4341        let mut zip = zip.finish_into_readable().unwrap();
4342        let file = zip.by_index(0).unwrap();
4343        assert_eq!(file.name().unwrap(), "sleep");
4344        let data_start = file.data_start().unwrap();
4345        assert_eq!(data_start, u64::from(page_size));
4346    }
4347
4348    #[test]
4349    fn test_alignment_2() {
4350        let page_size = 4096;
4351        let mut data = Vec::new();
4352        {
4353            let options = SimpleFileOptions::default()
4354                .compression_method(Stored)
4355                .with_alignment(page_size);
4356            let mut zip = ZipWriter::new(Cursor::new(&mut data));
4357            let contents = b"sleeping";
4358            let () = zip.start_file("sleep", options).unwrap();
4359            let _count = zip.write(&contents[..]).unwrap();
4360        }
4361        assert_eq!(data[4096..4104], b"sleeping"[..]);
4362        {
4363            let mut zip = ZipArchive::new(Cursor::new(&mut data)).unwrap();
4364            let file = zip.by_index(0).unwrap();
4365            assert_eq!(file.name().unwrap(), "sleep");
4366            let data_start = file.data_start().unwrap();
4367            assert_eq!(data_start, u64::from(page_size));
4368        }
4369    }
4370
4371    #[test]
4372    fn test_crash_short_read() {
4373        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4374        let comment = vec![
4375            1, 80, 75, 5, 6, 237, 237, 237, 237, 237, 237, 237, 237, 44, 255, 191, 255, 255, 255,
4376            255, 255, 255, 255, 255, 16,
4377        ]
4378        .into_boxed_slice();
4379        writer.set_raw_comment(comment).unwrap();
4380        let options = SimpleFileOptions::default()
4381            .compression_method(Stored)
4382            .with_alignment(11823);
4383        writer.start_file("", options).unwrap();
4384        writer.write_all(&[255, 255, 44, 255, 0]).unwrap();
4385        let written = writer.finish().unwrap();
4386        let _ = ZipWriter::new_append(written).unwrap();
4387    }
4388
4389    #[cfg(all(feature = "_deflate-any", feature = "aes-crypto"))]
4390    #[test]
4391    fn test_fuzz_failure_2024_05_08() {
4392        let mut first_writer = ZipWriter::new(Cursor::new(Vec::new()));
4393        let mut second_writer = ZipWriter::new(Cursor::new(Vec::new()));
4394        let options = SimpleFileOptions::default()
4395            .compression_method(Stored)
4396            .with_alignment(46036);
4397        second_writer.add_symlink("\0", "", options).unwrap();
4398        let second_archive = second_writer.finish_into_readable().unwrap().into_inner();
4399        let mut second_writer = ZipWriter::new_append(second_archive).unwrap();
4400        let options = SimpleFileOptions::default()
4401            .compression_method(CompressionMethod::Deflated)
4402            .large_file(true)
4403            .with_alignment(46036)
4404            .with_aes_encryption(crate::AesMode::Aes128, "\0\0");
4405        second_writer.add_symlink("", "", options).unwrap();
4406        let second_archive = second_writer.finish_into_readable().unwrap().into_inner();
4407        let mut second_writer = ZipWriter::new_append(second_archive).unwrap();
4408        let options = SimpleFileOptions::default().compression_method(Stored);
4409        second_writer.start_file(" ", options).unwrap();
4410        let second_archive = second_writer.finish_into_readable().unwrap();
4411        first_writer.merge_archive(second_archive).unwrap();
4412        let _ = ZipArchive::new(first_writer.finish().unwrap()).unwrap();
4413    }
4414
4415    #[cfg(all(feature = "_bzip2_any", not(miri)))]
4416    #[test]
4417    fn test_fuzz_failure_2024_06_08() -> ZipResult<()> {
4418        use crate::write::ExtendedFileOptions;
4419        use CompressionMethod::Bzip2;
4420
4421        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4422        writer.set_flush_on_finish_file(false);
4423        const SYMLINK_PATH: &str = "PK\u{6}\u{6}K\u{6}\u{6}\u{6}\0\0\0\0\u{18}\0\0\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\u{1}\0\0PK\u{1}\u{2},\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\u{1}\0\0PK\u{1}\u{2},\0\0\0\0\0\0\0\0\0\0l\0\0\0\0\0\0PK\u{6}\u{7}P\0\0\0\0\0\0\0\0\0\0\0\0\u{1}\0\0";
4424        let sub_writer = {
4425            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4426            writer.set_flush_on_finish_file(false);
4427            let options = FileOptions {
4428                compression_method: Bzip2,
4429                compression_level: None,
4430                last_modified_time: DateTime::from_date_and_time(1980, 5, 20, 21, 0, 57)?,
4431                permissions: None,
4432                large_file: false,
4433                encrypt_with: None,
4434                extended_options: ExtendedFileOptions {
4435                    extra_fields: vec![].into(),
4436                    file_comment: None,
4437                    validate_extra_fields: false,
4438                },
4439                alignment: 2048,
4440                ..Default::default()
4441            };
4442            writer.add_symlink_from_path(SYMLINK_PATH, "||\0\0\0\0", options)?;
4443            writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
4444            writer.deep_copy_file_from_path(SYMLINK_PATH, "")?;
4445            writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
4446            writer.abort_file()?;
4447            writer
4448        };
4449        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4450        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
4451        writer.deep_copy_file_from_path(SYMLINK_PATH, "foo")?;
4452        let _ = writer.finish_into_readable()?;
4453        Ok(())
4454    }
4455
4456    #[test]
4457    fn test_short_extra_data() {
4458        use crate::extra_fields::CustomExtraField;
4459
4460        let custom_creation = CustomExtraField::new_from_raw(true, &[99, 0, 15, 0, 207]);
4461        assert!(custom_creation.is_err());
4462    }
4463
4464    #[test]
4465    #[cfg(not(feature = "unreserved"))]
4466    fn test_invalid_extra_data() -> ZipResult<()> {
4467        use crate::extra_fields::CustomExtraField;
4468        use crate::write::ExtendedFileOptions;
4469
4470        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4471        writer.set_flush_on_finish_file(false);
4472        let options = FileOptions {
4473            compression_method: Stored,
4474            compression_level: None,
4475            last_modified_time: DateTime::from_date_and_time(1980, 1, 4, 6, 54, 0)?,
4476            permissions: None,
4477            large_file: false,
4478            encrypt_with: None,
4479            extended_options: ExtendedFileOptions {
4480                extra_fields: vec![
4481                    CustomExtraField::new_from_raw(
4482                        true,
4483                        &[
4484                            7, 0, 15, 0, 207, 117, 177, 117, 112, 2, 0, 255, 255, 131, 255, 255,
4485                            255, 80, 185,
4486                        ],
4487                    )
4488                    .unwrap(),
4489                ]
4490                .into(),
4491                file_comment: None,
4492                validate_extra_fields: false,
4493                ..Default::default()
4494            },
4495            alignment: 32787,
4496            ..Default::default()
4497        };
4498        assert!(writer.start_file_from_path("", options).is_err());
4499        Ok(())
4500    }
4501
4502    #[test]
4503    #[cfg(not(feature = "unreserved"))]
4504    fn test_invalid_extra_data_without_feature_unreserved() {
4505        use crate::extra_fields::CustomExtraField;
4506        use crate::write::ExtendedFileOptions;
4507
4508        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4509        let options = FileOptions {
4510            compression_method: Stored,
4511            extended_options: ExtendedFileOptions {
4512                extra_fields: vec![
4513                    CustomExtraField::new_from_raw(true, &[1, 41, 4, 0, 1, 255, 245, 117]).unwrap(),
4514                ]
4515                .into(),
4516                file_comment: None,
4517                validate_extra_fields: false,
4518                ..Default::default()
4519            },
4520            alignment: 4103,
4521            ..Default::default()
4522        };
4523
4524        // [1, 41] which is 0x2901 is an unknown extra field
4525        assert!(writer.start_file_from_path("", options).is_ok());
4526    }
4527
4528    #[cfg(feature = "deflate64")]
4529    #[test]
4530    fn test_fuzz_crash_2024_06_13a() -> ZipResult<()> {
4531        use crate::write::ExtendedFileOptions;
4532        use CompressionMethod::Deflate64;
4533
4534        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4535        writer.set_flush_on_finish_file(false);
4536        let options = FileOptions {
4537            compression_method: Deflate64,
4538            compression_level: None,
4539            last_modified_time: DateTime::from_date_and_time(2039, 4, 17, 6, 18, 19)?,
4540            permissions: None,
4541            large_file: true,
4542            encrypt_with: None,
4543            extended_options: ExtendedFileOptions::default(),
4544            alignment: 4,
4545            ..Default::default()
4546        };
4547        writer.add_directory_from_path("", options)?;
4548        let _ = writer.finish_into_readable()?;
4549        Ok(())
4550    }
4551
4552    #[test]
4553    fn test_fuzz_crash_2024_06_13b() -> ZipResult<()> {
4554        use crate::write::ExtendedFileOptions;
4555        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4556        writer.set_flush_on_finish_file(false);
4557        let sub_writer = {
4558            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4559            writer.set_flush_on_finish_file(false);
4560            let options = FileOptions {
4561                compression_method: Stored,
4562                compression_level: None,
4563                last_modified_time: DateTime::from_date_and_time(1980, 4, 14, 6, 11, 54)?,
4564                permissions: None,
4565                large_file: false,
4566                encrypt_with: None,
4567                extended_options: ExtendedFileOptions::default(),
4568                alignment: 185,
4569                ..Default::default()
4570            };
4571            writer.add_symlink_from_path("", "", options)?;
4572            writer
4573        };
4574        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4575        writer.deep_copy_file_from_path("", "_copy")?;
4576        let _ = writer.finish_into_readable()?;
4577        Ok(())
4578    }
4579
4580    #[test]
4581    fn test_fuzz_crash_2024_06_14() -> ZipResult<()> {
4582        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4583        writer.set_flush_on_finish_file(false);
4584        let sub_writer = {
4585            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4586            writer.set_flush_on_finish_file(false);
4587            let options = FullFileOptions {
4588                compression_method: Stored,
4589                large_file: true,
4590                alignment: 93,
4591                ..Default::default()
4592            };
4593            writer.start_file_from_path("\0", options)?;
4594            writer = ZipWriter::new_append(writer.finish()?)?;
4595            writer.deep_copy_file_from_path("\0", "")?;
4596            writer
4597        };
4598        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4599        writer.deep_copy_file_from_path("", "copy")?;
4600        let _ = writer.finish_into_readable()?;
4601        Ok(())
4602    }
4603
4604    #[test]
4605    fn test_fuzz_crash_2024_06_14a() -> ZipResult<()> {
4606        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4607        writer.set_flush_on_finish_file(false);
4608        let options = FileOptions {
4609            compression_method: Stored,
4610            compression_level: None,
4611            last_modified_time: DateTime::from_date_and_time(2083, 5, 30, 21, 45, 35)?,
4612            permissions: None,
4613            large_file: false,
4614            encrypt_with: None,
4615            extended_options: ExtendedFileOptions::default(),
4616            alignment: 2565,
4617            ..Default::default()
4618        };
4619        writer.add_symlink_from_path("", "", options)?;
4620        writer.abort_file()?;
4621        let options = FileOptions {
4622            compression_method: Stored,
4623            compression_level: None,
4624            last_modified_time: DateTime::default(),
4625            permissions: None,
4626            large_file: false,
4627            encrypt_with: None,
4628            extended_options: ExtendedFileOptions::default(),
4629            alignment: 0,
4630            ..Default::default()
4631        };
4632        writer.start_file_from_path("", options)?;
4633        let _ = writer.finish_into_readable()?;
4634        Ok(())
4635    }
4636
4637    #[allow(deprecated)]
4638    #[test]
4639    fn test_fuzz_crash_2024_06_14b() -> ZipResult<()> {
4640        use crate::extra_fields::CustomExtraField;
4641
4642        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4643        writer.set_flush_on_finish_file(false);
4644        let options = FileOptions {
4645            compression_method: Stored,
4646            compression_level: None,
4647            last_modified_time: DateTime::from_date_and_time(2078, 3, 6, 12, 48, 58)?,
4648            permissions: None,
4649            large_file: true,
4650            encrypt_with: None,
4651            extended_options: ExtendedFileOptions::default(),
4652            alignment: 0xFFF1,
4653            ..Default::default()
4654        };
4655        writer.start_file_from_path("\u{4}\0@\n//\u{c}", options)?;
4656        writer = ZipWriter::new_append(writer.finish()?)?;
4657        writer.abort_file()?;
4658        let options = FileOptions {
4659            compression_method: CompressionMethod::Unsupported(0xFFFF),
4660            compression_level: None,
4661            last_modified_time: DateTime::from_date_and_time(2055, 10, 2, 11, 48, 49)?,
4662            permissions: None,
4663            large_file: true,
4664            encrypt_with: None,
4665            extended_options: ExtendedFileOptions {
4666                extra_fields: vec![
4667                    CustomExtraField::new_from_raw(false, &[255, 255, 1, 0, 255]).unwrap(),
4668                    CustomExtraField::new_from_raw(false, &[0, 0, 0, 0]).unwrap(),
4669                ]
4670                .into(),
4671                file_comment: None,
4672                validate_extra_fields: false,
4673                ..Default::default()
4674            },
4675            alignment: 0xFFFF,
4676            ..Default::default()
4677        };
4678        writer.add_directory_from_path("", options)?;
4679        let _ = writer.finish_into_readable()?;
4680        Ok(())
4681    }
4682
4683    #[test]
4684    fn test_fuzz_crash_2024_06_14c() -> ZipResult<()> {
4685        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4686        writer.set_flush_on_finish_file(false);
4687        let sub_writer = {
4688            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4689            writer.set_flush_on_finish_file(false);
4690            let options = FileOptions {
4691                compression_method: Stored,
4692                compression_level: None,
4693                last_modified_time: DateTime::from_date_and_time(2060, 4, 6, 13, 13, 3)?,
4694                permissions: None,
4695                large_file: true,
4696                encrypt_with: None,
4697                extended_options: ExtendedFileOptions::default(),
4698                alignment: 0,
4699                ..Default::default()
4700            };
4701            writer.start_file_from_path("\0", options)?;
4702            writer.write_all(&([]))?;
4703            writer = ZipWriter::new_append(writer.finish()?)?;
4704            writer.deep_copy_file_from_path("\0", "")?;
4705            writer
4706        };
4707        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4708        writer.deep_copy_file_from_path("", "_copy")?;
4709        let _ = writer.finish_into_readable()?;
4710        Ok(())
4711    }
4712
4713    #[cfg(all(feature = "_deflate-any", feature = "aes-crypto"))]
4714    #[test]
4715    /// Created on
4716    /// https://github.com/zip-rs/zip2/commit/2a035f520104b7df343b02726c35ebd53ac2e15a
4717    /// Then changed in
4718    /// https://github.com/zip-rs/zip2/commit/16aa9bcddf58887849aaa36caf6e377eae3636dd
4719    /// Because of
4720    /// https://github.com/zip-rs/zip2/commit/e3ccaf6e005a855e87d2244a5ccdff9c18279b0c
4721    fn test_fuzz_crash_2024_06_14d() -> ZipResult<()> {
4722        use crate::extra_fields::CustomExtraField;
4723        use crate::format::aes::{AesMode, AesVendorVersion};
4724        use crate::write::EncryptWith;
4725        use CompressionMethod::Deflated;
4726
4727        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4728        writer.set_flush_on_finish_file(false);
4729        let options = FileOptions {
4730            compression_method: Deflated,
4731            compression_level: Some(5),
4732            last_modified_time: DateTime::from_date_and_time(2107, 4, 8, 15, 54, 19)?,
4733            permissions: None,
4734            large_file: true,
4735            encrypt_with: Some(EncryptWith::Aes {
4736                mode: AesMode::Aes256,
4737                password: Some(&[]),
4738                vendor_version: AesVendorVersion::Ae2,
4739                salt: None,
4740            }),
4741            extended_options: ExtendedFileOptions {
4742                extra_fields: vec![
4743                    CustomExtraField::new_from_raw(false, &[2, 0, 1, 0, 0]).unwrap(),
4744                    CustomExtraField::new_from_raw(true, &[35, 229, 2, 0, 41, 41]).unwrap(),
4745                    CustomExtraField::new_from_raw(true, &[231, 44, 2, 0, 52, 233]).unwrap(),
4746                    CustomExtraField::new_from_raw(true, &[82, 201, 0, 0]).unwrap(),
4747                    CustomExtraField::new_from_raw(true, &[3, 0, 2, 0, 233, 255]).unwrap(),
4748                    CustomExtraField::new_from_raw(true, &[3, 0, 2, 0, 26, 154]).unwrap(),
4749                    CustomExtraField::new_from_raw(true, &[38, 251, 0, 0]).unwrap(),
4750                ]
4751                .into(),
4752                file_comment: None,
4753                validate_extra_fields: false,
4754                ..Default::default()
4755            },
4756            alignment: 0xFFFF,
4757            ..Default::default()
4758        };
4759        assert!(writer.add_directory_from_path("", options).is_ok());
4760        Ok(())
4761    }
4762
4763    // Created on
4764    // https://github.com/zip-rs/zip2/commit/e23f676c40ffef9ac62ad8a82cf4bcdd43b7a4e7
4765    // Then changed
4766    // https://github.com/zip-rs/zip2/commit/e3ccaf6e005a855e87d2244a5ccdff9c18279b0c
4767    #[test]
4768    fn test_fuzz_crash_2024_06_14e() -> ZipResult<()> {
4769        use crate::extra_fields::CustomExtraField;
4770
4771        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4772        writer.set_flush_on_finish_file(false);
4773        let options = FileOptions {
4774            compression_method: Stored,
4775            compression_level: None,
4776            last_modified_time: DateTime::from_date_and_time(1988, 1, 1, 1, 6, 26)?,
4777            permissions: None,
4778            large_file: true,
4779            encrypt_with: None,
4780            extended_options: ExtendedFileOptions {
4781                extra_fields: vec![
4782                    CustomExtraField::new_from_raw(false, &[76, 0, 1, 0, 0]).unwrap(),
4783                    CustomExtraField::new_from_raw(false, &[2, 0, 0, 0]).unwrap(),
4784                    CustomExtraField::new_from_raw(true, &[1, 149, 1, 0, 255]).unwrap(),
4785                    CustomExtraField::new_from_raw(true, &[3, 0, 0, 0]).unwrap(),
4786                    CustomExtraField::new_from_raw(true, &[2, 255, 0, 0]).unwrap(),
4787                    CustomExtraField::new_from_raw(true, &[12, 65, 1, 0, 0]).unwrap(),
4788                    CustomExtraField::new_from_raw(true, &[67, 149, 0, 0]).unwrap(),
4789                    CustomExtraField::new_from_raw(true, &[76, 149, 2, 0, 149, 149]).unwrap(),
4790                    CustomExtraField::new_from_raw(true, &[67, 149, 0, 0]).unwrap(),
4791                ]
4792                .into(),
4793                file_comment: None,
4794                validate_extra_fields: false,
4795                ..Default::default()
4796            },
4797            alignment: 0xFFFF,
4798            ..Default::default()
4799        };
4800        assert!(writer.add_directory_from_path("", options).is_ok());
4801        let _ = writer.finish_into_readable()?;
4802        Ok(())
4803    }
4804
4805    #[allow(deprecated)]
4806    #[test]
4807    fn test_fuzz_crash_2024_06_17() -> ZipResult<()> {
4808        use crate::extra_fields::CustomExtraField;
4809
4810        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4811        writer.set_flush_on_finish_file(false);
4812        let sub_writer = {
4813            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4814            writer.set_flush_on_finish_file(false);
4815            let sub_writer = {
4816                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4817                writer.set_flush_on_finish_file(false);
4818                let sub_writer = {
4819                    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4820                    writer.set_flush_on_finish_file(false);
4821                    let sub_writer = {
4822                        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4823                        writer.set_flush_on_finish_file(false);
4824                        let sub_writer = {
4825                            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4826                            writer.set_flush_on_finish_file(false);
4827                            let sub_writer = {
4828                                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4829                                writer.set_flush_on_finish_file(false);
4830                                let sub_writer = {
4831                                    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4832                                    writer.set_flush_on_finish_file(false);
4833                                    let sub_writer = {
4834                                        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
4835                                        writer.set_flush_on_finish_file(false);
4836                                        let sub_writer = {
4837                                            let mut writer =
4838                                                ZipWriter::new(Cursor::new(Vec::new()));
4839                                            writer.set_flush_on_finish_file(false);
4840                                            let options = FileOptions {
4841                                                compression_method: CompressionMethod::Unsupported(
4842                                                    0xFFFF,
4843                                                ),
4844                                                compression_level: Some(5),
4845                                                last_modified_time: DateTime::from_date_and_time(
4846                                                    2107, 2, 8, 15, 0, 0,
4847                                                )?,
4848                                                permissions: None,
4849                                                large_file: true,
4850                                                encrypt_with: Some(ZipCrypto(
4851                                                    ZipCryptoKeys::of(
4852                                                        0x63ff, 0xc62d3103, 0xfffe00ea,
4853                                                    ),
4854                                                    PhantomData,
4855                                                )),
4856                                                extended_options: ExtendedFileOptions::default(),
4857                                                alignment: 255,
4858                                                ..Default::default()
4859                                            };
4860                                            writer.add_symlink_from_path("1\0PK\u{6}\u{6}\u{b}\u{6}\u{6}\u{6}\0\0\0\0\0\0\0\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\u{b}\0\0PK\u{1}\u{2},\0\0\0\0\0\0\0\0\0\0\0\u{10}\0\0\0K\u{6}\u{6}\0\0\0\0\0\0\0\0PK\u{2}\u{6}", "", options)?;
4861                                            writer = ZipWriter::new_append(
4862                                                writer.finish_into_readable()?.into_inner(),
4863                                            )?;
4864                                            writer
4865                                        };
4866                                        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4867                                        writer = ZipWriter::new_append(
4868                                            writer.finish_into_readable()?.into_inner(),
4869                                        )?;
4870                                        let options = FileOptions {
4871                                            compression_method: Stored,
4872                                            compression_level: None,
4873                                            last_modified_time: DateTime::from_date_and_time(
4874                                                1992, 7, 3, 0, 0, 0,
4875                                            )?,
4876                                            permissions: None,
4877                                            large_file: true,
4878                                            encrypt_with: None,
4879                                            extended_options: ExtendedFileOptions::default(),
4880                                            alignment: 43,
4881                                            ..Default::default()
4882                                        };
4883                                        writer.start_file_from_path(
4884                                            "\0\0\0\u{3}\0\u{1a}\u{1a}\u{1a}\u{1a}\u{1a}\u{1a}",
4885                                            options,
4886                                        )?;
4887                                        let options = FileOptions {
4888                                            compression_method: Stored,
4889                                            compression_level: None,
4890                                            last_modified_time: DateTime::from_date_and_time(
4891                                                2006, 3, 27, 2, 24, 26,
4892                                            )?,
4893                                            permissions: None,
4894                                            large_file: false,
4895                                            encrypt_with: None,
4896                                            extended_options: ExtendedFileOptions::default(),
4897                                            alignment: 26,
4898                                            ..Default::default()
4899                                        };
4900                                        writer.start_file_from_path("\0K\u{6}\u{6}\0PK\u{6}\u{7}PK\u{6}\u{6}\0\0\0\0\0\0\0\0PK\u{2}\u{6}", options)?;
4901                                        writer = ZipWriter::new_append(
4902                                            writer.finish_into_readable()?.into_inner(),
4903                                        )?;
4904                                        let options = FileOptions {
4905                                            compression_method: Stored,
4906                                            compression_level: Some(17),
4907                                            last_modified_time: DateTime::from_date_and_time(
4908                                                2103, 4, 10, 23, 15, 18,
4909                                            )?,
4910                                            permissions: Some(3284386755),
4911                                            large_file: true,
4912                                            encrypt_with: Some(ZipCrypto(
4913                                                ZipCryptoKeys::of(
4914                                                    0x8888c5bf, 0x88888888, 0xff888888,
4915                                                ),
4916                                                PhantomData,
4917                                            )),
4918                                            extended_options: ExtendedFileOptions {
4919                                                extra_fields: vec![
4920                                                    CustomExtraField::new_from_raw(
4921                                                        false,
4922                                                        &[3, 0, 1, 0, 255],
4923                                                    )
4924                                                    .unwrap(),
4925                                                    CustomExtraField::new_from_raw(
4926                                                        false,
4927                                                        &[144, 136, 0, 0],
4928                                                    )
4929                                                    .unwrap(),
4930                                                ]
4931                                                .into(),
4932                                                file_comment: None,
4933                                                validate_extra_fields: false,
4934                                                ..Default::default()
4935                                            },
4936                                            alignment: 0xFFFF,
4937                                            ..Default::default()
4938                                        };
4939                                        writer.add_symlink_from_path("", "\nu", options)?;
4940                                        writer = ZipWriter::new_append(writer.finish()?)?;
4941                                        writer
4942                                    };
4943                                    writer.merge_archive(sub_writer.finish_into_readable()?)?;
4944                                    writer = ZipWriter::new_append(
4945                                        writer.finish_into_readable()?.into_inner(),
4946                                    )?;
4947                                    writer
4948                                };
4949                                writer.merge_archive(sub_writer.finish_into_readable()?)?;
4950                                writer = ZipWriter::new_append(writer.finish()?)?;
4951                                writer
4952                            };
4953                            writer.merge_archive(sub_writer.finish_into_readable()?)?;
4954                            writer =
4955                                ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
4956                            writer.abort_file()?;
4957                            let options = FileOptions {
4958                                compression_method: CompressionMethod::Unsupported(49603),
4959                                compression_level: Some(20),
4960                                last_modified_time: DateTime::from_date_and_time(
4961                                    2047, 4, 14, 3, 15, 14,
4962                                )?,
4963                                permissions: Some(3284386755),
4964                                large_file: true,
4965                                encrypt_with: Some(ZipCrypto(
4966                                    ZipCryptoKeys::of(0xc3, 0x0, 0x0),
4967                                    PhantomData,
4968                                )),
4969                                extended_options: ExtendedFileOptions::default(),
4970                                alignment: 0,
4971                                ..Default::default()
4972                            };
4973                            writer.add_directory_from_path("", options)?;
4974                            writer.deep_copy_file_from_path("/", "")?;
4975                            writer.shallow_copy_file_from_path("", "copy")?;
4976                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4977                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4978                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4979                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4980                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4981                            assert!(writer.shallow_copy_file_from_path("", "copy").is_err());
4982                            writer
4983                        };
4984                        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4985                        writer
4986                    };
4987                    writer.merge_archive(sub_writer.finish_into_readable()?)?;
4988                    writer
4989                };
4990                writer.merge_archive(sub_writer.finish_into_readable()?)?;
4991                writer
4992            };
4993            writer.merge_archive(sub_writer.finish_into_readable()?)?;
4994            writer
4995        };
4996        writer.merge_archive(sub_writer.finish_into_readable()?)?;
4997        let _ = writer.finish_into_readable()?;
4998        Ok(())
4999    }
5000
5001    #[test]
5002    fn test_fuzz_crash_2024_06_17a() -> ZipResult<()> {
5003        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5004        writer.set_flush_on_finish_file(false);
5005        const PATH_1: &str = "\0I\01\0P\0\0\u{2}\0\0\u{1a}\u{1a}\u{1a}\u{1a}\u{1b}\u{1a}UT\u{5}\0\0\u{1a}\u{1a}\u{1a}\u{1a}UT\u{5}\0\u{1}\0\u{1a}\u{1a}\u{1a}UT\t\0uc\u{5}\0\0\0\0\u{7f}\u{7f}\u{7f}\u{7f}PK\u{6}";
5006        let sub_writer = {
5007            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5008            writer.set_flush_on_finish_file(false);
5009            let sub_writer = {
5010                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5011                writer.set_flush_on_finish_file(false);
5012                let options = FileOptions {
5013                    compression_method: Stored,
5014                    compression_level: None,
5015                    last_modified_time: DateTime::from_date_and_time(1981, 1, 1, 0, 24, 21)?,
5016                    permissions: Some(16908288),
5017                    large_file: false,
5018                    encrypt_with: None,
5019                    extended_options: ExtendedFileOptions::default(),
5020                    alignment: 20555,
5021                    ..Default::default()
5022                };
5023                writer.start_file_from_path(
5024                    "\0\u{7}\u{1}\0\0\0\0\0\0\0\0\u{1}\0\0PK\u{1}\u{2};",
5025                    options,
5026                )?;
5027                writer.write_all(
5028                    &([
5029                        255, 255, 255, 255, 253, 253, 253, 203, 203, 203, 253, 253, 253, 253, 255,
5030                        255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 249, 191, 225, 225,
5031                        241, 197,
5032                    ]),
5033                )?;
5034                writer.write_all(
5035                    &([
5036                        197, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
5037                        255, 75, 0,
5038                    ]),
5039                )?;
5040                writer
5041            };
5042            writer.merge_archive(sub_writer.finish_into_readable()?)?;
5043            writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5044            let options = FileOptions {
5045                compression_method: Stored,
5046                compression_level: None,
5047                last_modified_time: DateTime::from_date_and_time(1980, 11, 14, 10, 46, 47)?,
5048                permissions: None,
5049                large_file: false,
5050                encrypt_with: None,
5051                extended_options: ExtendedFileOptions::default(),
5052                alignment: 0,
5053                ..Default::default()
5054            };
5055            writer.start_file_from_path(PATH_1, options)?;
5056            writer.deep_copy_file_from_path(PATH_1, "eee\u{6}\0\0\0\0\0\0\0\0\0\0\0$\0\0\0\0\0\0\u{7f}\u{7f}PK\u{6}\u{6}K\u{6}\u{6}\u{6}\0\0\0\0\0\0\0\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\u{1}\0\0PK\u{1}\u{1e},\0\0\0\0\0\0\0\0\0\0\0\u{8}\0*\0\0\u{1}PK\u{6}\u{7}PK\u{6}\u{6}\0\0\0\0\0\0\0\0}K\u{2}\u{6}")?;
5057            writer
5058        };
5059        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5060        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5061        writer.deep_copy_file_from_path(PATH_1, "")?;
5062        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5063        writer.shallow_copy_file_from_path("", "copy")?;
5064        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5065        let _ = writer.finish_into_readable()?;
5066        Ok(())
5067    }
5068
5069    #[test]
5070    #[allow(clippy::octal_escapes)]
5071    #[cfg(all(feature = "_bzip2_any", not(miri)))]
5072    fn test_fuzz_crash_2024_06_17b() -> ZipResult<()> {
5073        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5074        writer.set_flush_on_finish_file(false);
5075        let sub_writer = {
5076            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5077            writer.set_flush_on_finish_file(false);
5078            let sub_writer = {
5079                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5080                writer.set_flush_on_finish_file(false);
5081                let sub_writer = {
5082                    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5083                    writer.set_flush_on_finish_file(false);
5084                    let sub_writer = {
5085                        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5086                        writer.set_flush_on_finish_file(false);
5087                        let sub_writer = {
5088                            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5089                            writer.set_flush_on_finish_file(false);
5090                            let sub_writer = {
5091                                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5092                                writer.set_flush_on_finish_file(false);
5093                                let sub_writer = {
5094                                    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5095                                    writer.set_flush_on_finish_file(false);
5096                                    let sub_writer = {
5097                                        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5098                                        writer.set_flush_on_finish_file(false);
5099                                        let options = FileOptions {
5100                                            compression_method: Stored,
5101                                            compression_level: None,
5102                                            last_modified_time: DateTime::from_date_and_time(
5103                                                1981, 1, 1, 0, 0, 21,
5104                                            )?,
5105                                            permissions: Some(16908288),
5106                                            large_file: false,
5107                                            encrypt_with: None,
5108                                            extended_options: ExtendedFileOptions::default(),
5109                                            alignment: 20555,
5110                                            ..Default::default()
5111                                        };
5112                                        writer.start_file_from_path("\0\u{7}\u{1}\0\0\0\0\0\0\0\0\u{1}\0\0PK\u{1}\u{2};\u{1a}\u{18}\u{1a}UT\t.........................\0u", options)?;
5113                                        writer
5114                                    };
5115                                    writer.merge_archive(sub_writer.finish_into_readable()?)?;
5116                                    let options = FileOptions {
5117                                        compression_method: CompressionMethod::Bzip2,
5118                                        compression_level: Some(5),
5119                                        last_modified_time: DateTime::from_date_and_time(
5120                                            2055, 7, 7, 3, 6, 6,
5121                                        )?,
5122                                        permissions: None,
5123                                        large_file: false,
5124                                        encrypt_with: None,
5125                                        extended_options: ExtendedFileOptions::default(),
5126                                        alignment: 0,
5127                                        ..Default::default()
5128                                    };
5129                                    writer.start_file_from_path("\0\0\0\0..\0\0\0\0\0\u{7f}\u{7f}PK\u{6}\u{6}K\u{6}\u{6}\u{6}\0\0\0\0\0\0\0\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\u{1}\0\0PK\u{1}\u{1e},\0\0\0\0\0\0\0\0\0\0\0\u{8}\0*\0\0\u{1}PK\u{6}\u{7}PK\u{6}\u{6}\0\0\0\0\0\0\0\0}K\u{2}\u{6}", options)?;
5130                                    writer = ZipWriter::new_append(
5131                                        writer.finish_into_readable()?.into_inner(),
5132                                    )?;
5133                                    writer
5134                                };
5135                                writer.merge_archive(sub_writer.finish_into_readable()?)?;
5136                                writer = ZipWriter::new_append(
5137                                    writer.finish_into_readable()?.into_inner(),
5138                                )?;
5139                                writer
5140                            };
5141                            writer.merge_archive(sub_writer.finish_into_readable()?)?;
5142                            writer =
5143                                ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5144                            writer
5145                        };
5146                        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5147                        writer =
5148                            ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5149                        writer
5150                    };
5151                    writer.merge_archive(sub_writer.finish_into_readable()?)?;
5152                    writer
5153                };
5154                writer.merge_archive(sub_writer.finish_into_readable()?)?;
5155                writer
5156            };
5157            writer.merge_archive(sub_writer.finish_into_readable()?)?;
5158            writer
5159        };
5160        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5161        let _ = writer.finish_into_readable()?;
5162        Ok(())
5163    }
5164
5165    #[test]
5166    fn test_fuzz_crash_2024_06_18() -> ZipResult<()> {
5167        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5168        writer
5169            .set_raw_comment(Box::<[u8]>::from([
5170                80, 75, 5, 6, 255, 255, 255, 255, 255, 255, 80, 75, 5, 6, 255, 255, 255, 255, 255,
5171                255, 13, 0, 13, 13, 13, 13, 13, 255, 255, 255, 255, 255, 255, 255, 255,
5172            ]))
5173            .unwrap();
5174        let sub_writer = {
5175            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5176            writer.set_flush_on_finish_file(false);
5177            writer.set_raw_comment(Box::new([])).unwrap();
5178            writer
5179        };
5180        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5181        writer = ZipWriter::new_append(writer.finish()?)?;
5182        let _ = writer.finish_into_readable()?;
5183        Ok(())
5184    }
5185
5186    #[test]
5187    fn test_fuzz_crash_2024_06_18a() -> ZipResult<()> {
5188        use crate::extra_fields::CustomExtraField;
5189
5190        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5191        writer.set_flush_on_finish_file(false);
5192        writer.set_raw_comment(Box::<[u8]>::from([])).unwrap();
5193        let sub_writer = {
5194            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5195            writer.set_flush_on_finish_file(false);
5196            let sub_writer = {
5197                let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5198                writer.set_flush_on_finish_file(false);
5199                let sub_writer = {
5200                    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5201                    writer.set_flush_on_finish_file(false);
5202                    let options = FullFileOptions {
5203                        compression_method: Stored,
5204                        compression_level: None,
5205                        last_modified_time: DateTime::from_date_and_time(2107, 4, 8, 14, 0, 19)?,
5206                        permissions: None,
5207                        large_file: false,
5208                        encrypt_with: None,
5209                        extended_options: ExtendedFileOptions {
5210                            extra_fields: vec![
5211                                CustomExtraField::new_from_raw(false, &[182, 180, 1, 0, 180])
5212                                    .unwrap(),
5213                                CustomExtraField::new_from_raw(false, &[182, 74, 0, 0]).unwrap(),
5214                                CustomExtraField::new_from_raw(false, &[200, 0, 0, 0]).unwrap(),
5215                                CustomExtraField::new_from_raw(false, &[2, 0, 0, 0]).unwrap(),
5216                            ]
5217                            .into(),
5218                            file_comment: None,
5219                            validate_extra_fields: false,
5220                            ..Default::default()
5221                        },
5222                        alignment: 1542,
5223                        ..Default::default()
5224                    };
5225                    writer.start_file_from_path("\0\0PK\u{6}\u{6}K\u{6}PK\u{3}\u{4}\0\0\0\0\0\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\u{1}\u{1}\0PK\u{1}\u{2},\0\0\0\0\0\0\0\0\0\0\0P\u{7}\u{4}/.\0KP\0\0;\0\0\0\u{1e}\0\0\0\0\0\0\0\0\0\0\0\0\0", options)?;
5226                    let finished = writer.finish_into_readable()?;
5227                    assert_eq!(1, finished.file_names().count());
5228                    writer = ZipWriter::new_append(finished.into_inner())?;
5229                    let options = FullFileOptions {
5230                        compression_method: Stored,
5231                        compression_level: Some(5),
5232                        last_modified_time: DateTime::from_date_and_time(2107, 4, 1, 0, 0, 0)?,
5233                        permissions: None,
5234                        large_file: false,
5235                        encrypt_with: Some(ZipCrypto(
5236                            ZipCryptoKeys::of(0x0, 0x62e4b50, 0x100),
5237                            PhantomData,
5238                        )),
5239                        ..Default::default()
5240                    };
5241                    writer.add_symlink_from_path(
5242                        "\0K\u{6}\0PK\u{6}\u{7}PK\u{6}\u{6}\0\0\0\0\0\0\0\0PK\u{2}\u{6}",
5243                        "\u{8}\0\0\0\0/\0",
5244                        options,
5245                    )?;
5246                    let finished = writer.finish_into_readable()?;
5247                    assert_eq!(2, finished.file_names().count());
5248                    writer = ZipWriter::new_append(finished.into_inner())?;
5249                    assert_eq!(2, writer.files.len());
5250                    writer
5251                };
5252                let finished = sub_writer.finish_into_readable()?;
5253                assert_eq!(2, finished.file_names().count());
5254                writer.merge_archive(finished)?;
5255                writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5256                writer
5257            };
5258            writer.merge_archive(sub_writer.finish_into_readable()?)?;
5259            writer
5260        };
5261        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5262        let _ = writer.finish_into_readable()?;
5263        Ok(())
5264    }
5265
5266    #[cfg(all(feature = "_bzip2_any", feature = "aes-crypto", not(miri)))]
5267    #[test]
5268    fn test_fuzz_crash_2024_06_18b() -> ZipResult<()> {
5269        use crate::format::aes::{AesMode, AesVendorVersion};
5270        use crate::write::options::EncryptWith;
5271
5272        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5273        writer.set_flush_on_finish_file(true);
5274        writer.set_raw_comment([0].into())?;
5275        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5276        assert_eq!(writer.get_raw_comment()[0], 0);
5277        let options = FileOptions {
5278            compression_method: CompressionMethod::Bzip2,
5279            compression_level: None,
5280            last_modified_time: DateTime::from_date_and_time(2009, 6, 3, 13, 37, 39)?,
5281            permissions: Some(2644352413),
5282            large_file: true,
5283            encrypt_with: Some(EncryptWith::Aes {
5284                mode: AesMode::Aes256,
5285                vendor_version: AesVendorVersion::Ae2,
5286                password: Some(&[]),
5287                salt: None,
5288            }),
5289            extended_options: ExtendedFileOptions::default(),
5290            alignment: 255,
5291            ..Default::default()
5292        };
5293        writer.add_symlink_from_path("", "", options)?;
5294        writer.deep_copy_file_from_path("", "PK\u{5}\u{6}\0\0\0\0\0\0\0\0\0\0\0\0\0\u{4}\0\0\0")?;
5295        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5296        assert_eq!(writer.get_raw_comment()[0], 0);
5297        writer.deep_copy_file_from_path(
5298            "PK\u{5}\u{6}\0\0\0\0\0\0\0\0\0\0\0\0\0\u{4}\0\0\0",
5299            "\u{2}yy\u{5}qu\0",
5300        )?;
5301        let finished = writer.finish()?;
5302        let archive = ZipArchive::new(finished.clone())?;
5303        assert_eq!(archive.comment(), [0]);
5304        writer = ZipWriter::new_append(finished)?;
5305        assert_eq!(writer.get_raw_comment()[0], 0);
5306        let _ = writer.finish_into_readable()?;
5307        Ok(())
5308    }
5309
5310    #[test]
5311    fn test_fuzz_crash_2024_06_19() -> ZipResult<()> {
5312        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5313        writer.set_flush_on_finish_file(false);
5314        let options = FileOptions {
5315            compression_method: Stored,
5316            compression_level: None,
5317            last_modified_time: DateTime::from_date_and_time(1980, 3, 1, 19, 55, 58)?,
5318            permissions: None,
5319            large_file: false,
5320            encrypt_with: None,
5321            extended_options: ExtendedFileOptions::default(),
5322            alignment: 256,
5323            ..Default::default()
5324        };
5325        writer.start_file_from_path(
5326            "\0\0\0PK\u{5}\u{6}\0\0\0\0\u{1}\0\u{12}\u{6}\0\0\0\0\0\u{1}\0\0\0\0\0\0\0\0\0",
5327            options,
5328        )?;
5329        writer.set_flush_on_finish_file(false);
5330        writer.shallow_copy_file_from_path(
5331            "\0\0\0PK\u{5}\u{6}\0\0\0\0\u{1}\0\u{12}\u{6}\0\0\0\0\0\u{1}\0\0\0\0\0\0\0\0\0",
5332            "",
5333        )?;
5334        writer.set_flush_on_finish_file(false);
5335        writer.deep_copy_file_from_path("", "copy")?;
5336        writer.abort_file()?;
5337        writer.set_flush_on_finish_file(false);
5338        writer.set_raw_comment([255, 0].into())?;
5339        writer.abort_file()?;
5340        assert_eq!(writer.get_raw_comment(), [255, 0]);
5341        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5342        assert_eq!(writer.get_raw_comment(), [255, 0]);
5343        writer.set_flush_on_finish_file(false);
5344        let options = FileOptions {
5345            compression_method: Stored,
5346            compression_level: None,
5347            last_modified_time: DateTime::default(),
5348            permissions: None,
5349            large_file: false,
5350            encrypt_with: None,
5351            extended_options: ExtendedFileOptions::default(),
5352            ..Default::default()
5353        };
5354        writer.start_file_from_path("", options)?;
5355        assert_eq!(writer.get_raw_comment(), [255, 0]);
5356        let archive = writer.finish_into_readable()?;
5357        assert_eq!(archive.comment(), [255, 0]);
5358        Ok(())
5359    }
5360
5361    #[test]
5362    fn fuzz_crash_2024_06_21() -> ZipResult<()> {
5363        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5364        writer.set_flush_on_finish_file(false);
5365        let options = FullFileOptions {
5366            compression_method: Stored,
5367            compression_level: None,
5368            last_modified_time: DateTime::from_date_and_time(1980, 2, 1, 0, 0, 0)?,
5369            permissions: None,
5370            large_file: false,
5371            encrypt_with: None,
5372            ..Default::default()
5373        };
5374        const LONG_PATH: &str = "\0@PK\u{6}\u{6}\u{7}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@/\0\0\00ΝPK\u{5}\u{6}O\0\u{10}\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0@PK\u{6}\u{7}\u{6}\0/@\0\0\0\0\0\0\0\0 \0\0";
5375        writer.start_file_from_path(LONG_PATH, options)?;
5376        writer = ZipWriter::new_append(writer.finish()?)?;
5377        writer.deep_copy_file_from_path(LONG_PATH, "oo\0\0\0")?;
5378        writer.abort_file()?;
5379        writer.set_raw_comment([33].into())?;
5380        let archive = writer.finish_into_readable()?;
5381        writer = ZipWriter::new_append(archive.into_inner())?;
5382        assert!(writer.get_raw_comment().starts_with(&[33]));
5383        let archive = writer.finish_into_readable()?;
5384        assert!(archive.comment().starts_with(&[33]));
5385        Ok(())
5386    }
5387
5388    #[test]
5389    fn abort_after_merging_archive_with_zipcrypto_entry() -> ZipResult<()> {
5390        use crate::extra_fields::CustomExtraField;
5391        use crate::read::read_zipfile_from_stream;
5392        use std::io::{Seek, SeekFrom, copy};
5393
5394        let mut sub_writer = ZipWriter::new(Cursor::new(Vec::new()));
5395        let symlink_options = FileOptions::<ExtendedFileOptions> {
5396            compression_method: Stored,
5397            compression_level: Some(1),
5398            last_modified_time: DateTime::from_date_and_time(1986, 6, 1, 0, 0, 10)?,
5399            large_file: true,
5400            alignment: 33,
5401            name: Some(&[0, 9, 0, 75, 76, 5, 1, 0, 0, 0, 71, 0, 0, 84]),
5402            ..Default::default()
5403        };
5404        sub_writer.add_symlink_from_path(
5405            "M\u{5}\u{6}\u{12}PK\u{1}\u{2}",
5406            "\u{1d}\0KJ\u{6}lllllllllllllllllllllllllllllllllllllllllllllllllllll\u{6}",
5407            symlink_options,
5408        )?;
5409        sub_writer.deep_copy_file_from_path(
5410            "M\u{5}\u{6}\u{12}PK\u{1}\u{2}",
5411            "\u{1}\0\u{1}PK\u{5}\u{6}$\0\0P\u{1}\u{1}PK\u{5}\u{6}\0\0\0\0",
5412        )?;
5413        let encrypted_options = FileOptions::<ExtendedFileOptions> {
5414            compression_method: Stored,
5415            last_modified_time: DateTime::from_date_and_time(2055, 6, 26, 14, 1, 0)?,
5416            large_file: true,
5417            encrypt_with: Some(ZipCrypto(
5418                ZipCryptoKeys::of(0x6054b50, 0, 0x587a37fd),
5419                PhantomData,
5420            )),
5421            extended_options: ExtendedFileOptions {
5422                extra_fields: vec![
5423                    CustomExtraField::new(true, 40582, [].into()),
5424                    CustomExtraField::new(false, 61465, [].into()),
5425                    CustomExtraField::new(true, 36850, [229, 229, 76, 214].into()),
5426                    CustomExtraField::new(true, 28112, [7].into()),
5427                    CustomExtraField::new(false, 45315, [132, 0, 255, 255, 27, 255].into()),
5428                    CustomExtraField::new(false, 65282, [40].into()),
5429                    CustomExtraField::new(false, 10, [].into()),
5430                    CustomExtraField::new(false, 3, [].into()),
5431                    CustomExtraField::new(false, 37, [].into()),
5432                ]
5433                .into(),
5434                file_comment: None,
5435                validate_extra_fields: false,
5436            },
5437            alignment: 90,
5438            name: Some(&[]),
5439            ..Default::default()
5440        };
5441        sub_writer.start_file_from_path("", encrypted_options)?;
5442        let sub_writer = ZipWriter::new_append(sub_writer.finish()?)?;
5443
5444        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5445        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5446        writer.abort_file()?;
5447        let writer = ZipWriter::new_append(writer.finish()?)?;
5448        let mut stream = writer.finish()?;
5449        stream.seek(SeekFrom::Start(0))?;
5450
5451        let mut files_read = 0;
5452        loop {
5453            let file = match read_zipfile_from_stream(&mut stream) {
5454                Ok(Some(file)) => file,
5455                Ok(None) | Err(_) => break,
5456            };
5457            let mut file = file;
5458            copy(&mut file, &mut std::io::sink())?;
5459            files_read += 1;
5460        }
5461        assert_eq!(files_read, 2);
5462        Ok(())
5463    }
5464
5465    #[test]
5466    #[cfg(all(feature = "_bzip2_any", not(miri)))]
5467    fn fuzz_crash_2024_07_17() -> ZipResult<()> {
5468        use crate::extra_fields::CustomExtraField;
5469
5470        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5471        writer.set_flush_on_finish_file(false);
5472        let options = FileOptions {
5473            compression_method: CompressionMethod::Bzip2,
5474            compression_level: None,
5475            last_modified_time: DateTime::from_date_and_time(2095, 2, 16, 21, 0, 1)?,
5476            permissions: Some(84238341),
5477            large_file: true,
5478            encrypt_with: None,
5479            extended_options: ExtendedFileOptions {
5480                extra_fields: vec![
5481                    CustomExtraField::new_from_raw(false, &[117, 99, 6, 0, 0, 0, 0, 0, 0, 0])
5482                        .unwrap(),
5483                    CustomExtraField::new_from_raw(false, &[2, 1, 0, 0]).unwrap(),
5484                    CustomExtraField::new_from_raw(false, &[2, 0, 0, 0]).unwrap(),
5485                ]
5486                .into(),
5487                file_comment: None,
5488                validate_extra_fields: false,
5489                ..Default::default()
5490            },
5491            alignment: 0xFFFF,
5492            ..Default::default()
5493        };
5494        writer.start_file_from_path("", options)?;
5495        //writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5496        writer.deep_copy_file_from_path("", "copy")?;
5497        let _ = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5498        Ok(())
5499    }
5500
5501    #[test]
5502    fn fuzz_crash_2024_07_19() -> ZipResult<()> {
5503        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5504        writer.set_flush_on_finish_file(false);
5505        let options = FileOptions {
5506            compression_method: Stored,
5507            compression_level: None,
5508            last_modified_time: DateTime::from_date_and_time(1980, 6, 1, 0, 34, 47)?,
5509            permissions: None,
5510            large_file: true,
5511            encrypt_with: None,
5512            extended_options: ExtendedFileOptions::default(),
5513            alignment: 45232,
5514            ..Default::default()
5515        };
5516        writer.add_directory_from_path("", options)?;
5517        writer.deep_copy_file_from_path("/", "")?;
5518        writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5519        writer.deep_copy_file_from_path("", "copy")?;
5520        let _ = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5521        Ok(())
5522    }
5523
5524    #[test]
5525    #[cfg(feature = "aes-crypto")]
5526    fn fuzz_crash_2024_07_19a() -> ZipResult<()> {
5527        use crate::extra_fields::CustomExtraField;
5528        use crate::format::aes::{AesMode, AesVendorVersion};
5529        use crate::write::EncryptWith;
5530
5531        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5532        writer.set_flush_on_finish_file(false);
5533        let options = FileOptions {
5534            compression_method: Stored,
5535            compression_level: None,
5536            last_modified_time: DateTime::from_date_and_time(2107, 6, 5, 13, 0, 21)?,
5537            permissions: None,
5538            large_file: true,
5539            encrypt_with: Some(EncryptWith::Aes {
5540                mode: AesMode::Aes128,
5541                password: Some(&[]),
5542                vendor_version: AesVendorVersion::Ae2,
5543                salt: None,
5544            }),
5545            extended_options: ExtendedFileOptions {
5546                extra_fields: vec![
5547                    CustomExtraField::new_from_raw(false, &[3, 0, 4, 0, 209, 53, 53, 8])?,
5548                    CustomExtraField::new_from_raw(false, &[2, 61, 0, 0])?,
5549                ]
5550                .into(),
5551                file_comment: None,
5552                validate_extra_fields: false,
5553                ..Default::default()
5554            },
5555            alignment: 0xFFFF,
5556            ..Default::default()
5557        };
5558        writer.start_file_from_path("", options)?;
5559        let _ = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5560        Ok(())
5561    }
5562
5563    #[test]
5564    fn fuzz_crash_2024_07_20() -> ZipResult<()> {
5565        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5566        writer.set_flush_on_finish_file(true);
5567        let options = FileOptions {
5568            compression_method: Stored,
5569            compression_level: None,
5570            last_modified_time: DateTime::from_date_and_time(2041, 8, 2, 19, 38, 0)?,
5571            permissions: None,
5572            large_file: false,
5573            encrypt_with: None,
5574            extended_options: ExtendedFileOptions::default(),
5575            alignment: 0,
5576            ..Default::default()
5577        };
5578        writer.add_directory_from_path("\0\0\0\0\0\0\07黻", options)?;
5579        let sub_writer = {
5580            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5581            writer.set_flush_on_finish_file(false);
5582            let options = FileOptions {
5583                compression_method: Stored,
5584                compression_level: None,
5585                last_modified_time: DateTime::default(),
5586                permissions: None,
5587                large_file: false,
5588                encrypt_with: None,
5589                extended_options: ExtendedFileOptions::default(),
5590                alignment: 4,
5591                ..Default::default()
5592            };
5593            writer.add_directory_from_path("\0\0\0黻", options)?;
5594            writer = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5595            writer.abort_file()?;
5596            let options = FileOptions {
5597                compression_method: Stored,
5598                compression_level: None,
5599                last_modified_time: DateTime::from_date_and_time(1980, 1, 1, 0, 7, 0)?,
5600                permissions: Some(2663103419),
5601                large_file: false,
5602                encrypt_with: None,
5603                extended_options: ExtendedFileOptions::default(),
5604                alignment: 32256,
5605                ..Default::default()
5606            };
5607            writer.add_directory_from_path("\0", options)?;
5608            writer = ZipWriter::new_append(writer.finish()?)?;
5609            writer
5610        };
5611        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5612        let _ = ZipWriter::new_append(writer.finish_into_readable()?.into_inner())?;
5613        Ok(())
5614    }
5615
5616    #[test]
5617    fn fuzz_crash_2024_07_21() -> ZipResult<()> {
5618        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5619        let sub_writer = {
5620            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5621            writer.add_directory_from_path(
5622                "",
5623                FileOptions {
5624                    compression_method: Stored,
5625                    compression_level: None,
5626                    last_modified_time: DateTime::from_date_and_time(2105, 8, 1, 15, 0, 0)?,
5627                    permissions: None,
5628                    large_file: false,
5629                    encrypt_with: None,
5630                    extended_options: ExtendedFileOptions::default(),
5631                    alignment: 0,
5632                    ..Default::default()
5633                },
5634            )?;
5635            writer.abort_file()?;
5636            let mut writer = ZipWriter::new_append(writer.finish()?)?;
5637            writer.add_directory_from_path(
5638                "",
5639                FileOptions {
5640                    compression_method: Stored,
5641                    compression_level: None,
5642                    last_modified_time: DateTime::default(),
5643                    permissions: None,
5644                    large_file: false,
5645                    encrypt_with: None,
5646                    extended_options: ExtendedFileOptions::default(),
5647                    alignment: 16,
5648                    ..Default::default()
5649                },
5650            )?;
5651            ZipWriter::new_append(writer.finish()?)?
5652        };
5653        writer.merge_archive(sub_writer.finish_into_readable()?)?;
5654        let writer = ZipWriter::new_append(writer.finish()?)?;
5655        let _ = writer.finish_into_readable()?;
5656
5657        Ok(())
5658    }
5659
5660    #[test]
5661    fn test_explicit_system_roundtrip() -> ZipResult<()> {
5662        use crate::read::HasZipMetadata;
5663        // Test round-trip: write with various systems, read back and verify
5664        let systems = vec![System::Unix, System::Dos, System::WindowsNTFS];
5665
5666        for system in systems {
5667            let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5668            let options = SimpleFileOptions::default()
5669                .compression_method(Stored)
5670                .system(system);
5671
5672            let filename = format!("test_{:?}.txt", system);
5673            writer.start_file(&filename, options)?;
5674            writer.write_all(b"content")?;
5675
5676            // Write and read back
5677            let bytes = writer.finish()?.into_inner();
5678            let mut reader = ZipArchive::new(Cursor::new(bytes))?;
5679
5680            let file = reader.by_index(0)?;
5681            assert_eq!(
5682                file.get_metadata().system,
5683                system,
5684                "System mismatch for {:?}",
5685                system
5686            );
5687        }
5688
5689        Ok(())
5690    }
5691
5692    #[test]
5693    fn test_system_default_behavior() -> ZipResult<()> {
5694        use crate::read::HasZipMetadata;
5695        // Test that when system is not set, default behavior is preserved
5696        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5697        let options = SimpleFileOptions::default().compression_method(Stored);
5698
5699        writer.start_file("test.txt", options)?;
5700        writer.write_all(b"test")?;
5701
5702        let bytes = writer.finish()?.into_inner();
5703        let mut reader = ZipArchive::new(Cursor::new(bytes))?;
5704
5705        let file = reader.by_index(0)?;
5706        let expected_system = if cfg!(windows) {
5707            System::Dos
5708        } else {
5709            System::Unix
5710        };
5711        assert_eq!(file.get_metadata().system, expected_system);
5712
5713        Ok(())
5714    }
5715
5716    #[test]
5717    #[cfg(not(feature = "unreserved"))]
5718    fn test_invalid_extra_data_known_extra_field_without_feature_unreserved() {
5719        use crate::CompressionMethod::Stored;
5720        use crate::ZipWriter;
5721        use crate::extra_fields::CustomExtraField;
5722        use crate::write::ExtendedFileOptions;
5723        use crate::write::FileOptions;
5724        use std::io::Cursor;
5725
5726        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5727        let options = FileOptions {
5728            compression_method: Stored,
5729            extended_options: ExtendedFileOptions {
5730                extra_fields: vec![
5731                    CustomExtraField::new_from_raw(false, &[0x0d, 0x00, 4, 0, 1, 255, 245, 117])
5732                        .unwrap(),
5733                ]
5734                .into(),
5735                file_comment: None,
5736                validate_extra_fields: false,
5737                ..Default::default()
5738            },
5739            alignment: 4103,
5740            ..Default::default()
5741        };
5742        // 0x000d is a known extra field
5743        // we don't have the feature "unreserved" so the parsing will fail
5744        assert!(writer.start_file_from_path("", options).is_err());
5745    }
5746
5747    #[test]
5748    #[cfg(feature = "unreserved")]
5749    fn test_invalid_extra_data_known_extra_field_with_feature_unreserved() {
5750        use crate::CompressionMethod::Stored;
5751        use crate::ZipWriter;
5752        use crate::extra_fields::CustomExtraField;
5753        use crate::write::ExtendedFileOptions;
5754        use crate::write::FileOptions;
5755        use std::io::Cursor;
5756
5757        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5758        let options = FileOptions {
5759            compression_method: Stored,
5760            extended_options: ExtendedFileOptions {
5761                extra_fields: vec![
5762                    CustomExtraField::new_from_raw(false, &[0x0d, 0x00, 4, 0, 1, 255, 245, 117])
5763                        .unwrap(),
5764                ]
5765                .into(),
5766                file_comment: None,
5767                validate_extra_fields: false,
5768                ..Default::default()
5769            },
5770            alignment: 4103,
5771            ..Default::default()
5772        };
5773        // 0x000d is a known extra field
5774        // we have the feature "unreserved" so the parsing will succeed
5775        assert!(writer.start_file_from_path("", options).is_ok());
5776    }
5777
5778    #[test]
5779    fn test_max_len_extra_field() {
5780        use crate::format::blocks::ZipLocalEntryBlock;
5781        use crate::format::magic::Magic;
5782        assert_eq!(core::mem::size_of::<Magic>(), 4);
5783        assert_eq!(core::mem::size_of::<ZipLocalEntryBlock>(), 26);
5784    }
5785
5786    #[test]
5787    fn test_set_archive_comment_then_reopen() -> ZipResult<()> {
5788        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5789        writer.start_file_from_path(
5790            "",
5791            SimpleFileOptions {
5792                name: Some(&[37, 37, 255, 255, 41, 47, 213]),
5793                compression_method: Stored,
5794                ..Default::default()
5795            },
5796        )?;
5797        writer.abort_file()?;
5798        writer.set_raw_comment(Box::new([255]))?;
5799        let _ = ZipWriter::new_append(writer.finish()?)?;
5800        Ok(())
5801    }
5802
5803    /// Regression test for fuzz_write (PR #1175 merge queue): a central-only Unicode Path field
5804    /// whose CRC-32 matches the entry name renamed the entry on read-back ("" -> "%$!"), so the
5805    /// writer's view of the archive no longer matched what `new_append` read.
5806    #[test]
5807    fn validate_extra_fields_rejects_renaming_unicode_path() -> ZipResult<()> {
5808        let mut options = FullFileOptions::default().validate_extra_fields(true);
5809        // version 50, CRC-32 of "" (0), content "%$!"
5810        options.add_extra_field(0x7075, [50, 0, 0, 0, 0, 37, 36, 33], true)?;
5811        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5812        assert!(writer.start_file("", options.clone()).is_err());
5813        // The CRC doesn't match "a", so a reader ignores the field.
5814        writer.start_file("a", options)?;
5815        // Content equal to the name is harmless.
5816        let mut same = FullFileOptions::default().validate_extra_fields(true);
5817        let mut data = vec![1];
5818        data.extend_from_slice(&crc32fast::hash(b"b").to_le_bytes());
5819        data.push(b'b');
5820        same.add_extra_field(0x7075, data, false)?;
5821        writer.start_file("b", same)?;
5822        let archive = ZipArchive::new(writer.finish()?)?;
5823        let names: Vec<_> = archive
5824            .file_names()
5825            .map(|n| n.unwrap().into_owned())
5826            .collect();
5827        assert_eq!(names, ["a", "b"]);
5828        Ok(())
5829    }
5830
5831    /// A malformed Info-ZIP Unicode Path field is written verbatim by default, as before, so
5832    /// nobody relying on that breaks; the archive then can't be read back. With
5833    /// `validate_extra_fields(true)` it's rejected before anything is written.
5834    #[test]
5835    fn validate_extra_fields_is_opt_in() -> ZipResult<()> {
5836        // 0x7075 needs at least a version byte and a CRC-32 (5 bytes).
5837        let mut options = FullFileOptions::default();
5838        options.add_extra_field(0x7075, [28], true)?;
5839        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5840        writer.start_file("a", options.clone())?;
5841        assert!(ZipArchive::new(writer.finish()?).is_err());
5842
5843        // Opted in: rejected by add_extra_field ...
5844        let mut validated = FullFileOptions::default().validate_extra_fields(true);
5845        assert!(validated.add_extra_field(0x7075, [28], true).is_err());
5846        assert!(validated.add_extra_field(0x7075, [28], false).is_err());
5847        // ... and by start_file, if it was added before opting in.
5848        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5849        assert!(
5850            writer
5851                .start_file("a", options.validate_extra_fields(true))
5852                .is_err()
5853        );
5854
5855        // A vendor ID the reader doesn't interpret is still stored verbatim.
5856        validated.add_extra_field(0xbeef, [28], false)?;
5857        // Extended timestamps use different parsing rules in local and central headers.
5858        validated.add_extra_field(0x5455, [1, 1, 0, 0, 0, 2, 0, 0, 0], true)?;
5859        assert!(
5860            validated
5861                .add_extra_field(0x5455, [1, 1, 0, 0, 0, 2, 0, 0, 0], false)
5862                .is_err()
5863        );
5864        writer.start_file("b", validated)?;
5865        let mut archive = ZipArchive::new(writer.finish()?)?;
5866        assert_eq!(archive.len(), 1);
5867        drop(archive.by_index(0)?);
5868        Ok(())
5869    }
5870
5871    /// `表示写真.txt` in Shift-JIS, as Japanese Windows tools store it: no
5872    /// language encoding flag, and not valid UTF-8, so [`ZipFile::name`] reads it
5873    /// as CP437.
5874    const SHIFT_JIS_NAME: &[u8] = b"\x95\x5c\x8e\xa6\x8e\xca\x90\x5e.txt";
5875
5876    /// One stored entry named `name_raw` with the language encoding flag clear,
5877    /// made by patching an ASCII placeholder of the same length in both headers.
5878    fn archive_with_unflagged_name(name_raw: &[u8]) -> ZipResult<ZipArchive<Cursor<Vec<u8>>>> {
5879        let placeholder = "x".repeat(name_raw.len());
5880        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5881        writer.start_file(
5882            &*placeholder,
5883            SimpleFileOptions::default().compression_method(Stored),
5884        )?;
5885        writer.write_all(b"data")?;
5886        let mut bytes = writer.finish()?.into_inner();
5887        let mut patched = 0;
5888        for start in 0..=bytes.len() - name_raw.len() {
5889            if &bytes[start..start + name_raw.len()] == placeholder.as_bytes() {
5890                bytes[start..start + name_raw.len()].copy_from_slice(name_raw);
5891                patched += 1;
5892            }
5893        }
5894        assert_eq!(
5895            patched, 2,
5896            "the name sits in the local header and the central directory"
5897        );
5898        ZipArchive::new(Cursor::new(bytes))
5899    }
5900
5901    fn copied(
5902        mut source: ZipArchive<Cursor<Vec<u8>>>,
5903        copy: impl FnOnce(
5904            &mut ZipWriter<Cursor<Vec<u8>>>,
5905            crate::read::ZipFile<'_, Cursor<Vec<u8>>>,
5906        ) -> ZipResult<()>,
5907    ) -> ZipResult<Vec<u8>> {
5908        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5909        copy(&mut writer, source.by_index_raw(0)?)?;
5910        Ok(writer.finish()?.into_inner())
5911    }
5912
5913    fn name_and_language_encoding(bytes: Vec<u8>) -> ZipResult<(Vec<u8>, bool)> {
5914        let mut archive = ZipArchive::new(Cursor::new(bytes))?;
5915        let file = archive.by_index_raw(0)?;
5916        let language_encoding = file
5917            .flags()
5918            .matching(crate::format::flags::ZipFlags::LanguageEncoding);
5919        Ok((file.name_raw().to_vec(), language_encoding))
5920    }
5921
5922    #[test]
5923    fn raw_copy_file_keeps_a_legacy_code_page_name_as_stored() -> ZipResult<()> {
5924        let bytes = copied(
5925            archive_with_unflagged_name(SHIFT_JIS_NAME)?,
5926            |writer, file| writer.raw_copy_file(file),
5927        )?;
5928        let in_both_headers = bytes
5929            .windows(SHIFT_JIS_NAME.len())
5930            .filter(|window| *window == SHIFT_JIS_NAME)
5931            .count();
5932        assert_eq!(in_both_headers, 2);
5933        assert_eq!(
5934            name_and_language_encoding(bytes)?,
5935            (SHIFT_JIS_NAME.to_vec(), false)
5936        );
5937        Ok(())
5938    }
5939
5940    #[test]
5941    fn raw_copy_file_keeps_an_unflagged_utf8_name_unflagged() -> ZipResult<()> {
5942        // Valid UTF-8 without the flag, as older Info-ZIP on Linux writes. A Shift-JIS
5943        // or GBK name can be valid UTF-8 by accident too, so the flag must not be guessed.
5944        let name = "café.txt".as_bytes();
5945        let bytes = copied(archive_with_unflagged_name(name)?, |writer, file| {
5946            writer.raw_copy_file(file)
5947        })?;
5948        assert_eq!(name_and_language_encoding(bytes)?, (name.to_vec(), false));
5949        Ok(())
5950    }
5951
5952    #[test]
5953    fn raw_copy_file_keeps_a_flagged_utf8_name_flagged() -> ZipResult<()> {
5954        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5955        writer.start_file(
5956            "café.txt",
5957            SimpleFileOptions::default().compression_method(Stored),
5958        )?;
5959        writer.write_all(b"data")?;
5960        let source = ZipArchive::new(Cursor::new(writer.finish()?.into_inner()))?;
5961        let bytes = copied(source, |writer, file| writer.raw_copy_file(file))?;
5962        assert_eq!(
5963            name_and_language_encoding(bytes)?,
5964            ("café.txt".as_bytes().to_vec(), true)
5965        );
5966        Ok(())
5967    }
5968
5969    #[test]
5970    fn raw_copy_file_rename_flags_a_new_utf8_name() -> ZipResult<()> {
5971        let bytes = copied(
5972            archive_with_unflagged_name(SHIFT_JIS_NAME)?,
5973            |writer, file| writer.raw_copy_file_rename(file, "写真.txt"),
5974        )?;
5975        assert_eq!(
5976            name_and_language_encoding(bytes)?,
5977            ("写真.txt".as_bytes().to_vec(), true)
5978        );
5979        Ok(())
5980    }
5981
5982    #[test]
5983    fn raw_copy_file_touch_keeps_the_name_as_stored() -> ZipResult<()> {
5984        let bytes = copied(
5985            archive_with_unflagged_name(SHIFT_JIS_NAME)?,
5986            |writer, file| writer.raw_copy_file_touch(file, DateTime::default(), None),
5987        )?;
5988        assert_eq!(
5989            name_and_language_encoding(bytes)?,
5990            (SHIFT_JIS_NAME.to_vec(), false)
5991        );
5992        Ok(())
5993    }
5994
5995    #[test]
5996    fn a_copy_under_a_new_name_takes_that_names_language_encoding() -> ZipResult<()> {
5997        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
5998        writer.start_file(
5999            "plain.txt",
6000            SimpleFileOptions::default().compression_method(Stored),
6001        )?;
6002        writer.write_all(b"data")?;
6003        writer.deep_copy_file("plain.txt", "déjà.txt")?;
6004        writer.shallow_copy_file("plain.txt", "voilà.txt")?;
6005        writer.start_file(
6006            "café.txt",
6007            SimpleFileOptions::default().compression_method(Stored),
6008        )?;
6009        writer.write_all(b"data")?;
6010        writer.deep_copy_file("café.txt", "cafe.txt")?;
6011        let mut archive = ZipArchive::new(Cursor::new(writer.finish()?.into_inner()))?;
6012        for (name, language_encoding) in [
6013            ("plain.txt", false),
6014            ("déjà.txt", true),
6015            ("voilà.txt", true),
6016            ("café.txt", true),
6017            ("cafe.txt", false),
6018        ] {
6019            let file = archive.by_name(name)?;
6020            let flagged = file
6021                .flags()
6022                .matching(crate::format::flags::ZipFlags::LanguageEncoding);
6023            assert_eq!(flagged, language_encoding, "{name}");
6024        }
6025        Ok(())
6026    }
6027
6028    fn decrypted(bytes: Vec<u8>, password: &[u8]) -> ZipResult<Vec<u8>> {
6029        use std::io::Read;
6030        let mut archive = ZipArchive::new(Cursor::new(bytes))?;
6031        let mut file = archive.by_index_decrypt(0, password)?;
6032        let mut contents = Vec::new();
6033        file.read_to_end(&mut contents)?;
6034        Ok(contents)
6035    }
6036
6037    #[test]
6038    fn raw_copy_file_keeps_a_zipcrypto_entry_decryptable() -> ZipResult<()> {
6039        // The writer gives ZipCrypto a data descriptor and checks the password
6040        // against the DOS time's high byte, the shape Info-ZIP's `zip -e` writes.
6041        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
6042        let options = SimpleFileOptions::default()
6043            .compression_method(Stored)
6044            .last_modified_time(DateTime::from_date_and_time(2024, 5, 6, 13, 26, 52)?)
6045            .with_deprecated_encryption(b"Password");
6046        writer.start_file("secret.txt", options)?;
6047        writer.write_all(b"secret contents")?;
6048        let source = ZipArchive::new(Cursor::new(writer.finish()?.into_inner()))?;
6049        for rename in [false, true] {
6050            let bytes = copied(source.clone(), |writer, file| {
6051                if rename {
6052                    writer.raw_copy_file_rename(file, "moved.txt")
6053                } else {
6054                    writer.raw_copy_file(file)
6055                }
6056            })?;
6057            let mut archive = ZipArchive::new(Cursor::new(bytes.clone()))?;
6058            let flags = archive.by_index_raw(0)?.flags();
6059            assert!(flags.is_encrypted(), "rename: {rename}");
6060            assert!(flags.is_using_data_descriptor(), "rename: {rename}");
6061            assert_eq!(
6062                decrypted(bytes, b"Password")?,
6063                b"secret contents",
6064                "rename: {rename}"
6065            );
6066        }
6067        Ok(())
6068    }
6069
6070    /// `写真` in Shift-JIS, as Japanese Windows tools store it: no language
6071    /// encoding flag, so [`ZipFile::comment`] reads it as CP437.
6072    const SHIFT_JIS_COMMENT: &[u8] = b"\x8e\xca\x90\x5e";
6073
6074    /// The mojibake [`ZipFile::comment`] returns for [`SHIFT_JIS_COMMENT`]: the Shift-JIS
6075    /// bytes `8E CA 90 5E` reinterpreted as CP437 (`Ä`, `╩`, `É`, `^`), then converted to
6076    /// UTF-8. A copy under a new name stores these UTF-8 bytes, under the language encoding flag.
6077    const MOJIBAKE_COMMENT: &str = "Ä╩É^";
6078
6079    /// One stored entry named `a.txt` whose comment is `comment_raw` with the
6080    /// language encoding flag clear, made by patching an ASCII placeholder.
6081    fn archive_with_unflagged_comment(
6082        comment_raw: &[u8],
6083    ) -> ZipResult<ZipArchive<Cursor<Vec<u8>>>> {
6084        let placeholder = "x".repeat(comment_raw.len());
6085        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
6086        writer.start_file(
6087            "a.txt",
6088            FullFileOptions::default()
6089                .compression_method(Stored)
6090                .with_file_comment(&*placeholder),
6091        )?;
6092        writer.write_all(b"data")?;
6093        let mut bytes = writer.finish()?.into_inner();
6094        let start = bytes
6095            .windows(comment_raw.len())
6096            .position(|window| window == placeholder.as_bytes())
6097            .expect("the comment sits in the central directory");
6098        bytes[start..start + comment_raw.len()].copy_from_slice(comment_raw);
6099        ZipArchive::new(Cursor::new(bytes))
6100    }
6101
6102    fn comment_raw_and_language_encoding(bytes: Vec<u8>) -> ZipResult<(Vec<u8>, bool)> {
6103        let mut archive = ZipArchive::new(Cursor::new(bytes))?;
6104        let file = archive.by_index_raw(0)?;
6105        let language_encoding = file
6106            .flags()
6107            .matching(crate::format::flags::ZipFlags::LanguageEncoding);
6108        Ok((file.comment_raw().to_vec(), language_encoding))
6109    }
6110
6111    #[test]
6112    fn comment_raw_is_the_comment_as_stored() -> ZipResult<()> {
6113        let mut archive = archive_with_unflagged_comment(SHIFT_JIS_COMMENT)?;
6114        let file = archive.by_index_raw(0)?;
6115        assert_eq!(file.comment(), MOJIBAKE_COMMENT);
6116        assert_eq!(file.comment_raw(), SHIFT_JIS_COMMENT);
6117        drop(file);
6118
6119        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
6120        writer.start_file(
6121            "a.txt",
6122            FullFileOptions::default()
6123                .compression_method(Stored)
6124                .with_file_comment("写真"),
6125        )?;
6126        let mut archive = ZipArchive::new(writer.finish()?)?;
6127        assert_eq!(archive.by_index_raw(0)?.comment_raw(), "写真".as_bytes());
6128        Ok(())
6129    }
6130
6131    #[test]
6132    fn raw_copy_file_keeps_a_legacy_code_page_comment_as_stored() -> ZipResult<()> {
6133        let bytes = copied(
6134            archive_with_unflagged_comment(SHIFT_JIS_COMMENT)?,
6135            |writer, file| writer.raw_copy_file(file),
6136        )?;
6137        assert_eq!(
6138            comment_raw_and_language_encoding(bytes)?,
6139            (SHIFT_JIS_COMMENT.to_vec(), false)
6140        );
6141        Ok(())
6142    }
6143
6144    #[test]
6145    fn raw_copy_file_touch_keeps_the_comment_as_stored() -> ZipResult<()> {
6146        let bytes = copied(
6147            archive_with_unflagged_comment(SHIFT_JIS_COMMENT)?,
6148            |writer, file| writer.raw_copy_file_touch(file, DateTime::default(), None),
6149        )?;
6150        assert_eq!(
6151            comment_raw_and_language_encoding(bytes)?,
6152            (SHIFT_JIS_COMMENT.to_vec(), false)
6153        );
6154        Ok(())
6155    }
6156
6157    #[test]
6158    fn raw_copy_file_rename_writes_the_comment_as_utf8() -> ZipResult<()> {
6159        let bytes = copied(
6160            archive_with_unflagged_comment(SHIFT_JIS_COMMENT)?,
6161            |writer, file| writer.raw_copy_file_rename(file, "b.txt"),
6162        )?;
6163        assert_eq!(
6164            comment_raw_and_language_encoding(bytes)?,
6165            (MOJIBAKE_COMMENT.as_bytes().to_vec(), true)
6166        );
6167        Ok(())
6168    }
6169
6170    #[test]
6171    fn new_append_keeps_a_legacy_code_page_comment_as_stored() -> ZipResult<()> {
6172        let source = archive_with_unflagged_comment(SHIFT_JIS_COMMENT)?;
6173        let mut writer = ZipWriter::new_append(source.into_inner())?;
6174        writer.deep_copy_file("a.txt", "b.txt")?;
6175        let mut archive = ZipArchive::new(writer.finish()?)?;
6176        let file = archive.by_name("a.txt")?;
6177        assert_eq!(file.comment_raw(), SHIFT_JIS_COMMENT);
6178        assert!(
6179            !file
6180                .flags()
6181                .matching(crate::format::flags::ZipFlags::LanguageEncoding)
6182        );
6183        drop(file);
6184        // A copy under a new name writes its comment as UTF-8, like its name.
6185        let file = archive.by_name("b.txt")?;
6186        assert_eq!(file.comment_raw(), MOJIBAKE_COMMENT.as_bytes());
6187        assert!(
6188            file.flags()
6189                .matching(crate::format::flags::ZipFlags::LanguageEncoding)
6190        );
6191        Ok(())
6192    }
6193
6194    #[test]
6195    fn test_try_from_zip_file_builder() -> ZipResult<()> {
6196        use super::{PreparedZipFile, ZipFileBuilder};
6197
6198        let mut builder = ZipFileBuilder::new(
6199            "test_try_from.txt",
6200            SimpleFileOptions::default().compression_method(Stored),
6201        )?;
6202        builder.write_all(b"Hello TryFrom")?;
6203
6204        let prepared: PreparedZipFile = builder.try_into()?;
6205        assert_eq!(prepared.file_name_raw(), b"test_try_from.txt");
6206        assert_eq!(prepared.uncompressed_size(), 13);
6207        assert_eq!(prepared.compressed_size(), 13);
6208
6209        let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
6210        writer.add_prepared_file(prepared)?;
6211        let mut archive = ZipArchive::new(Cursor::new(writer.finish()?.into_inner()))?;
6212        let mut file = archive.by_name("test_try_from.txt")?;
6213        let mut content = Vec::new();
6214        std::io::Read::read_to_end(&mut file, &mut content)?;
6215        assert_eq!(content, b"Hello TryFrom");
6216        Ok(())
6217    }
6218}