|
| 1 | +//! `fs.copy` for plug-ins: the host's verified copy ([`crate::import_move::copy_verified`]), run |
| 2 | +//! as an I/O job of the scheduler ([`crate::io_sched`]) so it queues on its volumes with the app's |
| 3 | +//! own copies, and a volume that stops answering fails it instead of hanging the app. |
| 4 | +//! |
| 5 | +//! The copy runs on a thread of its own; the plug-in's thread waits for it, telling the plug-in's |
| 6 | +//! host (`tick`) how many bytes are done every [`lcc_plugins::COPY_TICK`] and stopping the copy |
| 7 | +//! when `tick` says so (a cancelled job). Without `overwrite` the copy is made at the target |
| 8 | +//! itself (created new, so nothing there is replaced); with it, beside the target and then renamed |
| 9 | +//! over it, so the old file stays whole until the new one is verified. A failed or cancelled copy |
| 10 | +//! leaves nothing behind. |
| 11 | +//! |
| 12 | +//! The paths were checked by the plug-in's permissions, but a link may be swapped in after that: |
| 13 | +//! the source is opened with [`lcc_plugins::open_checked`] (the very regular file at its path, not |
| 14 | +//! reached through a link) and copied and verified from that open file, and the file the copy |
| 15 | +//! creates (the copy itself, or the temp file renamed over the target) must be in the target's |
| 16 | +//! very folder before anything is written to it, and again before the rename. So nothing outside |
| 17 | +//! the plug-in's roots is read, created or replaced, and only a file this copy made is removed. |
| 18 | +
|
| 19 | +use std::path::{Path, PathBuf}; |
| 20 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
| 21 | + |
| 22 | +use lcc_plugins::CopyRequest; |
| 23 | + |
| 24 | +use crate::import_move::{CopyWatch, copy_verified_open, sync_dir}; |
| 25 | + |
| 26 | +/// A temp name beside `to` for an overwriting copy. |
| 27 | +fn temp_beside(to: &Path) -> PathBuf { |
| 28 | + static N: AtomicUsize = AtomicUsize::new(0); |
| 29 | + let name = to.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); |
| 30 | + to.with_file_name(format!(".{name}.{}.{}.copy", std::process::id(), N.fetch_add(1, Ordering::Relaxed))) |
| 31 | +} |
| 32 | + |
| 33 | +/// `PermissionDenied` unless the file at `made` is in `folder` itself (not reached through a link |
| 34 | +/// swapped in for the folder). |
| 35 | +fn in_folder(made: &Path, folder: Option<&Path>) -> std::io::Result<()> { |
| 36 | + if made.canonicalize()?.parent() != folder { |
| 37 | + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the folder changed while copying (a symbolic link?)")); |
| 38 | + } |
| 39 | + Ok(()) |
| 40 | +} |
| 41 | + |
| 42 | +/// The copy itself, on the I/O job's thread. |
| 43 | +fn copy(req: &CopyRequest, expect: Option<lcc_preview::Hash128>, watch: &CopyWatch) -> std::io::Result<u64> { |
| 44 | + let (src, _) = lcc_plugins::open_checked(&req.from)?; |
| 45 | + let folder = req.to.parent(); |
| 46 | + let check = |made: &Path| in_folder(made, folder); |
| 47 | + let n = if !req.overwrite { |
| 48 | + copy_verified_open(&src, &req.to, &check, expect, Some(watch))? |
| 49 | + } else { |
| 50 | + let tmp = temp_beside(&req.to); |
| 51 | + let n = copy_verified_open(&src, &tmp, &check, expect, Some(watch))?; |
| 52 | + // the folder may have been swapped since the temp file was made: never rename over a file |
| 53 | + // elsewhere |
| 54 | + if let Err(e) = check(&tmp).and_then(|()| std::fs::rename(&tmp, &req.to)) { |
| 55 | + let _ = std::fs::remove_file(&tmp); |
| 56 | + return Err(e); |
| 57 | + } |
| 58 | + n |
| 59 | + }; |
| 60 | + if let Some(dir) = folder { |
| 61 | + sync_dir(dir)?; |
| 62 | + } |
| 63 | + Ok(n) |
| 64 | +} |
| 65 | + |
| 66 | +/// `fs.copy`: see the module docs. → the bytes copied. |
| 67 | +pub(crate) fn copy_file(req: &CopyRequest, tick: &mut dyn FnMut(u64) -> bool) -> Result<u64, String> { |
| 68 | + let expect = match &req.expect_hash { |
| 69 | + None => None, |
| 70 | + Some(h) => Some(lcc_preview::Hash128::parse(h).ok_or("`expectHash` is not a content hash")?), |
| 71 | + }; |
| 72 | + let watch = CopyWatch::default(); |
| 73 | + let (tx, rx) = std::sync::mpsc::channel(); |
| 74 | + let job_req = req.clone(); |
| 75 | + let job_watch = watch.clone(); |
| 76 | + let source = req.from.to_string_lossy().into_owned(); |
| 77 | + let dest = req.to.parent().map(|d| d.to_string_lossy().into_owned()); |
| 78 | + let cancel = watch.cancel.clone(); |
| 79 | + let worker = std::thread::Builder::new() |
| 80 | + .name("plugin-fs-copy".into()) |
| 81 | + .spawn(move || { |
| 82 | + let run: Box<dyn FnOnce() -> std::io::Result<u64> + Send> = Box::new(move || copy(&job_req, expect, &job_watch)); |
| 83 | + let job = crate::io_sched::IoJob { source, dest, skippable: false, run }; |
| 84 | + let done = AtomicUsize::new(0); |
| 85 | + let r = crate::io_sched::run_jobs(crate::io_sched::IoContext::global(), vec![job], 1, Result::is_ok, &cancel, &done); |
| 86 | + let _ = tx.send(r.map(|mut r| r.outcomes.pop())); |
| 87 | + }) |
| 88 | + .map_err(|e| format!("can't start the copy: {e}"))?; |
| 89 | + let outcome = loop { |
| 90 | + match rx.recv_timeout(lcc_plugins::COPY_TICK) { |
| 91 | + Ok(r) => break r, |
| 92 | + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { |
| 93 | + if !tick(watch.bytes.load(Ordering::Relaxed)) { |
| 94 | + watch.cancel.store(true, Ordering::Relaxed); |
| 95 | + } |
| 96 | + } |
| 97 | + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break Ok(None), |
| 98 | + } |
| 99 | + }; |
| 100 | + let _ = worker.join(); |
| 101 | + let cancelled = watch.cancel.load(Ordering::Relaxed); |
| 102 | + use crate::io_sched::JobOutcome; |
| 103 | + match outcome { |
| 104 | + Ok(Some(JobOutcome::Done(Ok(n)))) => { |
| 105 | + tick(n); |
| 106 | + Ok(n) |
| 107 | + } |
| 108 | + _ if cancelled => Err("cancelled".into()), |
| 109 | + Ok(Some(JobOutcome::Done(Err(e)))) => Err(e.to_string()), |
| 110 | + Ok(Some(JobOutcome::VolumeNotResponding { volume, .. })) => Err(format!("the drive {volume} is not responding")), |
| 111 | + Ok(Some(JobOutcome::Panicked(m))) => Err(format!("the copy stopped on an internal error ({m})")), |
| 112 | + Ok(Some(o)) => Err(format!("the copy didn't run ({o:?})")), |
| 113 | + Ok(None) => Err("the copy stopped on an internal error".into()), |
| 114 | + Err(e) => Err(e.to_string()), |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +#[cfg(test)] |
| 119 | +mod tests { |
| 120 | + use super::*; |
| 121 | + use crate::import_move::copy_verified_watched; |
| 122 | + |
| 123 | + fn dir(tag: &str) -> PathBuf { |
| 124 | + let d = std::env::temp_dir().join(format!("lcc-plugin-fs-{tag}-{}", std::process::id())); |
| 125 | + let _ = std::fs::remove_dir_all(&d); |
| 126 | + std::fs::create_dir_all(&d).unwrap(); |
| 127 | + // as a permission check resolves it |
| 128 | + d.canonicalize().unwrap() |
| 129 | + } |
| 130 | + |
| 131 | + #[test] |
| 132 | + fn copies_verified_and_never_overwrites_unasked() { |
| 133 | + let d = dir("copy"); |
| 134 | + let (a, b) = (d.join("a.bin"), d.join("b.bin")); |
| 135 | + let data: Vec<u8> = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); |
| 136 | + std::fs::write(&a, &data).unwrap(); |
| 137 | + let req = |overwrite, expect_hash: Option<String>| CopyRequest { from: a.clone(), to: b.clone(), expect_hash, overwrite }; |
| 138 | + let mut ticks = Vec::new(); |
| 139 | + assert_eq!( |
| 140 | + copy_file(&req(false, None), &mut |n| { |
| 141 | + ticks.push(n); |
| 142 | + true |
| 143 | + }) |
| 144 | + .unwrap(), |
| 145 | + data.len() as u64 |
| 146 | + ); |
| 147 | + assert_eq!(std::fs::read(&b).unwrap(), data); |
| 148 | + assert_eq!(ticks.last(), Some(&(data.len() as u64)), "the end is reported"); |
| 149 | + // taken: refused, the file untouched |
| 150 | + assert!(copy_file(&req(false, None), &mut |_| true).is_err()); |
| 151 | + // with the right hash, over it; with a wrong one, refused and the old copy kept |
| 152 | + let good = lcc_preview::hash_bytes(&data).to_string(); |
| 153 | + std::fs::write(&b, b"old").unwrap(); |
| 154 | + copy_file(&req(true, Some(good)), &mut |_| true).unwrap(); |
| 155 | + assert_eq!(std::fs::read(&b).unwrap(), data); |
| 156 | + std::fs::write(&b, b"old").unwrap(); |
| 157 | + assert!(copy_file(&req(true, Some("0".repeat(32))), &mut |_| true).is_err()); |
| 158 | + assert_eq!(std::fs::read(&b).unwrap(), b"old"); |
| 159 | + assert!(copy_file(&req(true, Some("not a hash".into())), &mut |_| true).is_err()); |
| 160 | + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 2, "no temp file left"); |
| 161 | + let _ = std::fs::remove_dir_all(&d); |
| 162 | + } |
| 163 | + |
| 164 | + #[test] |
| 165 | + fn a_cancelled_copy_leaves_nothing() { |
| 166 | + let d = dir("cancel"); |
| 167 | + let (a, b) = (d.join("a.bin"), d.join("b.bin")); |
| 168 | + std::fs::write(&a, vec![7u8; 1 << 20]).unwrap(); |
| 169 | + // cancelled before it starts: nothing runs |
| 170 | + let watch = CopyWatch::default(); |
| 171 | + watch.cancel.store(true, Ordering::Relaxed); |
| 172 | + assert!(copy_verified_watched(&a, &b, None, Some(&watch)).is_err()); |
| 173 | + assert!(!b.exists()); |
| 174 | + let missing = CopyRequest { from: d.join("missing"), to: b.clone(), expect_hash: None, overwrite: false }; |
| 175 | + assert!(copy_file(&missing, &mut |_| true).is_err()); |
| 176 | + assert!(!b.exists()); |
| 177 | + let _ = std::fs::remove_dir_all(&d); |
| 178 | + } |
| 179 | + |
| 180 | + /// A link swapped in after the permission check, for the source or for the target's folder: |
| 181 | + /// nothing outside the root is read, created or replaced. |
| 182 | + #[cfg(unix)] |
| 183 | + #[test] |
| 184 | + fn links_swapped_in_after_the_check_are_refused() { |
| 185 | + let d = dir("links"); |
| 186 | + let (root, outside) = (d.join("root"), d.join("outside")); |
| 187 | + std::fs::create_dir_all(&root).unwrap(); |
| 188 | + std::fs::create_dir_all(&outside).unwrap(); |
| 189 | + let secret = outside.join("id_rsa"); |
| 190 | + std::fs::write(&secret, b"secret key").unwrap(); |
| 191 | + // the source checked as a file, then swapped for a link to a file outside the root |
| 192 | + let from = root.join("a.bin"); |
| 193 | + std::os::unix::fs::symlink(&secret, &from).unwrap(); |
| 194 | + for overwrite in [false, true] { |
| 195 | + let req = CopyRequest { from: from.clone(), to: root.join("b.bin"), expect_hash: None, overwrite }; |
| 196 | + assert!(copy_file(&req, &mut |_| true).is_err(), "a source reached through a link is refused"); |
| 197 | + assert!(!root.join("b.bin").exists(), "nothing copied out of the root"); |
| 198 | + } |
| 199 | + std::fs::remove_file(&from).unwrap(); |
| 200 | + std::fs::write(&from, b"photo").unwrap(); |
| 201 | + // the target's folder checked, then swapped for a link to a folder outside the root |
| 202 | + let sub = root.join("sub"); |
| 203 | + std::os::unix::fs::symlink(&outside, &sub).unwrap(); |
| 204 | + let precious = outside.join("b.bin"); |
| 205 | + let req = CopyRequest { from: from.clone(), to: sub.join("b.bin"), expect_hash: None, overwrite: false }; |
| 206 | + assert!(copy_file(&req, &mut |_| true).is_err()); |
| 207 | + assert!(!precious.exists(), "no file made outside the root"); |
| 208 | + std::fs::write(&precious, b"precious").unwrap(); |
| 209 | + let req = CopyRequest { overwrite: true, ..req }; |
| 210 | + assert!(copy_file(&req, &mut |_| true).is_err()); |
| 211 | + assert_eq!(std::fs::read(&precious).unwrap(), b"precious", "a file outside the root is never replaced"); |
| 212 | + assert_eq!( |
| 213 | + std::fs::read_dir(&outside).unwrap().count(), |
| 214 | + 2, |
| 215 | + "no temp file left outside: {:?}", |
| 216 | + std::fs::read_dir(&outside).unwrap().collect::<Vec<_>>() |
| 217 | + ); |
| 218 | + let _ = std::fs::remove_dir_all(&d); |
| 219 | + } |
| 220 | +} |
0 commit comments