Skip to main content

smriti/db/
network_drive.rs

1//! Libraries kept on a NAS or network share.
2//!
3//! SQLite's WAL mode keeps its index in shared memory (the `-shm` file),
4//! which only works when every connection runs on the machine that owns
5//! the file. Over SMB or NFS the locks behind it are unreliable: scans
6//! stall on "database is locked" and memory-mapped pages can go stale.
7//! A library on a network filesystem therefore uses SQLite's classic
8//! rollback journal and no memory mapping (see `Database::open_for_drive`).
9//!
10//! Detection is automatic. A marker file in the library's metadata folder
11//! turns network mode on for mounts that look local — FUSE mounts the
12//! detector misses, unusual setups — and travels with the library.
13//! Treating a local disk as network costs some write speed; treating a
14//! share as local costs a stuck library, so doubtful cases count as network.
15
16use std::path::{Path, PathBuf};
17
18use super::connection::library_metadata_dir;
19
20const MARKER_FILE: &str = "network-drive";
21
22/// Whether a library's database runs in network mode, and why.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct NetworkDrive {
25    /// The library sits on a filesystem Smriti recognises as networked.
26    pub detected: bool,
27    /// The user turned network mode on for this library.
28    pub forced: bool,
29}
30
31impl NetworkDrive {
32    pub fn active(&self) -> bool {
33        self.detected || self.forced
34    }
35}
36
37pub fn network_drive(drive_root: &Path) -> NetworkDrive {
38    NetworkDrive {
39        detected: is_network_filesystem(drive_root),
40        forced: marker_path(drive_root).is_file(),
41    }
42}
43
44/// Turn the user's network-mode override for a library on or off. Takes
45/// effect the next time the library opens.
46pub fn set_forced(drive_root: &Path, forced: bool) -> std::io::Result<()> {
47    let marker = marker_path(drive_root);
48    if forced {
49        std::fs::create_dir_all(library_metadata_dir(drive_root))?;
50        std::fs::write(
51            marker,
52            "Smriti keeps this library's database in network-drive mode.\n",
53        )
54    } else {
55        match std::fs::remove_file(marker) {
56            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
57            result => result,
58        }
59    }
60}
61
62fn marker_path(drive_root: &Path) -> PathBuf {
63    library_metadata_dir(drive_root).join(MARKER_FILE)
64}
65
66/// True when `path` lives on a network filesystem.
67pub fn is_network_filesystem(path: &Path) -> bool {
68    let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
69    platform::is_network_filesystem(&path)
70}
71
72#[cfg(windows)]
73mod platform {
74    use std::path::{Component, Path, Prefix};
75
76    const DRIVE_REMOTE: u32 = 4;
77
78    #[link(name = "kernel32")]
79    extern "system" {
80        fn GetDriveTypeW(root_path_name: *const u16) -> u32;
81    }
82
83    pub fn is_network_filesystem(path: &Path) -> bool {
84        let Some(Component::Prefix(prefix)) = path.components().next() else {
85            return false;
86        };
87        match prefix.kind() {
88            Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
89            // Mapped network drives keep their letter.
90            Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
91                let root: Vec<u16> = format!("{}:\\", letter as char)
92                    .encode_utf16()
93                    .chain(Some(0))
94                    .collect();
95                // SAFETY: `root` is a NUL-terminated UTF-16 string that
96                // outlives the call.
97                unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
98            }
99            _ => false,
100        }
101    }
102}
103
104#[cfg(target_os = "linux")]
105mod platform {
106    use std::path::Path;
107
108    pub fn is_network_filesystem(path: &Path) -> bool {
109        std::fs::read_to_string("/proc/self/mountinfo")
110            .ok()
111            .and_then(|mountinfo| super::fstype_for(&mountinfo, path))
112            .is_some_and(|fstype| super::is_network_fstype(&fstype))
113    }
114}
115
116#[cfg(target_os = "macos")]
117mod platform {
118    use std::ffi::{CStr, CString};
119    use std::os::unix::ffi::OsStrExt;
120    use std::path::Path;
121
122    pub fn is_network_filesystem(path: &Path) -> bool {
123        let Ok(c_path) = CString::new(path.as_os_str().as_bytes()) else {
124            return false;
125        };
126        let mut stat = std::mem::MaybeUninit::<libc::statfs>::uninit();
127        // SAFETY: `c_path` is NUL-terminated and `stat` is a valid out-pointer.
128        if unsafe { libc::statfs(c_path.as_ptr(), stat.as_mut_ptr()) } != 0 {
129            return false;
130        }
131        // SAFETY: statfs succeeded, so it filled in `stat`, and
132        // `f_fstypename` is NUL-terminated.
133        let fstype = unsafe { CStr::from_ptr(stat.assume_init_ref().f_fstypename.as_ptr()) };
134        matches!(
135            fstype.to_bytes(),
136            b"smbfs" | b"nfs" | b"afpfs" | b"webdav" | b"cifs" | b"ftp" | b"macfuse" | b"osxfuse"
137        )
138    }
139}
140
141#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
142mod platform {
143    pub fn is_network_filesystem(_path: &std::path::Path) -> bool {
144        false
145    }
146}
147
148/// The filesystem type of the mount holding `path`, from the contents of
149/// Linux's `/proc/self/mountinfo`.
150#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
151fn fstype_for(mountinfo: &str, path: &Path) -> Option<String> {
152    let mut best: Option<(usize, &str)> = None;
153    for line in mountinfo.lines() {
154        // `<id> <parent> <dev> <root> <mount point> <options> [tags] - <fstype> <source> <options>`
155        let Some((mount, fs)) = line.split_once(" - ") else {
156            continue;
157        };
158        let (Some(mount_point), Some(fstype)) = (mount.split(' ').nth(4), fs.split(' ').next())
159        else {
160            continue;
161        };
162        let mount_point = unescape_mount_point(mount_point);
163        // Longest match wins; on a tie the later (newer, on top) mount does.
164        let depth = Path::new(&mount_point).components().count();
165        if path.starts_with(&mount_point) && best.is_none_or(|(d, _)| depth >= d) {
166            best = Some((depth, fstype));
167        }
168    }
169    best.map(|(_, fstype)| fstype.to_string())
170}
171
172/// mountinfo escapes space, tab, newline and backslash as `\ooo` octal.
173#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
174fn unescape_mount_point(raw: &str) -> String {
175    let bytes = raw.as_bytes();
176    let mut out = Vec::with_capacity(bytes.len());
177    let mut i = 0;
178    while i < bytes.len() {
179        let octal = bytes
180            .get(i + 1..i + 4)
181            .filter(|d| d.iter().all(|b| (b'0'..=b'7').contains(b)));
182        if let (b'\\', Some(digits)) = (bytes[i], octal) {
183            out.push(
184                digits
185                    .iter()
186                    .fold(0u8, |n, d| n.wrapping_mul(8).wrapping_add(d - b'0')),
187            );
188            i += 4;
189            continue;
190        }
191        out.push(bytes[i]);
192        i += 1;
193    }
194    String::from_utf8_lossy(&out).into_owned()
195}
196
197/// Network filesystems, plus every named FUSE filesystem (sshfs, rclone,
198/// GNOME's gvfs SMB mounts). Block-device FUSE mounts such as ntfs-3g and
199/// exFAT report `fuseblk` and stay local.
200#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
201fn is_network_fstype(fstype: &str) -> bool {
202    matches!(
203        fstype,
204        "cifs"
205            | "smb3"
206            | "smbfs"
207            | "nfs"
208            | "nfs4"
209            | "ncpfs"
210            | "afs"
211            | "ceph"
212            | "glusterfs"
213            | "9p"
214            | "davfs"
215            | "lustre"
216            | "beegfs"
217            | "gpfs"
218    ) || fstype.starts_with("fuse.")
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    const MOUNTINFO: &str = "\
22622 1 8:2 / / rw,relatime shared:1 - ext4 /dev/sda2 rw
22740 22 8:17 / /media/me/USB\\040Drive rw,nosuid shared:20 - fuseblk /dev/sdb1 rw
22841 22 0:50 / /mnt/nas rw,relatime shared:21 - cifs //nas/photos rw,vers=3.0
22942 41 0:51 / /mnt/nas/local rw,relatime shared:22 - ext4 /dev/sdc1 rw
23043 22 0:52 / /run/user/1000/gvfs rw shared:23 - fuse.gvfsd-fuse gvfsd-fuse rw
231";
232
233    #[test]
234    fn picks_the_deepest_mount_holding_the_path() {
235        let fstype = |p: &str| fstype_for(MOUNTINFO, Path::new(p));
236        assert_eq!(fstype("/home/me/Pictures").as_deref(), Some("ext4"));
237        assert_eq!(fstype("/mnt/nas/2023").as_deref(), Some("cifs"));
238        assert_eq!(fstype("/mnt/nas/local/x").as_deref(), Some("ext4"));
239        // Component-wise: /mnt/nassy is not under /mnt/nas.
240        assert_eq!(fstype("/mnt/nassy").as_deref(), Some("ext4"));
241        assert_eq!(
242            fstype("/media/me/USB Drive/DCIM").as_deref(),
243            Some("fuseblk")
244        );
245    }
246
247    #[test]
248    fn classifies_filesystem_types() {
249        for fstype in [
250            "cifs",
251            "smb3",
252            "nfs4",
253            "fuse.sshfs",
254            "fuse.rclone",
255            "fuse.gvfsd-fuse",
256        ] {
257            assert!(is_network_fstype(fstype), "{fstype}");
258        }
259        for fstype in ["ext4", "btrfs", "exfat", "vfat", "ntfs3", "fuseblk", "apfs"] {
260            assert!(!is_network_fstype(fstype), "{fstype}");
261        }
262    }
263
264    #[test]
265    fn unescapes_octal_sequences() {
266        assert_eq!(unescape_mount_point("/a\\040b\\134c"), "/a b\\c");
267        assert_eq!(unescape_mount_point("/plain"), "/plain");
268        assert_eq!(unescape_mount_point("/trailing\\04"), "/trailing\\04");
269    }
270
271    #[test]
272    fn marker_turns_network_mode_on_and_off() {
273        let dir = tempfile::tempdir().unwrap();
274        assert!(!network_drive(dir.path()).forced);
275        set_forced(dir.path(), true).unwrap();
276        assert!(network_drive(dir.path()).forced);
277        assert!(network_drive(dir.path()).active());
278        set_forced(dir.path(), false).unwrap();
279        set_forced(dir.path(), false).unwrap(); // already off: no error
280        assert!(!network_drive(dir.path()).forced);
281    }
282
283    #[test]
284    fn temp_dirs_are_local() {
285        let dir = tempfile::tempdir().unwrap();
286        assert!(!is_network_filesystem(dir.path()));
287    }
288}