zip-framing 0.0.17

Strict, bounded framing for seekable ZIP archives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
use std::{borrow::Cow, cell::RefCell, collections::HashMap, mem};

use memchr::memmem;
use tokio::io::{AsyncRead, AsyncSeek};

use crate::{
    Budget, Error, ExtraFieldPolicy, IndexPolicyViolation, Limits, add,
    constants::{extra, signature, size, version},
    invalid, policy_violation,
    record::{GeneralPurposeFlags, RecordReader, array_at},
};

mod entry;

use entry::{BufferedEntry, ResolvedMember};
pub use entry::{CentralDirectoryEntry, Entry, IndexedEntry};

thread_local! {
    static DIRECTORY_WINDOW: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}

/// Owns its window across awaits, returning a bounded allocation for later opens.
struct DirectoryWindow(Vec<u8>);

impl DirectoryWindow {
    fn take() -> Self {
        Self(
            DIRECTORY_WINDOW
                .try_with(|window| {
                    window
                        .try_borrow_mut()
                        .map(|mut window| mem::take(&mut *window))
                        .unwrap_or_default()
                })
                .unwrap_or_default(),
        )
    }
}

impl Drop for DirectoryWindow {
    fn drop(&mut self) {
        // Variable records can require a larger window; retain only the usual
        // bounded end-record scan allocation, at most one per thread.
        if self.0.capacity() <= size::END + usize::from(u16::MAX) {
            self.0.clear();
            let _ = DIRECTORY_WINDOW.try_with(|window| {
                if let Ok(mut window) = window.try_borrow_mut()
                    && window.capacity() < self.0.capacity()
                {
                    *window = mem::take(&mut self.0);
                }
            });
        }
    }
}

/// Which ZIP comment bytes the reader accepts. Empty comments are always accepted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CommentRule {
    /// Reject nonempty comments.
    Reject,
    /// Accept only ASCII bytes.
    AllowAscii,
    /// Accept UTF-8. Non-ASCII member comments must set the UTF-8 flag (bit 11).
    AllowUtf8,
    /// Accept arbitrary bytes. Member comments with bit 11 set must still be UTF-8.
    AllowAll,
}

impl CommentRule {
    fn check(
        self,
        bytes: &[u8],
        member_flags: Option<GeneralPurposeFlags>,
        position: u64,
    ) -> Result<(), Error> {
        if bytes.is_empty() {
            return Ok(());
        }
        let utf8 = member_flags.map(|flags| flags.contains(GeneralPurposeFlags::UTF8));
        if utf8 == Some(true) && str::from_utf8(bytes).is_err() {
            return Err(invalid(position, "non-UTF-8 comment"));
        }

        let accepted = match (self, utf8) {
            (Self::Reject, _) => false,
            (Self::AllowAscii, _) | (Self::AllowUtf8, Some(false)) => bytes.is_ascii(),
            (Self::AllowUtf8, None) => str::from_utf8(bytes).is_ok(),
            (Self::AllowUtf8, Some(true)) | (Self::AllowAll, _) => true,
        };
        if accepted {
            return Ok(());
        }

        let violation = if member_flags.is_some() {
            IndexPolicyViolation::MemberComment { rule: self }
        } else {
            IndexPolicyViolation::ArchiveComment { rule: self }
        };
        Err(policy_violation(position, violation))
    }
}

/// Which comments the reader accepts in member and end records.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CommentPolicy {
    /// Comments in central directory entries. Defaults to [`CommentRule::Reject`].
    pub per_member: CommentRule,
    /// Comment in the end record. Defaults to [`CommentRule::AllowAscii`].
    pub archive: CommentRule,
}

impl Default for CommentPolicy {
    fn default() -> Self {
        Self {
            per_member: CommentRule::Reject,
            archive: CommentRule::AllowAscii,
        }
    }
}

/// Controls resource limits and compatibility when indexing a ZIP archive.
#[derive(Clone, Copy, Debug)]
#[must_use]
pub struct IndexPolicy {
    limits: Limits,
    extra_fields: ExtraFieldPolicy,
    comments: CommentPolicy,
    allow_redundant_zip64_sizes: bool,
    allow_stored_data_descriptors: bool,
    allow_empty_deflate_streams: bool,
    allow_incompatible_extraction_versions: bool,
    allow_ambiguous_symlink_modes: bool,
    allow_backslashes: bool,
}

impl Default for IndexPolicy {
    fn default() -> Self {
        Self {
            limits: Limits::default(),
            extra_fields: ExtraFieldPolicy::default(),
            comments: CommentPolicy::default(),
            allow_redundant_zip64_sizes: false,
            allow_stored_data_descriptors: false,
            allow_empty_deflate_streams: true,
            allow_incompatible_extraction_versions: false,
            allow_ambiguous_symlink_modes: false,
            allow_backslashes: false,
        }
    }
}

impl IndexPolicy {
    /// Sets the resource limits for the archive.
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Sets the extra fields accepted in both headers. Defaults to [`ExtraFieldPolicy::Zip64Only`].
    pub fn extra_field_policy(mut self, policy: ExtraFieldPolicy) -> Self {
        self.extra_fields = policy;
        self
    }

    /// Sets the rules for member and archive comments.
    pub fn comment_policy(mut self, policy: CommentPolicy) -> Self {
        self.comments = policy;
        self
    }

    /// Allows a local ZIP64 extra that repeats both 32-bit sizes on a member
    /// without a data descriptor. Disabled by default.
    ///
    /// [Older CPython versions] wrote these extras with `force_zip64` even
    /// when the extraction version was below 4.5. Both sizes must match
    /// exactly.
    ///
    /// [Older CPython versions]: https://github.com/python/cpython/issues/103861
    pub fn allow_redundant_zip64_sizes(mut self, allow: bool) -> Self {
        self.allow_redundant_zip64_sizes = allow;
        self
    }

    /// Allows Stored members with data descriptors (bit 3). Disabled by default.
    pub fn allow_stored_data_descriptors(mut self, allow: bool) -> Self {
        self.allow_stored_data_descriptors = allow;
        self
    }

    /// Allows empty DEFLATE streams. Enabled by default.
    ///
    /// Disable to require zero compressed bytes for empty DEFLATE members
    /// under [APPNOTE §4.3.8].
    ///
    /// [APPNOTE §4.3.8]: https://pkwaredownloads.blob.core.windows.net/pkware-general/Documentation/APPNOTE-6.3.9.TXT
    pub fn allow_empty_deflate_streams(mut self, allow: bool) -> Self {
        self.allow_empty_deflate_streams = allow;
        self
    }

    /// Allows local and central member headers to declare an extraction version
    /// below the minimum for their compression method, ZIP64 fields, or member
    /// kind (APPNOTE 4.4.3.2). Disabled by default. Versions above 4.5
    /// remain unsupported.
    ///
    /// Info-ZIP 3.0 can declare version 1.0 for directories, which require 2.0.
    /// Go's [`zip.Writer.CreateRaw`](https://pkg.go.dev/archive/zip#Writer.CreateRaw)
    /// can write version 0 if the caller leaves `FileHeader.ReaderVersion` unset.
    pub fn allow_incompatible_extraction_versions(mut self, allow: bool) -> Self {
        self.allow_incompatible_extraction_versions = allow;
        self
    }

    /// Allows Unix symlink mode bits from non-Unix creator systems. Disabled by default.
    /// When enabled, Darwin uses Unix modes. Other creators use their usual attributes.
    pub fn allow_ambiguous_symlink_modes(mut self, allow: bool) -> Self {
        self.allow_ambiguous_symlink_modes = allow;
        self
    }

    /// Allows literal backslashes in member names. Disabled by default.
    ///
    /// Member names are returned verbatim. Only `/` is a path separator.
    pub fn allow_backslashes(mut self, allow: bool) -> Self {
        self.allow_backslashes = allow;
        self
    }

    fn check_version(&self, declared: u16, minimum: u16, position: u64) -> Result<(), Error> {
        if declared < minimum && !self.allow_incompatible_extraction_versions {
            return Err(policy_violation(
                position,
                IndexPolicyViolation::IncompatibleExtractionVersion { declared, minimum },
            ));
        }
        Ok(())
    }
}

/// A ZIP member index.
///
/// This is constructed from the central directory, with referenced
/// local file entries being resolved lazily upon access through
/// [`Self::entry`].
#[derive(Debug)]
pub struct Index {
    /// The indexed members, in central directory order.
    entries: Vec<IndexedEntry>,
    /// Cached resolutions in directory order, allocated on first access.
    resolved: Vec<Option<ResolvedMember>>,
    /// Policy used to validate local records on member access.
    policy: IndexPolicy,
    /// The parse budget. This is debited against when parsing local
    /// file entries and reconciling local/central metadata.
    budget: Budget,
    /// Scratch space for local records, cleared between resolutions.
    buffer: Vec<u8>,
}

impl Index {
    /// Borrows indexed members, without fetching local records or payloads.
    pub fn entries(&self) -> &[IndexedEntry] {
        &self.entries
    }

    /// Returns a previously checked entry by index, without performing I/O.
    ///
    /// Returns [`None`] if the index is out of bounds or the member is unresolved.
    pub fn resolved(&self, index: usize) -> Option<Entry<'_>> {
        Some(Entry {
            indexed: self.entries.get(index)?,
            resolved: self.resolved.get(index)?.as_ref()?,
        })
    }

    /// Indexes the directory with the default [`IndexPolicy`].
    ///
    /// Local headers and descriptors are checked by [`Self::entry`] on access,
    /// or by [`Self::validate_all`]. The source must remain unchanged and be the
    /// same source passed to subsequent operations. A cancelled read may leave
    /// its cursor anywhere; another call restarts from the end.
    pub async fn read<R: AsyncRead + AsyncSeek + Unpin>(reader: &mut R) -> Result<Self, Error> {
        Self::read_with_policy(reader, IndexPolicy::default()).await
    }

    /// Indexes the directory with the supplied policy and checks bounds derivable from its records.
    ///
    /// The policy also applies when checking local records. See [`Self::read`]
    /// for requirements on the source.
    pub async fn read_with_policy<R: AsyncRead + AsyncSeek + Unpin>(
        reader: &mut R,
        policy: IndexPolicy,
    ) -> Result<Self, Error> {
        // Opening owns this budget until the index is complete. Errors and
        // cancellation discard all charges made by the opening helpers.
        let mut budget = Budget::new(policy.limits);
        let mut buffer = DirectoryWindow::take();
        let mut buffered = RecordReader::new(reader, 64 * 1024, &mut buffer.0);
        let end =
            CentralDirectory::read(&mut buffered, &mut budget, policy.comments.archive).await?;
        let mut entries = end
            .read_entries(&mut buffered, &mut budget, &policy)
            .await?;

        if entries.is_sorted_by_key(|entry| entry.directory().position()) {
            if entries
                .first()
                .map_or(end.offset, |entry| entry.directory().position())
                != 0
            {
                return Err(invalid(0, "unaccounted bytes before the first member"));
            }

            // Most directories follow physical order. Assign their boundaries
            // in place, without a second allocation for the indexed entries.
            let mut directory = entries.iter_mut().peekable();
            while let Some(entry) = directory.next() {
                entry.set_boundary(
                    directory
                        .peek()
                        .map_or(end.offset, |next| next.directory().position()),
                )?;
            }
        } else {
            // APPNOTE 4.4.1.3 permits central entries out of physical order.
            // Preserve directory order while assigning boundaries in physical order.
            // Only local reads can establish exact coverage inside these spans.
            let mut order: Vec<_> = (0..entries.len()).collect();
            order.sort_unstable_by_key(|&index| entries[index].directory().position());
            if order
                .first()
                .map_or(end.offset, |&index| entries[index].directory().position())
                != 0
            {
                return Err(invalid(0, "unaccounted bytes before the first member"));
            }

            // The last entry already has the directory offset as its boundary.
            // Keep the earliest directory-order error even though assignment
            // proceeds in physical order.
            let mut first_error = None;
            for (&index, &next) in order.iter().zip(order.iter().skip(1)) {
                let boundary = entries[next].directory().position();
                if let Err(error) = entries[index].set_boundary(boundary)
                    && first_error.as_ref().is_none_or(|(first, _)| index < *first)
                {
                    first_error = Some((index, error));
                }
            }
            if let Some((_, error)) = first_error {
                return Err(error);
            }

            check_destination_order(&entries).await?;
        }

        Ok(Self {
            resolved: Vec::new(),
            policy,
            entries,
            budget,
            buffer: Vec::new(),
        })
    }

    /// Checks one member's local header, extras and descriptor before exposing it.
    ///
    /// Successful resolutions are cached. This does not decode or check payload
    /// contents. The source must be the immutable source used by [`Self::read`].
    pub async fn entry<R: AsyncRead + AsyncSeek + Unpin>(
        &mut self,
        reader: &mut R,
        index: usize,
    ) -> Result<Option<Entry<'_>>, Error> {
        let Some(indexed) = self.entries.get(index) else {
            return Ok(None);
        };

        if self.resolved.is_empty() {
            self.resolved.resize_with(self.entries.len(), || None);
        }

        let resolved = match &mut self.resolved[index] {
            Some(resolved) => resolved,
            slot => {
                // Cover the fixed header, matching filename, and ZIP64 sizes
                // without speculatively copying a large prefix of the payload.
                let capacity = (size::LOCAL
                    + indexed.directory().path().len()
                    + extra::HEADER_SIZE
                    + extra::ZIP64_LOCAL_SIZE)
                    .min(4096);
                let mut buffered = RecordReader::new(reader, capacity, &mut self.buffer);
                // Failed or cancelled resolution must not charge the same metadata
                // again on retry. Publish the cache and budget only after success.
                let mut pending_budget = self.budget;
                let resolved = indexed
                    .read_local(&mut buffered, &mut pending_budget, &self.policy)
                    .await?;
                self.budget = pending_budget;
                slot.insert(resolved)
            }
        };

        Ok(Some(Entry { indexed, resolved }))
    }

    /// Checks every local header, descriptor, and kind, including unselected members.
    ///
    /// Success establishes complete, non-overlapping record coverage and
    /// agreement of redundant and kind-specific metadata except timestamps
    /// and Windows NT security descriptor sizes.
    /// Payload sizes and CRCs still need to be verified when decoding.
    /// Already checked members require no I/O.
    pub async fn validate_all<R: AsyncRead + AsyncSeek + Unpin>(
        &mut self,
        reader: &mut R,
    ) -> Result<(), Error> {
        for index in 0..self.entries.len() {
            self.entry(reader, index).await?;
            tokio::task::consume_budget().await;
        }

        Ok(())
    }
}

/// A ZIP archive's central directory's validated location and extent.
struct CentralDirectory {
    /// The absolute offset to the central directory, relative to the
    /// start of the source.
    offset: u64,
    /// The overall size of the central directory in bytes.
    ///
    /// Note that this does not include the size of the EOCD or any other
    /// trailing records that may follow the central directory.
    size: u64,
    /// The total number of central directory entries.
    count: u64,
}

impl CentralDirectory {
    /// Reads the central directory's location and extent from the end records.
    ///
    /// Validates its bounds and entry count, and charges directory and ZIP64 end
    /// metadata before returning.
    async fn read<R: AsyncRead + AsyncSeek + Unpin>(
        reader: &mut RecordReader<'_, R>,
        budget: &mut Budget,
        archive_comment: CommentRule,
    ) -> Result<Self, Error> {
        let length = reader.length().await?;
        budget.check_archive_size(length)?;
        if length < size::END as u64 {
            return Err(invalid(0, "missing end of central directory"));
        }

        // EOCD has a 16-bit comment length. Never search before this bounded tail.
        let tail_size = length.min(size::END as u64 + u64::from(u16::MAX)) as usize;
        let tail_start = length - tail_size as u64;
        let tail = reader.read_slice(tail_start, tail_size, length).await?;

        let (offset, end) = find_end(tail, tail_start)?;
        let position = tail_start + offset as u64;
        let comment = &tail[offset + size::END..];
        // Readers such as Python's zipfile search backward for the last EOCD
        // signature when there is a comment, even if its length is wrong.
        if !comment.is_empty()
            && let Some(shadow) = memmem::find(
                &tail[offset + size::SIGNATURE..],
                &signature::END.to_le_bytes(),
            )
        {
            return Err(invalid(
                position + (size::SIGNATURE + shadow) as u64,
                "ambiguous end records",
            ));
        }
        archive_comment.check(comment, None, position)?;

        let disk = u16::from_le_bytes(array_at::<4, 2, _>(&end));
        let directory_disk = u16::from_le_bytes(array_at::<6, 2, _>(&end));
        let disk_count = u16::from_le_bytes(array_at::<8, 2, _>(&end));
        let count = u16::from_le_bytes(array_at::<10, 2, _>(&end));
        let size = u32::from_le_bytes(array_at::<12, 4, _>(&end));
        let offset = u32::from_le_bytes(array_at::<16, 4, _>(&end));

        let (directory, boundary) = if let Some((directory, boundary)) =
            Self::read_zip64(reader, position, budget).await?
        {
            // Each classic field may carry its ZIP64 sentinel independently.
            let agrees16 = |field: u16, value| field == u16::MAX || u64::from(field) == value;
            let agrees32 = |field: u32, value| field == u32::MAX || u64::from(field) == value;
            if !agrees16(disk, 0)
                || !agrees16(directory_disk, 0)
                || !agrees16(disk_count, directory.count)
                || !agrees16(count, directory.count)
                || !agrees32(size, directory.size)
                || !agrees32(offset, directory.offset)
            {
                return Err(invalid(position, "classic and ZIP64 end records disagree"));
            }
            (directory, boundary)
        } else {
            if disk != 0 || directory_disk != 0 {
                return Err(Error::Unsupported {
                    position,
                    feature: "multiple volumes",
                });
            }
            if disk_count != count {
                return Err(invalid(position, "entry counts disagree"));
            }
            // Without a ZIP64 locator, 0xffff is a literal entry count. The
            // declared records must still fill the entire directory.
            if size == u32::MAX || offset == u32::MAX {
                return Err(invalid(position, "ZIP64 sentinel without locator"));
            }

            let directory = Self {
                offset: u64::from(offset),
                size: u64::from(size),
                count: u64::from(count),
            };
            budget.check_entry_count(directory.count)?;
            budget.charge_metadata(directory.size)?;
            (directory, position)
        };

        if add(directory.offset, directory.size)? != boundary {
            return Err(invalid(
                directory.offset,
                "central directory boundary mismatch",
            ));
        }

        if directory.count > directory.size / size::CENTRAL as u64 {
            return Err(invalid(
                directory.offset,
                "entry count exceeds directory capacity",
            ));
        }

        Ok(directory)
    }

    /// Reads the entries from this checked directory and charges their output sizes.
    async fn read_entries<R: AsyncRead + AsyncSeek + Unpin>(
        &self,
        reader: &mut RecordReader<'_, R>,
        budget: &mut Budget,
        policy: &IndexPolicy,
    ) -> Result<Vec<IndexedEntry>, Error> {
        let end = add(self.offset, self.size)?;
        let mut position = self.offset;
        // The entry count and directory size have already passed their budgets.
        let mut entries = Vec::with_capacity(self.count as usize);

        if self.size >= size::SIGNATURE as u64 {
            let mut signature = [0; size::SIGNATURE];
            reader.read_at(position, &mut signature, end).await?;
            if u32::from_le_bytes(signature) == signature::ARCHIVE_EXTRA {
                return Err(Error::Unsupported {
                    position,
                    feature: "archive extra data record",
                });
            }
        }

        let mut bytes = reader.buffered(position, end);
        while entries.len() < self.count as usize {
            match CentralDirectoryEntry::parse(bytes, position, budget, policy)? {
                BufferedEntry::Complete(entry, length) => {
                    entries.push(IndexedEntry::new(entry, self.offset)?);
                    position += length as u64;
                    bytes = &bytes[length..];
                }
                BufferedEntry::Incomplete(needed) => {
                    // Yield between bounded read-ahead windows.
                    tokio::task::yield_now().await;
                    reader.read_slice(position, needed, end).await?;
                    bytes = reader.buffered(position, end);
                }
            }
        }

        if position != end {
            return Err(invalid(
                position,
                "unaccounted directory bytes or digital signature",
            ));
        }

        Ok(entries)
    }
}

/// Readers may visit members in directory or physical order. Both must visit
/// repeated destinations in the same relative order.
async fn check_destination_order(entries: &[IndexedEntry]) -> Result<(), Error> {
    let mut last_offsets = HashMap::with_capacity(entries.len());
    for entry in entries {
        let directory = entry.directory();
        let offset = directory.position();
        if last_offsets
            .insert(member_destination(directory.path()), offset)
            .is_some_and(|previous| previous > offset)
        {
            return Err(invalid(
                offset,
                "duplicate destination order disagrees with local headers",
            ));
        }
        tokio::task::consume_budget().await;
    }
    Ok(())
}

/// Ignore empty and `.` components and compare `..` literally.
fn member_destination(path: &str) -> Cow<'_, str> {
    let path = path.trim_end_matches('/');
    if !path.split('/').any(|part| matches!(part, "" | ".")) {
        return Cow::Borrowed(path);
    }
    let mut destination = String::with_capacity(path.len());
    for part in path.split('/').filter(|part| !matches!(*part, "" | ".")) {
        if !destination.is_empty() {
            destination.push('/');
        }
        destination.push_str(part);
    }
    Cow::Owned(destination)
}

/// Scans the whole tail: a second EOCD reaching EOF is ambiguous even when the
/// last 22 bytes already look like an end record.
fn find_end(tail: &[u8], tail_start: u64) -> Result<(usize, [u8; size::END]), Error> {
    const SIGNATURE: [u8; 4] = signature::END.to_le_bytes();
    let mut candidate = None;
    let mut scan = |bytes: &[u8], start: usize| {
        for offset in memmem::find_iter(bytes, &SIGNATURE).map(|offset| start + offset) {
            if let Some(header) = tail[offset..].first_chunk::<{ size::END }>()
                && offset
                    + size::END
                    + usize::from(u16::from_le_bytes(array_at::<20, 2, _>(header)))
                    == tail.len()
                && candidate.replace((offset, *header)).is_some()
            {
                return Err(invalid(tail_start + offset as u64, "ambiguous end records"));
            }
        }
        Ok(())
    };

    // Filter short blocks by the EOCD suffix, avoiding the common PK prefix of
    // other ZIP records. The reduction permits vectorization without intrinsics.
    let candidates = tail.len() - (size::END - 1);
    let (blocks, remainder) = tail[2..2 + candidates].as_chunks::<64>();
    for (ordinal, first) in blocks.iter().enumerate() {
        let start = ordinal * 64;
        let second = &tail[start + 3..start + 3 + 64];
        let candidate = first
            .iter()
            .zip(second)
            .fold(0, |found, (&first, &second)| {
                found | (u8::from(first == SIGNATURE[2]) & u8::from(second == SIGNATURE[3]))
            });
        if candidate != 0 {
            // Include the next three bytes for signatures crossing a block
            // boundary. Each possible starting position is checked once.
            scan(&tail[start..start + 64 + 3], start)?;
        }
    }
    let start = blocks.len() * 64;
    scan(&tail[start..start + remainder.len() + 3], start)?;

    candidate.ok_or_else(|| {
        invalid(
            tail_start + tail.len() as u64,
            "missing end record or trailing bytes",
        )
    })
}

impl CentralDirectory {
    /// Reads the directory and the ZIP64 end record's position when a locator is present.
    ///
    /// Charges both the directory and this record to the metadata budget.
    async fn read_zip64<R: AsyncRead + AsyncSeek + Unpin>(
        reader: &mut RecordReader<'_, R>,
        end_position: u64,
        budget: &mut Budget,
    ) -> Result<Option<(Self, u64)>, Error> {
        let Some(locator_position) = end_position.checked_sub(size::ZIP64_LOCATOR as u64) else {
            return Ok(None);
        };
        let mut locator = [0; size::ZIP64_LOCATOR];
        reader
            .read_at(locator_position, &mut locator, end_position)
            .await?;
        if u32::from_le_bytes(array_at::<0, 4, _>(&locator)) != signature::ZIP64_LOCATOR {
            return Ok(None);
        }

        if u32::from_le_bytes(array_at::<4, 4, _>(&locator)) != 0
            || u32::from_le_bytes(array_at::<16, 4, _>(&locator)) != 1
        {
            return Err(Error::Unsupported {
                position: locator_position,
                feature: "multiple volumes",
            });
        }

        let position = u64::from_le_bytes(array_at::<8, 8, _>(&locator));
        let mut header = [0; size::ZIP64_END];
        reader
            .read_at(position, &mut header, locator_position)
            .await?;
        if u32::from_le_bytes(array_at::<0, 4, _>(&header)) != signature::ZIP64_END {
            return Err(invalid(position, "invalid ZIP64 end signature"));
        }

        let end_size = u64::from_le_bytes(array_at::<4, 8, _>(&header));
        if end_size < size::ZIP64_END_BODY as u64
            || add(position, add(size::ZIP64_END_PREFIX as u64, end_size)?)? != locator_position
        {
            return Err(invalid(position, "invalid ZIP64 end length"));
        }

        let version_needed = u16::from_le_bytes(array_at::<14, 2, _>(&header));
        if version_needed >= version::ZIP64_V2 {
            return Err(Error::Unsupported {
                position,
                feature: "ZIP64 version-2 directory",
            });
        }
        if version_needed != version::ZIP64 {
            return Err(invalid(position, "invalid ZIP64 extraction version"));
        }
        if end_size != size::ZIP64_END_BODY as u64 {
            return Err(Error::Unsupported {
                position,
                feature: "ZIP64 extensible data sector",
            });
        }

        if u32::from_le_bytes(array_at::<16, 4, _>(&header)) != 0
            || u32::from_le_bytes(array_at::<20, 4, _>(&header)) != 0
        {
            return Err(Error::Unsupported {
                position,
                feature: "multiple volumes",
            });
        }

        let count = u64::from_le_bytes(array_at::<32, 8, _>(&header));
        if u64::from_le_bytes(array_at::<24, 8, _>(&header)) != count {
            return Err(invalid(position, "ZIP64 entry counts disagree"));
        }

        let directory = Self {
            offset: u64::from_le_bytes(array_at::<48, 8, _>(&header)),
            size: u64::from_le_bytes(array_at::<40, 8, _>(&header)),
            count,
        };
        budget.check_entry_count(count)?;
        budget.charge_metadata(directory.size)?;
        budget.charge_metadata(locator_position - position)?;

        Ok(Some((directory, position)))
    }
}