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                eprintln!(
117                    "trg: {}: buffered inflate fell back to streaming ({e})",
118                    path.display()
119                );
120            }
121        }
122    }
123    open_stream(path, drop_cache)
124}
125
126/// The streaming open. `prepare` runs after the sniff rather than immediately
127/// after `File::open`, because until the head has been read we do not know
128/// whether this is an archive we are allowed to touch.
129///
130/// The cost of that ordering is paid on macOS, and it is larger than the
131/// 512-byte sniff suggests: the file is wrapped in a 64 KiB `BufReader` before
132/// `peek`, so the first read pulls **64 KiB — 16 pages — into the cache before
133/// `F_NOCACHE` is set**. It is paid on *archives*, which are the only inputs
134/// `F_NOCACHE` is ever applied to; plain files are excluded by design and stay
135/// fully cached regardless. Sixteen pages per archive against the alternative
136/// of setting `F_NOCACHE` on a live Apache log is the trade being made.
137fn open_stream(path: &Path, drop_cache: bool) -> anyhow::Result<Box<dyn Read + Send>> {
138    let f = File::open(path)?;
139    let dup = f.try_clone()?;
140    let rdr = io::BufReader::with_capacity(64 * 1024, f);
141    let (head, body) = peek(rdr)?;
142
143    let format = sniff(&head);
144    let drop_cache = drop_cache && format != Format::Plain;
145    crate::resource::prepare(&dup, drop_cache);
146    let guard = CacheGuard { file: dup, drop_cache };
147
148    Ok(match format {
149        Format::Gzip => Guarded::boxed(flate2::read::MultiGzDecoder::new(body), guard),
150        // `zstd`'s reader is streaming like flate2's, so the bounded-memory
151        // guarantee and the cache guard carry over unchanged.
152        Format::Zstd => Guarded::boxed(zstd::stream::read::Decoder::new(body)?, guard),
153        // Multi-stream, like `MultiGzDecoder`: `cat a.xz b.xz` is a valid .xz
154        // and `xz -d` decodes all of it.
155        Format::Xz => Guarded::boxed(liblzma::read::XzDecoder::new_multi_decoder(body), guard),
156        Format::Tar | Format::Plain => Guarded::boxed(body, guard),
157    })
158}
159
160/// Whole-buffer inflate through a handle we control, so the compressed bytes
161/// are read under the same cache policy as the streaming path. `fs::read`
162/// inside `inflate::inflate_buffered` would open its own descriptor, which on
163/// macOS could never carry `F_NOCACHE`.
164///
165/// The guard is dropped at the end of this function rather than travelling
166/// with the returned `Cursor`: by then the file has been read whole and there
167/// is nothing left to keep warm.
168fn inflate_whole(
169    path: &Path,
170    capacity: usize,
171    ceiling: usize,
172    drop_cache: bool,
173) -> io::Result<Vec<u8>> {
174    let mut f = File::open(path)?;
175
176    let mut raw = vec![0u8; SNIFF_LEN];
177    let mut filled = 0;
178    while filled < raw.len() {
179        match f.read(&mut raw[filled..])? {
180            0 => break,
181            n => filled += n,
182        }
183    }
184    raw.truncate(filled);
185
186    let drop_cache = drop_cache && sniff(&raw) != Format::Plain;
187    crate::resource::prepare(&f, drop_cache);
188    let guard = CacheGuard { file: f.try_clone()?, drop_cache };
189
190    f.read_to_end(&mut raw)?;
191    let out = crate::inflate::inflate_bytes(&raw, path, capacity, ceiling);
192    drop(guard);
193    out
194}
195
196/// Like `open_decoded`, but lets the caller choose whole-buffer inflate.
197///
198/// `Strategy::Buffer` is only ever a fast path: a failure there — the ISIZE
199/// hint lied and the retry loop in `inflate_buffered` hit the budget-derived
200/// `ceiling` before it ran out of room, or the data was simply bad — falls
201/// back to `open_decoded`'s streaming path, which always works, and never
202/// fails the search outright. With a small `--inflate-budget` and a large
203/// archive this fallback is the expected, common case, not an error: the
204/// message `inflate_buffered` produces says so.
205///
206/// Signature frozen alongside `open_decoded`; see [`open_decoded_dropping`]
207/// for the cache-dropping variant.
208pub fn open_decoded_with(
209    path: &Path,
210    strategy: crate::inflate::Strategy,
211) -> anyhow::Result<Box<dyn Read + Send>> {
212    open_decoded_dropping(path, strategy, false)
213}
214
215/// Read the sniff window, then hand back a reader with those bytes replayed in
216/// front of the remainder.
217///
218/// The return type is concrete rather than `impl Read`, and carries no `Send`
219/// bound: `Send`-ness is then inferred per call site. `open_decoded`'s
220/// `BufReader<File>` chain is still `Send` (so it boxes into
221/// `Box<dyn Read + Send>` for the worker threads of Task 10), while
222/// `for_each_member` can also call this on a `&mut tar::Entry<'_, R>`, which is
223/// not `Send`.
224fn peek<R: Read>(mut rdr: R) -> io::Result<(Vec<u8>, io::Chain<io::Cursor<Vec<u8>>, R>)> {
225    let mut head = vec![0u8; SNIFF_LEN];
226    let mut filled = 0;
227    while filled < head.len() {
228        match rdr.read(&mut head[filled..])? {
229            0 => break,
230            n => filled += n,
231        }
232    }
233    head.truncate(filled);
234    let replay = io::Cursor::new(head.clone());
235    Ok((head, replay.chain(rdr)))
236}
237
238/// Walk every regular member, handing each to `f` as its own reader.
239///
240/// Never returns `Err`: a failure on one member is recorded in `Outcome.errors`
241/// and iteration continues, because one bad archive must not abort the others.
242pub fn for_each_member<R, F>(rdr: R, globs: Option<&globset::GlobSet>, mut f: F) -> Outcome
243where
244    R: Read,
245    F: FnMut(&str, &mut dyn Read) -> io::Result<()>,
246{
247    let mut out = Outcome::default();
248
249    let (head, mut body) = match peek(rdr) {
250        Ok(v) => v,
251        Err(e) => {
252            out.errors.push(format!("read failed: {e}"));
253            return out;
254        }
255    };
256
257    // Not a tar at all: the whole input is a single anonymous member.
258    if sniff(&head) != Format::Tar {
259        out.members_seen = 1;
260        match f("", &mut body) {
261            Ok(()) => out.members_searched = 1,
262            Err(e) => out.errors.push(format!("search failed: {e}")),
263        }
264        return out;
265    }
266
267    let mut ar = tar::Archive::new(body);
268    let entries = match ar.entries() {
269        Ok(e) => e,
270        Err(e) => {
271            out.errors.push(format!("not a readable tar: {e}"));
272            return out;
273        }
274    };
275
276    for entry in entries {
277        let mut entry = match entry {
278            Ok(e) => e,
279            Err(e) => {
280                // Truncated or corrupt: stop this archive, keep what we had.
281                out.errors.push(format!("tar entry: {e}"));
282                break;
283            }
284        };
285
286        // `is_file()` is exactly `== Regular`, which excludes hardlinks,
287        // symlinks, dirs, devices, FIFOs, GNU sparse, @LongLink and pax
288        // headers in one check. Hardlinks in particular carry no content.
289        if !entry.header().entry_type().is_file() {
290            continue;
291        }
292
293        let name = match entry.path() {
294            Ok(p) => p.to_string_lossy().into_owned(),
295            Err(e) => {
296                out.errors.push(format!("bad member path: {e}"));
297                continue;
298            }
299        };
300
301        out.members_seen += 1;
302
303        if let Some(set) = globs {
304            if !set.is_match(&name) {
305                continue;
306            }
307        }
308
309        // Exactly one level of nesting: logrotate puts access.log.1.gz inside
310        // the tgz. Fixed at one level — that cap is the bomb guard.
311        let (inner_head, mut inner) = match peek(&mut entry) {
312            Ok(v) => v,
313            Err(e) => {
314                out.errors.push(format!("{name}: {e}"));
315                continue;
316            }
317        };
318
319        // Exactly one level, and every compression format — logrotate leaves
320        // `access.log.1.gz` (or `.zst`, `.xz`) inside the archive, so a check that
321        // named only gzip would silently hand a compressed member to the
322        // searcher as binary.
323        let res = match sniff(&inner_head) {
324            Format::Gzip => {
325                let mut dec = flate2::read::MultiGzDecoder::new(&mut inner);
326                f(&name, &mut dec)
327            }
328            Format::Zstd => match zstd::stream::read::Decoder::new(&mut inner) {
329                Ok(mut dec) => f(&name, &mut dec),
330                Err(e) => Err(e),
331            },
332            Format::Xz => {
333                let mut dec = liblzma::read::XzDecoder::new_multi_decoder(&mut inner);
334                f(&name, &mut dec)
335            }
336            _ => f(&name, &mut inner),
337        };
338
339        match res {
340            Ok(()) => out.members_searched += 1,
341            Err(e) => out.errors.push(format!("{name}: {e}")),
342        }
343    }
344
345    out
346}