diff --git a/Cargo.lock b/Cargo.lock index 4f14ea0..24207ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -211,6 +211,12 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arboard" version = "3.7.0" @@ -3569,6 +3575,7 @@ dependencies = [ name = "reclaim" version = "0.2.4" dependencies = [ + "anyhow", "chrono", "core-foundation-sys", "crc32fast", diff --git a/Cargo.toml b/Cargo.toml index 6024612..da92376 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,8 @@ description = "Read-only disk image carving and file recovery" [dependencies] slint = { version = "=1.18.1", default-features = false, features = ["std", "backend-winit", "renderer-software", "compat-1-2", "accessibility"] } log = "=0.4.34" +# One error type for app-level failures (updater, installer, processes); parsers keep io::Result. +anyhow = { version = "=1.0.104", default-features = false, features = ["std"] } rfd = "=0.17.2" serde_json = "=1.0.151" image = { version = "=0.25.10", default-features = false, features = ["ico", "png", "bmp", "jpeg", "gif", "webp"] } @@ -54,8 +56,35 @@ version = "=3.27.0" # Compiler-enforced half of the project audit (tests/audit checks these stay on). [lints.rust] unsafe_op_in_unsafe_fn = "deny" +# Peak tier: compiler lints that catch dead, unclear or misused code. +unused_must_use = "deny" +unused_qualifications = "deny" +unused_lifetimes = "deny" +trivial_casts = "deny" +trivial_numeric_casts = "deny" +let_underscore_drop = "deny" +elided_lifetimes_in_paths = "deny" +meta_variable_misuse = "deny" +non_ascii_idents = "deny" +redundant_lifetimes = "deny" +unit_bindings = "deny" +missing_debug_implementations = "deny" [lints.clippy] +# Peak tier: whole Clippy groups. A lint here is a likely bug, not taste. +correctness = { level = "deny", priority = -1 } +suspicious = { level = "deny", priority = -1 } +perf = { level = "deny", priority = -1 } +complexity = { level = "deny", priority = -1 } +style = { level = "deny", priority = -1 } +pedantic = { level = "deny", priority = -1 } +# Pedantic lints that are taste, not bugs: opted out on purpose. +must_use_candidate = "allow" +too_many_lines = "allow" +module_name_repetitions = "allow" +missing_errors_doc = "allow" +struct_excessive_bools = "allow" +similar_names = "allow" # Panics on malformed input are a denial of service (CWE-248). unwrap_used = "deny" expect_used = "deny" @@ -86,6 +115,53 @@ fallible_impl_from = "deny" get_unwrap = "deny" exit = "deny" let_underscore_must_use = "deny" +# Peak tier, bug-catching picks from nursery and restriction. +wildcard_enum_match_arm = "deny" +match_wildcard_for_single_variants = "deny" +map_err_ignore = "deny" +let_underscore_untyped = "deny" +significant_drop_in_scrutinee = "deny" +significant_drop_tightening = "deny" +collection_is_never_read = "deny" +read_zero_byte_vec = "deny" +literal_string_with_formatting_args = "deny" +debug_assert_with_mut_call = "deny" +path_buf_push_overwrite = "deny" +suspicious_operation_groupings = "deny" +iter_over_hash_type = "deny" +mixed_read_write_in_expression = "deny" +lossy_float_literal = "deny" +float_cmp_const = "deny" +rc_mutex = "deny" +mutex_atomic = "deny" +mutex_integer = "deny" +clone_on_ref_ptr = "deny" +try_err = "deny" +verbose_file_reads = "deny" +filetype_is_file = "deny" +fn_to_numeric_cast_any = "deny" +same_name_method = "deny" +rest_pat_in_fully_bound_structs = "deny" +assertions_on_result_states = "deny" +multiple_unsafe_ops_per_block = "deny" +unnecessary_safety_comment = "deny" +unnecessary_safety_doc = "deny" +infinite_loop = "deny" +error_impl_error = "deny" +string_lit_chars_any = "deny" +suspicious_xor_used_as_pow = "deny" +redundant_clone = "deny" +needless_collect = "deny" +or_fun_call = "deny" +useless_let_if_seq = "deny" +equatable_if_let = "deny" +branches_sharing_code = "deny" +set_contains_or_insert = "deny" +while_float = "deny" +unused_peekable = "deny" +non_send_fields_in_send_ty = "deny" +trait_duplication_in_bounds = "deny" +type_repetition_in_bounds = "deny" [profile.release] opt-level = "z" diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 3bb8107..bde2ab2 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -90,6 +90,14 @@ cargo test --locked cargo clippy --locked --all-targets -- -D warnings ``` +Clippy runs every lint group (including `pedantic`) at `deny`, plus selected +lints that catch likely bugs: unhandled enum variants, discarded error causes, +lock guards held across a `match`, and output that depends on hash order. An +intended exception is a scoped `#[expect(lint, reason = "...")]`. `#[allow]` is +denied, and the audit fails if a required lint is removed from `Cargo.toml`. +Also run Clippy with `--target x86_64-pc-windows-gnu`, because the Windows-only +code is not checked on Linux. + `cargo test` includes the project audit and the headless UI renders. [TESTING.md](TESTING.md) lists every suite, the audit rules, the layout checks, fuzzing, the opt-in hardware tests, CI and the real USB drive results. diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 4dbde9e..9756405 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -211,6 +211,12 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "arbitrary" version = "1.5.0" @@ -230,7 +236,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.61.2", "wl-clipboard-rs", "x11rb", ] @@ -1113,7 +1119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3160,7 +3166,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] @@ -3585,6 +3591,7 @@ dependencies = [ name = "reclaim" version = "0.2.4" dependencies = [ + "anyhow", "chrono", "core-foundation-sys", "crc32fast", @@ -3827,7 +3834,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4416,7 +4423,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5282,7 +5289,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/src/allocation.rs b/src/allocation.rs index 530d91c..4dbec67 100644 --- a/src/allocation.rs +++ b/src/allocation.rs @@ -72,10 +72,10 @@ fn check(cancel: &AtomicBool) -> io::Result<()> { } } fn u16at(b: &[u8], p: usize) -> u64 { - crate::bytes::u16_le(b, p) as u64 + u64::from(crate::bytes::u16_le(b, p)) } fn u32at(b: &[u8], p: usize) -> u64 { - crate::bytes::u32_le(b, p) as u64 + u64::from(crate::bytes::u32_le(b, p)) } fn u64at(b: &[u8], p: usize) -> u64 { crate::bytes::u64_le(b, p) @@ -305,7 +305,8 @@ impl Seek for FreeSpace<'_, R> { SeekFrom::Current(n) => i128::from(self.position) + i128::from(n), SeekFrom::End(n) => i128::from(self.length) + i128::from(n), }; - self.position = u64::try_from(next).map_err(|_| invalid("Invalid candidate position"))?; + self.position = u64::try_from(next) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?; Ok(self.position) } } @@ -316,7 +317,7 @@ impl Seek for FreeSpace<'_, R> { /// first bytes match its type is trusted to own that space; the others stay in /// the list as unverified and their space is still carved, so a newer deleted /// file stored there is not hidden. -fn exclude_known_files(input: &mut (impl Read + Seek), plan: &mut Plan) -> io::Result<()> { +fn exclude_known_files(input: &mut (impl Read + Seek), plan: &mut Plan) { let mut owned: Vec<(u64, u64)> = Vec::new(); for file in &mut plan.files { let Some(extents) = file.extents.clone() else { @@ -347,12 +348,11 @@ fn exclude_known_files(input: &mut (impl Read + Seek), plan: &mut Plan) -> io::R } } if owned.is_empty() { - return Ok(()); + return; } owned.sort_unstable(); plan.ranges = subtract(&plan.ranges, &owned); plan.unused = plan.ranges.iter().map(|(_, length)| length).sum(); - Ok(()) } /// `ranges` with the sorted `owned` ranges cut out. fn subtract(ranges: &[(u64, u64)], owned: &[(u64, u64)]) -> Vec<(u64, u64)> { @@ -401,7 +401,7 @@ pub(crate) fn scan( } result => result?, }; - exclude_known_files(input, &mut plan)?; + exclude_known_files(input, &mut plan); event(crate::Event::UnusedSpace { bytes: plan.unused, filesystem: plan.filesystem, @@ -470,7 +470,7 @@ pub(crate) fn scan( event(crate::Event::Found(file)); } crate::Event::Progress(bytes) => { - event(crate::Event::Progress(scale(bytes.min(length)))) + event(crate::Event::Progress(scale(bytes.min(length)))); } crate::Event::Checking { offset, diff --git a/src/allocation/directory.rs b/src/allocation/directory.rs index 3a15b26..67d9eb0 100644 --- a/src/allocation/directory.rs +++ b/src/allocation/directory.rs @@ -60,8 +60,8 @@ impl Heap { } Some(extents) } - pub(super) fn cluster_count(self, size: u64) -> Option { - Some(size.div_ceil(self.cluster_size).max(1)) + pub(super) fn cluster_count(self, size: u64) -> u64 { + size.div_ceil(self.cluster_size).max(1) } } @@ -84,15 +84,15 @@ pub(super) fn found(name: String, size: u64, extents: Vec<(u64, u64)>) -> Option /// A name from directory data is shown and used as a file name, so it must /// be printable and must not climb or split paths. -pub(super) fn clean_name(name: String) -> Option { - let name = name.trim_end_matches([' ', '.']).to_owned(); +pub(super) fn clean_name(name: &str) -> Option { + let name = name.trim_end_matches([' ', '.']); (!name.is_empty() && name.chars().count() <= 255 && !name .chars() .any(|c| c.is_control() || matches!(c, '/' | '\\' | '\0')) - && !matches!(name.as_str(), "." | "..")) - .then_some(name) + && !matches!(name, "." | "..")) + .then(|| name.to_owned()) } /// Tracks the work budget of one directory walk. @@ -245,7 +245,7 @@ pub(super) fn fat_entries(data: &[u8], fat32: bool) -> Vec { (derived.is_some_and(matches) || matches(b'_')).then_some(long) }); let name = long.or_else(|| short_name(entry, b'_')); - if let Some(name) = name.and_then(clean_name) { + if let Some(name) = name.as_deref().and_then(clean_name) { entries.push(FatEntry::Deleted(name, size, cluster)); } } @@ -269,7 +269,7 @@ pub(super) fn exfat_entries(data: &[u8]) -> Vec { .as_chunks::<32>() .0 .iter() - .map(|r| r.as_slice()) + .map(<[u8; 32]>::as_slice) .collect(); let mut index = 0usize; while let Some(record) = records.get(index) { @@ -329,7 +329,11 @@ pub(super) fn exfat_entries(data: &[u8]) -> Vec { if in_use || length == 0 || units.len() != name_length { continue; } - if let Some(name) = String::from_utf16(&units).ok().and_then(clean_name) { + if let Some(name) = String::from_utf16(&units) + .ok() + .as_deref() + .and_then(clean_name) + { entries.push(ExfatEntry::Deleted(name, length, cluster, contiguous)); } } @@ -457,11 +461,11 @@ mod tests { .wrapping_add(u32::try_from(i).unwrap().wrapping_mul(40_503)); *byte = mixed.to_le_bytes()[1]; } - let _ = fat_entries(&data, seed % 2 == 0); - let _ = exfat_entries(&data); + drop(fat_entries(&data, seed % 2 == 0)); + drop(exfat_entries(&data)); } - assert!(clean_name("../x".into()).is_none()); - assert!(clean_name("a\u{0}b".into()).is_none()); - assert_eq!(clean_name("name. ".into()).as_deref(), Some("name")); + assert!(clean_name("../x").is_none()); + assert!(clean_name("a\u{0}b").is_none()); + assert_eq!(clean_name("name. ").as_deref(), Some("name")); } } diff --git a/src/allocation/ext.rs b/src/allocation/ext.rs index 5875327..6312f58 100644 --- a/src/allocation/ext.rs +++ b/src/allocation/ext.rs @@ -40,7 +40,7 @@ const INCOMPAT_INLINE_DATA: u32 = 0x8000; const INCOMPAT_ENCRYPT: u32 = 0x10000; const INCOMPAT_CASEFOLD: u32 = 0x20000; /// Features that do not change where block bitmaps live or what a bit means. -/// Compression, external journal devices and META_BG descriptor placement are +/// Compression, external journal devices and `META_BG` descriptor placement are /// not in this list, so those volumes are rejected instead of misread. const INCOMPAT_KNOWN: u32 = INCOMPAT_FILETYPE | INCOMPAT_RECOVER diff --git a/src/allocation/fat.rs b/src/allocation/fat.rs index 1547e91..ee00e12 100644 --- a/src/allocation/fat.rs +++ b/src/allocation/fat.rs @@ -1,5 +1,8 @@ use super::directory; -use super::*; +use super::{ + AtomicBool, BitOrder, MAX_MAP, Plan, Read, Seek, check, files_or_none, from_bitmap, invalid, + io, product, read_at, u16at, u32at, u64at, +}; use crate::bytes::to_usize; use std::collections::HashSet; struct Table { @@ -59,7 +62,7 @@ impl Table { } } 16 => u16at(&self.bytes(input, cluster * 2, 2, total, cancel)?, 0), - 32 => u32at(&self.bytes(input, cluster * 4, 4, total, cancel)?, 0) & 0x0fffffff, + 32 => u32at(&self.bytes(input, cluster * 4, 4, total, cancel)?, 0) & 0x0fff_ffff, _ => u32at(&self.bytes(input, cluster * 4, 4, total, cancel)?, 0), }) } @@ -108,7 +111,7 @@ pub(super) fn classic( (32, "FAT32") }; if clusters == 0 - || clusters > 0x0ffffff5 + || clusters > 0x0fff_fff5 || (bits == 32 && (roots != 0 || u16at(b, 22) != 0 || u16at(b, 42) != 0)) || (bits != 32 && (roots == 0 || u16at(b, 22) == 0)) { @@ -172,12 +175,12 @@ pub(super) fn classic( let Some(table) = tables.first_mut() else { return Ok(plan); }; - plan.files = super::files_or_none( + plan.files = files_or_none( classic_files( input, table, bits, - root_directory, + &root_directory, heap, &plan, total, @@ -261,7 +264,7 @@ fn read_clusters( /// The clusters a deleted file stored in one piece from `start` would use, /// if all of them are still unused. fn free_run(plan: &Plan, heap: directory::Heap, start: u64, size: u64) -> Option> { - let count = heap.cluster_count(size)?; + let count = heap.cluster_count(size); let end = start.checked_add(count)?; if end.checked_sub(1)? > heap.last { return None; @@ -284,7 +287,7 @@ fn classic_files( input: &mut (impl Read + Seek), table: &mut Table, bits: u32, - root: Root, + root: &Root, heap: directory::Heap, plan: &Plan, total: u64, @@ -295,7 +298,7 @@ fn classic_files( let mut pending: Vec<(Option, usize)> = vec![(None, 0)]; while let Some((start, depth)) = pending.pop() { check(cancel)?; - let data = match (start.as_ref(), &root) { + let data = match (start.as_ref(), root) { (None, Root::Fixed(at, length)) => { if !budget.take(*length) { break; @@ -366,7 +369,7 @@ pub(super) fn exfat( let root = u32at(b, 96); let flags = u16at(b, 106); if clusters == 0 - || clusters > 0xfffffff5 + || clusters > 0xffff_fff5 || clusters.div_ceil(8) > MAX_MAP as u64 || fat_start < 24 || fat_length == 0 @@ -448,7 +451,7 @@ pub(super) fn exfat( } let next = table.entry(input, current, 64, total, cancel)?; // exFAT uses the full 32-bit value, unlike FAT32's 28-bit entries. - if next >= 0xfffffff8 { + if next >= 0xffff_fff8 { break; } current = next; @@ -501,7 +504,7 @@ pub(super) fn exfat( cluster_size, last: clusters + 1, }; - plan.files = super::files_or_none( + plan.files = files_or_none( exfat_files(input, &mut table, root, heap, &plan, total, cancel), "exFAT", cancel, @@ -528,7 +531,7 @@ fn exfat_files( while let Some((start, length, contiguous, depth)) = pending.pop() { check(cancel)?; let clusters = if contiguous { - let Some(count) = length.and_then(|length| heap.cluster_count(length)) else { + let Some(count) = length.map(|length| heap.cluster_count(length)) else { continue; }; let Some(end) = start.checked_add(count) else { @@ -555,16 +558,16 @@ fn exfat_files( } } directory::ExfatEntry::Deleted(name, size, cluster, contiguous) => { - let mut clusters = None; - if !contiguous + let clusters = if !contiguous && let Some(found) = chain(input, table, cluster, 64, heap, total, cancel)? - && heap.cluster_count(size) == Some(found.len() as u64) + && heap.cluster_count(size) == found.len() as u64 && heap.extents(&found).is_some_and(|extents| { extents.iter().all(|(at, len)| plan.is_unused(*at, *len)) - }) - { - clusters = Some(found); - } + }) { + Some(found) + } else { + None + }; let Some(clusters) = clusters.or_else(|| free_run(plan, heap, cluster, size)) else { continue; diff --git a/src/allocation/indirect.rs b/src/allocation/indirect.rs index 71ac279..eca5163 100644 --- a/src/allocation/indirect.rs +++ b/src/allocation/indirect.rs @@ -75,14 +75,15 @@ fn find_maps( geometry: Geometry, cancel: &AtomicBool, progress: &mut impl FnMut(u64), -) -> io::Result>> { +) -> io::Result>> { let block_size = geometry.block_size; let chunk = CHUNK .checked_div(block_size) .unwrap_or(1) .max(1) .saturating_mul(block_size); - let mut maps = HashMap::new(); + // Ordered, so which map claims a shared child does not depend on hashing. + let mut maps = BTreeMap::new(); let mut runs = 0usize; let mut done = 0u64; let mut buffer = Vec::new(); @@ -202,9 +203,7 @@ pub(super) fn chains( if listed == per_map { let last = blocks_of(runs).last().unwrap_or(0); // The double-indirect map, if written in line, sits between the pieces. - let parent = (1..=3u64) - .filter_map(|gap| parents.get(&last.saturating_add(gap))) - .next(); + let parent = (1..=3u64).find_map(|gap| parents.get(&last.saturating_add(gap))); if let Some(child_runs) = parent.and_then(|parent| maps.get(parent)) { for child in blocks_of(child_runs) { for block in maps @@ -374,7 +373,7 @@ mod tests { |_| {}, ) .unwrap(); - assert!(files.is_empty()); + assert!(files.is_empty(), "{files:?}"); } #[test] diff --git a/src/allocation/journal.rs b/src/allocation/journal.rs index 600908c..f0f442a 100644 --- a/src/allocation/journal.rs +++ b/src/allocation/journal.rs @@ -301,7 +301,7 @@ fn directory_names(block: &[u8], names: &mut HashMap) { && let Some(name) = entry .get(8..length.saturating_add(8)) .and_then(|raw| std::str::from_utf8(raw).ok()) - .and_then(|name| directory::clean_name(name.to_owned())) + .and_then(directory::clean_name) { names.insert(inode, name); } diff --git a/src/allocation/ntfs.rs b/src/allocation/ntfs.rs index f98786c..0410b86 100644 --- a/src/allocation/ntfs.rs +++ b/src/allocation/ntfs.rs @@ -1,4 +1,7 @@ -use super::*; +use super::{ + AtomicBool, BitOrder, MAX_MAP, Ordering, Plan, Read, Seek, check, files_or_none, from_bitmap, + invalid, io, product, read_at, u16at, u32at, u64at, +}; use crate::bytes::to_usize; #[derive(Clone)] struct Stream { @@ -59,7 +62,7 @@ fn data(record: &[u8], clusters: u64, cluster_size: u64) -> io::Result { let mut terminated = false; while at + 4 <= used { let kind = u32at(record, at); - if kind == 0xffffffff { + if kind == 0xffff_ffff { terminated = true; break; } @@ -320,7 +323,7 @@ pub(super) fn plan( cluster_size, clusters, }; - plan.files = super::files_or_none( + plan.files = files_or_none( deleted_files(input, &mft, record_size, geometry, &bitmap, total, cancel), "MFT", cancel, @@ -402,22 +405,18 @@ fn deleted_files( let Some(mut file) = crate::ntfs::deleted_file(raw.to_vec(), geometry, cancel) else { continue; }; - match &file.extents { - Some(extents) => { - if !extents - .iter() - .all(|(at, length)| all_free(bitmap, *at, *length, geometry.cluster_size)) - { - continue; - } - } - None => { - let Some(at) = physical(mft, number * record_size, geometry.cluster_size) - else { - continue; - }; - file.offset = at; + if let Some(extents) = &file.extents { + if !extents + .iter() + .all(|(at, length)| all_free(bitmap, *at, *length, geometry.cluster_size)) + { + continue; } + } else { + let Some(at) = physical(mft, number * record_size, geometry.cluster_size) else { + continue; + }; + file.offset = at; } files.push(file); if files.len() >= MAX_DELETED { diff --git a/src/allocation/tests.rs b/src/allocation/tests.rs index 4cc376d..6edb40f 100644 --- a/src/allocation/tests.rs +++ b/src/allocation/tests.rs @@ -169,7 +169,7 @@ fn run(b: &[u8]) -> (Vec, u64, u64) { assert!(n <= free); progress = n; } - _ => {} + crate::Event::Unreadable { .. } | crate::Event::Checking { .. } => {} }, ) .unwrap(); @@ -177,11 +177,6 @@ fn run(b: &[u8]) -> (Vec, u64, u64) { } #[test] fn occupied_files_are_not_read_or_found_and_free_offsets_export_correctly() { - let (mut b, heap) = fat12(); - let occupied = b"%PDF-1.7\noccupied\n%%EOF"; - let free = b"%PDF-1.7\ndeleted\n%%EOF"; - b[heap..heap + occupied.len()].copy_from_slice(occupied); - b[heap + 512..heap + 512 + free.len()].copy_from_slice(free); struct Audit { input: Cursor>, forbidden: (u64, u64), @@ -206,6 +201,11 @@ fn occupied_files_are_not_read_or_found_and_free_offsets_export_correctly() { self.input.seek(from) } } + let (mut b, heap) = fat12(); + let occupied = b"%PDF-1.7\noccupied\n%%EOF"; + let free = b"%PDF-1.7\ndeleted\n%%EOF"; + b[heap..heap + occupied.len()].copy_from_slice(occupied); + b[heap + 512..heap + 512 + free.len()].copy_from_slice(free); let mut input = Audit { input: Cursor::new(b.clone()), forbidden: (heap as u64, heap as u64 + 512), @@ -213,7 +213,7 @@ fn occupied_files_are_not_read_or_found_and_free_offsets_export_correctly() { let mut files = Vec::new(); scan(&mut input, b.len() as u64, &AtomicBool::new(false), |e| { if let crate::Event::Found(f) = e { - files.push(f) + files.push(f); } }) .unwrap(); @@ -297,14 +297,12 @@ fn exfat_bitmap_is_authoritative_and_metadata_cannot_be_marked_free() { assert_eq!(files.len(), 1); assert_eq!(files[0].offset, at as u64); b[65 * 512] &= !1; - assert!( - plan( - &mut Cursor::new(&b), - b.len() as u64, - &AtomicBool::new(false) - ) - .is_err() - ); + plan( + &mut Cursor::new(&b), + b.len() as u64, + &AtomicBool::new(false), + ) + .unwrap_err(); } #[test] fn unsupported_and_corrupt_maps_never_fall_back_to_full_disk_scanning() { @@ -333,11 +331,10 @@ fn unsupported_and_corrupt_maps_never_fall_back_to_full_disk_scanning() { ); assert_eq!(events, 0); let cancel = AtomicBool::new(true); - assert!( - scan(&mut Cursor::new(&b), b.len() as u64, &cancel, |_| events += - 1) - .is_ok() - ); + scan(&mut Cursor::new(&b), b.len() as u64, &cancel, |_| { + events += 1; + }) + .unwrap(); assert_eq!(events, 0); } #[test] @@ -399,11 +396,13 @@ fn media_faults_skip_free_data_but_never_fabricate_an_allocation_map() { scan(&mut fault, total, &cancel, |e| match e { crate::Event::Found(f) => found.push(f.offset), crate::Event::Unreadable { offset, bytes } => skipped.push((offset, bytes)), - _ => {} + crate::Event::UnusedSpace { .. } + | crate::Event::Progress(_) + | crate::Event::Checking { .. } => {} }) .unwrap(); assert_eq!(found, vec![good_start as u64]); - assert!(!skipped.is_empty()); + assert_ne!(skipped, Vec::<(u64, u64)>::new()); let mut fault = Fault { input: Cursor::new(bytes), bad: 512..1024, @@ -524,7 +523,7 @@ fn hfs_plus_damaged_or_overflowing_maps_fail_closed() { assert_eq!(map(&b).unwrap_err().kind(), io::ErrorKind::Unsupported); let mut b = hfs_plus(); b[1024 + 132..1024 + 136].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(map(&b).is_err()); + map(&b).unwrap_err(); } #[test] fn refs_volumes_are_named_and_never_scanned() { diff --git a/src/detection.rs b/src/detection.rs index 3a6a7f1..0b4b84c 100644 --- a/src/detection.rs +++ b/src/detection.rs @@ -8,13 +8,23 @@ pub(crate) enum CandidateEnd { Invalid, Complete(usize), } +impl CandidateEnd { + /// The verdict for any failure inside data a parser already holds in full. + /// + /// A carving verdict needs no error detail: a bad field, a failed decode or + /// invalid text all mean the bytes are not this format. Used as + /// `.map_err(CandidateEnd::malformed)` so the choice is visible at each site. + pub(crate) fn malformed(_error: E) -> Self { + Self::Invalid + } +} use std::{ collections::BTreeMap, sync::atomic::{AtomicBool, Ordering}, }; pub(crate) fn sqlite_end(bytes: &[u8]) -> CandidateEnd { - use CandidateEnd::*; + use CandidateEnd::{Complete, Invalid, More}; if bytes.len() < 100 { return More; } @@ -145,7 +155,7 @@ impl Ogg { } pub(crate) fn push(&mut self, bytes: &[u8], cancel: &AtomicBool) -> CandidateEnd { - use CandidateEnd::*; + use CandidateEnd::{Complete, Invalid, More}; loop { if cancel.load(Ordering::Relaxed) { return Invalid; diff --git a/src/diagnostics.rs b/src/diagnostics.rs index ecb49f7..d1c0250 100644 --- a/src/diagnostics.rs +++ b/src/diagnostics.rs @@ -124,7 +124,7 @@ pub fn install() { } } if let Err(error) = hardening { - write(&error); + write(&format!("{error:#}")); } if log::set_logger(&LOGGER).is_ok() { log::set_max_level(log::LevelFilter::Info); @@ -150,7 +150,7 @@ pub fn install() { /// file the user opened could run inside Reclaim (CWE-427). One-way and /// process-wide. #[cfg(windows)] -fn restrict_dll_search() -> Result<(), String> { +fn restrict_dll_search() -> anyhow::Result<()> { use windows_sys::Win32::System::LibraryLoader::{ LOAD_LIBRARY_SEARCH_APPLICATION_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, SetDefaultDllDirectories, }; @@ -158,18 +158,21 @@ fn restrict_dll_search() -> Result<(), String> { let ok = unsafe { SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_APPLICATION_DIR) }; - if ok == 0 { - return Err(format!( - // audit-allow(I18N-MISSING): a line in the diagnostic log, not interface text. - "Could not restrict the DLL search path: {}", - std::io::Error::last_os_error() - )); - } + anyhow::ensure!( + ok != 0, + // audit-allow(I18N-MISSING): a line in the diagnostic log, not interface text. + "Could not restrict the DLL search path: {}", + std::io::Error::last_os_error() + ); Ok(()) } #[cfg(not(windows))] -fn restrict_dll_search() -> Result<(), String> { +#[expect( + clippy::unnecessary_wraps, + reason = "same signature as the Windows version, which can fail" +)] +fn restrict_dll_search() -> anyhow::Result<()> { Ok(()) } @@ -178,10 +181,10 @@ fn restrict_dll_search() -> Result<(), String> { pub fn report(summary: &str, details: &str) { use reclaim::i18n; write(&format!("ERROR: {summary}\n{details}")); - let location = LOG_PATH - .get() - .map(|path| i18n::message("Diagnostic log: {0}", &[&path.display().to_string()])) - .unwrap_or_else(|| i18n::t("The diagnostic log could not be written.")); + let location = LOG_PATH.get().map_or_else( + || i18n::t("The diagnostic log could not be written."), + |path| i18n::message("Diagnostic log: {0}", &[&path.display().to_string()]), + ); let display_details: String = details.chars().take(2000).collect(); let hint = i18n::t( "If this is a virtual machine, install or update its graphics drivers or guest additions.", @@ -202,7 +205,7 @@ pub fn report(summary: &str, details: &str) { .encode_utf16() .chain(Some(0)) .collect(); - let title: Vec = reclaim::i18n::t("Reclaim could not continue") + let title: Vec = i18n::t("Reclaim could not continue") .encode_utf16() .chain(Some(0)) .collect(); diff --git a/src/drives.rs b/src/drives.rs index 4169b3e..725d3df 100644 --- a/src/drives.rs +++ b/src/drives.rs @@ -121,6 +121,7 @@ pub fn open_source(path: &Path) -> io::Result { #[cfg(target_os = "linux")] fn object_path(device: &Path) -> io::Result { + use std::fmt::Write as _; use std::os::unix::ffi::OsStrExt; let name = device .file_name() @@ -130,7 +131,8 @@ fn object_path(device: &Path) -> io::Result { if byte.is_ascii_alphanumeric() { path.push(char::from(*byte)); } else { - path.push_str(&format!("_{byte:02x}")); + // Writing to a String cannot fail. + write!(path, "_{byte:02x}").ok(); } } Ok(path) diff --git a/src/drives/linux.rs b/src/drives/linux.rs index 5573934..23c792b 100644 --- a/src/drives/linux.rs +++ b/src/drives/linux.rs @@ -125,15 +125,12 @@ fn unescape(value: &str, octal: bool) -> String { _ => None, }; // Both escape forms are four bytes: the backslash and three more. - match (decoded, tail) { - (Some(byte), [_, _, _, after @ ..]) => { - output.push(byte); - rest = after; - } - _ => { - output.push(first); - rest = tail; - } + if let (Some(byte), [_, _, _, after @ ..]) = (decoded, tail) { + output.push(byte); + rest = after; + } else { + output.push(first); + rest = tail; } } String::from_utf8_lossy(&output).into_owned() @@ -169,7 +166,7 @@ fn discover_at(sys: &Path, dev: &Path, mounts: &Path, udev: &Path) -> std::io::R .entry((*device).into()) .and_modify(|old| { if point == "/" { - *old = point.clone(); + old.clone_from(&point); } }) .or_insert(point); @@ -260,7 +257,7 @@ fn discover_at(sys: &Path, dev: &Path, mounts: &Path, udev: &Path) -> std::io::R .map(|(k, v)| (k.to_owned(), v.to_owned())) }) .collect(); - let get = |key: &str| properties.get(key).map(String::as_str).unwrap_or(""); + let get = |key: &str| properties.get(key).map_or("", String::as_str); let label = labels .get(&fs::canonicalize(&path).unwrap_or_else(|_| path.clone())) .cloned() @@ -269,7 +266,7 @@ fn discover_at(sys: &Path, dev: &Path, mounts: &Path, udev: &Path) -> std::io::R let unlocked = dm_uuid.starts_with("CRYPT-"); let encrypted = get("ID_FS_TYPE") == "crypto_LUKS"; let usb = get("ID_BUS") == "usb" - || fs::canonicalize(&node.sys).ok().is_some_and(|p| { + || fs::canonicalize(&node.sys).is_ok_and(|p| { p.components() .any(|c| c.as_os_str().to_string_lossy().starts_with("usb")) }); @@ -497,7 +494,7 @@ mod tests { ); assert!(!phones[1].name.contains('\u{1b}')); assert!(phones[1].name.chars().count() <= MAX_PHONE_NAME); - assert!(phones_at(&root.path().join("missing")).is_empty()); + assert_eq!(phones_at(&root.path().join("missing")), Vec::::new()); } #[test] @@ -607,7 +604,7 @@ mod tests { let rows = f.discover().unwrap(); assert_eq!(rows.len(), 1); assert!(rows[0].path.ends_with("sdb1")); - assert_eq!(rows[0].size, 119000 * 512); + assert_eq!(rows[0].size, 119_000 * 512); assert_eq!(rows[0].name, "HBCD_PE_X64"); assert!(rows[0].mounted); } @@ -672,11 +669,11 @@ mod tests { fs::remove_dir_all(f.0.path().join("dev/disk")).unwrap(); let rows = f.discover().unwrap(); assert_eq!(rows.len(), 1); - assert_eq!(rows[0].size, 1048576); + assert_eq!(rows[0].size, 1_048_576); assert_eq!(rows[0].sector_size, 512); assert!(!rows[0].mounted); fs::remove_file(f.0.path().join("mountinfo")).unwrap(); - assert!(f.discover().is_err()); + f.discover().unwrap_err(); } #[test] #[ignore = "reads the host kernel inventory; requires Linux sysfs/procfs"] diff --git a/src/drives/macos.rs b/src/drives/macos.rs index a269a66..965116d 100644 --- a/src/drives/macos.rs +++ b/src/drives/macos.rs @@ -1,6 +1,18 @@ //! IOKit/Disk Arbitration discovery; no diskutil or plist conversion process. use super::{Destination, Drive}; -use core_foundation_sys::{base::*, dictionary::*, number::*, string::*, url::*}; +use core_foundation_sys::{ + base::{CFAllocatorRef, CFGetTypeID, CFRelease, CFTypeID, CFTypeRef}, + dictionary::{CFDictionaryGetValue, CFDictionaryRef, CFMutableDictionaryRef}, + number::{ + CFBooleanGetTypeID, CFBooleanGetValue, CFNumberGetTypeID, CFNumberGetValue, + kCFNumberSInt64Type, + }, + string::{ + CFStringCreateWithCString, CFStringGetCString, CFStringGetLength, + CFStringGetMaximumSizeForEncoding, CFStringGetTypeID, CFStringRef, kCFStringEncodingUTF8, + }, + url::{CFURLCopyFileSystemPath, CFURLGetTypeID, kCFURLPOSIXPathStyle}, +}; use std::{ collections::{HashMap, HashSet}, ffi::{CStr, CString}, @@ -62,7 +74,7 @@ impl Drop for Cf { } } } -/// A CFString for a registry or dictionary key; null if the key contains NUL. +/// A `CFString` for a registry or dictionary key; null if the key contains NUL. fn cf_string(text: &str) -> Cf { let Ok(value) = CString::new(text) else { return Cf(ptr::null()); @@ -73,16 +85,26 @@ fn cf_string(text: &str) -> Cf { .cast(), ) } -fn string(value: CFTypeRef) -> Option { +/// Whether `value` is a non-null CF object of the type `type_id` names. +fn is_type(value: CFTypeRef, type_id: unsafe extern "C" fn() -> CFTypeID) -> bool { + if value.is_null() { + return false; + } + // SAFETY: the CF `*GetTypeID` functions take no arguments and return a constant. + let expected = unsafe { type_id() }; // SAFETY: value is a non-null CF object borrowed for the duration of the call. - if value.is_null() || unsafe { CFGetTypeID(value) != CFStringGetTypeID() } { + let actual = unsafe { CFGetTypeID(value) }; + actual == expected +} +fn string(value: CFTypeRef) -> Option { + if !is_type(value, CFStringGetTypeID) { return None; } let value = value.cast(); // SAFETY: value was checked above to be a CFString. - let length = unsafe { - CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) - }; + let characters = unsafe { CFStringGetLength(value) }; + // SAFETY: a plain size calculation on a character count; no pointers. + let length = unsafe { CFStringGetMaximumSizeForEncoding(characters, kCFStringEncodingUTF8) }; if !(0..=1024 * 1024).contains(&length) { return None; } @@ -109,24 +131,18 @@ fn string(value: CFTypeRef) -> Option { ) } fn boolean(value: CFTypeRef) -> bool { - !value.is_null() - // SAFETY: the type ID is checked before value is read as a CFBoolean. - && unsafe { CFGetTypeID(value) == CFBooleanGetTypeID() && CFBooleanGetValue(value.cast()) } + is_type(value, CFBooleanGetTypeID) + // SAFETY: value was checked to be a CFBoolean just before it is read. + && unsafe { CFBooleanGetValue(value.cast()) } } fn number(value: CFTypeRef) -> Option { - // SAFETY: value is a non-null CF object borrowed for the duration of the call. - if value.is_null() || unsafe { CFGetTypeID(value) != CFNumberGetTypeID() } { + if !is_type(value, CFNumberGetTypeID) { return None; } let mut number = 0i64; // SAFETY: value is a CFNumber (checked above) and number is a valid i64 out-pointer. - let ok = unsafe { - CFNumberGetValue( - value.cast(), - kCFNumberSInt64Type, - (&mut number as *mut i64).cast(), - ) - }; + let ok = + unsafe { CFNumberGetValue(value.cast(), kCFNumberSInt64Type, (&raw mut number).cast()) }; if ok { u64::try_from(number).ok() } else { None } } fn property(entry: u32, key: &str) -> Cf { @@ -159,7 +175,7 @@ fn valid_id(id: &str) -> bool { fn registry_id(object: u32) -> Option { let mut id = 0; // SAFETY: object is a live registry entry and id a valid out-pointer. - (unsafe { IORegistryEntryGetRegistryEntryID(object, &mut id) } == 0).then_some(id) + (unsafe { IORegistryEntryGetRegistryEntryID(object, &raw mut id) } == 0).then_some(id) } fn ancestors(object: u32) -> Vec { let mut ids = Vec::new(); @@ -168,7 +184,7 @@ fn ancestors(object: u32) -> Vec { for _ in 0..128 { let mut parent = 0; // SAFETY: current is a live entry, the plane name is a static C string, parent is an out-pointer. - if unsafe { IORegistryEntryGetParentEntry(current, c"IOService".as_ptr(), &mut parent) } + if unsafe { IORegistryEntryGetParentEntry(current, c"IOService".as_ptr(), &raw mut parent) } != 0 { break; @@ -200,7 +216,7 @@ pub fn discover() -> Result, String> { entries.as_mut_ptr(), // At most 65,536 entries of a few KiB, far below i32::MAX; a // larger buffer would be reported as smaller, which is safe. - i32::try_from(std::mem::size_of_val(entries.as_slice())).unwrap_or(i32::MAX), + i32::try_from(size_of_val(entries.as_slice())).unwrap_or(i32::MAX), libc::MNT_NOWAIT, ) }; @@ -243,7 +259,7 @@ pub fn discover() -> Result, String> { let mut iterator = 0; // IOKit consumes the matching dictionary even on failure. // SAFETY: matching is a fresh dictionary that IOKit consumes; iterator is an out-pointer. - if unsafe { IOServiceGetMatchingServices(0, matching, &mut iterator) } != 0 { + if unsafe { IOServiceGetMatchingServices(0, matching, &raw mut iterator) } != 0 { return Err("macOS could not inspect drives. Open a raw disk image instead.".into()); } let iterator = Object(iterator); @@ -306,8 +322,7 @@ pub fn discover() -> Result, String> { .map(|(_, point)| point.clone()); } let url = field(dictionary, "DAVolumePath"); - // SAFETY: url is a non-null CF object borrowed from a live dictionary. - if mount.is_none() && !url.is_null() && unsafe { CFGetTypeID(url) == CFURLGetTypeID() } { + if mount.is_none() && is_type(url, CFURLGetTypeID) { let value = // SAFETY: url was checked to be a CFURL; the copied path is owned by Cf. Cf(unsafe { CFURLCopyFileSystemPath(url.cast(), kCFURLPOSIXPathStyle) }.cast()); @@ -384,7 +399,7 @@ pub fn destination(source: &std::path::Path, folder: &std::path::Path) -> Destin // SAFETY: statfs is plain old data, for which all zero bytes is a valid value. let mut mount: libc::statfs = unsafe { std::mem::zeroed() }; // SAFETY: folder is NUL-terminated and mount is a writable statfs. - if unsafe { libc::statfs(folder.as_ptr(), &mut mount) } != 0 { + if unsafe { libc::statfs(folder.as_ptr(), &raw mut mount) } != 0 { return Destination::Unknown; } // SAFETY: the kernel fills f_mntfromname with a NUL-terminated name. diff --git a/src/drives/monitor.rs b/src/drives/monitor.rs index 94be216..55732a0 100644 --- a/src/drives/monitor.rs +++ b/src/drives/monitor.rs @@ -96,7 +96,7 @@ mod tests { #[test] fn monitor_reports_plug_unplug_and_manual_refresh_without_unchanged_updates() { let state = Arc::new(Mutex::new(Ok(vec![drive("one")]))); - let worker_state = state.clone(); + let worker_state = Arc::clone(&state); let monitor = watch_with(Duration::from_millis(10), move || { worker_state.lock().unwrap().clone() }) @@ -110,12 +110,10 @@ mod tests { .len(), 1 ); - assert!( - monitor - .updates - .recv_timeout(Duration::from_millis(40)) - .is_err() - ); + monitor + .updates + .recv_timeout(Duration::from_millis(40)) + .unwrap_err(); *state.lock().unwrap() = Ok(vec![drive("one"), drive("two")]); assert_eq!( monitor @@ -147,20 +145,16 @@ mod tests { 1 ); *state.lock().unwrap() = Err("temporary discovery error".into()); - assert!( - monitor - .updates - .recv_timeout(Duration::from_secs(1)) - .unwrap() - .is_err() - ); + monitor + .updates + .recv_timeout(Duration::from_secs(1)) + .unwrap() + .unwrap_err(); *state.lock().unwrap() = Ok(vec![drive("two")]); - assert!( - monitor - .updates - .recv_timeout(Duration::from_secs(1)) - .unwrap() - .is_ok() - ); + monitor + .updates + .recv_timeout(Duration::from_secs(1)) + .unwrap() + .unwrap(); } } diff --git a/src/drives/windows.rs b/src/drives/windows.rs index f255a78..a952fe0 100644 --- a/src/drives/windows.rs +++ b/src/drives/windows.rs @@ -12,8 +12,19 @@ use std::{ }; use windows_sys::Win32::{ Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE}, - Storage::FileSystem::*, - System::{IO::DeviceIoControl, Ioctl::*}, + Storage::FileSystem::{ + CreateFileW, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, GetDriveTypeW, + GetLogicalDrives, GetVolumeInformationW, GetVolumeNameForVolumeMountPointW, + GetVolumePathNameW, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, OPEN_EXISTING, QueryDosDeviceW, + }, + System::{ + IO::DeviceIoControl, + Ioctl::{ + DISK_EXTENT, DISK_GEOMETRY, DISK_GEOMETRY_EX, FSCTL_ALLOW_EXTENDED_DASD_IO, + IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IOCTL_STORAGE_QUERY_PROPERTY, + STORAGE_DEVICE_DESCRIPTOR, VOLUME_DISK_EXTENTS, + }, + }, }; fn wide(text: &str) -> Vec { @@ -28,7 +39,7 @@ fn is_volume_device(path: &Path) -> bool { /// Read-only access through the end of a Windows volume. Without extended DASD /// reads, filesystem boundary checks can return EOF before the partition ends, -/// including during SourceReader's bounded read-ahead near the final clusters. +/// including during `SourceReader`'s bounded read-ahead near the final clusters. pub fn open_source(path: &Path) -> std::io::Result { let file = File::open(path)?; if is_volume_device(path) { @@ -44,7 +55,7 @@ pub fn open_source(path: &Path) -> std::io::Result { 0, ptr::null_mut(), 0, - &mut returned, + &raw mut returned, ptr::null_mut(), ) }; @@ -101,7 +112,7 @@ fn query(file: &File, code: u32, input: &[u8]) -> Option> { win32_len(input.len()), output.as_mut_ptr().cast(), win32_len(output.len()), - &mut returned, + &raw mut returned, ptr::null_mut(), ) }; @@ -155,8 +166,9 @@ pub fn discover() -> Result, String> { .collect(); disks.sort_by_key(|(number, _)| *number); let mut rows = Vec::new(); - let mut disk_rows = std::collections::HashMap::new(); - let mut represented_disks = std::collections::HashSet::new(); + // Ordered by disk number, so every pass over it is deterministic. + let mut disk_rows = std::collections::BTreeMap::new(); + let mut represented_disks = HashSet::new(); for (number, name) in disks { let path = format!(r"\\.\{name}"); let Some(file) = open(&path) else { @@ -222,8 +234,8 @@ pub fn discover() -> Result, String> { // All backing disks receive mounted warnings, even when a spanned // volume is deliberately omitted from recovery sources. let count = u32_at(&extents, 0).unwrap_or(0) as usize; - for i in 0..count.min(extents.len() / std::mem::size_of::()) { - let offset = extent_offset + i * std::mem::size_of::(); + for i in 0..count.min(extents.len() / size_of::()) { + let offset = extent_offset + i * size_of::(); if let Some(row) = u32_at(&extents, offset).and_then(|n| disk_rows.get(&n)) { rows[*row].mounted = true; rows[*row].location = "Contains mounted volumes".into(); @@ -257,8 +269,7 @@ pub fn discover() -> Result, String> { let encrypted = ok == 0; let sector_size = u32_at(&extents, extent_offset) .and_then(|number| disk_rows.get(&number)) - .map(|&index| rows[index].sector_size) - .unwrap_or(4096); + .map_or(4096, |&index| rows[index].sector_size); if !encrypted && let Some(number) = u32_at(&extents, extent_offset) { represented_disks.insert(number); } @@ -287,7 +298,7 @@ pub fn discover() -> Result, String> { rows[index].location = "Contains mounted volumes".into(); } } - let hidden: std::collections::HashSet<_> = represented_disks + let hidden: HashSet<_> = represented_disks .iter() .filter_map(|number| disk_rows.get(number).map(|&index| rows[index].path.clone())) .collect(); @@ -300,7 +311,7 @@ fn volume_disks(path: &str) -> Option> { let first = std::mem::offset_of!(VOLUME_DISK_EXTENTS, Extents); let count = u32_at(&extents, 0)? as usize; let disks: HashSet<_> = (0..count) - .filter_map(|i| u32_at(&extents, first + i * std::mem::size_of::())) + .filter_map(|i| u32_at(&extents, first + i * size_of::())) .collect(); (!disks.is_empty()).then_some(disks) } @@ -310,15 +321,19 @@ fn folder_disks(folder: &Path) -> Option> { let name: Vec = folder.as_os_str().encode_wide().chain([0]).collect(); let mut mount = vec![0u16; 32768]; let mut volume = vec![0u16; 64]; - // SAFETY: name is NUL-terminated; output buffers match the given lengths. + // SAFETY: name is NUL-terminated; the mount buffer matches the given length. let ok = unsafe { GetVolumePathNameW(name.as_ptr(), mount.as_mut_ptr(), win32_len(mount.len())) != 0 - && GetVolumeNameForVolumeMountPointW( + } + // SAFETY: mount was NUL-terminated by the call above; the volume buffer + // matches the given length. + && unsafe { + GetVolumeNameForVolumeMountPointW( mount.as_ptr(), volume.as_mut_ptr(), win32_len(volume.len()), ) != 0 - }; + }; if !ok { return None; } @@ -375,13 +390,10 @@ mod tests { #[test] fn disk_image_sources_are_readable_without_device_controls() { - use std::io::Read; let folder = tempfile::tempdir().unwrap(); let path = folder.path().join("source.img"); std::fs::write(&path, b"read-only source").unwrap(); - let mut file = open_source(&path).unwrap(); - let mut content = String::new(); - file.read_to_string(&mut content).unwrap(); + let content = std::io::read_to_string(open_source(&path).unwrap()).unwrap(); assert_eq!(content, "read-only source"); } } diff --git a/src/formats.rs b/src/formats.rs index c1fc6c9..b45f287 100644 --- a/src/formats.rs +++ b/src/formats.rs @@ -1,4 +1,4 @@ -//! Format-specific bounded probes. See docs/FILE_FORMAT_RESEARCH.md for sources +//! Format-specific bounded probes. See `docs/FILE_FORMAT_RESEARCH.md` for sources //! and recovery limits. No recovered program or archive is ever executed. use crate::bytes::to_usize; use crate::{CandidateEnd, Validation, detection::LIMIT}; @@ -99,7 +99,7 @@ pub(crate) fn end(kind: &str, bytes: &[u8], cancel: &AtomicBool) -> Option dex(bytes), "gz" => match Gzip::default().push(bytes, cancel) { CandidateEnd::Complete(n) => Ok(n), - state => Err(state), + state @ (CandidateEnd::More | CandidateEnd::Invalid) => Err(state), }, "xar" | "pkg" => xar::inspect(bytes, cancel).map(|(size, _)| size), // Only the kinds listed above reach this function. @@ -392,7 +392,7 @@ fn deb(b: &[u8], cancel: &AtomicBool) -> Probe { return Err(CandidateEnd::Invalid); } let name = std::str::from_utf8(&b[at..at + 16]) - .map_err(|_| CandidateEnd::Invalid)? + .map_err(CandidateEnd::malformed)? .trim_end() .trim_end_matches('/'); let size = decimal(&b[at + 48..at + 58]).ok_or(CandidateEnd::Invalid)?; @@ -404,14 +404,14 @@ fn deb(b: &[u8], cancel: &AtomicBool) -> Probe { && b[at + 60..stop].starts_with(b"2.") && b[stop - 1] == b'\n' => { - stage = 1 + stage = 1; } 1 if matches!( name, "control.tar" | "control.tar.gz" | "control.tar.xz" | "control.tar.zst" ) && size > 0 => { - stage = 2 + stage = 2; } 2 if matches!( name, @@ -615,18 +615,18 @@ fn rar(b: &[u8], cancel: &AtomicBool) -> Probe { } // Parse within this header only; malformed fields must not consume data. let header = &b[..end]; - let kind = vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; - let flags = vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; + let kind = vint(header, &mut p).map_err(CandidateEnd::malformed)?; + let flags = vint(header, &mut p).map_err(CandidateEnd::malformed)?; if flags & 0x18 != 0 || flags & !0x7f != 0 { return Err(CandidateEnd::Invalid); } let extra = if flags & 1 != 0 { - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)? + vint(header, &mut p).map_err(CandidateEnd::malformed)? } else { 0 }; let data = if flags & 2 != 0 { - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)? + vint(header, &mut p).map_err(CandidateEnd::malformed)? } else { 0 }; @@ -635,16 +635,16 @@ fn rar(b: &[u8], cancel: &AtomicBool) -> Probe { } match kind { 1 if !main && at == 8 => { - let archive_flags = vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; + let archive_flags = vint(header, &mut p).map_err(CandidateEnd::malformed)?; if archive_flags & 1 != 0 { return Err(CandidateEnd::Invalid); } main = true; } 2 | 3 if main => { - let f = vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; + let f = vint(header, &mut p).map_err(CandidateEnd::malformed)?; + vint(header, &mut p).map_err(CandidateEnd::malformed)?; + vint(header, &mut p).map_err(CandidateEnd::malformed)?; if f & 2 != 0 { p += 4; } @@ -654,16 +654,16 @@ fn rar(b: &[u8], cancel: &AtomicBool) -> Probe { if p > header.len() { return Err(CandidateEnd::Invalid); } - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; - vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; - let name = vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)?; + vint(header, &mut p).map_err(CandidateEnd::malformed)?; + vint(header, &mut p).map_err(CandidateEnd::malformed)?; + let name = vint(header, &mut p).map_err(CandidateEnd::malformed)?; if name == 0 || name > end.saturating_sub(p) as u64 { return Err(CandidateEnd::Invalid); } p += to_usize(name); } 5 if main && data == 0 => { - if vint(header, &mut p).map_err(|_| CandidateEnd::Invalid)? != 0 + if vint(header, &mut p).map_err(CandidateEnd::malformed)? != 0 || p + to_usize(extra) != end { return Err(CandidateEnd::Invalid); @@ -781,7 +781,7 @@ fn dex(b: &[u8]) -> Probe { b"035\0" | b"037\0" | b"038\0" | b"039\0" | b"040\0" ) || le32(b, 36) != 112 - || le32(b, 40) != 0x12345678 + || le32(b, 40) != 0x1234_5678 { return Err(CandidateEnd::Invalid); } diff --git a/src/formats/cfb.rs b/src/formats/cfb.rs index 3e6ef83..2f3606f 100644 --- a/src/formats/cfb.rs +++ b/src/formats/cfb.rs @@ -4,10 +4,10 @@ use std::{ collections::HashSet, sync::atomic::{AtomicBool, Ordering}, }; -const FREE: u32 = 0xffffffff; -const END: u32 = 0xfffffffe; -const FAT: u32 = 0xfffffffd; -const DIF: u32 = 0xfffffffc; +const FREE: u32 = 0xffff_ffff; +const END: u32 = 0xffff_fffe; +const FAT: u32 = 0xffff_fffd; +const DIF: u32 = 0xffff_fffc; fn sector(id: u32, size: usize) -> Result { span((u64::from(id) + 1) * size as u64, size as u64).map(|end| end - size) } @@ -146,9 +146,9 @@ pub(super) fn kind(b: &[u8]) -> &'static str { return "ole"; } match le32(guid, 0) { - 0x000c1084 => "msi", - 0x000c1086 => "msp", - 0x000c1082 => "mst", + 0x000c_1084 => "msi", + 0x000c_1086 => "msp", + 0x000c_1082 => "mst", _ => "ole", } } diff --git a/src/formats/gzip.rs b/src/formats/gzip.rs index 43beda2..dd01040 100644 --- a/src/formats/gzip.rs +++ b/src/formats/gzip.rs @@ -78,7 +78,7 @@ impl Gzip { &mut output, flate2::FlushDecompress::None, ) - .map_err(|_| CandidateEnd::Invalid)?; + .map_err(CandidateEnd::malformed)?; // flate2's totals only grow; a decrease would be a decoder bug. let consumed = to_usize(decoder.total_in().saturating_sub(before_in)); let produced = to_usize(decoder.total_out().saturating_sub(before_out)); diff --git a/src/formats/xar.rs b/src/formats/xar.rs index 80f0aaa..dc3ce52 100644 --- a/src/formats/xar.rs +++ b/src/formats/xar.rs @@ -38,7 +38,7 @@ pub(super) fn inspect(b: &[u8], cancel: &AtomicBool) -> Result<(usize, bool), Ca .by_ref() .take(unpacked.saturating_add(1)) .read_to_end(&mut xml) - .map_err(|_| CandidateEnd::Invalid)?; + .map_err(CandidateEnd::malformed)?; if xml.len() as u64 != unpacked || decoder.total_in() != compressed { return Err(CandidateEnd::Invalid); } @@ -53,7 +53,7 @@ pub(super) fn inspect(b: &[u8], cancel: &AtomicBool) -> Result<(usize, bool), Ca if cancel.load(Ordering::Relaxed) { return Err(CandidateEnd::Invalid); } - match reader.read_event().map_err(|_| CandidateEnd::Invalid)? { + match reader.read_event().map_err(CandidateEnd::malformed)? { Event::Start(element) => { if stack.len() >= 64 { return Err(CandidateEnd::Invalid); @@ -126,7 +126,7 @@ pub(super) fn inspect(b: &[u8], cancel: &AtomicBool) -> Result<(usize, bool), Ca need(b, end)?; return Ok((end, package)); } - _ => {} + Event::Empty(_) | Event::Comment(_) | Event::Decl(_) | Event::PI(_) => {} } } Err(CandidateEnd::Invalid) diff --git a/src/i18n.rs b/src/i18n.rs index 81d9635..443a2a6 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -246,14 +246,15 @@ pub fn message(key: &str, values: &[&str]) -> String { for part in parts(&template) { match part { Part::Text(text) => output.push_str(text), - Part::Field(token) => match token.parse::().ok().and_then(|i| values.get(i)) { - Some(value) => output.push_str(&isolate(value)), - None => { + Part::Field(token) => { + if let Some(value) = token.parse::().ok().and_then(|i| values.get(i)) { + output.push_str(&isolate(value)); + } else { output.push('{'); output.push_str(token); output.push('}'); } - }, + } } } output @@ -273,7 +274,9 @@ pub fn is_message(text: &str) -> bool { /// `detail` as the user should see it: unchanged when it is already a catalog /// message, otherwise placed into `summary` (an English key with one `{0}` /// field) so the lead sentence is translated and the technical part is not. -pub fn explain(summary: &str, detail: String) -> String { +/// `{:#}` keeps the whole cause chain of an `anyhow::Error`. +pub fn explain(summary: &str, detail: impl std::fmt::Display) -> String { + let detail = format!("{detail:#}"); if is_message(&detail) { detail } else { @@ -401,11 +404,11 @@ mod tests { "{language:?}" ); for (key, translation) in translations { - assert!(!translation.trim().is_empty()); + assert_ne!(translation.trim(), ""); let mut source = field_names(&parts(key)); let mut target = field_names(&parts(translation)); - source.sort(); - target.sort(); + source.sort_unstable(); + target.sort_unstable(); assert_eq!( source, target, "Placeholder mismatch in {language:?}: {key}" @@ -437,7 +440,7 @@ mod tests { assert!(error.contains(&translate("Invalid source offset", language, 0))); assert!(translate("2 files", language, 0).contains('2')); with_language(language, || { - assert_eq!(is_rtl(), language == Language::Arabic) + assert_eq!(is_rtl(), language == Language::Arabic); }); } } @@ -491,14 +494,14 @@ mod tests { with_language(language, || { // Workers keep catalog keys so switching the UI language also // translates an error that was reported before the switch. - let error = explain("Could not read this volume: {0}", premature_end.into()); + let error = explain("Could not read this volume: {0}", premature_end); assert_eq!(t(&error), catalog(language)[premature_end]); assert_eq!(t(cancelled), catalog(language)[cancelled]); for summary in [ "Could not prepare read-only access to this volume: {0}", "Could not restart as administrator: {0}", ] { - let error = explain(summary, technical.into()); + let error = explain(summary, technical); let translated = t(&error); assert!(translated.contains(technical)); if language != Language::English { diff --git a/src/installer.rs b/src/installer.rs index f313565..d691f86 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -3,24 +3,26 @@ not(test), deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) )] +#[cfg(unix)] +use anyhow::Context; +use anyhow::{anyhow, bail}; /// Hand a verified local package to the operating system without a shell or /// command helper. Installation remains visible and controlled by the user. -pub fn open_installer(path: &std::path::Path) -> Result<(), String> { +pub fn open_installer(path: &std::path::Path) -> anyhow::Result<()> { // ShellExecute expects a shell path, rather than Windows canonicalize's // verbatim \?\ path prefix. Other platforms can resolve symlinks normally. let path = if cfg!(windows) { std::path::absolute(path) } else { path.canonicalize() - } - .map_err(|e| e.to_string())?; + }?; #[cfg(target_os = "linux")] { portal_open(Some(&path), None)?; } #[cfg(windows)] shell_open(path.as_os_str()).map_err(|code| { - format!( + anyhow!( "Could not open installer (Windows error {code}). Open the downloaded file from Explorer." ) })?; @@ -40,9 +42,11 @@ pub fn open_installer(path: &std::path::Path) -> Result<(), String> { ) }; launch(url) - .ok_or_else(|| reclaim::i18n::diagnostic("Could not create installer file URL"))? + .with_context(|| reclaim::i18n::diagnostic("Could not create installer file URL"))? .map_err(|status| { - reclaim::i18n::diagnostic(&format!("Could not open installer: {status}")) + anyhow!(reclaim::i18n::diagnostic(&format!( + "Could not open installer: {status}" + ))) })?; } Ok(()) @@ -80,35 +84,29 @@ fn launch(url: core_foundation_sys::url::CFURLRef) -> Option> { if url.is_null() { return None; } - // SAFETY: `url` is a live, owned CFURL; it is released exactly once here. - let status = unsafe { - let status = LSOpenCFURLRef(url, std::ptr::null_mut()); - CFRelease(url.cast()); - status - }; + // SAFETY: `url` is a live, owned CFURL; a null out-pointer is allowed. + let status = unsafe { LSOpenCFURLRef(url, std::ptr::null_mut()) }; + // SAFETY: `url` is owned here and released exactly once, after its last use. + unsafe { CFRelease(url.cast()) }; Some(if status == 0 { Ok(()) } else { Err(status) }) } #[cfg(target_os = "linux")] -fn portal_open(path: Option<&std::path::Path>, uri: Option<&str>) -> Result<(), String> { +fn portal_open(path: Option<&std::path::Path>, uri: Option<&str>) -> anyhow::Result<()> { use std::{collections::HashMap, os::fd::AsFd}; - let file = path - .map(std::fs::File::open) - .transpose() - .map_err(|e| e.to_string())?; - let connection = zbus::blocking::Connection::session().map_err(|e| e.to_string())?; + let file = path.map(std::fs::File::open).transpose()?; + let connection = zbus::blocking::Connection::session()?; let portal = zbus::blocking::Proxy::new( &connection, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.OpenURI", - ) - .map_err(|e| e.to_string())?; + )?; // Subscribe before requesting the launch, and keep the connection alive // until the portal responds (disconnecting early can cancel its dialog). let sender = connection .unique_name() - .ok_or_else(|| reclaim::i18n::diagnostic("Desktop session has no connection name"))? + .with_context(|| reclaim::i18n::diagnostic("Desktop session has no connection name"))? .as_str() .trim_start_matches(':') .replace('.', "_"); @@ -116,8 +114,7 @@ fn portal_open(path: Option<&std::path::Path>, uri: Option<&str>) -> Result<(), "reclaim_{}_{}", std::process::id(), std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|e| e.to_string())? + .duration_since(std::time::UNIX_EPOCH)? .as_nanos() ); let request_path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}"); @@ -126,11 +123,8 @@ fn portal_open(path: Option<&std::path::Path>, uri: Option<&str>) -> Result<(), "org.freedesktop.portal.Desktop", request_path.as_str(), "org.freedesktop.portal.Request", - ) - .map_err(|e| e.to_string())?; - let mut responses = request - .receive_signal("Response") - .map_err(|e| e.to_string())?; + )?; + let mut responses = request.receive_signal("Response")?; let mut options = HashMap::<&str, zbus::zvariant::Value<'_>>::new(); options.insert("handle_token", zbus::zvariant::Value::from(token.as_str())); let handle: zbus::zvariant::OwnedObjectPath = (if let Some(file) = &file { @@ -142,35 +136,39 @@ fn portal_open(path: Option<&std::path::Path>, uri: Option<&str>) -> Result<(), portal.call("OpenURI", &("", uri.unwrap_or_default(), options)) }) .map_err(|e| { - format!( + anyhow!( "Could not open link or file: {e}. Try opening it from your browser or file manager." ) })?; if handle.as_str() != request_path { - return Err("The desktop returned an unexpected open request. Try opening the link or file manually.".into()); + bail!( + "The desktop returned an unexpected open request. Try opening the link or file manually." + ); } - let response = responses.next().ok_or_else(|| { + let response = responses.next().with_context(|| { reclaim::i18n::diagnostic("The desktop link or file request ended without a response") })?; let (status, _): (u32, HashMap) = - response.body().deserialize().map_err(|e| e.to_string())?; + response.body().deserialize()?; if status != 0 { - return Err("The desktop did not open the link or file. Try opening it manually.".into()); + bail!("The desktop did not open the link or file. Try opening it manually."); } Ok(()) } /// Open an HTTPS link using the desktop's native URL handler, without helpers. -pub fn open_url(url: &str) -> Result<(), String> { +pub fn open_url(url: &str) -> anyhow::Result<()> { if !url.starts_with("https://") || url.contains(['\0', '\r', '\n']) { - return Err(reclaim::i18n::diagnostic("Only HTTPS links can be opened.")); + bail!(reclaim::i18n::diagnostic("Only HTTPS links can be opened.")); } #[cfg(target_os = "linux")] portal_open(None, Some(url))?; #[cfg(windows)] shell_open(std::ffi::OsStr::new(url)).map_err(|code| { - reclaim::i18n::diagnostic(&format!("Could not open browser (Windows error {code}).")) + anyhow!(reclaim::i18n::diagnostic(&format!( + "Could not open browser (Windows error {code})." + ))) })?; #[cfg(target_os = "macos")] { @@ -185,13 +183,15 @@ pub fn open_url(url: &str) -> Result<(), String> { ) }; launch(native_url) - .ok_or_else(|| reclaim::i18n::diagnostic("Could not create browser URL."))? + .with_context(|| reclaim::i18n::diagnostic("Could not create browser URL."))? .map_err(|status| { - reclaim::i18n::diagnostic(&format!("Could not open browser: {status}")) + anyhow!(reclaim::i18n::diagnostic(&format!( + "Could not open browser: {status}" + ))) })?; } #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))] - return Err(reclaim::i18n::diagnostic( + bail!(reclaim::i18n::diagnostic( "Opening browser links is unavailable on this platform.", )); Ok(()) diff --git a/src/lib.rs b/src/lib.rs index 3477862..232e6ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,7 +123,7 @@ fn portable_name(name: &str) -> String { } }) .collect(); - name = name.trim_end_matches([' ', '.']).to_owned(); + name.truncate(name.trim_end_matches([' ', '.']).len()); let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || (stem.len() == 4 @@ -153,6 +153,7 @@ fn portable_name(name: &str) -> String { name } +#[derive(Debug)] pub enum Event { /// Absolute source byte range that could not be read (offset, length). Unreadable { @@ -705,6 +706,19 @@ fn candidate_kind(fmt: &Format, bytes: &[u8]) -> &'static str { // Only classify packages from a complete, single-disk classic ZIP directory. // Names appearing in compressed payloads must not change the recovered extension. fn zip_kind(bytes: &[u8]) -> &'static str { + const PACKAGE_NAMES: &[&[u8]] = &[ + b"[Content_Types].xml", + b"word/document.xml", + b"word/vbaProject.bin", + b"xl/workbook.xml", + b"xl/vbaProject.bin", + b"ppt/presentation.xml", + b"ppt/vbaProject.bin", + b"META-INF/container.xml", + b"AndroidManifest.xml", + b"classes.dex", + b"META-INF/MANIFEST.MF", + ]; // The classic EOCD is 22 bytes plus at most a u16-sized comment. let search_start = bytes.len().saturating_sub(22 + u16::MAX as usize); let Some((relative, _)) = bytes[search_start..] @@ -720,19 +734,6 @@ fn zip_kind(bytes: &[u8]) -> &'static str { let u32_at = |p| bytes::u32_le(bytes, p) as usize; let count = u16_at(eocd + 10); let mut cursor = u32_at(eocd + 16); - const PACKAGE_NAMES: &[&[u8]] = &[ - b"[Content_Types].xml", - b"word/document.xml", - b"word/vbaProject.bin", - b"xl/workbook.xml", - b"xl/vbaProject.bin", - b"ppt/presentation.xml", - b"ppt/vbaProject.bin", - b"META-INF/container.xml", - b"AndroidManifest.xml", - b"classes.dex", - b"META-INF/MANIFEST.MF", - ]; let mut names = [false; PACKAGE_NAMES.len()]; let mut mime = None; for _ in 0..count { @@ -810,7 +811,7 @@ fn read_chunk(input: &mut impl Read, bytes: &mut [u8], cancel: &AtomicBool) -> i return Ok(0); } match input.read(bytes) { - Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} result => return result, } } @@ -1068,6 +1069,15 @@ pub struct FoundReader<'a, R> { used: u64, remaining: u64, } +impl std::fmt::Debug for FoundReader<'_, R> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FoundReader") + .field("extents", &self.extents.len()) + .field("current", &self.current) + .field("remaining", &self.remaining) + .finish_non_exhaustive() + } +} impl<'a, R: Read + Seek> FoundReader<'a, R> { pub fn new(input: &'a mut R, found: &'a Found) -> io::Result { let extents = match &found.extents { @@ -1150,8 +1160,7 @@ pub fn recover_unique( .to_string_lossy(); let extension = path .extension() - .map(|ext| format!(".{}", ext.to_string_lossy())) - .unwrap_or_default(); + .map_or_default(|ext| format!(".{}", ext.to_string_lossy())); for attempt in 0..10_000 { let name = if attempt == 0 { name.clone() @@ -1161,7 +1170,7 @@ pub fn recover_unique( let destination = directory.join(name); match recover_reader(input, &destination, found) { Ok(()) => return Ok(destination), - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} Err(e) => return Err(e), } } @@ -1180,7 +1189,7 @@ pub fn recover_reader( if (found.size == 0 && found.resident_data.is_none()) || (found.size > LIMIT as u64 && found.extents.is_none() - && !(found.kind == "zip" && found.size <= u32::MAX as u64 + 65557)) + && !(found.kind == "zip" && found.size <= u64::from(u32::MAX) + 65557)) || found .resident_data .as_ref() @@ -1381,7 +1390,7 @@ mod tests { let mut results = vec![]; scan(&source, &AtomicBool::new(false), |e| { if let Event::Found(f) = e { - results.push(f) + results.push(f); } }) .unwrap(); @@ -1398,15 +1407,11 @@ mod tests { let mut bytes = pdf.to_vec(); bytes.extend_from_slice(&[0; 64]); let mut results = vec![]; - scan_reader( - &mut std::io::Cursor::new(&bytes), - &AtomicBool::new(false), - |e| { - if let Event::Found(f) = e { - results.push(f) - } - }, - ) + scan_reader(&mut io::Cursor::new(&bytes), &AtomicBool::new(false), |e| { + if let Event::Found(f) = e { + results.push(f); + } + }) .unwrap(); assert_eq!(results.len(), 1); let found = &results[0]; @@ -1455,7 +1460,7 @@ mod tests { let mut count = 0; scan(&p, &AtomicBool::new(cancelled), |e| { if matches!(e, Event::Found(_)) { - count += 1 + count += 1; } }) .unwrap(); diff --git a/src/main.rs b/src/main.rs index 87535f7..52aaf4f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,13 @@ mod updates; clippy::todo, clippy::let_underscore_must_use, clippy::unwrap_in_result, + trivial_casts, + trivial_numeric_casts, + let_underscore_drop, + missing_debug_implementations, + clippy::let_underscore_untyped, + clippy::clone_on_ref_ptr, + clippy::same_name_method, reason = "code generated by slint-build" )] mod ui { @@ -217,18 +224,19 @@ impl Reclaim { let windows_drive = cfg!(windows) && drive.is_some(); #[cfg(windows)] let windows_drive = windows_drive && !native_process::is_administrator(); - let source_size = drive - .map(|d| d.size) - .unwrap_or_else(|| path.metadata().map(|m| m.len()).unwrap_or(0)); + let source_size = drive.map_or_else(|| path.metadata().map_or(0, |m| m.len()), |d| d.size); self.source_size = (source_size > 0).then_some(source_size); self.source_handle = None; - self.source_alignment = drive.map(|d| d.sector_size).unwrap_or_else(|| { - if cfg!(target_os = "windows") && path.to_string_lossy().starts_with(r"\\.\") { - 4096 - } else { - 1 - } - }); + self.source_alignment = drive.map_or_else( + || { + if cfg!(target_os = "windows") && path.to_string_lossy().starts_with(r"\\.\") { + 4096 + } else { + 1 + } + }, + |d| d.sector_size, + ); let alignment = self.source_alignment; let source_size = self.source_size; self.scanned_source = Some(path.clone()); @@ -236,7 +244,7 @@ impl Reclaim { self.status = "Opening source… If Linux asks, authorize read-only access to the drive.".into(); self.cancel = Arc::new(AtomicBool::new(false)); - let cancel = self.cancel.clone(); + let cancel = Arc::clone(&self.cancel); let (tx, rx) = mpsc::sync_channel(256); self.receiver = Some(rx); std::thread::spawn(move || { @@ -258,8 +266,16 @@ impl Reclaim { } let mut input = reclaim::SourceReader::new(handle.try_clone()?, alignment, source_size)?; - tx.send(Message::Opened(handle)) - .map_err(|_| std::io::Error::other("Window closed"))?; + // The user sees this message translated; the send error holds + // only the unsent handle. + #[expect( + clippy::map_err_ignore, + reason = "a catalog message replaces the detail" + )] + let sent = tx + .send(Message::Opened(handle)) + .map_err(|_| std::io::Error::other("Window closed")); + sent?; let size = source_size.ok_or_else(|| { std::io::Error::other( "The volume size is unknown; unused-space scanning cannot start.", @@ -349,7 +365,7 @@ impl Reclaim { self.shown.last = self.results.last().map(identity); match model { // Diff in place so the list keeps its scroll position and focus. - Some(_) if rebuild => replace_model(files.clone(), added, |m| ui.set_files(m)), + Some(_) if rebuild => replace_model(&files, added, |m| ui.set_files(m)), Some(model) => model.extend(added), None => ui.set_files(Rc::new(VecModel::from(added)).into()), } @@ -399,7 +415,9 @@ impl Reclaim { }; match drives::destination(source, &directory) { drives::Destination::Separate => self.export(directory), - destination => self.destination_review = Some((directory, destination)), + destination @ (drives::Destination::SameDrive | drives::Destination::Unknown) => { + self.destination_review = Some((directory, destination)); + } } } /// Saves to a folder whose drive could not be determined, after the user @@ -445,7 +463,7 @@ impl Reclaim { self.recovery_status = "Recovering selected files…".into(); self.exporting = true; self.export_cancel = Arc::new(AtomicBool::new(false)); - let cancel = self.export_cancel.clone(); + let cancel = Arc::clone(&self.export_cancel); let alignment = self.source_alignment; let source_size = self.source_size; std::thread::spawn(move || { @@ -459,7 +477,7 @@ impl Reclaim { // temporary file is discarded, never published. let mut input = StoppableReader { inner: input, - stop: cancel.clone(), + stop: Arc::clone(&cancel), }; let mut count = 0usize; let stopped = |count: usize| { @@ -526,7 +544,7 @@ impl Reclaim { if self .drive_monitor .as_ref() - .is_some_and(|monitor| monitor.request_refresh()) + .is_some_and(drives::DriveMonitor::request_refresh) { return; } @@ -558,7 +576,7 @@ impl Reclaim { if let Some(result) = self .drive_monitor .as_mut() - .and_then(|monitor| monitor.take_update()) + .and_then(drives::DriveMonitor::take_update) { changed = true; self.apply_drive_update(result); @@ -636,8 +654,7 @@ impl Reclaim { let since = self .scan_activity .filter(|(at, previous, _, _)| *at == offset && *previous == kind) - .map(|(_, _, _, since)| since) - .unwrap_or(now); + .map_or(now, |(_, _, _, since)| since); self.scan_activity = Some((offset, kind, bytes, since)); self.last_scan_update = Some(now); if !self.unused_scan { @@ -669,10 +686,8 @@ impl Reclaim { ) } Err(e) => { - self.scan_error = Some(i18n::explain( - "Could not read this volume: {0}", - e.clone(), - )); + self.scan_error = + Some(i18n::explain("Could not read this volume: {0}", e)); "Scan failed. See the message above.".into() } }; @@ -706,7 +721,12 @@ fn format_bytes(n: u64) -> String { ("KiB", 1 << 10), ] { if n >= divisor { - return format!("{:.1} {unit}", n as f64 / divisor as f64); + #[expect( + clippy::cast_precision_loss, + reason = "a display value with one decimal; lost low bits cannot show" + )] + let value = n as f64 / divisor as f64; + return format!("{value:.1} {unit}"); } } format!("{n} B") @@ -758,8 +778,10 @@ impl Reclaim { ui.set_source( self.source .as_ref() - .map(|p| i18n::isolate(&p.display().to_string())) - .unwrap_or_else(|| i18n::t("No source selected")) + .map_or_else( + || i18n::t("No source selected"), + |p| i18n::isolate(&p.display().to_string()), + ) .into(), ); ui.set_busy(self.busy); @@ -774,8 +796,7 @@ impl Reclaim { ui.set_destination_same_drive(matches!(review, Some((_, drives::Destination::SameDrive)))); ui.set_destination_path( review - .map(|(folder, _)| i18n::isolate(&folder.display().to_string())) - .unwrap_or_default() + .map_or_default(|(folder, _)| i18n::isolate(&folder.display().to_string())) .into(), ); ui.set_all_selected(visible > 0 && selected == visible); @@ -794,12 +815,12 @@ impl Reclaim { self.scan_error .as_ref() .or(self.drives_error.as_ref()) - .map(|error| i18n::t(error)) - .unwrap_or_default() + .map_or_default(|error| i18n::t(error)) .into(), ); #[expect( clippy::cast_possible_truncation, + clippy::cast_precision_loss, reason = "a ratio clamped to 0..=1 fits f32; only precision is reduced" )] ui.set_progress(if self.total > 0 { @@ -854,10 +875,10 @@ impl Reclaim { detail: format!( "{} · {}{}", i18n::t(&d.kind), - d.location - .strip_prefix("Mounted at ") - .map(|path| i18n::message("Mounted at {0}", &[path])) - .unwrap_or_else(|| i18n::t(&d.location)), + d.location.strip_prefix("Mounted at ").map_or_else( + || i18n::t(&d.location), + |path| i18n::message("Mounted at {0}", &[path]) + ), if d.encrypted { format!(" · {}", i18n::t("Locked")) } else { @@ -874,7 +895,7 @@ impl Reclaim { available: d.scannable(), }) .collect(); - replace_model(ui.get_drives(), drives, |m| ui.set_drives(m)); + replace_model(&ui.get_drives(), drives, |m| ui.set_drives(m)); ui.set_phone_connected(self.drives.iter().any(|d| d.phone)); } } @@ -890,7 +911,7 @@ fn file_item(f: &Found, index: usize) -> FileItem { } /// Clear the preview and invalidate any preview still loading on a worker. fn reset_preview(ui: &AppWindow) { - ui.set_preview(Default::default()); + ui.set_preview(slint::Image::default()); ui.set_preview_error_raw("".into()); ui.set_preview_error("".into()); ui.set_preview_token(ui.get_preview_token().wrapping_add(1)); @@ -927,7 +948,7 @@ fn drive_icon(drive: &drives::Drive) -> DriveIcon { } } fn replace_model( - current: ModelRc, + current: &ModelRc, rows: Vec, set: impl FnOnce(ModelRc), ) { @@ -1059,14 +1080,14 @@ fn run() -> Result<(), slint::PlatformError> { let url = about_link_url(link); std::thread::spawn(move || { if let Err(e) = installer::open_url(url) { - diagnostics::write(&e); + diagnostics::write(&format!("{e:#}")); } }); }); let state = Rc::new(RefCell::new(Reclaim::default())); #[cfg(windows)] { - let state = state.clone(); + let state = Rc::clone(&state); let weak = ui.as_weak(); ui.on_restart_as_administrator(move || { if state.borrow().working() || !state.borrow().needs_administrator { @@ -1188,7 +1209,7 @@ fn run() -> Result<(), slint::PlatformError> { } }); { - let state = state.clone(); + let state = Rc::clone(&state); let weak = ui.as_weak(); ui.on_inspect(move |i| { // A negative index from the UI means "nothing"; ignore it. @@ -1213,7 +1234,7 @@ fn run() -> Result<(), slint::PlatformError> { let weak = ui.as_weak(); let token = ui.get_preview_token(); std::thread::spawn(move || { - let result = preview::load(&f, handle, alignment); + let result = preview::load(&f, handle, alignment).map_err(|e| format!("{e:#}")); // Fails only when the event loop has already quit. weak.upgrade_in_event_loop(move |ui| { if ui.get_preview_token() != token { @@ -1239,16 +1260,16 @@ fn run() -> Result<(), slint::PlatformError> { } let updates = Rc::new(RefCell::new(updates::Updates::new())); { - let updates = updates.clone(); + let updates = Rc::clone(&updates); ui.on_check_update(move || updates.borrow_mut().check()); } { - let updates = updates.clone(); + let updates = Rc::clone(&updates); ui.on_dismiss_update(move || updates.borrow_mut().dismiss()); } { - let updates = updates.clone(); - let state = state.clone(); + let updates = Rc::clone(&updates); + let state = Rc::clone(&state); let weak = ui.as_weak(); ui.on_apply_update(move || { if !state.borrow().working() { @@ -1263,7 +1284,7 @@ fn run() -> Result<(), slint::PlatformError> { } let timer = slint::Timer::default(); { - let state = state.clone(); + let state = Rc::clone(&state); let weak = ui.as_weak(); let last_language = std::cell::Cell::new(i18n::preference()); let started = std::time::Instant::now(); @@ -1291,7 +1312,7 @@ fn run() -> Result<(), slint::PlatformError> { ui.set_update_status(i18n::t(&updates.status).into()); if last_notes != updates.notes { replace_model( - ui.get_update_notes(), + &ui.get_update_notes(), updates .notes .iter() @@ -1355,7 +1376,10 @@ fn main() { i18n::init(); #[cfg(target_os = "linux")] if let Err(error) = native_bus_addresses() { - diagnostics::report(&i18n::t("A native desktop session is required"), &error); + diagnostics::report( + &i18n::t("A native desktop session is required"), + &format!("{error:#}"), + ); std::process::exit(1); } update_runtime::cleanup_staged_updates(); @@ -1380,46 +1404,51 @@ impl Drop for Reclaim { // our clients or desktop dependencies. A session socket is required so the // native dialog library cannot fall back to autolaunching a bus helper. #[cfg(target_os = "linux")] -fn native_bus_addresses() -> Result<(), String> { - let session = std::env::var("DBUS_SESSION_BUS_ADDRESS").map_err(|_| { - reclaim::i18n::diagnostic( - "A native desktop D-Bus session is required; helper autolaunch is disabled.", - ) - })?; +fn native_bus_addresses() -> anyhow::Result<()> { + use anyhow::Context; + let session = std::env::var("DBUS_SESSION_BUS_ADDRESS") + .ok() + .with_context(|| { + i18n::diagnostic( + "A native desktop D-Bus session is required; helper autolaunch is disabled.", + ) + })?; native_bus_address(&session)?; for name in ["DBUS_SYSTEM_BUS_ADDRESS", "AT_SPI_BUS_ADDRESS"] { if let Some(address) = std::env::var_os(name) { native_bus_address( address .to_str() - .ok_or_else(|| reclaim::i18n::diagnostic("Invalid native bus address"))?, + .with_context(|| i18n::diagnostic("Invalid native bus address"))?, )?; } } Ok(()) } #[cfg(target_os = "linux")] -fn native_bus_address(value: &str) -> Result<(), String> { - if value.contains(';') { - return Err(reclaim::i18n::diagnostic( - "D-Bus address fallback lists are disabled.", - )); - } +fn native_bus_address(value: &str) -> anyhow::Result<()> { + use anyhow::Context; + anyhow::ensure!( + !value.contains(';'), + i18n::diagnostic("D-Bus address fallback lists are disabled.") + ); let address: zbus::Address = value .parse() - .map_err(|_| reclaim::i18n::diagnostic("Invalid native D-Bus address"))?; - if !matches!(address.transport(), zbus::address::Transport::Unix(_)) { - return Err(reclaim::i18n::diagnostic( + .ok() + .with_context(|| i18n::diagnostic("Invalid native D-Bus address"))?; + anyhow::ensure!( + matches!(address.transport(), zbus::address::Transport::Unix(_)), + i18n::diagnostic( "Only native Unix-socket D-Bus addresses are allowed; process-backed transports are disabled.", - )); - } + ) + ); Ok(()) } #[cfg(all(test, target_os = "linux"))] #[test] fn native_bus_transport_rejects_external_programs() { - assert!(native_bus_address("unix:path=/run/user/1000/bus").is_ok()); - assert!(native_bus_address("unix:abstract=desktop-bus").is_ok()); + native_bus_address("unix:path=/run/user/1000/bus").unwrap(); + native_bus_address("unix:abstract=desktop-bus").unwrap(); for address in [ "unixexec:path=/bin/sh,argv1=-c,argv2=echo", "autolaunch:", diff --git a/src/native_process.rs b/src/native_process.rs index 265f064..3862fac 100644 --- a/src/native_process.rs +++ b/src/native_process.rs @@ -4,6 +4,7 @@ not(test), deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) )] +use anyhow::bail; use std::path::Path; #[cfg(windows)] @@ -16,7 +17,7 @@ pub fn is_administrator() -> bool { /// Relaunch only this executable via Windows UAC, without forwarding arguments /// or starting a scan. Cancellation leaves the current window running. #[cfg(windows)] -pub fn restart_elevated() -> Result { +pub fn restart_elevated() -> anyhow::Result { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::{ Foundation::ERROR_CANCELLED, @@ -24,7 +25,7 @@ pub fn restart_elevated() -> Result { SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, ShellExecuteExW, }, }; - let executable = std::env::current_exe().map_err(|e| e.to_string())?; + let executable = std::env::current_exe()?; let file: Vec = executable .as_os_str() .encode_wide() @@ -34,20 +35,19 @@ pub fn restart_elevated() -> Result { // audit-allow(SEC-UNINIT): Windows documents zero initialization of unused fields. // SAFETY: SHELLEXECUTEINFOW is plain data; unused pointers/handles may be null. let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() }; - info.cbSize = - u32::try_from(std::mem::size_of::()).map_err(|e| e.to_string())?; + info.cbSize = u32::try_from(size_of::())?; info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC; info.lpVerb = verb.as_ptr(); info.lpFile = file.as_ptr(); info.nShow = 1; // SAFETY: both UTF-16 strings are terminated and live through this synchronous // call. The target is our own executable; no shell commands or arguments. - if unsafe { ShellExecuteExW(&mut info) } == 0 { + if unsafe { ShellExecuteExW(&raw mut info) } == 0 { let error = std::io::Error::last_os_error(); if error.raw_os_error() == i32::try_from(ERROR_CANCELLED).ok() { return Ok(false); } - return Err(error.to_string()); + return Err(error.into()); } if info.hProcess.is_null() { return Ok(false); @@ -65,7 +65,7 @@ pub struct Child(windows_sys::Win32::Foundation::HANDLE); pub struct Child; #[cfg(target_os = "linux")] -pub fn spawn(program: &Path, arguments: &[String]) -> Result { +pub fn spawn(program: &Path, arguments: &[String]) -> anyhow::Result { let environment = std::env::vars_os() .map(|(key, value)| { let mut item = key; @@ -84,12 +84,12 @@ pub fn spawn_with_environment( program: &Path, arguments: &[String], environment: Vec, -) -> Result { +) -> anyhow::Result { use std::{ffi::CString, os::unix::ffi::OsStrExt}; - let program = CString::new(program.as_os_str().as_bytes()).map_err(|e| e.to_string())?; + let program = CString::new(program.as_os_str().as_bytes())?; let mut args = vec![program.clone()]; for arg in arguments { - args.push(CString::new(arg.as_bytes()).map_err(|e| e.to_string())?); + args.push(CString::new(arg.as_bytes())?); } let argv: Vec<_> = args .iter() @@ -98,7 +98,7 @@ pub fn spawn_with_environment( .collect(); let environment: Vec<_> = environment .into_iter() - .map(|item| CString::new(item.as_bytes()).map_err(|e| e.to_string())) + .map(|item| CString::new(item.as_bytes())) .collect::>()?; let envp: Vec<_> = environment .iter() @@ -110,7 +110,7 @@ pub fn spawn_with_environment( // remain live through posix_spawn. No inherited custom file actions. let result = unsafe { libc::posix_spawn( - &mut pid, + &raw mut pid, program.as_ptr(), std::ptr::null(), std::ptr::null(), @@ -119,23 +119,26 @@ pub fn spawn_with_environment( ) }; if result != 0 { - return Err(std::io::Error::from_raw_os_error(result).to_string()); + return Err(std::io::Error::from_raw_os_error(result).into()); } Ok(Child(pid)) } #[cfg(windows)] -pub fn spawn(program: &Path, arguments: &[String]) -> Result { +pub fn spawn(program: &Path, arguments: &[String]) -> anyhow::Result { + use anyhow::Context; use std::os::windows::ffi::OsStrExt; - use windows_sys::Win32::System::Threading::*; + use windows_sys::Win32::System::Threading::{ + CREATE_NO_WINDOW, CreateProcessW, PROCESS_INFORMATION, STARTUPINFOW, + }; let application: Vec<_> = program.as_os_str().encode_wide().chain(Some(0)).collect(); let program_text = program .to_str() - .ok_or_else(|| reclaim::i18n::diagnostic("Update path is not valid Unicode"))?; + .with_context(|| reclaim::i18n::diagnostic("Update path is not valid Unicode"))?; let mut parts = vec![quote_argument(program_text)]; for arg in arguments { if arg.contains('\0') { - return Err(reclaim::i18n::diagnostic("Invalid update argument")); + bail!(reclaim::i18n::diagnostic("Invalid update argument")); } parts.push(quote_argument(arg)); } @@ -147,7 +150,7 @@ pub fn spawn(program: &Path, arguments: &[String]) -> Result { clippy::cast_possible_truncation, reason = "STARTUPINFOW is about 100 bytes; Win32 requires its exact size in cb" )] - let size = std::mem::size_of::() as u32; + let size = size_of::() as u32; startup.cb = size; // audit-allow(SEC-UNINIT): an output structure that CreateProcessW fills in. // SAFETY: PROCESS_INFORMATION is plain old data; CreateProcessW overwrites it. @@ -164,12 +167,12 @@ pub fn spawn(program: &Path, arguments: &[String]) -> Result { CREATE_NO_WINDOW, std::ptr::null(), std::ptr::null(), - &startup, - &mut process, + &raw const startup, + &raw mut process, ) }; if ok == 0 { - return Err(std::io::Error::last_os_error().to_string()); + return Err(std::io::Error::last_os_error().into()); } // SAFETY: CreateProcessW returned this thread handle and nothing else owns it. unsafe { @@ -179,8 +182,8 @@ pub fn spawn(program: &Path, arguments: &[String]) -> Result { } #[cfg(not(any(target_os = "linux", windows)))] -pub fn spawn(_program: &Path, _arguments: &[String]) -> Result { - Err("Automatic restart is unavailable on this platform".into()) +pub fn spawn(_program: &Path, _arguments: &[String]) -> anyhow::Result { + bail!("Automatic restart is unavailable on this platform") } #[cfg(target_os = "linux")] @@ -197,26 +200,26 @@ impl Drop for Child { impl Child { /// Waits for the child to exit and returns its exit code. #[cfg(any(test, target_os = "linux"))] - pub fn wait(self) -> Result { + pub fn wait(self) -> anyhow::Result { #[cfg(target_os = "linux")] { let mut status = 0; loop { // SAFETY: self owns a child PID returned by posix_spawn. - if unsafe { libc::waitpid(self.0, &mut status, 0) } >= 0 { + if unsafe { libc::waitpid(self.0, &raw mut status, 0) } >= 0 { break; } let error = std::io::Error::last_os_error(); if error.kind() != std::io::ErrorKind::Interrupted { - return Err(error.to_string()); + return Err(error.into()); } } if libc::WIFEXITED(status) { // WEXITSTATUS is the low 8 bits of the status, so it is never negative. return Ok(libc::WEXITSTATUS(status).cast_unsigned()); } - Err(reclaim::i18n::diagnostic( - "Update process terminated unexpectedly", + bail!(reclaim::i18n::diagnostic( + "Update process terminated unexpectedly" )) } #[cfg(windows)] @@ -224,18 +227,18 @@ impl Child { use windows_sys::Win32::System::Threading::*; // SAFETY: self.0 is the live process handle this Child owns. if unsafe { WaitForSingleObject(self.0, INFINITE) } != 0 { - return Err(std::io::Error::last_os_error().to_string()); + return Err(std::io::Error::last_os_error().into()); } let mut code = 0; // SAFETY: self.0 is the live process handle and code a valid out-pointer. - if unsafe { GetExitCodeProcess(self.0, &mut code) } == 0 { - return Err(std::io::Error::last_os_error().to_string()); + if unsafe { GetExitCodeProcess(self.0, &raw mut code) } == 0 { + return Err(std::io::Error::last_os_error().into()); } Ok(code) } #[cfg(not(any(target_os = "linux", windows)))] - Err(reclaim::i18n::diagnostic( - "Native process waiting is unavailable", + bail!(reclaim::i18n::diagnostic( + "Native process waiting is unavailable" )) } } diff --git a/src/ntfs.rs b/src/ntfs.rs index 51a1ad2..4b76d41 100644 --- a/src/ntfs.rs +++ b/src/ntfs.rs @@ -34,7 +34,7 @@ fn filetime(bytes: &[u8], at: usize) -> Option { (seconds <= 253_402_300_799).then_some(seconds) } -pub fn read_record( +pub(crate) fn read_record( input: &mut impl Read, offset: u64, cancel: &AtomicBool, @@ -358,7 +358,7 @@ fn parse_record( let validation = match crate::validation::validate(kind, &data, cancel)? { Validation::ImageDecoded => Validation::ImageDecoded, Validation::StructureChecked => Validation::StructureChecked, - _ => Validation::MetadataChecked, + Validation::MetadataChecked | Validation::Unverified => Validation::MetadataChecked, }; Some(Found { offset, diff --git a/src/preview.rs b/src/preview.rs index 724e018..af10036 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -3,6 +3,7 @@ not(test), deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) )] +use anyhow::{Context, bail}; use reclaim::Found; use std::io::{Read, Seek, SeekFrom}; use std::sync::Arc; @@ -24,6 +25,17 @@ pub(crate) struct Input { position: u64, } impl Input { + #[cfg_attr( + not(windows), + expect(clippy::unnecessary_wraps, reason = "only the Windows reopen can fail") + )] + #[cfg_attr( + windows, + expect( + clippy::needless_pass_by_value, + reason = "kept elsewhere; on Windows it is reopened with its own cursor" + ) + )] pub(crate) fn new(file: Arc) -> std::io::Result { #[cfg(windows)] let file = { @@ -68,7 +80,7 @@ impl Input { 0, std::ptr::null_mut(), 0, - &mut returned, + &raw mut returned, std::ptr::null_mut(), ); } @@ -105,8 +117,14 @@ impl Seek for Input { i128::from(self.file.metadata()?.len()).saturating_add(i128::from(value)) } }; - self.position = u64::try_from(position) - .map_err(|_| std::io::Error::other("Invalid preview position"))?; + // The user sees this message translated; the conversion error adds nothing. + #[expect( + clippy::map_err_ignore, + reason = "a catalog message replaces the detail" + )] + let position = + u64::try_from(position).map_err(|_| std::io::Error::other("Invalid preview position")); + self.position = position?; Ok(self.position) } } @@ -115,40 +133,31 @@ pub fn load( found: &Found, handle: Option>, alignment: usize, -) -> Result { +) -> anyhow::Result { if found.size > 32 * 1024 * 1024 { - return Err( - "This image is too large to preview. Recover it to view the full image.".into(), - ); + bail!("This image is too large to preview. Recover it to view the full image."); } let bytes = if let Some(bytes) = &found.resident_data { std::borrow::Cow::Borrowed(bytes.as_ref()) } else { - let file = handle.ok_or("The source is no longer available.")?; - let mut input = reclaim::SourceReader::new( - Input::new(file).map_err(|e| e.to_string())?, - alignment, - None, - ) - .map_err(|e| e.to_string())?; + let file = handle.context("The source is no longer available.")?; + let mut input = reclaim::SourceReader::new(Input::new(file)?, alignment, None)?; // audit-allow(DOS-ALLOC): previews are refused above 32 MiB at the top of this function. - let mut bytes = vec![0; usize::try_from(found.size).map_err(|e| e.to_string())?]; + let mut bytes = vec![0; usize::try_from(found.size)?]; reclaim::FoundReader::new(&mut input, found) - .and_then(|mut reader| reader.read_exact(&mut bytes)) - .map_err(|e| e.to_string())?; + .and_then(|mut reader| reader.read_exact(&mut bytes))?; std::borrow::Cow::Owned(bytes) }; - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)) - .with_guessed_format() - .map_err(|e| e.to_string())?; + let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?; let mut limits = image::Limits::default(); limits.max_image_width = Some(16384); limits.max_image_height = Some(16384); limits.max_alloc = Some(128 * 1024 * 1024); reader.limits(limits); - let image = reader.decode().map_err(|_| { - "This image could not be previewed. Its contents may be incomplete or damaged.".to_string() - })?; + let image = reader + .decode() + .ok() + .context("This image could not be previewed. Its contents may be incomplete or damaged.")?; let image = if image.width() > 512 || image.height() > 512 { image.thumbnail(512, 512) } else { @@ -184,10 +193,15 @@ mod tests { image.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); let preview = load(&candidate(bytes.get_ref()), None, 1).unwrap(); assert_eq!(preview.dimensions(), (2, 3)); - assert!(load(&candidate(b"damaged"), None, 1).is_err()); + load(&candidate(b"damaged"), None, 1).unwrap_err(); let mut large = candidate(b""); large.size = 33 * 1024 * 1024; - assert!(load(&large, None, 1).unwrap_err().contains("too large")); + assert!( + load(&large, None, 1) + .unwrap_err() + .to_string() + .contains("too large") + ); } #[test] @@ -202,7 +216,7 @@ mod tests { let mut file = crate::drives::open_source(&path).unwrap(); file.seek(SeekFrom::Start(7)).unwrap(); let file = Arc::new(file); - let mut input = Input::new(file.clone()).unwrap(); + let mut input = Input::new(Arc::clone(&file)).unwrap(); input.seek(SeekFrom::Start(2)).unwrap(); let mut bytes = [0; 3]; input.read_exact(&mut bytes).unwrap(); diff --git a/src/recovery_tests.rs b/src/recovery_tests.rs index fa9a2ab..23d7d0e 100644 --- a/src/recovery_tests.rs +++ b/src/recovery_tests.rs @@ -384,7 +384,7 @@ fn scanned_source(app: &mut Reclaim) -> (tempfile::TempPath, Arc) let (path, source) = source_file(); let handle = Arc::new(source); app.scanned_source = Some("test-volume".into()); - app.source_handle = Some(handle.clone()); + app.source_handle = Some(Arc::clone(&handle)); app.source_size = Some(4100); app.results = vec![Found { offset: 4096, @@ -424,7 +424,7 @@ fn recovery_while_scanning_keeps_the_scan_running_and_its_cursor_in_place() { let (scan, rx) = mpsc::sync_channel(4); app.receiver = Some(rx); app.status = "Scanning for recoverable files…".into(); - let scan_cancel = app.cancel.clone(); + let scan_cancel = Arc::clone(&app.cancel); (&*handle).seek(SeekFrom::Start(1234)).unwrap(); let directory = tempfile::tempdir().unwrap(); app.export(directory.path().to_owned()); @@ -499,9 +499,9 @@ fn stop_recovery_interrupts_a_large_file_and_leaves_nothing_behind() { let mut input = StoppableReader { inner: StopsDuringFirstRead { data: std::io::Cursor::new(vec![b'x'; size]), - stop: stop.clone(), + stop: Arc::clone(&stop), }, - stop: stop.clone(), + stop: Arc::clone(&stop), }; let file = Found { offset: 0, @@ -515,11 +515,11 @@ fn stop_recovery_interrupts_a_large_file_and_leaves_nothing_behind() { extents: None, }; let directory = tempfile::tempdir().unwrap(); - assert!(reclaim::recover_unique(&mut input, directory.path(), &file, 1).is_err()); + reclaim::recover_unique(&mut input, directory.path(), &file, 1).unwrap_err(); assert!(stop.load(Ordering::Relaxed)); // Neither the file nor its private temporary file is left in the folder. assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 0); // The wrapper only refuses reads; seeking is unaffected. assert_eq!(input.seek(std::io::SeekFrom::Start(0)).unwrap(), 0); - assert!(input.read(&mut [0; 4]).is_err()); + input.read(&mut [0; 4]).unwrap_err(); } diff --git a/src/resilient.rs b/src/resilient.rs index cbfc978..ca7cc2b 100644 --- a/src/resilient.rs +++ b/src/resilient.rs @@ -57,8 +57,9 @@ impl Read for Reader<'_, R> { .ranges .range(at..) .next() - .map(|(&start, _)| to_usize(start.saturating_sub(at).min(bytes.len() as u64))) - .unwrap_or(bytes.len()); + .map_or(bytes.len(), |(&start, _)| { + to_usize(start.saturating_sub(at).min(bytes.len() as u64)) + }); let Some(bytes) = bytes.get_mut(..before_next) else { return Err(io::Error::from(io::ErrorKind::InvalidInput)); }; @@ -127,7 +128,7 @@ pub(crate) fn scan( let damage = Rc::new(RefCell::new(Damage::default())); let mut reader = Reader { input, - damage: damage.clone(), + damage: Rc::clone(&damage), cancel, area_end, }; @@ -210,7 +211,7 @@ mod tests { |e| match e { Event::Found(f) => found.push(f.offset), Event::Unreadable { offset, bytes } => skipped.push((offset, bytes)), - _ => {} + Event::UnusedSpace { .. } | Event::Progress(_) | Event::Checking { .. } => {} }, 32768, &|_| u64::MAX, @@ -255,7 +256,7 @@ mod tests { drop(reader); assert_eq!(input.reads, 2); input.seek(SeekFrom::Start(8192)).unwrap(); - assert!(input.read(&mut [0; 4096]).is_err()); + input.read(&mut [0; 4096]).unwrap_err(); } } diff --git a/src/slint_ui_tests.rs b/src/slint_ui_tests.rs index 4e2b01d..98d5aad 100644 --- a/src/slint_ui_tests.rs +++ b/src/slint_ui_tests.rs @@ -165,8 +165,8 @@ fn slint_workspace_renders_all_pages_and_filters_recovery_selection() { i18n::with_language(language, || { ui_text::apply(&ui); state.sync_ui(&ui); - assert_eq!(ui.global::().get_rtl(), i18n::is_rtl()); - assert_eq!(ui.global::().get_sources(), i18n::t("Sources")); + assert_eq!(ui.global::>().get_rtl(), i18n::is_rtl()); + assert_eq!(ui.global::>().get_sources(), i18n::t("Sources")); assert_eq!(ui.get_query(), "תמונות report العربية"); assert_eq!(state.source, original_path); assert_eq!( @@ -178,8 +178,9 @@ fn slint_workspace_renders_all_pages_and_filters_recovery_selection() { original_names ); for dark in [true, false] { - ui.global::().set_theme(if dark { 2 } else { 1 }); - assert_eq!(ui.global::().get_dark(), dark); + ui.global::>() + .set_theme(if dark { 2 } else { 1 }); + assert_eq!(ui.global::>().get_dark(), dark); for (width, height) in [(1160, 780), (900, 640)] { if width == 900 && !matches!(code, "en" | "he" | "ar") { continue; @@ -223,7 +224,7 @@ fn slint_workspace_renders_all_pages_and_filters_recovery_selection() { // The sidebar must physically switch edges, not just align its text. let edge = if i18n::is_rtl() { width - 2 } else { 1 }; let pixel = snapshot.as_slice()[(300 * width + edge) as usize]; - let surface = ui.global::().get_surface(); + let surface = ui.global::>().get_surface(); assert_eq!( (pixel.r, pixel.g, pixel.b), (surface.red(), surface.green(), surface.blue()), @@ -291,9 +292,10 @@ fn recovery_scrollbar_keeps_controls_clear_and_reaches_the_last_file() { ui.show().unwrap(); ui.window().set_size(slint::PhysicalSize::new(900, 640)); for (code, rtl) in [("en", false), ("he", true)] { - ui.global::().set_rtl(rtl); + ui.global::>().set_rtl(rtl); for dark in [false, true] { - ui.global::().set_theme(if dark { 2 } else { 1 }); + ui.global::>() + .set_theme(if dark { 2 } else { 1 }); ui.window().take_snapshot().unwrap(); let list = i_slint_backend_testing::ElementHandle::find_by_element_id( &ui, @@ -409,7 +411,7 @@ fn update_notice_can_be_dismissed_and_release_notes_open_only_on_request() { .into(), ); let installed = Rc::new(std::cell::Cell::new(false)); - let flag = installed.clone(); + let flag = Rc::clone(&installed); ui.on_apply_update(move || flag.set(true)); let weak = ui.as_weak(); ui.on_dismiss_update(move || weak.upgrade().unwrap().set_update_notice(false)); @@ -424,7 +426,8 @@ fn update_notice_can_be_dismissed_and_release_notes_open_only_on_request() { ui.set_update_title(i18n::message("Version {0} is available.", &["0.3.0"]).into()); ui.set_update_label(i18n::t("Update and restart").into()); for dark in [false, true] { - ui.global::().set_theme(if dark { 2 } else { 1 }); + ui.global::>() + .set_theme(if dark { 2 } else { 1 }); ui.set_page(0); ui.set_update_notice(true); ui.set_update_details_open(false); @@ -547,9 +550,9 @@ fn refresh_buttons_animate_even_when_results_do_not_change() { ui_text::apply(&ui); let drives = Rc::new(std::cell::Cell::new(0)); let checks = Rc::new(std::cell::Cell::new(0)); - let count = drives.clone(); + let count = Rc::clone(&drives); ui.on_refresh(move || count.set(count.get() + 1)); - let count = checks.clone(); + let count = Rc::clone(&checks); ui.on_check_update(move || count.set(count.get() + 1)); ui.show().unwrap(); ui.window().set_size(slint::PhysicalSize::new(900, 640)); @@ -892,19 +895,22 @@ fn layout_is_clear_and_steady_on_every_page_language_and_size() { ui_text::apply(&ui); ui.set_update_title(i18n::message("Version {0} is available.", &["0.3.0"]).into()); ui.set_update_label(i18n::t("Update and restart").into()); - for (width, height) in [(900u32, 640u32), (1160, 780)] { - ui.window() - .set_size(slint::PhysicalSize::new(width, height)); - let window = (width as f32, height as f32); + for (width, height) in [(900u16, 640u16), (1160, 780)] { + ui.window().set_size(slint::PhysicalSize::new( + u32::from(width), + u32::from(height), + )); + let window = (f32::from(width), f32::from(height)); for page in 0..3 { ui.set_page(page); - for (name, make, notice) in [ - ("first run", &first_run as &dyn Fn() -> Reclaim, false), + let states: [(&str, &dyn Fn() -> Reclaim, bool); 5] = [ + ("first run", &first_run, false), ("phone connected", &with_phone, false), ("scanning", &scanning, false), ("recovering while scanning", &recovering, false), ("update notice", &first_run, true), - ] { + ]; + for (name, make, notice) in states { let mut state = make(); state.sync_ui(&ui); ui.set_update_notice(notice); @@ -1091,7 +1097,7 @@ fn windows_drive_access_failure_has_an_actionable_aligned_restart_button() { .unwrap(); let ui = AppWindow::new().unwrap(); let restarted = Rc::new(std::cell::Cell::new(false)); - let flag = restarted.clone(); + let flag = Rc::clone(&restarted); ui.on_restart_as_administrator(move || flag.set(true)); ui.show().unwrap(); for (code, language) in [ @@ -1107,7 +1113,7 @@ fn windows_drive_access_failure_has_an_actionable_aligned_restart_button() { ui.set_needs_administrator(true); ui.window().set_size(slint::PhysicalSize::new(900, 640)); let snapshot = ui.window().take_snapshot().unwrap(); - crate::layout_checks::assert_controls_clear(&ui, (900., 640.), code); + layout_checks::assert_controls_clear(&ui, (900., 640.), code); let action = i_slint_backend_testing::ElementHandle::find_by_accessible_label( &ui, &i18n::t("Restart as administrator"), @@ -1171,9 +1177,11 @@ fn destination_review_offers_a_safe_choice_and_never_accepts_the_source_drive() ] { i18n::with_language(language, || { ui_text::apply(&ui); - for (width, height) in [(900u32, 640u32), (1160, 780)] { - ui.window() - .set_size(slint::PhysicalSize::new(width, height)); + for (width, height) in [(900u16, 640u16), (1160, 780)] { + ui.window().set_size(slint::PhysicalSize::new( + u32::from(width), + u32::from(height), + )); for (kind, destination) in [ ("same-drive", drives::Destination::SameDrive), ("unknown", drives::Destination::Unknown), @@ -1192,7 +1200,7 @@ fn destination_review_offers_a_safe_choice_and_never_accepts_the_source_drive() destination == drives::Destination::Unknown, "{context}: only an undetermined drive can be accepted" ); - assert_controls_clear(&ui, (width as f32, height as f32), &context); + assert_controls_clear(&ui, (f32::from(width), f32::from(height)), &context); // Dialog buttons never elide, so each must fit inside the card. let card = i_slint_backend_testing::ElementHandle::find_by_element_id( &ui, @@ -1234,9 +1242,9 @@ fn destination_review_offers_a_safe_choice_and_never_accepts_the_source_drive() }); } // Escape cancels. - let cancelled = std::rc::Rc::new(std::cell::Cell::new(false)); + let cancelled = Rc::new(std::cell::Cell::new(false)); ui.on_cancel_destination({ - let cancelled = cancelled.clone(); + let cancelled = Rc::clone(&cancelled); move || cancelled.set(true) }); ui.set_destination_review(false); @@ -1254,7 +1262,7 @@ fn destination_review_offers_a_safe_choice_and_never_accepts_the_source_drive() // "Save here anyway" never writes onto the scanned drive, even if invoked // for a same-drive folder; the dialog just closes. let mut state = Reclaim::default(); - state.destination_review = Some((folder.clone(), drives::Destination::SameDrive)); + state.destination_review = Some((folder, drives::Destination::SameDrive)); state.save_to_unconfirmed_destination(); assert!(!state.exporting && state.destination_review.is_none()); } @@ -1329,7 +1337,8 @@ fn stop_buttons_are_filled_red_in_light_and_dark() { state.exporting = true; state.status = "Scanning for recoverable files…".into(); for dark in [false, true] { - ui.global::().set_theme(if dark { 2 } else { 1 }); + ui.global::>() + .set_theme(if dark { 2 } else { 1 }); state.sync_ui(&ui); ui.window().take_snapshot().unwrap(); // Let the button's background animation finish. @@ -1405,7 +1414,7 @@ fn about_rows_are_keyboard_buttons_with_descriptions() { i18n::with_language(i18n::Language::English, || ui_text::apply(&ui)); ui.set_page(2); let opened = Rc::new(RefCell::new(Vec::new())); - let sink = opened.clone(); + let sink = Rc::clone(&opened); ui.on_open_link(move |link| sink.borrow_mut().push(link)); for label in [ "Source code", @@ -1460,7 +1469,8 @@ fn about_card_previews() { ui.set_version("0.2.3".into()); ui.set_page(2); for dark in [false, true] { - ui.global::().set_theme(if dark { 2 } else { 1 }); + ui.global::>() + .set_theme(if dark { 2 } else { 1 }); // Let colour transitions finish so the render shows the settled theme. ui.window().take_snapshot().unwrap(); std::thread::sleep(Duration::from_millis(300)); diff --git a/src/source.rs b/src/source.rs index f36b0fd..0674b24 100644 --- a/src/source.rs +++ b/src/source.rs @@ -14,6 +14,15 @@ pub struct SourceReader { cached_at: Option, cached_len: usize, } +impl std::fmt::Debug for SourceReader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SourceReader") + .field("position", &self.position) + .field("size", &self.size) + .field("alignment", &self.alignment) + .finish_non_exhaustive() + } +} impl SourceReader { pub fn new(inner: R, alignment: usize, size: Option) -> io::Result { if !alignment.is_power_of_two() || alignment > 65536 { @@ -66,10 +75,9 @@ impl Read for SourceReader { self.position < start || self.position >= start + self.cached_len as u64 }) { self.inner.seek(SeekFrom::Start(aligned))?; - let mut required = self - .size - .map(|n| to_usize((n - aligned).min(self.window_size as u64))) - .unwrap_or(self.window_size); + let mut required = self.size.map_or(self.window_size, |n| { + to_usize((n - aligned).min(self.window_size as u64)) + }); // A failed refill must not expose new bytes under the old offset. self.cached_at = None; self.cached_len = 0; @@ -86,7 +94,7 @@ impl Read for SourceReader { } Ok(0) => break, Ok(n) => self.cached_len += n, - Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} Err(e) if is_media_error(&e) && required > self.alignment => { // A large read may include a bad sector beyond the requested bytes. // Retry only the sector at the current position before failing. @@ -265,6 +273,6 @@ mod tests { let out = out_temp.path().join("aligned.pdf"); crate::recover_reader(&mut reader, &out, &found[0]).unwrap(); assert_eq!(std::fs::read(&out).unwrap(), content); - assert!(reader.seek(SeekFrom::Current(-100000)).is_err()); + reader.seek(SeekFrom::Current(-100_000)).unwrap_err(); } } diff --git a/src/ui_text.rs b/src/ui_text.rs index 100aa21..acdce30 100644 --- a/src/ui_text.rs +++ b/src/ui_text.rs @@ -104,8 +104,8 @@ ui_strings! { } pub fn apply(ui: &AppWindow) { - ui.global::().set_rtl(i18n::is_rtl()); - let strings = ui.global::(); + ui.global::>().set_rtl(i18n::is_rtl()); + let strings = ui.global::>(); apply_labels(&strings); strings.set_recovery_step_list(slint::ModelRc::new(slint::VecModel::from(recovery_steps()))); strings.set_window_title( diff --git a/src/update_runtime.rs b/src/update_runtime.rs index cf386ac..cbcaa3e 100644 --- a/src/update_runtime.rs +++ b/src/update_runtime.rs @@ -4,6 +4,9 @@ not(test), deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) )] +use anyhow::{Context, bail}; +#[cfg(target_os = "linux")] +use anyhow::{anyhow, ensure}; use reclaim::updater::{self, Release}; use std::path::{Path, PathBuf}; @@ -40,7 +43,7 @@ fn windows_installer_arguments() -> Vec { /// Private per-user folder for staged update packages. Each download gets its /// own `pending-*` folder, removed after installing or on the next launch. -pub(super) fn cache_root() -> Result { +pub(super) fn cache_root() -> anyhow::Result { #[cfg(windows)] let base = std::env::var_os("LOCALAPPDATA") .map(PathBuf::from) @@ -55,24 +58,23 @@ pub(super) fn cache_root() -> Result { .filter(|p| p.is_absolute()) .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) .map(|p| p.join("reclaim/updates")); - let path = - base.ok_or_else(|| reclaim::i18n::diagnostic("Could not locate the private update cache"))?; - std::fs::create_dir_all(&path).map_err(|e| e.to_string())?; + let path = base + .with_context(|| reclaim::i18n::diagnostic("Could not locate the private update cache"))?; + std::fs::create_dir_all(&path)?; Ok(path) } -fn new_stage() -> Result { - tempfile::Builder::new() +fn new_stage() -> anyhow::Result { + Ok(tempfile::Builder::new() .prefix(STAGE_PREFIX) - .tempdir_in(cache_root()?) - .map_err(|e| e.to_string()) + .tempdir_in(cache_root()?)?) } const STAGE_PREFIX: &str = "pending-"; /// Download and verify an installer the user opens themselves (macOS packages). /// It stays staged until the next launch, then [`cleanup_staged_updates`] removes it. -pub fn stage_installer(release: &Release, progress: impl Fn(u64, u64)) -> Result { +pub fn stage_installer(release: &Release, progress: impl Fn(u64, u64)) -> anyhow::Result { let stage = new_stage()?; let package = stage.path().join(&release.asset); updater::download_installer(release, &package, progress)?; @@ -84,10 +86,10 @@ pub fn update( release: &Release, progress: impl Fn(u64, u64), phase: impl Fn(&'static str), -) -> Result<(), String> { - let executable = std::env::current_exe().map_err(|e| e.to_string())?; +) -> anyhow::Result<()> { + let executable = std::env::current_exe()?; #[cfg(not(any(target_os = "linux", windows)))] - let _ = &executable; + let _: &PathBuf = &executable; if updater::installer_download(release).is_none() { #[cfg(target_os = "linux")] { @@ -98,18 +100,18 @@ pub fn update( return Ok(()); } #[cfg(not(target_os = "linux"))] - return Err("Automatic updates require an installed copy of Reclaim".into()); + bail!("Automatic updates require an installed copy of Reclaim"); } #[cfg(target_os = "linux")] if !Path::new(PKEXEC).is_file() { - return Err("Automatic package updates require pkexec (polkit)".into()); + bail!("Automatic package updates require pkexec (polkit)"); } #[cfg(windows)] if !executable .parent() .is_some_and(|p| p.join("installed-by-inno").is_file()) { - return Err("Run the Windows setup once to enable automatic updates".into()); + bail!("Run the Windows setup once to enable automatic updates"); } // Dropping `stage` deletes the package on every path, including errors; // only the Windows hand-off keeps it, because the installer is still running. @@ -135,7 +137,7 @@ pub fn update( Ok(()) } #[cfg(not(any(target_os = "linux", windows)))] - Err("Automatic updates are unavailable on this platform".into()) + bail!("Automatic updates are unavailable on this platform") } #[cfg(target_os = "linux")] @@ -146,12 +148,11 @@ const PKEXEC: &str = "/usr/bin/pkexec"; /// `/usr/bin/reclaim` checks the signature again over a private copy (see /// [`run_privileged_deb_update`]). Blocks until the package manager is done. #[cfg(target_os = "linux")] -fn install_deb(release: &Release, package: &Path) -> Result<(), String> { - std::fs::write(updater::signature_path(package), &release.signature) - .map_err(|e| e.to_string())?; +fn install_deb(release: &Release, package: &Path) -> anyhow::Result<()> { + std::fs::write(updater::signature_path(package), &release.signature)?; let package = package .to_str() - .ok_or_else(|| reclaim::i18n::diagnostic("Update cache path is not valid Unicode"))?; + .with_context(|| reclaim::i18n::diagnostic("Update cache path is not valid Unicode"))?; // Always elevate the system-installed binary, never a user-controlled one. let arguments = [ "/usr/bin/reclaim".to_owned(), @@ -160,7 +161,7 @@ fn install_deb(release: &Release, package: &Path) -> Result<(), String> { package.to_owned(), ]; let code = crate::native_process::spawn(Path::new(PKEXEC), &arguments) - .map_err(|e| format!("Could not ask for administrator permission: {e}"))? + .map_err(|e| anyhow!("Could not ask for administrator permission: {e}"))? .wait(); pkexec_result(code.ok()) } @@ -169,19 +170,19 @@ fn install_deb(release: &Release, package: &Path) -> Result<(), String> { /// Only the root-only copy that [`updater::protect_deb_update`] verified is /// passed to apt, with a fixed environment instead of the caller's. #[cfg(target_os = "linux")] -pub fn run_privileged_deb_update(args: &[std::ffi::OsString]) -> Result<(), String> { +pub fn run_privileged_deb_update(args: &[std::ffi::OsString]) -> anyhow::Result<()> { // SAFETY: geteuid has no preconditions and cannot fail. if unsafe { libc::geteuid() } != 0 { - return Err(reclaim::i18n::diagnostic( + bail!(reclaim::i18n::diagnostic( "This command is used only by Reclaim's updater", )); } - std::env::set_current_dir("/").map_err(|e| e.to_string())?; + std::env::set_current_dir("/")?; let package = updater::protect_deb_update(args)?; let path = package .path .to_str() - .ok_or_else(|| reclaim::i18n::diagnostic("Update path is not valid Unicode"))?; + .with_context(|| reclaim::i18n::diagnostic("Update path is not valid Unicode"))?; let arguments = ["install", "-y", "--", path].map(str::to_owned); let environment = [ "PATH=/usr/sbin:/usr/bin:/sbin:/bin", @@ -194,30 +195,30 @@ pub fn run_privileged_deb_update(args: &[std::ffi::OsString]) -> Result<(), Stri &arguments, environment, ) - .map_err(|e| format!("Could not start the package manager: {e}"))? + .map_err(|e| anyhow!("Could not start the package manager: {e}"))? .wait()?; // `package` (the protected copy) is removed when it goes out of scope. - if code == 0 { - Ok(()) - } else { - Err(format!( - "The package manager did not install the update (status {code})" - )) - } + ensure!( + code == 0, + "The package manager did not install the update (status {code})" + ); + Ok(()) } /// pkexec exits with 126 when the password prompt is dismissed and 127 when /// permission is refused; the elevated step exits with 1 on failure. `None` /// means it did not exit normally. #[cfg(any(target_os = "linux", test))] -fn pkexec_result(code: Option) -> Result<(), String> { +fn pkexec_result(code: Option) -> anyhow::Result<()> { match code { Some(0) => Ok(()), - Some(126 | 127) => Err("The update was not installed: administrator permission was not given. Reclaim was left open.".into()), - other => Err(format!( + Some(126 | 127) => bail!( + "The update was not installed: administrator permission was not given. Reclaim was left open." + ), + other => bail!( "Package update did not complete (status {}). Reclaim was left open.", other.map_or_else(|| "interrupted".into(), |c| c.to_string()) - )), + ), } } @@ -290,7 +291,7 @@ mod tests { #[test] fn cancellation_and_install_errors_never_request_a_restart() { - assert!(super::pkexec_result(Some(0)).is_ok()); + super::pkexec_result(Some(0)).unwrap(); for code in [Some(1), Some(126), Some(127), None] { assert!(super::pkexec_result(code).is_err(), "{code:?}"); } diff --git a/src/updater.rs b/src/updater.rs index 7482261..04ab9b0 100644 --- a/src/updater.rs +++ b/src/updater.rs @@ -11,6 +11,7 @@ deny(clippy::indexing_slicing, clippy::arithmetic_side_effects) )] use crate::i18n::diagnostic; +use anyhow::{Context, anyhow, bail}; use minisign_verify::{PublicKey, Signature}; use serde_json::Value; use sha2::{Digest, Sha256}; @@ -71,21 +72,30 @@ fn release_url(tag: &str, asset: &str) -> String { format!("https://github.com/{REPO}/releases/download/{tag}/{asset}") } -fn check_error(error: ureq::Error) -> String { +#[expect( + clippy::needless_pass_by_value, + reason = "a map_err adapter: it takes the error the way map_err hands it over" +)] +fn check_error(error: ureq::Error) -> anyhow::Error { log::warn!("Could not check GitHub releases: {error}"); - match error { + #[expect( + clippy::wildcard_enum_match_arm, + reason = "ureq::Error is non_exhaustive, so a catch-all arm is required" + )] + let message = match error { ureq::Error::Io(_) | ureq::Error::HostNotFound | ureq::Error::ConnectionFailed | ureq::Error::Timeout(_) => { "Could not connect to the update server. Check your internet connection and try again." } + // ureq::Error is non_exhaustive: every other failure, including future ones. _ => "Could not check for updates. Please try again later.", - } - .into() + }; + anyhow!(message) } -pub fn check() -> Result, String> { +pub fn check() -> anyhow::Result> { let mut response = get(&format!( "https://api.github.com/repos/{REPO}/releases/latest" )) @@ -98,15 +108,14 @@ pub fn check() -> Result, String> { .limit(2 * 1024 * 1024) .read_to_string() .map_err(check_error)?; - let json: Value = serde_json::from_str(&json).map_err(|e| e.to_string())?; + let json: Value = serde_json::from_str(&json)?; let version = semver::Version::parse( json.get("tag_name") .and_then(Value::as_str) .unwrap_or("") .trim_start_matches('v'), - ) - .map_err(|e| e.to_string())?; - let executable = std::env::current_exe().map_err(|e| e.to_string())?; + )?; + let executable = std::env::current_exe()?; let asset = installer_name(&executable, &version).unwrap_or_else(asset_name); let Some(mut release) = parse_release(&json, &asset)? else { return Ok(None); @@ -141,22 +150,23 @@ pub fn deb_asset(version: &semver::Version) -> String { /// Decode `text` and check it was made by the release key with exactly /// `comment`. The file contents are verified separately, while streaming. -fn checked_signature(text: &str, comment: &str) -> Result<(PublicKey, Signature), String> { - let key = - PublicKey::decode(TRUSTED_KEY).map_err(|_| diagnostic("Invalid built-in release key"))?; - let signature = Signature::decode(text).map_err(|_| UNSIGNED)?; +fn checked_signature(text: &str, comment: &str) -> anyhow::Result<(PublicKey, Signature)> { + let key = PublicKey::decode(TRUSTED_KEY) + .ok() + .with_context(|| diagnostic("Invalid built-in release key"))?; + let signature = Signature::decode(text).ok().context(UNSIGNED)?; // Binds file name and version; the comment itself is covered by the signature. if signature.trusted_comment() != comment { - return Err(UNSIGNED.into()); + bail!(UNSIGNED); } // Rejects other keys and legacy (non-prehashed) signatures before any download. - key.verify_stream(&signature).map_err(|_| UNSIGNED)?; + key.verify_stream(&signature).ok().context(UNSIGNED)?; Ok((key, signature)) } /// Decode the signature and check it was made by the release key for exactly /// this file and version. The file contents are verified while downloading. -fn signed_by_release_key(release: &Release) -> Result<(PublicKey, Signature), String> { +fn signed_by_release_key(release: &Release) -> anyhow::Result<(PublicKey, Signature)> { checked_signature(&release.signature, &signed_comment(release)) } @@ -172,6 +182,7 @@ pub const INSTALL_DEB_FLAG: &str = "--install-deb-update"; /// A verified package in a root-only folder, removed again when dropped. #[cfg(target_os = "linux")] +#[derive(Debug)] pub struct ProtectedPackage { _dir: tempfile::TempDir, pub path: std::path::PathBuf, @@ -189,27 +200,28 @@ pub struct ProtectedPackage { /// folder while being verified. Only versions newer than the installed one /// are accepted, so an older signed package cannot be used to downgrade. #[cfg(target_os = "linux")] -pub fn protect_deb_update(args: &[std::ffi::OsString]) -> Result { +pub fn protect_deb_update(args: &[std::ffi::OsString]) -> anyhow::Result { let [flag, version, package] = args else { - return Err(diagnostic("This command is used only by Reclaim's updater")); + bail!(diagnostic("This command is used only by Reclaim's updater")); }; if flag != INSTALL_DEB_FLAG { - return Err(diagnostic("This command is used only by Reclaim's updater")); + bail!(diagnostic("This command is used only by Reclaim's updater")); } let current = current_version(); let version = version .to_str() .and_then(|v| semver::Version::parse(v).ok()) .filter(|v| v.pre.is_empty() && v.build.is_empty() && *v > current) - .ok_or_else(|| diagnostic("Not a newer Reclaim version"))?; + .with_context(|| diagnostic("Not a newer Reclaim version"))?; let package = std::path::Path::new(package); let mut text = String::new(); regular_file(&signature_path(package))? .take(MAX_SIGNATURE + 1) .read_to_string(&mut text) - .map_err(|_| UNSIGNED)?; + .ok() + .context(UNSIGNED)?; if text.len() as u64 > MAX_SIGNATURE { - return Err(UNSIGNED.into()); + bail!(UNSIGNED); } let asset = deb_asset(&version); let (key, signature) = checked_signature(&text, &trusted_comment(&asset, &version))?; @@ -223,29 +235,29 @@ pub fn protect_deb_update(args: &[std::ffi::OsString]) -> Result Result { +fn regular_file(path: &std::path::Path) -> anyhow::Result { use std::os::unix::fs::OpenOptionsExt; // Non-blocking, so opening a FIFO returns at once and is refused below. let file = std::fs::OpenOptions::new() .read(true) .custom_flags(libc::O_NONBLOCK) .open(path) - .map_err(|e| diagnostic(&format!("Could not open the update: {e}")))?; + .map_err(|e| anyhow!(diagnostic(&format!("Could not open the update: {e}"))))?; let is_file = file.metadata().is_ok_and(|m| m.is_file()); is_file .then_some(file) - .ok_or_else(|| diagnostic("The staged update is not a regular file")) + .with_context(|| diagnostic("The staged update is not a regular file")) } /// A new folder inside `parent` that only its owner (root, when elevated) can use. #[cfg(target_os = "linux")] -fn protected_dir(parent: &std::path::Path) -> Result { +fn protected_dir(parent: &std::path::Path) -> anyhow::Result { use std::os::unix::fs::PermissionsExt; tempfile::Builder::new() .prefix("reclaim-update-") .permissions(std::fs::Permissions::from_mode(0o700)) .tempdir_in(parent) - .map_err(|e| diagnostic(&format!("Could not prepare the update: {e}"))) + .map_err(|e| anyhow!(diagnostic(&format!("Could not prepare the update: {e}")))) } /// Copies `source` into a new file at `protected`, verifying the signature @@ -256,30 +268,33 @@ fn copy_verified_package( protected: &std::path::Path, key: &PublicKey, signature: &Signature, -) -> Result<(), String> { - let mut dest = std::fs::File::create_new(protected).map_err(|e| e.to_string())?; - let mut verifier = key.verify_stream(signature).map_err(|_| UNSIGNED)?; +) -> anyhow::Result<()> { + let mut dest = std::fs::File::create_new(protected)?; + let mut verifier = key.verify_stream(signature).ok().context(UNSIGNED)?; let mut reader = regular_file(source)?.take(MAX_BINARY + 1); let mut buffer = vec![0u8; 64 * 1024]; let mut size = 0u64; loop { - let count = reader.read(&mut buffer).map_err(|e| e.to_string())?; + let count = reader.read(&mut buffer)?; if count == 0 { break; } // `Read` promises count <= buffer.len(); refuse a reader that breaks it. - let chunk = buffer.get(..count).ok_or("Update exceeds expected size")?; + let chunk = buffer + .get(..count) + .context("Update exceeds expected size")?; size = size.saturating_add(count as u64); if size > MAX_BINARY { - return Err("Update exceeds expected size".into()); + bail!("Update exceeds expected size"); } verifier.update(chunk); - dest.write_all(chunk).map_err(|e| e.to_string())?; + dest.write_all(chunk)?; } verifier .finalize() - .map_err(|_| "Update signature verification failed")?; - dest.sync_all().map_err(|e| e.to_string()) + .ok() + .context("Update signature verification failed")?; + Ok(dest.sync_all()?) } /// This build's version, from Cargo's always-numeric version parts. @@ -291,7 +306,7 @@ fn current_version() -> semver::Version { part(env!("CARGO_PKG_VERSION_PATCH")), ) } -fn parse_release(json: &Value, asset_name: &str) -> Result, String> { +fn parse_release(json: &Value, asset_name: &str) -> anyhow::Result> { parse_release_after(json, asset_name, ¤t_version()) } @@ -299,23 +314,23 @@ fn parse_release_after( json: &Value, asset_name: &str, current: &semver::Version, -) -> Result, String> { +) -> anyhow::Result> { if json["draft"].as_bool() != Some(false) || json["prerelease"].as_bool() != Some(false) { return Ok(None); } let tag = json["tag_name"] .as_str() - .ok_or_else(|| diagnostic("Missing release version"))?; - let version = semver::Version::parse(tag.trim_start_matches('v')).map_err(|e| e.to_string())?; + .with_context(|| diagnostic("Missing release version"))?; + let version = semver::Version::parse(tag.trim_start_matches('v'))?; if !version.pre.is_empty() || version <= *current { return Ok(None); } let asset = json["assets"] .as_array() - .ok_or_else(|| diagnostic("Missing release assets"))? + .with_context(|| diagnostic("Missing release assets"))? .iter() .find(|a| a["name"].as_str() == Some(asset_name)) - .ok_or("No update for this platform yet")?; + .context("No update for this platform yet")?; let signature_name = format!("{asset_name}.minisig"); let signature_url = json["assets"] .as_array() @@ -324,24 +339,24 @@ fn parse_release_after( .find(|a| a["name"].as_str() == Some(&signature_name)) .and_then(|a| a["browser_download_url"].as_str()) .filter(|url| *url == release_url(tag, &signature_name)) - .ok_or("This update is not signed by the Reclaim release key")? + .context("This update is not signed by the Reclaim release key")? .to_owned(); let url = asset["browser_download_url"] .as_str() - .ok_or_else(|| diagnostic("Missing download URL"))?; + .with_context(|| diagnostic("Missing download URL"))?; if url != release_url(tag, asset_name) { - return Err(diagnostic("Unexpected release download URL")); + bail!(diagnostic("Unexpected release download URL")); } let digest = asset["digest"] .as_str() .and_then(|s| s.strip_prefix("sha256:")) .filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())) - .ok_or_else(|| diagnostic("Release has no valid SHA-256 digest"))? + .with_context(|| diagnostic("Release has no valid SHA-256 digest"))? .to_ascii_lowercase(); let size = asset["size"] .as_u64() .filter(|s| *s > 0 && *s <= MAX_BINARY) - .ok_or_else(|| diagnostic("Invalid update size"))?; + .with_context(|| diagnostic("Invalid update size"))?; let release = Release { version, asset: asset_name.into(), @@ -362,6 +377,10 @@ pub fn installer_download(release: &Release) -> Option { is_installer(&release.asset).then(|| release.url.clone()) } +#[expect( + clippy::case_sensitive_file_extension_comparisons, + reason = "release asset names are exact; another case is not one of our assets" +)] fn is_installer(name: &str) -> bool { name.ends_with("-setup.exe") || name.ends_with(".deb") || name.ends_with(".pkg") } @@ -372,11 +391,11 @@ pub fn download_installer( release: &Release, destination: &std::path::Path, progress: impl Fn(u64, u64), -) -> Result<(), String> { +) -> anyhow::Result<()> { expect_installer(release)?; let mut response = get(&release.url) .call() - .map_err(|e| format!("Could not download update: {e}"))?; + .map_err(|e| anyhow!("Could not download update: {e}"))?; publish_download( response.body_mut().as_reader(), release, @@ -390,22 +409,20 @@ fn publish_download( release: &Release, destination: &std::path::Path, progress: impl Fn(u64, u64), -) -> Result<(), String> { +) -> anyhow::Result<()> { let parent = destination .parent() - .ok_or_else(|| diagnostic("Download destination has no parent folder"))?; - let mut pending = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?; + .with_context(|| diagnostic("Download destination has no parent folder"))?; + let mut pending = tempfile::NamedTempFile::new_in(parent)?; verify_download_progress(reader, &mut pending, release, progress)?; - pending.as_file().sync_all().map_err(|e| e.to_string())?; - pending - .persist(destination) - .map_err(|e| e.error.to_string())?; + pending.as_file().sync_all()?; + pending.persist(destination).map_err(|e| e.error)?; Ok(()) } -fn validate_url(release: &Release) -> Result<(), String> { +fn validate_url(release: &Release) -> anyhow::Result<()> { if release.asset.is_empty() || release.asset.contains(['/', '\\', '?', '#', '%']) { - return Err(diagnostic("Unexpected release asset name")); + bail!(diagnostic("Unexpected release asset name")); } let version = release.version.to_string(); if [format!("v{version}"), version] @@ -414,15 +431,15 @@ fn validate_url(release: &Release) -> Result<(), String> { { Ok(()) } else { - Err(diagnostic("Unexpected release download URL")) + bail!(diagnostic("Unexpected release download URL")) } } /// The release must be the package format this installation was installed with. -fn expect_installer(release: &Release) -> Result<(), String> { - let executable = std::env::current_exe().map_err(|e| e.to_string())?; +fn expect_installer(release: &Release) -> anyhow::Result<()> { + let executable = std::env::current_exe()?; if installer_name(&executable, &release.version).as_deref() != Some(&release.asset) { - return Err(diagnostic("Unexpected installer for this installation")); + bail!(diagnostic("Unexpected installer for this installation")); } validate_url(release) } @@ -448,36 +465,36 @@ fn installer_name(executable: &std::path::Path, version: &semver::Version) -> Op } } -pub fn install(release: &Release) -> Result<(), String> { +pub fn install(release: &Release) -> anyhow::Result<()> { install_with_progress(release, |_, _| {}) } -pub fn install_with_progress(release: &Release, progress: impl Fn(u64, u64)) -> Result<(), String> { - let executable = std::env::current_exe().map_err(|e| e.to_string())?; +pub fn install_with_progress(release: &Release, progress: impl Fn(u64, u64)) -> anyhow::Result<()> { + let executable = std::env::current_exe()?; if installer_name(&executable, &release.version).is_some() || installer_download(release).is_some() { - return Err("This installation must be updated using the matching installer.".into()); + bail!("This installation must be updated using the matching installer."); } if release.asset != asset_name() { - return Err(diagnostic("Unexpected executable update asset")); + bail!(diagnostic("Unexpected executable update asset")); } validate_url(release)?; if cfg!(windows) { - return Err("This installation must be updated using the matching installer.".into()); + bail!("This installation must be updated using the matching installer."); } // Private temporary file, bounded streaming download, verify before replacing anything. - let mut file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?; - let mut response = get(&release.url).call().map_err(|e| e.to_string())?; + let mut file = tempfile::NamedTempFile::new()?; + let mut response = get(&release.url).call()?; verify_download_progress( response.body_mut().as_reader(), &mut file, release, progress, )?; - file.as_file().sync_all().map_err(|e| e.to_string())?; + file.as_file().sync_all()?; replace_executable(&executable, file.path()).map_err(|e| { - format!("Could not install update: {e}. Move Reclaim to a writable folder and retry.") + anyhow!("Could not install update: {e}. Move Reclaim to a writable folder and retry.") }) } @@ -500,10 +517,10 @@ fn replace_executable( } /// Recheck a staged package immediately before handing it to the native installer. -pub fn verify_installer_file(release: &Release, path: &std::path::Path) -> Result<(), String> { +pub fn verify_installer_file(release: &Release, path: &std::path::Path) -> anyhow::Result<()> { expect_installer(release)?; verify_download_progress( - std::fs::File::open(path).map_err(|e| e.to_string())?, + std::fs::File::open(path)?, std::io::sink(), release, |_, _| {}, @@ -515,7 +532,7 @@ fn verify_download( reader: impl Read, mut file: impl Write, release: &Release, -) -> Result<(), String> { +) -> anyhow::Result<()> { verify_download_progress(reader, &mut file, release, |_, _| {}) } @@ -524,44 +541,45 @@ fn verify_download_progress( mut file: impl Write, release: &Release, progress: impl Fn(u64, u64), -) -> Result<(), String> { +) -> anyhow::Result<()> { // Release is public: enforce bounds here as well as when parsing the API. if release.size == 0 || release.size > MAX_BINARY || release.digest.len() != 64 || !release.digest.bytes().all(|b| b.is_ascii_hexdigit()) { - return Err(diagnostic("Invalid update metadata")); + bail!(diagnostic("Invalid update metadata")); } let (key, signature) = signed_by_release_key(release)?; - let mut verifier = key - .verify_stream(&signature) - .map_err(|_| "This update is not signed by the Reclaim release key")?; + let mut verifier = key.verify_stream(&signature).ok().context(UNSIGNED)?; let mut reader = reader.take(release.size.saturating_add(1)); let mut hash = Sha256::new(); let mut size = 0u64; let mut buffer = vec![0u8; 64 * 1024]; loop { - let count = reader.read(&mut buffer).map_err(|e| e.to_string())?; + let count = reader.read(&mut buffer)?; if count == 0 { break; } - let chunk = buffer.get(..count).ok_or("Update exceeds expected size")?; + let chunk = buffer + .get(..count) + .context("Update exceeds expected size")?; size = size.saturating_add(count as u64); if size > release.size { - return Err("Update exceeds expected size".into()); + bail!("Update exceeds expected size"); } hash.update(chunk); verifier.update(chunk); progress(size, release.size); - file.write_all(chunk).map_err(|e| e.to_string())?; + file.write_all(chunk)?; } if size != release.size || format!("{:x}", hash.finalize()) != release.digest { - return Err("Update checksum verification failed".into()); + bail!("Update checksum verification failed"); } verifier .finalize() - .map_err(|_| "Update signature verification failed".into()) + .ok() + .context("Update signature verification failed") } #[cfg(test)] @@ -643,13 +661,14 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT &version ) .unwrap() + .to_ascii_lowercase() .ends_with(".pkg") ); } #[test] fn download_rejects_corruption_truncation_and_oversize() { let r = signed_abc(); - assert!(verify_download(&b"abc"[..], Vec::new(), &r).is_ok()); + verify_download(&b"abc"[..], Vec::new(), &r).unwrap(); for bad in [b"abd".as_slice(), b"ab".as_slice(), b"abcd".as_slice()] { assert!(verify_download(bad, Vec::new(), &r).is_err()); } @@ -674,7 +693,7 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT let mut r = release(); r["assets"][0]["browser_download_url"] = format!("https://github.com/{REPO}/releases/download/v99.0.0/{suffix}").into(); - assert!(parse_release(&r, "test").is_err()); + parse_release(&r, "test").unwrap_err(); } } @@ -770,7 +789,7 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT #[test] fn only_updates_signed_by_the_release_key_for_this_version_install() { let good = signed_abc(); - assert!(verify_download(&b"abc"[..], Vec::new(), &good).is_ok()); + verify_download(&b"abc"[..], Vec::new(), &good).unwrap(); // Unsigned, garbage, or a valid signature for a different version/file. for signature in ["", "not a signature", SIGNED_ABC_AS_1_0_0] { let mut r = good.clone(); @@ -784,19 +803,19 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT renamed.asset = "other".into(); assert!(signed_by_release_key(&renamed).is_err()); // Contents that match a forged digest but not the signature. - let mut forged = good.clone(); + let mut forged = good; forged.digest = format!("{:x}", Sha256::digest(b"abd")); assert!(verify_download(&b"abd"[..], Vec::new(), &forged).is_err()); // A release without a matching .minisig asset is not offered at all. let mut json = release(); json["assets"].as_array_mut().unwrap().pop(); - assert!(parse_release(&json, "test").is_err()); + parse_release(&json, "test").unwrap_err(); json["assets"] .as_array_mut() .unwrap() .push(serde_json::json!({"name": "test.minisig", "browser_download_url": "https://evil.example/test.minisig"})); - assert!(parse_release(&json, "test").is_err()); + parse_release(&json, "test").unwrap_err(); } #[cfg(target_os = "linux")] @@ -890,13 +909,13 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT parse_release(&release(), "test").unwrap().unwrap().notes, "What's new" ); - assert!(parse_release(&release(), "other").is_err()); + parse_release(&release(), "other").unwrap_err(); let mut r = release(); r["assets"][0]["digest"] = Value::Null; - assert!(parse_release(&r, "test").is_err()); + parse_release(&r, "test").unwrap_err(); r = release(); r["assets"][0]["browser_download_url"] = "https://evil.example/app".into(); - assert!(parse_release(&r, "test").is_err()); + parse_release(&r, "test").unwrap_err(); r = release(); r["prerelease"] = true.into(); assert!(parse_release(&r, "test").unwrap().is_none()); @@ -905,7 +924,7 @@ MbpIWMky15o9MmvgFruTTeC1TX8xqIARe0bHCg69++aqfnx8HJDHPdy6DG0miEizEhAabxrfS0lYPwBT assert!(parse_release(&r, "test").unwrap().is_none()); r = release(); r["assets"][0]["size"] = (MAX_BINARY + 1).into(); - assert!(parse_release(&r, "test").is_err()); + parse_release(&r, "test").unwrap_err(); } } @@ -924,14 +943,14 @@ mod connection_message_tests { ureq::Error::HostNotFound, ureq::Error::ConnectionFailed, ] { - assert_eq!(check_error(error), expected); + assert_eq!(check_error(error).to_string(), expected); } } #[test] fn server_errors_do_not_claim_the_user_is_offline() { assert_eq!( - check_error(ureq::Error::StatusCode(503)), + check_error(ureq::Error::StatusCode(503)).to_string(), "Could not check for updates. Please try again later." ); } diff --git a/src/updates.rs b/src/updates.rs index 3362213..796fbc8 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -6,15 +6,16 @@ )] use reclaim::updater::{self, Release}; use std::{ + fmt::Write as _, io::{Read, Write}, path::PathBuf, sync::mpsc::{self, Receiver}, }; enum Message { - Checked(Result, String>), + Checked(anyhow::Result>), Progress(u64, u64), Phase(&'static str), - Finished(Result, String>), + Finished(anyhow::Result>), } #[derive(Default)] pub struct Updates { @@ -94,12 +95,9 @@ impl Updates { } } pub fn title(&self) -> String { - self.release - .as_ref() - .map(|release| { - reclaim::i18n::message("Version {0} is available.", &[&release.version.to_string()]) - }) - .unwrap_or_default() + self.release.as_ref().map_or_default(|release| { + reclaim::i18n::message("Version {0} is available.", &[&release.version.to_string()]) + }) } pub fn busy(&self) -> bool { self.receiver.is_some() @@ -203,14 +201,12 @@ impl Updates { self.notice_visible = release .as_ref() .is_some_and(|r| self.dismissed.as_ref() != Some(&r.version)); - self.status = release - .as_ref() - .map(|r| format!("Version {} is available.", r.version)) - .unwrap_or_else(|| "You’re up to date.".into()); - self.notes = release - .as_ref() - .map(|r| format_notes(&r.notes)) - .unwrap_or_default(); + self.status = release.as_ref().map_or_else( + || "You’re up to date.".into(), + |r| format!("Version {} is available.", r.version), + ); + self.notes = + release.as_ref().map_or_default(|r| format_notes(&r.notes)); self.release = release; } Err(e) => { @@ -223,7 +219,14 @@ impl Updates { } } } - Message::Progress(done, total) => self.progress = done as f32 / total.max(1) as f32, + Message::Progress(done, total) => { + #[expect( + clippy::cast_precision_loss, + reason = "a progress bar fraction; lost low bits cannot show" + )] + let progress = done as f32 / total.max(1) as f32; + self.progress = progress; + } Message::Phase(phase) => self.status = phase.into(), Message::Finished(result) => { self.receiver = None; @@ -309,7 +312,8 @@ fn format_notes(notes: &str) -> Vec { kind = 2; text.push_str(&" ".repeat(lists.len().saturating_sub(1))); if let Some(Some(number)) = lists.last_mut() { - text.push_str(&format!("{number}. ")); + // Writing to a String cannot fail. + write!(text, "{number}. ").ok(); *number = number.saturating_add(1); } else { text.push_str("• "); @@ -336,7 +340,11 @@ fn format_notes(notes: &str) -> Vec { flush(&mut blocks, &mut text, kind); } Event::TaskListMarker(checked) => text.push_str(if checked { "☑ " } else { "☐ " }), - _ => {} + Event::Start(_) + | Event::End(_) + | Event::InlineMath(_) + | Event::DisplayMath(_) + | Event::FootnoteReference(_) => {} } } flush(&mut blocks, &mut text, kind); @@ -358,7 +366,7 @@ mod tests { signature: String::new(), } } - fn checked(updates: &mut Updates, result: Result, String>) { + fn checked(updates: &mut Updates, result: anyhow::Result>) { let (tx, rx) = mpsc::channel(); updates.receiver = Some(rx); tx.send(Message::Checked(result)).unwrap(); @@ -394,8 +402,8 @@ mod tests { updates.receiver = Some(rx); assert!(updates.busy()); assert!(!updates.installing()); - checked(&mut updates, Err("offline".into())); - assert!(updates.status.is_empty()); + checked(&mut updates, Err(anyhow::anyhow!("offline"))); + assert_eq!(updates.status, ""); assert!(!updates.notice_visible); updates.checked = true; updates.check_automatically(); @@ -404,8 +412,8 @@ mod tests { "a completed automatic check is not repeated" ); updates.manual_check = true; - checked(&mut updates, Err("offline".into())); - assert!(!updates.status.is_empty()); + checked(&mut updates, Err(anyhow::anyhow!("offline"))); + assert_ne!(updates.status, ""); } #[test] fn release_notes_render_markdown_with_bounds() { @@ -424,7 +432,7 @@ mod tests { (3, "let x = 1;") ] ); - assert!(format_notes("No release notes.").is_empty()); + assert_eq!(format_notes("No release notes."), Vec::::new()); assert!(format_notes(&"א".repeat(10000))[0].text.chars().count() <= 6000); assert!(format_notes(&"line\n\n".repeat(100)).len() <= 40); } diff --git a/src/validation.rs b/src/validation.rs index a8f2233..bc5e8b8 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -1,11 +1,11 @@ use crate::{CandidateEnd, LIMIT, Validation}; -use image::{ImageFormat, ImageReader}; +use image::{AnimationDecoder, ImageDecoder, ImageFormat, ImageReader}; use std::{ io::Cursor, sync::atomic::{AtomicBool, Ordering}, }; -pub fn validate(kind: &str, bytes: &[u8], cancel: &AtomicBool) -> Option { +pub(crate) fn validate(kind: &str, bytes: &[u8], cancel: &AtomicBool) -> Option { if cancel.load(Ordering::Relaxed) { return None; } @@ -55,7 +55,6 @@ pub fn validate(kind: &str, bytes: &[u8], cancel: &AtomicBool) -> Option bool { reader.decode().is_ok() } -pub fn png_end(bytes: &[u8]) -> CandidateEnd { - use CandidateEnd::*; +pub(crate) fn png_end(bytes: &[u8]) -> CandidateEnd { + use CandidateEnd::{Complete, Invalid, More}; let mut p = 8usize; let mut data_seen = false; loop { @@ -162,8 +161,8 @@ pub fn png_end(bytes: &[u8]) -> CandidateEnd { } } -pub fn gif_end(bytes: &[u8]) -> CandidateEnd { - use CandidateEnd::*; +pub(crate) fn gif_end(bytes: &[u8]) -> CandidateEnd { + use CandidateEnd::{Complete, Invalid, More}; if bytes.len() < 13 { return More; } @@ -231,8 +230,8 @@ pub fn gif_end(bytes: &[u8]) -> CandidateEnd { } } -pub fn jpeg_end(bytes: &[u8]) -> CandidateEnd { - use CandidateEnd::*; +pub(crate) fn jpeg_end(bytes: &[u8]) -> CandidateEnd { + use CandidateEnd::{Complete, Invalid, More}; let mut p = 2; let mut entropy = false; let mut scan_seen = false; @@ -297,8 +296,8 @@ pub fn jpeg_end(bytes: &[u8]) -> CandidateEnd { } } -pub fn ico_end(bytes: &[u8], cancel: &AtomicBool) -> CandidateEnd { - use CandidateEnd::*; +pub(crate) fn ico_end(bytes: &[u8], cancel: &AtomicBool) -> CandidateEnd { + use CandidateEnd::{Complete, Invalid, More}; if bytes.len() >= 4 && &bytes[..4] != b"\0\0\x01\0" { return Invalid; } diff --git a/src/zip.rs b/src/zip.rs index f3aee8a..3ea77eb 100644 --- a/src/zip.rs +++ b/src/zip.rs @@ -12,10 +12,10 @@ use std::{ }; const MAX_END: u64 = u32::MAX as u64 + 65557; fn short(bytes: &[u8], at: usize) -> u64 { - crate::bytes::u16_le(bytes, at) as u64 + u64::from(crate::bytes::u16_le(bytes, at)) } fn long(bytes: &[u8], at: usize) -> u64 { - crate::bytes::u32_le(bytes, at) as u64 + u64::from(crate::bytes::u32_le(bytes, at)) } fn read( input: &mut (impl Read + Seek), @@ -58,7 +58,7 @@ pub(crate) fn large_end( ) -> io::Result> { Ok(match inspect(input, start, cancel)? { Inspection::Complete(size) if size > crate::LIMIT as u64 => Some(size), - _ => None, + Inspection::Complete(_) | Inspection::Invalid | Inspection::Unsupported => None, }) } fn walk(input: &mut (impl Read + Seek), start: u64, cancel: &AtomicBool) -> io::Result { @@ -81,7 +81,7 @@ fn walk(input: &mut (impl Read + Seek), start: u64, cancel: &AtomicBool) -> io:: if short(&header, 26) == 0 || short(&header, 4) > 63 { return Ok(Inspection::Invalid); } - if short(&header, 6) & 8 != 0 || long(&header, 18) == u32::MAX as u64 { + if short(&header, 6) & 8 != 0 || long(&header, 18) == u64::from(u32::MAX) { return Ok(Inspection::Unsupported); } locals.insert(at); diff --git a/tests/audit/main.rs b/tests/audit/main.rs index 8d9a10e..f94c9db 100644 --- a/tests/audit/main.rs +++ b/tests/audit/main.rs @@ -17,6 +17,10 @@ //! outlive the code they excused. #![expect(clippy::string_slice, reason = "the rules slice ASCII-delimited text")] +#![expect( + clippy::case_sensitive_file_extension_comparisons, + reason = "repository file names, whose case is fixed by the project" +)] // Test-only code, so Clippy treats the harness helpers as tests on every // toolchain: they report findings by panicking. @@ -40,92 +44,92 @@ fn workspace() -> &'static Workspace { #[test] fn unsafe_code_is_confined_and_documented() { - report(rules::unsafe_code(workspace())); + report(&rules::unsafe_code(workspace())); } #[test] fn no_memory_or_concurrency_hazards() { - report(rules::memory_hazards(workspace())); + report(&rules::memory_hazards(workspace())); } #[test] fn processes_are_only_started_by_the_native_launcher() { - report(rules::process_launching(workspace())); + report(&rules::process_launching(workspace())); } #[test] fn network_and_crypto_use_secure_defaults() { - report(rules::transport_and_crypto(workspace())); + report(&rules::transport_and_crypto(workspace())); } #[test] fn no_secrets_in_the_repository() { - report(rules::secrets(workspace())); + report(&rules::secrets(workspace())); } #[test] fn fixtures_carry_no_local_user_paths() { - report(rules::fixture_privacy(workspace())); + report(&rules::fixture_privacy(workspace())); } #[test] fn temporary_files_are_unpredictable() { - report(rules::temporary_files(workspace())); + report(&rules::temporary_files(workspace())); } #[test] fn untrusted_input_cannot_exhaust_memory() { - report(rules::resource_limits(workspace())); + report(&rules::resource_limits(workspace())); } #[test] fn unchecked_indexing_does_not_grow() { - report(rules::index_ratchet(workspace())); + report(&rules::index_ratchet(workspace())); } #[test] fn no_debug_leftovers_or_dead_code_markers() { - report(rules::leftovers(workspace())); + report(&rules::leftovers(workspace())); } #[test] fn lint_policy_stays_strict() { - report(rules::lint_policy(workspace())); + report(&rules::lint_policy(workspace())); } #[test] fn translation_catalogs_are_consistent() { - report(translations::catalogs(workspace())); + report(&translations::catalogs(workspace())); } #[test] fn every_interface_message_is_translated() { - report(translations::missing(workspace())); + report(&translations::missing(workspace())); } #[test] fn no_dead_translation_keys() { - report(translations::dead(workspace())); + report(&translations::dead(workspace())); } #[test] fn interface_strings_match_their_setters() { - report(translations::slint_strings(workspace())); + report(&translations::slint_strings(workspace())); } #[test] fn dependencies_are_pinned_and_locked() { - report(supply_chain::manifest(workspace())); + report(&supply_chain::manifest(workspace())); } #[test] fn advisory_exceptions_are_reviewed_and_current() { - report(supply_chain::advisories(workspace())); + report(&supply_chain::advisories(workspace())); } #[test] fn fuzz_harness_uses_production_dependencies() { - report(supply_chain::fuzz_lock(workspace())); + report(&supply_chain::fuzz_lock(workspace())); } /// Runs last by name: every rule above has recorded which suppressions it used. @@ -133,7 +137,7 @@ fn fuzz_harness_uses_production_dependencies() { fn zz_every_suppression_is_used() { let ws = workspace(); // Run each rule so the used-suppression set is complete regardless of test order. - let _ = ( + drop(( rules::unsafe_code(ws), rules::memory_hazards(ws), rules::process_launching(ws), @@ -144,6 +148,6 @@ fn zz_every_suppression_is_used() { rules::index_ratchet(ws), rules::leftovers(ws), translations::missing(ws), - ); - report(ws.unused_suppressions()); + )); + report(&ws.unused_suppressions()); } diff --git a/tests/audit/rules.rs b/tests/audit/rules.rs index a899ba5..75007ac 100644 --- a/tests/audit/rules.rs +++ b/tests/audit/rules.rs @@ -55,7 +55,7 @@ fn everywhere(ws: &Workspace) -> impl Iterator { /// CWE-676 (dangerous functions) and CWE-119 (memory safety): `unsafe` only in the /// platform layer, and every block explains why it is sound. -pub fn unsafe_code(ws: &Workspace) -> Vec { +pub(crate) fn unsafe_code(ws: &Workspace) -> Vec { let mut findings = Vec::new(); for file in &ws.rust { let lines: Vec<&str> = file.text.lines().collect(); @@ -95,7 +95,7 @@ pub fn unsafe_code(ws: &Workspace) -> Vec { /// CWE-362, CWE-843, CWE-401 and CWE-908: global mutable state, type punning, /// leaks and uninitialised memory. -pub fn memory_hazards(ws: &Workspace) -> Vec { +pub(crate) fn memory_hazards(ws: &Workspace) -> Vec { let mut findings = Vec::new(); for (file, event) in everywhere(ws) { match event { @@ -140,9 +140,14 @@ pub fn memory_hazards(ws: &Workspace) -> Vec { file, *line, "`assume_init` needs a reviewed reason", - )) + )); } - _ => {} + Event::Unsafe { .. } + | Event::Method { .. } + | Event::Macro { .. } + | Event::Index + | Event::Str { .. } + | Event::Ident { .. } => {} } } ws.unsuppressed(findings) @@ -150,7 +155,7 @@ pub fn memory_hazards(ws: &Workspace) -> Vec { /// CWE-78: OS command injection. No shell, no `Command`, and native process APIs /// only in the two reviewed launchers. -pub fn process_launching(ws: &Workspace) -> Vec { +pub(crate) fn process_launching(ws: &Workspace) -> Vec { let mut findings = Vec::new(); for (file, event) in production(ws) { match event { @@ -161,7 +166,7 @@ pub fn process_launching(ws: &Workspace) -> Vec { file, *line, "`std::process::Command` is not allowed in the app; use native_process", - )) + )); } Event::Ident { line, name } if PROCESS_IDENTS.contains(&name.as_str()) => { let allowed = PROCESS_APIS @@ -177,7 +182,14 @@ pub fn process_launching(ws: &Workspace) -> Vec { )); } } - _ => {} + Event::Unsafe { .. } + | Event::StaticMut { .. } + | Event::Call { .. } + | Event::Method { .. } + | Event::Macro { .. } + | Event::Index + | Event::Str { .. } + | Event::Ident { .. } => {} } } ws.unsuppressed(dedupe(findings)) @@ -185,7 +197,7 @@ pub fn process_launching(ws: &Workspace) -> Vec { /// CWE-319 (cleartext transport), CWE-295 (certificate validation) and CWE-327/328 /// (broken cryptography). -pub fn transport_and_crypto(ws: &Workspace) -> Vec { +pub(crate) fn transport_and_crypto(ws: &Workspace) -> Vec { const TLS_BYPASS: &[&str] = &[ "danger", "insecure", @@ -230,14 +242,20 @@ pub fn transport_and_crypto(ws: &Workspace) -> Vec { )); } } - _ => {} + Event::Unsafe { .. } + | Event::StaticMut { .. } + | Event::Call { .. } + | Event::Method { .. } + | Event::Macro { .. } + | Event::Index + | Event::Str { .. } => {} } } ws.unsuppressed(dedupe(findings)) } /// CWE-798: credentials committed to the repository. -pub fn secrets(ws: &Workspace) -> Vec { +pub(crate) fn secrets(ws: &Workspace) -> Vec { let mut findings = Vec::new(); for file in &ws.text { if file.path.starts_with("tests/audit/") { @@ -294,7 +312,7 @@ fn secret_kind(line: &str) -> Option<&'static str> { } /// CWE-377 and CWE-379: predictable names in the shared temporary directory. -pub fn temporary_files(ws: &Workspace) -> Vec { +pub(crate) fn temporary_files(ws: &Workspace) -> Vec { let findings = everywhere(ws) .filter_map(|(file, event)| match event { Event::Call { line, path, .. } if path.ends_with("temp_dir") => Some(Finding::new( @@ -304,7 +322,7 @@ pub fn temporary_files(ws: &Workspace) -> Vec { *line, "`env::temp_dir()` paths are predictable; use `tempfile` for a private, unique directory", )), - _ => None, + Event::Unsafe { .. } | Event::StaticMut { .. } | Event::Call { .. } | Event::Method { .. } | Event::Macro { .. } | Event::Index | Event::Str { .. } | Event::Ident { .. } => None, }) .collect(); ws.unsuppressed(findings) @@ -312,7 +330,7 @@ pub fn temporary_files(ws: &Workspace) -> Vec { /// CWE-400, CWE-770 and CWE-789: reads and allocations sized by untrusted input /// must have an explicit upper bound. -pub fn resource_limits(ws: &Workspace) -> Vec { +pub(crate) fn resource_limits(ws: &Workspace) -> Vec { let mut findings = Vec::new(); for (file, event) in production(ws) { match event { @@ -342,7 +360,7 @@ pub fn resource_limits(ws: &Workspace) -> Vec { file, *line, "whole-file read has no size limit; open the file and use `.take(limit)`", - )) + )); } Event::Call { line, path, args } if path.ends_with("with_capacity") => { if let Some(size) = args.first().filter(|size| !bounded(size)) { @@ -369,7 +387,14 @@ pub fn resource_limits(ws: &Workspace) -> Vec { } } } - _ => {} + Event::Unsafe { .. } + | Event::StaticMut { .. } + | Event::Call { .. } + | Event::Method { .. } + | Event::Macro { .. } + | Event::Index + | Event::Str { .. } + | Event::Ident { .. } => {} } } ws.unsuppressed(findings) @@ -391,7 +416,7 @@ fn bounded(expression: &str) -> bool { /// CWE-125 and CWE-129: unchecked `a[i]` panics on malformed input, which in a /// scanner is a denial of service. The count per file may only go down. -pub fn index_ratchet(ws: &Workspace) -> Vec { +pub(crate) fn index_ratchet(ws: &Workspace) -> Vec { let baseline_text = ws.read("tests/audit/baseline.toml"); let baseline: toml::Table = baseline_text .parse() @@ -409,7 +434,10 @@ pub fn index_ratchet(ws: &Workspace) -> Vec { } let mut findings = Vec::new(); for (file, count) in &counts { - let limit = limits.get(*file).and_then(|v| v.as_integer()).unwrap_or(0); + let limit = limits + .get(*file) + .and_then(toml::Value::as_integer) + .unwrap_or(0); if *count > limit { findings.push(Finding::new( "OOB-INDEX", @@ -438,7 +466,7 @@ pub fn index_ratchet(ws: &Workspace) -> Vec { /// CWE-489 (leftover debug code), CWE-561 (dead code) and CWE-1164 (irrelevant /// code): no debug macros, no silenced warnings, no stray files, no TODOs. -pub fn leftovers(ws: &Workspace) -> Vec { +pub(crate) fn leftovers(ws: &Workspace) -> Vec { const DEBUG_MACROS: &[&str] = &[ "dbg", "todo", @@ -568,8 +596,18 @@ fn orphans(ws: &Workspace) -> Vec { /// The compiler-enforced half of the audit: these lints must stay at `deny`, and /// CI must keep running Clippy, the tests and the advisory scan. -pub fn lint_policy(ws: &Workspace) -> Vec { - const RUST: &[&str] = &["unsafe_op_in_unsafe_fn"]; +pub(crate) fn lint_policy(ws: &Workspace) -> Vec { + const RUST: &[&str] = &[ + "unsafe_op_in_unsafe_fn", + // Peak tier (references/peak-lints.md in the house skill). + "unused_must_use", + "unused_qualifications", + "trivial_casts", + "trivial_numeric_casts", + "let_underscore_drop", + "elided_lifetimes_in_paths", + "missing_debug_implementations", + ]; const CLIPPY: &[&str] = &[ "undocumented_unsafe_blocks", "unwrap_used", @@ -586,6 +624,21 @@ pub fn lint_policy(ws: &Workspace) -> Vec { "mem_forget", "large_stack_arrays", "unreachable", + // Peak tier: whole groups plus the bug-catching picks. + "correctness", + "suspicious", + "perf", + "complexity", + "style", + "pedantic", + "wildcard_enum_match_arm", + "map_err_ignore", + "significant_drop_in_scrutinee", + "iter_over_hash_type", + "clone_on_ref_ptr", + "collection_is_never_read", + "read_zero_byte_vec", + "multiple_unsafe_ops_per_block", ]; let manifest: toml::Table = ws .file("Cargo.toml") @@ -689,7 +742,7 @@ fn user_paths(bytes: &[u8]) -> Vec { /// Test fixtures, disk images most of all, must not carry the local user /// name of whoever made them (CWE-538). Mounting an ext image, for example, /// records `/run/media//...` in its superblock and journal. -pub fn fixture_privacy(ws: &Workspace) -> Vec { +pub(crate) fn fixture_privacy(ws: &Workspace) -> Vec { use std::io::Read; let mut findings = Vec::new(); let mut pending = vec![ws.root.join("tests/fixtures")]; @@ -770,5 +823,8 @@ pub fn fixture_privacy(ws: &Workspace) -> Vec { fn user_paths_are_found_in_raw_bytes() { let image = b"\0\0/run/media/alex/1234-ABCD\0\0C:\\Users\\Sam\\Desktop\0word/media/x"; assert_eq!(user_paths(image), vec!["/run/media/alex", "\\Users\\Sam"]); - assert!(user_paths(b"word/media/image1.png /home/ alone").is_empty()); + assert_eq!( + user_paths(b"word/media/image1.png /home/ alone"), + Vec::::new() + ); } diff --git a/tests/audit/supply_chain.rs b/tests/audit/supply_chain.rs index 1e34de8..1d22575 100644 --- a/tests/audit/supply_chain.rs +++ b/tests/audit/supply_chain.rs @@ -54,11 +54,10 @@ fn dependency_tables(manifest: &toml::Value) -> Vec<(String, &toml::Table)> { fn line_of(text: &str, needle: &str) -> usize { text.lines() .position(|l| l.contains(needle)) - .map(|i| i + 1) - .unwrap_or(1) + .map_or(1, |i| i + 1) } -pub fn manifest(ws: &Workspace) -> Vec { +pub(crate) fn manifest(ws: &Workspace) -> Vec { let text = ws.file("Cargo.toml"); let manifest = toml::Value::Table(text.parse().expect("Cargo.toml is valid TOML")); let mut findings = Vec::new(); @@ -174,14 +173,13 @@ fn parse_date(text: &str) -> Option { } /// cargo-deny records a reason but does not expire exceptions; this does. -pub fn advisories(ws: &Workspace) -> Vec { +pub(crate) fn advisories(ws: &Workspace) -> Vec { let text = ws.file("deny.toml"); let config = toml::Value::Table(text.parse().expect("deny.toml is valid TOML")); let today = SystemTime::now() .duration_since(UNIX_EPOCH) // Days since 1970 are far below i64::MAX. - .map(|d| (d.as_secs() / 86_400).cast_signed()) - .unwrap_or(0); + .map_or(0, |d| (d.as_secs() / 86_400).cast_signed()); let locked = packages(ws.file("Cargo.lock")); let mut findings = Vec::new(); let ignores = config @@ -254,7 +252,7 @@ pub fn advisories(ws: &Workspace) -> Vec { /// The fuzz harnesses have their own lockfiles; they must not drift to versions /// the app does not ship, or the fuzzing proves nothing about the release. -pub fn fuzz_lock(ws: &Workspace) -> Vec { +pub(crate) fn fuzz_lock(ws: &Workspace) -> Vec { const HARNESS_ONLY: &[&str] = &[ "reclaim-fuzz", "reclaim-container-fuzz", diff --git a/tests/audit/translations.rs b/tests/audit/translations.rs index ff64e65..c3cef56 100644 --- a/tests/audit/translations.rs +++ b/tests/audit/translations.rs @@ -55,13 +55,12 @@ fn line_of_key(ws: &Workspace, path: &str, key: &str) -> usize { ws.file(path) .lines() .position(|l| l.trim_start().starts_with("ed)) - .map(|i| i + 1) - .unwrap_or(1) + .map_or(1, |i| i + 1) } /// `{0}`, `{e}`, `{}` and `{code:08X}` are all one placeholder to the translator, /// which matches the text around them. -pub fn normalize(text: &str) -> String { +pub(crate) fn normalize(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut chars = text.chars(); while let Some(c) = chars.next() { @@ -85,7 +84,7 @@ fn placeholders(text: &str) -> Vec { let Some(end) = rest[start..].find('}') else { break; }; - found.push(rest[start..start + end + 1].to_owned()); + found.push(rest[start..=(start + end)].to_owned()); rest = &rest[start + end + 1..]; } found.sort(); @@ -94,7 +93,7 @@ fn placeholders(text: &str) -> Vec { /// Catalog integrity: the same keys everywhere, no duplicates, nothing empty, /// placeholders preserved, English values equal to their keys. -pub fn catalogs(ws: &Workspace) -> Vec { +pub(crate) fn catalogs(ws: &Workspace) -> Vec { let catalogs = load(ws); let mut findings = Vec::new(); let english: BTreeSet<&str> = catalogs[0].pairs.iter().map(|(k, _)| k.as_str()).collect(); @@ -291,14 +290,14 @@ fn has_unanchored_trailing_symbol(value: &str) -> bool { /// Whether a literal reads like a sentence meant for people rather than an /// identifier, format, path or file signature. fn looks_like_message(text: &str) -> bool { - let words: Vec<&str> = text - .split_whitespace() - .filter(|w| w.chars().filter(|c| c.is_alphabetic()).count() >= 2) - .collect(); text.trim() == text && text.chars().next().is_some_and(|c| c.is_ascii_uppercase()) - && words.len() >= 2 - && text.chars().any(|c| c.is_lowercase()) + && text + .split_whitespace() + .filter(|w| w.chars().filter(|c| c.is_alphabetic()).count() >= 2) + .count() + >= 2 + && text.chars().any(char::is_lowercase) && !text.chars().any(char::is_control) && !["://", "::", "\\", "=", "%", "/dev/", "$"] .iter() @@ -306,16 +305,12 @@ fn looks_like_message(text: &str) -> bool { } fn english(ws: &Workspace) -> BTreeMap { - load(ws) - .into_iter() - .next() - .map(|c| { - c.pairs - .into_iter() - .map(|(k, _)| (normalize(&k), k)) - .collect() - }) - .unwrap_or_default() + load(ws).into_iter().next().map_or_default(|c| { + c.pairs + .into_iter() + .map(|(k, _)| (normalize(&k), k)) + .collect() + }) } /// String literals in `ui/app.slint` outside the `Strings` global, which the app @@ -349,7 +344,7 @@ fn slint_literals(ws: &Workspace) -> Vec<(usize, String)> { /// Interface text in the code that has no catalog entry is shown in English to /// everyone. Log lines, assertions and attribute text are not interface text. -pub fn missing(ws: &Workspace) -> Vec { +pub(crate) fn missing(ws: &Workspace) -> Vec { let keys = english(ws); let mut findings = Vec::new(); for file in ws.rust.iter().filter(|f| f.path.starts_with("src/")) { @@ -389,7 +384,7 @@ pub fn missing(ws: &Workspace) -> Vec { /// Keys no production code refers to. The translator derives singular forms /// (`files` to `file`), so those count as used when their plural is. -pub fn dead(ws: &Workspace) -> Vec { +pub(crate) fn dead(ws: &Workspace) -> Vec { let mut used: BTreeSet = BTreeSet::new(); for file in ws.rust.iter().filter(|f| f.path.starts_with("src/")) { for event in &file.production { @@ -440,7 +435,7 @@ pub fn dead(ws: &Workspace) -> Vec { /// Every translatable property in the `Strings` global has a setter in /// `src/ui_text.rs`, and its built-in English default is the same text. -pub fn slint_strings(ws: &Workspace) -> Vec { +pub(crate) fn slint_strings(ws: &Workspace) -> Vec { let slint = ws.file("ui/app.slint"); let ui_text = ws.file("src/ui_text.rs"); let mut setters: BTreeMap = BTreeMap::new(); diff --git a/tests/audit/workspace.rs b/tests/audit/workspace.rs index a67f934..5de0350 100644 --- a/tests/audit/workspace.rs +++ b/tests/audit/workspace.rs @@ -13,7 +13,7 @@ use syn::{ ItemStatic, Macro, StaticMutability, visit::Visit, }; -pub struct Finding { +pub(crate) struct Finding { pub rule: &'static str, pub cwe: Option, pub file: String, @@ -22,7 +22,7 @@ pub struct Finding { } impl Finding { - pub fn new( + pub(crate) fn new( rule: &'static str, cwe: Option, file: &str, @@ -41,7 +41,7 @@ impl Finding { impl fmt::Display for Finding { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let cwe = self.cwe.map(|id| format!(" CWE-{id}")).unwrap_or_default(); + let cwe = self.cwe.map_or_default(|id| format!(" CWE-{id}")); write!( f, "[{}{cwe}] {}:{}: {}", @@ -51,7 +51,7 @@ impl fmt::Display for Finding { } /// Fails the calling test with every finding, one per line. -pub fn report(findings: Vec) { +pub(crate) fn report(findings: &[Finding]) { if findings.is_empty() { return; } @@ -65,7 +65,7 @@ pub fn report(findings: Vec) { /// Where a string literal appears, which decides whether it can be interface text. #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Context { +pub(crate) enum Context { Code, /// Arguments of `log::*` macros: diagnostics for the log file, never shown. Log, @@ -79,7 +79,7 @@ pub enum Context { } #[derive(Debug)] -pub enum Event { +pub(crate) enum Event { Unsafe { line: usize, kind: &'static str, @@ -116,7 +116,7 @@ pub enum Event { }, } -pub struct RustFile { +pub(crate) struct RustFile { pub path: String, pub text: String, /// Events outside `#[cfg(test)]` code; test files have none. @@ -125,7 +125,7 @@ pub struct RustFile { pub tests: Vec, } -pub struct TextFile { +pub(crate) struct TextFile { pub path: String, pub text: String, } @@ -136,7 +136,7 @@ struct Suppression { rule: String, } -pub struct Workspace { +pub(crate) struct Workspace { pub root: PathBuf, pub rust: Vec, /// Every text file the repository ships (code, configuration, docs, site source). @@ -149,6 +149,8 @@ pub struct Workspace { const SKIP_DIRS: &[&str] = &[ "target", ".git", + // Git-ignored tool state, including other sessions' worktrees of this repository. + ".claude", "node_modules", "dist", ".astro", @@ -162,7 +164,7 @@ const TEXT_EXTENSIONS: &[&str] = &[ ]; impl Workspace { - pub fn load() -> Self { + pub(crate) fn load() -> Self { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut text = Vec::new(); collect_text(&root, &root, &mut text); @@ -244,7 +246,7 @@ impl Workspace { /// Whether a finding is accepted by a suppression on its line or in the comment /// block directly above it. - pub fn suppressed(&self, rule: &str, file: &str, line: usize) -> bool { + pub(crate) fn suppressed(&self, rule: &str, file: &str, line: usize) -> bool { let Some(text) = self.text.iter().find(|t| t.path == file) else { return false; }; @@ -253,7 +255,7 @@ impl Workspace { let mut above = line; while above > 1 { above -= 1; - let trimmed = lines.get(above - 1).map(|l| l.trim_start()).unwrap_or(""); + let trimmed = lines.get(above - 1).map_or("", |l| l.trim_start()); if trimmed.starts_with("//") { candidates.push(above); } else { @@ -267,7 +269,7 @@ impl Workspace { { self.used .lock() - .unwrap_or_else(|e| e.into_inner()) + .unwrap_or_else(std::sync::PoisonError::into_inner) .insert(index); return true; } @@ -276,15 +278,18 @@ impl Workspace { } /// Keeps findings that no suppression accepts. - pub fn unsuppressed(&self, findings: Vec) -> Vec { + pub(crate) fn unsuppressed(&self, findings: Vec) -> Vec { findings .into_iter() .filter(|f| !self.suppressed(f.rule, &f.file, f.line)) .collect() } - pub fn unused_suppressions(&self) -> Vec { - let used = self.used.lock().unwrap_or_else(|e| e.into_inner()); + pub(crate) fn unused_suppressions(&self) -> Vec { + let used = self + .used + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); let mut findings: Vec = self .suppressions .iter() @@ -311,15 +316,14 @@ impl Workspace { findings } - pub fn file(&self, path: &str) -> &str { + pub(crate) fn file(&self, path: &str) -> &str { self.text .iter() .find(|t| t.path == path) - .map(|t| t.text.as_str()) - .unwrap_or_else(|| panic!("{path} is missing")) + .map_or_else(|| panic!("{path} is missing"), |t| t.text.as_str()) } - pub fn read(&self, path: &str) -> String { + pub(crate) fn read(&self, path: &str) -> String { std::fs::read_to_string(self.root.join(path)).unwrap_or_else(|e| panic!("{path}: {e}")) } } @@ -403,9 +407,9 @@ struct Walker { impl Walker { fn push(&mut self, event: Event) { if self.in_test { - self.tests.push(event) + self.tests.push(event); } else { - self.production.push(event) + self.production.push(event); } } @@ -452,6 +456,8 @@ impl Walker { } const LOG_MACROS: &[&str] = &["trace", "debug", "info", "warn", "error", "log"]; +/// `anyhow` macros whose arguments are parsed as expressions. +const ERROR_MACROS: &[&str] = &["anyhow", "bail", "ensure"]; const ASSERT_MACROS: &[&str] = &[ "assert", "assert_eq", @@ -478,7 +484,7 @@ impl<'ast> Visit<'ast> for Walker { fn visit_item_mod(&mut self, node: &'ast ItemMod) { self.scoped(is_test_attr(&node.attrs), |w| { - syn::visit::visit_item_mod(w, node) + syn::visit::visit_item_mod(w, node); }); } @@ -490,7 +496,7 @@ impl<'ast> Visit<'ast> for Walker { kind: "unsafe fn", }); } - syn::visit::visit_item_fn(w, node) + syn::visit::visit_item_fn(w, node); }); } @@ -502,7 +508,7 @@ impl<'ast> Visit<'ast> for Walker { kind: "unsafe fn", }); } - syn::visit::visit_impl_item_fn(w, node) + syn::visit::visit_impl_item_fn(w, node); }); } @@ -514,7 +520,7 @@ impl<'ast> Visit<'ast> for Walker { kind: "unsafe impl", }); } - syn::visit::visit_item_impl(w, node) + syn::visit::visit_item_impl(w, node); }); } @@ -548,8 +554,7 @@ impl<'ast> Visit<'ast> for Walker { .path .segments .first() - .map(|s| line_of(s.ident.span())) - .unwrap_or(0); + .map_or(0, |s| line_of(s.ident.span())); let diagnostic = matches!(text.rsplit("::").next(), Some("diagnostic" | "invalid")) || text.ends_with("Error::other") || text.ends_with("Error::new"); @@ -561,7 +566,7 @@ impl<'ast> Visit<'ast> for Walker { if diagnostic { self.visit_expr(&node.func); self.with_context(Context::Diagnostic, |w| { - node.args.iter().for_each(|arg| w.visit_expr(arg)) + node.args.iter().for_each(|arg| w.visit_expr(arg)); }); return; } @@ -598,14 +603,12 @@ impl<'ast> Visit<'ast> for Walker { .path .segments .last() - .map(|s| s.ident.to_string()) - .unwrap_or_default(); + .map_or_default(|s| s.ident.to_string()); let line = node .path .segments .last() - .map(|s| line_of(s.ident.span())) - .unwrap_or(0); + .map_or(0, |s| line_of(s.ident.span())); self.push(Event::Macro { line, name: name.clone(), @@ -618,6 +621,16 @@ impl<'ast> Visit<'ast> for Walker { } else { self.context }; + // Error macros take expressions, so `bail!(diagnostic("..."))` is read + // like `Err(diagnostic("..."))` instead of as loose tokens. + if ERROR_MACROS.contains(&name.as_str()) + && let Ok(args) = node.parse_body_with( + syn::punctuated::Punctuated::::parse_terminated, + ) + { + self.with_context(context, |w| args.iter().for_each(|arg| w.visit_expr(arg))); + return; + } self.with_context(context, |w| w.walk_tokens(node.tokens.clone())); } diff --git a/tests/expanded_formats.rs b/tests/expanded_formats.rs index b4eebff..4d986f1 100644 --- a/tests/expanded_formats.rs +++ b/tests/expanded_formats.rs @@ -199,7 +199,7 @@ fn generated_names_are_readable_and_keep_the_correct_extension() { }; assert_eq!(found.recovery_name(3), expected); assert_eq!( - found.recovery_name(100000), + found.recovery_name(100_000), expected.replace("0003", "100000") ); } diff --git a/tests/large_zip.rs b/tests/large_zip.rs index 08ffa33..fb86e3e 100644 --- a/tests/large_zip.rs +++ b/tests/large_zip.rs @@ -23,7 +23,7 @@ fn archive(file: &mut std::fs::File, prefix: u64) -> u64 { file.seek(SeekFrom::Start(prefix)).unwrap(); file.write_all(&local).unwrap(); file.write_all(b"a").unwrap(); - let directory = 31 + size as u64; + let directory = 31 + u64::from(size); file.seek(SeekFrom::Start(prefix + directory)).unwrap(); let mut central = [0; 46]; central[..4].copy_from_slice(b"PK\x01\x02"); diff --git a/tests/new_formats.rs b/tests/new_formats.rs index e8b1b76..00f2bff 100644 --- a/tests/new_formats.rs +++ b/tests/new_formats.rs @@ -1,6 +1,6 @@ use reclaim::{Event, Found, Validation, recover_reader, scan_reader}; use std::{ - io::{self, Cursor, Read, Seek, SeekFrom}, + io::{self, Cursor, Read, Seek, SeekFrom, Write}, sync::atomic::{AtomicBool, Ordering}, }; const FIXTURES: &[(&str, &[u8])] = &[ @@ -38,7 +38,7 @@ fn collect(input: &mut (impl Read + Seek)) -> Vec { let mut found = Vec::new(); scan_reader(input, &AtomicBool::new(false), |e| { if let Event::Found(f) = e { - found.push(f) + found.push(f); } }) .unwrap(); @@ -148,7 +148,7 @@ fn short_device_reads_and_cancellation_are_supported() { scan_reader(&mut Cursor::new(FIXTURES[0].1), &cancel, |e| match e { Event::Checking { .. } => cancel.store(true, Ordering::Relaxed), Event::Found(_) => found += 1, - _ => {} + Event::Unreadable { .. } | Event::UnusedSpace { .. } | Event::Progress(_) => {} }) .unwrap(); assert_eq!(found, 0); @@ -274,7 +274,7 @@ fn swf_extended_tags_are_bounded_and_version_eight_requires_file_attributes() { #[test] fn varied_header_mutations_never_panic_or_report_out_of_bounds_files() { - let mut state = 0x3141592653589793u64; + let mut state = 0x3141_5926_5358_9793_u64; for (_, fixture) in FIXTURES { for _ in 0..48 { let mut bytes = fixture.to_vec(); @@ -310,7 +310,6 @@ fn gzip_crc_and_xar_xml_are_checked_and_archive_members_do_not_consume_neighbour ); let plain = b'X'; let xml = b"]>"; - use std::io::Write; let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); encoder.write_all(xml).unwrap(); let toc = encoder.finish().unwrap(); diff --git a/tests/security.rs b/tests/security.rs index 37e5afb..08aa5a2 100644 --- a/tests/security.rs +++ b/tests/security.rs @@ -91,14 +91,14 @@ fn source_reader_preserves_bytes_and_checks_seek_bounds() { let mut buffer = [0; 7]; source.read_exact(&mut buffer).unwrap(); assert_eq!(buffer, data[511..518]); - assert!(source.seek(SeekFrom::Current(-519)).is_err()); + source.seek(SeekFrom::Current(-519)).unwrap_err(); assert_eq!(source.stream_position().unwrap(), 518); source.seek(SeekFrom::End(-7)).unwrap(); source.read_exact(&mut buffer).unwrap(); assert_eq!(buffer, data[2041..]); assert_eq!(source.read(&mut buffer).unwrap(), 0); source.seek(SeekFrom::Start(u64::MAX)).unwrap(); - assert!(source.seek(SeekFrom::Current(1)).is_err()); + source.seek(SeekFrom::Current(1)).unwrap_err(); assert_eq!(source.read(&mut buffer).unwrap(), 0); } } @@ -154,9 +154,15 @@ fn simultaneous_exports_never_replace_each_other_or_existing_data() { std::fs::write(&existing, b"irreplaceable").unwrap(); let barrier = Arc::new(Barrier::new(8)); let outputs = std::thread::scope(|scope| { + // Collected first: every worker must be spawned before any is joined, + // or the barrier never fills. + #[expect( + clippy::needless_collect, + reason = "all threads must start before the first join" + )] let workers: Vec<_> = (0u8..8) .map(|value| { - let barrier = barrier.clone(); + let barrier = Arc::clone(&barrier); let directory = directory.path(); scope.spawn(move || { barrier.wait();