From 4c44beba35e038c30ca2085c6de73e2f8293a686 Mon Sep 17 00:00:00 2001 From: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> Date: Sat, 5 Dec 2026 17:00:34 +0530 Subject: [PATCH] fix(vfs): save existing files in place so their links, ACLs, xattrs and read-only bit survive (#8199) Saving wrote a temp file next to the file and renamed it over the original, so the saved file was a different file: another hard link kept the old text, and extended attributes (Finder tags, the quarantine flag), ACL entries, the group and the creation date were lost; a file made read-only with chmod 444 was overwritten, and a writable file whose ACL denies deleting could not be saved. An existing user file is now written in place (ide_vfs::save_file): a copy is made next to it first, written back if the write fails and removed after it succeeds; a read-only file is refused with a permission error. In a folder that allows no new file, the editor save writes in place without the copy while the notebook save (save_file_strict) refuses. New files and the IDE's own files are still written to a temp file and renamed. Editor, .properties, plugin and notebook saves use it. Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com> --- crates/ide-host/src/plugins/api.rs | 2 +- crates/ide-notebook/src/document.rs | 2 +- crates/ide-notebook/tests/document.rs | 14 ++ crates/ide-vfs/src/encoding.rs | 201 ++++++++++++++++++++++---- crates/ide-vfs/src/lib.rs | 11 +- crates/ide-vfs/tests/save_in_place.rs | 101 +++++++++++++ 6 files changed, 297 insertions(+), 34 deletions(-) create mode 100644 crates/ide-vfs/tests/save_in_place.rs diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index e12a7ca400..f9fd2368ca 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -4242,7 +4242,7 @@ impl HostApi for PluginApi { if private { ide_vfs::write_atomic_private(real, bytes).map(drop).map_err(|e| not_writable(real, e)) } else { - ide_vfs::write_atomic(real, bytes).map(drop).map_err(|e| not_writable(real, e)) + ide_vfs::save_file(real, bytes).map(drop).map_err(|e| not_writable(real, e)) } } } diff --git a/crates/ide-notebook/src/document.rs b/crates/ide-notebook/src/document.rs index c87bcdac29..b8b8446ee7 100644 --- a/crates/ide-notebook/src/document.rs +++ b/crates/ide-notebook/src/document.rs @@ -259,7 +259,7 @@ impl NotebookDocument { } if self.is_dirty() { let text = self.to_text(); - ide_vfs::write_atomic_strict(&self.path, text.as_bytes())?; + ide_vfs::save_file_strict(&self.path, text.as_bytes())?; self.baseline_text = text.into(); self.baseline = self.root.clone(); } diff --git a/crates/ide-notebook/tests/document.rs b/crates/ide-notebook/tests/document.rs index e044770c6a..9f14a49742 100644 --- a/crates/ide-notebook/tests/document.rs +++ b/crates/ide-notebook/tests/document.rs @@ -357,6 +357,20 @@ fn streams_merge_only_adjacent_same_names_and_errors_and_mime_data_are_retained( assert_eq!(state.cells[0].outputs[4]["data"]["application/vnd.vendor+json"]["x"], 1); } +#[test] +fn saving_writes_the_notebook_file_in_place() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("document.ipynb"); + let twin = dir.path().join("twin.ipynb"); + std::fs::write(&path, ORIGINAL).unwrap(); + std::fs::hard_link(&path, &twin).unwrap(); + let mut doc = NotebookDocument::load(&path).unwrap(); + apply(&mut doc, NotebookEdit::SetSource { cell: "second".into(), source: "saved".into() }); + doc.save().unwrap(); + let twin = std::fs::read_to_string(&twin).unwrap(); + assert!(twin == doc.to_text(), "the other link still reads the notebook from before the save"); +} + #[test] fn save_undo_and_reload_track_the_exact_disk_baseline_and_document_incarnation() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-vfs/src/encoding.rs b/crates/ide-vfs/src/encoding.rs index ec3c66f301..539b2e70f5 100644 --- a/crates/ide-vfs/src/encoding.rs +++ b/crates/ide-vfs/src/encoding.rs @@ -4,7 +4,7 @@ use crate::{LoadedText, mtime_ms}; use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE}; use ide_core::{IdeError, IdeResult}; use std::fs; -use std::io::Write; +use std::io::{Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU32, Ordering}; @@ -98,7 +98,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult { { return Ok(mtime_ms(&fs::metadata(path)?)); } - write_atomic(path, encode_properties_ascii(text).as_bytes()) + save_file(path, encode_properties_ascii(text).as_bytes()) } /// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text. @@ -483,17 +483,7 @@ fn write_atomic_impl(path: &Path, bytes: &[u8], allow_in_place: bool, private: b file.set_permissions(fs::Permissions::from_mode(0o600))?; } file.write_all(bytes)?; - if let Err(e) = file.sync_all() { - // virtio-fs (macOS VMs) and similar filesystems have no fsync/F_FULLFSYNC - // (ENOTTY, EINVAL): the write itself already went through, so the rename is - // still the best durability the filesystem offers — degrade like SQLite - // instead of failing the whole atomic write. - if sync_error_is_tolerable(&e) { - tracing::debug!("fsync unsupported for {}: {e}; continuing", target.display()); - } else { - return Err(e); - } - } + sync(&file, &target)?; if let Some(meta) = &existing { #[allow(unused_mut)] let mut permissions = meta.permissions(); @@ -514,6 +504,116 @@ fn write_atomic_impl(path: &Path, bytes: &[u8], allow_in_place: bool, private: b Ok(mtime_ms(&fs::metadata(&target)?)) } +/// `file.sync_all()`, except that virtio-fs (macOS VMs) and similar filesystems have no +/// fsync/F_FULLFSYNC (ENOTTY, EINVAL): the write itself already went through, so it is the best +/// durability the filesystem offers. Degrade like SQLite instead of failing the write. +fn sync(file: &fs::File, path: &Path) -> std::io::Result<()> { + match file.sync_all() { + Err(e) if sync_error_is_tolerable(&e) => { + tracing::debug!("fsync unsupported for {}: {e}; continuing", path.display()); + Ok(()) + } + result => result, + } +} + +/// Saves a user's file. An existing one is written in place, as IDEA's `SafeFileOutputStream` +/// does, so it keeps what belongs to the file rather than to its contents: other hard links, +/// extended attributes, ACLs, owner, group and creation date; a read-only one is refused. A copy +/// made next to it first is written back if the write fails and removed after it succeeds. A +/// crash during the write can leave that copy, `..openidea-tmp-…`, beside a partly written +/// file. A new file is written atomically. Returns the new mtime in ms. +pub fn save_file(path: &Path, bytes: &[u8]) -> IdeResult { + save_file_impl(path, bytes, false) +} + +/// [`save_file`] that never writes an existing file without that copy: in a folder that allows +/// no new file, it fails and leaves the file as it was. +pub fn save_file_strict(path: &Path, bytes: &[u8]) -> IdeResult { + save_file_impl(path, bytes, true) +} + +fn save_file_impl(path: &Path, bytes: &[u8], strict: bool) -> IdeResult { + let target = match fs::symlink_metadata(path) { + Ok(m) if m.file_type().is_symlink() => fs::canonicalize(path)?, + _ => path.to_path_buf(), + }; + let Some(meta) = fs::metadata(&target).ok().filter(fs::Metadata::is_file) else { + return write_atomic_impl(path, bytes, !strict, false); + }; + if meta.permissions().readonly() { + let message = format!("{} is read-only", target.display()); + return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, message)); + } + let mut opened = None; + retrying(RENAME_ATTEMPTS, RENAME_PAUSE, held_by_another_process, || { + opened = Some(fs::OpenOptions::new().write(true).open(&target)?); + Ok(()) + })?; + let mut file = opened.expect("opened"); + let backup = match backup_copy(&target) { + Ok(backup) => Some(backup), + Err(e) if !strict && e.kind() == std::io::ErrorKind::PermissionDenied => { + tracing::debug!("cannot copy {} before saving it: {e}; writing in place", target.display()); + None + } + Err(e) => return Err(e.into()), + }; + let written = (|| -> std::io::Result<()> { + file.set_len(0)?; + file.write_all(bytes)?; + sync(&file, &target) + })(); + match (written, backup) { + (Ok(()), Some(backup)) => { + if let Err(e) = fs::remove_file(&backup) { + tracing::warn!("cannot remove {}: {e}", backup.display()); + } + } + (Ok(()), None) => {} + (Err(e), Some(backup)) => return Err(restore(&mut file, &target, &backup, e)), + (Err(e), None) => return Err(e.into()), + } + drop(file); + Ok(mtime_ms(&fs::metadata(&target)?)) +} + +/// A copy of `target` next to it, on disk before `target` is written. +fn backup_copy(target: &Path) -> std::io::Result { + let backup = temp_path_for(target); + let copied = + fs::copy(target, &backup).and_then(|_| sync(&fs::OpenOptions::new().write(true).open(&backup)?, &backup)); + match copied { + Ok(()) => Ok(backup), + Err(e) => { + let _ = fs::remove_file(&backup); + Err(e) + } + } +} + +/// Writing `target` failed with `error`: its content goes back from `backup`. When that fails too, +/// the backup stays and the error names it. +fn restore(file: &mut fs::File, target: &Path, backup: &Path, error: std::io::Error) -> IdeError { + let restored = (|| -> std::io::Result<()> { + file.set_len(0)?; + file.seek(std::io::SeekFrom::Start(0))?; + std::io::copy(&mut fs::File::open(backup)?, file)?; + sync(file, target) + })(); + let mut error = IdeError::from(error); + match restored { + Ok(()) => { + let _ = fs::remove_file(backup); + } + Err(e) => { + tracing::warn!("cannot restore {} from {}: {e}", target.display(), backup.display()); + error.message = format!("{}; its previous content is in {}", error.message, backup.display()); + } + } + error +} + #[cfg(test)] mod tests { use super::*; @@ -638,20 +738,24 @@ mod tests { use std::os::windows::fs::OpenOptionsExt; use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE}; // No sharing at all (os error 32), and readers that don't allow deletion (os error 5). - for share in [0, FILE_SHARE_READ | FILE_SHARE_WRITE] { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - fs::write(&path, b"old").unwrap(); - let held = fs::OpenOptions::new().read(true).share_mode(share).open(&path).unwrap(); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(300)); - drop(held); - }); - let result = write_atomic(&path, b"new"); - release.join().unwrap(); - result.unwrap(); - assert_eq!(fs::read(&path).unwrap(), b"new", "share mode {share}"); - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1, "no temp file left behind"); + type Write = fn(&Path, &[u8]) -> IdeResult; + let writers: [Write; 2] = [write_atomic, save_file]; + for write in writers { + for share in [0, FILE_SHARE_READ | FILE_SHARE_WRITE] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + fs::write(&path, b"old").unwrap(); + let held = fs::OpenOptions::new().read(true).share_mode(share).open(&path).unwrap(); + let release = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(300)); + drop(held); + }); + let result = write(&path, b"new"); + release.join().unwrap(); + result.unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"new", "share mode {share}"); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1, "no temp file left behind"); + } } } @@ -680,6 +784,49 @@ mod tests { assert_eq!(fs::read(&path).unwrap(), b"original notebook"); } + /// In a folder that allows no new file there is no room for the copy: only the strict save + /// refuses to write without it. + #[cfg(unix)] + #[test] + fn a_save_in_a_read_only_folder_needs_no_copy_unless_strict() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("notebook.ipynb"); + fs::write(&path, b"original").unwrap(); + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap(); + // Privileged test runners can bypass directory permissions. + if fs::File::create(dir.path().join("probe")).is_ok() { + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap(); + return; + } + let strict = save_file_strict(&path, b"strict"); + let lenient = save_file(&path, b"in place"); + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap(); + + assert_eq!(strict.unwrap_err().kind, ide_core::error::ErrorKind::PermissionDenied); + lenient.unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"in place"); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1, "no copy left behind"); + } + + #[test] + fn a_failed_write_puts_the_copy_back() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.txt"); + fs::write(&path, b"partly written").unwrap(); + let backup = dir.path().join("backup"); + fs::write(&backup, b"before the save").unwrap(); + let mut file = fs::OpenOptions::new().write(true).open(&path).unwrap(); + + let error = restore(&mut file, &path, &backup, std::io::Error::from(std::io::ErrorKind::StorageFull)); + drop(file); + + assert_eq!(fs::read(&path).unwrap(), b"before the save"); + assert!(!backup.exists()); + assert_eq!(error.kind, IdeError::from(std::io::Error::from(std::io::ErrorKind::StorageFull)).kind); + } + #[test] fn decode_variants() { let (t, e, bom, bin) = decode(b"\xEF\xBB\xBFhi"); diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index 2144ef624e..c8f9d01d13 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -35,7 +35,8 @@ pub use decode_stream::{DecodedReader, decode_stream}; use encoding::SNIFF_LEN; pub use encoding::{ Fallback, LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode, - encode_properties_ascii, save_properties_text, write_atomic, write_atomic_private, write_atomic_strict, + encode_properties_ascii, save_file, save_file_strict, save_properties_text, write_atomic, write_atomic_private, + write_atomic_strict, }; pub use private::create_private_dir; pub use rules::ExcludeMatcher; @@ -287,12 +288,12 @@ pub fn load_text_as(path: &Path, encoding: &str) -> IdeResult { encoding::load_text_as(path, encoding) } -/// Writes atomically (temp file + rename), re-encoding to `encoding`. -/// Returns the new mtime in ms. Fails with `InvalidInput` when the text has -/// characters `encoding` cannot represent (rather than corrupting them). +/// [`save_file`] of `text` encoded in `encoding`. Returns the new mtime in ms. Fails with +/// `InvalidInput` when the text has characters `encoding` cannot represent (rather than +/// corrupting them). pub fn save_text(path: &Path, text: &str, encoding: &str, has_bom: bool) -> IdeResult { let bytes = encode(text, encoding, has_bom)?; - write_atomic(path, &bytes) + save_file(path, &bytes) } /// Creates an empty file (and missing parent directories). Fails with diff --git a/crates/ide-vfs/tests/save_in_place.rs b/crates/ide-vfs/tests/save_in_place.rs new file mode 100644 index 0000000000..f097475764 --- /dev/null +++ b/crates/ide-vfs/tests/save_in_place.rs @@ -0,0 +1,101 @@ +//! Saving an existing file writes it in place, so what belongs to the file rather than to its +//! contents survives: other hard links, extended attributes, ACLs, group, and a read-only bit. +use ide_core::error::ErrorKind; +use ide_vfs::{save_properties_text, save_text}; +use std::fs; +use std::path::Path; + +fn save(path: &Path, text: &str) { + save_text(path, text, "utf-8", false).unwrap(); + assert_eq!(fs::read_to_string(path).unwrap(), text); +} + +/// The save leaves nothing next to the file (the backup copy is gone). +fn assert_only(dir: &Path, names: &[&str]) { + let mut found: Vec = + fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + found.sort(); + assert_eq!(found, names); +} + +#[test] +fn a_hard_link_sees_the_saved_text() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.txt"); + let twin = dir.path().join("b.txt"); + fs::write(&path, "old\n").unwrap(); + fs::hard_link(&path, &twin).unwrap(); + save(&path, "new\n"); + assert_eq!(fs::read_to_string(&twin).unwrap(), "new\n"); + // `.properties` files with native-to-ascii have a save of their own. + save_properties_text(&path, "key=\u{fc}ber\n").unwrap(); + assert_eq!(fs::read_to_string(&twin).unwrap(), "key=\\u00FCber\n"); + assert_only(dir.path(), &["a.txt", "b.txt"]); +} + +#[test] +fn a_read_only_file_is_not_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("locked.txt"); + fs::write(&path, "protected\n").unwrap(); + ide_vfs::set_writable(&path, false).unwrap(); + let error = save_text(&path, "overwritten\n", "utf-8", false).unwrap_err(); + assert_eq!(fs::read_to_string(&path).unwrap(), "protected\n"); + ide_vfs::set_writable(&path, true).unwrap(); + assert_eq!(error.kind, ErrorKind::PermissionDenied); + assert_only(dir.path(), &["locked.txt"]); +} + +#[cfg(unix)] +#[test] +fn the_file_keeps_its_inode_group_and_extended_attributes() { + use std::os::unix::fs::MetadataExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("tagged.txt"); + fs::write(&path, "old\n").unwrap(); + // Another of the user's groups than the one a new file in this folder gets, when there is one. + let folder_group = fs::metadata(&path).unwrap().gid(); + let other = rustix::process::getgroups().unwrap().into_iter().map(|g| g.as_raw()).find(|g| *g != folder_group); + if let Some(gid) = other { + std::os::unix::fs::chown(&path, None, Some(gid)).unwrap(); + } + // Some filesystems have no user attributes. + let tagged = rustix::fs::setxattr(&path, "user.openidea-test", b"keep", rustix::fs::XattrFlags::empty()).is_ok(); + let before = fs::metadata(&path).unwrap(); + save(&path, "new\n"); + let after = fs::metadata(&path).unwrap(); + assert_eq!((after.ino(), after.gid()), (before.ino(), before.gid())); + if tagged { + let mut value = [0u8; 8]; + let len = rustix::fs::getxattr(&path, "user.openidea-test", &mut value[..]).unwrap(); + assert_eq!(&value[..len], b"keep"); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn acl_entries_stay_and_one_that_denies_deleting_does_not_stop_a_save() { + use std::process::Command; + let chmod = |args: &[&str], path: &Path| { + assert!(Command::new("/bin/chmod").args(args).arg(path).status().unwrap().success()); + }; + let acl = |path: &Path| { + let out = Command::new("/bin/ls").arg("-le").arg(path).output().unwrap(); + String::from_utf8(out.stdout).unwrap().lines().skip(1).collect::>().join("\n") + }; + let dir = tempfile::tempdir().unwrap(); + let shared = dir.path().join("shared.txt"); + fs::write(&shared, "old\n").unwrap(); + chmod(&["+a", "group:everyone allow write"], &shared); + let entries = acl(&shared); + save(&shared, "new\n"); + assert_eq!(acl(&shared), entries); + + let kept = dir.path().join("kept.txt"); + fs::write(&kept, "old\n").unwrap(); + chmod(&["+a", "everyone deny delete"], &kept); + let saved = save_text(&kept, "new\n", "utf-8", false); + chmod(&["-N"], &kept); + saved.unwrap(); + assert_eq!(fs::read_to_string(&kept).unwrap(), "new\n"); +}