From 523a622e966f14a0b127ed0988263571381a1f98 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:11:39 -0800 Subject: [PATCH] RAR volumes read each byte once: the signature probe is the first piece Opening a RAR volume read its first MiB twice: once to find the signature (up to MAX_SFX + 8 bytes in, for a self-extractor) and again as the reader's first piece. The probe's bytes now seed the reader, so every volume's head is read once, SFX detection unchanged. - The checked route recognizes a RAR from its 1 KiB head when the signature is there, and hands the bytes to the volume; the whole window is probed only for a later signature. - extract::run and list keep the file and head the format sniff read; inspect keeps its probe and handle. - A big stored part copied by position (stored_parallel) takes the bytes the volume read with the headers rather than reading them again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/batch.rs | 49 ++++- src/extract.rs | 378 ++++++++++++++++++++++++++++++++++---- src/rar5/reader.rs | 211 +++++++++++++-------- src/zip/read/projected.rs | 2 +- src/zip/session.rs | 5 + 5 files changed, 525 insertions(+), 120 deletions(-) diff --git a/src/batch.rs b/src/batch.rs index b90cc487..28444f0f 100644 --- a/src/batch.rs +++ b/src/batch.rs @@ -427,8 +427,13 @@ fn decode( /// Checks (and, given `out`, copies to `out` from `out_at` on) `len` stored bytes at `at` in the open `volume`, on /// `threads` threads (no more than [`STORED_THREADS`]). Returns the CRC32 of the bytes. +/// +/// `head` is the range's first bytes, read already (no more than `len` of them count): they are checked and copied +/// first, and only the rest is read. +#[allow(clippy::too_many_arguments)] pub(crate) fn stored_detailed( (volume, volume_path): (&File, Option<&Path>), + head: &[u8], at: u64, len: u64, out: Option<(&File, Option<&Path>)>, @@ -436,6 +441,14 @@ pub(crate) fn stored_detailed( threads: usize, cancel: Option<&Cancellation>, ) -> RarResult { + let head = &head[..usize::try_from(len).map_or(head.len(), |len| len.min(head.len()))]; + let mut total = crate::crc32::Hasher::new(); + total.update(head); + if let Some((out, path)) = out { + write_at(out, head, out_at, path)?; + } + let skip = head.len() as u64; + let (at, len, out_at) = (at.saturating_add(skip), len - skip, out_at.saturating_add(skip)); let pieces = len.div_ceil(PIECE) as usize; let crcs: Vec>> = (0..pieces).map(|_| Mutex::new(None)).collect(); let next = AtomicUsize::new(0); @@ -460,7 +473,7 @@ pub(crate) fn stored_detailed( } let off = i as u64 * PIECE; let n = PIECE.min(len - off) as usize; - read_at_detailed(volume, &mut buf[..n], at + off).map_err(|e| match e { + crate::rar5::reader::read_volume(volume, &mut buf[..n], at + off).map_err(|e| match e { PositionReadError::Eof => RarFault::new( RarFailure::integrity( RarScope::Header { @@ -500,7 +513,6 @@ pub(crate) fn stored_detailed( if let Some(e) = first_error.into_inner().unwrap() { return Err(e); } - let mut total = crate::crc32::Hasher::new(); for c in crcs { total.combine(&c.into_inner().unwrap().expect("every piece was done")); } @@ -621,20 +633,45 @@ mod positional_tests { fs::write(&output, b"keep").unwrap(); let write_only = OpenOptions::new().write(true).open(&input).unwrap(); let read_only = File::open(&output).unwrap(); - let fault = stored_detailed((&write_only, Some(&input)), 1, 1, None, 0, 2, None).err().unwrap(); + let fault = stored_detailed((&write_only, Some(&input)), &[], 1, 1, None, 0, 2, None).err().unwrap(); assert!(matches!(fault.failure.as_ref(), RarFailure::Input { operation: IoOperation::Read, path: Some(path), offset: Some(1), source, .. } if path == &input && source.raw_os_error() == Some(libc::EBADF))); let source_file = File::open(&input).unwrap(); - let fault = stored_detailed((&source_file, Some(&input)), 1, 1, Some((&read_only, Some(&output))), 2, 2, None) - .err() - .unwrap(); + let fault = + stored_detailed((&source_file, Some(&input)), &[], 1, 1, Some((&read_only, Some(&output))), 2, 2, None) + .err() + .unwrap(); assert!(matches!(fault.failure.as_ref(), RarFailure::Output { operation: IoOperation::Write, path: Some(path), offset: Some(2), source, .. } if path == &output && source.raw_os_error() == Some(libc::EBADF))); assert_eq!(fs::read(input).unwrap(), b"abcd"); assert_eq!(fs::read(output).unwrap(), b"keep"); } + + /// The bytes a volume read already with the headers are taken, not read again: only the rest comes from the file, + /// and the CRC covers both, in order. + #[test] + fn a_held_head_is_copied_and_only_the_rest_is_read() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("input"); + let data: Vec = (0..3 * PIECE + 17).map(|i| (i * 7) as u8).collect(); + fs::write(&input, [b"head".as_slice(), &data].concat()).unwrap(); + let source = File::open(&input).unwrap(); + for held in [0, 1, 4096, PIECE as usize + 3, data.len(), data.len() + 9] { + // the held bytes differ from the file's, so they show where each byte came from + let head: Vec = (0..held).map(|i| !data.get(i).copied().unwrap_or(0)).collect(); + let mut want = data.clone(); + let taken = held.min(data.len()); + want[..taken].copy_from_slice(&head[..taken]); + let output = dir.path().join(format!("out{held}")); + let out = OpenOptions::new().create(true).truncate(true).read(true).write(true).open(&output).unwrap(); + let crc = + stored_detailed((&source, None), &head, 4, data.len() as u64, Some((&out, None)), 0, 3, None).unwrap(); + assert_eq!(fs::read(&output).unwrap(), want, "held {held}"); + assert_eq!(crc.finalize(), crate::crc32::hash(&want), "held {held}"); + } + } } #[cfg(all(test, target_os = "macos"))] diff --git a/src/extract.rs b/src/extract.rs index 5477f576..06a9d834 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -1538,17 +1538,37 @@ enum Format { const HEAD_PROBE_BYTES: usize = 1024; fn sniff(path: &Path) -> Result { + sniff_held(path).map(|(format, _)| format) +} + +/// The file at `path` and the first bytes [`sniff_held`] read of it, which a RAR volume opened from it keeps rather +/// than reading them again. +struct Sniffed { + file: File, + head: Vec, +} + +impl Sniffed { + fn open_rar(self, path: &Path, password: Option<&str>) -> Result { + Volume::open_head(path, self.file, self.head, password) + } +} + +/// [`sniff`], keeping the file open and its head, for a RAR read of [`Format::Other`]. +fn sniff_held(path: &Path) -> Result<(Format, Option)> { // a spanned set's `.zip` (or `.z01`) starts where the disk before it stopped, often mid-member if crate::zip::is_spanned(path) { - return Ok(Format::Zip); + return Ok((Format::Zip, None)); } - let mut head = [0u8; HEAD_PROBE_BYTES]; + let mut head = vec![0u8; HEAD_PROBE_BYTES]; let mut file = File::open(path)?; let n = crate::tar::read_full(&mut file, &mut head)?; - match classify_head(&head[..n]) { + head.truncate(n); + match classify_head(&head) { // an ISO 9660 image says so 32 KiB in, past the probe - Format::Other if crate::tar::sniff_iso(&file) => Ok(Format::Tar), - format => Ok(format), + Format::Other if crate::tar::sniff_iso(&file) => Ok((Format::Tar, None)), + Format::Other => Ok((Format::Other, Some(Sniffed { file, head }))), + format => Ok((format, None)), } } @@ -1636,8 +1656,14 @@ pub(crate) fn checked_route(path: &Path, cancel: &Cancellation) -> crate::zip::Z Ok(CheckedRoute::Legacy(LegacyRoute::Tar)) } Format::Other => { - let (opened, probe) = opened.probe(SIGNATURE_PROBE_BYTES as usize, cancel)?; - match opened.recognize_rar(&probe) { + // A RAR that starts within the head is recognized from it; a later signature (behind a self-extractor) + // takes the whole window. + let (opened, probe) = if signature_end(&head).is_ok() { + (opened, head) + } else { + opened.probe(SIGNATURE_PROBE_BYTES as usize, cancel)? + }; + match opened.recognize_rar(probe) { Ok((signature, path)) => Ok(CheckedRoute::Legacy(LegacyRoute::Rar { signature, path })), // A byte-split ZIP whose first piece doesn't start with a ZIP signature (a self-extractor, or a // first piece of under four bytes) is still read as the pieces concatenated. @@ -2592,13 +2618,17 @@ pub fn inspect_cancelable(first: &Path, password: Option<&str>, cancel: &Cancell crate::sevenzip::list(first, password)? } Format::Other => { - let signature = signature_end(&source.probe_prefix(SIGNATURE_PROBE_BYTES, cancel)?); + // a RAR that starts within the head is recognized from it; a later one takes the whole window + let probe = if signature_end(&head[..n]).is_ok() { + head[..n].to_vec() + } else { + source.probe_prefix(SIGNATURE_PROBE_BYTES, cancel)? + }; + let signature = signature_end(&probe); cancel.check_io().map_err(Error::from)?; match signature { - Ok(_) => { - drop(source); - rar_list(first, password)? - } + // the volume keeps the bytes read to find the signature rather than reading them again + Ok(_) => rar_list_held(first, Some(Sniffed { file: source.into_file(), head: probe }), password)?, // a byte-split ZIP whose first piece has no ZIP signature at its start, as above Err(Error::NotAnArchive) if crate::zip::is_byte_split(first) => { drop(source); @@ -2639,13 +2669,13 @@ impl Listing { /// [`list_with_password`], with the listing's warnings. pub fn list_detailed(first: &Path, password: Option<&str>) -> Result { let whole = |entries| Listing { entries, missing_volume: None, truncated: false }; - match sniff(first)? { - Format::Zip => return crate::zip::list_detailed(first), - Format::Tar => return crate::tar::list(first).map(whole), - Format::SevenZip => return crate::sevenzip::list(first, password).map(whole), - Format::Other => {} - } - match rar_list(first, password) { + let held = match sniff_held(first)? { + (Format::Zip, _) => return crate::zip::list_detailed(first), + (Format::Tar, _) => return crate::tar::list(first).map(whole), + (Format::SevenZip, _) => return crate::sevenzip::list(first, password).map(whole), + (Format::Other, held) => held, + }; + match rar_list_held(first, held, password) { Err(Error::NotAnArchive) => crate::zip::list_detailed(first), other => other.map(whole), } @@ -2658,13 +2688,13 @@ pub fn list(first: &Path) -> Result> { /// The entries of an archive, decrypting encrypted headers when `password` is given. pub fn list_with_password(first: &Path, password: Option<&str>) -> Result> { - match sniff(first)? { - Format::Zip => return crate::zip::list(first), - Format::Tar => return crate::tar::list(first), - Format::SevenZip => return crate::sevenzip::list(first, password), - Format::Other => {} - } - match rar_list(first, password) { + let held = match sniff_held(first)? { + (Format::Zip, _) => return crate::zip::list(first), + (Format::Tar, _) => return crate::tar::list(first), + (Format::SevenZip, _) => return crate::sevenzip::list(first, password), + (Format::Other, held) => held, + }; + match rar_list_held(first, held, password) { Err(Error::NotAnArchive) => crate::zip::list(first), other => other, } @@ -2930,10 +2960,10 @@ pub fn run_with_renames( password: Option<&str>, mut report: impl FnMut(&str), ) -> std::result::Result { - match sniff(first)? { - Format::Zip => return zip_run(first, opts, password, &mut report), - Format::Tar => return crate::tar::run_reporting(first, opts, &mut report), - Format::SevenZip => { + let held = match sniff_held(first)? { + (Format::Zip, _) => return zip_run(first, opts, password, &mut report), + (Format::Tar, _) => return crate::tar::run_reporting(first, opts, &mut report), + (Format::SevenZip, _) => { let limits = crate::sevenzip::SevenZipLimits::default(); return crate::sevenzip::run_reporting( first, @@ -2944,9 +2974,9 @@ pub fn run_with_renames( &mut report, ); } - Format::Other => {} - } - match rar_run(first, opts, password, &mut report) { + (Format::Other, held) => held, + }; + match rar_run(first, held, opts, password, &mut report) { Err(RunError { error: Error::NotAnArchive, .. }) => zip_run(first, opts, password, &mut report), other => other, } @@ -2964,8 +2994,14 @@ fn zip_run( crate::zip::run_renaming(path, opts, password, None, report) } -fn rar_list(first: &Path, password: Option<&str>) -> Result> { - rar_list_from_volume(Volume::open_with_password(first, password)?, password) +/// The entries of a RAR set from its first volume: the file [`sniff_held`] kept open when it did, else opened by +/// path. +fn rar_list_held(first: &Path, held: Option, password: Option<&str>) -> Result> { + let volume = match held { + Some(held) => held.open_rar(first, password)?, + None => Volume::open_with_password(first, password)?, + }; + rar_list_from_volume(volume, password) } fn rar_list_from_volume(volume: Volume, password: Option<&str>) -> Result> { @@ -3827,12 +3863,16 @@ fn invariant(reason: &'static str, legacy: Error) -> RarFault { fn rar_run( first: &Path, + held: Option, opts: &Options, password: Option<&str>, mut report: impl FnMut(&str), ) -> std::result::Result { let mut reports = Reports::legacy(&mut report); - let result = rar_run_shared(first, opts, password, &mut reports); + let result = rar_run_shared_open(first, opts, password, None, &mut reports, || match held { + Some(Sniffed { file, head }) => Volume::open_head_detailed(first, file, head, password), + None => Volume::open_detailed(first, password), + }); let Reports::Legacy { summary, .. } = reports else { unreachable!() }; legacy_result(result, summary) } @@ -5417,8 +5457,10 @@ impl Run<'_, '_, '_> { } }; let volume_path = vol.path.clone(); + // what the volume read already with the headers is taken from it, not read again let part = batch::stored_detailed( (vol.file(), Some(&volume_path)), + vol.held_at(h.data_at, h.packed_size), h.data_at, h.packed_size, file.as_ref().map(|f| (&f.file, f.target())), @@ -5966,3 +6008,267 @@ mod seven_zip_selected_tests { } } } + +/// Every byte of a RAR volume is read once on the plain paths: the head read to tell the format and find the +/// signature is the volume's first piece, not read again (Prybar's strace of a 10-volume RAR5 set). +#[cfg(all(test, unix))] +mod read_once { + use super::*; + use crate::rar5::reader::VOLUME_READS; + + fn vint(mut v: u64, out: &mut Vec) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + + fn block(kind: u64, mut flags: u64, fields: &[u8], data: Option<&[u8]>) -> Vec { + if data.is_some() { + flags |= 2; + } + let mut body = Vec::new(); + vint(kind, &mut body); + vint(flags, &mut body); + if let Some(data) = data { + vint(data.len() as u64, &mut body); + } + body.extend_from_slice(fields); + let mut sized = Vec::new(); + vint(body.len() as u64, &mut sized); + sized.extend_from_slice(&body); + let mut out = crate::crc32::hash(&sized).to_le_bytes().to_vec(); + out.extend_from_slice(&sized); + out.extend_from_slice(data.unwrap_or_default()); + out + } + + /// A RAR 5.0 set of one stored file split into volumes of `chunk` data bytes, each volume after `prefix`es. + fn volumes(data: &[u8], chunk: usize, prefix: &[u8]) -> Vec> { + let parts: Vec<&[u8]> = data.chunks(chunk).collect(); + let n = parts.len(); + parts + .iter() + .enumerate() + .map(|(i, part)| { + let last = i + 1 == n; + let mut out = if i == 0 { prefix.to_vec() } else { Vec::new() }; + out.extend_from_slice(b"Rar!\x1a\x07\x01\x00"); + let mut main = Vec::new(); + vint(if i == 0 { 1 } else { 3 }, &mut main); + if i > 0 { + vint(i as u64, &mut main); + } + out.extend(block(1, 0, &main, None)); + let mut file = Vec::new(); + vint(0x4, &mut file); + vint(data.len() as u64, &mut file); + vint(0o644, &mut file); + let crc = if last { crate::crc32::hash(data) } else { crate::crc32::hash(part) }; + file.extend_from_slice(&crc.to_le_bytes()); + vint(0, &mut file); + vint(1, &mut file); + vint(4, &mut file); + file.extend_from_slice(b"data"); + let split = if i > 0 { 0x8 } else { 0 } | if last { 0 } else { 0x10 }; + out.extend(block(2, split, &file, Some(part))); + let mut end = Vec::new(); + vint(u64::from(!last), &mut end); + out.extend(block(5, 0, &end, None)); + out + }) + .collect() + } + + fn options(dest: &Path, threads: usize) -> Options { + Options { + mode: Mode::Extract, + dest: dest.to_path_buf(), + overwrite: Overwrite::Always, + flatten: false, + threads: Some(threads), + protected_paths: Default::default(), + parallel_min: None, + select: None, + windows_safe_names: false, + special_entries: Default::default(), + fallback_mtime: None, + compressed_tar: Default::default(), + version_naming: Default::default(), + preexisting_links: Default::default(), + refused_link_placeholder: false, + restart_from_first_volume: false, + replace_placed_links: false, + keep_broken: false, + attempt_continued_members: false, + unsupported_filters: Default::default(), + salvage_truncated_zip: false, + unix_modes: Default::default(), + backslashes: Default::default(), + } + } + + fn identity(path: &Path) -> (u64, u64) { + use std::os::unix::fs::MetadataExt; + let meta = fs::metadata(path).unwrap(); + (meta.dev(), meta.ino()) + } + + /// Where the volume reads recorded from `since` on went, for each of `paths`: every byte of each volume read + /// once, in reads that follow on from each other, the first volume's from `head` on (its first bytes, read to + /// tell its format before any volume opened). + fn assert_read_once(paths: &[PathBuf], since: usize, head: u64) { + let reads = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner())[since..].to_vec(); + for (i, path) in paths.iter().enumerate() { + let id = identity(path); + let mut ranges: Vec<(u64, u64)> = + reads.iter().filter(|(of, _, _)| *of == id).map(|&(_, at, len)| (at, at + len)).collect(); + ranges.sort(); + let mut at = if i == 0 { head } else { 0 }; + for range in ranges { + assert_eq!(range.0, at, "{}: read {range:?} with {at} read so far", path.display()); + at = range.1; + } + assert_eq!(at, fs::metadata(path).unwrap().len(), "{}: bytes read", path.display()); + } + } + + fn write_set(dir: &Path, set: &[Vec]) -> Vec { + set.iter() + .enumerate() + .map(|(i, bytes)| { + let path = dir.join(format!("set.part{}.rar", i + 1)); + fs::write(&path, bytes).unwrap(); + path + }) + .collect() + } + + fn data(len: usize) -> Vec { + (0..len).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect() + } + + #[test] + fn a_rar5_set_reads_each_volume_once() { + let data = data(7 << 20); + for prefix in [&[][..], &[0x4d; 100_000][..]] { + for threads in [1, 4] { + let dir = tempfile::tempdir().unwrap(); + let paths = write_set(dir.path(), &volumes(&data, 5 << 19, prefix)); + let dest = dir.path().join("out"); + let since = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).len(); + let summary = run(&paths[0], &options(&dest, threads), |_| {}).unwrap(); + assert!(summary.errors.is_empty(), "{:?}", summary.errors); + assert_eq!(fs::read(dest.join("data")).unwrap(), data, "prefix {} threads {threads}", prefix.len()); + assert_read_once(&paths, since, HEAD_PROBE_BYTES as u64); + } + } + } + + #[test] + fn the_checked_route_reads_each_volume_once() { + let data = data(5 << 20); + for prefix in [&[][..], &[0x4d; 100_000][..]] { + let dir = tempfile::tempdir().unwrap(); + let paths = write_set(dir.path(), &volumes(&data, 3 << 19, prefix)); + let dest = dir.path().join("out"); + let since = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).len(); + run_with_policy( + &paths[0], + &options(&dest, 2), + None, + &Cancellation::default(), + &crate::zip::EncryptedReadOverrides::default(), + |_: crate::zip::ZipRunEvent<'_>| Ok(()), + ) + .unwrap(); + assert_eq!(fs::read(dest.join("data")).unwrap(), data, "prefix {}", prefix.len()); + // a signature behind a self-extractor is searched for in the whole window, read on the checked route + let head = if prefix.is_empty() { HEAD_PROBE_BYTES as u64 } else { SIGNATURE_PROBE_BYTES }; + assert_read_once(&paths, since, head); + } + } + + #[test] + fn a_rar5_listing_reads_the_first_volume_head_once() { + let data = data(3 << 20); + for prefix in [&[][..], &[0x4d; 100_000][..]] { + let dir = tempfile::tempdir().unwrap(); + let paths = write_set(dir.path(), &volumes(&data, 1 << 20, prefix)); + for lister in + [&(|p: &Path| list(p).unwrap().len()) as &dyn Fn(&Path) -> usize, &|p: &Path| match inspect(p).unwrap() + { + Inspection::Other(entries) => entries.len(), + Inspection::Zip(_) => panic!("a RAR set"), + }] + { + let since = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).len(); + assert_eq!(lister(&paths[0]), 1); + let reads = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner())[since..].to_vec(); + let id = identity(&paths[0]); + let mut ranges: Vec<(u64, u64)> = + reads.iter().filter(|(of, _, _)| *of == id).map(|&(_, at, len)| (at, at + len)).collect(); + ranges.sort(); + for pair in ranges.windows(2) { + assert!(pair[0].1 <= pair[1].0, "read twice: {:?} and {:?}", pair[0], pair[1]); + } + } + } + } + + /// A big stored part is copied on several threads, by position: the part of it the volume read with the headers + /// is taken from there, not read again. + #[test] + fn a_big_stored_part_reads_its_volume_once() { + let data = data(batch::STORED_PARALLEL_MIN as usize + (3 << 19)); + let dir = tempfile::tempdir().unwrap(); + let paths = write_set(dir.path(), &volumes(&data, data.len() - 1000, &[])); + let dest = dir.path().join("out"); + let since = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).len(); + let summary = run(&paths[0], &options(&dest, 4), |_| {}).unwrap(); + assert!(summary.errors.is_empty(), "{:?}", summary.errors); + assert!(fs::read(dest.join("data")).unwrap() == data); + assert_read_once(&paths, since, HEAD_PROBE_BYTES as u64); + } + + #[test] + fn a_rar4_set_reads_each_volume_once() { + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rar4-volumes"); + let dir = tempfile::tempdir().unwrap(); + let paths: Vec = (1..=3) + .map(|i| { + let name = format!("multi.part{i}.rar"); + let path = dir.path().join(&name); + fs::copy(fixtures.join(&name), &path).unwrap(); + path + }) + .collect(); + let dest = dir.path().join("out"); + let since = VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).len(); + let summary = run(&paths[0], &options(&dest, 1), |_| {}).unwrap(); + assert!(summary.errors.is_empty() && summary.files > 0, "{summary:?}"); + assert_read_once(&paths, since, HEAD_PROBE_BYTES as u64); + } + + /// A self-extractor longer than the signature window is still no RAR, as before. + #[test] + fn a_signature_past_the_window_is_not_found() { + let dir = tempfile::tempdir().unwrap(); + let prefix = vec![0x4d; crate::rar5::MAX_SFX as usize + 1]; + let paths = write_set(dir.path(), &volumes(b"small", 8, &prefix)); + assert!(Volume::open(&paths[0]).is_err()); + let file = File::open(&paths[0]).unwrap(); + assert!(Volume::open_head(&paths[0], file, prefix[..1024].to_vec(), None).is_err()); + let mut at_edge = vec![0x4d; crate::rar5::MAX_SFX as usize]; + at_edge.extend_from_slice(&volumes(b"small", 8, &[])[0]); + fs::write(&paths[0], &at_edge).unwrap(); + assert!(Volume::open(&paths[0]).is_ok(), "a signature right at the window's end is found"); + let file = File::open(&paths[0]).unwrap(); + assert!(Volume::open_head(&paths[0], file, at_edge[..1024].to_vec(), None).is_ok()); + } +} diff --git a/src/rar5/reader.rs b/src/rar5/reader.rs index 800fed52..d7cc4269 100644 --- a/src/rar5/reader.rs +++ b/src/rar5/reader.rs @@ -93,6 +93,30 @@ impl SourceError { } } +/// Reads `buf.len()` bytes of a volume at `at`. Every read of a volume's bytes goes through this (here and in +/// [`crate::batch::stored_detailed`]), so a test can check that each byte is read once. +pub(crate) fn read_volume(file: &File, buf: &mut [u8], at: u64) -> std::result::Result<(), PositionReadError> { + #[cfg(all(test, unix))] + count_read(file, at, buf.len()); + read_at_detailed(file, buf, at) +} + +/// A volume read in tests: the file's (device, inode), where, and how many bytes. +#[cfg(all(test, unix))] +pub(crate) type VolumeRead = ((u64, u64), u64, u64); + +/// Every volume read in tests. +#[cfg(all(test, unix))] +pub(crate) static VOLUME_READS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(all(test, unix))] +fn count_read(file: &File, at: u64, len: usize) { + use std::os::unix::fs::MetadataExt; + if let Ok(meta) = file.metadata() { + VOLUME_READS.lock().unwrap_or_else(|e| e.into_inner()).push(((meta.dev(), meta.ino()), at, len as u64)); + } +} + /// Bytes read from a volume at a time. Headers and the data of small files after them come in together, so a /// run of small files takes one read for several of them. const READ: usize = 1 << 20; @@ -207,7 +231,7 @@ fn read_ahead( let n = (len - at).min(READ as u64) as usize; let mut buf = spares.lock().ok().and_then(|s| s.try_recv().ok()).unwrap_or_default(); buf.resize(n, 0); - let read = read_at_detailed(file, &mut buf, at).map(|()| buf); + let read = read_volume(file, &mut buf, at).map(|()| buf); let failed = read.is_err(); if send.send(read).is_err() || failed { return; @@ -217,17 +241,11 @@ fn read_ahead( } impl Source { - fn new(file: File, len: u64) -> Source { - Source { - file, - len, - piece: Piece::new(Vec::new(), None), - at: 0, - off: 0, - sequential: false, - ahead: None, - readers: 1, - } + /// A source whose first piece is `head`, the volume's first bytes as they were read to find its signature, so + /// they aren't read again. At most `len` of them are kept. + fn new(file: File, len: u64, mut head: Vec) -> Source { + head.truncate(usize::try_from(len).unwrap_or(usize::MAX)); + Source { file, len, piece: Piece::new(head, None), at: 0, off: 0, sequential: false, ahead: None, readers: 1 } } /// What is left of the piece in use. @@ -303,7 +321,7 @@ impl Source { // the first piece after a move is read here; read on past it, and the thread takes over let mut buf = used; buf.resize((self.len - from).min(READ as u64) as usize, 0); - read_at_detailed(&self.file, &mut buf, from).map_err(SourceError::Read)?; + read_volume(&self.file, &mut buf, from).map_err(SourceError::Read)?; self.sequential = true; Piece::new(buf, None) } @@ -350,30 +368,41 @@ fn signature_location(head: &[u8]) -> Result<(u64, RarFormat)> { super::framing::SignatureParser::default().advance(head).1.ok_or(Error::NotAnArchive) } +fn signature_fault(e: Error) -> RarFault { + let failure = match e { + Error::NotAnArchive => RarFailure::NotRar, + _ => RarFailure::Unsupported(RarUnsupported::ArchiveVersion(4)), + }; + RarFault::new(failure, e) +} + #[cfg(all(test, unix))] thread_local! { pub(crate) static VOLUME_OPENS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Recognition and its initial held data handle cannot become separated. +/// Recognition and its initial held data handle cannot become separated. The bytes read to recognize it (from the +/// start of the file) are kept, so the volume doesn't read them again. pub(crate) struct HeldSignature { file: File, len: u64, next: u64, format: RarFormat, + head: Vec, } impl HeldSignature { - pub(crate) fn recognize(file: File, len: u64, head: &[u8]) -> std::result::Result { - match signature_location(head) { - Ok((next, format)) => Ok(Self { file, len, next, format }), + pub(crate) fn recognize(file: File, len: u64, head: Vec) -> std::result::Result { + match signature_location(&head) { + Ok((next, format)) => Ok(Self { file, len, next, format, head }), Err(_) => Err(file), } } } impl Volume { pub(crate) fn from_held_signature(path: &Path, signature: HeldSignature, password: Option<&str>) -> Result { - let HeldSignature { file, len, next, format } = signature; - Self::initialize_held(path, file, len, password, next, format, false, None).map_err(RarFault::into_legacy) + let HeldSignature { file, len, next, format, head } = signature; + Self::initialize_held(path, file, len, password, (head, next, format), false, None) + .map_err(RarFault::into_legacy) } #[cfg(any(target_os = "macos", target_os = "linux"))] pub(crate) fn from_held_signature_detailed( @@ -381,8 +410,34 @@ impl Volume { signature: HeldSignature, password: Option<&str>, ) -> RarResult { - let HeldSignature { file, len, next, format } = signature; - Self::initialize_held(path, file, len, password, next, format, true, None) + let HeldSignature { file, len, next, format, head } = signature; + Self::initialize_held(path, file, len, password, (head, next, format), true, None) + } + /// Opens the volume in `file` (at `path`), whose first bytes `head` were read already (to tell its format): they + /// are kept rather than read again, and only what the signature search needs past them is read. + pub(crate) fn open_head(path: &Path, file: File, head: Vec, password: Option<&str>) -> Result { + Self::open_head_impl(path, file, head, password, false).map_err(RarFault::into_legacy) + } + pub(crate) fn open_head_detailed( + path: &Path, + file: File, + head: Vec, + password: Option<&str>, + ) -> RarResult { + Self::open_head_impl(path, file, head, password, true) + } + fn open_head_impl( + path: &Path, + file: File, + head: Vec, + password: Option<&str>, + detailed: bool, + ) -> RarResult { + #[cfg(all(test, unix))] + VOLUME_OPENS.set(VOLUME_OPENS.get() + 1); + let len = volume_length(path, || file.metadata())?; + let found = Self::probe_head(path, &file, len, head)?; + Self::initialize_held(path, file, len, password, found, detailed, None) } pub fn open(path: &Path) -> Result { Self::open_with_password(path, None) @@ -402,9 +457,12 @@ impl Volume { #[cfg(all(test, unix))] VOLUME_OPENS.set(VOLUME_OPENS.get() + 1); let len = volume_length(path, || file.metadata())?; - Self::open_file(path, file, len, password, detailed, None) + let found = Self::probe_head(path, &file, len, Vec::new())?; + Self::initialize_held(path, file, len, password, found, detailed, None) } + /// Opens a volume for the catalogue, whose reads are counted by `budget`: it reads the signature's bytes, and + /// searches the rest of the window only when they aren't one. pub(super) fn open_catalogue( path: &Path, file: File, @@ -412,52 +470,51 @@ impl Volume { password: Option<&str>, budget: &mut ScanBudget<'_>, ) -> RarResult { - Self::open_file(path, file, len, password, true, Some(budget)) - } - - fn open_file( - path: &Path, - file: File, - len: u64, - password: Option<&str>, - detailed: bool, - mut budget: Option<&mut ScanBudget<'_>>, - ) -> RarResult { - let first = if let Some(budget) = budget.as_deref_mut() { - let mut first = [0; SIGNATURE.len()]; - let used = len.min(SIGNATURE.len() as u64) as usize; - budget.read(&file, path, &mut first[..used], 0)?; - Some((first, used)) - } else { - None - }; - let (next, format) = if let Some((first, _)) = first - && first == *SIGNATURE - { + let mut first = [0; SIGNATURE.len()]; + let used = len.min(SIGNATURE.len() as u64) as usize; + budget.read(&file, path, &mut first[..used], 0)?; + let (next, format) = if first == *SIGNATURE { (SIGNATURE.len() as u64, RarFormat::Rar5) - } else if let Some((first, _)) = first - && first.starts_with(SIGNATURE_V4) - { + } else if first.starts_with(SIGNATURE_V4) { (SIGNATURE_V4.len() as u64, RarFormat::Rar4) } else { - Self::probe_signature(path, &file, len, first, budget.as_deref_mut())? + Self::probe_signature(path, &file, len, (first, used), budget)? }; - Self::initialize_held(path, file, len, password, next, format, detailed, budget) + Self::initialize_held(path, file, len, password, (Vec::new(), next, format), true, Some(budget)) } - #[allow(clippy::too_many_arguments)] // Shared post-recognition legacy initialization. + + /// The signature's end and the format, searched for in the volume's first bytes: `head` (read already, from the + /// start of the file), and as much more of the window as the search needs. The bytes read are returned with it, + /// for the volume's first piece, so nothing is read twice. + fn probe_head(path: &Path, file: &File, len: u64, mut head: Vec) -> RarResult<(Vec, u64, RarFormat)> { + head.truncate(usize::try_from(len).unwrap_or(usize::MAX)); + if let Ok((next, format)) = signature_location(&head) { + return Ok((head, next, format)); + } + let want = len.min(SIGNATURE_PROBE_BYTES) as usize; + let have = head.len(); + if have < want { + head.try_reserve_exact(want - have).map_err(|_| allocation())?; + head.resize(want, 0); + read_volume(file, &mut head[have..], have as u64) + .map_err(|e| read_failure(e, Some(path.to_path_buf()), RarIntegrityReason::TruncatedHeader))?; + } + let (next, format) = signature_location(&head).map_err(signature_fault)?; + Ok((head, next, format)) + } + fn initialize_held( path: &Path, file: File, len: u64, password: Option<&str>, - next: u64, - format: RarFormat, + (head, next, format): (Vec, u64, RarFormat), detailed: bool, budget: Option<&mut ScanBudget<'_>>, ) -> RarResult { let mut vol = Volume { path: path.to_path_buf(), - src: Source::new(file, len), + src: Source::new(file, len, head), next, len, main: MainHeader::default(), @@ -486,33 +543,20 @@ impl Volume { Ok(vol) } + /// The catalogue's search of the rest of the signature window, past the `first` bytes it read. fn probe_signature( path: &Path, file: &File, len: u64, - first: Option<([u8; SIGNATURE.len()], usize)>, - budget: Option<&mut ScanBudget<'_>>, + (first, used): ([u8; SIGNATURE.len()], usize), + budget: &mut ScanBudget<'_>, ) -> RarResult<(u64, RarFormat)> { let len = len.min(SIGNATURE_PROBE_BYTES) as usize; - if let (Some(budget), Some((_, used))) = (&budget, first) { - budget.check_read(len - used)?; - } + budget.check_read(len - used)?; let mut head = header_buffer(len)?; - if let Some(budget) = budget { - let (first, used) = first.expect("catalogue probe reads the signature prefix"); - head[..used].copy_from_slice(&first[..used]); - budget.read(file, path, &mut head[used..], used as u64)?; - } else { - read_at_detailed(file, &mut head, 0) - .map_err(|e| read_failure(e, Some(path.to_path_buf()), RarIntegrityReason::TruncatedHeader))?; - } - signature_location(&head).map_err(|e| { - let failure = match e { - Error::NotAnArchive => RarFailure::NotRar, - _ => RarFailure::Unsupported(RarUnsupported::ArchiveVersion(4)), - }; - RarFault::new(failure, e) - }) + head[..used].copy_from_slice(&first[..used]); + budget.read(file, path, &mut head[used..], used as u64)?; + signature_location(&head).map_err(signature_fault) } /// The next block, or None at the physical end of the volume. @@ -680,8 +724,21 @@ impl Volume { result } + /// The bytes from `at` on (no more than `len`) that the volume holds already from its last read: a caller that + /// reads the range itself can take these and start past them. + pub(crate) fn held_at(&self, at: u64, len: u64) -> &[u8] { + let bytes = self.src.piece.bytes(); + match at.checked_sub(self.src.at).and_then(|skip| usize::try_from(skip).ok()) { + Some(skip) if skip < bytes.len() => { + let n = usize::try_from(len).unwrap_or(usize::MAX).min(bytes.len() - skip); + &bytes[skip..skip + n] + } + _ => &[], + } + } + /// The open volume, for reads by position. - pub fn file(&mut self) -> &File { + pub fn file(&self) -> &File { &self.src.file } @@ -816,7 +873,7 @@ mod tests { let file = File::open(&path).unwrap(); let mut volume = Volume { path: path.clone(), - src: Source::new(file, 1), + src: Source::new(file, 1, Vec::new()), next: 0, len: 1, main: MainHeader::default(), @@ -855,7 +912,7 @@ mod tests { std::fs::write(&path, b"one byte").unwrap(); let mut volume = Volume { path: path.clone(), - src: Source::new(File::open(&path).unwrap(), 1), + src: Source::new(File::open(&path).unwrap(), 1, Vec::new()), next: 0, len: 1, main: MainHeader::default(), @@ -896,7 +953,7 @@ mod tests { for readers in [1, 2, 3] { // from the start, from just past it (read on through), and from a far place (started again there) for start in [0, 13, 5 * READ + 77] { - let mut src = Source::new(File::open(&path).unwrap(), data.len() as u64); + let mut src = Source::new(File::open(&path).unwrap(), data.len() as u64, Vec::new()); src.readers = readers; src.seek(start as u64); let mut got = Vec::new(); diff --git a/src/zip/read/projected.rs b/src/zip/read/projected.rs index c876fb3c..ac8d6659 100644 --- a/src/zip/read/projected.rs +++ b/src/zip/read/projected.rs @@ -1467,7 +1467,7 @@ impl CheckedOpen { .map_err(|report| ZipReadError::from(report).with_bootstrap(self.bootstrap.usage())) } - pub(crate) fn recognize_rar(self, head: &[u8]) -> Result<(crate::rar5::reader::HeldSignature, PathBuf), Self> { + pub(crate) fn recognize_rar(self, head: Vec) -> Result<(crate::rar5::reader::HeldSignature, PathBuf), Self> { let Self { file, path, len, source, bootstrap } = self; match crate::rar5::reader::HeldSignature::recognize(file, len, head) { Ok(signature) => Ok((signature, path)), diff --git a/src/zip/session.rs b/src/zip/session.rs index 8c8f1e7f..57d82db3 100644 --- a/src/zip/session.rs +++ b/src/zip/session.rs @@ -304,6 +304,11 @@ impl InspectionSource { Ok(Self { file, source, dispatch_bytes: 0 }) } + /// The data file, for a format other than ZIP to read. + pub(crate) fn into_file(self) -> File { + self.file + } + pub(crate) fn probe_prefix(&mut self, max_len: u64, cancel: &Cancellation) -> Result> { check_cancel(Some(cancel))?; let len = self.file.metadata()?.len().min(max_len) as usize;