Skip to main content

trg/
archive.rs

1//! Turns one input path into a sequence of independently-readable members.
2//!
3//! The load-bearing decision: every tar member is handed to the caller as its
4//! own `Read`. That is what makes per-member line numbers, real member paths,
5//! and per-member binary detection all fall out for free.
6
7use std::fs::File;
8use std::io::{self, Read};
9use std::path::Path;
10
11use crate::sniff::{sniff, Format, SNIFF_LEN};
12
13/// What happened while walking one archive.
14///
15/// `errors` being non-empty is what marks the whole run partial (exit 2), and
16/// it is the **only** thing that does. In particular neither `members_seen !=
17/// members_searched` nor `members_searched == 0` may be read as a partial run:
18/// an archive whose members are all excluded by `-g` yields `seen = 2,
19/// searched = 0, errors = []`, and it was read completely. (`members_searched`
20/// also counts a glob-skipped plain file as searched, so it is not a sound
21/// basis for anything.)
22#[derive(Debug, Default)]
23pub struct Outcome {
24    pub members_seen: usize,
25    pub members_searched: usize,
26    pub errors: Vec<String>,
27    /// Whether any member matched. Set by the caller — `for_each_member` has
28    /// no opinion about what a match is — and it is the authoritative source
29    /// for exit code 0, in place of "did this archive write any bytes".
30    pub matched: bool,
31    /// Advisory lines for stderr. Deliberately **not** `errors`: a note says
32    /// the run read everything and printed less than it found, which is worth
33    /// telling an operator and must not turn a 0 or a 1 into a 2.
34    pub notes: Vec<String>,
35}
36
37/// Drops an archive's page-cache footprint when the reader that owns it dies.
38///
39/// An RAII guard rather than an explicit call after the member walk, for two
40/// reasons. It keeps `open_decoded`/`open_decoded_with` signatures unchanged,
41/// so nothing that already builds on them has to move; and, more importantly,
42/// it fires on the **error** paths too. A truncated archive — logrotate caught
43/// mid-write, the case `tgz_truncated` exists for — bails out of
44/// `for_each_member` early, and its pages are exactly the ones we still want
45/// gone.
46///
47/// The handle here is a `dup` of the one the reader is using. Both share one
48/// open file description, so `F_NOCACHE` set on either applies to both, and
49/// `posix_fadvise` addresses the inode's pages regardless of which fd it is
50/// called through.
51struct CacheGuard {
52    file: File,
53    drop_cache: bool,
54}
55
56impl Drop for CacheGuard {
57    fn drop(&mut self) {
58        crate::resource::finish(&self.file, self.drop_cache);
59    }
60}
61
62/// A reader that carries its `CacheGuard`. Field order is load-bearing: Rust
63/// drops fields in declaration order, so `inner` releases the decompressor and
64/// the underlying handle before `guard` issues `FADV_DONTNEED`.
65struct Guarded<R> {
66    inner: R,
67    /// Never read — it exists only for its `Drop`. Hence the underscore.
68    _guard: CacheGuard,
69}
70
71impl<R: Read> Read for Guarded<R> {
72    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
73        self.inner.read(buf)
74    }
75}
76
77// The guard is only ever read at drop time; `File` is `Send`, so the whole
78// wrapper is, which is what lets it box into `Box<dyn Read + Send>` for the
79// worker threads of Task 10.
80impl<R: Read + Send> Guarded<R> {
81    fn boxed(inner: R, guard: CacheGuard) -> Box<dyn Read + Send>
82    where
83        R: 'static,
84    {
85        Box::new(Guarded { inner, _guard: guard })
86    }
87}
88
89/// Open a path and strip one layer of compression if present.
90///
91/// Signature frozen: Tasks 4 and 8 build on it. Cache-dropping behaviour is
92/// reached through [`open_decoded_dropping`].
93pub fn open_decoded(path: &Path) -> anyhow::Result<Box<dyn Read + Send>> {
94    open_stream(path, false)
95}
96
97/// `open_decoded`, plus the option to hand the archive's pages back to the
98/// kernel once it has been read.
99///
100/// Cache-dropping is decided **here**, per input, and applies to archives
101/// only: `Format::Plain` is left alone no matter what the operator asked for.
102/// Apache holds its live logfiles open for append, and evicting those pages
103/// would evict cache another process is actively using — precisely the harm
104/// this feature exists to prevent.
105pub fn open_decoded_dropping(
106    path: &Path,
107    strategy: crate::inflate::Strategy,
108    drop_cache: bool,
109) -> anyhow::Result<Box<dyn Read + Send>> {
110    if let crate::inflate::Strategy::Buffer { capacity, ceiling } = strategy {
111        match inflate_whole(path, capacity, ceiling, drop_cache) {
112            Ok(bytes) => return Ok(Box::new(io::Cursor::new(bytes))),
113            Err(e) => {
114                // Never fail the search because the fast path did not fit:
115                // fall back to streaming, which always works.
116                let msg = format!("{}: buffered inflate fell back to streaming ({e})", path.display());
117                eprintln!("trg: {}", crate::escape::for_stderr(&msg));
118            }
119        }
120    }
121    open_stream(path, drop_cache)
122}
123
124/// The streaming open. `prepare` runs after the sniff rather than immediately
125/// after `File::open`, because until the head has been read we do not know
126/// whether this is an archive we are allowed to touch.
127///
128/// The cost of that ordering is paid on macOS, and it is larger than the
129/// 512-byte sniff suggests: the file is wrapped in a 64 KiB `BufReader` before
130/// `peek`, so the first read pulls **64 KiB — 16 pages — into the cache before
131/// `F_NOCACHE` is set**. It is paid on *archives*, which are the only inputs
132/// `F_NOCACHE` is ever applied to; plain files are excluded by design and stay
133/// fully cached regardless. Sixteen pages per archive against the alternative
134/// of setting `F_NOCACHE` on a live Apache log is the trade being made.
135fn open_stream(path: &Path, drop_cache: bool) -> anyhow::Result<Box<dyn Read + Send>> {
136    let f = File::open(path)?;
137    let dup = f.try_clone()?;
138    let rdr = io::BufReader::with_capacity(64 * 1024, f);
139    let (head, body) = peek(rdr)?;
140
141    let format = sniff(&head);
142    let drop_cache = drop_cache && format != Format::Plain;
143    crate::resource::prepare(&dup, drop_cache);
144    let guard = CacheGuard { file: dup, drop_cache };
145
146    Ok(match format {
147        Format::Gzip => Guarded::boxed(flate2::read::MultiGzDecoder::new(body), guard),
148        // `zstd`'s reader is streaming like flate2's, so the bounded-memory
149        // guarantee and the cache guard carry over unchanged.
150        Format::Zstd => Guarded::boxed(zstd::stream::read::Decoder::new(body)?, guard),
151        // Multi-stream, like `MultiGzDecoder`: `cat a.xz b.xz` is a valid .xz
152        // and `xz -d` decodes all of it.
153        Format::Xz => Guarded::boxed(liblzma::read::XzDecoder::new_multi_decoder(body), guard),
154        Format::Tar | Format::Plain => Guarded::boxed(body, guard),
155    })
156}
157
158/// Whole-buffer inflate through a handle we control, so the compressed bytes
159/// are read under the same cache policy as the streaming path. `fs::read`
160/// inside `inflate::inflate_buffered` would open its own descriptor, which on
161/// macOS could never carry `F_NOCACHE`.
162///
163/// The guard is dropped at the end of this function rather than travelling
164/// with the returned `Cursor`: by then the file has been read whole and there
165/// is nothing left to keep warm.
166fn inflate_whole(
167    path: &Path,
168    capacity: usize,
169    ceiling: usize,
170    drop_cache: bool,
171) -> io::Result<Vec<u8>> {
172    let mut f = File::open(path)?;
173
174    let mut raw = vec![0u8; SNIFF_LEN];
175    let mut filled = 0;
176    while filled < raw.len() {
177        match f.read(&mut raw[filled..])? {
178            0 => break,
179            n => filled += n,
180        }
181    }
182    raw.truncate(filled);
183
184    let drop_cache = drop_cache && sniff(&raw) != Format::Plain;
185    crate::resource::prepare(&f, drop_cache);
186    let guard = CacheGuard { file: f.try_clone()?, drop_cache };
187
188    f.read_to_end(&mut raw)?;
189    let out = crate::inflate::inflate_bytes(&raw, path, capacity, ceiling);
190    drop(guard);
191    out
192}
193
194/// Like `open_decoded`, but lets the caller choose whole-buffer inflate.
195///
196/// `Strategy::Buffer` is only ever a fast path: a failure there — the ISIZE
197/// hint lied and the retry loop in `inflate_buffered` hit the budget-derived
198/// `ceiling` before it ran out of room, or the data was simply bad — falls
199/// back to `open_decoded`'s streaming path, which always works, and never
200/// fails the search outright. With a small `--inflate-budget` and a large
201/// archive this fallback is the expected, common case, not an error: the
202/// message `inflate_buffered` produces says so.
203///
204/// Signature frozen alongside `open_decoded`; see [`open_decoded_dropping`]
205/// for the cache-dropping variant.
206pub fn open_decoded_with(
207    path: &Path,
208    strategy: crate::inflate::Strategy,
209) -> anyhow::Result<Box<dyn Read + Send>> {
210    open_decoded_dropping(path, strategy, false)
211}
212
213/// Read the sniff window, then hand back a reader with those bytes replayed in
214/// front of the remainder.
215///
216/// The return type is concrete rather than `impl Read`, and carries no `Send`
217/// bound: `Send`-ness is then inferred per call site. `open_decoded`'s
218/// `BufReader<File>` chain is still `Send` (so it boxes into
219/// `Box<dyn Read + Send>` for the worker threads of Task 10), while
220/// `for_each_member` can also call this on a `&mut tar::Entry<'_, R>`, which is
221/// not `Send`.
222/// The sniffed head, and a reader that replays it before the rest.
223type Peeked<R> = (Vec<u8>, io::Chain<io::Cursor<Vec<u8>>, R>);
224
225fn peek<R: Read>(mut rdr: R) -> io::Result<Peeked<R>> {
226    let mut head = vec![0u8; SNIFF_LEN];
227    let mut filled = 0;
228    while filled < head.len() {
229        match rdr.read(&mut head[filled..])? {
230            0 => break,
231            n => filled += n,
232        }
233    }
234    head.truncate(filled);
235    let replay = io::Cursor::new(head.clone());
236    Ok((head, replay.chain(rdr)))
237}
238
239/// Walk every regular member, handing each to `f` as its own reader.
240///
241/// Never returns `Err`: a failure on one member is recorded in `Outcome.errors`
242/// and iteration continues, because one bad archive must not abort the others.
243pub fn for_each_member<R, F>(rdr: R, globs: Option<&globset::GlobSet>, mut f: F) -> Outcome
244where
245    R: Read,
246    F: FnMut(&str, &mut dyn Read) -> io::Result<()>,
247{
248    let mut out = Outcome::default();
249
250    let (head, mut body) = match peek(rdr) {
251        Ok(v) => v,
252        Err(e) => {
253            out.errors.push(format!("read failed: {e}"));
254            return out;
255        }
256    };
257
258    // Not a tar at all: the whole input is a single anonymous member.
259    if sniff(&head) != Format::Tar {
260        out.members_seen = 1;
261        match f("", &mut body) {
262            Ok(()) => out.members_searched = 1,
263            Err(e) => out.errors.push(format!("search failed: {e}")),
264        }
265        return out;
266    }
267
268    let mut ar = tar::Archive::new(body);
269    let entries = match ar.entries() {
270        Ok(e) => e,
271        Err(e) => {
272            out.errors.push(format!("not a readable tar: {e}"));
273            return out;
274        }
275    };
276
277    for entry in entries {
278        let mut entry = match entry {
279            Ok(e) => e,
280            Err(e) => {
281                // Truncated or corrupt: stop this archive, keep what we had.
282                out.errors.push(format!("tar entry: {e}"));
283                break;
284            }
285        };
286
287        // `is_file()` is exactly `== Regular`, which excludes hardlinks,
288        // symlinks, dirs, devices, FIFOs, GNU sparse, @LongLink and pax
289        // headers in one check. Hardlinks in particular carry no content.
290        if !entry.header().entry_type().is_file() {
291            continue;
292        }
293
294        let name = match entry.path() {
295            Ok(p) => p.to_string_lossy().into_owned(),
296            Err(e) => {
297                out.errors.push(format!("bad member path: {e}"));
298                continue;
299            }
300        };
301
302        out.members_seen += 1;
303
304        if globs.is_some_and(|set| !set.is_match(&name)) {
305            continue;
306        }
307
308        // Exactly one level of nesting: logrotate puts access.log.1.gz inside
309        // the tgz. Fixed at one level — that cap is the bomb guard.
310        let (inner_head, mut inner) = match peek(&mut entry) {
311            Ok(v) => v,
312            Err(e) => {
313                out.errors.push(format!("{name}: {e}"));
314                continue;
315            }
316        };
317
318        // Exactly one level, and every compression format — logrotate leaves
319        // `access.log.1.gz` (or `.zst`, `.xz`) inside the archive, so a check that
320        // named only gzip would silently hand a compressed member to the
321        // searcher as binary.
322        let res = match sniff(&inner_head) {
323            Format::Gzip => {
324                let mut dec = flate2::read::MultiGzDecoder::new(&mut inner);
325                f(&name, &mut dec)
326            }
327            Format::Zstd => match zstd::stream::read::Decoder::new(&mut inner) {
328                Ok(mut dec) => f(&name, &mut dec),
329                Err(e) => Err(e),
330            },
331            Format::Xz => {
332                let mut dec = liblzma::read::XzDecoder::new_multi_decoder(&mut inner);
333                f(&name, &mut dec)
334            }
335            _ => f(&name, &mut inner),
336        };
337
338        match res {
339            Ok(()) => out.members_searched += 1,
340            Err(e) => out.errors.push(format!("{name}: {e}")),
341        }
342    }
343
344    out
345}