Skip to main content

hatchzip_core/archive/
mod.rs

1//! What the engine needs from an archive format: the archive split into
2//! units, byte ranges that can be truncated away once every file in them is
3//! safely on disk, and a way to decode one unit.
4
5#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11mod tarbz2;
12pub mod targz;
13pub mod tarxz;
14pub mod tarzst;
15mod xz;
16mod zip;
17
18use std::fs;
19use std::io::{Read, Seek, SeekFrom};
20use std::path::{Component, Path, PathBuf};
21use std::sync::Arc;
22use std::time::SystemTime;
23
24use anyhow::{Context, Result, bail};
25
26use crate::journal::Resume;
27use storage::{Storage, Tail};
28use targz::Event;
29use targz::Profile;
30
31/// An archive that is one compressed stream, decodable only from the front:
32/// everything it holds is inside one decode pass, so instead of units
33/// extracted from the end, the whole archive is one unit extracted front to
34/// back, and the engine frees the compressed bytes behind the decoder. See
35/// `targz` and `tarxz`.
36pub trait SolidStream: Send + Sync {
37    /// What a scan measured about the output: see [`targz::Profile`].
38    fn profile(&self) -> &targz::Profile;
39    /// Walks the archive from `from`, or from its start. The walk depends
40    /// on nothing but the archive, so the box outlives the cloneable
41    /// handle it came from.
42    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
43}
44
45/// The walk a [`SolidStream`] produces: the tar's events and, at the
46/// [`Event::Point`] ones, how decoding can restart.
47pub trait SolidWalker {
48    /// The next event. `Data` is at most `max` bytes, borrowed until the
49    /// next call.
50    fn next(&mut self, max: usize) -> Result<Event<'_>>;
51    /// The resume point at the `Point` event just returned. Its `unit` is
52    /// left for the engine to fill in.
53    fn point(&self) -> Result<Resume>;
54    /// The archive byte a resume point here would restart in. Cheap: for
55    /// measuring only.
56    fn point_byte(&self) -> Option<u64>;
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum Kind {
61    File,
62    Dir,
63    /// The link target is the item's data.
64    Symlink,
65    /// Hard links point at an earlier entry, which is extracted later than
66    /// the link when going from the end, so they are made at the very end.
67    HardLink(PathBuf),
68}
69
70#[derive(Clone, Debug)]
71pub struct Item {
72    pub path: PathBuf,
73    pub size: u64,
74    pub kind: Kind,
75    pub mode: Option<u32>,
76    pub mtime: Option<SystemTime>,
77}
78
79#[derive(Clone)]
80pub struct Unit {
81    /// Where the unit's bytes begin. Once it is committed the archive is
82    /// truncated to this offset.
83    pub start: u64,
84    /// The format's own handle for the unit: a ZIP entry index, a 7z block.
85    pub key: usize,
86    pub items: Vec<Item>,
87    /// Decoding it needs the archive's password.
88    pub encrypted: bool,
89}
90
91/// The archive is encrypted and nothing can be read without its password.
92/// Front ends look for this error to ask for one.
93#[derive(Debug)]
94pub struct PasswordNeeded;
95
96impl std::fmt::Display for PasswordNeeded {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.write_str("this archive is password protected")
99    }
100}
101
102impl std::error::Error for PasswordNeeded {}
103
104/// The password doesn't open the archive.
105#[derive(Debug)]
106pub struct WrongPassword;
107
108impl std::fmt::Display for WrongPassword {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str("incorrect password")
111    }
112}
113
114impl std::error::Error for WrongPassword {}
115
116/// The archive is damaged, found while opening it and before anything was
117/// touched. Front ends look for this error to report damage as such.
118#[derive(Debug)]
119pub struct Damaged(pub anyhow::Error);
120
121impl std::fmt::Display for Damaged {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        write!(f, "{:#}", self.0)
124    }
125}
126
127impl std::error::Error for Damaged {}
128
129/// The archive is valid but uses something this build does not extract: an
130/// unknown or unprovided check, an unknown filter, several xz streams, or a
131/// dictionary too large to hold. Front ends report it as unsupported, never
132/// as damage.
133#[derive(Debug)]
134pub struct Unsupported(pub anyhow::Error);
135
136impl std::fmt::Display for Unsupported {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        write!(f, "{:#}", self.0)
139    }
140}
141
142impl std::error::Error for Unsupported {}
143
144/// The format name of RAR archives in the journal.
145pub const RAR: &str = "rar";
146
147/// The format name of native split ZIPs (`.z01`, ..., `.zip`) in the journal.
148pub const SPLIT_ZIP: &str = zip::SPLIT;
149
150/// Whether this build extracts RAR archives. Builds without UnRAR refuse
151/// them before anything is touched.
152pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
153
154/// Why a build without UnRAR refuses a RAR archive.
155pub fn no_rar() -> anyhow::Error {
156    anyhow::anyhow!(
157        "this build of HatchZip does not include RAR support, and the archive was not \
158         modified. Download the release build from hatchzip.dev or \
159         github.com/xevrion/hatchzip/releases"
160    )
161}
162
163/// How the password of an encrypted archive is proven before anything is
164/// touched.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum PasswordCheck {
167    /// Decode the start of the smallest encrypted unit: a wrong password
168    /// fails at once, or within the first blocks.
169    Sample,
170    /// The headers hold a check value for the password, so
171    /// [`Format::prove_password`] answers without decoding anything.
172    Headers,
173    /// Only the checksum at the end of a file can tell, so the smallest
174    /// encrypted unit is decoded whole, writing nothing.
175    WholeUnit,
176}
177
178impl Unit {
179    /// Saturates instead of wrapping: sizes come straight from the archive.
180    pub fn size(&self) -> u64 {
181        self.items
182            .iter()
183            .fold(0u64, |sum, i| sum.saturating_add(i.size))
184    }
185}
186
187pub trait Format: Send + Sync {
188    /// A worker decodes units on one thread. `threads` is a hint for codecs
189    /// that can decode a single stream on several cores.
190    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
191
192    /// For a unit holding one file whose data [`resumable`] can decode from
193    /// the middle: where that data lies. Such units can free their archive
194    /// bytes while they are extracted instead of only once they are done.
195    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
196        Ok(None)
197    }
198
199    /// For an archive that is one compressed stream, decodable only from the
200    /// front: its single unit, extracted front to back while the bytes behind
201    /// the decoder are freed.
202    fn solid(&self) -> Option<&dyn SolidStream> {
203        None
204    }
205
206    /// The decoder finds a unit only by reading everything before it, and
207    /// one handle can't be shared between threads. A batch is then decoded
208    /// on one thread by one worker, lowest unit first, so the worker can
209    /// walk forward instead of starting over for every unit.
210    fn serial(&self) -> bool {
211        false
212    }
213
214    /// Why the archive can't be extracted in place, if it can't: it can
215    /// still be extracted while it is kept.
216    fn refuses_in_place(&self) -> Option<String> {
217        None
218    }
219
220    fn password_check(&self) -> PasswordCheck {
221        PasswordCheck::Sample
222    }
223
224    /// Proves the password from the headers alone; only called when
225    /// [`password_check`](Self::password_check) says it can.
226    fn prove_password(&self) -> Result<()> {
227        Ok(())
228    }
229}
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq)]
232pub enum Codec {
233    Stored,
234    /// Raw deflate, as ZIP stores it.
235    Deflate,
236}
237
238#[derive(Clone, Debug)]
239pub struct Stream {
240    /// Where the file's data begins. The headers before it stay untouched
241    /// until the unit is committed, so the archive still parses on resume.
242    pub data_start: u64,
243    /// Length of the data in the archive.
244    pub packed: u64,
245    pub codec: Codec,
246    /// CRC-32 of the output, if the format records one.
247    pub crc: Option<u32>,
248}
249
250pub trait Worker {
251    /// Decodes `unit`, handing each item to `sink` in order.
252    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
253}
254
255pub trait Sink {
256    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
257}
258
259pub struct Opened {
260    pub name: &'static str,
261    pub format: Box<dyn Format>,
262    pub units: Vec<Unit>,
263    /// Everything from here to the end is saved before anything is reclaimed.
264    pub tail_start: u64,
265}
266
267/// Parses the archive. `resume` carries the format recorded by an earlier
268/// run, the tail it saved and its resume point, which a compressed tar is
269/// read from; a fresh run sniffs the format instead. The password is only
270/// needed for encrypted archives; whether it is right is found out when a
271/// unit is decoded (see `Job::check_password`).
272pub fn open(
273    storage: &Arc<Storage>,
274    resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
275    password: Option<&str>,
276) -> Result<Opened> {
277    let (name, tail, point) = match resume {
278        Some((name, tail, point)) => (name.to_string(), Some(tail), point),
279        None => (sniff(storage)?.to_string(), None, None),
280    };
281    match name.as_str() {
282        "zip" => zip::open(storage, tail, password),
283        zip::SPLIT => zip::open_split(storage, tail, password),
284        "7z" => sevenz::open(storage, tail, password),
285        "tar" => tar::open(storage, tail),
286        #[cfg(feature = "rar")]
287        RAR => rar::open(storage, tail.is_some(), password),
288        #[cfg(not(feature = "rar"))]
289        RAR => Err(no_rar()),
290        targz::NAME => targz::open(storage, point),
291        tarbz2::NAME => tarbz2::open(storage, point),
292        tarxz::NAME => tarxz::open(storage, point),
293        tarzst::NAME => tarzst::open(storage, point),
294        other => bail!("unknown archive format '{other}' in the journal"),
295    }
296}
297
298/// What turns the first `keep` bytes of a half-extracted archive back into an
299/// archive any tool opens.
300pub struct NewIndex {
301    /// Written at `keep`.
302    pub append: Vec<u8>,
303    /// Written over bytes below `keep`: the 7z start header, which has to
304    /// point at the new header.
305    pub patches: Vec<(u64, Vec<u8>)>,
306    /// `append` is a new last volume of its own, created at the last
307    /// recorded part's path, which the extraction deleted, instead of being
308    /// written at `keep`: a native split ZIP whose `.zip` is gone.
309    pub new_last: bool,
310}
311
312/// Lists the entries of a [`SolidStream`]'s walk from `from` once to the
313/// end, and measures how the output runs ahead of the decoded bytes, which
314/// the space check needs. Damage found here, in the pass that runs before
315/// anything is touched and again from the resume point of a resumed run,
316/// stops the run.
317fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
318    let from_byte = from.map_or(0, |r| r.bit / 8);
319    let mut w = solid.walk(from)?;
320    let mut items = Vec::new();
321    let mut p = Profile::default();
322    let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
323    loop {
324        match w.next(usize::MAX)? {
325            Event::Entry { item, .. } => {
326                if item.kind == Kind::File {
327                    size = item.size;
328                }
329                items.push(item);
330            }
331            Event::Data(d) => out += d.len() as u64,
332            Event::FileEnd => out += size.next_multiple_of(4096) - size,
333            Event::Point => {
334                let consumed = w
335                    .point_byte()
336                    .unwrap_or(from_byte)
337                    .saturating_sub(from_byte);
338                p.lead = p.lead.max(out as i128 - consumed as i128);
339                p.gap = p.gap.max(out - last);
340                last = out;
341            }
342            Event::End => break,
343        }
344    }
345    p.gap = p.gap.max(out - last);
346    p.files = out;
347    tar::size_links(&mut items);
348    p.links = items
349        .iter()
350        .filter(|i| i.kind != Kind::File)
351        .fold(0u64, |sum, i| {
352            let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
353            sum.saturating_add(size)
354        });
355    Ok((items, p))
356}
357
358/// Builds the [`NewIndex`] for the entries that start below `keep`, from
359/// the tail an earlier run saved. `hard_links` are tar links already cut off
360/// whose targets are still in the archive.
361pub fn rebuild_index(
362    format: &str,
363    storage: &Storage,
364    tail: Arc<Tail>,
365    keep: u64,
366    hard_links: &[(&Path, &Path)],
367) -> Result<NewIndex> {
368    if format == zip::SPLIT {
369        let (append, new_last) = zip::rebuild_split_index(storage.parts(), &tail, keep)?;
370        return Ok(NewIndex {
371            append,
372            patches: Vec::new(),
373            new_last,
374        });
375    }
376    let (append, patches) = match format {
377        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
378        "tar" => (tar::closing(hard_links)?, Vec::new()),
379        "7z" => {
380            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
381            (header, vec![(0, start)])
382        }
383        // No index: the last volume left only needs its end header back.
384        #[cfg(feature = "rar")]
385        RAR => (rar::closing(storage, keep)?, Vec::new()),
386        #[cfg(not(feature = "rar"))]
387        RAR => return Err(no_rar()),
388        other => bail!("unknown archive format '{other}' in the journal"),
389    };
390    Ok(NewIndex {
391        append,
392        patches,
393        new_last: false,
394    })
395}
396
397fn sniff(storage: &Storage) -> Result<&'static str> {
398    // Named `.z01` and opened with its `.zip`: the first segment of a native
399    // split ZIP. Its index is in the last segment, in a form only `zip`'s
400    // split reader takes.
401    if storage.parts().len() > 1 && storage::is_split_zip(storage.primary()) {
402        return Ok(zip::SPLIT);
403    }
404    let mut head = [0u8; 512];
405    let mut r = storage.reader(None);
406    let n = read_up_to(&mut r, &mut head)?;
407    let head = &head[..n];
408    let starts = |magic: &[u8]| head.starts_with(magic);
409    if starts(b"7z\xBC\xAF\x27\x1C") {
410        return Ok("7z");
411    }
412    let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
413    if is_tar(head) {
414        return Ok("tar");
415    }
416    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
417    if starts(b"\x1F\x8B") {
418        // Look inside: a plain .gz of one file is not an archive.
419        let named = [".tar.gz", ".tgz", ".taz"]
420            .iter()
421            .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
422        if gzip_holds_tar(storage)? || named {
423            return Ok(targz::NAME);
424        }
425        bail!(
426            "this is a gzip-compressed file that does not contain a tar archive. Only \
427             compressed tar archives (.tar.gz) can be extracted"
428        );
429    }
430    if starts(b"\xFD7zXZ\x00") {
431        // A .xz only ever comes as a compressed tar here; anything else is
432        // refused once the stream opens.
433        return Ok(tarxz::NAME);
434    }
435    if starts(b"BZh") {
436        let first = (|| -> Result<_> {
437            let mut bz = tarbz2::Bzip2::new(
438                storage.reader(None),
439                storage.original_len(),
440                &tarbz2::BzPoint::start(),
441            )?;
442            let mut first = [0; 512];
443            let mut n = 0;
444            while n < first.len() {
445                let k = bz.read(&mut first[n..])?;
446                if k == 0 {
447                    break;
448                }
449                n += k;
450            }
451            Ok((first, n))
452        })()
453        // A volume that can't be read is not damage in the stream.
454        .map_err(|e| {
455            if e.downcast_ref::<std::io::Error>().is_some() {
456                e
457            } else {
458                anyhow::Error::new(Damaged(e))
459            }
460        })
461        .context(
462            "checking the bzip2 archive (nothing was changed); if it is damaged, download it again",
463        )?;
464        // Like a .tar.gz, a stream that doesn't start with a ustar header is
465        // still taken as a tar when its own name says so.
466        let named = named_bzip2(
467            &storage
468                .primary()
469                .file_name()
470                .unwrap_or_default()
471                .to_string_lossy(),
472        );
473        if is_tar(&first.0[..first.1]) || named {
474            return Ok(tarbz2::NAME);
475        }
476        bail!(
477            "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"
478        );
479    }
480    let zstd_magic = head.len() >= 4 && {
481        let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
482        magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
483    };
484    if zstd_magic {
485        // Look inside, as for gzip: a plain .zst of one file is not an
486        // archive. pzstd puts a skippable frame first, so the magic alone
487        // does not say where the first real frame is.
488        if named_zstd(&ext) || tarzst::holds_tar(storage)? {
489            return Ok(tarzst::NAME);
490        }
491        bail!(
492            "this is a zstd-compressed file that does not contain a tar archive. Only \
493             compressed tar archives (.tar.zst) can be extracted"
494        );
495    }
496    if starts(b"Rar!\x1A\x07") {
497        return Ok(RAR);
498    }
499    if ext.ends_with(".tar") || ext.contains(".tar.") {
500        return Ok("tar");
501    }
502    // Anything else gets a ZIP parse: self-extracting archives put an
503    // executable in front, so the signature isn't at the start.
504    Ok("zip")
505}
506
507/// The file's own name says `.tar.bz2`, alone or before a numeric split
508/// suffix such as `.001`. The folders it sits in don't count.
509fn named_bzip2(name: &str) -> bool {
510    let name = name.to_ascii_lowercase();
511    let base = match name.rsplit_once('.') {
512        Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
513        _ => &name,
514    };
515    [".tar.bz2", ".tbz2", ".tbz"]
516        .iter()
517        .any(|e| base.ends_with(e))
518}
519
520/// The file's own name says `.tar.zst`, alone or before a numeric split
521/// suffix such as `.001`. The folders it sits in don't count.
522fn named_zstd(name: &str) -> bool {
523    let name = name.to_ascii_lowercase();
524    let base = match name.rsplit_once('.') {
525        Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
526        _ => &name,
527    };
528    [".tar.zst", ".tzst"].iter().any(|e| base.ends_with(e))
529}
530
531/// Whether the gzip stream `storage` opens with a tar header.
532fn gzip_holds_tar(storage: &Storage) -> Result<bool> {
533    let mut gz = resumable::Gzip::new(
534        storage.reader(None),
535        storage.original_len(),
536        &resumable::GzPoint::start(),
537    )?;
538    let mut first = [0u8; 512];
539    let mut n = 0;
540    while n < first.len() {
541        match gz
542            .read(&mut first[n..])
543            .context("reading the start of the compressed stream")?
544        {
545            0 => break,
546            k => n += k,
547        }
548    }
549    Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
550}
551
552/// Whether the bzip2 stream `storage` opens with a tar header.
553fn bzip2_holds_tar(storage: &Storage) -> Result<bool> {
554    let mut bz = tarbz2::Bzip2::new(
555        storage.reader(None),
556        storage.original_len(),
557        &tarbz2::BzPoint::start(),
558    )?;
559    let mut first = [0u8; 512];
560    let mut n = 0;
561    while n < first.len() {
562        match bz.read(&mut first[n..])? {
563            0 => break,
564            k => n += k,
565        }
566    }
567    Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
568}
569
570/// Whether a ZIP's end record sits in its last 64 KiB, which every archive
571/// this crate can open has.
572fn zip_has_an_index(path: &Path) -> bool {
573    const MAX: u64 = 22 + 0xFFFF;
574    let Ok(mut file) = fs::File::open(path) else {
575        return false;
576    };
577    let Ok(len) = file.metadata().map(|m| m.len()) else {
578        return false;
579    };
580    if len < 22 {
581        return false;
582    }
583    let start = len.saturating_sub(MAX);
584    if file.seek(SeekFrom::Start(start)).is_err() {
585        return false;
586    }
587    let mut tail = Vec::with_capacity((len - start) as usize);
588    if file.take(len - start).read_to_end(&mut tail).is_err() {
589        return false;
590    }
591    let has = |magic: &[u8]| tail.windows(magic.len()).any(|w| w == magic);
592    has(b"PK\x05\x06") || has(b"PK\x06\x06")
593}
594
595/// The format `path` holds, from its signature, or `None` when it is not a
596/// file this build can extract. Links and folders are not considered.
597pub fn detect(path: &Path) -> Option<&'static str> {
598    let meta = fs::symlink_metadata(path).ok()?;
599    if !meta.is_file() {
600        return None;
601    }
602    let mut head = [0u8; 512];
603    let n = read_up_to(&mut fs::File::open(path).ok()?, &mut head).ok()?;
604    let head = &head[..n];
605    let starts = |magic: &[u8]| head.starts_with(magic);
606    if starts(b"7z\xBC\xAF\x27\x1C") {
607        return Some("7z");
608    }
609    if head.len() >= 263 && &head[257..262] == b"ustar" {
610        return Some("tar");
611    }
612    if starts(b"\xFD7zXZ\x00") {
613        let storage = Arc::new(Storage::open(path, false).ok()?);
614        return tarxz::holds_tar(&storage).then_some(tarxz::NAME);
615    }
616    if starts(b"Rar!\x1A\x07") {
617        return cfg!(feature = "rar").then_some(RAR);
618    }
619    if starts(b"\x1F\x8B") {
620        let storage = Storage::open(path, false).ok()?;
621        return gzip_holds_tar(&storage).ok()?.then_some(targz::NAME);
622    }
623    if starts(b"BZh") {
624        let storage = Storage::open(path, false).ok()?;
625        return bzip2_holds_tar(&storage).ok()?.then_some(tarbz2::NAME);
626    }
627    let zstd = head.len() >= 4 && {
628        let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
629        magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
630    };
631    if zstd {
632        let storage = Arc::new(Storage::open(path, false).ok()?);
633        return tarzst::holds_tar(&storage).ok()?.then_some(tarzst::NAME);
634    }
635    if starts(b"PK\x03\x04") || starts(b"PK\x05\x06") {
636        return zip_has_an_index(path).then_some("zip");
637    }
638    None
639}
640
641/// The format `path` holds if its name claims an archive format and its
642/// signature agrees. Both matter: `.jar`, `.docx`, `.pk3` and `.apk` are
643/// ZIPs, and `.ova` and `.gem` are tars, and none of them should be offered.
644///
645/// A `.z01` that starts like the first segment of a native split ZIP is
646/// [`SPLIT_ZIP`]. That says nothing about the rest of the set, which
647/// [`crate::session::nested_offer`] checks before offering it.
648pub fn nested_kind(path: &Path) -> Option<&'static str> {
649    if storage::is_split_zip(path) {
650        return starts_like_split_zip(path).then_some(SPLIT_ZIP);
651    }
652    let name = path.file_name()?.to_string_lossy().to_ascii_lowercase();
653    let expected = if name.ends_with(".zip") {
654        "zip"
655    } else if name.ends_with(".7z") {
656        "7z"
657    } else if name.ends_with(".tar") {
658        "tar"
659    } else if [".tar.gz", ".tgz", ".taz"]
660        .iter()
661        .any(|e| name.ends_with(e))
662    {
663        targz::NAME
664    } else if [".tar.xz", ".txz"].iter().any(|e| name.ends_with(e)) {
665        tarxz::NAME
666    } else if [".tar.zst", ".tzst"].iter().any(|e| name.ends_with(e)) {
667        tarzst::NAME
668    } else if [".tar.bz2", ".tbz2", ".tbz"]
669        .iter()
670        .any(|e| name.ends_with(e))
671    {
672        tarbz2::NAME
673    } else if name.ends_with(".rar") {
674        RAR
675    } else {
676        return None;
677    };
678    (detect(path)? == expected).then_some(expected)
679}
680
681/// Whether the file at `path` starts the way the split reader takes a first
682/// segment: the split marker `zip -s` writes, or the marker of a split that
683/// needed one segment, then a local header; or a local header straight
684/// away. `detect` never names such a file, as the marker is no signature.
685fn starts_like_split_zip(path: &Path) -> bool {
686    if !fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) {
687        return false;
688    }
689    let mut head = [0u8; 8];
690    let Ok(n) = fs::File::open(path).and_then(|mut f| read_up_to(&mut f, &mut head)) else {
691        return false;
692    };
693    let head = &head[..n];
694    let local: &[u8] = b"PK\x03\x04";
695    head.starts_with(local)
696        || ((head.starts_with(b"PK\x07\x08") || head.starts_with(b"PK00")) && &head[4..] == local)
697}
698
699fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
700    let mut n = 0;
701    while n < buf.len() {
702        match r.read(&mut buf[n..])? {
703            0 => break,
704            k => n += k,
705        }
706    }
707    Ok(n)
708}
709
710/// Turns an archive member name into a relative path that can't leave the
711/// output folder. Leading slashes are dropped, as tar does; `..`, NUL bytes
712/// and drive letters are refused.
713pub fn safe_path(name: &str) -> Option<PathBuf> {
714    if name.contains('\0') {
715        return None;
716    }
717    let mut out = PathBuf::new();
718    for part in name.split(['/', '\\']) {
719        match part {
720            "" | "." => {}
721            ".." => return None,
722            // A leading `C:` names a drive. Any other `:` is left to
723            // `platform::name_problem`, as it is a normal name character
724            // outside Windows, like in `10:30.txt`.
725            p if out.as_os_str().is_empty()
726                && p.len() == 2
727                && p.as_bytes()[0].is_ascii_alphabetic()
728                && p.ends_with(':') =>
729            {
730                return None;
731            }
732            p => out.push(p),
733        }
734    }
735    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
736    (clean && !out.as_os_str().is_empty()).then_some(out)
737}
738
739/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
740/// the Windows attributes.
741fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
742    (attrs & 0x8000 != 0).then_some(attrs >> 16)
743}
744
745const S_IFMT: u32 = 0o170000;
746const S_IFLNK: u32 = 0o120000;
747
748fn is_symlink_mode(mode: Option<u32>) -> bool {
749    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
750}
751
752#[cfg(test)]
753mod named_tests {
754    use super::named_bzip2;
755
756    #[test]
757    fn only_the_file_name_and_a_split_number_select_bzip2() {
758        for yes in ["a.tar.bz2", "A.TBZ2", "a.tbz", "a.tar.bz2.001", "a.tbz2.12"] {
759            assert!(named_bzip2(yes), "{yes}");
760        }
761        for no in [
762            "a.zip",
763            "a.tar.bz2.old",
764            "a.tar.bz2.",
765            "a.bz2",
766            "a.tar.gz.001",
767        ] {
768            assert!(!named_bzip2(no), "{no}");
769        }
770    }
771}