ignition-core 1.6.8

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! The read archive of a Windows deploy read (quick 261105-dl1).
//!
//! A Windows OpenSSH sftp server costs about 0.37 s per `get`, so a read
//! that fetched each listed file with its own `get` took about 88 minutes at
//! production shape (14,270 files). A Windows read therefore fetches its
//! files as one archive: [`render_list`] writes the exact list the listing
//! produced, the host zips exactly those files ([`winps::BUNDLE`]), one sftp
//! `get` downloads the archive, and [`extract`] unpacks it into the read's
//! private download dir. The listing is never redone on the host: the list is
//! uploaded, and BUNDLE checks its SHA-256 before it reads a name from it.
//!
//! ## Threat model
//!
//! The host controls every byte of the archive: entry names, types, flags,
//! declared sizes, the compressed data and the framing. Nothing in it is
//! trusted until [`extract`] has checked it, in this order:
//!
//! 1. Framing: the archive is a zip the crate can open, with no data before
//!    its first entry, and its central directory holds exactly as many
//!    records as the crate reports, no name twice (the crate keys entries by
//!    name and silently keeps one of two records that share it).
//! 2. Every central-directory record, before any byte is inflated: the name
//!    rules (UTF-8, no backslash, not absolute, not a directory entry, no
//!    drive or stream `:`, no empty, `.` or `..` component), a regular-file
//!    type, not encrypted, Stored or Deflated.
//! 3. Membership both ways: no entry that was not listed, then no listed file
//!    missing from the archive.
//! 4. Every declared size equals the listed size.
//! 5. Inflation: each entry is copied through a limit of its listed size plus
//!    one byte, and the running total may not pass the listed total plus the
//!    slack, so a zip bomb stops at the listed bytes.
//!
//! A file is created only below the destination, from the listed name's own
//! components (which passed the listing's name gates), with `create_new`. The
//! caller then runs the same final check as the per-file path
//! (`verify_download`: listed against actual, exact sizes, hashes).
//!
//! [`winps::BUNDLE`]: super::winps::BUNDLE

use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;

use super::READ_MAX_ENTRIES;

/// The uploaded list's name in the staging dir.
pub const LIST_FILE: &str = "read.tsv";
/// The archive's name in the staging dir.
pub const ARCHIVE_FILE: &str = "read.zip";
/// Free bytes BUNDLE requires on the archive's drive beyond the archive's own
/// bound, so a read never fills the host's disk (a production master runs
/// near 88% full).
pub const STAGING_FREE_MARGIN: u64 = 256 * 1024 * 1024;

/// The `S_IFMT` mask and the regular-file type of a unix mode.
const S_IFMT: u32 = 0o170_000;
const S_IFREG: u32 = 0o100_000;
/// The "version made by" host of MS-DOS and Windows (APPNOTE 4.4.2).
const HOST_DOS: u8 = 0;

/// One file of a read archive: `{collection}/{rel}` with `/`, and its listed
/// size.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BundleFile {
    pub collection: String,
    /// Collection-relative path, `/`-separated.
    pub rel: String,
    pub size: u64,
}

impl BundleFile {
    /// The archive entry name.
    pub fn name(&self) -> String {
        format!("{}/{}", self.collection, self.rel)
    }
}

/// The list BUNDLE reads: one line per file in fetch order, `{size}` TAB
/// `{collection}/{rel}` LF, UTF-8, no header. A listed name holds no TAB or
/// LF (it passed `safe_remote_path`).
pub fn render_list(files: &[BundleFile]) -> Vec<u8> {
    let mut out = Vec::new();
    for file in files {
        out.extend_from_slice(file.size.to_string().as_bytes());
        out.push(b'\t');
        out.extend_from_slice(file.name().as_bytes());
        out.push(b'\n');
    }
    out
}

/// The largest archive a faithful host can build of `files`.
///
/// - Data: Deflate never grows a block by more than its stored-block framing
///   (5 bytes per 65,535) and an empty file is 2 bytes; `total / 64` covers
///   that with room to spare.
/// - Per entry: a 30-byte local header and a 46-byte central record, each
///   with the name, plus a Zip64 extra field in each (up to 32 bytes) and a
///   data descriptor (up to 24 bytes): `2 x name + 192` covers them.
/// - Once: the end record (22), the Zip64 end record and locator (76) and a
///   comment: 4,096.
pub fn archive_limit(files: &[BundleFile]) -> u64 {
    let total: u64 = files.iter().map(|f| f.size).sum();
    let per_entry: u64 = files.iter().map(|f| 2 * f.name().len() as u64 + 192).sum();
    total + total / 64 + per_entry + 4096
}

/// What the central-directory walk saw of one record.
struct Record {
    name: Vec<u8>,
    /// The high byte of "version made by": the host that wrote the entry.
    host: u8,
    external: u32,
    local_offset: u64,
}

/// Why a name from the archive cannot be used, by the module's name rules.
fn name_problem(raw: &[u8]) -> Option<&'static str> {
    let Ok(name) = std::str::from_utf8(raw) else {
        return Some("is not UTF-8");
    };
    if name.contains('\\') {
        Some("holds a backslash")
    } else if name.starts_with('/') {
        Some("is an absolute path")
    } else if name.ends_with('/') {
        Some("is a directory entry")
    } else if name.contains(':') {
        Some("names a drive or a stream")
    } else if name
        .split('/')
        .any(|c| c.is_empty() || c == "." || c == "..")
    {
        Some("has an empty, `.` or `..` component")
    } else {
        None
    }
}

fn shown(raw: &[u8]) -> String {
    format!("{:?}", String::from_utf8_lossy(raw))
}

/// Walk the central directory from `start` to the end of `file` (`len`
/// bytes): every record's name, host, external attributes and local header
/// offset, at most `READ_MAX_ENTRIES + 1` records. The records are read one
/// at a time through a buffer, so the walk reads only the records and one
/// buffer past them, whatever follows them in the file (quick 261105-cr1).
/// Every length is checked against the bytes present.
fn central_records(
    file: &mut (impl Read + Seek),
    start: u64,
    len: u64,
) -> Result<Vec<Record>, String> {
    let unreadable = |e: std::io::Error| format!("the read archive is not a readable zip ({e})");
    let cut_off =
        || "the read archive is not a readable zip (a central record is cut off)".to_string();
    if start > len {
        return Err(
            "the read archive is not a readable zip (its central directory is outside it)"
                .to_string(),
        );
    }
    file.seek(SeekFrom::Start(start)).map_err(unreadable)?;
    let mut reader = std::io::BufReader::with_capacity(64 * 1024, file.take(len - start));
    let mut records = Vec::new();
    let mut header = [0u8; 46];
    let mut tail = Vec::new();
    loop {
        // the walk ends at the first four bytes that are not a record
        // signature, or with fewer than four bytes left
        match reader.read_exact(&mut header[..4]) {
            Ok(()) => {}
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
            Err(e) => return Err(unreadable(e)),
        }
        if header[..4] != [0x50, 0x4b, 0x01, 0x02] {
            break;
        }
        if records.len() > READ_MAX_ENTRIES {
            return Err(format!(
                "the read archive holds more than {READ_MAX_ENTRIES} entries"
            ));
        }
        reader.read_exact(&mut header[4..]).map_err(|e| {
            if e.kind() == std::io::ErrorKind::UnexpectedEof {
                cut_off()
            } else {
                unreadable(e)
            }
        })?;
        let le16 = |at: usize| usize::from(u16::from_le_bytes([header[at], header[at + 1]]));
        let le32 = |at: usize| {
            u32::from_le_bytes([header[at], header[at + 1], header[at + 2], header[at + 3]])
        };
        let (name_len, extra_len) = (le16(28), le16(30));
        // name, extra field and comment: at most 3 x 65,535 bytes
        tail.resize(name_len + extra_len + le16(32), 0);
        reader.read_exact(&mut tail).map_err(|e| {
            if e.kind() == std::io::ErrorKind::UnexpectedEof {
                cut_off()
            } else {
                unreadable(e)
            }
        })?;
        let mut local_offset = u64::from(le32(42));
        if local_offset == u64::from(u32::MAX) {
            // the real offset is in the Zip64 extra field of the record
            local_offset = zip64_offset(&tail[name_len..name_len + extra_len], le32(24), le32(20))
                .ok_or("the read archive is not a readable zip (a Zip64 record is malformed)")?;
        }
        records.push(Record {
            name: tail[..name_len].to_vec(),
            host: header[5],
            external: le32(38),
            local_offset,
        });
    }
    Ok(records)
}

/// The local header offset in a Zip64 extended-information extra field
/// (`extra` of a central record whose 32-bit offset is `0xFFFFFFFF`). The
/// field holds, in order, only the values whose 32-bit slots are
/// `0xFFFFFFFF`: uncompressed size, compressed size, then the offset.
fn zip64_offset(extra: &[u8], uncompressed: u32, compressed: u32) -> Option<u64> {
    let mut at = 0usize;
    while at + 4 <= extra.len() {
        let id = u16::from_le_bytes([extra[at], extra[at + 1]]);
        let size = usize::from(u16::from_le_bytes([extra[at + 2], extra[at + 3]]));
        let body = extra.get(at + 4..at + 4 + size)?;
        if id == 0x0001 {
            let mut skip = 0usize;
            if uncompressed == u32::MAX {
                skip += 8;
            }
            if compressed == u32::MAX {
                skip += 8;
            }
            let value = body.get(skip..skip + 8)?;
            return Some(u64::from_le_bytes(value.try_into().ok()?));
        }
        at += 4 + size;
    }
    None
}

/// Extract the read archive at `archive` into `dest/<collection>/<rel>` for
/// exactly `files`, under the module's checks, and return the bytes written.
/// `slack` is how far past the listed total the inflated bytes may run in
/// total before extraction stops (the per-entry limit is exact).
pub fn extract(
    archive: &Path,
    files: &[BundleFile],
    dest: &Path,
    slack: u64,
) -> Result<u64, String> {
    let opened = std::fs::File::open(archive)
        .map_err(|e| format!("the read archive cannot be opened ({:?})", e.kind()))?;
    let len = opened
        .metadata()
        .map_err(|e| format!("the read archive cannot be inspected ({:?})", e.kind()))?
        .len();
    let mut walk = opened
        .try_clone()
        .map_err(|e| format!("the read archive cannot be opened ({:?})", e.kind()))?;
    let mut zip = zip::ZipArchive::new(opened)
        .map_err(|e| format!("the read archive is not a readable zip ({e})"))?;

    // 1. framing
    if zip.offset() != 0 {
        return Err("the read archive has data before its first entry".to_string());
    }
    let records = central_records(&mut walk, zip.central_directory_start(), len)?;
    let mut seen: BTreeSet<&[u8]> = BTreeSet::new();
    for record in &records {
        if !seen.insert(&record.name) {
            return Err(format!(
                "the read archive names {} twice",
                shown(&record.name)
            ));
        }
    }
    if records.len() != zip.len() {
        return Err(format!(
            "the read archive's central directory holds {} records for {} entries; an entry is named twice",
            records.len(),
            zip.len()
        ));
    }
    if records.iter().map(|r| r.local_offset).min().unwrap_or(0) != 0 {
        return Err("the read archive has data before its first entry".to_string());
    }
    let by_name: BTreeMap<&[u8], &Record> =
        records.iter().map(|r| (r.name.as_slice(), r)).collect();

    // 2. every record: name, type, encryption, method; nothing inflated
    let mut names: Vec<Vec<u8>> = Vec::with_capacity(zip.len());
    for index in 0..zip.len() {
        let entry = zip
            .by_index_raw(index)
            .map_err(|e| format!("the read archive is not a readable zip ({e})"))?;
        let raw = entry.name_raw().to_vec();
        if let Some(why) = name_problem(&raw) {
            return Err(format!("the read archive entry {} {why}", shown(&raw)));
        }
        let record = by_name.get(raw.as_slice()).ok_or_else(|| {
            format!(
                "the read archive entry {} is not in its central directory",
                shown(&raw)
            )
        })?;
        let regular = match entry.unix_mode() {
            Some(mode) => mode & S_IFMT == S_IFREG,
            // .NET Framework (Windows PowerShell 5.1) writes MS-DOS-made
            // records with no attributes at all; the crate reports no mode
            None => record.host == HOST_DOS && record.external == 0,
        };
        if !regular {
            return Err(format!(
                "the read archive entry {} is not a regular file",
                shown(&raw)
            ));
        }
        if entry.encrypted() {
            return Err(format!(
                "the read archive entry {} is encrypted",
                shown(&raw)
            ));
        }
        if !matches!(
            entry.compression(),
            zip::CompressionMethod::Stored | zip::CompressionMethod::Deflated
        ) {
            return Err(format!(
                "the read archive entry {} uses an unsupported compression method",
                shown(&raw)
            ));
        }
        names.push(raw);
    }

    // 3. membership both ways
    let listed: BTreeMap<String, &BundleFile> = files.iter().map(|f| (f.name(), f)).collect();
    for raw in &names {
        let name = std::str::from_utf8(raw).unwrap_or_default();
        if !listed.contains_key(name) {
            return Err(format!(
                "the read archive holds {}, which was not listed",
                shown(raw)
            ));
        }
    }
    let present: BTreeSet<&str> = names
        .iter()
        .map(|raw| std::str::from_utf8(raw).unwrap_or_default())
        .collect();
    for file in files {
        if !present.contains(file.name().as_str()) {
            return Err(format!(
                "config/resources/{} was listed but is not in the read archive",
                file.name()
            ));
        }
    }

    // 4. declared sizes
    for (index, raw) in names.iter().enumerate() {
        let name = std::str::from_utf8(raw).unwrap_or_default();
        let file = listed[name];
        let declared = zip
            .by_index_raw(index)
            .map_err(|e| format!("the read archive is not a readable zip ({e})"))?
            .size();
        if declared != file.size {
            return Err(format!(
                "config/resources/{name} is {declared} bytes in the read archive but was listed as {}; it changed while it was read",
                file.size
            ));
        }
    }

    // 5. inflate, bounded per entry and in total
    let listed_total: u64 = files.iter().map(|f| f.size).sum();
    let limit = listed_total.saturating_add(slack);
    let mut written = 0u64;
    for (index, raw) in names.iter().enumerate() {
        let name = std::str::from_utf8(raw).unwrap_or_default();
        let file = listed[name];
        let target = file
            .rel
            .split('/')
            .fold(dest.join(&file.collection), |p, c| p.join(c));
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("cannot create a download dir ({:?})", e.kind()))?;
        }
        let mut out = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&target)
            .map_err(|e| format!("cannot write config/resources/{name} ({:?})", e.kind()))?;
        let entry = zip
            .by_index(index)
            .map_err(|e| format!("config/resources/{name} cannot be extracted ({e})"))?;
        let copied = copy_bounded(entry.take(file.size + 1), &mut out).map_err(|e| match e {
            Copy::Read(e) => format!("config/resources/{name} cannot be extracted ({e})"),
            Copy::Write(kind) => format!("cannot write config/resources/{name} ({kind:?})"),
        })?;
        if copied > file.size {
            return Err(format!(
                "config/resources/{name} inflates past its listed {} bytes",
                file.size
            ));
        }
        if copied != file.size {
            return Err(format!(
                "config/resources/{name} is {copied} bytes but was listed as {}; it changed while it was read",
                file.size
            ));
        }
        written += copied;
        if written > limit {
            return Err(format!(
                "the read archive inflates past the {limit} bytes listed for it"
            ));
        }
    }
    Ok(written)
}

/// Why a bounded copy stopped.
enum Copy {
    Read(std::io::Error),
    Write(std::io::ErrorKind),
}

/// Copy `from` into `to` until `from` ends; read and write errors apart.
fn copy_bounded(mut from: impl Read, to: &mut impl std::io::Write) -> Result<u64, Copy> {
    let mut buf = vec![0u8; 64 * 1024];
    let mut total = 0u64;
    loop {
        let n = match from.read(&mut buf) {
            Ok(0) => return Ok(total),
            Ok(n) => n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(Copy::Read(e)),
        };
        to.write_all(&buf[..n]).map_err(|e| Copy::Write(e.kind()))?;
        total += n as u64;
    }
}

/// The "version made by" host and the external attributes of every
/// central-directory record of the archive at `archive`, by entry name, for
/// a live check of what a real host builds (quick 261105-dl1).
pub fn record_attributes(archive: &Path) -> Result<Vec<(String, u8, u32)>, String> {
    let opened = std::fs::File::open(archive)
        .map_err(|e| format!("the read archive cannot be opened ({:?})", e.kind()))?;
    let len = opened
        .metadata()
        .map_err(|e| format!("the read archive cannot be inspected ({:?})", e.kind()))?
        .len();
    let mut walk = opened
        .try_clone()
        .map_err(|e| format!("the read archive cannot be opened ({:?})", e.kind()))?;
    let zip = zip::ZipArchive::new(opened)
        .map_err(|e| format!("the read archive is not a readable zip ({e})"))?;
    Ok(
        central_records(&mut walk, zip.central_directory_start(), len)?
            .into_iter()
            .map(|r| {
                (
                    String::from_utf8_lossy(&r.name).into_owned(),
                    r.host,
                    r.external,
                )
            })
            .collect(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn file(collection: &str, rel: &str, size: u64) -> BundleFile {
        BundleFile {
            collection: collection.to_string(),
            rel: rel.to_string(),
            size,
        }
    }

    #[test]
    fn render_list_is_size_tab_name_lf_in_order() {
        let files = [
            file("core", "ignition/a b,1/config.json", 10),
            file("production", "ignition/caf\u{e9}.json", 0),
            file("core", "ignition/b.json", 12_345_678_901),
        ];
        assert_eq!(
            render_list(&files),
            "10\tcore/ignition/a b,1/config.json\n0\tproduction/ignition/caf\u{e9}.json\n12345678901\tcore/ignition/b.json\n"
                .as_bytes()
        );
        assert!(render_list(&[]).is_empty());
    }

    #[test]
    fn archive_limit_arithmetic() {
        assert_eq!(archive_limit(&[]), 4096);
        // `core/a/b.js` is 11 bytes: 6400 + 100 + (2 x 11 + 192) + 4096
        assert_eq!(archive_limit(&[file("core", "a/b.js", 6400)]), 10_810);
        let two = [file("core", "a", 64), file("mode", "bc", 0)];
        // 64 + 1 + (2 x 6 + 192) + (2 x 7 + 192) + 4096
        assert_eq!(archive_limit(&two), 64 + 1 + 204 + 206 + 4096);
    }

    #[test]
    fn name_rules() {
        for (name, want) in [
            (&b"core/a\\b"[..], Some("holds a backslash")),
            (b"/core/a", Some("is an absolute path")),
            (b"core/a/", Some("is a directory entry")),
            (b"C:/core/a", Some("names a drive or a stream")),
            (b"core/a:s", Some("names a drive or a stream")),
            (b"core//a", Some("has an empty, `.` or `..` component")),
            (b"core/./a", Some("has an empty, `.` or `..` component")),
            (b"core/../a", Some("has an empty, `.` or `..` component")),
            (b"", Some("has an empty, `.` or `..` component")),
            (b"core/\xff", Some("is not UTF-8")),
            (b"core/caf\xc3\xa9/a b,1.json", None),
        ] {
            assert_eq!(name_problem(name), want, "{}", shown(name));
        }
    }

    /// The central-directory walk sees a record the crate collapses: two
    /// records with one name.
    #[test]
    fn central_walk_counts_a_crafted_duplicate() {
        use std::io::Write as _;
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated);
        for name in ["core/a.json", "core/b.json"] {
            writer.start_file(name, options).expect("entry");
            writer.write_all(b"{}").expect("write");
        }
        let mut bytes = writer.finish().expect("finish").into_inner();
        // rename every `core/b.json` to `core/a.json` (local and central)
        let from = b"core/b.json";
        let mut at = 0;
        while let Some(found) = bytes[at..].windows(from.len()).position(|w| w == from) {
            bytes[at + found..at + found + from.len()].copy_from_slice(b"core/a.json");
            at += found + from.len();
        }
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("dup.zip");
        std::fs::write(&path, &bytes).expect("write");
        let mut opened = std::fs::File::open(&path).expect("open");
        let zip =
            zip::ZipArchive::new(opened.try_clone().expect("clone")).expect("the crate opens it");
        let records = central_records(
            &mut opened,
            zip.central_directory_start(),
            bytes.len() as u64,
        )
        .expect("walk");
        assert_eq!(records.len(), 2, "both records are seen");
        assert_eq!(zip.len(), 1, "the crate keeps one of them");
        let why = extract(
            &path,
            &[file("core", "a.json", 2)],
            &dir.path().join("out"),
            1024,
        )
        .expect_err("refused");
        assert!(why.contains("twice"), "{why}");
    }

    /// A reader that counts the bytes read through it.
    struct Counting<R> {
        inner: R,
        read: u64,
    }

    impl<R: Read> Read for Counting<R> {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = self.inner.read(buf)?;
            self.read += n as u64;
            Ok(n)
        }
    }

    impl<R: Seek> Seek for Counting<R> {
        fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
            self.inner.seek(pos)
        }
    }

    /// `count` central records named `core/<i>.json`, all local offset 0.
    fn crafted_records(count: usize) -> Vec<u8> {
        let mut out = Vec::new();
        for i in 0..count {
            let name = format!("core/{i}.json");
            let mut record = [0u8; 46];
            record[..4].copy_from_slice(&[0x50, 0x4b, 0x01, 0x02]);
            record[5] = 3;
            record[28..30].copy_from_slice(&(name.len() as u16).to_le_bytes());
            record[38..42].copy_from_slice(&(0o100_644u32 << 16).to_le_bytes());
            out.extend_from_slice(&record);
            out.extend_from_slice(name.as_bytes());
        }
        out
    }

    /// Quick 261105-cr1: the walk reads the records one at a time. A crafted
    /// archive whose central directory starts at offset 0 with 8 MiB after
    /// its records costs a small read, not the whole file. The walk also
    /// stops at the first record past `READ_MAX_ENTRIES + 1`.
    #[test]
    fn central_walk_reads_only_the_records() {
        let mut bytes = crafted_records(3);
        let records_len = bytes.len() as u64;
        bytes.extend(std::iter::repeat_n(0u8, 8 << 20));
        let len = bytes.len() as u64;
        let mut reader = Counting {
            inner: std::io::Cursor::new(bytes),
            read: 0,
        };
        let records = central_records(&mut reader, 0, len).expect("walk");
        assert_eq!(records.len(), 3);
        assert_eq!(records[2].name, b"core/2.json");
        assert_eq!(records[2].host, 3);
        assert!(
            reader.read <= records_len + (256 << 10),
            "the walk read {} bytes of a {len}-byte file",
            reader.read
        );

        // READ_MAX_ENTRIES + 1 records are returned; one more is refused
        // before the junk after it is read
        let mut bytes = crafted_records(READ_MAX_ENTRIES + 1);
        let len = bytes.len() as u64;
        let walked = central_records(&mut std::io::Cursor::new(&bytes), 0, len).expect("walk");
        assert_eq!(walked.len(), READ_MAX_ENTRIES + 1);
        bytes.extend(crafted_records(1));
        let records_len = bytes.len() as u64;
        bytes.extend(std::iter::repeat_n(0u8, 8 << 20));
        let len = bytes.len() as u64;
        let mut reader = Counting {
            inner: std::io::Cursor::new(bytes),
            read: 0,
        };
        let why = central_records(&mut reader, 0, len).err().expect("refused");
        assert!(why.contains("more than 200000 entries"), "{why}");
        assert!(
            reader.read <= records_len + (256 << 10),
            "the walk read {} bytes of a {len}-byte file",
            reader.read
        );

        // a record cut off by the end of the central directory
        let bytes = crafted_records(2);
        let cut = bytes.len() as u64 - 3;
        let why = central_records(&mut std::io::Cursor::new(&bytes), 0, cut)
            .err()
            .expect("refused");
        assert!(why.contains("a central record is cut off"), "{why}");
        let why = central_records(&mut std::io::Cursor::new(&bytes), 0, 46 + 11 + 20)
            .err()
            .expect("refused");
        assert!(why.contains("a central record is cut off"), "{why}");
    }

    /// An honest Unix-made archive (the shape PowerShell 7 builds on a Unix
    /// host) round-trips, and the destination holds exactly the files. The
    /// writer is told the host: the zip crate records its own platform
    /// otherwise (MS-DOS on Windows, quick 261105-cr1).
    #[test]
    fn extract_round_trips_an_honest_archive() {
        use std::io::Write as _;
        let files = [
            file("core", "ignition/a b,1/config.json", 5),
            file("production", "ignition/caf\u{e9}/x.json", 0),
        ];
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated)
            .system(zip::System::Unix);
        for (f, body) in files.iter().zip([&b"hello"[..], b""]) {
            writer.start_file(f.name(), options).expect("entry");
            writer.write_all(body).expect("write");
        }
        let bytes = writer.finish().expect("finish").into_inner();
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("read.zip");
        std::fs::write(&path, &bytes).expect("write");
        assert!(bytes.len() as u64 <= archive_limit(&files));
        let out = dir.path().join("out");
        assert_eq!(extract(&path, &files, &out, 0).expect("extract"), 5);
        assert_eq!(
            std::fs::read(out.join("core/ignition/a b,1/config.json")).expect("read"),
            b"hello"
        );
        assert_eq!(
            std::fs::read(out.join("production/ignition/caf\u{e9}/x.json")).expect("read"),
            b""
        );
        let attributes = record_attributes(&path).expect("attributes");
        assert_eq!(attributes.len(), 2);
        assert!(
            attributes
                .iter()
                .all(|(_, host, ext)| *host == 3 && ext >> 16 == 0o100_644)
        );
    }
}