Skip to main content

vault_core/
platform.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Small platform differences that the rest of the code should not have to know about.
4//!
5//! - [`replace_file`]: the "write a temp file, rename it over the target" step. On Windows a rename
6//!   over a file another process has open (an antivirus scan, a backup agent, a reader) fails with a
7//!   sharing violation that clears within moments, so it is retried a bounded number of times.
8//! - [`network_fs`]: whether a path is on a network filesystem. SQLite's WAL mode needs shared
9//!   memory and locks that NFS and SMB do not provide reliably, so a vault there can corrupt;
10//!   `unv doctor` says so instead of letting it happen quietly.
11
12use std::io;
13use std::path::Path;
14use std::time::Duration;
15
16const ATTEMPTS: u32 = 8;
17const PAUSE: Duration = Duration::from_millis(40);
18
19/// `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION` and `ERROR_LOCK_VIOLATION`: what Windows
20/// reports while another handle blocks the rename.
21fn transient_windows(e: &io::Error) -> bool {
22    matches!(e.raw_os_error(), Some(5 | 32 | 33))
23}
24
25/// Runs `op`, repeating up to `ATTEMPTS` times while `transient` says the error will pass.
26pub fn retry<T>(
27    mut op: impl FnMut() -> io::Result<T>,
28    transient: impl Fn(&io::Error) -> bool,
29    pause: Duration,
30) -> io::Result<T> {
31    let mut attempt = 1;
32    loop {
33        match op() {
34            Err(e) if attempt < ATTEMPTS && transient(&e) => {
35                attempt += 1;
36                std::thread::sleep(pause);
37            }
38            other => return other,
39        }
40    }
41}
42
43/// Renames `from` over `to`. On Windows a sharing violation is retried briefly; elsewhere this is a
44/// plain rename, which is already atomic.
45pub fn replace_file(from: &Path, to: &Path) -> io::Result<()> {
46    retry(|| std::fs::rename(from, to), is_transient, PAUSE)
47}
48
49/// Whether a rename error is worth waiting out: only on Windows, where another handle can hold the
50/// target for a moment. Elsewhere a failed rename is final.
51fn is_transient(e: &io::Error) -> bool {
52    cfg!(windows) && transient_windows(e)
53}
54
55#[cfg(any(target_os = "linux", target_os = "macos", test))]
56const NETWORK_TYPES: &[&str] = &[
57    "nfs",
58    "nfs4",
59    "cifs",
60    "smb",
61    "smb2",
62    "smb3",
63    "smbfs",
64    "afpfs",
65    "webdav",
66    "9p",
67    "ceph",
68    "glusterfs",
69    "lustre",
70    "fuse.sshfs",
71    "fuse.rclone",
72    "fuse.s3fs",
73    "fuse.gcsfuse",
74];
75
76#[cfg(any(target_os = "linux", target_os = "macos", test))]
77fn is_network_type(fstype: &str) -> bool {
78    NETWORK_TYPES.contains(&fstype.to_ascii_lowercase().as_str())
79}
80
81/// The filesystem type of the longest mount point that contains `path`, from `/proc/mounts` text.
82pub fn parse_proc_mounts(text: &str, path: &Path) -> Option<String> {
83    text.lines()
84        .filter_map(|l| {
85            let mut f = l.split_whitespace();
86            let (_dev, mount, fstype) = (f.next()?, f.next()?, f.next()?);
87            // /proc/mounts escapes a space in a path as \040.
88            let mount = mount.replace("\\040", " ");
89            path.starts_with(&mount)
90                .then(|| (mount.len(), fstype.to_string()))
91        })
92        .max_by_key(|(len, _)| *len)
93        .map(|(_, t)| t)
94}
95
96/// The same for the output of `mount` on macOS: `host:/export on /Volumes/x (nfs, nodev, ...)`.
97pub fn parse_mount_output(text: &str, path: &Path) -> Option<String> {
98    text.lines()
99        .filter_map(|l| {
100            let (_, rest) = l.split_once(" on ")?;
101            let (mount, opts) = rest.rsplit_once(" (")?;
102            let fstype = opts.split([',', ')']).next()?.trim();
103            path.starts_with(mount)
104                .then(|| (mount.len(), fstype.to_string()))
105        })
106        .max_by_key(|(len, _)| *len)
107        .map(|(_, t)| t)
108}
109
110/// A Windows UNC path (`\\server\share\...`), which is always a network location.
111pub fn is_unc(path: &Path) -> bool {
112    let s = path.to_string_lossy();
113    (s.starts_with("\\\\") && !s.starts_with("\\\\?\\") && !s.starts_with("\\\\.\\"))
114        || s.starts_with("\\\\?\\UNC\\")
115}
116
117/// The name of the network filesystem `path` lives on, or `None` when it is local or unknown.
118pub fn network_fs(path: &Path) -> Option<String> {
119    let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
120    if is_unc(&path) {
121        return Some("a network share".into());
122    }
123    #[cfg(target_os = "linux")]
124    {
125        let text = std::fs::read_to_string("/proc/mounts").ok()?;
126        return parse_proc_mounts(&text, &path).filter(|t| is_network_type(t));
127    }
128    #[cfg(target_os = "macos")]
129    {
130        let out = std::process::Command::new("/sbin/mount").output().ok()?;
131        let text = String::from_utf8_lossy(&out.stdout).into_owned();
132        return parse_mount_output(&text, &path).filter(|t| is_network_type(t));
133    }
134    #[allow(unreachable_code)]
135    None
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use std::cell::Cell;
142
143    #[test]
144    fn a_transient_error_is_retried_until_it_passes_and_then_stops() {
145        let calls = Cell::new(0);
146        let r = retry(
147            || {
148                calls.set(calls.get() + 1);
149                if calls.get() < 4 {
150                    Err(io::Error::from_raw_os_error(32))
151                } else {
152                    Ok("renamed")
153                }
154            },
155            transient_windows,
156            Duration::ZERO,
157        );
158        assert_eq!(r.unwrap(), "renamed");
159        assert_eq!(calls.get(), 4);
160    }
161
162    #[test]
163    fn retrying_is_bounded_and_a_real_error_is_not_retried() {
164        let calls = Cell::new(0);
165        let r: io::Result<()> = retry(
166            || {
167                calls.set(calls.get() + 1);
168                Err(io::Error::from_raw_os_error(32))
169            },
170            transient_windows,
171            Duration::ZERO,
172        );
173        assert!(r.is_err());
174        assert_eq!(calls.get(), ATTEMPTS);
175        calls.set(0);
176        let r: io::Result<()> = retry(
177            || {
178                calls.set(calls.get() + 1);
179                Err(io::Error::from(io::ErrorKind::NotFound))
180            },
181            transient_windows,
182            Duration::ZERO,
183        );
184        assert!(r.is_err());
185        assert_eq!(calls.get(), 1, "a missing file will not appear by waiting");
186    }
187
188    #[test]
189    fn replace_file_overwrites_atomically_and_reports_a_missing_source() {
190        let d = std::env::temp_dir().join(format!("vc-plat-{}", crate::new_uuid()));
191        std::fs::create_dir_all(&d).unwrap();
192        std::fs::write(d.join("a"), "new").unwrap();
193        std::fs::write(d.join("b"), "old").unwrap();
194        replace_file(&d.join("a"), &d.join("b")).unwrap();
195        assert_eq!(std::fs::read_to_string(d.join("b")).unwrap(), "new");
196        assert!(replace_file(&d.join("a"), &d.join("b")).is_err());
197        let _ = std::fs::remove_dir_all(&d);
198    }
199
200    #[test]
201    fn the_longest_mount_wins_and_only_network_types_count() {
202        let mounts = "/dev/sda1 / ext4 rw 0 0\nnas:/export /mnt/nas nfs4 rw 0 0\n/dev/sdb1 /mnt/nas/local ext4 rw 0 0\n//srv/share /mnt/with\\040space cifs rw 0 0\n";
203        let t = |p: &str| parse_proc_mounts(mounts, Path::new(p));
204        assert_eq!(t("/home/me/vault.db").as_deref(), Some("ext4"));
205        assert_eq!(t("/mnt/nas/vault.db").as_deref(), Some("nfs4"));
206        assert_eq!(t("/mnt/nas/local/vault.db").as_deref(), Some("ext4"));
207        assert_eq!(t("/mnt/with space/x").as_deref(), Some("cifs"));
208        assert!(
209            is_network_type("nfs4") && is_network_type("CIFS") && is_network_type("fuse.sshfs")
210        );
211        assert!(!is_network_type("ext4") && !is_network_type("tmpfs"));
212    }
213
214    #[test]
215    fn the_macos_mount_listing_is_read_the_same_way() {
216        let out = "/dev/disk3s1 on / (apfs, local, journaled)\nnas.local:/export on /Volumes/nas (nfs, nodev, nosuid)\n//me@srv/share on /Volumes/share (smbfs, nodev)\n";
217        let t = |p: &str| parse_mount_output(out, Path::new(p));
218        assert_eq!(t("/Users/me/x").as_deref(), Some("apfs"));
219        assert_eq!(t("/Volumes/nas/v.db").as_deref(), Some("nfs"));
220        assert_eq!(t("/Volumes/share/v.db").as_deref(), Some("smbfs"));
221        assert_eq!(parse_mount_output("garbage", Path::new("/x")), None);
222    }
223
224    #[test]
225    fn unc_paths_are_network_and_device_paths_are_not() {
226        assert!(is_unc(Path::new("\\\\server\\share\\v.db")));
227        assert!(is_unc(Path::new("\\\\?\\UNC\\server\\share\\v.db")));
228        assert!(!is_unc(Path::new("\\\\?\\C:\\v.db")));
229        assert!(!is_unc(Path::new("C:\\v.db")));
230        assert!(!is_unc(Path::new("/home/me")));
231    }
232
233    #[test]
234    fn a_unc_path_is_reported_as_a_share_without_asking_the_system() {
235        assert_eq!(
236            network_fs(Path::new("\\\\srv\\share\\vault.db")).as_deref(),
237            Some("a network share")
238        );
239    }
240
241    #[test]
242    fn only_windows_waits_out_a_sharing_violation() {
243        let busy = io::Error::from_raw_os_error(32);
244        assert_eq!(is_transient(&busy), cfg!(windows));
245        assert!(!is_transient(&io::Error::from(io::ErrorKind::NotFound)));
246    }
247
248    #[test]
249    fn a_local_temp_directory_is_not_reported_as_a_network_one() {
250        assert_eq!(network_fs(&std::env::temp_dir()), None);
251    }
252}