Skip to main content

surjection_core/
fs.rs

1//! File system facade. Core code takes `&dyn Fs` so tests can confine every
2//! access to a temp root (`surjection_testkit::RootedFs`).
3
4use std::borrow::Cow;
5use std::fs::File;
6use std::io::{self, Write};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use crate::access::WriteProbe;
11use crate::paths::extended;
12
13pub trait Fs: Send + Sync {
14    /// The directory this view is confined to, or `None` for the whole file
15    /// system. Ancestor walks (such as sync-root detection) stop here.
16    fn root(&self) -> Option<&Path>;
17
18    fn exists(&self, path: &Path) -> bool;
19
20    fn is_dir(&self, path: &Path) -> bool;
21
22    fn read_to_string(&self, path: &Path) -> io::Result<String>;
23
24    /// The bytes of a file.
25    fn read(&self, path: &Path) -> io::Result<Vec<u8>>;
26
27    /// The size of a file in bytes. The default reads the file; real file
28    /// systems answer from its metadata.
29    fn file_size(&self, path: &Path) -> io::Result<u64> {
30        self.read(path).map(|bytes| bytes.len() as u64)
31    }
32
33    fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
34
35    /// Creates `path`, which must not exist, writes `contents` and flushes
36    /// them to disk. With `like`, the new file gets the permissions of that
37    /// existing file: its mode on Unix, its attributes and DACL on Windows.
38    /// Used for the temp file of an atomic replace (SPEC 8.4).
39    fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()>;
40
41    /// Moves `from` over `to`, replacing it atomically. On Unix the
42    /// directory is flushed afterwards.
43    fn replace(&self, from: &Path, to: &Path) -> io::Result<()>;
44
45    /// Writes `contents` to `path` (created or truncated) so that only the
46    /// current user can read or write it: mode 0600 on Unix, a protected
47    /// DACL granting only the file's owner on Windows. Flushes to disk.
48    fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()>;
49
50    fn create_dir_all(&self, path: &Path) -> io::Result<()>;
51
52    /// Creates `path` and its missing parents; `path` itself is restricted
53    /// to the current user (mode 0700 on Unix, a protected DACL granting
54    /// only the owner, inherited by new children, on Windows).
55    fn create_private_dir_all(&self, path: &Path) -> io::Result<()>;
56
57    fn remove_file(&self, path: &Path) -> io::Result<()>;
58
59    /// Whether `path` itself is a regular file: links are not followed, so
60    /// a symbolic link, a junction or another reparse point is not one.
61    fn is_regular_file(&self, path: &Path) -> bool;
62
63    /// Overwrites every byte of the existing regular file `path` with zero,
64    /// in place: the file is opened for writing without being created or
65    /// truncated, as many zero bytes as it holds are written from offset 0,
66    /// and the file is flushed to disk (`sync_all`). Its length stays the
67    /// same. Fails when `path` is missing or not a regular file.
68    fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()>;
69
70    fn remove_dir_all(&self, path: &Path) -> io::Result<()>;
71
72    /// Paths of the entries of a directory, sorted.
73    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
74
75    /// Opens `path` for use as an advisory lock file, creating it if needed.
76    /// The contents are never read or written.
77    fn open_lock_file(&self, path: &Path) -> io::Result<File>;
78
79    /// `path` with symlinks and junctions resolved (`std::fs::canonicalize`;
80    /// on Windows a `\\?\` path). Views that cannot resolve links return
81    /// `path` as it is.
82    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
83        Ok(path.to_path_buf())
84    }
85
86    /// Notes that what the caller works out depends on the content of
87    /// `path`, which it reads some other way (git2 reading a repository's
88    /// index). Nothing here; a recording view takes note (the plan cache,
89    /// [`crate::apply::cache`]).
90    fn note_dependency(&self, _path: &Path) {}
91
92    /// A probe of whether this account can write a path (SPEC 8.2
93    /// `read_only_target`), to run on a worker thread; it never writes.
94    /// `None`: this view cannot probe, so every target counts as
95    /// [`WriteAccess::Unknown`](crate::access::WriteAccess::Unknown).
96    fn write_probe(&self) -> Option<WriteProbe> {
97        None
98    }
99}
100
101/// The real file system, unconfined.
102#[derive(Debug, Clone, Copy, Default)]
103pub struct RealFs;
104
105/// `path` as [`RealFs`] hands it to the OS: on Windows, in its `\\?\` form
106/// ([`extended`]) once it is long enough to reach `MAX_PATH`, so names
107/// built from whole paths (backup copies) work past it (SPEC 16.1). std
108/// does this for its own calls; the Windows security calls need it too.
109/// Paths given back to callers stay as they were given.
110pub(crate) fn long(path: &Path) -> Cow<'_, Path> {
111    // std's threshold: `MAX_PATH` less room for an 8.3 file name.
112    const LIMIT: usize = 248;
113    if cfg!(windows) && path.as_os_str().len() >= LIMIT {
114        extended(path)
115    } else {
116        Cow::Borrowed(path)
117    }
118}
119
120impl Fs for RealFs {
121    fn root(&self) -> Option<&Path> {
122        None
123    }
124
125    fn exists(&self, path: &Path) -> bool {
126        long(path).exists()
127    }
128
129    fn is_dir(&self, path: &Path) -> bool {
130        long(path).is_dir()
131    }
132
133    fn read_to_string(&self, path: &Path) -> io::Result<String> {
134        std::fs::read_to_string(long(path))
135    }
136
137    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
138        std::fs::read(long(path))
139    }
140
141    fn file_size(&self, path: &Path) -> io::Result<u64> {
142        std::fs::metadata(long(path)).map(|meta| meta.len())
143    }
144
145    fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
146        std::fs::write(long(path), contents)
147    }
148
149    fn write_new(&self, path: &Path, contents: &[u8], like: Option<&Path>) -> io::Result<()> {
150        let path = long(path);
151        let like = like.map(long);
152        let mut options = File::options();
153        options.write(true).create_new(true);
154        if let Some(like) = &like {
155            platform::copy_open_options(&mut options, like)?;
156        }
157        let mut file = options.open(&path)?;
158        let written = (|| {
159            if let Some(like) = &like {
160                platform::copy_permissions(like, &path, &file)?;
161            }
162            file.write_all(contents)?;
163            file.sync_all()
164        })();
165        if written.is_err() {
166            drop(file);
167            let _ = std::fs::remove_file(&path);
168        }
169        written
170    }
171
172    fn replace(&self, from: &Path, to: &Path) -> io::Result<()> {
173        let to = long(to);
174        std::fs::rename(long(from), &to)?;
175        platform::sync_parent(&to)
176    }
177
178    fn write_private(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
179        let path = long(path);
180        let mut options = File::options();
181        options.write(true).create(true).truncate(true);
182        platform::private_open_options(&mut options);
183        let mut file = options.open(&path)?;
184        // Restrict before any content lands, also for an existing file.
185        platform::make_private(&path, &file)?;
186        file.write_all(contents)?;
187        file.sync_all()
188    }
189
190    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
191        std::fs::create_dir_all(long(path))
192    }
193
194    fn create_private_dir_all(&self, path: &Path) -> io::Result<()> {
195        let path = long(path);
196        std::fs::create_dir_all(&path)?;
197        platform::make_private_dir(&path)
198    }
199
200    fn remove_file(&self, path: &Path) -> io::Result<()> {
201        std::fs::remove_file(long(path))
202    }
203
204    fn is_regular_file(&self, path: &Path) -> bool {
205        std::fs::symlink_metadata(long(path)).is_ok_and(|meta| meta.file_type().is_file())
206    }
207
208    fn overwrite_with_zeros(&self, path: &Path) -> io::Result<()> {
209        let path = long(path);
210        if !std::fs::symlink_metadata(&path)?.file_type().is_file() {
211            return Err(io::Error::new(
212                io::ErrorKind::InvalidInput,
213                "not a regular file",
214            ));
215        }
216        // No `create`, no `truncate`: the zeros land on the file's own
217        // blocks (as far as the file system allows), never on new ones.
218        let mut file = File::options().write(true).open(&path)?;
219        let mut left = file.metadata()?.len();
220        let zeros = [0u8; 64 * 1024];
221        while left > 0 {
222            let chunk = usize::try_from(left).map_or(zeros.len(), |left| left.min(zeros.len()));
223            file.write_all(&zeros[..chunk])?;
224            left -= chunk as u64;
225        }
226        file.sync_all()
227    }
228
229    fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
230        std::fs::remove_dir_all(long(path))
231    }
232
233    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
234        // Entries are joined to `path` as given, never to its `\\?\` form.
235        let mut entries = std::fs::read_dir(long(path))?
236            .map(|entry| entry.map(|entry| path.join(entry.file_name())))
237            .collect::<io::Result<Vec<_>>>()?;
238        entries.sort();
239        Ok(entries)
240    }
241
242    fn open_lock_file(&self, path: &Path) -> io::Result<File> {
243        File::options()
244            .read(true)
245            .write(true)
246            .create(true)
247            .truncate(false)
248            .open(long(path))
249    }
250
251    fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
252        std::fs::canonicalize(long(path))
253    }
254
255    fn write_probe(&self) -> Option<WriteProbe> {
256        Some(Arc::new(crate::access::probe))
257    }
258}
259
260#[cfg(unix)]
261mod platform {
262    use std::fs::{File, OpenOptions, Permissions};
263    use std::io;
264    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
265    use std::path::Path;
266
267    pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
268        let mode = std::fs::metadata(like)?.permissions().mode();
269        options.mode(mode & 0o7777);
270        Ok(())
271    }
272
273    /// The umask may have narrowed the mode given at creation.
274    pub fn copy_permissions(like: &Path, _path: &Path, file: &File) -> io::Result<()> {
275        let mode = std::fs::metadata(like)?.permissions().mode();
276        file.set_permissions(Permissions::from_mode(mode & 0o7777))
277    }
278
279    pub fn private_open_options(options: &mut OpenOptions) {
280        options.mode(0o600);
281    }
282
283    pub fn make_private(_path: &Path, file: &File) -> io::Result<()> {
284        file.set_permissions(Permissions::from_mode(0o600))
285    }
286
287    pub fn make_private_dir(path: &Path) -> io::Result<()> {
288        std::fs::set_permissions(path, Permissions::from_mode(0o700))
289    }
290
291    /// Flushes the directory entry of a rename.
292    pub fn sync_parent(path: &Path) -> io::Result<()> {
293        match path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
294            Some(dir) => File::open(dir)?.sync_all(),
295            None => Ok(()),
296        }
297    }
298}
299
300#[cfg(windows)]
301mod platform {
302    use std::fs::{File, OpenOptions};
303    use std::io;
304    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
305    use std::path::Path;
306
307    use windows_permissions::constants::{AceFlags, SeObjectType, SecurityInformation};
308    use windows_permissions::{LocalBox, SecurityDescriptor, wrappers};
309
310    /// Attributes a replaced file keeps (as `ReplaceFileW` does). Read-only
311    /// is not carried over: the replace itself would fail on it.
312    const KEPT_ATTRIBUTES: u32 = 0x2 // hidden
313        | 0x4 // system
314        | 0x20 // archive
315        | 0x2000; // not content indexed
316
317    pub fn copy_open_options(options: &mut OpenOptions, like: &Path) -> io::Result<()> {
318        let attributes = std::fs::metadata(like)?.file_attributes() & KEPT_ATTRIBUTES;
319        options.attributes(attributes);
320        Ok(())
321    }
322
323    /// Gives `path` the DACL of `like`. A DACL made only of inherited
324    /// entries is already right: the new file sits in the same directory.
325    pub fn copy_permissions(like: &Path, path: &Path, _file: &File) -> io::Result<()> {
326        let sd = wrappers::GetNamedSecurityInfo(
327            like.as_os_str(),
328            SeObjectType::SE_FILE_OBJECT,
329            SecurityInformation::Dacl,
330        )?;
331        let sddl = sd.as_sddl()?.to_string_lossy().into_owned();
332        let protected = dacl_flags(&sddl).contains('P');
333        let Some(dacl) = sd.dacl() else {
334            return Ok(());
335        };
336        let explicit = (0..dacl.len())
337            .filter_map(|index| dacl.get_ace(index))
338            .any(|ace| !ace.flags().contains(AceFlags::Inherited));
339        if !protected && !explicit {
340            return Ok(());
341        }
342        let protection = if protected {
343            SecurityInformation::ProtectedDacl
344        } else {
345            SecurityInformation::UnprotectedDacl
346        };
347        wrappers::SetNamedSecurityInfo(
348            path.as_os_str(),
349            SeObjectType::SE_FILE_OBJECT,
350            SecurityInformation::Dacl | protection,
351            None,
352            None,
353            Some(dacl),
354            None,
355        )
356    }
357
358    /// The control flags of the DACL in an SDDL string (`D:PAI(...)` gives
359    /// `P` plus `AI`), without the auto-inherit flags.
360    fn dacl_flags(sddl: &str) -> String {
361        let Some(start) = sddl.find("D:") else {
362            return String::new();
363        };
364        let rest = &sddl[start + 2..];
365        let end = rest.find('(').unwrap_or(rest.len());
366        rest[..end].replace("AI", "").replace("AR", "")
367    }
368
369    pub fn private_open_options(_options: &mut OpenOptions) {}
370
371    pub fn make_private(path: &Path, _file: &File) -> io::Result<()> {
372        owner_only(path, false)
373    }
374
375    pub fn make_private_dir(path: &Path) -> io::Result<()> {
376        owner_only(path, true)
377    }
378
379    /// A protected DACL with one entry: full control for the owner of
380    /// `path` (the current user for anything this process creates).
381    fn owner_only(path: &Path, dir: bool) -> io::Result<()> {
382        let sd = wrappers::GetNamedSecurityInfo(
383            path.as_os_str(),
384            SeObjectType::SE_FILE_OBJECT,
385            SecurityInformation::Owner,
386        )?;
387        let owner = sd
388            .owner()
389            .ok_or_else(|| io::Error::other("the file has no owner"))?;
390        let inherit = if dir { "OICI" } else { "" };
391        let sddl = format!("D:P(A;{inherit};FA;;;{owner})");
392        let private: LocalBox<SecurityDescriptor> = sddl.parse()?;
393        let dacl = private
394            .dacl()
395            .ok_or_else(|| io::Error::other("the private DACL did not parse"))?;
396        wrappers::SetNamedSecurityInfo(
397            path.as_os_str(),
398            SeObjectType::SE_FILE_OBJECT,
399            SecurityInformation::Dacl | SecurityInformation::ProtectedDacl,
400            None,
401            None,
402            Some(dacl),
403            None,
404        )
405    }
406
407    /// NTFS makes a completed rename durable without a directory flush.
408    pub fn sync_parent(_path: &Path) -> io::Result<()> {
409        Ok(())
410    }
411}