Skip to main content

zip/
spec.rs

1//! Code linked with the specifications of the zip file
2
3use crate::read::ArchiveOffset;
4use crate::read::magic_finder::{Backwards, Forward, MagicFinder, OptimisticMagicFinder};
5use crate::result::{ZipError, ZipResult, invalid};
6use core::any::type_name;
7use core::mem;
8use core::slice;
9use std::io::{self, Read, Seek, Write};
10
11/// "Magic" header values used in the zip spec to locate metadata records.
12///
13/// These values currently always take up a fixed four bytes, so we can parse and wrap them in this
14/// struct to enforce some small amount of type safety.
15#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
16#[repr(transparent)]
17pub(crate) struct Magic(u32);
18
19impl Magic {
20    pub const fn literal(x: u32) -> Self {
21        Self(x)
22    }
23
24    #[inline(always)]
25    #[allow(dead_code)]
26    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
27        Self(u32::from_le_bytes(bytes))
28    }
29
30    #[inline(always)]
31    pub const fn to_le_bytes(self) -> [u8; 4] {
32        self.0.to_le_bytes()
33    }
34
35    #[allow(clippy::wrong_self_convention)]
36    #[allow(unused)]
37    #[inline(always)]
38    pub fn from_le(self) -> Self {
39        Self(u32::from_le(self.0))
40    }
41
42    #[allow(clippy::wrong_self_convention)]
43    #[inline(always)]
44    pub fn to_le(self) -> Self {
45        Self(u32::to_le(self.0))
46    }
47
48    pub const LOCAL_FILE_HEADER_SIGNATURE: Self = Self::literal(0x0403_4b50);
49    pub const CENTRAL_DIRECTORY_HEADER_SIGNATURE: Self = Self::literal(0x0201_4b50);
50    pub const CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x0605_4b50);
51    pub const ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x0606_4b50);
52    pub const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE: Self = Self::literal(0x0706_4b50);
53    pub const DATA_DESCRIPTOR_SIGNATURE: Self = Self::literal(0x0807_4b50);
54}
55
56/// Zip flags
57/// Stored as Little endian
58#[allow(unused)]
59#[rustfmt::skip]
60#[repr(u16)]
61#[derive(Debug, Copy, Clone, PartialEq, Eq)]
62#[non_exhaustive]
63pub(crate) enum ZipFlags {
64    /// If set, indicates that the file is encrypted.
65    Encrypted                   = 0b0000_0000_0000_0001,
66    CompressionSetting          = 0b0000_0000_0000_0010,
67    CompressionSetting2         = 0b0000_0000_0000_0100,
68    /// If this bit is set, the fields crc-32, compressed size and uncompressed size are set to zero in the  local header.
69    /// The correct values are put in the data descriptor immediately following the compressed data.
70    UsingDataDescriptor         = 0b0000_0000_0000_1000,
71    /// Reserved for use with method 8, for enhanced deflating.
72    ReservedEnhancedDeflating   = 0b0000_0000_0001_0000,
73    /// If this bit is set, this indicates that the file is compressed patched data.
74    CompressedPatchedData       = 0b0000_0000_0010_0000,
75    /// Strong encryption.
76    /// If this bit is set, you MUST set the version needed to extract value to at least 50 and you MUST also set bit 0.
77    /// If AES encryption is used, the version needed to extract value MUST be at least 51.
78    StrongEncryption            = 0b0000_0000_0100_0000,
79    // bit 7 Currently unused   = 0b0000_0000_1000_0000;
80    // bit 8 Currently unused   = 0b0000_0001_0000_0000;
81    // bit 9 Currently unused   = 0b0000_0010_0000_0000;
82    // bit 10 Currently unused  = 0b0000_0100_0000_0000;
83
84    /// Language encoding flag (EFS).
85    /// If this bit is set, the filename and comment fields for this file MUST be encoded using UTF-8.
86    LanguageEncoding            = 0b0000_1000_0000_0000,
87    /// Reserved by PKWARE for enhanced compression.
88    ReservedEnhancedCompression = 0b0001_0000_0000_0000,
89    /// Set when encrypting the Central Directory to indicate selected data values in the Local Header are masked to hide their actual values.
90    Masked                      = 0b0010_0000_0000_0000,
91    /// Reserved by PKWARE for alternate streams.
92    ReservedAlternateStream     = 0b0100_0000_0000_0000,
93    /// Reserved by PKWARE.
94    Reserved                    = 0b1000_0000_0000_0000,
95}
96
97impl ZipFlags {
98    pub(crate) fn matching(flags: u16, matching_flag: Self) -> bool {
99        flags & u16::from(matching_flag) != 0
100    }
101
102    pub(crate) const fn as_u16(self) -> u16 {
103        self as u16
104    }
105}
106
107impl From<ZipFlags> for u16 {
108    fn from(value: ZipFlags) -> u16 {
109        value.as_u16()
110    }
111}
112
113/// The file size at which a ZIP64 record becomes necessary.
114///
115/// If a file larger than this threshold attempts to be written, compressed or uncompressed, and
116/// [`FileOptions::large_file()`](crate::write::FileOptions::large_file) was not true, then [`crate::ZipWriter`] will
117/// raise an [`io::Error`] with [`io::ErrorKind::Other`].
118///
119/// If the zip file itself is larger than this value, then a zip64 central directory record will be
120/// written to the end of the file.
121///
122///```
123/// # fn main() -> Result<(), zip::result::ZipError> {
124/// # #[cfg(target_pointer_width = "64")]
125/// # #[cfg(all(target_endian = "little", not(miri)))] // too long to run on miri
126/// # {
127/// use std::io::{self, Cursor, Write};
128/// use std::error::Error;
129/// use zip::{ZipWriter, write::SimpleFileOptions};
130///
131/// let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
132/// // Writing an extremely large file for this test is faster without compression.
133///
134/// let big_len: usize = (zip::ZIP64_BYTES_THR as usize) + 1;
135/// let big_buf = vec![0u8; big_len];
136/// {
137///     let options = SimpleFileOptions::default()
138///         .compression_method(zip::CompressionMethod::Stored);
139///     zip.start_file("zero.dat", options)?;
140///     // This is too big!
141///     let res = zip.write_all(&big_buf[..]).err().unwrap();
142///     assert_eq!(res.kind(), io::ErrorKind::Other);
143///     let description = format!("{}", &res);
144///     assert_eq!(description, "Large file option has not been set");
145///     // Attempting to write anything further to the same zip will still succeed, but the previous
146///     // failing entry has been removed.
147///     zip.start_file("one.dat", options)?;
148///     let zip = zip.finish_into_readable()?;
149///     let names: Vec<_> = zip.file_names().collect();
150///     assert_eq!(&names, &["one.dat"]);
151/// }
152///
153/// // Create a new zip output.
154/// let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
155/// // This time, create a zip64 record for the file.
156/// let options = SimpleFileOptions::default()
157///      .compression_method(zip::CompressionMethod::Stored)
158///      .large_file(true);
159/// zip.start_file("zero.dat", options)?;
160/// // This succeeds because we specified that it could be a large file.
161/// assert!(zip.write_all(&big_buf[..]).is_ok());
162/// # }
163/// # Ok(())
164/// # }
165///```
166pub const ZIP64_BYTES_THR: u64 = u32::MAX as u64;
167/// The number of entries within a single zip necessary to allocate a zip64 central
168/// directory record.
169///
170/// If more than this number of entries is written to a [`crate::ZipWriter`], then [`crate::ZipWriter::finish()`]
171/// will write out extra zip64 data to the end of the zip file.
172pub const ZIP64_ENTRY_THR: usize = u16::MAX as usize;
173
174/// # Safety
175///
176/// - No padding/uninit bytes
177/// - All bytes patterns must be valid
178/// - No cell, pointers
179///
180/// See `bytemuck::Pod` for more details.
181pub(crate) unsafe trait Pod: Copy + 'static {
182    #[inline]
183    fn zeroed() -> Self {
184        unsafe { mem::zeroed() }
185    }
186
187    #[inline]
188    fn as_bytes(&self) -> &[u8] {
189        unsafe {
190            slice::from_raw_parts(
191                std::ptr::from_ref::<Self>(self).cast::<u8>(),
192                mem::size_of::<Self>(),
193            )
194        }
195    }
196
197    #[inline]
198    fn as_bytes_mut(&mut self) -> &mut [u8] {
199        unsafe {
200            slice::from_raw_parts_mut(
201                std::ptr::from_mut::<Self>(self).cast::<u8>(),
202                mem::size_of::<Self>(),
203            )
204        }
205    }
206}
207
208#[derive(Copy, Clone)]
209#[repr(C, packed)]
210struct BlockWithMagic<T: FixedSizeBlock> {
211    magic: Magic,
212    inner: T,
213}
214unsafe impl<T: FixedSizeBlock> Pod for BlockWithMagic<T> {}
215
216impl<T: FixedSizeBlock> BlockWithMagic<T> {
217    fn to_le(mut self) -> Self {
218        self.magic = self.magic.to_le();
219        self.inner = self.inner.to_le();
220        self
221    }
222}
223
224pub(crate) trait FixedSizeBlock: Pod {
225    const MAGIC: Magic;
226
227    const WRONG_MAGIC_ERROR: ZipError;
228
229    #[allow(clippy::wrong_self_convention)]
230    fn from_le(self) -> Self;
231
232    fn parse<R: Read + ?Sized>(reader: &mut R) -> ZipResult<Self> {
233        let mut block_with_magic = BlockWithMagic::zeroed();
234        if let Err(e) = reader.read_exact(block_with_magic.as_bytes_mut()) {
235            if e.kind() == io::ErrorKind::UnexpectedEof {
236                return Err(invalid!("Unexpected end of {}", type_name::<Self>()));
237            }
238            return Err(e.into());
239        }
240        let BlockWithMagic {
241            magic,
242            inner: block,
243        } = block_with_magic;
244        let magic = Magic::from_le(magic);
245        if magic != Self::MAGIC {
246            return Err(Self::WRONG_MAGIC_ERROR);
247        }
248        let block = Self::from_le(block);
249        Ok(block)
250    }
251
252    fn to_le(self) -> Self;
253
254    fn write<T: Write + ?Sized>(self, writer: &mut T) -> ZipResult<()> {
255        let block = BlockWithMagic {
256            magic: Self::MAGIC,
257            inner: self,
258        };
259        let block = block.to_le();
260        writer.write_all(block.as_bytes())?;
261        Ok(())
262    }
263}
264
265/// Convert all the fields of a struct *from* little-endian representations.
266macro_rules! from_le {
267    ($obj:ident, $field:ident, $type:ty) => {
268        $obj.$field = <$type>::from_le($obj.$field);
269    };
270    ($obj:ident, [($field:ident, $type:ty) $(,)?]) => {
271        from_le![$obj, $field, $type];
272    };
273    ($obj:ident, [($field:ident, $type:ty), $($rest:tt),+ $(,)?]) => {
274        from_le![$obj, $field, $type];
275        from_le!($obj, [$($rest),+]);
276    };
277}
278
279/// Convert all the fields of a struct *into* little-endian representations.
280macro_rules! to_le {
281    ($obj:ident, $field:ident, $type:ty) => {
282        $obj.$field = <$type>::to_le($obj.$field);
283    };
284    ($obj:ident, [($field:ident, $type:ty) $(,)?]) => {
285        to_le![$obj, $field, $type];
286    };
287    ($obj:ident, [($field:ident, $type:ty), $($rest:tt),+ $(,)?]) => {
288        to_le![$obj, $field, $type];
289        to_le!($obj, [$($rest),+]);
290    };
291}
292
293/* TODO: derive macro to generate these fields? */
294/// Implement `from_le()` and `to_le()`, providing the field specification to both macros
295/// and methods.
296#[macro_export]
297macro_rules! to_and_from_le {
298    ($($args:tt),+ $(,)?) => {
299        #[inline(always)]
300        fn from_le(mut self) -> Self {
301            from_le![self, [$($args),+]];
302            self
303        }
304        #[inline(always)]
305        fn to_le(mut self) -> Self {
306            to_le![self, [$($args),+]];
307            self
308        }
309    };
310}
311
312#[derive(Copy, Clone, Debug)]
313#[repr(packed, C)]
314pub(crate) struct ZipCentralEntryBlock {
315    pub version_made_by: u16,
316    pub version_to_extract: u16,
317    pub flags: u16,
318    pub compression_method: u16,
319    pub last_mod_time: u16,
320    pub last_mod_date: u16,
321    pub crc32: u32,
322    pub compressed_size: u32,
323    pub uncompressed_size: u32,
324    pub file_name_length: u16,
325    pub extra_field_length: u16,
326    pub file_comment_length: u16,
327    pub disk_number: u16,
328    pub internal_file_attributes: u16,
329    pub external_file_attributes: u32,
330    pub offset: u32,
331}
332
333unsafe impl Pod for ZipCentralEntryBlock {}
334
335impl FixedSizeBlock for ZipCentralEntryBlock {
336    const MAGIC: Magic = Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE;
337
338    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid Central Directory header");
339
340    to_and_from_le![
341        (version_made_by, u16),
342        (version_to_extract, u16),
343        (flags, u16),
344        (compression_method, u16),
345        (last_mod_time, u16),
346        (last_mod_date, u16),
347        (crc32, u32),
348        (compressed_size, u32),
349        (uncompressed_size, u32),
350        (file_name_length, u16),
351        (extra_field_length, u16),
352        (file_comment_length, u16),
353        (disk_number, u16),
354        (internal_file_attributes, u16),
355        (external_file_attributes, u32),
356        (offset, u32),
357    ];
358}
359
360#[derive(Copy, Clone, Debug)]
361#[repr(packed, C)]
362pub(crate) struct ZipLocalEntryBlock {
363    pub version_made_by: u16,
364    pub flags: u16,
365    pub compression_method: u16,
366    pub last_mod_time: u16,
367    pub last_mod_date: u16,
368    pub crc32: u32,
369    pub compressed_size: u32,
370    pub uncompressed_size: u32,
371    pub file_name_length: u16,
372    pub extra_field_length: u16,
373}
374
375unsafe impl Pod for ZipLocalEntryBlock {}
376
377impl FixedSizeBlock for ZipLocalEntryBlock {
378    const MAGIC: Magic = Magic::LOCAL_FILE_HEADER_SIGNATURE;
379
380    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid local file header");
381
382    to_and_from_le![
383        (version_made_by, u16),
384        (flags, u16),
385        (compression_method, u16),
386        (last_mod_time, u16),
387        (last_mod_date, u16),
388        (crc32, u32),
389        (compressed_size, u32),
390        (uncompressed_size, u32),
391        (file_name_length, u16),
392        (extra_field_length, u16),
393    ];
394}
395
396#[derive(Copy, Clone, Debug)]
397#[repr(packed, C)]
398pub(crate) struct ZipDataDescriptorBlock {
399    pub crc32: u32,
400    pub compressed_size: u32,
401    pub uncompressed_size: u32,
402}
403
404unsafe impl Pod for ZipDataDescriptorBlock {}
405
406impl FixedSizeBlock for ZipDataDescriptorBlock {
407    const MAGIC: Magic = Magic::DATA_DESCRIPTOR_SIGNATURE;
408
409    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid data descriptor header");
410
411    to_and_from_le![
412        (crc32, u32),
413        (compressed_size, u32),
414        (uncompressed_size, u32),
415    ];
416}
417
418#[derive(Copy, Clone, Debug)]
419#[repr(packed, C)]
420pub(crate) struct Zip64DataDescriptorBlock {
421    pub crc32: u32,
422    pub compressed_size: u64,
423    pub uncompressed_size: u64,
424}
425
426unsafe impl Pod for Zip64DataDescriptorBlock {}
427
428impl FixedSizeBlock for Zip64DataDescriptorBlock {
429    const MAGIC: Magic = Magic::DATA_DESCRIPTOR_SIGNATURE;
430
431    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid zip64 data descriptor header");
432
433    to_and_from_le![
434        (crc32, u32),
435        (compressed_size, u64),
436        (uncompressed_size, u64),
437    ];
438}
439
440#[derive(Copy, Clone, Debug)]
441#[repr(packed, C)]
442pub(crate) struct Zip32CDEBlock {
443    pub disk_number: u16,
444    pub disk_with_central_directory: u16,
445    pub number_of_files_on_this_disk: u16,
446    pub number_of_files: u16,
447    pub central_directory_size: u32,
448    pub central_directory_offset: u32,
449    pub zip_file_comment_length: u16,
450}
451
452unsafe impl Pod for Zip32CDEBlock {}
453
454impl FixedSizeBlock for Zip32CDEBlock {
455    const MAGIC: Magic = Magic::CENTRAL_DIRECTORY_END_SIGNATURE;
456
457    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid digital signature header");
458
459    to_and_from_le![
460        (disk_number, u16),
461        (disk_with_central_directory, u16),
462        (number_of_files_on_this_disk, u16),
463        (number_of_files, u16),
464        (central_directory_size, u32),
465        (central_directory_offset, u32),
466        (zip_file_comment_length, u16)
467    ];
468}
469
470#[derive(Debug)]
471pub(crate) struct Zip32CentralDirectoryEnd {
472    pub disk_number: u16,
473    pub disk_with_central_directory: u16,
474    pub number_of_files_on_this_disk: u16,
475    pub number_of_files: u16,
476    pub central_directory_size: u32,
477    pub central_directory_offset: u32,
478    pub zip_file_comment: Box<[u8]>,
479}
480
481impl Zip32CentralDirectoryEnd {
482    fn into_block_and_comment(self) -> (Zip32CDEBlock, Box<[u8]>) {
483        let Self {
484            disk_number,
485            disk_with_central_directory,
486            number_of_files_on_this_disk,
487            number_of_files,
488            central_directory_size,
489            central_directory_offset,
490            zip_file_comment,
491        } = self;
492        let block = Zip32CDEBlock {
493            disk_number,
494            disk_with_central_directory,
495            number_of_files_on_this_disk,
496            number_of_files,
497            central_directory_size,
498            central_directory_offset,
499            zip_file_comment_length: zip_file_comment.len() as u16,
500        };
501
502        (block, zip_file_comment)
503    }
504
505    pub fn parse<T: Read + ?Sized>(reader: &mut T) -> ZipResult<Zip32CentralDirectoryEnd> {
506        let Zip32CDEBlock {
507            disk_number,
508            disk_with_central_directory,
509            number_of_files_on_this_disk,
510            number_of_files,
511            central_directory_size,
512            central_directory_offset,
513            zip_file_comment_length,
514            ..
515        } = Zip32CDEBlock::parse(reader)?;
516
517        let mut zip_file_comment = vec![0u8; zip_file_comment_length as usize].into_boxed_slice();
518        if let Err(e) = reader.read_exact(&mut zip_file_comment) {
519            if e.kind() == io::ErrorKind::UnexpectedEof {
520                return Err(invalid!("EOCD comment exceeds file boundary"));
521            }
522
523            return Err(e.into());
524        }
525
526        Ok(Zip32CentralDirectoryEnd {
527            disk_number,
528            disk_with_central_directory,
529            number_of_files_on_this_disk,
530            number_of_files,
531            central_directory_size,
532            central_directory_offset,
533            zip_file_comment,
534        })
535    }
536
537    pub fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
538        let (block, comment) = self.into_block_and_comment();
539
540        if comment.len() > u16::MAX as usize {
541            return Err(invalid!("EOCD comment length exceeds u16::MAX"));
542        }
543
544        block.write(writer)?;
545        writer.write_all(&comment)?;
546        Ok(())
547    }
548
549    pub fn may_be_zip64(&self) -> bool {
550        self.number_of_files == u16::MAX
551            || self.central_directory_size == u32::MAX
552            || self.central_directory_offset == u32::MAX
553    }
554}
555
556#[derive(Copy, Clone)]
557#[repr(packed, C)]
558pub(crate) struct Zip64CDELocatorBlock {
559    pub disk_with_central_directory: u32,
560    pub end_of_central_directory_offset: u64,
561    pub number_of_disks: u32,
562}
563
564unsafe impl Pod for Zip64CDELocatorBlock {}
565
566impl FixedSizeBlock for Zip64CDELocatorBlock {
567    const MAGIC: Magic = Magic::ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE;
568
569    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid zip64 locator digital signature header");
570
571    to_and_from_le![
572        (disk_with_central_directory, u32),
573        (end_of_central_directory_offset, u64),
574        (number_of_disks, u32),
575    ];
576}
577
578pub(crate) struct Zip64CentralDirectoryEndLocator {
579    pub disk_with_central_directory: u32,
580    pub end_of_central_directory_offset: u64,
581    pub number_of_disks: u32,
582}
583
584impl Zip64CentralDirectoryEndLocator {
585    pub fn parse<T: Read + ?Sized>(reader: &mut T) -> ZipResult<Zip64CentralDirectoryEndLocator> {
586        let Zip64CDELocatorBlock {
587            disk_with_central_directory,
588            end_of_central_directory_offset,
589            number_of_disks,
590            ..
591        } = Zip64CDELocatorBlock::parse(reader)?;
592
593        Ok(Zip64CentralDirectoryEndLocator {
594            disk_with_central_directory,
595            end_of_central_directory_offset,
596            number_of_disks,
597        })
598    }
599
600    pub fn block(self) -> Zip64CDELocatorBlock {
601        let Self {
602            disk_with_central_directory,
603            end_of_central_directory_offset,
604            number_of_disks,
605        } = self;
606        Zip64CDELocatorBlock {
607            disk_with_central_directory,
608            end_of_central_directory_offset,
609            number_of_disks,
610        }
611    }
612
613    pub fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
614        self.block().write(writer)
615    }
616}
617
618#[derive(Copy, Clone)]
619#[repr(packed, C)]
620pub(crate) struct Zip64CDEBlock {
621    pub record_size: u64,
622    pub version_made_by: u16,
623    pub version_needed_to_extract: u16,
624    pub disk_number: u32,
625    pub disk_with_central_directory: u32,
626    pub number_of_files_on_this_disk: u64,
627    pub number_of_files: u64,
628    pub central_directory_size: u64,
629    pub central_directory_offset: u64,
630}
631
632unsafe impl Pod for Zip64CDEBlock {}
633
634impl FixedSizeBlock for Zip64CDEBlock {
635    const MAGIC: Magic = Magic::ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE;
636
637    const WRONG_MAGIC_ERROR: ZipError = invalid!("Invalid digital signature header");
638
639    to_and_from_le![
640        (record_size, u64),
641        (version_made_by, u16),
642        (version_needed_to_extract, u16),
643        (disk_number, u32),
644        (disk_with_central_directory, u32),
645        (number_of_files_on_this_disk, u64),
646        (number_of_files, u64),
647        (central_directory_size, u64),
648        (central_directory_offset, u64),
649    ];
650}
651
652pub(crate) struct Zip64CentralDirectoryEnd {
653    pub record_size: u64,
654    pub version_made_by: u16,
655    pub version_needed_to_extract: u16,
656    pub disk_number: u32,
657    pub disk_with_central_directory: u32,
658    pub number_of_files_on_this_disk: u64,
659    pub number_of_files: u64,
660    pub central_directory_size: u64,
661    pub central_directory_offset: u64,
662    pub(crate) zip64_extensible_data_sector: Option<Box<[u8]>>,
663}
664
665impl Zip64CentralDirectoryEnd {
666    /// Minimum size of the block
667    /// Block - record_size - extensible_data
668    const MIN_SIZE: usize = 2 * size_of::<u16>() + 2 * size_of::<u32>() + 4 * size_of::<u64>();
669
670    pub(crate) fn parse<T: Read + ?Sized>(
671        reader: &mut T,
672        max_size: u64,
673    ) -> ZipResult<Zip64CentralDirectoryEnd> {
674        let Zip64CDEBlock {
675            record_size,
676            version_made_by,
677            version_needed_to_extract,
678            disk_number,
679            disk_with_central_directory,
680            number_of_files_on_this_disk,
681            number_of_files,
682            central_directory_size,
683            central_directory_offset,
684            ..
685        } = Zip64CDEBlock::parse(reader)?;
686
687        if record_size < 40 {
688            return Err(invalid!("Low EOCD64 record size"));
689        } else if record_size.saturating_add(12) > max_size {
690            return Err(invalid!("EOCD64 extends beyond EOCD64 locator"));
691        }
692
693        let zip64_extensible_data_sector = if record_size > (Self::MIN_SIZE as u64) {
694            let mut extensible_data_sector =
695                vec![0u8; record_size as usize - Self::MIN_SIZE].into_boxed_slice();
696            if let Err(e) = reader.read_exact(&mut extensible_data_sector) {
697                if e.kind() == io::ErrorKind::UnexpectedEof {
698                    return Err(invalid!(
699                        "EOCD64 extensible data sector exceeds file boundary"
700                    ));
701                }
702                return Err(e.into());
703            }
704            Some(extensible_data_sector)
705        } else {
706            None
707        };
708
709        Ok(Self {
710            record_size,
711            version_made_by,
712            version_needed_to_extract,
713            disk_number,
714            disk_with_central_directory,
715            number_of_files_on_this_disk,
716            number_of_files,
717            central_directory_size,
718            central_directory_offset,
719            zip64_extensible_data_sector,
720        })
721    }
722
723    pub(crate) fn into_block_and_extensible_data(self) -> (Zip64CDEBlock, Option<Box<[u8]>>) {
724        let Self {
725            record_size,
726            version_made_by,
727            version_needed_to_extract,
728            disk_number,
729            disk_with_central_directory,
730            number_of_files_on_this_disk,
731            number_of_files,
732            central_directory_size,
733            central_directory_offset,
734            zip64_extensible_data_sector,
735        } = self;
736
737        (
738            Zip64CDEBlock {
739                record_size,
740                version_made_by,
741                version_needed_to_extract,
742                disk_number,
743                disk_with_central_directory,
744                number_of_files_on_this_disk,
745                number_of_files,
746                central_directory_size,
747                central_directory_offset,
748            },
749            zip64_extensible_data_sector,
750        )
751    }
752
753    pub(crate) fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
754        let (block, zip64_extensible_data) = self.into_block_and_extensible_data();
755        block.write(writer)?;
756        if let Some(extensible_data) = zip64_extensible_data {
757            writer.write_all(&extensible_data)?;
758        }
759        Ok(())
760    }
761}
762
763pub(crate) struct DataAndPosition<T> {
764    pub data: T,
765    #[allow(dead_code)]
766    pub position: u64,
767}
768
769impl<T> From<(T, u64)> for DataAndPosition<T> {
770    fn from(value: (T, u64)) -> Self {
771        Self {
772            data: value.0,
773            position: value.1,
774        }
775    }
776}
777
778pub(crate) struct CentralDirectoryEndInfo {
779    pub eocd: DataAndPosition<Zip32CentralDirectoryEnd>,
780    pub eocd64: Option<DataAndPosition<Zip64CentralDirectoryEnd>>,
781
782    pub archive_offset: u64,
783}
784
785/// Finds the EOCD and possibly the EOCD64 block and determines the archive offset.
786///
787/// In the best case scenario (no prepended junk), this function will not backtrack
788/// in the reader.
789pub(crate) fn find_central_directory<R: Read + Seek + ?Sized>(
790    reader: &mut R,
791    archive_offset: ArchiveOffset,
792    end_exclusive: u64,
793    file_len: u64,
794) -> ZipResult<CentralDirectoryEndInfo> {
795    const EOCD_SIG_BYTES: [u8; mem::size_of::<Magic>()] =
796        Magic::CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes();
797
798    const EOCD64_SIG_BYTES: [u8; mem::size_of::<Magic>()] =
799        Magic::ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes();
800
801    const CDFH_SIG_BYTES: [u8; mem::size_of::<Magic>()] =
802        Magic::CENTRAL_DIRECTORY_HEADER_SIGNATURE.to_le_bytes();
803
804    // Instantiate the mandatory finder
805    let mut eocd_finder = MagicFinder::<Backwards<'static>>::new(&EOCD_SIG_BYTES, 0, end_exclusive);
806    let mut subfinder: Option<OptimisticMagicFinder<Forward<'static>>> = None;
807
808    // Keep the last errors for cases of improper EOCD instances.
809    let mut parsing_error = None;
810
811    while let Some(eocd_offset) = eocd_finder.next(reader)? {
812        // Attempt to parse the EOCD block
813        let eocd = match Zip32CentralDirectoryEnd::parse(reader) {
814            Ok(eocd) => eocd,
815            Err(e) => {
816                if parsing_error.is_none() {
817                    parsing_error = Some(e);
818                }
819                continue;
820            }
821        };
822
823        // ! Relaxed (inequality) due to garbage-after-comment Python files
824        // Consistency check: the EOCD comment must terminate before the end of file
825        if eocd.zip_file_comment.len() as u64 + eocd_offset + 22 > file_len {
826            parsing_error = Some(invalid!("Invalid EOCD comment length"));
827            continue;
828        }
829
830        let zip64_metadata = if eocd.may_be_zip64() {
831            fn try_read_eocd64_locator(
832                reader: &mut (impl Read + Seek + ?Sized),
833                eocd_offset: u64,
834            ) -> ZipResult<(u64, Zip64CentralDirectoryEndLocator)> {
835                if eocd_offset
836                    < (mem::size_of::<Magic>() + mem::size_of::<Zip64CDELocatorBlock>()) as u64
837                {
838                    return Err(invalid!("EOCD64 Locator does not fit in file"));
839                }
840
841                let locator64_offset = eocd_offset
842                    - (mem::size_of::<Magic>() + mem::size_of::<Zip64CDELocatorBlock>()) as u64;
843
844                reader.seek(io::SeekFrom::Start(locator64_offset))?;
845                let locator64 = Zip64CentralDirectoryEndLocator::parse(reader);
846                Ok((locator64_offset, locator64?))
847            }
848
849            try_read_eocd64_locator(reader, eocd_offset).ok()
850        } else {
851            None
852        };
853
854        let Some((locator64_offset, locator64)) = zip64_metadata else {
855            // Branch out for zip32
856            let relative_cd_offset = u64::from(eocd.central_directory_offset);
857
858            // If the archive is empty, there is nothing more to be checked, the archive is correct.
859            if eocd.number_of_files == 0 {
860                return Ok(CentralDirectoryEndInfo {
861                    eocd: (eocd, eocd_offset).into(),
862                    eocd64: None,
863                    archive_offset: eocd_offset.saturating_sub(relative_cd_offset),
864                });
865            }
866
867            // Consistency check: the CD relative offset cannot be after the EOCD
868            if relative_cd_offset >= eocd_offset {
869                parsing_error = Some(invalid!("Invalid CDFH offset in EOCD"));
870                continue;
871            }
872
873            // Attempt to find the first CDFH
874            let subfinder = subfinder
875                .get_or_insert_with(OptimisticMagicFinder::new_empty)
876                .repurpose(
877                    &CDFH_SIG_BYTES,
878                    // The CDFH must be before the EOCD and after the relative offset,
879                    // because prepended junk can only move it forward.
880                    (relative_cd_offset, eocd_offset),
881                    match archive_offset {
882                        ArchiveOffset::Known(n) => {
883                            Some((relative_cd_offset.saturating_add(n).min(eocd_offset), true))
884                        }
885                        _ => Some((relative_cd_offset, false)),
886                    },
887                );
888
889            // Consistency check: find the first CDFH
890            if let Some(cd_offset) = subfinder.next(reader)? {
891                // The first CDFH will define the archive offset
892                let archive_offset = cd_offset - relative_cd_offset;
893
894                return Ok(CentralDirectoryEndInfo {
895                    eocd: (eocd, eocd_offset).into(),
896                    eocd64: None,
897                    archive_offset,
898                });
899            }
900
901            parsing_error = Some(invalid!("No CDFH found"));
902            continue;
903        };
904
905        // Consistency check: the EOCD64 offset must be before EOCD64 Locator offset */
906        if locator64.end_of_central_directory_offset >= locator64_offset {
907            parsing_error = Some(invalid!("Invalid EOCD64 Locator CD offset"));
908            continue;
909        }
910
911        if locator64.number_of_disks > 1 {
912            parsing_error = Some(invalid!("Multi-disk ZIP files are not supported"));
913            continue;
914        }
915
916        // This was hidden inside a function to collect errors in a single place.
917        // Once try blocks are stabilized, this can go away.
918        fn try_read_eocd64<R: Read + Seek + ?Sized>(
919            reader: &mut R,
920            locator64: &Zip64CentralDirectoryEndLocator,
921            expected_length: u64,
922        ) -> ZipResult<Zip64CentralDirectoryEnd> {
923            let z64 = Zip64CentralDirectoryEnd::parse(reader, expected_length)?;
924
925            // Consistency check: EOCD64 locator should agree with the EOCD64
926            if z64.disk_with_central_directory != locator64.disk_with_central_directory {
927                return Err(invalid!("Invalid EOCD64: inconsistency with Locator data"));
928            }
929
930            // Consistency check: the EOCD64 must have the expected length
931            if z64.record_size + 12 != expected_length {
932                return Err(invalid!("Invalid EOCD64: inconsistent length"));
933            }
934
935            Ok(z64)
936        }
937
938        // Attempt to find the EOCD64 with an initial guess
939        let subfinder = subfinder
940            .get_or_insert_with(OptimisticMagicFinder::new_empty)
941            .repurpose(
942                &EOCD64_SIG_BYTES,
943                (locator64.end_of_central_directory_offset, locator64_offset),
944                match archive_offset {
945                    ArchiveOffset::Known(n) => Some((
946                        locator64
947                            .end_of_central_directory_offset
948                            .saturating_add(n)
949                            .min(locator64_offset),
950                        true,
951                    )),
952                    _ => Some((locator64.end_of_central_directory_offset, false)),
953                },
954            );
955
956        // Consistency check: Find the EOCD64
957        let mut local_error = None;
958        while let Some(eocd64_offset) = subfinder.next(reader)? {
959            let archive_offset = eocd64_offset - locator64.end_of_central_directory_offset;
960
961            match try_read_eocd64(
962                reader,
963                &locator64,
964                locator64_offset.saturating_sub(eocd64_offset),
965            ) {
966                Ok(eocd64) => {
967                    if eocd64_offset
968                        < eocd64
969                            .number_of_files
970                            .saturating_mul(
971                                (mem::size_of::<Magic>() + mem::size_of::<ZipCentralEntryBlock>())
972                                    as u64,
973                            )
974                            .saturating_add(eocd64.central_directory_offset)
975                    {
976                        local_error =
977                            Some(invalid!("Invalid EOCD64: inconsistent number of files"));
978                        continue;
979                    }
980
981                    return Ok(CentralDirectoryEndInfo {
982                        eocd: (eocd, eocd_offset).into(),
983                        eocd64: Some((eocd64, eocd64_offset).into()),
984                        archive_offset,
985                    });
986                }
987                Err(e) => {
988                    local_error = Some(e);
989                }
990            }
991        }
992
993        parsing_error = local_error.or(Some(invalid!("Could not find EOCD64")));
994    }
995
996    Err(parsing_error.unwrap_or(invalid!("Could not find EOCD")))
997}
998
999#[inline]
1000pub(crate) fn is_dir(filename: &str) -> bool {
1001    matches!(filename.as_bytes().last(), Some(b'/') | Some(b'\\'))
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use std::io::Cursor;
1007
1008    use crate::{
1009        result::{ZipError, invalid},
1010        spec::{FixedSizeBlock, Magic, Pod},
1011    };
1012
1013    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1014    #[repr(packed, C)]
1015    pub struct TestBlock {
1016        pub file_name_length: u16,
1017    }
1018
1019    unsafe impl Pod for TestBlock {}
1020
1021    impl FixedSizeBlock for TestBlock {
1022        const MAGIC: Magic = Magic::literal(0x01111);
1023
1024        const WRONG_MAGIC_ERROR: ZipError = invalid!("unreachable");
1025
1026        to_and_from_le![(file_name_length, u16)];
1027    }
1028
1029    /// Demonstrate that a block object can be safely written to memory and deserialized back out.
1030    #[test]
1031    fn block_serde() {
1032        let block = TestBlock {
1033            file_name_length: 3,
1034        };
1035        let mut c = Cursor::new(Vec::new());
1036        block.write(&mut c).unwrap();
1037        c.set_position(0);
1038        let block2 = TestBlock::parse(&mut c).unwrap();
1039        assert_eq!(block, block2);
1040    }
1041
1042    #[test]
1043    fn test_size_zip64_central_directory_end() {
1044        use super::Zip64CentralDirectoryEnd;
1045        assert_eq!(Zip64CentralDirectoryEnd::MIN_SIZE, 44);
1046    }
1047}