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 library for the `ox*` CLI tools (`oxtar`/`oxcpio`/`oxcat`/`oxunzip`).
6//!
7//! Each `[[bin]]` is a thin `main` that forwards to a `run_*` entry point here and maps the
8//! returned [`CliError`] onto the unified exit-code contract:
9//!
10//! - **0** — success.
11//! - **1** — runtime failure (I/O error, corrupt archive, decompression-bomb cap hit).
12//! - **2** — usage error (bad/unknown/unsupported flag, missing operand).
13//!
14//! The tools mirror the de-facto `bsdtar`/`bsdcpio`/`bsdcat`/`bsdunzip` interfaces and reuse the
15//! flagship library's logic wholesale (auto-detecting [`reader`], [`extract`], the create/build
16//! functions, and [`decompress`]). Classic flags the library cannot honor faithfully are **not**
17//! silently stubbed: they return a clear `unsupported: <flag>` usage error (exit 2) and are
18//! documented in each tool's `--help`.
19//!
20//! # Safe defaults (an intentional, documented divergence from historical tar)
21//!
22//! Unlike classic `tar`, these tools keep two safety nets **on by default**, because the library is
23//! designed to consume untrusted archives:
24//!
25//! - **Path-traversal rejection**: entries whose sanitized path escapes the destination (`../`,
26//! absolute paths, Windows drive/UNC prefixes) are refused, via [`libarchive_oxide::sanitize`].
27//! - **Decompression-bomb cap**: transparent decompression is capped at [`MAX_DECOMPRESSED`] bytes.
28//!
29//! [`reader`]: libarchive_oxide::reader
30//! [`extract`]: libarchive_oxide::extract::extract
31//! [`decompress`]: libarchive_oxide::decompress
32
33#![forbid(unsafe_code)]
34
35pub mod cat;
36pub mod cpio;
37pub mod tar;
38pub mod unzip;
39
40use std::path::Path;
41
42use libarchive_oxide_core::{EntryData, EntryKind, EntryMeta, EntryReader};
43
44pub use cat::run_cat;
45pub use cpio::run_cpio;
46pub use tar::run_tar;
47pub use unzip::run_unzip;
48
49/// Cap on decompressed size for untrusted input (defends against decompression bombs).
50///
51/// Declared as `u64` so the 4 GiB literal does not overflow `usize` on 32-bit targets; it is
52/// clamped to `usize::MAX` at the call site.
53pub const MAX_DECOMPRESSED: u64 = 4 * 1024 * 1024 * 1024;
54
55/// The decompression-bomb cap as a `usize` (clamped on 32-bit targets).
56#[must_use]
57pub fn decompress_cap() -> usize {
58 usize::try_from(MAX_DECOMPRESSED).unwrap_or(usize::MAX)
59}
60
61/// A CLI failure carrying the exit code it maps to.
62///
63/// The two kinds encode the unified exit-code contract: [`CliError::usage`] → exit 2 (the user
64/// invoked the tool wrong, e.g. an unknown or unsupported flag), [`CliError::runtime`] → exit 1
65/// (the invocation was valid but the work failed). Success is the `Ok` arm, never a `CliError`.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct CliError {
68 /// Human-readable message, printed to stderr as `"<tool>: <message>"`.
69 pub message: String,
70 /// The process exit code this error maps to (1 = runtime, 2 = usage).
71 pub code: u8,
72}
73
74impl CliError {
75 /// A usage error (exit 2): bad, unknown, or unsupported flags; missing operands.
76 pub fn usage(message: impl Into<String>) -> Self {
77 Self {
78 message: message.into(),
79 code: 2,
80 }
81 }
82
83 /// A runtime error (exit 1): a valid invocation whose work failed.
84 pub fn runtime(message: impl Into<String>) -> Self {
85 Self {
86 message: message.into(),
87 code: 1,
88 }
89 }
90
91 /// An "unsupported flag" usage error (exit 2) with a consistent, greppable prefix.
92 pub fn unsupported(flag: impl std::fmt::Display) -> Self {
93 Self::usage(format!("unsupported: {flag}"))
94 }
95}
96
97impl std::fmt::Display for CliError {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 f.write_str(&self.message)
100 }
101}
102
103impl std::error::Error for CliError {}
104
105/// Convenience alias for CLI entry points.
106pub type CliResult = Result<(), CliError>;
107
108/// Reads a file into memory, mapping I/O failure onto a runtime error (exit 1).
109pub(crate) fn read_file(path: &str) -> Result<Vec<u8>, CliError> {
110 std::fs::read(path).map_err(|e| CliError::runtime(format!("cannot read {path}: {e}")))
111}
112
113/// Reads an archive's bytes, auto-detecting compression + format, and lists its entries to stdout.
114///
115/// The output mirrors the de-facto tools: **without** `verbose` one bare pathname per line (what
116/// `bsdtar -t` / GNU `tar -t` emit, so `tar -tf x | while read name` works); **with** `verbose` an
117/// `ls -l`-style long listing (mode, owner, size, mtime, name), matching `bsdtar -tv`.
118///
119/// When `members` is non-empty, only entries whose name matches one of them are listed (the faithful
120/// `tar -t member...` / `cpio -it pattern` selection); an empty slice lists everything. A member
121/// operand that matches no entry is an error (exit 1), never a silent success — see [`MemberFilter`].
122pub(crate) fn list_bytes(
123 bytes: &[u8],
124 password: Option<&[u8]>,
125 members: &[String],
126 verbose: bool,
127) -> CliResult {
128 let plain = libarchive_oxide::decompress_capped(bytes, decompress_cap())
129 .map_err(|e| CliError::runtime(e.to_string()))?;
130 let mut reader = libarchive_oxide::reader_with_password(&plain, password)
131 .map_err(|e| CliError::runtime(e.to_string()))?;
132 let mut filter = MemberFilter::new(members);
133 while let Some(entry) = reader
134 .next_entry()
135 .map_err(|e| CliError::runtime(e.to_string()))?
136 {
137 let meta = entry.meta();
138 if !filter.selects(&meta.path) {
139 continue;
140 }
141 if verbose {
142 println!("{}", format_long(meta));
143 } else {
144 println!("{}", String::from_utf8_lossy(&meta.path));
145 }
146 }
147 filter.ensure_all_matched()
148}
149
150/// Reads an archive's bytes and extracts its entries under `dest` (paths sanitized, size capped).
151///
152/// `verbose` echoes each materialized entry's name to stderr, mirroring `bsdtar -v`. When `members`
153/// is non-empty, only matching entries are extracted (faithful `tar -x member...` selection); an
154/// empty slice with `verbose == false` takes the library's tested batch-extract fast path.
155pub(crate) fn extract_bytes(
156 bytes: &[u8],
157 dest: &Path,
158 password: Option<&[u8]>,
159 verbose: bool,
160 members: &[String],
161) -> CliResult {
162 let plain = libarchive_oxide::decompress_capped(bytes, decompress_cap())
163 .map_err(|e| CliError::runtime(e.to_string()))?;
164 let mut reader = libarchive_oxide::reader_with_password(&plain, password)
165 .map_err(|e| CliError::runtime(e.to_string()))?;
166 if !verbose && members.is_empty() {
167 return libarchive_oxide::extract::extract(&mut reader, dest)
168 .map(|_| ())
169 .map_err(|e| CliError::runtime(e.to_string()));
170 }
171 extract_selected(&mut reader, dest, verbose, members)
172}
173
174/// Extraction with member selection and/or verbose logging. Reuses the same sanitize + kind
175/// dispatch as [`libarchive_oxide::extract::extract`]; only the member filter and the `-v` echo
176/// differ, so the safe-path guarantees (traversal rejection, symlink/device skip) are identical.
177fn extract_selected<R: EntryReader>(
178 reader: &mut R,
179 dest: &Path,
180 verbose: bool,
181 members: &[String],
182) -> CliResult {
183 use std::io::Write;
184
185 std::fs::create_dir_all(dest).map_err(|e| CliError::runtime(e.to_string()))?;
186 let mut filter = MemberFilter::new(members);
187 while let Some(mut entry) = reader
188 .next_entry()
189 .map_err(|e| CliError::runtime(e.to_string()))?
190 {
191 let kind = entry.meta().kind;
192 if !filter.selects(&entry.meta().path) {
193 continue;
194 }
195 let Some(rel) = libarchive_oxide::sanitize(&entry.meta().path) else {
196 continue;
197 };
198 let path = dest.join(&rel);
199 match kind {
200 EntryKind::Dir => {
201 std::fs::create_dir_all(&path).map_err(|e| CliError::runtime(e.to_string()))?;
202 },
203 EntryKind::File => {
204 if let Some(parent) = path.parent() {
205 std::fs::create_dir_all(parent)
206 .map_err(|e| CliError::runtime(e.to_string()))?;
207 }
208 let mut file =
209 std::fs::File::create(&path).map_err(|e| CliError::runtime(e.to_string()))?;
210 let mut buf = [0u8; 16 * 1024];
211 loop {
212 let n = entry
213 .data()
214 .read_chunk(&mut buf)
215 .map_err(|e| CliError::runtime(e.to_string()))?;
216 if n == 0 {
217 break;
218 }
219 file.write_all(&buf[..n])
220 .map_err(|e| CliError::runtime(e.to_string()))?;
221 }
222 if verbose {
223 eprintln!("x {}", rel.display());
224 }
225 },
226 _ => {},
227 }
228 }
229 filter.ensure_all_matched()
230}
231
232/// Selects entries by member operand while tracking which operands actually matched.
233///
234/// An empty operand list selects every entry. Otherwise an operand matches an entry when it equals
235/// the entry name, or the entry lies under a member directory (`member/...`); comparison is on raw
236/// bytes with a trailing `/` normalized away. Crucially, [`selects`](Self::selects) records each
237/// operand it satisfies so that [`ensure_all_matched`](Self::ensure_all_matched) can fail on an
238/// operand that named nothing — mirroring the non-zero exit and `<name>: Not found in archive`
239/// diagnostic that GNU `tar` and `bsdtar`/`bsdcpio` give, rather than the silent exit-0 that a bare
240/// `continue` would produce for a user's typo or wrong member name.
241#[derive(Debug)]
242struct MemberFilter<'m> {
243 members: &'m [String],
244 matched: Vec<bool>,
245}
246
247impl<'m> MemberFilter<'m> {
248 /// Builds a filter over `members`, with every operand initially unmatched.
249 fn new(members: &'m [String]) -> Self {
250 Self {
251 members,
252 matched: vec![false; members.len()],
253 }
254 }
255
256 /// Whether `path` is selected, recording **every** operand it satisfies. An empty operand list
257 /// selects everything (and leaves nothing to check afterwards).
258 fn selects(&mut self, path: &[u8]) -> bool {
259 if self.members.is_empty() {
260 return true;
261 }
262 let entry = trim_trailing_slash(path);
263 let mut selected = false;
264 for (i, m) in self.members.iter().enumerate() {
265 let want = trim_trailing_slash(m.as_bytes());
266 if entry == want
267 || (entry.len() > want.len()
268 && entry.starts_with(want)
269 && entry[want.len()] == b'/')
270 {
271 self.matched[i] = true;
272 selected = true;
273 }
274 }
275 selected
276 }
277
278 /// Fails (exit 1) if any member operand matched no entry, reporting the first such operand as
279 /// `<name>: Not found in archive`. A no-op when the operand list was empty or all matched.
280 fn ensure_all_matched(&self) -> CliResult {
281 match self.matched.iter().position(|&m| !m) {
282 Some(i) => Err(CliError::runtime(format!(
283 "{}: Not found in archive",
284 self.members[i]
285 ))),
286 None => Ok(()),
287 }
288 }
289}
290
291/// Trims a single trailing `/` for name comparison (`sub/` and `sub` name the same member).
292fn trim_trailing_slash(p: &[u8]) -> &[u8] {
293 p.strip_suffix(b"/").unwrap_or(p)
294}
295
296/// Formats one entry as an `ls -l`-style long listing line for `-tv`, matching `bsdtar -tv`'s
297/// mode / owner / size / mtime / name columns (symlinks append ` -> target`).
298fn format_long(meta: &EntryMeta<'_>) -> String {
299 let mode = mode_string(meta.kind, meta.mode);
300 let date = meta.mtime.map_or_else(
301 || "1970-01-01 00:00".to_string(),
302 |t| format_timestamp(t.secs),
303 );
304 let name = String::from_utf8_lossy(&meta.path);
305 match &meta.link_target {
306 Some(target) if matches!(meta.kind, EntryKind::Symlink) => format!(
307 "{mode} {}/{} {:>10} {date} {name} -> {}",
308 meta.uid,
309 meta.gid,
310 meta.size,
311 String::from_utf8_lossy(target),
312 ),
313 _ => format!(
314 "{mode} {}/{} {:>10} {date} {name}",
315 meta.uid, meta.gid, meta.size
316 ),
317 }
318}
319
320/// Builds the 10-char `drwxr-xr-x`-style mode string from an entry kind and permission bits.
321fn mode_string(kind: EntryKind, mode: u32) -> String {
322 let type_ch = match kind {
323 EntryKind::Dir => 'd',
324 EntryKind::Symlink => 'l',
325 EntryKind::Char => 'c',
326 EntryKind::Block => 'b',
327 EntryKind::Fifo => 'p',
328 EntryKind::Socket => 's',
329 _ => '-',
330 };
331 let mut s = String::with_capacity(10);
332 s.push(type_ch);
333 for shift in [6u32, 3, 0] {
334 let bits = (mode >> shift) & 0o7;
335 s.push(if bits & 0o4 != 0 { 'r' } else { '-' });
336 s.push(if bits & 0o2 != 0 { 'w' } else { '-' });
337 s.push(if bits & 0o1 != 0 { 'x' } else { '-' });
338 }
339 s
340}
341
342/// Formats a UNIX timestamp (seconds since the epoch) as `YYYY-MM-DD HH:MM` (UTC), for `-tv`.
343fn format_timestamp(secs: i64) -> String {
344 let days = secs.div_euclid(86_400);
345 let rem = secs.rem_euclid(86_400);
346 let (y, m, d) = civil_from_days(days);
347 let hour = rem / 3600;
348 let min = (rem % 3600) / 60;
349 format!("{y:04}-{m:02}-{d:02} {hour:02}:{min:02}")
350}
351
352/// Civil date `(year, month, day)` from days since the Unix epoch (Howard Hinnant's algorithm).
353fn civil_from_days(days: i64) -> (i64, i64, i64) {
354 let z = days + 719_468;
355 let era = z.div_euclid(146_097);
356 let doe = z - era * 146_097;
357 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
358 let y = yoe + era * 400;
359 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
360 let mp = (5 * doy + 2) / 153;
361 let d = doy - (153 * mp + 2) / 5 + 1;
362 let m = if mp < 10 { mp + 3 } else { mp - 9 };
363 (if m <= 2 { y + 1 } else { y }, m, d)
364}