zip 9.0.4

Library to support the reading and writing of zip files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Code related to zipfile

use crate::CompressionMethod;
use crate::DateTime;
use crate::HasZipMetadata;
use crate::ZIP64_BYTES_THR;
use crate::ZipReadOptions;
use crate::format::data_descriptor::ZipDataDescriptor;
use crate::format::ffi;
use crate::format::flags::ZipFileFlags;
use crate::format::system::System;
use crate::read::ExtraField;
use crate::read::extract::RootDirFilter;
use crate::read::readers::{ZipFileReader, ZipFileSeekReader};
use crate::result::ZipResult;
use crate::result::invalid;
use crate::types::ZipFileData;
use crate::write::options::SimpleFileOptions;

use core::mem::replace;
use std::borrow::Cow;
use std::ffi::OsStr;
use std::io::{self, Cursor, Read, Seek, SeekFrom, copy, sink};
use std::path::{Path, PathBuf};

/// A struct for reading a zip file
///
/// When reading from a `ZipFile` using [`Self::read()`], keep in mind that `read()` **does not guarantee** the buffer will be fully filled in a single call.
///
/// If your logic depends on the buffer being completely populated, use [`Self::read_exact()`] instead. It will continue reading until the entire buffer is filled or an error occurs.
#[derive(Debug)]
pub struct ZipFile<'a, R: Read + ?Sized> {
    pub(crate) file_name_raw: Cow<'a, [u8]>,
    pub(crate) data: Cow<'a, ZipFileData>,
    pub(crate) reader: ZipFileReader<'a, R>,
}

/// A zip file Entry with a data descriptor (if present).
///
/// The method [`Self::data_descriptor`] can be use to retrieve it
#[derive(Debug)]
pub struct ZipFileEntryWithDataDescriptor<'a> {
    pub(crate) file_name_raw: Cow<'a, [u8]>,
    pub(crate) data: Cow<'a, ZipFileData>,
    pub(crate) data_descriptor: Option<ZipDataDescriptor>,
}

/// A struct for reading a zip file, without a reader
#[derive(Debug)]
pub struct ZipFileEntry<'a> {
    pub(crate) file_name_raw: Cow<'a, [u8]>,
    pub(crate) data: Cow<'a, ZipFileData>,
}

/// A struct for reading and seeking a zip file
pub struct ZipFileSeek<'a, R> {
    pub(crate) file_name_raw: Cow<'a, [u8]>,
    pub(crate) data: Cow<'a, ZipFileData>,
    pub(crate) reader: ZipFileSeekReader<'a, R>,
}

macro_rules! zip_file_methods {
    () => {
        /// Get the name of the file, in the raw (internal) byte representation.
        ///
        /// The encoding of this data is currently undefined.
        pub fn name_raw(&self) -> &[u8] {
            &self.file_name_raw
        }

        /// Get the name of the file
        ///
        /// # Warnings
        ///
        /// It is dangerous to use this name directly when extracting an archive.
        /// It may contain an absolute path (`/etc/shadow`), or break out of the
        /// current directory (`../runtime`). Carelessly writing to these paths
        /// allows an attacker to craft a ZIP archive that will overwrite critical
        /// files.
        ///
        /// You can use the [`ZipFile::enclosed_name`] method to validate the name
        /// as a safe path.
        pub fn name(&self) -> ZipResult<Cow<'_, str>> {
            self.get_metadata().name(&self.file_name_raw)
        }

        /// Rewrite the path, ignoring any path components with special meaning.
        ///
        /// - Absolute paths are made relative
        /// - [`ParentDir`]s are ignored
        /// - Truncates the filename at a NULL byte
        ///
        /// This is appropriate if you need to be able to extract *something* from
        /// any archive, but will easily misrepresent trivial paths like
        /// `foo/../bar` as `foo/bar` (instead of `bar`). Because of this,
        /// [`ZipFile::enclosed_name`] is the better option in most scenarios.
        ///
        /// [`ParentDir`]: `std::path::Component::ParentDir`
        pub fn mangled_name(&self) -> ZipResult<PathBuf> {
            let file_name = self.name()?;
            let sanitized = self.get_metadata().file_name_sanitized(&file_name);
            Ok(sanitized)
        }

        /// Ensure the file path is safe to use as a [`Path`].
        ///
        /// - It can't contain NULL bytes
        /// - It can't resolve to a path outside the current directory
        ///   > `foo/../bar` is fine, `foo/../../bar` is not.
        /// - It can't be an absolute path
        ///
        /// This will read well-formed ZIP files correctly, and is resistant
        /// to path-based exploits. It is recommended over
        /// [`ZipFile::mangled_name`].
        pub fn enclosed_name(&self) -> Option<PathBuf> {
            self.get_metadata().enclosed_name(&self.name().ok()?)
        }

        /// Get the starting offset of the zip header for this file
        pub fn header_start(&self) -> u64 {
            self.get_metadata().header_start
        }
        /// Get the starting offset of the zip header in the central directory for this file
        pub fn central_header_start(&self) -> u64 {
            self.get_metadata().central_header_start
        }

        /// Get the version of the file
        pub fn version_made_by(&self) -> (u8, u8) {
            (
                self.get_metadata().version_made_by / 10,
                self.get_metadata().version_made_by % 10,
            )
        }

        /// PKZIP version needed to open this file (from APPNOTE 4.4.3.2).
        pub fn version_needed(&self) -> u16 {
            self.get_metadata().version_needed()
        }

        /// Get the comment of the file
        pub fn comment(&self) -> &str {
            &self.get_metadata().file_comment
        }

        /// Get the system of the file
        pub fn system(&self) -> System {
            self.get_metadata().system
        }

        /// Get the external attributes of the file
        pub fn external_attributes(&self) -> u32 {
            self.get_metadata().external_attributes
        }

        /// Get the flags of the file
        pub fn flags(&self) -> ZipFileFlags {
            self.get_metadata().flags
        }

        /// Get the compression method used to store the file
        pub fn compression(&self) -> CompressionMethod {
            self.get_metadata().compression_method
        }

        /// Get if the files is encrypted or not
        pub fn encrypted(&self) -> bool {
            self.data.is_encrypted()
        }

        /// Get the size of the file, in bytes, in the archive
        pub fn compressed_size(&self) -> u64 {
            self.get_metadata().compressed_size
        }

        /// Get the size of the file, in bytes, when uncompressed
        pub fn size(&self) -> u64 {
            self.get_metadata().uncompressed_size
        }

        /// Get the time the file was last modified
        pub fn last_modified(&self) -> Option<DateTime> {
            self.get_metadata().last_modified_time
        }
        /// Returns whether the file is actually a directory
        pub fn is_dir(&self) -> bool {
            self.get_metadata().is_dir(&self.file_name_raw)
        }

        /// Returns whether the file is actually a symbolic link
        pub fn is_symlink(&self) -> bool {
            self.unix_mode()
                .is_some_and(|mode| mode & ffi::S_IFLNK == ffi::S_IFLNK)
        }

        /// Returns whether the file is a normal file (i.e. not a directory or symlink)
        pub fn is_file(&self) -> bool {
            !self.is_dir() && !self.is_symlink()
        }

        /// Returns whether the file is read-only. (On Unix, this means it's not readable by
        /// *anyone*.)
        pub fn is_read_only(&self) -> bool {
            self.unix_mode().is_some_and(|mode| mode & 0o222 == 0)
        }

        /// Get unix mode for the file
        pub fn unix_mode(&self) -> Option<u32> {
            self.get_metadata().unix_mode()
        }

        /// Get the CRC32 hash of the original file
        pub fn crc32(&self) -> u32 {
            self.get_metadata().crc32
        }
    };
}
impl<'a> ZipFileEntryWithDataDescriptor<'a> {
    zip_file_methods!();

    /// Get the data descriptor
    pub fn data_descriptor(&self) -> &Option<ZipDataDescriptor> {
        &self.data_descriptor
    }
}

impl HasZipMetadata for ZipFileEntryWithDataDescriptor<'_> {
    fn get_metadata(&self) -> &ZipFileData {
        self.data.as_ref()
    }
}

impl<'a> ZipFileEntry<'a> {
    zip_file_methods!();

    /// Create a readable
    pub fn with_reader<R: Read + Seek>(
        self,
        reader: &'a mut R,
        options: ZipReadOptions<'_>,
    ) -> ZipResult<ZipFile<'a, R>> {
        let limit_reader = self.data.find_content(reader)?;

        let reader = self.data.make_reader(limit_reader, options)?;
        Ok(ZipFile {
            file_name_raw: self.file_name_raw,
            data: self.data,
            reader,
        })
    }
}

impl HasZipMetadata for ZipFileEntry<'_> {
    fn get_metadata(&self) -> &ZipFileData {
        self.data.as_ref()
    }
}

/// Methods for retrieving information on zip files
impl<'a, R: Read + ?Sized> ZipFile<'a, R> {
    zip_file_methods!();

    pub(crate) fn take_raw_reader(&mut self) -> io::Result<io::Take<&'a mut R>> {
        replace(&mut self.reader, ZipFileReader::NoReader).into_inner()
    }

    /// Prepare the path for extraction by creating necessary missing directories and checking for symlinks to be contained within the base path.
    ///
    /// `base_path` parameter is assumed to be canonicalized.
    pub(crate) fn safe_prepare_path(
        &self,
        base_path: &Path,
        outpath: &mut PathBuf,
        root_dir: Option<&(Vec<&OsStr>, impl RootDirFilter)>,
    ) -> ZipResult<()> {
        let file_name = self.name()?;
        let components = self
            .data
            .simplified_components(&file_name)
            .ok_or(invalid!("Invalid file path"))?;

        let components = match root_dir {
            Some((root_dir, filter)) => match components.strip_prefix(&**root_dir) {
                Some(components) => components,

                // In this case, we expect that the file was not in the root
                // directory, but was filtered out when searching for the
                // root directory.
                None => {
                    // We could technically find ourselves at this code
                    // path if the user provides an unstable or
                    // non-deterministic `filter` function.
                    //
                    // If debug assertions are on, we should panic here.
                    // Otherwise, the safest thing to do here is to just
                    // extract as-is.
                    debug_assert!(
                        !filter(&PathBuf::from_iter(components.iter())),
                        "Root directory filter should not match at this point"
                    );

                    // Extract as-is.
                    &components[..]
                }
            },

            None => &components[..],
        };

        *outpath = crate::path::resolve_enclosed(
            base_path,
            base_path,
            components.iter().map(|c| c.to_os_string()),
            true, // create intermediate directories
        )?;

        Ok(())
    }

    /// Get the extra data of the zip header for this file
    pub fn extra_data(&self) -> Option<Vec<u8>> {
        let out_buffer = Vec::new();
        let mut cursor = Cursor::new(out_buffer);
        let extra_fields = self.data.extra_fields.local_extra_fields();
        for one_extra_field in extra_fields {
            one_extra_field.write(&mut cursor, true).ok()?;
        }
        let extra_fields_data = cursor.into_inner();
        if extra_fields_data.is_empty() {
            None
        } else {
            Some(extra_fields_data)
        }
    }

    /// Get the starting offset of the data of the compressed file
    pub fn data_start(&self) -> Option<u64> {
        self.data.data_start.get().copied()
    }

    /// Get the [`SimpleFileOptions`] that would be used to write this file to
    /// a new zip archive.
    pub fn options(&self) -> SimpleFileOptions {
        let mut options = SimpleFileOptions::default()
            .large_file(self.compressed_size().max(self.size()) >= ZIP64_BYTES_THR)
            .compression_method(self.compression())
            .system(self.system())
            .external_attributes(self.external_attributes())
            .last_modified_time(
                self.last_modified()
                    .filter(DateTime::is_valid)
                    .unwrap_or_else(DateTime::default_for_write),
            );

        options.normalize();
        #[cfg(feature = "aes-crypto")]
        if let Some((mode, vendor_version)) = self.get_metadata().aes_settings() {
            use crate::write::options::EncryptWith;
            // Preserve AES metadata in options for downstream writers.
            // This is metadata-only and does not trigger encryption.
            options.encrypt_with = Some(EncryptWith::Aes {
                mode,
                vendor_version,
                salt: None,
                password: None,
            });
        }
        options
    }
}

/// Methods for retrieving information on zip files
impl<R: Read> ZipFile<'_, R> {
    /// iterate through all extra fields
    pub fn extra_data_fields(&self) -> impl Iterator<Item = &ExtraField> {
        self.data.extra_fields.inner.iter()
    }
}

impl<R: Read + ?Sized> HasZipMetadata for ZipFile<'_, R> {
    fn get_metadata(&self) -> &ZipFileData {
        self.data.as_ref()
    }
}

impl<R: Read + ?Sized> Read for ZipFile<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }

    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        self.reader.read_to_end(buf)
    }

    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
        self.reader.read_to_string(buf)
    }

    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        self.reader.read_exact(buf)
    }
}

impl<R: Read> Read for ZipFileSeek<'_, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match &mut self.reader {
            ZipFileSeekReader::Raw(r) => r.read(buf),
        }
    }
}

impl<R: Seek> Seek for ZipFileSeek<'_, R> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        match &mut self.reader {
            ZipFileSeekReader::Raw(r) => r.seek(pos),
        }
    }
}

impl<R> HasZipMetadata for ZipFileSeek<'_, R> {
    fn get_metadata(&self) -> &ZipFileData {
        self.data.as_ref()
    }
}

impl<'a, R> ZipFileSeek<'a, R> {
    zip_file_methods!();
}

impl<R: Read + ?Sized> Drop for ZipFile<'_, R> {
    fn drop(&mut self) {
        // self.data is Owned, this reader is constructed by a streaming reader.
        // In this case, we want to exhaust the reader so that the next file is accessible.
        if let Cow::Owned(_) = self.data {
            // Get the inner `Take` reader so all decryption, decompression and CRC calculation is skipped.
            if let Ok(mut inner) = self.take_raw_reader() {
                let _ = copy(&mut inner, &mut sink());
            }
        }
    }
}