Skip to main content

libarchive_oxide_cli/
lib.rs

1// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Shared implementation for `oxtar`, `oxcpio`, `oxcat`, and `oxunzip`.
6//!
7//! Exit codes are 0 for success, 1 for runtime errors, and 2 for usage errors.
8//! Extraction rejects path traversal. Transparent decompression is capped at
9//! [`MAX_DECOMPRESSED`].
10
11#![forbid(unsafe_code)]
12
13pub mod cat;
14pub mod cpio;
15pub mod tar;
16pub mod unzip;
17
18use std::io::{Read, Seek};
19use std::path::Path;
20
21use cap_std::ambient_authority;
22use cap_std::fs::Dir;
23use libarchive_oxide::{
24    ArchiveReader, EntryOutcomeKind, ExtractionPolicy, Extractor, FilterReader, ReaderEvent,
25    SecretBytes, SeekArchiveReader,
26};
27use libarchive_oxide_core::{EntryKind, EntryMetadata};
28
29pub use cat::run_cat;
30pub use cpio::run_cpio;
31pub use tar::run_tar;
32pub use unzip::run_unzip;
33
34/// Maximum decompressed size.
35///
36/// Stored as `u64` because 4 GiB exceeds `usize` on 32-bit targets.
37pub const MAX_DECOMPRESSED: u64 = 4 * 1024 * 1024 * 1024;
38
39/// Returns [`MAX_DECOMPRESSED`] as `usize`, clamped on 32-bit targets.
40#[must_use]
41pub fn decompress_cap() -> usize {
42    usize::try_from(MAX_DECOMPRESSED).unwrap_or(usize::MAX)
43}
44
45/// A CLI error and process exit code.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct CliError {
48    /// Message written to standard error.
49    pub message: String,
50    /// Process exit code: 1 for runtime errors, 2 for usage errors.
51    pub code: u8,
52}
53
54impl CliError {
55    /// Creates a usage error with exit code 2.
56    pub fn usage(message: impl Into<String>) -> Self {
57        Self {
58            message: message.into(),
59            code: 2,
60        }
61    }
62
63    /// Creates a runtime error with exit code 1.
64    pub fn runtime(message: impl Into<String>) -> Self {
65        Self {
66            message: message.into(),
67            code: 1,
68        }
69    }
70
71    /// Creates an unsupported-option error with exit code 2.
72    pub fn unsupported(flag: impl std::fmt::Display) -> Self {
73        Self::usage(format!("unsupported: {flag}"))
74    }
75}
76
77impl std::fmt::Display for CliError {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(&self.message)
80    }
81}
82
83impl std::error::Error for CliError {}
84
85/// Convenience alias for CLI entry points.
86pub type CliResult = Result<(), CliError>;
87
88/// Lists a sequential archive without retaining the compressed or plain input.
89pub(crate) fn list_stream<R: Read>(input: R, members: &[String], verbose: bool) -> CliResult {
90    let input = FilterReader::new(input).map_err(|error| CliError::runtime(error.to_string()))?;
91    let mut reader = ArchiveReader::new(input);
92    let mut filter = MemberFilter::new(members);
93    loop {
94        match reader
95            .next_event()
96            .map_err(|error| CliError::runtime(error.to_string()))?
97        {
98            ReaderEvent::Entry(metadata) => {
99                if !filter.selects(metadata.path().as_bytes()) {
100                    continue;
101                }
102                if verbose {
103                    println!("{}", format_long_v2(&metadata));
104                } else {
105                    println!("{}", metadata.path().display_lossy());
106                }
107            },
108            ReaderEvent::Done => return filter.ensure_all_matched(),
109            _ => {},
110        }
111    }
112}
113
114/// Extracts a sequential archive through the capability-based safe extractor.
115pub(crate) fn extract_stream<R: Read>(
116    input: R,
117    dest: &Path,
118    verbose: bool,
119    members: &[String],
120) -> CliResult {
121    std::fs::create_dir_all(dest).map_err(|error| CliError::runtime(error.to_string()))?;
122    let root = Dir::open_ambient_dir(dest, ambient_authority())
123        .map_err(|error| CliError::runtime(error.to_string()))?;
124    let input = FilterReader::new(input).map_err(|error| CliError::runtime(error.to_string()))?;
125    let mut reader = ArchiveReader::new(input);
126    let mut extractor = Extractor::new(root);
127    let mut filter = MemberFilter::new(members);
128    let report = extractor
129        .extract_matching(&mut reader, |metadata| {
130            filter.selects(metadata.path().as_bytes())
131        })
132        .map_err(|error| CliError::runtime(error.to_string()))?;
133    filter.ensure_all_matched()?;
134    for outcome in report.outcomes() {
135        match outcome.outcome() {
136            EntryOutcomeKind::File | EntryOutcomeKind::Directory if verbose => {
137                eprintln!("x {}", outcome.path().display_lossy());
138            },
139            EntryOutcomeKind::Rejected(reason) => {
140                eprintln!(
141                    "oxtar: refused {}: {reason:?}",
142                    outcome.path().display_lossy()
143                );
144            },
145            _ => {},
146        }
147    }
148    if report.has_rejections() {
149        return Err(CliError::runtime(
150            "one or more archive entries were refused by the safe extraction policy",
151        ));
152    }
153    Ok(())
154}
155
156/// Lists a seek-required archive while retaining only its bounded index.
157pub(crate) fn list_seek<R: Read + Seek>(
158    input: R,
159    password: Option<&[u8]>,
160    members: &[String],
161    verbose: bool,
162) -> CliResult {
163    let mut reader = match password {
164        Some(password) => SeekArchiveReader::with_password(input, SecretBytes::from(password)),
165        None => SeekArchiveReader::new(input),
166    }
167    .map_err(|error| CliError::runtime(error.to_string()))?;
168    let mut filter = MemberFilter::new(members);
169    loop {
170        match reader
171            .next_event()
172            .map_err(|error| CliError::runtime(error.to_string()))?
173        {
174            ReaderEvent::Entry(metadata) => {
175                if filter.selects(metadata.path().as_bytes()) {
176                    if verbose {
177                        println!("{}", format_long_v2(&metadata));
178                    } else {
179                        println!("{}", metadata.path().display_lossy());
180                    }
181                }
182                reader
183                    .skip_entry()
184                    .map_err(|error| CliError::runtime(error.to_string()))?;
185            },
186            ReaderEvent::Done => return filter.ensure_all_matched(),
187            _ => {},
188        }
189    }
190}
191
192/// Extracts a seek-required archive with capability-based safe filesystem I/O.
193pub(crate) fn extract_seek<R: Read + Seek>(
194    input: R,
195    password: Option<&[u8]>,
196    dest: &Path,
197    verbose: bool,
198    members: &[String],
199    overwrite: bool,
200) -> CliResult {
201    std::fs::create_dir_all(dest).map_err(|error| CliError::runtime(error.to_string()))?;
202    let root = Dir::open_ambient_dir(dest, ambient_authority())
203        .map_err(|error| CliError::runtime(error.to_string()))?;
204    let mut reader = match password {
205        Some(password) => SeekArchiveReader::with_password(input, SecretBytes::from(password)),
206        None => SeekArchiveReader::new(input),
207    }
208    .map_err(|error| CliError::runtime(error.to_string()))?;
209    let policy = ExtractionPolicy::safe().allow_overwrite(overwrite);
210    let mut extractor = Extractor::with_policy(root, policy);
211    let mut filter = MemberFilter::new(members);
212    let report = extractor
213        .extract_seek_matching(&mut reader, |metadata| {
214            filter.selects(metadata.path().as_bytes())
215        })
216        .map_err(|error| CliError::runtime(error.to_string()))?;
217    filter.ensure_all_matched()?;
218    for outcome in report.outcomes() {
219        match outcome.outcome() {
220            EntryOutcomeKind::File | EntryOutcomeKind::Directory if verbose => {
221                eprintln!("x {}", outcome.path().display_lossy());
222            },
223            EntryOutcomeKind::Rejected(reason) => {
224                eprintln!(
225                    "oxunzip: refused {}: {reason:?}",
226                    outcome.path().display_lossy()
227                );
228            },
229            _ => {},
230        }
231    }
232    if report.has_rejections() {
233        return Err(CliError::runtime(
234            "one or more archive entries were refused by the safe extraction policy",
235        ));
236    }
237    Ok(())
238}
239
240/// Selects entries and tracks matched operands.
241///
242/// Empty operands select all entries. Other operands match exact paths or
243/// directory prefixes. Trailing slashes are ignored.
244#[derive(Debug)]
245struct MemberFilter<'m> {
246    members: &'m [String],
247    matched: Vec<bool>,
248}
249
250impl<'m> MemberFilter<'m> {
251    /// Creates a member filter.
252    fn new(members: &'m [String]) -> Self {
253        Self {
254            members,
255            matched: vec![false; members.len()],
256        }
257    }
258
259    /// Returns whether `path` is selected and records matching operands.
260    fn selects(&mut self, path: &[u8]) -> bool {
261        if self.members.is_empty() {
262            return true;
263        }
264        let entry = trim_trailing_slash(path);
265        let mut selected = false;
266        for (i, m) in self.members.iter().enumerate() {
267            let want = trim_trailing_slash(m.as_bytes());
268            if entry == want
269                || (entry.len() > want.len()
270                    && entry.starts_with(want)
271                    && entry[want.len()] == b'/')
272            {
273                self.matched[i] = true;
274                selected = true;
275            }
276        }
277        selected
278    }
279
280    /// Fails (exit 1) if any member operand matched no entry, reporting the first such operand as
281    /// `<name>: Not found in archive`. A no-op when the operand list was empty or all matched.
282    fn ensure_all_matched(&self) -> CliResult {
283        match self.matched.iter().position(|&m| !m) {
284            Some(i) => Err(CliError::runtime(format!(
285                "{}: Not found in archive",
286                self.members[i]
287            ))),
288            None => Ok(()),
289        }
290    }
291}
292
293/// Trims a single trailing `/` for name comparison (`sub/` and `sub` name the same member).
294fn trim_trailing_slash(p: &[u8]) -> &[u8] {
295    p.strip_suffix(b"/").unwrap_or(p)
296}
297
298fn format_long_v2(meta: &EntryMetadata) -> String {
299    let mode = mode_string(meta.kind(), meta.mode().unwrap_or(0));
300    let date = meta.times().modified.map_or_else(
301        || "1970-01-01 00:00".to_string(),
302        |timestamp| format_timestamp(timestamp.secs),
303    );
304    let name = meta.path().display_lossy();
305    let owner = meta.owner();
306    let uid = owner.uid.unwrap_or(0);
307    let gid = owner.gid.unwrap_or(0);
308    match meta.link_target() {
309        Some(target) if matches!(meta.kind(), EntryKind::Symlink) => format!(
310            "{mode} {uid}/{gid} {:>10} {date} {name} -> {}",
311            meta.size().unwrap_or(0),
312            target.display_lossy(),
313        ),
314        _ => format!(
315            "{mode} {uid}/{gid} {:>10} {date} {name}",
316            meta.size().unwrap_or(0)
317        ),
318    }
319}
320
321/// Builds the 10-char `drwxr-xr-x`-style mode string from an entry kind and permission bits.
322fn mode_string(kind: EntryKind, mode: u32) -> String {
323    let type_ch = match kind {
324        EntryKind::Dir => 'd',
325        EntryKind::Symlink => 'l',
326        EntryKind::Char => 'c',
327        EntryKind::Block => 'b',
328        EntryKind::Fifo => 'p',
329        EntryKind::Socket => 's',
330        _ => '-',
331    };
332    let mut s = String::with_capacity(10);
333    s.push(type_ch);
334    for shift in [6u32, 3, 0] {
335        let bits = (mode >> shift) & 0o7;
336        s.push(if bits & 0o4 != 0 { 'r' } else { '-' });
337        s.push(if bits & 0o2 != 0 { 'w' } else { '-' });
338        s.push(if bits & 0o1 != 0 { 'x' } else { '-' });
339    }
340    s
341}
342
343/// Formats a UNIX timestamp (seconds since the epoch) as `YYYY-MM-DD HH:MM` (UTC), for `-tv`.
344fn format_timestamp(secs: i64) -> String {
345    let days = secs.div_euclid(86_400);
346    let rem = secs.rem_euclid(86_400);
347    let (y, m, d) = civil_from_days(days);
348    let hour = rem / 3600;
349    let min = (rem % 3600) / 60;
350    format!("{y:04}-{m:02}-{d:02} {hour:02}:{min:02}")
351}
352
353/// Civil date `(year, month, day)` from days since the Unix epoch (Howard Hinnant's algorithm).
354fn civil_from_days(days: i64) -> (i64, i64, i64) {
355    let z = days + 719_468;
356    let era = z.div_euclid(146_097);
357    let doe = z - era * 146_097;
358    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
359    let y = yoe + era * 400;
360    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
361    let mp = (5 * doy + 2) / 153;
362    let d = doy - (153 * mp + 2) / 5 + 1;
363    let m = if mp < 10 { mp + 3 } else { mp - 9 };
364    (if m <= 2 { y + 1 } else { y }, m, d)
365}