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 the `open_decoded` signature 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(path: &Path, drop_cache: bool) -> anyhow::Result<Box<dyn Read + Send>> {
106 open_stream(path, drop_cache)
107}
108
109/// The streaming open. `prepare` runs after the sniff rather than immediately
110/// after `File::open`, because until the head has been read we do not know
111/// whether this is an archive we are allowed to touch.
112///
113/// The cost of that ordering is paid on macOS, and it is larger than the
114/// 512-byte sniff suggests: the file is wrapped in a 64 KiB `BufReader` before
115/// `peek`, so the first read pulls **64 KiB — 16 pages — into the cache before
116/// `F_NOCACHE` is set**. It is paid on *archives*, which are the only inputs
117/// `F_NOCACHE` is ever applied to; plain files are excluded by design and stay
118/// fully cached regardless. Sixteen pages per archive against the alternative
119/// of setting `F_NOCACHE` on a live Apache log is the trade being made.
120fn open_stream(path: &Path, drop_cache: bool) -> anyhow::Result<Box<dyn Read + Send>> {
121 let f = File::open(path)?;
122 let dup = f.try_clone()?;
123 let rdr = io::BufReader::with_capacity(64 * 1024, f);
124 let (head, body) = peek(rdr)?;
125
126 let format = sniff(&head);
127 let drop_cache = drop_cache && format != Format::Plain;
128 crate::resource::prepare(&dup, drop_cache);
129 let guard = CacheGuard { file: dup, drop_cache };
130
131 Ok(match format {
132 Format::Gzip => Guarded::boxed(flate2::read::MultiGzDecoder::new(body), guard),
133 // `zstd`'s reader is streaming like flate2's, so the bounded-memory
134 // guarantee and the cache guard carry over unchanged.
135 Format::Zstd => Guarded::boxed(zstd::stream::read::Decoder::new(body)?, guard),
136 // Multi-stream, like `MultiGzDecoder`: `cat a.xz b.xz` is a valid .xz
137 // and `xz -d` decodes all of it.
138 Format::Xz => Guarded::boxed(liblzma::read::XzDecoder::new_multi_decoder(body), guard),
139 Format::Tar | Format::Plain => Guarded::boxed(body, guard),
140 })
141}
142
143/// Read the sniff window, then hand back a reader with those bytes replayed in
144/// front of the remainder.
145///
146/// The return type is concrete rather than `impl Read`, and carries no `Send`
147/// bound: `Send`-ness is then inferred per call site. `open_decoded`'s
148/// `BufReader<File>` chain is still `Send` (so it boxes into
149/// `Box<dyn Read + Send>` for the worker threads of Task 10), while
150/// `for_each_member` can also call this on a `&mut tar::Entry<'_, R>`, which is
151/// not `Send`.
152/// The sniffed head, and a reader that replays it before the rest.
153type Peeked<R> = (Vec<u8>, io::Chain<io::Cursor<Vec<u8>>, R>);
154
155fn peek<R: Read>(mut rdr: R) -> io::Result<Peeked<R>> {
156 let mut head = vec![0u8; SNIFF_LEN];
157 let mut filled = 0;
158 while filled < head.len() {
159 match rdr.read(&mut head[filled..])? {
160 0 => break,
161 n => filled += n,
162 }
163 }
164 head.truncate(filled);
165 let replay = io::Cursor::new(head.clone());
166 Ok((head, replay.chain(rdr)))
167}
168
169/// Walk every regular member, handing each to `f` as its own reader.
170///
171/// Never returns `Err`: a failure on one member is recorded in `Outcome.errors`
172/// and iteration continues, because one bad archive must not abort the others.
173pub fn for_each_member<R, F>(rdr: R, globs: Option<&crate::source::Globs>, mut f: F) -> Outcome
174where
175 R: Read,
176 F: FnMut(&str, &mut dyn Read) -> io::Result<()>,
177{
178 let mut out = Outcome::default();
179
180 let (head, mut body) = match peek(rdr) {
181 Ok(v) => v,
182 Err(e) => {
183 out.errors.push(format!("read failed: {e}"));
184 return out;
185 }
186 };
187
188 // Not a tar at all: the whole input is a single anonymous member.
189 if sniff(&head) != Format::Tar {
190 out.members_seen = 1;
191 match f("", &mut body) {
192 Ok(()) => out.members_searched = 1,
193 Err(e) => out.errors.push(format!("search failed: {e}")),
194 }
195 return out;
196 }
197
198 let mut ar = tar::Archive::new(body);
199 let entries = match ar.entries() {
200 Ok(e) => e,
201 Err(e) => {
202 out.errors.push(format!("not a readable tar: {e}"));
203 return out;
204 }
205 };
206
207 for entry in entries {
208 let mut entry = match entry {
209 Ok(e) => e,
210 Err(e) => {
211 // Truncated or corrupt: stop this archive, keep what we had.
212 out.errors.push(format!("tar entry: {e}"));
213 break;
214 }
215 };
216
217 // `is_file()` is exactly `== Regular`, which excludes hardlinks,
218 // symlinks, dirs, devices, FIFOs, GNU sparse, @LongLink and pax
219 // headers in one check. Hardlinks in particular carry no content.
220 if !entry.header().entry_type().is_file() {
221 continue;
222 }
223
224 let name = match entry.path() {
225 Ok(p) => p.to_string_lossy().into_owned(),
226 Err(e) => {
227 out.errors.push(format!("bad member path: {e}"));
228 continue;
229 }
230 };
231
232 out.members_seen += 1;
233
234 if globs.is_some_and(|set| !set.is_match(&name)) {
235 continue;
236 }
237
238 // Exactly one level of nesting: logrotate puts access.log.1.gz inside
239 // the tgz. Fixed at one level — that cap is the bomb guard.
240 let (inner_head, mut inner) = match peek(&mut entry) {
241 Ok(v) => v,
242 Err(e) => {
243 out.errors.push(format!("{name}: {e}"));
244 continue;
245 }
246 };
247
248 // Exactly one level, and every compression format — logrotate leaves
249 // `access.log.1.gz` (or `.zst`, `.xz`) inside the archive, so a check that
250 // named only gzip would silently hand a compressed member to the
251 // searcher as binary.
252 let res = match sniff(&inner_head) {
253 Format::Gzip => {
254 let mut dec = flate2::read::MultiGzDecoder::new(&mut inner);
255 f(&name, &mut dec)
256 }
257 Format::Zstd => match zstd::stream::read::Decoder::new(&mut inner) {
258 Ok(mut dec) => f(&name, &mut dec),
259 Err(e) => Err(e),
260 },
261 Format::Xz => {
262 let mut dec = liblzma::read::XzDecoder::new_multi_decoder(&mut inner);
263 f(&name, &mut dec)
264 }
265 _ => f(&name, &mut inner),
266 };
267
268 match res {
269 Ok(()) => out.members_searched += 1,
270 Err(e) => out.errors.push(format!("{name}: {e}")),
271 }
272 }
273
274 out
275}