Skip to content
Merged
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
151 changes: 151 additions & 0 deletions rust/src/parchecker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ struct ActiveStreamingSession {
/// their lost articles, so the repair as the download ends still takes them and
/// certifies them (see [`streaming_session_download_end_targets`]).
rebuilt_files: Mutex<HashSet<FileId>>,
/// The set lists files outside its recovery set: live PAR never verifies those.
non_recoverable: bool,
/// Every file of the set as post-processing first found it fully verified (see
/// [`streaming_session_verified_cover`]): a later change to one ends the trust.
cover_seal: Mutex<Option<Vec<(FileId, crate::parlive::FileStamp)>>>,
// Drop last, after the session, queue and all owned metadata. Grows with
// the syndrome slots as damage appears (see `grow_for_damage`).
budget: Mutex<SessionBudgetLease>,
Expand Down Expand Up @@ -767,6 +772,8 @@ fn build_streaming_session_with(
completed_sources: Mutex::new(HashSet::new()),
rebuilt_recheck: Mutex::new(Vec::new()),
rebuilt_files: Mutex::new(HashSet::new()),
non_recoverable: !main.non_recoverable_file_ids.is_empty(),
cover_seal: Mutex::new(None),
}))
}

Expand Down Expand Up @@ -4678,6 +4685,150 @@ pub(crate) fn streaming_session_verified_target_crc(
)
}

/// What live PAR proved about a download's par2 set by the time post-processing asks: see
/// [`streaming_session_verified_cover`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LiveCover {
/// The par2 file the session was built from.
pub par_name: Vec<u8>,
/// Files of the set (every one of them verified).
pub files: usize,
/// The queue ids of those files.
pub queue_ids: Vec<i32>,
}

/// Whether live PAR of job `nzb_id` has a complete verified state of its par2 set, so a
/// post-processing par-check would only read the set again to learn nothing new:
///
/// - the session is current (not cancelled, stopped or replaced: every RustyGet writer into
/// a source either reported its write to live PAR or stopped it), repairs `dest_dir`, and
/// still takes verified slices as proof (`trust_revoked` unset: each verified byte is the
/// byte written);
/// - every slice of every file is verified, or was rebuilt by a live repair and verified,
/// none diverged after a patch, and no fold is pending;
/// - the set has no file outside its recovery set (live PAR never checks those);
/// - each file of the set is one of `files` (the download's completed queue files as
/// `(queue id, name in dest_dir)`), under its par2 name, the queue file whose bytes live
/// PAR verified for it (its binding, or no other queue file bound to it), and on disk at
/// its par2 length;
/// - and no file changed since the first call that found all this: that call records each
/// file's inode, length and modification time, later ones compare.
///
/// `Err` says what is missing (for the log). Metadata only, at most one `stat` per file;
/// callers may hold the queue lock.
pub(crate) fn streaming_session_verified_cover(
nzb_id: i32,
dest_dir: &Path,
files: &[(i32, Vec<u8>)],
) -> Result<LiveCover, String> {
let entry = active_streaming_session(nzb_id).ok_or("no live PAR session")?;
ensure_current_generation(nzb_id, &entry).map_err(|_| "live PAR stopped".to_string())?;
if entry.base_dir != dest_dir {
return Err("live PAR verified another folder".into());
}
if entry.trust_revoked.load(Ordering::Acquire) {
return Err("a write into a file was not vouched for".into());
}
if entry.non_recoverable {
return Err("the par2 set lists files outside its recovery set".into());
}
let status = entry.session.status();
if status.total == 0
|| status.verified != status.total
|| status.damaged > 0
|| status.unarrived + status.partially_arrived > 0
|| status.pending_folds > 0
{
return Err(format!(
"{} of {} slice(s) verified, {} damaged, {} not arrived",
status.verified,
status.total,
status.damaged,
status.unarrived + status.partially_arrived
));
}
if !entry.session.diverged_slices().is_empty() {
return Err("a slice changed after it was verified".into());
}
if !entry.rebuilt_recheck.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
return Err("a slice rebuilt ahead waits for its file to complete".into());
}
if !entry.rebuilt_files.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
return Err("a file rebuilt ahead is not certified by the end repair yet".into());
}
let bindings = entry
.queue_bindings
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let bound_ids: HashSet<FileId> = bindings.values().copied().collect();
let mut stamps: Vec<(FileId, crate::parlive::FileStamp)> =
Vec::with_capacity(entry.target_names.len());
let mut queue_ids = Vec::with_capacity(entry.target_names.len());
for (queue_id, name) in files {
let Some(id) = entry.session.file_id_by_name(name) else {
continue; // not a file of this set, or not under its par2 name
};
let par_name = entry
.target_names
.get(&id)
.map(|n| par_rs::filenames::os_str_bytes(n.as_os_str()));
if par_name.as_deref() != Some(name.as_slice()) {
continue;
}
let owned = match bindings.get(queue_id) {
Some(bound) => *bound == id,
None => !bound_ids.contains(&id),
};
if !owned {
return Err(format!(
"{} is not the file live PAR verified under that name",
String::from_utf8_lossy(name)
));
}
if stamps.iter().any(|(known, _)| *known == id) {
return Err(format!("two files named {}", String::from_utf8_lossy(name)));
}
let stamp = crate::parlive::FileStamp::of(&dest_dir.join(crate::fsops::path(name)))
.ok_or_else(|| format!("{} is not on disk", String::from_utf8_lossy(name)))?;
if Some(stamp.len()) != entry.file_lengths.get(&id).copied() {
return Err(format!("{} changed length", String::from_utf8_lossy(name)));
}
stamps.push((id, stamp));
queue_ids.push(*queue_id);
}
if stamps.len() != entry.target_names.len() {
return Err(format!(
"{} of {} file(s) under their par2 names",
stamps.len(),
entry.target_names.len()
));
}
stamps.sort_unstable_by_key(|(id, _)| id.0);
let mut seal = entry.cover_seal.lock().unwrap_or_else(|e| e.into_inner());
match seal.as_ref() {
Some(sealed) if *sealed != stamps => {
return Err("a file changed after live PAR verified it".into());
}
Some(_) => {}
None => *seal = Some(stamps),
}
drop(seal);
let par_name = entry.par_name.lock().unwrap_or_else(|e| e.into_inner()).clone();
Ok(LiveCover {
par_name,
files: entry.target_names.len(),
queue_ids,
})
}

/// Whether [`streaming_session_verified_cover`] already recorded job `nzb_id`'s files.
pub(crate) fn streaming_session_cover_sealed(nzb_id: i32) -> bool {
active_streaming_session(nzb_id).is_some_and(|entry| {
entry.cover_seal.lock().unwrap_or_else(|e| e.into_inner()).is_some()
})
}

/// A bounded count upper bound only: the helper must authenticate owned RAM and
/// validate actual recovery rank before patching. This function performs no GF or I/O.
pub(crate) fn streaming_session_can_schedule_repair(nzb_id: i32) -> bool {
Expand Down
106 changes: 106 additions & 0 deletions rust/src/parchecker/live_trust_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,11 @@ fn a_file_rebuilt_ahead_is_certified_once_by_the_end_repair() {
crate::parlive::reserve_control(f.nzb_id, 4096, 500 << 20).unwrap(),
)
.unwrap();
// Every slice verified, but the file is not certified yet: post-processing may not
// take live PAR's word for it until the end repair has.
let named = [(42, b"part01.rar".to_vec())];
let early = streaming_session_verified_cover(f.nzb_id, &f.dir, &named).unwrap_err();
assert!(early.contains("rebuilt ahead"), "{early}");
let lease = request.acquire().unwrap();
let (report, released) = lease
.repair_and_publish(|verified| verified.len(), || ())
Expand All @@ -825,6 +830,7 @@ fn a_file_rebuilt_ahead_is_certified_once_by_the_end_repair() {
assert_eq!(released, 1, "certified");
assert_eq!(streaming_session_download_end_targets(f.nzb_id), None);
assert_eq!(std::fs::read(&path).unwrap(), f.data);
assert!(streaming_session_verified_cover(f.nzb_id, &f.dir, &named).is_ok());
}

/// Feeds the set with slices `lost` failed for good (recovery first), repairs and publishes the
Expand Down Expand Up @@ -934,3 +940,103 @@ fn a_live_repair_reads_nothing_back() {
);
}
}

fn cover(f: &Fixture) -> Result<LiveCover, String> {
streaming_session_verified_cover(f.nzb_id, &f.dir, &[(40, b"part01.rar".to_vec())])
}

/// Every slice verified, the file under its par2 name at its par2 length: post-processing
/// may take that instead of a par-check. Until then it may not.
#[cfg(unix)]
#[test]
fn verified_cover_needs_every_slice_verified() {
let f = fixture(0x7a75_0020, 6, 2, 2);
let entry = active_streaming_session(f.nzb_id).unwrap();
let id = file_id(f.nzb_id);
let half = f.data.chunks(SLICE).count() / 2;
for (i, chunk) in f.data.chunks(SLICE).enumerate().take(half) {
entry
.session
.on_article_finished_memory_only(
&id,
(i * SLICE) as u64,
chunk,
par_rs::crc::crc32(chunk),
)
.unwrap();
}
let partial = cover(&f).unwrap_err();
assert!(partial.contains("slice(s) verified"), "{partial}");
feed_all(&f);
let full = cover(&f).unwrap();
assert_eq!(full.files, 1);
assert_eq!(full.par_name, b"trust.par2".to_vec());
// Asked again with nothing changed: still covered.
assert!(cover(&f).is_ok());
// Not the folder live PAR verified, or no file under the par2 name: not covered.
let elsewhere = f.dir.join("x");
let named = [(40, b"part01.rar".to_vec())];
assert!(streaming_session_verified_cover(f.nzb_id, &elsewhere, &named).is_err());
let obfuscated = [(40, b"q1w2e3".to_vec())];
assert!(streaming_session_verified_cover(f.nzb_id, &f.dir, &obfuscated).is_err());
}

/// A file that changed after the cover was first taken (another inode, length or time) ends
/// the trust: the par-check runs.
#[cfg(unix)]
#[test]
fn verified_cover_ends_when_a_file_changes() {
let f = fixture(0x7a75_0021, 6, 2, 2);
feed_all(&f);
assert!(cover(&f).is_ok());
let path = f.dir.join("part01.rar");
let replacement = f.dir.join("part01.rar.new");
std::fs::write(&replacement, &f.data).unwrap();
std::fs::rename(&replacement, &path).unwrap();
let changed = cover(&f).unwrap_err();
assert!(changed.contains("changed after"), "{changed}");

let g = fixture(0x7a75_0022, 6, 2, 2);
feed_all(&g);
std::fs::write(g.dir.join("part01.rar"), &g.data[..g.data.len() - 1]).unwrap();
let short = cover(&g).unwrap_err();
assert!(short.contains("changed length"), "{short}");
}

/// A write live PAR could not vouch for (trust revoked) or a stopped session: no cover.
#[cfg(unix)]
#[test]
fn verified_cover_needs_trusted_slices_and_a_current_session() {
let f = fixture(0x7a75_0023, 6, 2, 2);
feed_all(&f);
streaming_session_distrust(f.nzb_id, "test");
assert!(cover(&f).unwrap_err().contains("not vouched"));

let g = fixture(0x7a75_0024, 6, 2, 2);
feed_all(&g);
streaming_session_cancel(g.nzb_id);
assert!(cover(&g).is_err());
}

/// The file under the par2 name must be the queue file whose bytes live PAR verified for it:
/// one bound to another par2 file, or an unbound one while another queue file holds the
/// binding (an obfuscated copy), is not covered.
#[cfg(unix)]
#[test]
fn verified_cover_needs_the_file_live_par_verified() {
let f = fixture(0x7a75_0025, 6, 2, 2);
feed_all(&f);
let entry = active_streaming_session(f.nzb_id).unwrap();
let id = file_id(f.nzb_id);
entry.queue_bindings.lock().unwrap().insert(40, FileId([9; 16]));
assert!(cover(&f).unwrap_err().contains("is not the file"));
{
let mut bindings = entry.queue_bindings.lock().unwrap();
bindings.clear();
bindings.insert(41, id);
}
assert!(cover(&f).unwrap_err().contains("is not the file"));
let owner = [(41, b"part01.rar".to_vec())];
let covered = streaming_session_verified_cover(f.nzb_id, &f.dir, &owner).unwrap();
assert_eq!(covered.queue_ids, vec![41]);
}
2 changes: 1 addition & 1 deletion rust/src/parlive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ fn reserve_control_inner(

mod write_control;
pub(crate) use write_control::{
RepairWriteLease, WriteBlocked, WriteCoordinator, WriterIdentity, WriterTarget,
FileStamp, RepairWriteLease, WriteBlocked, WriteCoordinator, WriterIdentity, WriterTarget,
};

#[cfg(all(test, unix))]
Expand Down
4 changes: 4 additions & 0 deletions rust/src/parlive/write_control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ impl FileStamp {
pub(crate) fn of(_path: &std::path::Path) -> Option<Self> {
None
}
/// The file's length in bytes.
pub(crate) fn len(&self) -> u64 {
self.len
}
}
/// A leaf name whose identity a case-insensitive comparison proves on every supported file
/// system: printable ASCII without separators or reserved characters, no trailing dot or
Expand Down
30 changes: 28 additions & 2 deletions rust/src/parrenamer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,19 @@ pub fn execute_all(
)
}

/// The MD5 of a file's first 16 KiB from the queue's `hash16k` (32 hex digits, as the
/// article analyzer stores it). None for anything else.
/// A queue file's 16k hash as the download stores it (`FileStr::Hash16k`, the article
/// analyzer's output): printed the way nzbget prints an MD5, its bytes last to first in
/// upper-case hex (`renameanalyzer::print`). Returns the digest in its own byte order, the
/// order par2 file descriptions and `par_rs` use. Before, the printed text was read as if it
/// were in digest order, so every known hash was reversed: par-rename reported every file
/// it had been told about as missing and asked for a par-check (6790 audit, finding 3).
pub fn parse_printed_hash16k(printed: &[u8]) -> Option<[u8; 16]> {
let mut hash = parse_hash16k(printed)?;
hash.reverse();
Some(hash)
}

/// 32 hex digits read as a 16-byte digest in the order written. None for anything else.
pub fn parse_hash16k(hex: &[u8]) -> Option<[u8; 16]> {
if hex.len() != 32 {
return None;
Expand Down Expand Up @@ -317,6 +328,21 @@ mod tests {
use super::*;
use md5::{Digest, Md5};

/// The analyzer prints a digest backwards; read back, it is the digest a par2 file
/// description holds.
#[test]
fn printed_hash16k_reads_back_in_digest_order() {
let bytes: Vec<u8> = (0..20_000u32).map(|i| (i * 7 + 3) as u8).collect();
let digest: [u8; 16] = Md5::digest(&bytes[..16384]).into();
let mut analyzer = crate::renameanalyzer::Analyzer::default();
analyzer.append(&bytes[..9000]);
analyzer.append(&bytes[9000..]);
let printed = analyzer.finish();
assert_eq!(parse_printed_hash16k(&printed[..32]), Some(digest));
assert_ne!(parse_hash16k(&printed[..32]), Some(digest));
assert_eq!(parse_printed_hash16k(b"not a hash"), None);
}

#[test]
fn splitted_fragments() {
assert!(is_splitted_fragment(b"/d/movie.mkv.001", b"movie.mkv"));
Expand Down
18 changes: 16 additions & 2 deletions rust/src/postproc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3625,6 +3625,19 @@ pub(crate) fn live_repair_should_defer_post(nzb_id: i32) -> bool {
false
}

/// No live PAR work of `nzb_id` is running or still due: no repair helper (download-end or
/// of held direct-unpack volumes) and no completed file waiting to be folded in. Read-only:
/// unlike [`live_repair_should_defer_post`] it starts no clock and cancels nothing.
#[cfg(unix)]
pub(crate) fn live_par_work_idle(nzb_id: i32) -> bool {
!live_end_repair_running(nzb_id)
&& !direct_unpack_holds()
.get(&nzb_id)
.is_some_and(|state| state.live_repair_running)
&& !crate::parchecker::streaming_session_pending_completed_jobs().contains(&nzb_id)
&& !crate::parchecker::streaming_session_completion_drain_active(nzb_id)
}

/// Within `limit` of the last progress at `since`: post-processing still waits.
#[cfg(unix)]
fn live_defer_within(since: std::time::Instant, now: std::time::Instant, limit: Duration) -> bool {
Expand Down Expand Up @@ -6114,7 +6127,8 @@ impl NzbgetRsPostJob {
let n = self.nzb_ptr(host);
let ns = host.nzb_snap(n, false);
// The first-16-KiB MD5 of every file downloaded whole, as its first article
// gave it: par-rename identifies those without reading them.
// gave it (stored printed, bytes last to first): par-rename identifies those
// without reading them.
// (The analyzer sets hash16k only for a first article whose NZB size is at
// least 16 KiB, or a file's only article: the MD5 of min(16 KiB, file size),
// except for a first article that decodes to just under 16 KiB, where the
Expand All @@ -6123,7 +6137,7 @@ impl NzbgetRsPostJob {
let mut known: Vec<(Vec<u8>, [u8; 16])> = (0..host.nzb_completed_files_len(n))
.map(|i| host.nzb_completed_file_at(n, i))
.filter(|f| f.status == crate::queuesubsys_host::CF_SUCCESS && !f.par_file)
.filter_map(|f| Some((f.filename, crate::parrenamer::parse_hash16k(&f.hash16k)?)))
.filter_map(|f| Some((f.filename, crate::parrenamer::parse_printed_hash16k(&f.hash16k)?)))
.collect();
let names: Vec<Vec<u8>> = known.iter().map(|(name, _)| name.clone()).collect();
known.retain(|(name, _)| names.iter().filter(|other| *other == name).count() == 1);
Expand Down
Loading
Loading