hatchzip-core 0.1.11

The engine behind HatchZip: extract ZIP, 7z and tar archives in place, freeing the archive as it goes.
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
//! What the engine needs from an archive format: the archive split into
//! units, byte ranges that can be truncated away once every file in them is
//! safely on disk, and a way to decode one unit.

#[cfg(feature = "rar")]
mod rar;
pub mod resumable;
mod sevenz;
pub mod storage;
mod tar;
mod tarbz2;
pub mod targz;
pub mod tarxz;
pub mod tarzst;
mod xz;
mod zip;

use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;

use anyhow::{Context, Result, bail};

use crate::journal::Resume;
use storage::{Storage, Tail};
use targz::Event;
use targz::Profile;

/// An archive that is one compressed stream, decodable only from the front:
/// everything it holds is inside one decode pass, so instead of units
/// extracted from the end, the whole archive is one unit extracted front to
/// back, and the engine frees the compressed bytes behind the decoder. See
/// `targz` and `tarxz`.
pub trait SolidStream: Send + Sync {
    /// What a scan measured about the output: see [`targz::Profile`].
    fn profile(&self) -> &targz::Profile;
    /// Walks the archive from `from`, or from its start. The walk depends
    /// on nothing but the archive, so the box outlives the cloneable
    /// handle it came from.
    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
}

/// The walk a [`SolidStream`] produces: the tar's events and, at the
/// [`Event::Point`] ones, how decoding can restart.
pub trait SolidWalker {
    /// The next event. `Data` is at most `max` bytes, borrowed until the
    /// next call.
    fn next(&mut self, max: usize) -> Result<Event<'_>>;
    /// The resume point at the `Point` event just returned. Its `unit` is
    /// left for the engine to fill in.
    fn point(&self) -> Result<Resume>;
    /// The archive byte a resume point here would restart in. Cheap: for
    /// measuring only.
    fn point_byte(&self) -> Option<u64>;
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Kind {
    File,
    Dir,
    /// The link target is the item's data.
    Symlink,
    /// Hard links point at an earlier entry, which is extracted later than
    /// the link when going from the end, so they are made at the very end.
    HardLink(PathBuf),
}

#[derive(Clone, Debug)]
pub struct Item {
    pub path: PathBuf,
    pub size: u64,
    pub kind: Kind,
    pub mode: Option<u32>,
    pub mtime: Option<SystemTime>,
}

#[derive(Clone)]
pub struct Unit {
    /// Where the unit's bytes begin. Once it is committed the archive is
    /// truncated to this offset.
    pub start: u64,
    /// The format's own handle for the unit: a ZIP entry index, a 7z block.
    pub key: usize,
    pub items: Vec<Item>,
    /// Decoding it needs the archive's password.
    pub encrypted: bool,
}

/// The archive is encrypted and nothing can be read without its password.
/// Front ends look for this error to ask for one.
#[derive(Debug)]
pub struct PasswordNeeded;

impl std::fmt::Display for PasswordNeeded {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("this archive is password protected")
    }
}

impl std::error::Error for PasswordNeeded {}

/// The password doesn't open the archive.
#[derive(Debug)]
pub struct WrongPassword;

impl std::fmt::Display for WrongPassword {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("incorrect password")
    }
}

impl std::error::Error for WrongPassword {}

/// The archive is damaged, found while opening it and before anything was
/// touched. Front ends look for this error to report damage as such.
#[derive(Debug)]
pub struct Damaged(pub anyhow::Error);

impl std::fmt::Display for Damaged {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#}", self.0)
    }
}

impl std::error::Error for Damaged {}

/// The archive is valid but uses something this build does not extract: an
/// unknown or unprovided check, an unknown filter, several xz streams, or a
/// dictionary too large to hold. Front ends report it as unsupported, never
/// as damage.
#[derive(Debug)]
pub struct Unsupported(pub anyhow::Error);

impl std::fmt::Display for Unsupported {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:#}", self.0)
    }
}

impl std::error::Error for Unsupported {}

/// The format name of RAR archives in the journal.
pub const RAR: &str = "rar";

/// The format name of native split ZIPs (`.z01`, ..., `.zip`) in the journal.
pub const SPLIT_ZIP: &str = zip::SPLIT;

/// Whether this build extracts RAR archives. Builds without UnRAR refuse
/// them before anything is touched.
pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");

/// Why a build without UnRAR refuses a RAR archive.
pub fn no_rar() -> anyhow::Error {
    anyhow::anyhow!(
        "this build of HatchZip does not include RAR support, and the archive was not \
         modified. Download the release build from hatchzip.dev or \
         github.com/xevrion/hatchzip/releases"
    )
}

/// How the password of an encrypted archive is proven before anything is
/// touched.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PasswordCheck {
    /// Decode the start of the smallest encrypted unit: a wrong password
    /// fails at once, or within the first blocks.
    Sample,
    /// The headers hold a check value for the password, so
    /// [`Format::prove_password`] answers without decoding anything.
    Headers,
    /// Only the checksum at the end of a file can tell, so the smallest
    /// encrypted unit is decoded whole, writing nothing.
    WholeUnit,
}

impl Unit {
    /// Saturates instead of wrapping: sizes come straight from the archive.
    pub fn size(&self) -> u64 {
        self.items
            .iter()
            .fold(0u64, |sum, i| sum.saturating_add(i.size))
    }
}

pub trait Format: Send + Sync {
    /// A worker decodes units on one thread. `threads` is a hint for codecs
    /// that can decode a single stream on several cores.
    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;

    /// For a unit holding one file whose data [`resumable`] can decode from
    /// the middle: where that data lies. Such units can free their archive
    /// bytes while they are extracted instead of only once they are done.
    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
        Ok(None)
    }

    /// For an archive that is one compressed stream, decodable only from the
    /// front: its single unit, extracted front to back while the bytes behind
    /// the decoder are freed.
    fn solid(&self) -> Option<&dyn SolidStream> {
        None
    }

    /// The decoder finds a unit only by reading everything before it, and
    /// one handle can't be shared between threads. A batch is then decoded
    /// on one thread by one worker, lowest unit first, so the worker can
    /// walk forward instead of starting over for every unit.
    fn serial(&self) -> bool {
        false
    }

    /// Why the archive can't be extracted in place, if it can't: it can
    /// still be extracted while it is kept.
    fn refuses_in_place(&self) -> Option<String> {
        None
    }

    fn password_check(&self) -> PasswordCheck {
        PasswordCheck::Sample
    }

    /// Proves the password from the headers alone; only called when
    /// [`password_check`](Self::password_check) says it can.
    fn prove_password(&self) -> Result<()> {
        Ok(())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Codec {
    Stored,
    /// Raw deflate, as ZIP stores it.
    Deflate,
}

#[derive(Clone, Debug)]
pub struct Stream {
    /// Where the file's data begins. The headers before it stay untouched
    /// until the unit is committed, so the archive still parses on resume.
    pub data_start: u64,
    /// Length of the data in the archive.
    pub packed: u64,
    pub codec: Codec,
    /// CRC-32 of the output, if the format records one.
    pub crc: Option<u32>,
}

pub trait Worker {
    /// Decodes `unit`, handing each item to `sink` in order.
    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
}

pub trait Sink {
    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
}

pub struct Opened {
    pub name: &'static str,
    pub format: Box<dyn Format>,
    pub units: Vec<Unit>,
    /// Everything from here to the end is saved before anything is reclaimed.
    pub tail_start: u64,
}

/// Parses the archive. `resume` carries the format recorded by an earlier
/// run, the tail it saved and its resume point, which a compressed tar is
/// read from; a fresh run sniffs the format instead. The password is only
/// needed for encrypted archives; whether it is right is found out when a
/// unit is decoded (see `Job::check_password`).
pub fn open(
    storage: &Arc<Storage>,
    resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
    password: Option<&str>,
) -> Result<Opened> {
    let (name, tail, point) = match resume {
        Some((name, tail, point)) => (name.to_string(), Some(tail), point),
        None => (sniff(storage)?.to_string(), None, None),
    };
    match name.as_str() {
        "zip" => zip::open(storage, tail, password),
        zip::SPLIT => zip::open_split(storage, tail, password),
        "7z" => sevenz::open(storage, tail, password),
        "tar" => tar::open(storage, tail),
        #[cfg(feature = "rar")]
        RAR => rar::open(storage, tail.is_some(), password),
        #[cfg(not(feature = "rar"))]
        RAR => Err(no_rar()),
        targz::NAME => targz::open(storage, point),
        tarbz2::NAME => tarbz2::open(storage, point),
        tarxz::NAME => tarxz::open(storage, point),
        tarzst::NAME => tarzst::open(storage, point),
        other => bail!("unknown archive format '{other}' in the journal"),
    }
}

/// What turns the first `keep` bytes of a half-extracted archive back into an
/// archive any tool opens.
pub struct NewIndex {
    /// Written at `keep`.
    pub append: Vec<u8>,
    /// Written over bytes below `keep`: the 7z start header, which has to
    /// point at the new header.
    pub patches: Vec<(u64, Vec<u8>)>,
    /// `append` is a new last volume of its own, created at the last
    /// recorded part's path, which the extraction deleted, instead of being
    /// written at `keep`: a native split ZIP whose `.zip` is gone.
    pub new_last: bool,
}

/// Lists the entries of a [`SolidStream`]'s walk from `from` once to the
/// end, and measures how the output runs ahead of the decoded bytes, which
/// the space check needs. Damage found here, in the pass that runs before
/// anything is touched and again from the resume point of a resumed run,
/// stops the run.
fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
    let from_byte = from.map_or(0, |r| r.bit / 8);
    let mut w = solid.walk(from)?;
    let mut items = Vec::new();
    let mut p = Profile::default();
    let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
    loop {
        match w.next(usize::MAX)? {
            Event::Entry { item, .. } => {
                if item.kind == Kind::File {
                    size = item.size;
                }
                items.push(item);
            }
            Event::Data(d) => out += d.len() as u64,
            Event::FileEnd => out += size.next_multiple_of(4096) - size,
            Event::Point => {
                let consumed = w
                    .point_byte()
                    .unwrap_or(from_byte)
                    .saturating_sub(from_byte);
                p.lead = p.lead.max(out as i128 - consumed as i128);
                p.gap = p.gap.max(out - last);
                last = out;
            }
            Event::End => break,
        }
    }
    p.gap = p.gap.max(out - last);
    p.files = out;
    tar::size_links(&mut items);
    p.links = items
        .iter()
        .filter(|i| i.kind != Kind::File)
        .fold(0u64, |sum, i| {
            let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
            sum.saturating_add(size)
        });
    Ok((items, p))
}

/// Builds the [`NewIndex`] for the entries that start below `keep`, from
/// the tail an earlier run saved. `hard_links` are tar links already cut off
/// whose targets are still in the archive.
pub fn rebuild_index(
    format: &str,
    storage: &Storage,
    tail: Arc<Tail>,
    keep: u64,
    hard_links: &[(&Path, &Path)],
) -> Result<NewIndex> {
    if format == zip::SPLIT {
        let (append, new_last) = zip::rebuild_split_index(storage.parts(), &tail, keep)?;
        return Ok(NewIndex {
            append,
            patches: Vec::new(),
            new_last,
        });
    }
    let (append, patches) = match format {
        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
        "tar" => (tar::closing(hard_links)?, Vec::new()),
        "7z" => {
            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
            (header, vec![(0, start)])
        }
        // No index: the last volume left only needs its end header back.
        #[cfg(feature = "rar")]
        RAR => (rar::closing(storage, keep)?, Vec::new()),
        #[cfg(not(feature = "rar"))]
        RAR => return Err(no_rar()),
        other => bail!("unknown archive format '{other}' in the journal"),
    };
    Ok(NewIndex {
        append,
        patches,
        new_last: false,
    })
}

fn sniff(storage: &Storage) -> Result<&'static str> {
    // Named `.z01` and opened with its `.zip`: the first segment of a native
    // split ZIP. Its index is in the last segment, in a form only `zip`'s
    // split reader takes.
    if storage.parts().len() > 1 && storage::is_split_zip(storage.primary()) {
        return Ok(zip::SPLIT);
    }
    let mut head = [0u8; 512];
    let mut r = storage.reader(None);
    let n = read_up_to(&mut r, &mut head)?;
    let head = &head[..n];
    let starts = |magic: &[u8]| head.starts_with(magic);
    if starts(b"7z\xBC\xAF\x27\x1C") {
        return Ok("7z");
    }
    let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
    if is_tar(head) {
        return Ok("tar");
    }
    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
    if starts(b"\x1F\x8B") {
        // Look inside: a plain .gz of one file is not an archive.
        let named = [".tar.gz", ".tgz", ".taz"]
            .iter()
            .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
        if gzip_holds_tar(storage)? || named {
            return Ok(targz::NAME);
        }
        bail!(
            "this is a gzip-compressed file that does not contain a tar archive. Only \
             compressed tar archives (.tar.gz) can be extracted"
        );
    }
    if starts(b"\xFD7zXZ\x00") {
        // A .xz only ever comes as a compressed tar here; anything else is
        // refused once the stream opens.
        return Ok(tarxz::NAME);
    }
    if starts(b"BZh") {
        let first = (|| -> Result<_> {
            let mut bz = tarbz2::Bzip2::new(
                storage.reader(None),
                storage.original_len(),
                &tarbz2::BzPoint::start(),
            )?;
            let mut first = [0; 512];
            let mut n = 0;
            while n < first.len() {
                let k = bz.read(&mut first[n..])?;
                if k == 0 {
                    break;
                }
                n += k;
            }
            Ok((first, n))
        })()
        // A volume that can't be read is not damage in the stream.
        .map_err(|e| {
            if e.downcast_ref::<std::io::Error>().is_some() {
                e
            } else {
                anyhow::Error::new(Damaged(e))
            }
        })
        .context(
            "checking the bzip2 archive (nothing was changed); if it is damaged, download it again",
        )?;
        // Like a .tar.gz, a stream that doesn't start with a ustar header is
        // still taken as a tar when its own name says so.
        let named = named_bzip2(
            &storage
                .primary()
                .file_name()
                .unwrap_or_default()
                .to_string_lossy(),
        );
        if is_tar(&first.0[..first.1]) || named {
            return Ok(tarbz2::NAME);
        }
        bail!(
            "this is a bzip2-compressed file that does not contain a tar archive; the file was not changed. Decompress it with bzip2, or use a .tar.bz2 archive"
        );
    }
    let zstd_magic = head.len() >= 4 && {
        let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
        magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
    };
    if zstd_magic {
        // Look inside, as for gzip: a plain .zst of one file is not an
        // archive. pzstd puts a skippable frame first, so the magic alone
        // does not say where the first real frame is.
        if named_zstd(&ext) || tarzst::holds_tar(storage)? {
            return Ok(tarzst::NAME);
        }
        bail!(
            "this is a zstd-compressed file that does not contain a tar archive. Only \
             compressed tar archives (.tar.zst) can be extracted"
        );
    }
    if starts(b"Rar!\x1A\x07") {
        return Ok(RAR);
    }
    if ext.ends_with(".tar") || ext.contains(".tar.") {
        return Ok("tar");
    }
    // Anything else gets a ZIP parse: self-extracting archives put an
    // executable in front, so the signature isn't at the start.
    Ok("zip")
}

/// The file's own name says `.tar.bz2`, alone or before a numeric split
/// suffix such as `.001`. The folders it sits in don't count.
fn named_bzip2(name: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let base = match name.rsplit_once('.') {
        Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
        _ => &name,
    };
    [".tar.bz2", ".tbz2", ".tbz"]
        .iter()
        .any(|e| base.ends_with(e))
}

/// The file's own name says `.tar.zst`, alone or before a numeric split
/// suffix such as `.001`. The folders it sits in don't count.
fn named_zstd(name: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let base = match name.rsplit_once('.') {
        Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
        _ => &name,
    };
    [".tar.zst", ".tzst"].iter().any(|e| base.ends_with(e))
}

/// Whether the gzip stream `storage` opens with a tar header.
fn gzip_holds_tar(storage: &Storage) -> Result<bool> {
    let mut gz = resumable::Gzip::new(
        storage.reader(None),
        storage.original_len(),
        &resumable::GzPoint::start(),
    )?;
    let mut first = [0u8; 512];
    let mut n = 0;
    while n < first.len() {
        match gz
            .read(&mut first[n..])
            .context("reading the start of the compressed stream")?
        {
            0 => break,
            k => n += k,
        }
    }
    Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
}

/// Whether the bzip2 stream `storage` opens with a tar header.
fn bzip2_holds_tar(storage: &Storage) -> Result<bool> {
    let mut bz = tarbz2::Bzip2::new(
        storage.reader(None),
        storage.original_len(),
        &tarbz2::BzPoint::start(),
    )?;
    let mut first = [0u8; 512];
    let mut n = 0;
    while n < first.len() {
        match bz.read(&mut first[n..])? {
            0 => break,
            k => n += k,
        }
    }
    Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
}

/// Whether a ZIP's end record sits in its last 64 KiB, which every archive
/// this crate can open has.
fn zip_has_an_index(path: &Path) -> bool {
    const MAX: u64 = 22 + 0xFFFF;
    let Ok(mut file) = fs::File::open(path) else {
        return false;
    };
    let Ok(len) = file.metadata().map(|m| m.len()) else {
        return false;
    };
    if len < 22 {
        return false;
    }
    let start = len.saturating_sub(MAX);
    if file.seek(SeekFrom::Start(start)).is_err() {
        return false;
    }
    let mut tail = Vec::with_capacity((len - start) as usize);
    if file.take(len - start).read_to_end(&mut tail).is_err() {
        return false;
    }
    let has = |magic: &[u8]| tail.windows(magic.len()).any(|w| w == magic);
    has(b"PK\x05\x06") || has(b"PK\x06\x06")
}

/// The format `path` holds, from its signature, or `None` when it is not a
/// file this build can extract. Links and folders are not considered.
pub fn detect(path: &Path) -> Option<&'static str> {
    let meta = fs::symlink_metadata(path).ok()?;
    if !meta.is_file() {
        return None;
    }
    let mut head = [0u8; 512];
    let n = read_up_to(&mut fs::File::open(path).ok()?, &mut head).ok()?;
    let head = &head[..n];
    let starts = |magic: &[u8]| head.starts_with(magic);
    if starts(b"7z\xBC\xAF\x27\x1C") {
        return Some("7z");
    }
    if head.len() >= 263 && &head[257..262] == b"ustar" {
        return Some("tar");
    }
    if starts(b"\xFD7zXZ\x00") {
        let storage = Arc::new(Storage::open(path, false).ok()?);
        return tarxz::holds_tar(&storage).then_some(tarxz::NAME);
    }
    if starts(b"Rar!\x1A\x07") {
        return cfg!(feature = "rar").then_some(RAR);
    }
    if starts(b"\x1F\x8B") {
        let storage = Storage::open(path, false).ok()?;
        return gzip_holds_tar(&storage).ok()?.then_some(targz::NAME);
    }
    if starts(b"BZh") {
        let storage = Storage::open(path, false).ok()?;
        return bzip2_holds_tar(&storage).ok()?.then_some(tarbz2::NAME);
    }
    let zstd = head.len() >= 4 && {
        let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
        magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
    };
    if zstd {
        let storage = Arc::new(Storage::open(path, false).ok()?);
        return tarzst::holds_tar(&storage).ok()?.then_some(tarzst::NAME);
    }
    if starts(b"PK\x03\x04") || starts(b"PK\x05\x06") {
        return zip_has_an_index(path).then_some("zip");
    }
    None
}

/// The format `path` holds if its name claims an archive format and its
/// signature agrees. Both matter: `.jar`, `.docx`, `.pk3` and `.apk` are
/// ZIPs, and `.ova` and `.gem` are tars, and none of them should be offered.
///
/// A `.z01` that starts like the first segment of a native split ZIP is
/// [`SPLIT_ZIP`]. That says nothing about the rest of the set, which
/// [`crate::session::nested_offer`] checks before offering it.
pub fn nested_kind(path: &Path) -> Option<&'static str> {
    if storage::is_split_zip(path) {
        return starts_like_split_zip(path).then_some(SPLIT_ZIP);
    }
    let name = path.file_name()?.to_string_lossy().to_ascii_lowercase();
    let expected = if name.ends_with(".zip") {
        "zip"
    } else if name.ends_with(".7z") {
        "7z"
    } else if name.ends_with(".tar") {
        "tar"
    } else if [".tar.gz", ".tgz", ".taz"]
        .iter()
        .any(|e| name.ends_with(e))
    {
        targz::NAME
    } else if [".tar.xz", ".txz"].iter().any(|e| name.ends_with(e)) {
        tarxz::NAME
    } else if [".tar.zst", ".tzst"].iter().any(|e| name.ends_with(e)) {
        tarzst::NAME
    } else if [".tar.bz2", ".tbz2", ".tbz"]
        .iter()
        .any(|e| name.ends_with(e))
    {
        tarbz2::NAME
    } else if name.ends_with(".rar") {
        RAR
    } else {
        return None;
    };
    (detect(path)? == expected).then_some(expected)
}

/// Whether the file at `path` starts the way the split reader takes a first
/// segment: the split marker `zip -s` writes, or the marker of a split that
/// needed one segment, then a local header; or a local header straight
/// away. `detect` never names such a file, as the marker is no signature.
fn starts_like_split_zip(path: &Path) -> bool {
    if !fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) {
        return false;
    }
    let mut head = [0u8; 8];
    let Ok(n) = fs::File::open(path).and_then(|mut f| read_up_to(&mut f, &mut head)) else {
        return false;
    };
    let head = &head[..n];
    let local: &[u8] = b"PK\x03\x04";
    head.starts_with(local)
        || ((head.starts_with(b"PK\x07\x08") || head.starts_with(b"PK00")) && &head[4..] == local)
}

fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
    let mut n = 0;
    while n < buf.len() {
        match r.read(&mut buf[n..])? {
            0 => break,
            k => n += k,
        }
    }
    Ok(n)
}

/// Turns an archive member name into a relative path that can't leave the
/// output folder. Leading slashes are dropped, as tar does; `..`, NUL bytes
/// and drive letters are refused.
pub fn safe_path(name: &str) -> Option<PathBuf> {
    if name.contains('\0') {
        return None;
    }
    let mut out = PathBuf::new();
    for part in name.split(['/', '\\']) {
        match part {
            "" | "." => {}
            ".." => return None,
            // A leading `C:` names a drive. Any other `:` is left to
            // `platform::name_problem`, as it is a normal name character
            // outside Windows, like in `10:30.txt`.
            p if out.as_os_str().is_empty()
                && p.len() == 2
                && p.as_bytes()[0].is_ascii_alphabetic()
                && p.ends_with(':') =>
            {
                return None;
            }
            p => out.push(p),
        }
    }
    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
    (clean && !out.as_os_str().is_empty()).then_some(out)
}

/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
/// the Windows attributes.
fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
    (attrs & 0x8000 != 0).then_some(attrs >> 16)
}

const S_IFMT: u32 = 0o170000;
const S_IFLNK: u32 = 0o120000;

fn is_symlink_mode(mode: Option<u32>) -> bool {
    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
}

#[cfg(test)]
mod named_tests {
    use super::named_bzip2;

    #[test]
    fn only_the_file_name_and_a_split_number_select_bzip2() {
        for yes in ["a.tar.bz2", "A.TBZ2", "a.tbz", "a.tar.bz2.001", "a.tbz2.12"] {
            assert!(named_bzip2(yes), "{yes}");
        }
        for no in [
            "a.zip",
            "a.tar.bz2.old",
            "a.tar.bz2.",
            "a.bz2",
            "a.tar.gz.001",
        ] {
            assert!(!named_bzip2(no), "{no}");
        }
    }
}