Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 17.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! File system access inside a workspace that never follows a symlink.
5//!
6//! Everything goes through [`cap_std`] directory handles, one name at a time:
7//! a directory is opened from its parent's handle with `O_NOFOLLOW`, a file
8//! is opened or created by its single name in its directory, and the only
9//! path that is ever resolved as a whole is the workspace root itself. A
10//! symlink in the working copy, whoever made it, is therefore a leaf: braid
11//! reads its target as data, replaces or removes it, and never goes through
12//! it. On Unix, a directory's listing, its own metadata and its entries'
13//! metadata are read through the same handles with plain system calls: the
14//! listing through a second handle opened as `.`, and an entry's metadata by
15//! its single name, without following a symlink.
16
17use std::ffi::OsStr;
18use std::io::{self, Read, Seek, SeekFrom, Write};
19use std::path::{Path, PathBuf};
20
21use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
22use cap_std::fs::{Dir, File, Metadata, OpenOptions};
23
24use crate::error::Error;
25use crate::fsprobe::{SCRATCH_PREFIX, random_hex};
26use crate::paths::{names, os_name, show};
27
28/// What a file system entry is, as far as a workspace cares.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub(crate) enum StatKind {
31 File,
32 Dir,
33 Symlink,
34 /// A device, a socket, a pipe: never part of a working copy.
35 Other,
36}
37
38/// The parts of a file's metadata that a workspace uses.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub(crate) struct Stat {
41 pub kind: StatKind,
42 /// The owner may execute it.
43 pub executable: bool,
44 pub size: u64,
45 /// Modification time: seconds and nanoseconds since the Unix epoch.
46 pub mtime: (i64, u32),
47 /// The file's number on its device, 0 where there is none.
48 pub ino: u64,
49}
50
51impl Stat {
52 pub(crate) fn of(meta: &Metadata) -> Stat {
53 let file_type = meta.file_type();
54 let kind = if file_type.is_symlink() {
55 StatKind::Symlink
56 } else if file_type.is_dir() {
57 StatKind::Dir
58 } else if file_type.is_file() {
59 StatKind::File
60 } else {
61 StatKind::Other
62 };
63 #[cfg(unix)]
64 {
65 use cap_std::fs::MetadataExt;
66 Stat {
67 kind,
68 executable: meta.mode() & 0o100 != 0,
69 size: meta.size(),
70 mtime: (meta.mtime(), u32::try_from(meta.mtime_nsec()).unwrap_or(0)),
71 ino: meta.ino(),
72 }
73 }
74 #[cfg(not(unix))]
75 {
76 let mtime = meta
77 .modified()
78 .ok()
79 .and_then(|time| time.into_std().duration_since(std::time::UNIX_EPOCH).ok())
80 .map_or((0, 0), |since| {
81 (since.as_secs() as i64, since.subsec_nanos())
82 });
83 Stat {
84 kind,
85 executable: false,
86 size: meta.len(),
87 mtime,
88 ino: 0,
89 }
90 }
91 }
92}
93
94/// What a directory's own metadata says of its entries: when they last
95/// changed, by its modification and status change times, and which
96/// directory it is. Adding, removing or renaming an entry changes both
97/// times; only the first can be set back by hand.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub(crate) struct DirStamp {
100 pub mtime: (i64, u32),
101 pub ctime: (i64, u32),
102 pub ino: u64,
103}
104
105impl DirStamp {
106 /// Whether both times are strictly older than `time`.
107 pub(crate) fn older_than(&self, time: (i64, u32)) -> bool {
108 self.mtime < time && self.ctime < time
109 }
110}
111
112/// The stamp of an open directory, where the system gives one.
113#[cfg(unix)]
114#[allow(clippy::unnecessary_cast, clippy::useless_conversion)]
115pub(crate) fn dir_stamp(dir: &Dir) -> Option<DirStamp> {
116 let stat = rustix::fs::fstat(dir).ok()?;
117 Some(DirStamp {
118 mtime: (
119 i64::try_from(stat.st_mtime).ok()?,
120 u32::try_from(stat.st_mtime_nsec).ok()?,
121 ),
122 ctime: (
123 i64::try_from(stat.st_ctime).ok()?,
124 u32::try_from(stat.st_ctime_nsec).ok()?,
125 ),
126 ino: u64::try_from(stat.st_ino).ok()?,
127 })
128}
129
130/// The stamp of an open directory, where the system gives one: not here,
131/// where there is no status change time.
132#[cfg(not(unix))]
133pub(crate) fn dir_stamp(_dir: &Dir) -> Option<DirStamp> {
134 None
135}
136
137impl Stat {
138 /// The metadata in a `stat` structure, as [`Stat::of`] reads it from
139 /// [`Metadata`]. Its fields' types differ between systems.
140 #[cfg(unix)]
141 #[allow(clippy::unnecessary_cast, clippy::useless_conversion)]
142 pub(crate) fn of_raw(stat: &rustix::fs::Stat) -> Stat {
143 use rustix::fs::{FileType, RawMode};
144 let mode = stat.st_mode as RawMode;
145 let kind = match FileType::from_raw_mode(mode) {
146 FileType::Symlink => StatKind::Symlink,
147 FileType::Directory => StatKind::Dir,
148 FileType::RegularFile => StatKind::File,
149 _ => StatKind::Other,
150 };
151 Stat {
152 kind,
153 executable: mode & 0o100 != 0,
154 size: u64::try_from(stat.st_size).unwrap_or(0),
155 mtime: (
156 i64::try_from(stat.st_mtime).unwrap_or(0),
157 u32::try_from(stat.st_mtime_nsec).unwrap_or(0),
158 ),
159 ino: u64::try_from(stat.st_ino).unwrap_or(0),
160 }
161 }
162}
163
164/// What is at a path of the working copy.
165#[derive(Debug)]
166pub(crate) enum Found<T> {
167 /// This.
168 Here(T),
169 /// Nothing, and every directory above it that exists is a directory.
170 Missing,
171 /// Nothing can be there: the prefix of this many bytes is a file, a
172 /// symlink or something else that is not a directory.
173 Blocked(usize),
174}
175
176/// The root directory of a workspace, open.
177#[derive(Debug)]
178pub(crate) struct Root {
179 dir: Dir,
180 path: PathBuf,
181}
182
183impl Root {
184 /// Opens the workspace directory at `path`, which must exist.
185 pub(crate) fn open(path: &Path) -> Result<Root, Error> {
186 let dir = Dir::open_ambient_dir(path, cap_std::ambient_authority())
187 .map_err(Error::io("open", path))?;
188 Ok(Root {
189 dir,
190 path: path.to_path_buf(),
191 })
192 }
193
194 /// The workspace's root directory.
195 pub(crate) fn dir(&self) -> &Dir {
196 &self.dir
197 }
198
199 /// The path the root was opened at, for messages.
200 pub(crate) fn path(&self) -> &Path {
201 &self.path
202 }
203
204 /// The directory at `path` (empty for the root), opened name by name
205 /// without following symlinks.
206 pub(crate) fn open_dir(&self, path: &[u8]) -> Result<Found<Dir>, Error> {
207 let mut dir = self
208 .dir
209 .try_clone()
210 .map_err(Error::io("open", &self.path))?;
211 let mut end = 0;
212 for name in names(path) {
213 end += name.len() + usize::from(end > 0);
214 let os = os_name(name).ok_or_else(|| unrepresentable(&path[..end]))?;
215 match dir.open_dir_nofollow(os) {
216 Ok(next) => dir = next,
217 Err(err) => {
218 return match dir.symlink_metadata(os) {
219 Err(missing) if missing.kind() == io::ErrorKind::NotFound => {
220 Ok(Found::Missing)
221 }
222 Ok(meta) if !meta.is_dir() => Ok(Found::Blocked(end)),
223 _ => Err(self.error("open", &path[..end], err)),
224 };
225 }
226 }
227 }
228 Ok(Found::Here(dir))
229 }
230
231 /// The metadata of the entry at `path`, without following symlinks.
232 pub(crate) fn stat(&self, path: &[u8]) -> Result<Found<Stat>, Error> {
233 let (parent, name) = crate::paths::split_last(path);
234 let dir = match self.open_dir(parent)? {
235 Found::Here(dir) => dir,
236 Found::Missing => return Ok(Found::Missing),
237 Found::Blocked(at) => return Ok(Found::Blocked(at)),
238 };
239 let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
240 match dir.symlink_metadata(os) {
241 Ok(meta) => Ok(Found::Here(Stat::of(&meta))),
242 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Found::Missing),
243 Err(err) => Err(self.error("read", path, err)),
244 }
245 }
246
247 /// The directory at `path`, creating the directories that are missing.
248 /// A name on the way that is not a directory is an error, never
249 /// something to go through.
250 pub(crate) fn create_dirs(&self, path: &[u8]) -> Result<Dir, Error> {
251 let mut dir = self
252 .dir
253 .try_clone()
254 .map_err(Error::io("open", &self.path))?;
255 let mut end = 0;
256 for name in names(path) {
257 end += name.len() + usize::from(end > 0);
258 let os = os_name(name).ok_or_else(|| unrepresentable(&path[..end]))?;
259 match dir.create_dir(os) {
260 Ok(()) => {}
261 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
262 Err(err) => return Err(self.error("create directory", &path[..end], err)),
263 }
264 dir = dir.open_dir_nofollow(os).map_err(|_| Error::Unsafe {
265 path: path[..end].to_vec(),
266 reason: "it is in the way of a directory: a file or a symlink".to_owned(),
267 })?;
268 }
269 Ok(dir)
270 }
271
272 /// The modification time the file system gives a file written now: a
273 /// one-byte rewrite of the workspace's `.braid` file, read back. This is
274 /// the clock and the granularity of the workspace's own file system,
275 /// which the system clock may not match.
276 pub(crate) fn file_system_now(&self) -> io::Result<(i64, u32)> {
277 let mut options = OpenOptions::new();
278 options.read(true).write(true).follow(FollowSymlinks::No);
279 let mut file = self.dir.open_with(braid_repo::DIR, &options)?;
280 let mut first = [0u8; 1];
281 file.read_exact(&mut first)?;
282 file.seek(SeekFrom::Start(0))?;
283 file.write_all(&first)?;
284 let meta = file.metadata()?;
285 Ok(Stat::of(&meta).mtime)
286 }
287
288 pub(crate) fn error(&self, action: &'static str, path: &[u8], source: io::Error) -> Error {
289 Error::Io {
290 action,
291 path: self.path.join(show(path).as_ref()),
292 source,
293 }
294 }
295}
296
297fn unrepresentable(path: &[u8]) -> Error {
298 Error::Unsafe {
299 path: path.to_vec(),
300 reason: "this platform cannot represent the name".to_owned(),
301 }
302}
303
304/// The names in `dir`, less `.` and `..`, in no order, each with whether
305/// the listing says it is a directory. Read through a handle of its own on
306/// the same directory, opened as `.`, so that `dir` stays usable meanwhile
307/// and its position in the listing is never shared.
308#[cfg(unix)]
309pub(crate) fn list(dir: &Dir) -> io::Result<Vec<(Vec<u8>, bool)>> {
310 use rustix::fs::{Mode, OFlags};
311 let flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC;
312 let mut stream = rustix::fs::Dir::new(rustix::fs::openat(dir, ".", flags, Mode::empty())?)?;
313 let mut names = Vec::new();
314 while let Some(entry) = stream.read() {
315 let entry = entry?;
316 let name = entry.file_name().to_bytes();
317 if name != b"." && name != b".." {
318 let is_dir = entry.file_type() == rustix::fs::FileType::Directory;
319 names.push((name.to_vec(), is_dir));
320 }
321 }
322 Ok(names)
323}
324
325/// The names in `dir`, less `.` and `..`, in no order, each with whether
326/// the listing says it is a directory.
327#[cfg(not(unix))]
328pub(crate) fn list(dir: &Dir) -> io::Result<Vec<(Vec<u8>, bool)>> {
329 let mut names = Vec::new();
330 for entry in dir.entries()? {
331 let entry = entry?;
332 // A name that is not UTF-8 has no repository bytes here.
333 if let Ok(name) = entry.file_name().into_string() {
334 names.push((
335 name.into_bytes(),
336 entry.file_type().is_ok_and(|kind| kind.is_dir()),
337 ));
338 }
339 }
340 Ok(names)
341}
342
343/// The metadata of the entry `name` of `dir`, without following a symlink.
344#[cfg(unix)]
345pub(crate) fn stat_entry(dir: &Dir, name: &OsStr) -> io::Result<Stat> {
346 let stat = rustix::fs::statat(dir, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW)?;
347 Ok(Stat::of_raw(&stat))
348}
349
350/// The metadata of the entry `name` of `dir`, without following a symlink.
351#[cfg(not(unix))]
352pub(crate) fn stat_entry(dir: &Dir, name: &OsStr) -> io::Result<Stat> {
353 Ok(Stat::of(&dir.symlink_metadata(name)?))
354}
355
356/// Opens the directory `name` of `dir` without following a symlink: `None`
357/// when nothing is there, or something that is not a directory.
358pub(crate) fn open_child_dir(dir: &Dir, name: &OsStr) -> io::Result<Option<Dir>> {
359 match dir.open_dir_nofollow(name) {
360 Ok(child) => Ok(Some(child)),
361 Err(err) => match dir.symlink_metadata(name) {
362 Err(missing) if missing.kind() == io::ErrorKind::NotFound => Ok(None),
363 Ok(meta) if !meta.is_dir() => Ok(None),
364 _ => Err(err),
365 },
366 }
367}
368
369/// Opens the regular file `name` of `dir` for reading, refusing a symlink.
370pub(crate) fn open_file(dir: &Dir, name: &OsStr) -> io::Result<File> {
371 let mut options = OpenOptions::new();
372 options.read(true).follow(FollowSymlinks::No);
373 dir.open_with(name, &options)
374}
375
376/// The target of the symlink `name` of `dir`, as bytes.
377pub(crate) fn read_link(dir: &Dir, name: &OsStr) -> io::Result<Vec<u8>> {
378 let target = dir.read_link_contents(name)?;
379 crate::paths::name_bytes(target.as_os_str())
380 .map(<[u8]>::to_vec)
381 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "symlink target is not text"))
382}
383
384/// Writes `name` in `dir` as a regular file with `content`, mode 0644 or
385/// 0755: into a new scratch file first, then renamed over `name`. A
386/// directory in the way is removed first, and must be empty.
387pub(crate) fn write_file(
388 dir: &Dir,
389 name: &OsStr,
390 content: &[u8],
391 executable: bool,
392) -> io::Result<()> {
393 write_file_from(dir, name, executable, |file| file.write_all(content))
394}
395
396/// Writes `name` in `dir` like [`write_file`], with the content `fill`
397/// writes into the scratch file, a piece at a time: a large file never
398/// needs to be in memory whole. If `fill` fails, `name` is left as it was.
399pub(crate) fn write_file_from(
400 dir: &Dir,
401 name: &OsStr,
402 executable: bool,
403 fill: impl FnOnce(&mut dyn Write) -> io::Result<()>,
404) -> io::Result<()> {
405 let (scratch, mut file) = create_scratch(dir)?;
406 let written = {
407 let mut out = io::BufWriter::new(&mut file);
408 fill(&mut out).and_then(|()| out.flush())
409 }
410 .and_then(|()| set_mode(&file, executable));
411 drop(file);
412 finish(dir, &scratch, name, written)
413}
414
415/// Creates `name` in `dir` as a symlink to `target`, which is stored as it
416/// is and never resolved; renamed over whatever file or symlink was there.
417pub(crate) fn write_symlink(dir: &Dir, name: &OsStr, target: &[u8]) -> io::Result<()> {
418 if target.is_empty() || target.contains(&0) {
419 return Err(io::Error::new(
420 io::ErrorKind::InvalidData,
421 "a symlink target must be non-empty and hold no NUL byte",
422 ));
423 }
424 let target = os_name(target).ok_or_else(|| {
425 io::Error::new(
426 io::ErrorKind::InvalidData,
427 "the platform cannot represent the target",
428 )
429 })?;
430 loop {
431 let scratch = format!("{SCRATCH_PREFIX}tmp-{}", random_hex());
432 match make_symlink(dir, target, &scratch) {
433 Ok(()) => return finish(dir, &scratch, name, Ok(())),
434 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
435 Err(err) => return Err(err),
436 }
437 }
438}
439
440#[cfg(unix)]
441fn make_symlink(dir: &Dir, target: &OsStr, name: &str) -> io::Result<()> {
442 dir.symlink_contents(target, name)
443}
444
445#[cfg(not(unix))]
446fn make_symlink(_dir: &Dir, _target: &OsStr, _name: &str) -> io::Result<()> {
447 Err(io::Error::new(
448 io::ErrorKind::Unsupported,
449 "symlinks are only written on Unix-like systems",
450 ))
451}
452
453/// Removes the file or symlink `name` from `dir`; nothing there is fine.
454pub(crate) fn remove_entry(dir: &Dir, name: &OsStr) -> io::Result<()> {
455 match dir.remove_file_or_symlink(name) {
456 Ok(()) => Ok(()),
457 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
458 Err(err) => Err(err),
459 }
460}
461
462fn create_scratch(dir: &Dir) -> io::Result<(String, File)> {
463 loop {
464 let name = format!("{SCRATCH_PREFIX}tmp-{}", random_hex());
465 let mut options = OpenOptions::new();
466 options.write(true).create_new(true);
467 #[cfg(unix)]
468 {
469 use cap_std::fs::OpenOptionsExt;
470 options.mode(0o600);
471 }
472 match dir.open_with(&name, &options) {
473 Ok(file) => return Ok((name, file)),
474 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
475 Err(err) => return Err(err),
476 }
477 }
478}
479
480/// Moves the scratch entry over `name` once it is written, removing an
481/// empty directory in the way first; removes the scratch entry on failure.
482fn finish(dir: &Dir, scratch: &str, name: &OsStr, written: io::Result<()>) -> io::Result<()> {
483 let result = written.and_then(|()| {
484 if let Ok(meta) = dir.symlink_metadata(name)
485 && meta.is_dir()
486 {
487 dir.remove_dir(name)?;
488 }
489 dir.rename(scratch, dir, name)
490 });
491 if result.is_err() {
492 let _ = dir.remove_file_or_symlink(scratch);
493 }
494 result
495}
496
497/// Sets a regular file's mode to exactly 0644, or 0755 if executable.
498#[cfg(unix)]
499fn set_mode(file: &File, executable: bool) -> io::Result<()> {
500 use cap_std::fs::PermissionsExt;
501 let mode = if executable { 0o755 } else { 0o644 };
502 file.set_permissions(cap_std::fs::Permissions::from_mode(mode))
503}
504
505/// Other systems have no executable bit.
506#[cfg(not(unix))]
507fn set_mode(_file: &File, _executable: bool) -> io::Result<()> {
508 Ok(())
509}