Skip to main content

purple_ssh/
fs_util.rs

1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5use log::{debug, error};
6
7/// Advisory file lock using a `.lock` file.
8/// The lock is released when the `FileLock` is dropped.
9pub struct FileLock {
10    lock_path: PathBuf,
11    #[cfg(unix)]
12    _file: fs::File,
13}
14
15impl FileLock {
16    /// Acquire an advisory lock for the given path.
17    /// Creates a `.purple_lock` file alongside the target and holds an `flock` on it.
18    /// Blocks until the lock is acquired (or returns an error on failure).
19    pub fn acquire(path: &Path) -> io::Result<Self> {
20        let mut lock_name = path.file_name().unwrap_or_default().to_os_string();
21        lock_name.push(".purple_lock");
22        let lock_path = path.with_file_name(lock_name);
23
24        #[cfg(unix)]
25        {
26            use std::os::unix::fs::OpenOptionsExt;
27            let file = fs::OpenOptions::new()
28                .write(true)
29                .create(true)
30                .truncate(false)
31                .mode(0o600)
32                .open(&lock_path)?;
33
34            // SAFETY: flock() is safe to call on any valid file descriptor.
35            // The fd comes from a File we just opened and own. LOCK_EX
36            // requests an exclusive advisory lock, blocking until acquired.
37            let ret =
38                unsafe { libc::flock(std::os::unix::io::AsRawFd::as_raw_fd(&file), libc::LOCK_EX) };
39            if ret != 0 {
40                return Err(io::Error::last_os_error());
41            }
42
43            Ok(FileLock {
44                lock_path,
45                _file: file,
46            })
47        }
48
49        #[cfg(not(unix))]
50        {
51            // On non-Unix, use a simple lock file (best-effort)
52            let file = fs::OpenOptions::new()
53                .write(true)
54                .create_new(true)
55                .open(&lock_path)
56                .or_else(|_| {
57                    // If it already exists, wait briefly and retry
58                    std::thread::sleep(std::time::Duration::from_millis(100));
59                    fs::remove_file(&lock_path).ok();
60                    fs::OpenOptions::new()
61                        .write(true)
62                        .create_new(true)
63                        .open(&lock_path)
64                })?;
65            Ok(FileLock {
66                lock_path,
67                _file: file,
68            })
69        }
70    }
71}
72
73impl Drop for FileLock {
74    fn drop(&mut self) {
75        // On Unix, flock is released when the file descriptor is closed (automatic).
76        // The lockfile itself is intentionally left on disk: unlinking it here
77        // creates a race where a second process opens a fresh inode at the
78        // same path and obtains an independent flock, so both processes
79        // think they hold the lock. Leaving the file (1 byte at chmod 600)
80        // matches the standard advisory-lock pattern.
81        // The `lock_path` field is kept for diagnostics (Debug, logging).
82        let _ = &self.lock_path;
83    }
84}
85
86/// Atomic write: write content to a PID-suffixed temp file with chmod 600, then rename.
87/// Uses O_EXCL (create_new) to prevent symlink attacks on the temp file path.
88/// Cleans up the temp file on failure.
89pub fn atomic_write(path: &Path, content: &[u8]) -> io::Result<()> {
90    debug!("Atomic write: {}", path.display());
91    // Ensure parent directory exists
92    if let Some(parent) = path.parent() {
93        fs::create_dir_all(parent)?;
94    }
95
96    let mut tmp_name = path.file_name().unwrap_or_default().to_os_string();
97    tmp_name.push(format!(".purple_tmp.{}", std::process::id()));
98    let tmp_path = path.with_file_name(tmp_name);
99
100    #[cfg(unix)]
101    {
102        use std::io::Write;
103        use std::os::unix::fs::OpenOptionsExt;
104        // Try O_EXCL first. If a stale tmp file exists from a crashed run, remove
105        // it and retry once. This avoids a TOCTOU gap from removing before creating.
106        let open = || {
107            fs::OpenOptions::new()
108                .write(true)
109                .create_new(true)
110                .mode(0o600)
111                .open(&tmp_path)
112        };
113        let mut file = match open() {
114            Ok(f) => f,
115            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
116                let _ = fs::remove_file(&tmp_path);
117                open().map_err(|e| {
118                    io::Error::new(
119                        e.kind(),
120                        format!("Failed to create temp file {}: {}", tmp_path.display(), e),
121                    )
122                })?
123            }
124            Err(e) => {
125                return Err(io::Error::new(
126                    e.kind(),
127                    format!("Failed to create temp file {}: {}", tmp_path.display(), e),
128                ));
129            }
130        };
131        if let Err(e) = file.write_all(content) {
132            drop(file);
133            let _ = fs::remove_file(&tmp_path);
134            return Err(e);
135        }
136        if let Err(e) = file.sync_all() {
137            drop(file);
138            let _ = fs::remove_file(&tmp_path);
139            return Err(e);
140        }
141    }
142
143    #[cfg(not(unix))]
144    {
145        if let Err(e) = fs::write(&tmp_path, content) {
146            let _ = fs::remove_file(&tmp_path);
147            return Err(e);
148        }
149        // sync_all via reopen since fs::write doesn't return a File handle
150        match fs::File::open(&tmp_path) {
151            Ok(f) => {
152                if let Err(e) = f.sync_all() {
153                    let _ = fs::remove_file(&tmp_path);
154                    return Err(e);
155                }
156            }
157            Err(e) => {
158                let _ = fs::remove_file(&tmp_path);
159                return Err(e);
160            }
161        }
162    }
163
164    let result = fs::rename(&tmp_path, path);
165    if let Err(ref err) = result {
166        let _ = fs::remove_file(&tmp_path);
167        error!("[purple] Atomic write failed: {}: {err}", path.display());
168        return result;
169    }
170
171    // Durable rename: the temp file's data was synced before rename, but the
172    // directory entry change produced by `rename` lives in the page cache
173    // until the parent directory itself is synced. Without this, a crash
174    // within seconds of save can leave the directory pointing at the old
175    // inode (= silently dropped edit). Best-effort: log but don't fail the
176    // write if the parent sync itself fails — the rename already succeeded.
177    #[cfg(unix)]
178    if let Some(parent) = path.parent() {
179        if let Err(err) = fs::File::open(parent).and_then(|d| d.sync_all()) {
180            debug!(
181                "[purple] parent dir sync after rename failed (rename succeeded): {}: {err}",
182                parent.display()
183            );
184        }
185    }
186
187    result
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn file_lock_does_not_remove_lockfile_on_drop() {
196        // Regression for the lockfile-unlink race: a second process can open
197        // a new inode at the same path between fd-close and remove_file,
198        // and then both processes hold flock on independent inodes.
199        // Leaving the lockfile in place after drop prevents this entirely.
200        let dir = tempfile::tempdir().expect("tempdir");
201        let target = dir.path().join("config");
202        let lockfile = dir.path().join("config.purple_lock");
203
204        {
205            let _lock = FileLock::acquire(&target).expect("acquire");
206            assert!(lockfile.exists(), "lockfile must be created on acquire");
207        }
208        assert!(
209            lockfile.exists(),
210            "lockfile must remain after drop (not unlinked)"
211        );
212    }
213
214    #[test]
215    fn atomic_write_creates_file_with_content() {
216        let dir = tempfile::tempdir().expect("tempdir");
217        let target = dir.path().join("file");
218        atomic_write(&target, b"hello\n").expect("write");
219        let content = std::fs::read_to_string(&target).expect("read");
220        assert_eq!(content, "hello\n");
221    }
222
223    #[test]
224    fn atomic_write_replaces_existing_file() {
225        let dir = tempfile::tempdir().expect("tempdir");
226        let target = dir.path().join("file");
227        std::fs::write(&target, b"old").expect("write old");
228        atomic_write(&target, b"new").expect("write new");
229        let content = std::fs::read_to_string(&target).expect("read");
230        assert_eq!(content, "new");
231    }
232
233    #[test]
234    fn atomic_write_leaves_no_temp_file() {
235        let dir = tempfile::tempdir().expect("tempdir");
236        let target = dir.path().join("file");
237        atomic_write(&target, b"content").expect("write");
238        let stem = target.file_name().unwrap().to_string_lossy().to_string();
239        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
240            .unwrap()
241            .filter_map(|e| e.ok())
242            .filter(|e| {
243                let n = e.file_name().to_string_lossy().to_string();
244                n.starts_with(&format!("{}.purple_tmp.", stem))
245            })
246            .collect();
247        assert!(
248            leftovers.is_empty(),
249            "temp file leaked after successful write: {:?}",
250            leftovers.iter().map(|e| e.path()).collect::<Vec<_>>()
251        );
252    }
253}