Skip to main content

zip_framing/
index.rs

1use std::{borrow::Cow, cell::RefCell, collections::HashMap, mem};
2
3use memchr::memmem;
4use tokio::io::{AsyncRead, AsyncSeek};
5
6use crate::{
7    Budget, Error, ExtraFieldPolicy, IndexPolicyViolation, Limits, add,
8    constants::{extra, signature, size, version},
9    invalid, policy_violation,
10    record::{GeneralPurposeFlags, RecordReader, array_at},
11};
12
13mod entry;
14
15use entry::{BufferedEntry, ResolvedMember};
16pub use entry::{CentralDirectoryEntry, Entry, IndexedEntry};
17
18thread_local! {
19    static DIRECTORY_WINDOW: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
20}
21
22/// Owns its window across awaits, returning a bounded allocation for later opens.
23struct DirectoryWindow(Vec<u8>);
24
25impl DirectoryWindow {
26    fn take() -> Self {
27        Self(
28            DIRECTORY_WINDOW
29                .try_with(|window| {
30                    window
31                        .try_borrow_mut()
32                        .map(|mut window| mem::take(&mut *window))
33                        .unwrap_or_default()
34                })
35                .unwrap_or_default(),
36        )
37    }
38}
39
40impl Drop for DirectoryWindow {
41    fn drop(&mut self) {
42        // Variable records can require a larger window; retain only the usual
43        // bounded end-record scan allocation, at most one per thread.
44        if self.0.capacity() <= size::END + usize::from(u16::MAX) {
45            self.0.clear();
46            let _ = DIRECTORY_WINDOW.try_with(|window| {
47                if let Ok(mut window) = window.try_borrow_mut()
48                    && window.capacity() < self.0.capacity()
49                {
50                    *window = mem::take(&mut self.0);
51                }
52            });
53        }
54    }
55}
56
57/// Which ZIP comment bytes the reader accepts. Empty comments are always accepted.
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59#[non_exhaustive]
60pub enum CommentRule {
61    /// Reject nonempty comments.
62    Reject,
63    /// Accept only ASCII bytes.
64    AllowAscii,
65    /// Accept UTF-8. Non-ASCII member comments must set the UTF-8 flag (bit 11).
66    AllowUtf8,
67    /// Accept arbitrary bytes. Member comments with bit 11 set must still be UTF-8.
68    AllowAll,
69}
70
71impl CommentRule {
72    fn check(
73        self,
74        bytes: &[u8],
75        member_flags: Option<GeneralPurposeFlags>,
76        position: u64,
77    ) -> Result<(), Error> {
78        if bytes.is_empty() {
79            return Ok(());
80        }
81        let utf8 = member_flags.map(|flags| flags.contains(GeneralPurposeFlags::UTF8));
82        if utf8 == Some(true) && str::from_utf8(bytes).is_err() {
83            return Err(invalid(position, "non-UTF-8 comment"));
84        }
85
86        let accepted = match (self, utf8) {
87            (Self::Reject, _) => false,
88            (Self::AllowAscii, _) | (Self::AllowUtf8, Some(false)) => bytes.is_ascii(),
89            (Self::AllowUtf8, None) => str::from_utf8(bytes).is_ok(),
90            (Self::AllowUtf8, Some(true)) | (Self::AllowAll, _) => true,
91        };
92        if accepted {
93            return Ok(());
94        }
95
96        let violation = if member_flags.is_some() {
97            IndexPolicyViolation::MemberComment { rule: self }
98        } else {
99            IndexPolicyViolation::ArchiveComment { rule: self }
100        };
101        Err(policy_violation(position, violation))
102    }
103}
104
105/// Which comments the reader accepts in member and end records.
106#[derive(Clone, Copy, Debug, Eq, PartialEq)]
107pub struct CommentPolicy {
108    /// Comments in central directory entries. Defaults to [`CommentRule::Reject`].
109    pub per_member: CommentRule,
110    /// Comment in the end record. Defaults to [`CommentRule::AllowAscii`].
111    pub archive: CommentRule,
112}
113
114impl Default for CommentPolicy {
115    fn default() -> Self {
116        Self {
117            per_member: CommentRule::Reject,
118            archive: CommentRule::AllowAscii,
119        }
120    }
121}
122
123/// Controls resource limits and compatibility when indexing a ZIP archive.
124#[derive(Clone, Copy, Debug)]
125#[must_use]
126pub struct IndexPolicy {
127    limits: Limits,
128    extra_fields: ExtraFieldPolicy,
129    comments: CommentPolicy,
130    allow_redundant_zip64_sizes: bool,
131    allow_stored_data_descriptors: bool,
132    allow_empty_deflate_streams: bool,
133    allow_incompatible_extraction_versions: bool,
134    allow_ambiguous_symlink_modes: bool,
135    allow_backslashes: bool,
136}
137
138impl Default for IndexPolicy {
139    fn default() -> Self {
140        Self {
141            limits: Limits::default(),
142            extra_fields: ExtraFieldPolicy::default(),
143            comments: CommentPolicy::default(),
144            allow_redundant_zip64_sizes: false,
145            allow_stored_data_descriptors: false,
146            allow_empty_deflate_streams: true,
147            allow_incompatible_extraction_versions: false,
148            allow_ambiguous_symlink_modes: false,
149            allow_backslashes: false,
150        }
151    }
152}
153
154impl IndexPolicy {
155    /// Sets the resource limits for the archive.
156    pub fn limits(mut self, limits: Limits) -> Self {
157        self.limits = limits;
158        self
159    }
160
161    /// Sets the extra fields accepted in both headers. Defaults to [`ExtraFieldPolicy::Zip64Only`].
162    pub fn extra_field_policy(mut self, policy: ExtraFieldPolicy) -> Self {
163        self.extra_fields = policy;
164        self
165    }
166
167    /// Sets the rules for member and archive comments.
168    pub fn comment_policy(mut self, policy: CommentPolicy) -> Self {
169        self.comments = policy;
170        self
171    }
172
173    /// Allows a local ZIP64 extra that repeats both 32-bit sizes on a member
174    /// without a data descriptor. Disabled by default.
175    ///
176    /// [Older CPython versions] wrote these extras with `force_zip64` even
177    /// when the extraction version was below 4.5. Both sizes must match
178    /// exactly.
179    ///
180    /// [Older CPython versions]: https://github.com/python/cpython/issues/103861
181    pub fn allow_redundant_zip64_sizes(mut self, allow: bool) -> Self {
182        self.allow_redundant_zip64_sizes = allow;
183        self
184    }
185
186    /// Allows Stored members with data descriptors (bit 3). Disabled by default.
187    pub fn allow_stored_data_descriptors(mut self, allow: bool) -> Self {
188        self.allow_stored_data_descriptors = allow;
189        self
190    }
191
192    /// Allows empty DEFLATE streams. Enabled by default.
193    ///
194    /// Disable to require zero compressed bytes for empty DEFLATE members
195    /// under [APPNOTE §4.3.8].
196    ///
197    /// [APPNOTE §4.3.8]: https://pkwaredownloads.blob.core.windows.net/pkware-general/Documentation/APPNOTE-6.3.9.TXT
198    pub fn allow_empty_deflate_streams(mut self, allow: bool) -> Self {
199        self.allow_empty_deflate_streams = allow;
200        self
201    }
202
203    /// Allows local and central member headers to declare an extraction version
204    /// below the minimum for their compression method, ZIP64 fields, or member
205    /// kind (APPNOTE 4.4.3.2). Disabled by default. Versions above 4.5
206    /// remain unsupported.
207    ///
208    /// Info-ZIP 3.0 can declare version 1.0 for directories, which require 2.0.
209    /// Go's [`zip.Writer.CreateRaw`](https://pkg.go.dev/archive/zip#Writer.CreateRaw)
210    /// can write version 0 if the caller leaves `FileHeader.ReaderVersion` unset.
211    pub fn allow_incompatible_extraction_versions(mut self, allow: bool) -> Self {
212        self.allow_incompatible_extraction_versions = allow;
213        self
214    }
215
216    /// Allows Unix symlink mode bits from non-Unix creator systems. Disabled by default.
217    /// When enabled, Darwin uses Unix modes. Other creators use their usual attributes.
218    pub fn allow_ambiguous_symlink_modes(mut self, allow: bool) -> Self {
219        self.allow_ambiguous_symlink_modes = allow;
220        self
221    }
222
223    /// Allows literal backslashes in member names. Disabled by default.
224    ///
225    /// Member names are returned verbatim. Only `/` is a path separator.
226    pub fn allow_backslashes(mut self, allow: bool) -> Self {
227        self.allow_backslashes = allow;
228        self
229    }
230
231    fn check_version(&self, declared: u16, minimum: u16, position: u64) -> Result<(), Error> {
232        if declared < minimum && !self.allow_incompatible_extraction_versions {
233            return Err(policy_violation(
234                position,
235                IndexPolicyViolation::IncompatibleExtractionVersion { declared, minimum },
236            ));
237        }
238        Ok(())
239    }
240}
241
242/// A ZIP member index.
243///
244/// This is constructed from the central directory, with referenced
245/// local file entries being resolved lazily upon access through
246/// [`Self::entry`].
247#[derive(Debug)]
248pub struct Index {
249    /// The indexed members, in central directory order.
250    entries: Vec<IndexedEntry>,
251    /// Cached resolutions in directory order, allocated on first access.
252    resolved: Vec<Option<ResolvedMember>>,
253    /// Policy used to validate local records on member access.
254    policy: IndexPolicy,
255    /// The parse budget. This is debited against when parsing local
256    /// file entries and reconciling local/central metadata.
257    budget: Budget,
258    /// Scratch space for local records, cleared between resolutions.
259    buffer: Vec<u8>,
260}
261
262impl Index {
263    /// Borrows indexed members, without fetching local records or payloads.
264    pub fn entries(&self) -> &[IndexedEntry] {
265        &self.entries
266    }
267
268    /// Returns a previously checked entry by index, without performing I/O.
269    ///
270    /// Returns [`None`] if the index is out of bounds or the member is unresolved.
271    pub fn resolved(&self, index: usize) -> Option<Entry<'_>> {
272        Some(Entry {
273            indexed: self.entries.get(index)?,
274            resolved: self.resolved.get(index)?.as_ref()?,
275        })
276    }
277
278    /// Indexes the directory with the default [`IndexPolicy`].
279    ///
280    /// Local headers and descriptors are checked by [`Self::entry`] on access,
281    /// or by [`Self::validate_all`]. The source must remain unchanged and be the
282    /// same source passed to subsequent operations. A cancelled read may leave
283    /// its cursor anywhere; another call restarts from the end.
284    pub async fn read<R: AsyncRead + AsyncSeek + Unpin>(reader: &mut R) -> Result<Self, Error> {
285        Self::read_with_policy(reader, IndexPolicy::default()).await
286    }
287
288    /// Indexes the directory with the supplied policy and checks bounds derivable from its records.
289    ///
290    /// The policy also applies when checking local records. See [`Self::read`]
291    /// for requirements on the source.
292    pub async fn read_with_policy<R: AsyncRead + AsyncSeek + Unpin>(
293        reader: &mut R,
294        policy: IndexPolicy,
295    ) -> Result<Self, Error> {
296        // Opening owns this budget until the index is complete. Errors and
297        // cancellation discard all charges made by the opening helpers.
298        let mut budget = Budget::new(policy.limits);
299        let mut buffer = DirectoryWindow::take();
300        let mut buffered = RecordReader::new(reader, 64 * 1024, &mut buffer.0);
301        let end =
302            CentralDirectory::read(&mut buffered, &mut budget, policy.comments.archive).await?;
303        let mut entries = end
304            .read_entries(&mut buffered, &mut budget, &policy)
305            .await?;
306
307        if entries.is_sorted_by_key(|entry| entry.directory().position()) {
308            if entries
309                .first()
310                .map_or(end.offset, |entry| entry.directory().position())
311                != 0
312            {
313                return Err(invalid(0, "unaccounted bytes before the first member"));
314            }
315
316            // Most directories follow physical order. Assign their boundaries
317            // in place, without a second allocation for the indexed entries.
318            let mut directory = entries.iter_mut().peekable();
319            while let Some(entry) = directory.next() {
320                entry.set_boundary(
321                    directory
322                        .peek()
323                        .map_or(end.offset, |next| next.directory().position()),
324                )?;
325            }
326        } else {
327            // APPNOTE 4.4.1.3 permits central entries out of physical order.
328            // Preserve directory order while assigning boundaries in physical order.
329            // Only local reads can establish exact coverage inside these spans.
330            let mut order: Vec<_> = (0..entries.len()).collect();
331            order.sort_unstable_by_key(|&index| entries[index].directory().position());
332            if order
333                .first()
334                .map_or(end.offset, |&index| entries[index].directory().position())
335                != 0
336            {
337                return Err(invalid(0, "unaccounted bytes before the first member"));
338            }
339
340            // The last entry already has the directory offset as its boundary.
341            // Keep the earliest directory-order error even though assignment
342            // proceeds in physical order.
343            let mut first_error = None;
344            for (&index, &next) in order.iter().zip(order.iter().skip(1)) {
345                let boundary = entries[next].directory().position();
346                if let Err(error) = entries[index].set_boundary(boundary)
347                    && first_error.as_ref().is_none_or(|(first, _)| index < *first)
348                {
349                    first_error = Some((index, error));
350                }
351            }
352            if let Some((_, error)) = first_error {
353                return Err(error);
354            }
355
356            check_destination_order(&entries).await?;
357        }
358
359        Ok(Self {
360            resolved: Vec::new(),
361            policy,
362            entries,
363            budget,
364            buffer: Vec::new(),
365        })
366    }
367
368    /// Checks one member's local header, extras and descriptor before exposing it.
369    ///
370    /// Successful resolutions are cached. This does not decode or check payload
371    /// contents. The source must be the immutable source used by [`Self::read`].
372    pub async fn entry<R: AsyncRead + AsyncSeek + Unpin>(
373        &mut self,
374        reader: &mut R,
375        index: usize,
376    ) -> Result<Option<Entry<'_>>, Error> {
377        let Some(indexed) = self.entries.get(index) else {
378            return Ok(None);
379        };
380
381        if self.resolved.is_empty() {
382            self.resolved.resize_with(self.entries.len(), || None);
383        }
384
385        let resolved = match &mut self.resolved[index] {
386            Some(resolved) => resolved,
387            slot => {
388                // Cover the fixed header, matching filename, and ZIP64 sizes
389                // without speculatively copying a large prefix of the payload.
390                let capacity = (size::LOCAL
391                    + indexed.directory().path().len()
392                    + extra::HEADER_SIZE
393                    + extra::ZIP64_LOCAL_SIZE)
394                    .min(4096);
395                let mut buffered = RecordReader::new(reader, capacity, &mut self.buffer);
396                // Failed or cancelled resolution must not charge the same metadata
397                // again on retry. Publish the cache and budget only after success.
398                let mut pending_budget = self.budget;
399                let resolved = indexed
400                    .read_local(&mut buffered, &mut pending_budget, &self.policy)
401                    .await?;
402                self.budget = pending_budget;
403                slot.insert(resolved)
404            }
405        };
406
407        Ok(Some(Entry { indexed, resolved }))
408    }
409
410    /// Checks every local header, descriptor, and kind, including unselected members.
411    ///
412    /// Success establishes complete, non-overlapping record coverage and
413    /// agreement of redundant and kind-specific metadata except timestamps
414    /// and Windows NT security descriptor sizes.
415    /// Payload sizes and CRCs still need to be verified when decoding.
416    /// Already checked members require no I/O.
417    pub async fn validate_all<R: AsyncRead + AsyncSeek + Unpin>(
418        &mut self,
419        reader: &mut R,
420    ) -> Result<(), Error> {
421        for index in 0..self.entries.len() {
422            self.entry(reader, index).await?;
423            tokio::task::consume_budget().await;
424        }
425
426        Ok(())
427    }
428}
429
430/// A ZIP archive's central directory's validated location and extent.
431struct CentralDirectory {
432    /// The absolute offset to the central directory, relative to the
433    /// start of the source.
434    offset: u64,
435    /// The overall size of the central directory in bytes.
436    ///
437    /// Note that this does not include the size of the EOCD or any other
438    /// trailing records that may follow the central directory.
439    size: u64,
440    /// The total number of central directory entries.
441    count: u64,
442}
443
444impl CentralDirectory {
445    /// Reads the central directory's location and extent from the end records.
446    ///
447    /// Validates its bounds and entry count, and charges directory and ZIP64 end
448    /// metadata before returning.
449    async fn read<R: AsyncRead + AsyncSeek + Unpin>(
450        reader: &mut RecordReader<'_, R>,
451        budget: &mut Budget,
452        archive_comment: CommentRule,
453    ) -> Result<Self, Error> {
454        let length = reader.length().await?;
455        budget.check_archive_size(length)?;
456        if length < size::END as u64 {
457            return Err(invalid(0, "missing end of central directory"));
458        }
459
460        // EOCD has a 16-bit comment length. Never search before this bounded tail.
461        let tail_size = length.min(size::END as u64 + u64::from(u16::MAX)) as usize;
462        let tail_start = length - tail_size as u64;
463        let tail = reader.read_slice(tail_start, tail_size, length).await?;
464
465        let (offset, end) = find_end(tail, tail_start)?;
466        let position = tail_start + offset as u64;
467        let comment = &tail[offset + size::END..];
468        // Readers such as Python's zipfile search backward for the last EOCD
469        // signature when there is a comment, even if its length is wrong.
470        if !comment.is_empty()
471            && let Some(shadow) = memmem::find(
472                &tail[offset + size::SIGNATURE..],
473                &signature::END.to_le_bytes(),
474            )
475        {
476            return Err(invalid(
477                position + (size::SIGNATURE + shadow) as u64,
478                "ambiguous end records",
479            ));
480        }
481        archive_comment.check(comment, None, position)?;
482
483        let disk = u16::from_le_bytes(array_at::<4, 2, _>(&end));
484        let directory_disk = u16::from_le_bytes(array_at::<6, 2, _>(&end));
485        let disk_count = u16::from_le_bytes(array_at::<8, 2, _>(&end));
486        let count = u16::from_le_bytes(array_at::<10, 2, _>(&end));
487        let size = u32::from_le_bytes(array_at::<12, 4, _>(&end));
488        let offset = u32::from_le_bytes(array_at::<16, 4, _>(&end));
489
490        let (directory, boundary) = if let Some((directory, boundary)) =
491            Self::read_zip64(reader, position, budget).await?
492        {
493            // Each classic field may carry its ZIP64 sentinel independently.
494            let agrees16 = |field: u16, value| field == u16::MAX || u64::from(field) == value;
495            let agrees32 = |field: u32, value| field == u32::MAX || u64::from(field) == value;
496            if !agrees16(disk, 0)
497                || !agrees16(directory_disk, 0)
498                || !agrees16(disk_count, directory.count)
499                || !agrees16(count, directory.count)
500                || !agrees32(size, directory.size)
501                || !agrees32(offset, directory.offset)
502            {
503                return Err(invalid(position, "classic and ZIP64 end records disagree"));
504            }
505            (directory, boundary)
506        } else {
507            if disk != 0 || directory_disk != 0 {
508                return Err(Error::Unsupported {
509                    position,
510                    feature: "multiple volumes",
511                });
512            }
513            if disk_count != count {
514                return Err(invalid(position, "entry counts disagree"));
515            }
516            // Without a ZIP64 locator, 0xffff is a literal entry count. The
517            // declared records must still fill the entire directory.
518            if size == u32::MAX || offset == u32::MAX {
519                return Err(invalid(position, "ZIP64 sentinel without locator"));
520            }
521
522            let directory = Self {
523                offset: u64::from(offset),
524                size: u64::from(size),
525                count: u64::from(count),
526            };
527            budget.check_entry_count(directory.count)?;
528            budget.charge_metadata(directory.size)?;
529            (directory, position)
530        };
531
532        if add(directory.offset, directory.size)? != boundary {
533            return Err(invalid(
534                directory.offset,
535                "central directory boundary mismatch",
536            ));
537        }
538
539        if directory.count > directory.size / size::CENTRAL as u64 {
540            return Err(invalid(
541                directory.offset,
542                "entry count exceeds directory capacity",
543            ));
544        }
545
546        Ok(directory)
547    }
548
549    /// Reads the entries from this checked directory and charges their output sizes.
550    async fn read_entries<R: AsyncRead + AsyncSeek + Unpin>(
551        &self,
552        reader: &mut RecordReader<'_, R>,
553        budget: &mut Budget,
554        policy: &IndexPolicy,
555    ) -> Result<Vec<IndexedEntry>, Error> {
556        let end = add(self.offset, self.size)?;
557        let mut position = self.offset;
558        // The entry count and directory size have already passed their budgets.
559        let mut entries = Vec::with_capacity(self.count as usize);
560
561        if self.size >= size::SIGNATURE as u64 {
562            let mut signature = [0; size::SIGNATURE];
563            reader.read_at(position, &mut signature, end).await?;
564            if u32::from_le_bytes(signature) == signature::ARCHIVE_EXTRA {
565                return Err(Error::Unsupported {
566                    position,
567                    feature: "archive extra data record",
568                });
569            }
570        }
571
572        let mut bytes = reader.buffered(position, end);
573        while entries.len() < self.count as usize {
574            match CentralDirectoryEntry::parse(bytes, position, budget, policy)? {
575                BufferedEntry::Complete(entry, length) => {
576                    entries.push(IndexedEntry::new(entry, self.offset)?);
577                    position += length as u64;
578                    bytes = &bytes[length..];
579                }
580                BufferedEntry::Incomplete(needed) => {
581                    // Yield between bounded read-ahead windows.
582                    tokio::task::yield_now().await;
583                    reader.read_slice(position, needed, end).await?;
584                    bytes = reader.buffered(position, end);
585                }
586            }
587        }
588
589        if position != end {
590            return Err(invalid(
591                position,
592                "unaccounted directory bytes or digital signature",
593            ));
594        }
595
596        Ok(entries)
597    }
598}
599
600/// Readers may visit members in directory or physical order. Both must visit
601/// repeated destinations in the same relative order.
602async fn check_destination_order(entries: &[IndexedEntry]) -> Result<(), Error> {
603    let mut last_offsets = HashMap::with_capacity(entries.len());
604    for entry in entries {
605        let directory = entry.directory();
606        let offset = directory.position();
607        if last_offsets
608            .insert(member_destination(directory.path()), offset)
609            .is_some_and(|previous| previous > offset)
610        {
611            return Err(invalid(
612                offset,
613                "duplicate destination order disagrees with local headers",
614            ));
615        }
616        tokio::task::consume_budget().await;
617    }
618    Ok(())
619}
620
621/// Ignore empty and `.` components and compare `..` literally.
622fn member_destination(path: &str) -> Cow<'_, str> {
623    let path = path.trim_end_matches('/');
624    if !path.split('/').any(|part| matches!(part, "" | ".")) {
625        return Cow::Borrowed(path);
626    }
627    let mut destination = String::with_capacity(path.len());
628    for part in path.split('/').filter(|part| !matches!(*part, "" | ".")) {
629        if !destination.is_empty() {
630            destination.push('/');
631        }
632        destination.push_str(part);
633    }
634    Cow::Owned(destination)
635}
636
637/// Scans the whole tail: a second EOCD reaching EOF is ambiguous even when the
638/// last 22 bytes already look like an end record.
639fn find_end(tail: &[u8], tail_start: u64) -> Result<(usize, [u8; size::END]), Error> {
640    const SIGNATURE: [u8; 4] = signature::END.to_le_bytes();
641    let mut candidate = None;
642    let mut scan = |bytes: &[u8], start: usize| {
643        for offset in memmem::find_iter(bytes, &SIGNATURE).map(|offset| start + offset) {
644            if let Some(header) = tail[offset..].first_chunk::<{ size::END }>()
645                && offset
646                    + size::END
647                    + usize::from(u16::from_le_bytes(array_at::<20, 2, _>(header)))
648                    == tail.len()
649                && candidate.replace((offset, *header)).is_some()
650            {
651                return Err(invalid(tail_start + offset as u64, "ambiguous end records"));
652            }
653        }
654        Ok(())
655    };
656
657    // Filter short blocks by the EOCD suffix, avoiding the common PK prefix of
658    // other ZIP records. The reduction permits vectorization without intrinsics.
659    let candidates = tail.len() - (size::END - 1);
660    let (blocks, remainder) = tail[2..2 + candidates].as_chunks::<64>();
661    for (ordinal, first) in blocks.iter().enumerate() {
662        let start = ordinal * 64;
663        let second = &tail[start + 3..start + 3 + 64];
664        let candidate = first
665            .iter()
666            .zip(second)
667            .fold(0, |found, (&first, &second)| {
668                found | (u8::from(first == SIGNATURE[2]) & u8::from(second == SIGNATURE[3]))
669            });
670        if candidate != 0 {
671            // Include the next three bytes for signatures crossing a block
672            // boundary. Each possible starting position is checked once.
673            scan(&tail[start..start + 64 + 3], start)?;
674        }
675    }
676    let start = blocks.len() * 64;
677    scan(&tail[start..start + remainder.len() + 3], start)?;
678
679    candidate.ok_or_else(|| {
680        invalid(
681            tail_start + tail.len() as u64,
682            "missing end record or trailing bytes",
683        )
684    })
685}
686
687impl CentralDirectory {
688    /// Reads the directory and the ZIP64 end record's position when a locator is present.
689    ///
690    /// Charges both the directory and this record to the metadata budget.
691    async fn read_zip64<R: AsyncRead + AsyncSeek + Unpin>(
692        reader: &mut RecordReader<'_, R>,
693        end_position: u64,
694        budget: &mut Budget,
695    ) -> Result<Option<(Self, u64)>, Error> {
696        let Some(locator_position) = end_position.checked_sub(size::ZIP64_LOCATOR as u64) else {
697            return Ok(None);
698        };
699        let mut locator = [0; size::ZIP64_LOCATOR];
700        reader
701            .read_at(locator_position, &mut locator, end_position)
702            .await?;
703        if u32::from_le_bytes(array_at::<0, 4, _>(&locator)) != signature::ZIP64_LOCATOR {
704            return Ok(None);
705        }
706
707        if u32::from_le_bytes(array_at::<4, 4, _>(&locator)) != 0
708            || u32::from_le_bytes(array_at::<16, 4, _>(&locator)) != 1
709        {
710            return Err(Error::Unsupported {
711                position: locator_position,
712                feature: "multiple volumes",
713            });
714        }
715
716        let position = u64::from_le_bytes(array_at::<8, 8, _>(&locator));
717        let mut header = [0; size::ZIP64_END];
718        reader
719            .read_at(position, &mut header, locator_position)
720            .await?;
721        if u32::from_le_bytes(array_at::<0, 4, _>(&header)) != signature::ZIP64_END {
722            return Err(invalid(position, "invalid ZIP64 end signature"));
723        }
724
725        let end_size = u64::from_le_bytes(array_at::<4, 8, _>(&header));
726        if end_size < size::ZIP64_END_BODY as u64
727            || add(position, add(size::ZIP64_END_PREFIX as u64, end_size)?)? != locator_position
728        {
729            return Err(invalid(position, "invalid ZIP64 end length"));
730        }
731
732        let version_needed = u16::from_le_bytes(array_at::<14, 2, _>(&header));
733        if version_needed >= version::ZIP64_V2 {
734            return Err(Error::Unsupported {
735                position,
736                feature: "ZIP64 version-2 directory",
737            });
738        }
739        if version_needed != version::ZIP64 {
740            return Err(invalid(position, "invalid ZIP64 extraction version"));
741        }
742        if end_size != size::ZIP64_END_BODY as u64 {
743            return Err(Error::Unsupported {
744                position,
745                feature: "ZIP64 extensible data sector",
746            });
747        }
748
749        if u32::from_le_bytes(array_at::<16, 4, _>(&header)) != 0
750            || u32::from_le_bytes(array_at::<20, 4, _>(&header)) != 0
751        {
752            return Err(Error::Unsupported {
753                position,
754                feature: "multiple volumes",
755            });
756        }
757
758        let count = u64::from_le_bytes(array_at::<32, 8, _>(&header));
759        if u64::from_le_bytes(array_at::<24, 8, _>(&header)) != count {
760            return Err(invalid(position, "ZIP64 entry counts disagree"));
761        }
762
763        let directory = Self {
764            offset: u64::from_le_bytes(array_at::<48, 8, _>(&header)),
765            size: u64::from_le_bytes(array_at::<40, 8, _>(&header)),
766            count,
767        };
768        budget.check_entry_count(count)?;
769        budget.charge_metadata(directory.size)?;
770        budget.charge_metadata(locator_position - position)?;
771
772        Ok(Some((directory, position)))
773    }
774}