Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/compat-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,9 +343,10 @@ Where it applies:
header (so just before the `MemberStarted` of a member whose header failed its checksum). See "Damaged headers in a
progressive session" below.

Persistent-partial sessions (`ProgressiveSession::new_partial`) still refuse a damaged header whatever `damaged_input`
says: their journal binds each member to the header bytes it was read from, and a header repaired later would no longer
match. Listings that take no `Options` (`extract::list`, `list_detailed`, `inspect*`) refuse it too. The CLI takes `--salvage` and
Persistent-partial sessions (`ProgressiveSession::new_partial`) honour it too, with the same events and hole rules; a
member read from a damaged header, or after one, is bound to its header's position so that a restart over the same
bytes, or over a header repaired since, finds it again (`docs/persistent-partials.md`, "Damaged headers"). Listings
that take no `Options` (`extract::list`, `list_detailed`, `inspect*`) refuse it too. The CLI takes `--salvage` and
`--resync` (for `l`, `t`, `x`, `e`; a listing of anything but RAR stays as it is), prints each damaged header and a warning, and exits 1.
`tests/rar_salvage.rs` checks each point.

Expand Down
24 changes: 23 additions & 1 deletion docs/persistent-partials.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/progressive-archives.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ runners do, and reports each as `ProgressiveEvent::HeaderDamaged { volume, damag
before. The rule with holes: only delivered bytes are judged. A header the source has not delivered yet is waited on,
one inside a `Hole` answer stops the session with `HeaderHole` (repair may still fill it), and a resync never searches
across a hole. See `docs/compat-options.md` ("Damaged headers in a progressive session"). Persistent-partial sessions
keep refusing damaged headers.
follow the same rules; see `docs/persistent-partials.md` ("Damaged headers") for how their members are bound.

## RAR4 capability boundary

Expand Down
25 changes: 22 additions & 3 deletions src/partial/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2837,13 +2837,32 @@ impl PartialCore {
Ok(())
}
/// Whether part `part` (with its header witness) is already recorded. A recorded part, or a witness at the same
/// archive position, that differs is a `BindingMismatch`: the archive is not the one the member came from.
/// archive position, that differs is a `BindingMismatch`: the archive is not the one the member came from. When
/// either witness was read past as damage, the two may differ in bytes as long as both describe the same member
/// ([`state::same_member_header`]): the header was repaired since, or damaged since; otherwise the member is
/// another one (`BindingMismatch(Member)`). The recorded witness is kept.
pub(crate) fn recorded_part(&self, part: &PlainPart, witness: &HeaderWitness) -> PartialResult<bool> {
let op = self.operation()?;
let evidence = &op.snapshot.evidence;
let old = evidence.headers.iter().find(|old| old.volume == witness.volume && old.packed == witness.packed);
if old.is_some_and(|old| old != witness) {
return Err(err(PartialErrorKind::BindingMismatch(BindingField::Source)));
if let Some(old) = old.filter(|old| *old != witness) {
// A header one of the readings took as damage (a run under `damaged_input` Salvage or Resync) may be
// read whole by the other, once repaired, or damaged by it: the same member only if both readings
// describe the same output. Any other difference is another archive.
if !(old.salvaged || witness.salvaged) {
return Err(err(PartialErrorKind::BindingMismatch(BindingField::Source)));
}
let expected = evidence
.admissions
.iter()
.find(|a| a.volume == witness.volume)
.map_or(std::ffi::OsStr::new(""), |a| a.expected.as_os_str());
let recorded = state::witness_header(old, evidence.format, expected, &self.budget)?;
let read = state::witness_header(witness, evidence.format, expected, &self.budget)
.map_err(|_| err(PartialErrorKind::BindingMismatch(BindingField::Member)))?;
if !state::same_member_header(&recorded, &read) {
return Err(err(PartialErrorKind::BindingMismatch(BindingField::Member)));
}
}
match evidence.parts.iter().find(|old| old.ordinal == part.ordinal) {
Some(recorded) if recorded == part && old.is_some() => Ok(true),
Expand Down
119 changes: 95 additions & 24 deletions src/partial/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ const FORMAT_RAR4: u8 = 4;
/// Header witness page tag of a direct member (created from a member map): no witnesses follow the count, and the
/// tag is followed by the [`DirectFacts`]. Its validity ledger lists only known leaves; unknown output is implicit.
const FORMAT_DIRECT: u8 = 0xD1;
/// Header witness page section listing the witnesses read past as damage ([`HeaderWitness::salvaged`]), version 1:
/// the tag, the version, a count and the ascending witness indices. Written only when some witness is salvaged, and
/// before the format tag, so every other state stays byte-identical and a build that predates it refuses such a
/// state with `StateVersion` (an unknown tag) instead of reading a damaged witness strictly.
const SALVAGED_WITNESSES: u8 = 0x5A;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PageKind {
Geometry = 1,
Expand Down Expand Up @@ -722,6 +727,16 @@ pub(super) fn encode_pages(snapshot: &Snapshot, budget: &PartialBudget) -> Parti
headers.range(&h.packed)?;
headers.blob(&h.bytes)?;
}
let salvaged = snapshot.evidence.headers.iter().filter(|h| h.salvaged).count();
if salvaged > 0 {
headers.reserve(6 + 4 * salvaged)?;
headers.u8(SALVAGED_WITNESSES)?;
headers.u8(1)?;
headers.u32(salvaged.try_into().map_err(|_| malformed())?)?;
for (index, _) in snapshot.evidence.headers.iter().enumerate().filter(|(_, h)| h.salvaged) {
headers.u32(index.try_into().map_err(|_| malformed())?)?;
}
}
// Trailing format tag, written only for RAR4 members so that RAR5 states stay byte-identical and readable by
// builds that predate RAR4 support. States without it are RAR5.
if let Some(direct) = &snapshot.evidence.direct {
Expand Down Expand Up @@ -906,7 +921,26 @@ pub(super) fn decode_pages(
if packed.end - packed.start != bytes.len() as u64 {
return Err(malformed());
}
headers.push(HeaderWitness { volume, packed, bytes });
headers.push(HeaderWitness { volume, packed, bytes, salvaged: false });
}
if d.bytes.get(d.at) == Some(&SALVAGED_WITNESSES) {
d.u8()?;
if d.u8()? != 1 {
return Err(err(PartialErrorKind::StateVersion));
}
let count = d.count(headers.len(), 4)?;
if count == 0 {
return Err(malformed());
}
let mut next = 0;
for _ in 0..count {
let index = d.u32()? as usize;
if index < next || index >= headers.len() {
return Err(malformed());
}
headers[index].salvaged = true;
next = index + 1;
}
}
let mut format = crate::rar5::RarFormat::Rar5;
let mut direct = None;
Expand Down Expand Up @@ -1067,10 +1101,6 @@ pub(super) fn validate_evidence(
evidence: &InitialEvidence,
budget: &PartialBudget,
) -> PartialResult<Option<crate::crypto::Rar5CryptParams>> {
use crate::rar5::{
framing::{HeaderParser, ParserStep},
reader::Block,
};
if evidence.direct.is_some() {
// One synthetic part over the whole output, no packed bytes behind it, no part checks (the member checks
// are in the head), and nothing parsed from an archive.
Expand Down Expand Up @@ -1120,25 +1150,7 @@ pub(super) fn validate_evidence(
if witness.packed.end.checked_sub(witness.packed.start) != Some(witness.bytes.len() as u64) {
return Err(malformed());
}
let mut parser =
HeaderParser::progressive(PathBuf::from(&admission.expected), witness.packed.start, budget.usage.clone());
if evidence.format == crate::rar5::RarFormat::Rar4 {
parser.set_format(crate::rar5::RarFormat::Rar4);
}
let mut step = parser.advance(&[])?.1;
let frame = loop {
match step {
ParserStep::Need { offset, len } => {
let at = offset.checked_sub(witness.packed.start).ok_or_else(malformed)? as usize;
let bytes =
witness.bytes.get(at..at.checked_add(len).ok_or_else(malformed)?).ok_or_else(malformed)?;
step = parser.advance(bytes)?.1;
}
ParserStep::Frame(frame) => break frame,
_ => return Err(malformed()),
}
};
let Block::File(header) = frame.block else { return Err(malformed()) };
let header = witness_header(witness, evidence.format, &admission.expected, budget)?;
if index == 0 {
let actual = crate::extract::Meta::from(&header);
if actual.mtime != evidence.metadata.mtime
Expand Down Expand Up @@ -1208,6 +1220,65 @@ pub(super) fn validate_evidence(
/// count, salt and password check. The parts are one CBC stream, so only the first part's IV is used (a later part
/// restating another is accepted, as member maps accept it), and the tweaked-checksum flag may appear on the final
/// part only (rar 7.00 writes it there), so neither is compared.
/// Parses a header witness again: strictly, or as it stands when it was read past as damage
/// ([`HeaderWitness::salvaged`]), as the session read it. Only a file header is a witness.
pub(super) fn witness_header(
witness: &HeaderWitness,
format: crate::rar5::RarFormat,
expected: &std::ffi::OsStr,
budget: &PartialBudget,
) -> PartialResult<crate::rar5::FileHeader> {
use crate::rar5::{
framing::{HeaderParser, ParserStep},
reader::Block,
};
let mut parser = HeaderParser::progressive(PathBuf::from(expected), witness.packed.start, budget.usage.clone());
if format == crate::rar5::RarFormat::Rar4 {
parser.set_format(crate::rar5::RarFormat::Rar4);
}
if witness.salvaged {
parser.set_salvage(crate::extract::DamagedInput::Salvage);
}
let mut step = parser.advance(&[])?.1;
let frame = loop {
match step {
ParserStep::Need { offset, len } => {
let at = offset.checked_sub(witness.packed.start).ok_or_else(malformed)? as usize;
let bytes = witness.bytes.get(at..at.checked_add(len).ok_or_else(malformed)?).ok_or_else(malformed)?;
step = parser.advance(bytes)?.1;
}
ParserStep::Frame(frame) => break frame,
_ => return Err(malformed()),
}
};
let Block::File(header) = frame.block else { return Err(malformed()) };
Ok(header)
}
/// Whether two readings of the header at one archive position describe the same member as far as its output is
/// concerned: name, sizes, where its data starts, method, checks, splitting, encryption and the host system (which
/// decides how the name is made a path). Times and attributes are left out: they change no output byte. Used when one
/// of the readings was damaged, to rebind a member to its header once the header is repaired.
pub(crate) fn same_member_header(a: &crate::rar5::FileHeader, b: &crate::rar5::FileHeader) -> bool {
let legacy = |h: &crate::rar5::FileHeader| h.rar4.map(|raw| (raw.unpack_version, raw.salt, raw.method));
a.format == b.format
&& a.name == b.name
&& a.packed_size == b.packed_size
&& a.data_at == b.data_at
&& a.unpacked_size == b.unpacked_size
&& a.size_unknown() == b.size_unknown()
&& a.crc32 == b.crc32
&& a.blake2sp == b.blake2sp
&& a.method == b.method
&& a.is_dir() == b.is_dir()
&& a.redirection.is_none()
&& b.redirection.is_none()
&& a.split_before() == b.split_before()
&& a.split_after() == b.split_after()
&& a.encrypted == b.encrypted
&& a.crypt == b.crypt
&& legacy(a) == legacy(b)
&& a.is_unix() == b.is_unix()
}
pub(crate) fn same_member_crypt(
part: Option<&crate::crypto::Rar5CryptParams>,
first: Option<&crate::crypto::Rar5CryptParams>,
Expand Down
59 changes: 59 additions & 0 deletions src/partial/tests/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ impl Fixture {
volume: index as u32,
packed: frame.extent.clone(),
bytes: bytes[frame.extent.start as usize..frame.extent.end as usize].to_vec(),
salvaged: false,
});
}
let checks = MemberChecks {
Expand Down Expand Up @@ -696,3 +697,61 @@ fn a_scattered_hole_costs_the_same_however_many_holes_came_before() {
assert!(late <= early + 64, "a hole cost {early} bytes after 10 holes and {late} after {}", HOLES - 10);
assert_eq!(file.core.operation().unwrap().snapshot.holes.len(), HOLES, "separate holes stay separate");
}

/// A header witness read past as damage (`salvaged`) is stored in a section only such states carry, and parsed
/// again as it stands: a damaged witness decodes when marked salvaged and is refused when not. States with no
/// salvaged witness are byte-identical to before, and a section of an unknown version is `StateVersion`, as an older
/// build reports for the section itself (an unknown trailing tag).
#[test]
fn salvaged_witnesses_persist_in_their_own_section() {
use crate::partial::state::{self, PageKind};
let f = Fixture::new(4096, false, true, false);
let file = f.create();
let op = file.core.operation().unwrap();
let witnesses = |pages: &[(PageKind, Vec<u8>)]| {
let (kind, bytes) = pages.iter().find(|(kind, _)| *kind == PageKind::HeaderWitnesses).unwrap();
state::page_payload(*kind, bytes).unwrap().to_vec()
};
let with = |witnesses: Vec<u8>, pages: &[(PageKind, Vec<u8>)]| -> Vec<(PageKind, Vec<u8>)> {
pages
.iter()
.map(|(kind, bytes)| match kind {
PageKind::HeaderWitnesses => (*kind, state::page_bytes(*kind, &witnesses).unwrap()),
_ => (*kind, bytes.clone()),
})
.collect()
};
let decode = |pages: Vec<(PageKind, Vec<u8>)>| {
state::decode_pages(op.snapshot.head.clone(), pages, &file.core.budget, &[]).map(|s| s.evidence.headers)
};
let (clean, _lease) = state::encode_pages(&op.snapshot, &file.core.budget).unwrap();
assert!(decode(clean.clone()).unwrap().iter().all(|h| !h.salvaged));

let (mut salvaged, _copy) = file.core.clone_snapshot(&op.snapshot).unwrap();
salvaged.evidence.headers[0].salvaged = true;
let (pages, _lease) = state::encode_pages(&salvaged, &file.core.budget).unwrap();
let marked = witnesses(&pages);
let plain = witnesses(&clean);
assert_eq!(marked.len(), plain.len() + 10, "tag, version, count and one index");
assert_eq!(&marked[..plain.len()], &plain[..], "the section follows the witnesses");
assert_eq!(marked[plain.len()], 0x5A);
assert!(decode(pages.clone()).unwrap()[0].salvaged);

// the witness's header CRC hit (its first byte, after the count, volume, range and length): read as it stands
// only when marked so
let header_crc = 4 + 4 + 16 + 4;
let damage = |mut bytes: Vec<u8>| {
bytes[header_crc] ^= 0x5a;
bytes
};
assert!(decode(with(damage(marked.clone()), &pages)).unwrap()[0].salvaged);
assert!(decode(with(damage(plain.clone()), &clean)).is_err(), "a damaged witness is not read strictly");

let mut future = marked.clone();
future[plain.len() + 1] = 2;
assert!(matches!(decode(with(future, &pages)).unwrap_err().kind, PartialErrorKind::StateVersion));
let mut stray = marked;
let last = stray.len() - 4;
stray[last..].copy_from_slice(&7u32.to_le_bytes());
assert!(decode(with(stray, &pages)).is_err(), "an index past the witnesses");
}
2 changes: 2 additions & 0 deletions src/partial/tests/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ impl Fixture {
volume: 0,
packed: frame.extent.clone(),
bytes: bytes[frame.extent.start as usize..frame.extent.end as usize].to_vec(),
salvaged: false,
}],
direct: None,
};
Expand Down Expand Up @@ -721,6 +722,7 @@ fn split_fixture() -> (Fixture, EvidenceUpdate) {
volume,
packed: frame.extent.clone(),
bytes: bytes[..frame.extent.end as usize].to_vec(),
salvaged: false,
}],
direct: None,
}
Expand Down
8 changes: 8 additions & 0 deletions src/partial/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ pub struct MemberKey {
pub(super) identity: [u8; 32],
}
impl MemberKey {
/// The ordinal of a member bound by its header's position rather than its place in the set: a persistent session
/// that honours [`crate::extract::Options::damaged_input`] binds so a member whose first header was read past as
/// damage, and every member after damage in the session, because damage can hide or invent members and so move
/// the ordinals of those after it (see `docs/persistent-partials.md`).
pub const POSITIONAL: u64 = u64::MAX;
pub fn new(binding: ArchiveBinding, ordinal: u64, identity: [u8; 32]) -> Self {
Self { binding, ordinal, identity }
}
Expand Down Expand Up @@ -331,6 +336,9 @@ pub(crate) struct HeaderWitness {
pub volume: u32,
pub packed: Range<u64>,
pub bytes: Vec<u8>,
/// The header failed its checksum and was read as it stands
/// ([`crate::extract::DamagedInput::Salvage`] or `Resync`): it is parsed again the same way.
pub salvaged: bool,
}
#[derive(Clone)]
pub(crate) struct InitialEvidence {
Expand Down
Loading
Loading