Skip to main content

zip/
types.rs

1//! Types that specify what is contained in a ZIP.
2
3use crate::CompressionMethod;
4use crate::cp437::FromCp437;
5use crate::datetime::DateTime;
6use crate::extra_fields::ExtraField;
7use crate::path::{enclosed_name, file_name_sanitized};
8use crate::read::readers::SeekableTake;
9use crate::result::{ZipError, ZipResult, invalid};
10use crate::spec::is_dir;
11use crate::spec::{
12    self, FixedSizeBlock, Magic, Zip64DataDescriptorBlock, ZipCentralEntryBlock,
13    ZipDataDescriptorBlock, ZipFlags, ZipLocalEntryBlock,
14};
15use crate::write::FileOptionExtension;
16use crate::zipcrypto::EncryptWith;
17use core::fmt::Debug;
18use core::fmt::Display;
19use std::ffi::OsStr;
20use std::io::{Read, Seek, SeekFrom, Take};
21use std::path::{Path, PathBuf};
22use std::sync::{Arc, OnceLock};
23
24pub(crate) mod ffi {
25    pub const S_IFDIR: u32 = 0o0_040_000;
26    pub const S_IFREG: u32 = 0o0_100_000;
27    pub const S_IFLNK: u32 = 0o0_120_000;
28}
29
30pub(crate) struct ZipRawValues {
31    pub(crate) crc32: u32,
32    pub(crate) compressed_size: u64,
33    pub(crate) uncompressed_size: u64,
34}
35
36/// System inside `version made by` (upper byte)
37/// Reference: 4.4.2.2
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
39#[allow(clippy::upper_case_acronyms)]
40#[repr(u8)]
41pub enum System {
42    /// `MS-DOS` and `OS/2` (`FAT` / `VFAT` / `FAT32` file systems; default on Windows)
43    Dos = 0,
44    /// `Amiga`
45    Amiga = 1,
46    /// `OpenVMS`
47    OpenVMS = 2,
48    /// Default on Unix; default for symlinks on all platforms
49    Unix = 3,
50    /// `VM/CMS`
51    VmCms = 4,
52    /// `Atari ST`
53    AtariSt = 5,
54    /// `OS/2 H.P.F.S.`
55    Os2 = 6,
56    /// Legacy `Mac OS`, pre `OS X`
57    Macintosh = 7,
58    /// `Z-System`
59    ZSystemO = 8,
60    /// `CP/M`
61    CPM = 9,
62    /// Windows NTFS (with extra attributes; not used by default)
63    WindowsNTFS = 10,
64    /// `MVS (OS/390 - Z/OS)`
65    MVS = 11,
66    /// `VSE`
67    VSE = 12,
68    /// `Acorn Risc`
69    AcornRisc = 13,
70    /// `VFAT`
71    VFAT = 14,
72    /// alternate MVS
73    AlternateMVS = 15,
74    /// `BeOS`
75    BeOS = 16,
76    /// `Tandem`
77    Tandem = 17,
78    /// `OS/400`
79    Os400 = 18,
80    /// `OS X` (Darwin) (with extra attributes; not used by default)
81    OsDarwin = 19,
82    /// unused
83    #[default]
84    Unknown = 255,
85}
86
87impl System {
88    /// Parse `version_made_by` block in local entry block.
89    #[must_use]
90    pub fn from_version_made_by(version_made_by: u16) -> Self {
91        // Extract upper byte from little-endian representation
92        let upper_byte = version_made_by.to_le_bytes()[1];
93        System::from(upper_byte) // from u8
94    }
95
96    /// Extract the system and version from a `version_made_by` field.
97    /// The first byte (lower) is the version, and the second byte (upper) is the system.
98    pub(crate) fn extract_bytes(version_made_by: u16) -> (u8, Self) {
99        let bytes = version_made_by.to_le_bytes();
100        (bytes[0], Self::from(bytes[1]))
101    }
102}
103
104impl From<u8> for System {
105    fn from(system: u8) -> Self {
106        match system {
107            0 => System::Dos,
108            1 => System::Amiga,
109            2 => System::OpenVMS,
110            3 => System::Unix,
111            4 => System::VmCms,
112            5 => System::AtariSt,
113            6 => System::Os2,
114            7 => System::Macintosh,
115            8 => System::ZSystemO,
116            9 => System::CPM,
117            10 => System::WindowsNTFS,
118            11 => System::MVS,
119            12 => System::VSE,
120            13 => System::AcornRisc,
121            14 => System::VFAT,
122            15 => System::AlternateMVS,
123            16 => System::BeOS,
124            17 => System::Tandem,
125            18 => System::Os400,
126            19 => System::OsDarwin,
127            _ => System::Unknown,
128        }
129    }
130}
131
132impl From<System> for u8 {
133    fn from(system: System) -> Self {
134        system as u8
135    }
136}
137
138/// Metadata for a file to be written
139#[non_exhaustive]
140#[derive(Clone, Debug, Copy, Eq, PartialEq)]
141pub struct FileOptions<'k, T: FileOptionExtension> {
142    pub(crate) compression_method: CompressionMethod,
143    pub(crate) compression_level: Option<i64>,
144    pub(crate) last_modified_time: DateTime,
145    pub(crate) permissions: Option<u32>,
146    pub(crate) large_file: bool,
147    pub(crate) encrypt_with: Option<EncryptWith<'k>>,
148    pub(crate) extended_options: T,
149    pub(crate) alignment: u16,
150    #[cfg(feature = "deflate-zopfli")]
151    pub(super) zopfli_buffer_size: Option<usize>,
152    #[cfg(feature = "aes-crypto")]
153    pub(crate) aes_mode: Option<crate::aes::AesModeOptions>,
154    pub(crate) system: Option<System>,
155}
156/// Simple File Options. Can be copied and good for simple writing zip files
157pub type SimpleFileOptions = FileOptions<'static, ()>;
158
159impl FileOptions<'static, ()> {
160    const DEFAULT_FILE_PERMISSION: u32 = 0o100_644;
161}
162
163pub const MIN_VERSION: u8 = 10;
164pub const DEFAULT_VERSION: u8 = 45;
165
166/// Structure representing a ZIP file.
167#[derive(Debug, Clone, Default)]
168pub struct ZipFileData {
169    /// Compatibility of the file attribute information
170    pub system: System,
171    /// Specification version
172    pub version_made_by: u8,
173    /// ZIP flags
174    pub flags: u16,
175    /// True if the file is encrypted.
176    pub encrypted: bool,
177    /// True if `file_name` and `file_comment` are UTF8
178    pub is_utf8: bool,
179    /// True if the file uses a data-descriptor section
180    pub using_data_descriptor: bool,
181    /// Compression method used to store the file
182    pub compression_method: crate::compression::CompressionMethod,
183    /// Compression level to store the file
184    pub compression_level: Option<i64>,
185    /// Last modified time. This will only have a 2 second precision.
186    pub last_modified_time: Option<DateTime>,
187    /// CRC32 checksum
188    pub crc32: u32,
189    /// Size of the file in the ZIP
190    pub compressed_size: u64,
191    /// Size of the file when extracted
192    pub uncompressed_size: u64,
193    /// Name of the file
194    pub file_name: Box<str>,
195    /// Raw file name. To be used when `file_name` was incorrectly decoded.
196    pub file_name_raw: Box<[u8]>,
197    /// Extra field usually used for storage expansion
198    pub extra_field: Option<Arc<[u8]>>,
199    /// Extra field only written to central directory
200    pub central_extra_field: Option<Arc<[u8]>>,
201    /// File comment
202    pub file_comment: Box<str>,
203    /// Specifies where the local header of the file starts
204    pub header_start: u64,
205    /// Specifies where the extra data of the file starts
206    pub extra_data_start: Option<u64>,
207    /// Specifies where the central header of the file starts
208    ///
209    /// Note that when this is not known, it is set to 0
210    pub central_header_start: u64,
211    /// Specifies where the compressed data of the file starts
212    pub data_start: OnceLock<u64>,
213    /// External file attributes
214    pub external_attributes: u32,
215    /// Reserve local ZIP64 extra field
216    pub large_file: bool,
217    /// AES mode if applicable
218    pub aes_mode: Option<(AesMode, AesVendorVersion, CompressionMethod)>,
219    /// Specifies where in the extra data the AES metadata starts
220    pub aes_extra_data_start: u64,
221
222    /// extra fields, see <https://libzip.org/specifications/extrafld.txt>
223    pub extra_fields: Vec<ExtraField>,
224}
225
226impl ZipFileData {
227    /// Get the starting offset of the data of the compressed file
228    pub fn data_start(&self, reader: &mut (impl Read + Seek + ?Sized)) -> ZipResult<u64> {
229        match self.data_start.get() {
230            Some(data_start) => Ok(*data_start),
231            None => Ok(self.find_data_start(reader)?),
232        }
233    }
234
235    pub(crate) fn find_data_start(
236        &self,
237        reader: &mut (impl Read + Seek + ?Sized),
238    ) -> Result<u64, ZipError> {
239        // Go to start of data.
240        reader.seek(SeekFrom::Start(self.header_start))?;
241
242        // Parse static-sized fields and check the magic value.
243        let block = ZipLocalEntryBlock::parse(reader)?;
244
245        // Calculate the end of the local header from the fields we just parsed.
246        let variable_fields_len =
247        // Each of these fields must be converted to u64 before adding, as the result may
248        // easily overflow a u16.
249        u64::from(block.file_name_length) + u64::from(block.extra_field_length);
250        let data_start = self.header_start
251            + (size_of::<Magic>() + size_of::<ZipLocalEntryBlock>()) as u64
252            + variable_fields_len;
253
254        // Set the value so we don't have to read it again.
255        match self.data_start.set(data_start) {
256            Ok(()) => (),
257            // If the value was already set in the meantime, ensure it matches (this is probably
258            // unnecessary).
259            Err(existing_value) => {
260                debug_assert_eq!(existing_value, data_start);
261            }
262        }
263
264        Ok(data_start)
265    }
266
267    pub(crate) fn find_content<'a, R: Read + Seek + ?Sized>(
268        &self,
269        reader: &'a mut R,
270    ) -> ZipResult<Take<&'a mut R>> {
271        // TODO: use .get_or_try_init() once stabilized to provide a closure returning a Result!
272        let data_start = self.data_start(reader)?;
273        reader.seek(SeekFrom::Start(data_start))?;
274
275        Ok(reader.take(self.compressed_size))
276    }
277
278    pub(crate) fn find_content_seek<'a, R: Read + Seek + ?Sized>(
279        &self,
280        reader: &'a mut R,
281    ) -> ZipResult<SeekableTake<'a, R>> {
282        // Parse local header
283        let data_start = self.data_start(reader)?;
284        reader.seek(SeekFrom::Start(data_start))?;
285
286        // Explicit Ok and ? are needed to convert io::Error to ZipError
287        Ok(SeekableTake::new(reader, self.compressed_size)?)
288    }
289
290    pub fn is_dir(&self) -> bool {
291        is_dir(&self.file_name)
292    }
293
294    pub fn file_name_sanitized(&self) -> PathBuf {
295        let no_null_filename = match self.file_name.find('\0') {
296            Some(index) => &self.file_name[0..index],
297            None => &self.file_name,
298        };
299
300        file_name_sanitized(no_null_filename)
301    }
302
303    /// Simplify the file name by removing the prefix and parent directories and only return normal components
304    pub(crate) fn simplified_components(&self) -> Option<Vec<&OsStr>> {
305        if self.file_name.contains('\0') {
306            return None;
307        }
308        let input = Path::new(OsStr::new(&*self.file_name));
309        crate::path::simplified_components(input)
310    }
311
312    pub(crate) fn enclosed_name(&self) -> Option<PathBuf> {
313        if self.file_name.contains('\0') {
314            return None;
315        }
316        enclosed_name(&self.file_name)
317    }
318
319    /// Get unix mode for the file
320    pub(crate) const fn unix_mode(&self) -> Option<u32> {
321        if self.external_attributes == 0 {
322            return None;
323        }
324        let unix_mode = self.external_attributes >> 16;
325        if unix_mode != 0 {
326            // If the high 16 bits are non-zero, they probably contain Unix permissions.
327            // This happens for archives created on Windows by this crate or other tools,
328            // and is the only way to identify symlinks in such archives.
329            return Some(unix_mode);
330        }
331        match self.system {
332            System::Unix => Some(unix_mode),
333            System::Dos => {
334                // Interpret MS-DOS directory bit
335                let mut mode = if 0x10 == (self.external_attributes & 0x10) {
336                    ffi::S_IFDIR | 0o0775
337                } else {
338                    ffi::S_IFREG | 0o0664
339                };
340                if 0x01 == (self.external_attributes & 0x01) {
341                    // Read-only bit; strip write permissions
342                    mode &= !0o222;
343                }
344                Some(mode)
345            }
346            _ => None,
347        }
348    }
349
350    /// PKZIP version needed to open this file (from APPNOTE 4.4.3.2).
351    pub fn version_needed(&self) -> u16 {
352        let compression_version: u16 = match self.compression_method {
353            CompressionMethod::Stored => MIN_VERSION.into(),
354            #[cfg(feature = "_deflate-any")]
355            CompressionMethod::Deflated => 20,
356            #[cfg(feature = "_bzip2_any")]
357            CompressionMethod::Bzip2 => 46,
358            #[cfg(feature = "deflate64")]
359            CompressionMethod::Deflate64 => 21,
360            #[cfg(feature = "lzma")]
361            CompressionMethod::Lzma => 63,
362            #[cfg(feature = "xz")]
363            CompressionMethod::Xz => 63,
364            // APPNOTE doesn't specify a version for Zstandard
365            _ => u16::from(DEFAULT_VERSION),
366        };
367        let crypto_version: u16 = if self.aes_mode.is_some() {
368            51
369        } else if self.encrypted {
370            20
371        } else {
372            10
373        };
374        let misc_feature_version: u16 = if self.large_file {
375            45
376        } else if self
377            .unix_mode()
378            .is_some_and(|mode| mode & ffi::S_IFDIR == ffi::S_IFDIR)
379        {
380            // file is directory
381            20
382        } else {
383            10
384        };
385        compression_version
386            .max(crypto_version)
387            .max(misc_feature_version)
388    }
389    #[inline(always)]
390    pub(crate) fn extra_field_len(&self) -> usize {
391        self.extra_field
392            .as_ref()
393            .map(|v| v.len())
394            .unwrap_or_default()
395    }
396    #[inline(always)]
397    pub(crate) fn central_extra_field_len(&self) -> usize {
398        self.central_extra_field
399            .as_ref()
400            .map(|v| v.len())
401            .unwrap_or_default()
402    }
403
404    #[allow(clippy::too_many_arguments)]
405    pub(crate) fn initialize_local_block<S, T: FileOptionExtension>(
406        name: &S,
407        options: &FileOptions<'_, T>,
408        raw_values: &ZipRawValues,
409        header_start: u64,
410        extra_data_start: Option<u64>,
411        aes_extra_data_start: u64,
412        compression_method: crate::compression::CompressionMethod,
413        aes_mode: Option<(AesMode, AesVendorVersion, CompressionMethod)>,
414        extra_field: &[u8],
415    ) -> Self
416    where
417        S: ToString,
418    {
419        let permissions = options
420            .permissions
421            .unwrap_or(FileOptions::DEFAULT_FILE_PERMISSION);
422        let file_name: Box<str> = name.to_string().into_boxed_str();
423        let file_name_raw: Box<[u8]> = file_name.as_bytes().into();
424        let mut external_attributes = permissions << 16;
425        let system = if (permissions & ffi::S_IFLNK) == ffi::S_IFLNK {
426            System::Unix
427        } else if let Some(system_option) = options.system {
428            // user provided
429            system_option
430        } else if cfg!(windows) {
431            System::Dos
432        } else {
433            System::Unix
434        };
435        if system == System::Dos {
436            if is_dir(&file_name) {
437                // DOS directory bit
438                external_attributes |= 0x10;
439            }
440            if options
441                .permissions
442                .is_some_and(|permissions| permissions & 0o444 == 0)
443            {
444                // DOS read-only bit
445                external_attributes |= 0x01;
446            }
447        }
448        let encrypted = options.encrypt_with.is_some();
449        #[cfg(feature = "aes-crypto")]
450        let encrypted = encrypted || options.aes_mode.is_some();
451        let mut local_block = ZipFileData {
452            system,
453            version_made_by: DEFAULT_VERSION,
454            flags: 0,
455            encrypted,
456            using_data_descriptor: false,
457            is_utf8: !file_name.is_ascii(),
458            compression_method,
459            compression_level: options.compression_level,
460            last_modified_time: Some(options.last_modified_time),
461            crc32: raw_values.crc32,
462            compressed_size: raw_values.compressed_size,
463            uncompressed_size: raw_values.uncompressed_size,
464            file_name, // Never used for saving, but used as map key in insert_file_data()
465            file_name_raw,
466            extra_field: Some(Arc::from(extra_field)),
467            central_extra_field: options
468                .extended_options
469                .central_extra_data()
470                .map(|v| Arc::from(v.as_ref().as_slice())),
471            file_comment: String::with_capacity(0).into_boxed_str(),
472            header_start,
473            data_start: OnceLock::new(),
474            central_header_start: 0,
475            external_attributes,
476            large_file: options.large_file,
477            aes_mode,
478            extra_fields: Vec::new(),
479            extra_data_start,
480            aes_extra_data_start,
481        };
482        local_block.version_made_by = local_block.version_needed() as u8;
483        local_block
484    }
485
486    pub(crate) fn from_local_block<R: std::io::Read + ?Sized>(
487        block: ZipLocalEntryBlock,
488        reader: &mut R,
489    ) -> ZipResult<Self> {
490        let ZipLocalEntryBlock {
491            version_made_by,
492            flags,
493            compression_method,
494            last_mod_time,
495            last_mod_date,
496            crc32,
497            compressed_size,
498            uncompressed_size,
499            file_name_length,
500            extra_field_length,
501            ..
502        } = block;
503
504        let encrypted: bool = ZipFlags::matching(flags, ZipFlags::Encrypted);
505        if encrypted {
506            return Err(ZipError::UnsupportedArchive(
507                "Encrypted files are not supported",
508            ));
509        }
510
511        /* FIXME: these were previously incorrect: add testing! */
512        let using_data_descriptor: bool = ZipFlags::matching(flags, ZipFlags::UsingDataDescriptor);
513        if using_data_descriptor {
514            return Err(ZipError::UnsupportedArchive(
515                "The file length is not available in the local header",
516            ));
517        }
518
519        let is_utf8: bool = ZipFlags::matching(flags, ZipFlags::LanguageEncoding);
520        let compression_method = crate::CompressionMethod::parse_from_u16(compression_method);
521        let file_name_length: usize = file_name_length.into();
522        let extra_field_length: usize = extra_field_length.into();
523
524        let mut file_name_raw = vec![0u8; file_name_length];
525        if let Err(e) = reader.read_exact(&mut file_name_raw) {
526            if e.kind() == std::io::ErrorKind::UnexpectedEof {
527                return Err(invalid!("File name extends beyond file boundary"));
528            }
529            return Err(e.into());
530        }
531        let mut extra_field = vec![0u8; extra_field_length];
532        if let Err(e) = reader.read_exact(&mut extra_field) {
533            if e.kind() == std::io::ErrorKind::UnexpectedEof {
534                return Err(invalid!("Extra field extends beyond file boundary"));
535            }
536            return Err(e.into());
537        }
538
539        let file_name: Box<str> = if is_utf8 {
540            String::from_utf8_lossy(&file_name_raw).into()
541        } else {
542            file_name_raw
543                .from_cp437()
544                .map_err(std::io::Error::other)?
545                .into()
546        };
547
548        let (version_made_by, system) = System::extract_bytes(version_made_by);
549        Ok(ZipFileData {
550            system,
551            version_made_by,
552            flags,
553            encrypted,
554            using_data_descriptor,
555            is_utf8,
556            compression_method,
557            compression_level: None,
558            last_modified_time: DateTime::try_from_msdos(last_mod_date, last_mod_time).ok(),
559            crc32,
560            compressed_size: compressed_size.into(),
561            uncompressed_size: uncompressed_size.into(),
562            file_name,
563            file_name_raw: file_name_raw.into(),
564            extra_field: Some(Arc::from(extra_field.into_boxed_slice())),
565            central_extra_field: None,
566            file_comment: String::with_capacity(0).into_boxed_str(), // file comment is only available in the central directory
567            // header_start and data start are not available, but also don't matter, since seeking is
568            // not available.
569            header_start: 0,
570            data_start: OnceLock::new(),
571            central_header_start: 0,
572            // The external_attributes field is only available in the central directory.
573            // We set this to zero, which should be valid as the docs state 'If input came
574            // from standard input, this field is set to zero.'
575            external_attributes: 0,
576            large_file: false,
577            aes_mode: None,
578            extra_fields: Vec::new(),
579            extra_data_start: None,
580            aes_extra_data_start: 0,
581        })
582    }
583
584    fn is_utf8(&self) -> bool {
585        std::str::from_utf8(&self.file_name_raw).is_ok()
586    }
587
588    fn is_ascii(&self) -> bool {
589        self.file_name_raw.is_ascii() && self.file_comment.is_ascii()
590    }
591
592    fn flags(&self) -> u16 {
593        let utf8_bit: u16 = if self.is_utf8() && !self.is_ascii() {
594            ZipFlags::LanguageEncoding.as_u16()
595        } else {
596            0
597        };
598
599        let using_data_descriptor_bit = if self.using_data_descriptor {
600            ZipFlags::UsingDataDescriptor.as_u16()
601        } else {
602            0
603        };
604
605        let encrypted_bit: u16 = if self.encrypted { 1u16 << 0 } else { 0 };
606
607        utf8_bit | using_data_descriptor_bit | encrypted_bit
608    }
609    fn clamp_size_field(&self, field: u64) -> Result<u32, std::io::Error> {
610        if self.large_file {
611            Ok(spec::ZIP64_BYTES_THR as u32)
612        } else {
613            field.min(spec::ZIP64_BYTES_THR).try_into().map_err(|_| {
614                std::io::Error::other(format!(
615                    "File size {field} exceeds maximum size for non-ZIP64 files"
616                ))
617            })
618        }
619    }
620
621    pub(crate) fn local_block(&self) -> ZipResult<ZipLocalEntryBlock> {
622        let (compressed_size, uncompressed_size) = if self.using_data_descriptor {
623            (0, 0)
624        } else {
625            (
626                self.clamp_size_field(self.compressed_size)?,
627                self.clamp_size_field(self.uncompressed_size)?,
628            )
629        };
630        let extra_field_length: u16 = self
631            .extra_field_len()
632            .try_into()
633            .map_err(|_| invalid!("Extra data field is too large"))?;
634
635        let last_modified_time = self
636            .last_modified_time
637            .unwrap_or_else(DateTime::default_for_write);
638        Ok(ZipLocalEntryBlock {
639            version_made_by: self.version_needed(),
640            flags: self.flags(),
641            compression_method: self.compression_method.serialize_to_u16(),
642            last_mod_time: last_modified_time.timepart(),
643            last_mod_date: last_modified_time.datepart(),
644            crc32: self.crc32,
645            compressed_size,
646            uncompressed_size,
647            file_name_length: self
648                .file_name_raw
649                .len()
650                .try_into()
651                .map_err(std::io::Error::other)?,
652            extra_field_length,
653        })
654    }
655
656    pub(crate) fn block(&self) -> ZipResult<ZipCentralEntryBlock> {
657        let compressed_size = if self.large_file {
658            spec::ZIP64_BYTES_THR as u32
659        } else {
660            self.compressed_size
661                .min(spec::ZIP64_BYTES_THR)
662                .try_into()
663                .map_err(std::io::Error::other)?
664        };
665        let uncompressed_size = if self.large_file {
666            spec::ZIP64_BYTES_THR as u32
667        } else {
668            self.uncompressed_size
669                .min(spec::ZIP64_BYTES_THR)
670                .try_into()
671                .map_err(std::io::Error::other)?
672        };
673        let offset = self
674            .header_start
675            .min(spec::ZIP64_BYTES_THR)
676            .try_into()
677            .map_err(std::io::Error::other)?;
678        let extra_field_len: u16 = self
679            .extra_field_len()
680            .try_into()
681            .map_err(std::io::Error::other)?;
682        let central_extra_field_len: u16 = self
683            .central_extra_field_len()
684            .try_into()
685            .map_err(std::io::Error::other)?;
686        let last_modified_time = self
687            .last_modified_time
688            .unwrap_or_else(DateTime::default_for_write);
689        let version_to_extract = self.version_needed();
690        let version_made_by = u16::from(self.version_made_by).max(version_to_extract);
691        Ok(ZipCentralEntryBlock {
692            version_made_by: ((self.system as u16) << 8) | version_made_by,
693            version_to_extract,
694            flags: self.flags(),
695            compression_method: self.compression_method.serialize_to_u16(),
696            last_mod_time: last_modified_time.timepart(),
697            last_mod_date: last_modified_time.datepart(),
698            crc32: self.crc32,
699            compressed_size,
700            uncompressed_size,
701            file_name_length: self
702                .file_name_raw
703                .len()
704                .try_into()
705                .map_err(std::io::Error::other)?,
706            extra_field_length: extra_field_len.checked_add(central_extra_field_len).ok_or(
707                invalid!("Extra field length in central directory exceeds 64KiB"),
708            )?,
709            file_comment_length: self
710                .file_comment
711                .len()
712                .try_into()
713                .map_err(std::io::Error::other)?,
714            disk_number: 0,
715            internal_file_attributes: 0,
716            external_file_attributes: self.external_attributes,
717            offset,
718        })
719    }
720
721    pub(crate) fn write_data_descriptor<W: std::io::Write>(
722        &self,
723        writer: &mut W,
724        auto_large_file: bool,
725    ) -> Result<(), ZipError> {
726        if self.large_file {
727            return self.zip64_data_descriptor_block().write(writer);
728        }
729        if self.compressed_size > spec::ZIP64_BYTES_THR
730            || self.uncompressed_size > spec::ZIP64_BYTES_THR
731        {
732            if auto_large_file {
733                return self.zip64_data_descriptor_block().write(writer);
734            }
735            return Err(ZipError::Io(std::io::Error::other(
736                "Large file option has not been set - use .large_file(true) in options",
737            )));
738        }
739        self.data_descriptor_block().write(writer)
740    }
741
742    pub(crate) fn data_descriptor_block(&self) -> ZipDataDescriptorBlock {
743        ZipDataDescriptorBlock {
744            crc32: self.crc32,
745            compressed_size: self.compressed_size as u32,
746            uncompressed_size: self.uncompressed_size as u32,
747        }
748    }
749
750    pub(crate) fn zip64_data_descriptor_block(&self) -> Zip64DataDescriptorBlock {
751        Zip64DataDescriptorBlock {
752            crc32: self.crc32,
753            compressed_size: self.compressed_size,
754            uncompressed_size: self.uncompressed_size,
755        }
756    }
757}
758
759/// The encryption specification used to encrypt a file with AES.
760///
761/// According to the [specification](https://www.winzip.com/win/en/aes_info.html#winzip11) AE-2
762/// does not make use of the CRC check.
763#[derive(Copy, Clone, Debug, Eq, PartialEq)]
764#[repr(u16)]
765pub enum AesVendorVersion {
766    Ae1 = 0x0001,
767    Ae2 = 0x0002,
768}
769
770impl AesVendorVersion {
771    /// As u16
772    #[must_use]
773    pub const fn as_u16(self) -> u16 {
774        self as u16
775    }
776}
777
778impl TryFrom<u16> for AesVendorVersion {
779    type Error = &'static str;
780
781    fn try_from(value: u16) -> Result<Self, Self::Error> {
782        let aes_vendor_version = match value {
783            0x0001 => AesVendorVersion::Ae1,
784            0x0002 => AesVendorVersion::Ae2,
785            _ => return Err("Invalid AES vendor version"),
786        };
787        Ok(aes_vendor_version)
788    }
789}
790
791impl From<AesVendorVersion> for u16 {
792    fn from(value: AesVendorVersion) -> Self {
793        value as u16
794    }
795}
796
797/// AES variant used.
798#[derive(Copy, Clone, Debug, Eq, PartialEq)]
799#[cfg_attr(feature = "_arbitrary", derive(arbitrary::Arbitrary))]
800#[repr(u8)]
801pub enum AesMode {
802    /// 128-bit AES encryption.
803    Aes128 = 0x01,
804    /// 192-bit AES encryption.
805    Aes192 = 0x02,
806    /// 256-bit AES encryption.
807    Aes256 = 0x03,
808}
809
810impl AesMode {
811    /// As u8
812    #[must_use]
813    pub const fn as_u8(self) -> u8 {
814        self as u8
815    }
816}
817
818impl Display for AesMode {
819    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
820        match self {
821            Self::Aes128 => write!(f, "AES-128"),
822            Self::Aes192 => write!(f, "AES-192"),
823            Self::Aes256 => write!(f, "AES-256"),
824        }
825    }
826}
827
828impl TryFrom<u8> for AesMode {
829    type Error = &'static str;
830
831    fn try_from(value: u8) -> Result<Self, Self::Error> {
832        let mode = match value {
833            0x01 => AesMode::Aes128,
834            0x02 => AesMode::Aes192,
835            0x03 => AesMode::Aes256,
836            _ => return Err("Invalid AES encryption strength"),
837        };
838        Ok(mode)
839    }
840}
841
842#[cfg(feature = "aes-crypto")]
843impl AesMode {
844    /// Length of the salt for the given AES mode.
845    #[must_use]
846    pub const fn salt_length(&self) -> usize {
847        self.key_length() / 2
848    }
849
850    /// Length of the key for the given AES mode.
851    #[must_use]
852    pub const fn key_length(&self) -> usize {
853        match self {
854            Self::Aes128 => 16,
855            Self::Aes192 => 24,
856            Self::Aes256 => 32,
857        }
858    }
859}
860
861#[cfg(test)]
862mod tests {
863    #[test]
864    fn system() {
865        use super::System;
866        assert_eq!(u8::from(System::Dos), 0u8);
867        assert_eq!(System::Dos as u8, 0u8);
868        assert_eq!(System::Unix as u8, 3u8);
869        assert_eq!(u8::from(System::Unix), 3u8);
870        assert_eq!(System::from(0), System::Dos);
871        assert_eq!(System::from(3), System::Unix);
872        assert_eq!(u8::from(System::Unknown), 255u8);
873        assert_eq!(System::Unknown as u8, 255u8);
874    }
875
876    #[test]
877    fn unix_mode_robustness() {
878        use super::{System, ZipFileData};
879        use crate::types::ffi;
880        let mut data = ZipFileData {
881            system: System::Dos,
882            external_attributes: (ffi::S_IFLNK | 0o777) << 16,
883            ..ZipFileData::default()
884        };
885        assert_eq!(data.unix_mode(), Some(ffi::S_IFLNK | 0o777));
886
887        data.system = System::Unknown;
888        assert_eq!(data.unix_mode(), Some(ffi::S_IFLNK | 0o777));
889
890        data.external_attributes = 0x10; // DOS directory bit
891        data.system = System::Dos;
892        assert_eq!(data.unix_mode().unwrap() & 0o170000, ffi::S_IFDIR);
893    }
894
895    #[test]
896    fn sanitize() {
897        use super::{System, ZipFileData};
898        use std::{path::PathBuf, sync::OnceLock};
899
900        let file_name = "/path/../../../../etc/./passwd\0/etc/shadow".to_string();
901        let data = ZipFileData {
902            system: System::Dos,
903            version_made_by: 0,
904            flags: 0,
905            encrypted: false,
906            using_data_descriptor: false,
907            is_utf8: true,
908            compression_method: crate::compression::CompressionMethod::Stored,
909            compression_level: None,
910            last_modified_time: None,
911            crc32: 0,
912            compressed_size: 0,
913            uncompressed_size: 0,
914            file_name: file_name.clone().into_boxed_str(),
915            file_name_raw: file_name.into_bytes().into_boxed_slice(),
916            extra_field: None,
917            central_extra_field: None,
918            file_comment: String::with_capacity(0).into_boxed_str(),
919            header_start: 0,
920            extra_data_start: None,
921            data_start: OnceLock::new(),
922            central_header_start: 0,
923            external_attributes: 0,
924            large_file: false,
925            aes_mode: None,
926            aes_extra_data_start: 0,
927            extra_fields: Vec::new(),
928        };
929        assert_eq!(data.file_name_sanitized(), PathBuf::from("path/etc/passwd"));
930    }
931}