diff --git a/arca-gui/src/archive_ops/io.rs b/arca-gui/src/archive_ops/io.rs index dcfdc5c..f740e84 100644 --- a/arca-gui/src/archive_ops/io.rs +++ b/arca-gui/src/archive_ops/io.rs @@ -233,7 +233,7 @@ pub(crate) fn check_access( let a = arca_rar::RarArchive::open_with_progress(archive, password, notify)?; if a.entries().iter().any(|e| e.encrypted) { let password = password.ok_or(arca_core::Error::PasswordRequired)?; - a.test(Some(password), notify) + a.check_password(password, notify) } else { Ok(()) } diff --git a/arca-gui/src/clipboard.rs b/arca-gui/src/clipboard.rs index 57c960f..32ab09d 100644 --- a/arca-gui/src/clipboard.rs +++ b/arca-gui/src/clipboard.rs @@ -132,6 +132,18 @@ pub fn clear() { } } +/// A path out of a text/uri-list without the carriage return that ends its +/// line. The list is CRLF by its RFC, and Nautilus and Dolphin write it so, +/// but arboard splits it at the line feed alone and leaves the return on the +/// path, which then names a file that does not exist. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn without_line_end(path: PathBuf) -> PathBuf { + match path.to_str() { + Some(text) if text.ends_with('\r') => PathBuf::from(text.trim_end_matches('\r')), + _ => path, + } +} + #[cfg(target_os = "linux")] mod linux { use super::PathBuf; @@ -172,7 +184,11 @@ mod linux { } pub fn files() -> Vec { - with(|clipboard| clipboard.get().file_list().unwrap_or_default()).unwrap_or_default() + with(|clipboard| clipboard.get().file_list().unwrap_or_default()) + .unwrap_or_default() + .into_iter() + .map(super::without_line_end) + .collect() } pub fn taken() -> (Vec, bool) { @@ -247,7 +263,7 @@ pub fn clear() {} #[cfg(test)] mod tests { - use super::shell_path; + use super::{shell_path, without_line_end}; use std::path::PathBuf; #[test] @@ -264,4 +280,16 @@ mod tests { assert_eq!(plain(r"C:\Temp\a.txt"), PathBuf::from(r"C:\Temp\a.txt")); assert_eq!(plain("/tmp/a.txt"), PathBuf::from("/tmp/a.txt")); } + + #[test] + fn a_uri_list_written_with_crlf_still_names_the_files() { + assert_eq!( + without_line_end(PathBuf::from("/home/me/a b.txt\r")), + PathBuf::from("/home/me/a b.txt") + ); + assert_eq!( + without_line_end(PathBuf::from("/home/me/plain.txt")), + PathBuf::from("/home/me/plain.txt") + ); + } } diff --git a/arca-gui/src/controller/disk.rs b/arca-gui/src/controller/disk.rs index 8f59367..6039e03 100644 --- a/arca-gui/src/controller/disk.rs +++ b/arca-gui/src/controller/disk.rs @@ -798,7 +798,10 @@ impl AppController { pub(crate) fn rename_on_disk(&mut self, from: &str, to: &str) { let s = self.s(); let (a, b) = (disk_path(from), disk_path(to)); - if b.exists() { + // On a disk that ignores case, `b` exists when only the case of the + // name is changing, and that one it is: renaming it is the point. + let same = arca_core::extraction::claim_key(&a) == arca_core::extraction::claim_key(&b); + if b.exists() && !same { let name = b .file_name() .map(|n| n.to_string_lossy().into_owned()) diff --git a/arca-gui/src/controller/disk_tests.rs b/arca-gui/src/controller/disk_tests.rs index 83875b0..dfd926a 100644 --- a/arca-gui/src/controller/disk_tests.rs +++ b/arca-gui/src/controller/disk_tests.rs @@ -529,3 +529,25 @@ fn places_and_drives_are_read_off_the_drawing_thread() { "nothing is read again before it is due" ); } + +// Changing only the case of a name is a rename like any other, though on a +// disk that ignores case the new name already "exists". +#[test] +fn a_name_can_change_only_its_case() { + let room = Room::new(); + std::fs::write(room.path("note.txt"), b"x").unwrap(); + let mut app = AppController::new(Settings::default()); + let dir = super::disk::disk_dir(&room.path("")); + let dir = if dir.ends_with('/') { + dir + } else { + format!("{dir}/") + }; + app.rename_on_disk(&format!("{dir}note.txt"), &format!("{dir}Note.txt")); + assert!(!app.state.error, "{}", app.state.notice); + let names: Vec = std::fs::read_dir(room.path("")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["Note.txt"]); +} diff --git a/arca-gui/src/controller/jobs.rs b/arca-gui/src/controller/jobs.rs index ea028d9..159f253 100644 --- a/arca-gui/src/controller/jobs.rs +++ b/arca-gui/src/controller/jobs.rs @@ -326,6 +326,14 @@ impl AppController { }; task.stop.store(true, Ordering::Relaxed); task.hold.store(false, Ordering::Relaxed); + // A task waiting on an answer about a conflict is not looking at the + // stop flag; the answer it is waiting for is the way to stop it. + if task.conflict.take().is_some() { + task.conflict_from = None; + if let Some(replies) = &task.replies { + let _ = replies.send(Answer::Cancel); + } + } if task.status == TaskStatus::Queued { task.status = TaskStatus::Stopped; task.result = stopped; diff --git a/arca-gui/src/controller/jobs_tests.rs b/arca-gui/src/controller/jobs_tests.rs index faff5f9..d9020e1 100644 --- a/arca-gui/src/controller/jobs_tests.rs +++ b/arca-gui/src/controller/jobs_tests.rs @@ -877,3 +877,56 @@ fn undoing_puts_back_an_archive_a_rewrite_left_missing() { assert!(!app.state.error, "{}", app.state.notice); assert_eq!(app.state.entries.len(), after + 1); } + +#[test] +fn opening_an_archive_can_be_given_up_on() { + let room = Room::new(); + let source = room.path("source"); + fs::create_dir_all(&source).unwrap(); + fs::write(source.join("a.txt"), b"contents").unwrap(); + let archive = room.path("slow.zip"); + crate::archive_ops::compress( + &archive, + &[source], + crate::Format::Zip, + Codec::Deflate, + Level::NORMAL, + &|_, _, _| true, + (None, false), + ) + .unwrap(); + let mut app = AppController::new(Settings::default()); + app.browse_disk(&room.path("")); + settle(&mut app); + app.open_with_password(archive.clone(), None); + assert!(app.state.listing); + app.cancel_opening(); + assert!(!app.state.listing && !app.state.busy); + assert!(app.state.channel.is_none()); + std::thread::sleep(Duration::from_millis(100)); + app.receive(); + assert!(app.on_disk(), "the window went back to the folder"); + assert_ne!(app.state.archive.as_ref(), Some(&archive)); +} + +#[test] +fn stopping_a_task_that_waits_on_a_question_lets_it_go() { + let mut app = AppController::new(Settings::default()); + let (answered_tx, answered_rx) = channel(); + let asker: Work = Box::new(move |tx, replies, _, _| { + let _ = tx.send(Message::Conflict("there.txt".into())); + let answer = replies.recv().unwrap_or(Answer::Cancel); + let _ = answered_tx.send(answer); + let _ = tx.send(Message::Failed(arca_core::Error::Cancelled.to_string())); + }); + let asking = app.enqueue(Task::new("Extract", "a", asker)); + settle_until(&mut app, |app| app.conflict().is_some()); + app.cancel_task(asking); + assert!(app.conflict().is_none()); + assert_eq!( + answered_rx.recv_timeout(Duration::from_secs(10)).unwrap(), + Answer::Cancel + ); + settle(&mut app); + assert_eq!(status(&app, asking), TaskStatus::Stopped); +} diff --git a/arca-gui/src/controller/mod.rs b/arca-gui/src/controller/mod.rs index 78584fc..ba7deb6 100644 --- a/arca-gui/src/controller/mod.rs +++ b/arca-gui/src/controller/mod.rs @@ -1030,6 +1030,24 @@ impl AppController { // stands for all of them, so a copy hands the clipboard one folder instead // of the fifteen hundred files inside it, and the Explorer pastes a folder // rather than a heap of loose files. + /// Gives up on an archive still being read and goes back to where the + /// window was. The reading thread is told to stop and whatever it still + /// sends is not listened to. + pub(crate) fn cancel_opening(&mut self) { + if !self.state.listing { + return; + } + self.state + .stop + .store(true, std::sync::atomic::Ordering::Relaxed); + self.state.channel = None; + self.state.busy = false; + self.state.listing = false; + self.state.overlay = false; + self.state.view = View::Browse; + self.close_archive(); + } + pub(crate) fn cancel_password(&mut self) { let was_job = matches!(self.state.waiting_on_password, Some(Pending::Extract(_))); let was_opening = matches!(self.state.waiting_on_password, Some(Pending::OpenArchive)); @@ -2096,7 +2114,7 @@ impl AppController { .entries .iter() .enumerate() - .map(|(i, e)| (e.name.replace('\\', "/"), i)) + .map(|(i, e)| (tree::normalized(e), i)) .collect(); index.sort_unstable(); let index = std::rc::Rc::new(index); diff --git a/arca-gui/src/controller/panes.rs b/arca-gui/src/controller/panes.rs index 7eb22f2..878e0f9 100644 --- a/arca-gui/src/controller/panes.rs +++ b/arca-gui/src/controller/panes.rs @@ -742,4 +742,29 @@ mod tests { built.len() ); } + + // 7z names an empty folder without the slash ZIP gives it, and its row + // still has to be one that can be ticked. + #[test] + fn an_empty_folder_named_without_a_slash_can_be_picked() { + let mut c = controller(); + let mut empty = entry("empty"); + empty.is_dir = true; + c.state.entries.push(empty); + c.entries_changed(); + c.state.active_pane_mut().checked = vec![false; c.state.entries.len()]; + let row = c + .visible_rows() + .iter() + .find(|r| r.path == "empty/") + .cloned() + .expect("the empty folder has a row"); + assert!(!c.is_checked(&row)); + c.dispatch(AppAction::SetChecked { + row: row.clone(), + value: true, + }); + assert!(c.is_checked(&row)); + assert!(*c.state.active_pane().checked.last().unwrap()); + } } diff --git a/arca-gui/src/tree.rs b/arca-gui/src/tree.rs index 11a2daa..362643a 100644 --- a/arca-gui/src/tree.rs +++ b/arca-gui/src/tree.rs @@ -63,8 +63,15 @@ pub struct Row { pub up: bool, } -fn normalized(e: &Entry) -> String { - e.name.replace('\\', "/") +/// The name with forward slashes, and with one on the end for a folder: 7z +/// and the disk list folders by the bare name, ZIP with the slash, and a +/// folder row is matched against what starts with its path and the slash. +pub(crate) fn normalized(e: &Entry) -> String { + let mut name = e.name.replace('\\', "/"); + if e.is_dir && !name.ends_with('/') { + name.push('/'); + } + name } pub fn children_of(entries: &[Entry], dir: &str) -> Vec { diff --git a/arca-gui/src/ui/browser.rs b/arca-gui/src/ui/browser.rs index 203ed0a..39996ba 100644 --- a/arca-gui/src/ui/browser.rs +++ b/arca-gui/src/ui/browser.rs @@ -382,6 +382,11 @@ impl Shell { .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); ui.add(egui::Label::new(RichText::new(name).color(hex(p.muted))).truncate()); + ui.add_space(16.0); + let escape = ui.input(|i| i.key_pressed(egui::Key::Escape)); + if secondary_button(ui, s.cancel, true).clicked() || escape { + self.stop_opening.set(true); + } }); ui.ctx() .request_repaint_after(std::time::Duration::from_millis(33)); diff --git a/arca-gui/src/ui/mod.rs b/arca-gui/src/ui/mod.rs index 1dabffb..2b1a7df 100644 --- a/arca-gui/src/ui/mod.rs +++ b/arca-gui/src/ui/mod.rs @@ -205,6 +205,9 @@ pub(crate) struct Shell { pane_action: Option, properties: Option, properties_job: Option>, + // Set by the opening screen when somebody gives up waiting for an + // archive to be read; acted on once the frame is drawn. + stop_opening: std::cell::Cell, // Size and kind of each file waiting to be compressed, read once for the // list they were read for rather than on every frame. input_facts: Option<(Vec, InputFacts)>, @@ -323,6 +326,7 @@ impl Shell { pane_action: None, properties: None, properties_job: None, + stop_opening: Default::default(), input_facts: None, last_active_pane: None, keyboard_drove: false, @@ -2156,6 +2160,14 @@ impl eframe::App for Shell { if !only_form { self.workspace(ui); } + if self.stop_opening.take() { + self.controller.cancel_opening(); + } + // A band ends when the button comes up, wherever that happens: the + // blank space that started it may be gone by then, filled by rows. + if self.marquee.is_some() && !ctx.input(|i| i.pointer.primary_down()) { + self.marquee = None; + } // After the lists, so every row has had its say about a drop. self.settle_blank_drop(&ctx); self.drag_shadow(&ctx); diff --git a/arca-rar/src/lib.rs b/arca-rar/src/lib.rs index 9cbba97..8b33f62 100644 --- a/arca-rar/src/lib.rs +++ b/arca-rar/src/lib.rs @@ -50,6 +50,9 @@ pub enum Conflict { pub struct RarArchive { entries: Vec, + // The Unix permissions each member recorded, where it was made on Unix. + #[cfg(feature = "rar")] + modes: Vec>, #[cfg(feature = "rar")] inner: volumes::Volumes, } @@ -95,6 +98,22 @@ impl RarArchive { } } + /// Checks a password against the first encrypted file only, decoding as + /// little of the archive as gets there, instead of all of it as [`test`] + /// does. A wrong password fails here; a right one says nothing about + /// whether the rest of the archive is intact. + /// + /// [`test`]: Self::test + pub fn check_password(&self, password: &str, progress: &Progress<'_>) -> Result<()> { + #[cfg(feature = "rar")] + return reader::check_password(self, password, progress); + #[cfg(not(feature = "rar"))] + { + let _ = (password, progress); + Err(disabled()) + } + } + pub fn read_entry(&self, index: usize, password: Option<&str>) -> Result> { #[cfg(feature = "rar")] return reader::read_entry(self, index, password); diff --git a/arca-rar/src/reader.rs b/arca-rar/src/reader.rs index fbd8675..e4c3e1f 100644 --- a/arca-rar/src/reader.rs +++ b/arca-rar/src/reader.rs @@ -100,6 +100,7 @@ pub(super) fn open( let mut names = HashSet::new(); let mut files = HashSet::new(); let mut total = 0u64; + let mut modes = Vec::new(); for (index, member) in inner.members(token)?.into_iter().enumerate() { let meta = &member.meta; if token.is_cancelled() { @@ -142,6 +143,10 @@ pub(super) fn open( ArchiveMemberDetail::Rar50Plus { crc32, .. } => crc32, _ => None, }; + modes.push( + (meta.attr_source() == rars::AttrSource::Unix) + .then_some((meta.file_attr & 0o7777) as u32), + ); entries.push(Entry { name, size: meta.unpacked_size, @@ -183,7 +188,11 @@ pub(super) fn open( parent = path.parent(); } } - Ok(RarArchive { inner, entries }) + Ok(RarArchive { + inner, + entries, + modes, + }) }) } @@ -246,6 +255,41 @@ pub(super) fn test( }) } +pub(super) fn check_password( + archive: &RarArchive, + password: &str, + progress: &Progress<'_>, +) -> Result<()> { + let Some(first) = archive + .entries + .iter() + .position(|e| e.encrypted && !e.is_dir) + else { + return Ok(()); + }; + // A set of volumes has no way to stop early, so it is tested whole. + let [single] = archive.inner.archives.as_slice() else { + return test(archive, Some(password), progress); + }; + // Everything up to the first encrypted file is decoded, since in a solid + // archive it is what that file is decoded from, and nothing after it. + let mut index = 0; + controlled(progress, |token| { + single + .extract_with_control(options(Some(password), token), |_| { + let decision = if index > first { + rars::ExtractionDecision::Stop + } else { + rars::ExtractionDecision::Extract(Box::new(io::sink())) + }; + index += 1; + Ok(decision) + }) + .map(|_| ()) + .map_err(|e| archive.inner.error(e)) + }) +} + pub(super) fn read_entry( archive: &RarArchive, index: usize, @@ -462,10 +506,25 @@ pub(super) fn extract( .ok_or_else(|| Error::Format("missing destination parent".into()))?; fs::create_dir_all(parent)?; // Publish only verified bytes, with a same-filesystem atomic replacement. + // A temporary is created readable by its owner alone; the file it + // becomes gets what any new file gets, through the umask, plus the + // execute bits the archive recorded. + #[cfg(unix)] + let mut output = { + use std::os::unix::fs::PermissionsExt; + tempfile::Builder::new() + .permissions(fs::Permissions::from_mode(0o666)) + .tempfile_in(parent)? + }; + #[cfg(not(unix))] let mut output = tempfile::NamedTempFile::new_in(parent)?; let mut input = File::open(staging.path().join(i.to_string()))?; bytes += io::copy(&mut input, &mut output)?; arca_core::extraction::set_mtime(output.as_file(), entry.mtime); + arca_core::extraction::set_executable( + output.as_file(), + archive.modes.get(i).copied().flatten(), + ); output.as_file().sync_all()?; reject_links(&target)?; if overwrite { diff --git a/arca-rar/tests/reader.rs b/arca-rar/tests/reader.rs index 423a8d9..ae77e17 100644 --- a/arca-rar/tests/reader.rs +++ b/arca-rar/tests/reader.rs @@ -224,3 +224,45 @@ fn refuses_destination_symlinks_and_preserves_external_files() { assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1); } } + +#[test] +fn a_password_is_checked_on_the_first_encrypted_file_alone() { + for (name, password) in [ + ("encrypted.rar", "arca-test-only"), + ("headers.rar", "arca-test-only"), + ("encrypted_multivol.part1.rar", "password"), + ] { + let a = RarArchive::open(&fixture(name), Some(password)).unwrap(); + a.check_password(password, &|_, _, _| true) + .unwrap_or_else(|e| panic!("{name}: {e}")); + let wrong = RarArchive::open(&fixture(name), Some("wrong")) + .and_then(|b| b.check_password("wrong", &|_, _, _| true)); + assert!(wrong.is_err(), "{name}: a wrong password passed"); + } + let plain = RarArchive::open(&fixture("plain.rar"), None).unwrap(); + plain.check_password("anything", &|_, _, _| true).unwrap(); +} + +// Extracted files get the permissions any new file gets, not those of the +// owner-only temporary they were written through. +#[cfg(unix)] +#[test] +fn extracted_files_get_the_usual_permissions() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let a = RarArchive::open(&fixture("plain.rar"), None).unwrap(); + a.extract(dir.path(), &[], None, &|_, _, _| true, &|_| { + Conflict::Overwrite + }) + .unwrap(); + let fresh = dir.path().join("fresh"); + fs::File::create(&fresh).unwrap(); + let usual = fs::metadata(&fresh).unwrap().permissions().mode() & 0o666; + for entry in a.entries().iter().filter(|e| !e.is_dir) { + let mode = fs::metadata(dir.path().join(&entry.name)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o666, usual, "{}", entry.name); + } +}