1use crate::logging::{debug, info, warn};
64use rand::Rng;
65use serde::{Deserialize, Serialize};
66use std::fs::{File, TryLockError};
67use std::io::{self, Read, Write};
68use std::path::{Path, PathBuf};
69use std::time::{SystemTime, UNIX_EPOCH};
70
71pub const MARKER_FILE: &str = ".ant-devnet-run.json";
73
74pub const LOCK_FILE: &str = ".ant-devnet-run.lock";
76
77const MARKER_TEMP_FILE: &str = ".ant-devnet-run.json.tmp";
80
81const MAX_MARKER_LEN: usize = 4096;
83
84const CREATE_ATTEMPTS: usize = 8;
86
87#[derive(Debug, Serialize, Deserialize)]
89struct Marker {
90 run_id: String,
92 file_id: u64,
94 lock_id: u64,
96 pid: u32,
98 started_at: u64,
100 version: String,
102 keep: bool,
104}
105
106#[derive(Debug, PartialEq, Eq)]
108struct FileId {
109 device: String,
112 file: u64,
114}
115
116pub struct RunDir {
121 path: PathBuf,
122 name: String,
123 run_id: String,
124 parent: Parent,
125 run: Run,
127 lock: File,
128}
129
130impl RunDir {
131 pub fn create(parent: &Path, keep: bool) -> io::Result<Self> {
143 let parent = Parent::open(parent)?;
144 sweep(&parent);
145
146 let pid = std::process::id();
147 let mut rng = rand::thread_rng();
148 let mut attempt = 0;
149 let name = loop {
150 let name = format!("{pid}-{:08x}", rng.gen::<u32>());
151 match parent.create_run(&name) {
152 Ok(()) => break name,
153 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
154 attempt += 1;
155 if attempt == CREATE_ATTEMPTS {
156 return Err(e);
157 }
158 }
159 Err(e) => return Err(e),
160 }
161 };
162
163 #[cfg(test)]
164 after_create(&parent.path.join(&name))?;
165 let run = parent.open_run(&name)?;
166 #[cfg(unix)]
171 let replaced = !run.is_empty()? || !run.is_owned_by_this_user()?;
172 #[cfg(windows)]
173 let replaced = !run.is_empty()?;
174 if replaced {
175 return Err(io::Error::new(
176 io::ErrorKind::AlreadyExists,
177 format!(
178 "{} was replaced before this run could open it",
179 parent.path.join(&name).display()
180 ),
181 ));
182 }
183 let claimed = run.id().and_then(|id| {
184 let mut marker = Marker {
185 run_id: hex::encode(rng.gen::<[u8; 16]>()),
186 file_id: id.file,
187 lock_id: 0,
189 pid,
190 started_at: SystemTime::now()
191 .duration_since(UNIX_EPOCH)
192 .map_or(0, |since| since.as_secs()),
193 version: env!("CARGO_PKG_VERSION").to_string(),
194 keep,
195 };
196 let lock = claim(&run, &mut marker)?;
197 Ok((marker.run_id, lock))
198 });
199 let (run_id, lock) = match claimed {
200 Ok(claimed) => claimed,
201 Err(e) => {
202 if let Err(cleanup) =
206 same_dir(&parent, &name, &run).and_then(|()| parent.remove_empty(&name, run))
207 {
208 warn!("Could not remove half-created devnet run directory {name}: {cleanup}");
209 }
210 return Err(e);
211 }
212 };
213
214 Ok(Self {
215 path: parent.path.join(&name),
216 name,
217 run_id,
218 parent,
219 run,
220 lock,
221 })
222 }
223
224 pub fn path(&self) -> &Path {
227 &self.path
228 }
229
230 pub fn remove(self) -> io::Result<()> {
239 let Self {
240 path,
241 name,
242 run_id,
243 parent,
244 run,
245 lock,
246 } = self;
247 let marker = read_marker(&run)?;
248 if marker.run_id != run_id || marker.file_id != run.id()?.file {
249 return Err(io::Error::new(
250 io::ErrorKind::InvalidData,
251 format!(
252 "{} is no longer this run's directory: its marker names another run",
253 path.display()
254 ),
255 ));
256 }
257 delete(&parent, &name, run, lock)
258 }
259
260 pub fn keep_locked_until_exit(self) {
264 let Self { lock, .. } = self;
265 std::mem::forget(lock);
266 }
267}
268
269fn claim(run: &Run, marker: &mut Marker) -> io::Result<File> {
274 let lock = run.create_file(LOCK_FILE)?;
275 let outcome = lock.try_lock().map_err(io::Error::from).and_then(|()| {
276 marker.lock_id = file_id(&lock)?.file;
277 write_marker(run, marker)
278 });
279 match outcome {
280 Ok(()) => Ok(lock),
281 Err(e) => {
282 drop(lock);
283 if let Err(cleanup) = run.remove_file(LOCK_FILE) {
284 warn!("Could not remove the lock file of a devnet run that failed to start: {cleanup}");
285 }
286 Err(e)
287 }
288 }
289}
290
291fn write_marker(run: &Run, marker: &Marker) -> io::Result<()> {
293 let json = serde_json::to_vec_pretty(marker).map_err(io::Error::other)?;
294 let mut temp = run.create_file(MARKER_TEMP_FILE)?;
295 let written = temp.write_all(&json).and_then(|()| temp.sync_all());
296 drop(temp);
297 let renamed = written.and_then(|()| run.rename(MARKER_TEMP_FILE, MARKER_FILE));
298 if renamed.is_err() {
299 if let Err(cleanup) = run.remove_file(MARKER_TEMP_FILE) {
300 warn!("Could not remove the marker of a devnet run that failed to start: {cleanup}");
301 }
302 }
303 renamed
304}
305
306fn read_marker(run: &Run) -> io::Result<Marker> {
307 let mut json = Vec::new();
308 run.open_file(MARKER_FILE)?
309 .take(MAX_MARKER_LEN as u64 + 1)
310 .read_to_end(&mut json)?;
311 if json.len() > MAX_MARKER_LEN {
312 return Err(io::Error::new(
313 io::ErrorKind::InvalidData,
314 "the marker is too large to be one",
315 ));
316 }
317 serde_json::from_slice(&json).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
318}
319
320fn same_dir(parent: &Parent, name: &str, run: &Run) -> io::Result<()> {
322 if parent.id_of(name)? == run.id()? {
323 Ok(())
324 } else {
325 Err(io::Error::new(
326 io::ErrorKind::InvalidData,
327 "it has been moved or replaced since it was opened",
328 ))
329 }
330}
331
332fn delete(parent: &Parent, name: &str, run: Run, lock: File) -> io::Result<()> {
339 same_dir(parent, name, &run)?;
344 run.remove_all_but(&[MARKER_FILE, LOCK_FILE])?;
345 run.remove_file(MARKER_FILE)?;
346 drop(lock);
348 run.remove_file(LOCK_FILE)?;
349 same_dir(parent, name, &run)?;
352 parent.remove_empty(name, run)
353}
354
355fn is_run_name(name: &str) -> bool {
357 name.split_once('-').is_some_and(|(pid, random)| {
358 !pid.is_empty()
359 && pid.bytes().all(|b| b.is_ascii_digit())
360 && random.len() == 8
361 && random
362 .bytes()
363 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
364 })
365}
366
367fn sweep(parent: &Parent) {
370 let names = match parent.names() {
371 Ok(names) => names,
372 Err(e) => {
373 warn!(
374 "Could not list {} for finished devnet runs: {e}",
375 parent.path.display()
376 );
377 return;
378 }
379 };
380 let mut removed = 0_usize;
381 for name in names.iter().filter(|name| is_run_name(name)) {
382 match finished_run(parent, name) {
383 Ok(Some((run, lock))) => {
384 #[cfg(test)]
385 after_found(&parent.path.join(name));
386 match delete(parent, name, run, lock) {
387 Ok(()) => removed += 1,
388 Err(e) => warn!(
389 "Could not remove the finished devnet run directory {}: {e}",
390 parent.path.join(name).display()
391 ),
392 }
393 }
394 Ok(None) => {}
395 Err(e) => debug!("Leaving {}: {e}", parent.path.join(name).display()),
396 }
397 }
398 if removed > 0 {
399 info!(
400 "Removed {removed} directories left by earlier devnet runs from {}",
401 parent.path.display()
402 );
403 }
404}
405
406fn finished_run(parent: &Parent, name: &str) -> io::Result<Option<(Run, File)>> {
409 let run = parent.open_run(name)?;
410 #[cfg(unix)]
413 if !run.is_owned_by_this_user()? {
414 return Ok(None);
415 }
416 let marker = read_marker(&run)?;
417 let pid_in_name = name.split_once('-').map(|(pid, _)| pid);
418 let id = run.id()?;
419 if marker.keep
420 || pid_in_name != Some(marker.pid.to_string().as_str())
421 || marker.file_id != id.file
422 || id.device != parent.id()?.device
423 {
424 return Ok(None);
425 }
426 #[cfg(unix)]
431 if run.mount()? != parent.mount()? {
432 return Ok(None);
433 }
434 let lock = run.open_file(LOCK_FILE)?;
435 let lock_id = file_id(&lock)?;
438 let the_runs_lock = lock_id.file == marker.lock_id;
439 if !the_runs_lock || lock_id.device != id.device {
440 return Ok(None);
441 }
442 match lock.try_lock() {
443 Ok(()) => Ok(Some((run, lock))),
446 Err(TryLockError::WouldBlock) => Ok(None),
447 Err(TryLockError::Error(e)) => Err(e),
448 }
449}
450
451#[cfg(test)]
452thread_local! {
453 static FAIL_AFTER: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
456 static AFTER_CREATE: std::cell::RefCell<Option<AfterCreate>> =
459 const { std::cell::RefCell::new(None) };
460 static AFTER_FOUND: std::cell::RefCell<Option<AfterFound>> =
463 const { std::cell::RefCell::new(None) };
464 #[cfg(unix)]
467 static MOUNT_POINT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
468}
469
470#[cfg(test)]
471type AfterCreate = Box<dyn FnOnce(&Path) -> io::Result<()>>;
472
473#[cfg(test)]
474type AfterFound = Box<dyn FnOnce(&Path)>;
475
476#[cfg(test)]
477fn after_create(path: &Path) -> io::Result<()> {
478 AFTER_CREATE
479 .with(|act| act.borrow_mut().take())
480 .map_or(Ok(()), |act| act(path))
481}
482
483#[cfg(test)]
484fn after_found(path: &Path) {
485 if let Some(act) = AFTER_FOUND.with(|act| act.borrow_mut().take()) {
486 act(path);
487 }
488}
489
490#[cfg(all(test, unix))]
491fn is_test_mount_point(name: &std::ffi::CStr) -> bool {
492 MOUNT_POINT.with(|mount| mount.borrow().as_deref().map(str::as_bytes) == Some(name.to_bytes()))
493}
494
495#[cfg(test)]
497fn injected_failure() -> io::Result<()> {
498 FAIL_AFTER.with(|left| match left.get() {
499 Some(0) => Err(io::Error::other("injected failure")),
500 Some(n) => {
501 left.set(Some(n - 1));
502 Ok(())
503 }
504 None => Ok(()),
505 })
506}
507
508#[cfg(unix)]
509use unix::{file_id, Parent, Run};
510
511#[cfg(windows)]
512use windows::{file_id, Parent, Run};
513
514#[cfg(unix)]
516mod unix {
517 use super::FileId;
518 use rustix::fs::{AtFlags, Dev, FileType, Mode, OFlags, Stat};
519 use rustix::io::Errno;
520 use std::ffi::{CStr, CString};
521 use std::fs::File;
522 use std::io;
523 use std::os::fd::OwnedFd;
524 use std::path::{Path, PathBuf};
525
526 const DIR_FLAGS: OFlags = OFlags::RDONLY
527 .union(OFlags::DIRECTORY)
528 .union(OFlags::NOFOLLOW)
529 .union(OFlags::CLOEXEC);
530
531 pub struct Parent {
533 pub path: PathBuf,
535 fd: OwnedFd,
536 }
537
538 pub struct Run {
540 fd: OwnedFd,
541 }
542
543 impl Parent {
544 pub fn open(path: &Path) -> io::Result<Self> {
545 std::fs::create_dir_all(path)?;
546 let real = std::fs::canonicalize(path)?;
547 no_one_else_can_change(&real)?;
548 let fd = rustix::fs::open(
549 &real,
550 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
551 Mode::empty(),
552 )?;
553 if std::fs::canonicalize(&real)? != real
556 || id(&rustix::fs::stat(&real)?) != id(&rustix::fs::fstat(&fd)?)
557 {
558 return Err(io::Error::new(
559 io::ErrorKind::InvalidData,
560 format!("{} changed while it was being opened", path.display()),
561 ));
562 }
563 Ok(Self { path: real, fd })
564 }
565
566 pub fn mount(&self) -> io::Result<Mount> {
567 mount_of(&self.fd)
568 }
569
570 pub fn create_run(&self, name: &str) -> io::Result<()> {
571 Ok(rustix::fs::mkdirat(
572 &self.fd,
573 name,
574 Mode::from_raw_mode(0o755),
575 )?)
576 }
577
578 pub fn open_run(&self, name: &str) -> io::Result<Run> {
579 let fd = rustix::fs::openat(&self.fd, name, DIR_FLAGS, Mode::empty())?;
580 Ok(Run { fd })
581 }
582
583 pub fn names(&self) -> io::Result<Vec<String>> {
584 Ok(read_names(&self.fd)?
585 .into_iter()
586 .filter_map(|name| name.into_string().ok())
587 .collect())
588 }
589
590 pub fn id(&self) -> io::Result<FileId> {
591 Ok(id(&rustix::fs::fstat(&self.fd)?))
592 }
593
594 pub fn id_of(&self, name: &str) -> io::Result<FileId> {
596 let stat = rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW)?;
597 if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
598 return Err(io::Error::new(
599 io::ErrorKind::InvalidData,
600 format!("{name} is not a directory"),
601 ));
602 }
603 Ok(id(&stat))
604 }
605
606 pub fn remove_empty(&self, name: &str, run: Run) -> io::Result<()> {
609 drop(run);
610 gone_is_fine(rustix::fs::unlinkat(&self.fd, name, AtFlags::REMOVEDIR))
611 }
612 }
613
614 impl Run {
615 pub fn id(&self) -> io::Result<FileId> {
616 Ok(id(&rustix::fs::fstat(&self.fd)?))
617 }
618
619 pub fn is_empty(&self) -> io::Result<bool> {
620 Ok(read_names(&self.fd)?.is_empty())
621 }
622
623 pub fn is_owned_by_this_user(&self) -> io::Result<bool> {
624 Ok(rustix::fs::fstat(&self.fd)?.st_uid == rustix::process::geteuid().as_raw())
625 }
626
627 pub fn mount(&self) -> io::Result<Mount> {
628 mount_of(&self.fd)
629 }
630
631 pub fn create_file(&self, name: &str) -> io::Result<File> {
632 let fd = rustix::fs::openat(
633 &self.fd,
634 name,
635 OFlags::RDWR | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
636 Mode::from_raw_mode(0o644),
637 )?;
638 Ok(File::from(fd))
639 }
640
641 pub fn open_file(&self, name: &str) -> io::Result<File> {
644 let fd = rustix::fs::openat(
645 &self.fd,
646 name,
647 OFlags::RDWR | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
648 Mode::empty(),
649 )?;
650 if FileType::from_raw_mode(rustix::fs::fstat(&fd)?.st_mode) != FileType::RegularFile {
651 return Err(io::Error::new(
652 io::ErrorKind::InvalidData,
653 format!("{name} is not a regular file"),
654 ));
655 }
656 Ok(File::from(fd))
657 }
658
659 pub fn rename(&self, from: &str, to: &str) -> io::Result<()> {
660 Ok(rustix::fs::renameat(&self.fd, from, &self.fd, to)?)
661 }
662
663 pub fn remove_file(&self, name: &str) -> io::Result<()> {
664 gone_is_fine(rustix::fs::unlinkat(&self.fd, name, AtFlags::empty()))
665 }
666
667 pub fn remove_all_but(&self, keep: &[&str]) -> io::Result<()> {
669 let mount = mount_of(&self.fd)?;
670 for name in read_names(&self.fd)? {
671 if keep.iter().any(|keep| keep.as_bytes() == name.as_bytes()) {
672 continue;
673 }
674 #[cfg(test)]
675 super::injected_failure()?;
676 remove_entry(&self.fd, &name, &mount)?;
677 }
678 Ok(())
679 }
680 }
681
682 pub fn file_id(file: &File) -> io::Result<FileId> {
683 Ok(id(&rustix::fs::fstat(file)?))
684 }
685
686 fn id(stat: &Stat) -> FileId {
687 FileId {
688 device: stat.st_dev.to_string(),
689 file: stat.st_ino,
690 }
691 }
692
693 fn no_one_else_can_change(real: &Path) -> io::Result<()> {
699 let uid = rustix::process::geteuid().as_raw();
700 for dir in real.ancestors() {
701 let stat = rustix::fs::lstat(dir)?;
702 if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
703 return Err(io::Error::new(
704 io::ErrorKind::InvalidData,
705 format!("{} changed while it was being opened", real.display()),
706 ));
707 }
708 let mode = Mode::from_raw_mode(stat.st_mode);
709 let who = if stat.st_uid != 0 && stat.st_uid != uid {
710 Some(format!("belongs to user {}", stat.st_uid))
711 } else if mode.contains(Mode::SVTX) {
712 None
713 } else if mode.contains(Mode::WOTH) {
714 Some("can be written to by every user".to_string())
715 } else if mode.contains(Mode::WGRP) {
716 group_writers(dir, &stat)?
717 } else {
718 None
719 };
720 if let Some(who) = who {
721 return Err(io::Error::new(
722 io::ErrorKind::PermissionDenied,
723 format!(
724 "{} {who}, so another user could move or redirect a devnet's \
725 data under it: use a data directory that only you and root \
726 can change, with only such directories above it",
727 dir.display()
728 ),
729 ));
730 }
731 }
732 Ok(())
733 }
734
735 fn group_writers(dir: &Path, stat: &Stat) -> io::Result<Option<String>> {
737 #[cfg(target_os = "linux")]
741 if stat.st_gid == rustix::process::getegid().as_raw() {
742 return match rustix::fs::lgetxattr(dir, "system.posix_acl_access", &mut [0_u8; 0]) {
745 Ok(_) => Ok(Some(
746 "has an ACL, which can let other users write to it".to_string(),
747 )),
748 Err(Errno::NODATA | Errno::OPNOTSUPP) => Ok(None),
749 Err(e) => Err(e.into()),
750 };
751 }
752 #[cfg(not(target_os = "linux"))]
753 let _ = dir;
754 Ok(Some(format!("can be written to by group {}", stat.st_gid)))
755 }
756
757 #[derive(Debug, PartialEq, Eq)]
760 pub struct Mount {
761 device: Dev,
762 #[cfg(target_os = "linux")]
763 id: u64,
764 }
765
766 pub(super) fn mount_of(dir: &OwnedFd) -> io::Result<Mount> {
769 let device = rustix::fs::fstat(dir)?.st_dev;
770 #[cfg(target_os = "linux")]
771 {
772 use rustix::fs::StatxFlags;
773 let unsupported = || {
774 io::Error::new(
775 io::ErrorKind::Unsupported,
776 "cannot tell a bind mount from the directory it is in: that needs \
777 mount ids, from Linux 5.8, and `statx` allowed",
778 )
779 };
780 let statx = match rustix::fs::statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) {
781 Ok(statx) => statx,
782 Err(Errno::NOSYS | Errno::PERM) => return Err(unsupported()),
783 Err(e) => return Err(e.into()),
784 };
785 if statx.stx_mask & StatxFlags::MNT_ID.bits() == 0 {
786 return Err(unsupported());
787 }
788 Ok(Mount {
789 device,
790 id: statx.stx_mnt_id,
791 })
792 }
793 #[cfg(target_os = "macos")]
795 {
796 Ok(Mount { device })
797 }
798 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
799 {
800 let _ = device;
801 Err(io::Error::new(
802 io::ErrorKind::Unsupported,
803 "cannot tell mounts apart on this system",
804 ))
805 }
806 }
807
808 fn remove_entry(dir: &OwnedFd, name: &CStr, mount: &Mount) -> io::Result<()> {
812 let stat = match rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
813 Ok(stat) => stat,
814 Err(Errno::NOENT) => return Ok(()),
815 Err(e) => return Err(e.into()),
816 };
817 if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
818 return gone_is_fine(rustix::fs::unlinkat(dir, name, AtFlags::empty()));
819 }
820 let child = match rustix::fs::openat(dir, name, DIR_FLAGS, Mode::empty()) {
821 Ok(child) => child,
822 Err(Errno::NOENT) => return Ok(()),
823 Err(e) => return Err(e.into()),
824 };
825 #[cfg(not(test))]
826 let mount_point = mount_of(&child)? != *mount;
827 #[cfg(test)]
828 let mount_point = mount_of(&child)? != *mount || super::is_test_mount_point(name);
829 if mount_point {
830 return Err(io::Error::new(
831 io::ErrorKind::InvalidData,
832 format!(
833 "{} is a mount point, so it and what is in it are left",
834 name.to_string_lossy()
835 ),
836 ));
837 }
838 for entry in read_names(&child)? {
839 remove_entry(&child, &entry, mount)?;
840 }
841 gone_is_fine(rustix::fs::unlinkat(dir, name, AtFlags::REMOVEDIR))
842 }
843
844 fn read_names(dir: &OwnedFd) -> io::Result<Vec<CString>> {
848 let mut names = Vec::new();
849 for entry in rustix::fs::Dir::read_from(dir)? {
850 let name = entry?.file_name().to_owned();
851 if name.as_bytes() != b"." && name.as_bytes() != b".." {
852 names.push(name);
853 }
854 }
855 Ok(names)
856 }
857
858 fn gone_is_fine(result: rustix::io::Result<()>) -> io::Result<()> {
860 match result {
861 Ok(()) | Err(Errno::NOENT) => Ok(()),
862 Err(e) => Err(e.into()),
863 }
864 }
865}
866
867#[cfg(windows)]
870mod windows {
871 use super::FileId;
872 use std::fs::{File, OpenOptions};
873 use std::io;
874 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
875 use std::path::{Path, PathBuf};
876
877 const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
879 const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
881 const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
882 const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
883 const SHARE_ALL_BUT_DELETE: u32 = 0x1 | 0x2;
885
886 pub struct Parent {
888 pub path: PathBuf,
890 real: PathBuf,
892 held: File,
893 }
894
895 pub struct Run {
897 path: PathBuf,
898 held: File,
899 }
900
901 impl Parent {
902 pub fn open(path: &Path) -> io::Result<Self> {
903 std::fs::create_dir_all(path)?;
904 let real = std::fs::canonicalize(path)?;
905 let held = hold_dir(&real)?;
906 if std::fs::canonicalize(&real)? != real {
909 return Err(io::Error::new(
910 io::ErrorKind::InvalidData,
911 format!("{} changed while it was being opened", path.display()),
912 ));
913 }
914 Ok(Self {
915 path: plain(&real),
916 real,
917 held,
918 })
919 }
920
921 pub fn create_run(&self, name: &str) -> io::Result<()> {
922 std::fs::create_dir(self.real.join(name))
923 }
924
925 pub fn open_run(&self, name: &str) -> io::Result<Run> {
926 let path = self.real.join(name);
927 let held = hold_dir(&path)?;
928 Ok(Run { path, held })
929 }
930
931 pub fn names(&self) -> io::Result<Vec<String>> {
932 let mut names = Vec::new();
933 for entry in std::fs::read_dir(&self.real)? {
934 if let Ok(name) = entry?.file_name().into_string() {
935 names.push(name);
936 }
937 }
938 Ok(names)
939 }
940
941 pub fn id(&self) -> io::Result<FileId> {
942 file_id(&self.held)
943 }
944
945 pub fn id_of(&self, name: &str) -> io::Result<FileId> {
947 file_id(&hold_dir(&self.real.join(name))?)
948 }
949
950 pub fn remove_empty(&self, name: &str, run: Run) -> io::Result<()> {
953 drop(run);
954 gone_is_fine(std::fs::remove_dir(self.real.join(name)))
955 }
956 }
957
958 impl Run {
959 pub fn id(&self) -> io::Result<FileId> {
960 file_id(&self.held)
961 }
962
963 pub fn is_empty(&self) -> io::Result<bool> {
964 Ok(std::fs::read_dir(&self.path)?.next().is_none())
965 }
966
967 pub fn create_file(&self, name: &str) -> io::Result<File> {
968 OpenOptions::new()
969 .read(true)
970 .write(true)
971 .create_new(true)
972 .open(self.path.join(name))
973 }
974
975 pub fn open_file(&self, name: &str) -> io::Result<File> {
978 let file = OpenOptions::new()
979 .read(true)
980 .write(true)
981 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
982 .open(self.path.join(name))?;
983 let meta = file.metadata()?;
984 if !meta.is_file() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
985 return Err(io::Error::new(
986 io::ErrorKind::InvalidData,
987 format!("{name} is not a regular file"),
988 ));
989 }
990 Ok(file)
991 }
992
993 pub fn rename(&self, from: &str, to: &str) -> io::Result<()> {
994 std::fs::rename(self.path.join(from), self.path.join(to))
995 }
996
997 pub fn remove_file(&self, name: &str) -> io::Result<()> {
998 gone_is_fine(std::fs::remove_file(self.path.join(name)))
999 }
1000
1001 pub fn remove_all_but(&self, keep: &[&str]) -> io::Result<()> {
1003 for entry in std::fs::read_dir(&self.path)? {
1004 let entry = entry?;
1005 if keep.iter().any(|keep| entry.file_name() == *keep) {
1006 continue;
1007 }
1008 #[cfg(test)]
1009 super::injected_failure()?;
1010 let path = entry.path();
1014 gone_is_fine(
1015 if entry.metadata()?.file_attributes() & FILE_ATTRIBUTE_DIRECTORY == 0 {
1016 std::fs::remove_file(path)
1017 } else {
1018 std::fs::remove_dir_all(path)
1019 },
1020 )?;
1021 }
1022 Ok(())
1023 }
1024 }
1025
1026 fn plain(real: &Path) -> PathBuf {
1030 real.to_str()
1031 .and_then(|text| text.strip_prefix(r"\\?\"))
1032 .map(PathBuf::from)
1033 .filter(|plain| std::fs::canonicalize(plain).is_ok_and(|again| again == real))
1034 .unwrap_or_else(|| real.to_path_buf())
1035 }
1036
1037 fn hold_dir(path: &Path) -> io::Result<File> {
1039 let dir = OpenOptions::new()
1040 .read(true)
1041 .share_mode(SHARE_ALL_BUT_DELETE)
1042 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1043 .open(path)?;
1044 let meta = dir.metadata()?;
1045 if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1046 return Err(io::Error::new(
1047 io::ErrorKind::InvalidData,
1048 format!("{} is not a directory", path.display()),
1049 ));
1050 }
1051 Ok(dir)
1052 }
1053
1054 pub fn file_id(file: &File) -> io::Result<FileId> {
1055 let info = winapi_util::file::information(file)?;
1056 Ok(FileId {
1057 device: info.volume_serial_number().to_string(),
1058 file: info.file_index(),
1059 })
1060 }
1061
1062 fn gone_is_fine(result: io::Result<()>) -> io::Result<()> {
1064 match result {
1065 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
1066 result => result,
1067 }
1068 }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073 use super::*;
1074
1075 type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
1076
1077 fn marker_in(dir: &Path) -> std::result::Result<Marker, Box<dyn std::error::Error>> {
1078 Ok(serde_json::from_slice(&std::fs::read(
1079 dir.join(MARKER_FILE),
1080 )?)?)
1081 }
1082
1083 fn lock_is_free(dir: &Path) -> std::result::Result<bool, Box<dyn std::error::Error>> {
1085 let lock = File::options()
1086 .read(true)
1087 .write(true)
1088 .open(dir.join(LOCK_FILE))?;
1089 match lock.try_lock() {
1090 Ok(()) => Ok(true),
1091 Err(TryLockError::WouldBlock) => Ok(false),
1092 Err(TryLockError::Error(e)) => Err(e.into()),
1093 }
1094 }
1095
1096 fn file_id_of(path: &Path) -> std::result::Result<u64, Box<dyn std::error::Error>> {
1097 Ok(file_id(&File::open(path)?)?.file)
1098 }
1099
1100 fn finished(
1102 parent: &Path,
1103 keep: bool,
1104 ) -> std::result::Result<PathBuf, Box<dyn std::error::Error>> {
1105 let run = RunDir::create(parent, keep)?;
1106 let path = run.path().to_path_buf();
1107 std::fs::create_dir_all(path.join("nodes").join("peer"))?;
1108 std::fs::write(path.join("nodes").join("peer").join("chunk"), b"data")?;
1109 drop(run);
1110 Ok(path)
1111 }
1112
1113 fn forged(
1117 parent: &Path,
1118 name: &str,
1119 edit: impl FnOnce(&mut Marker),
1120 ) -> std::result::Result<PathBuf, Box<dyn std::error::Error>> {
1121 let dir = parent.join(name);
1122 std::fs::create_dir_all(&dir)?;
1123 let file_id = Parent::open(parent)?.open_run(name)?.id()?.file;
1124 std::fs::write(dir.join(LOCK_FILE), b"")?;
1125 let lock_id = file_id_of(&dir.join(LOCK_FILE))?;
1126 let mut marker = Marker {
1127 run_id: "forged".to_string(),
1128 file_id,
1129 lock_id,
1130 pid: std::process::id(),
1131 started_at: 0,
1132 version: env!("CARGO_PKG_VERSION").to_string(),
1133 keep: false,
1134 };
1135 edit(&mut marker);
1136 std::fs::write(dir.join(MARKER_FILE), serde_json::to_vec(&marker)?)?;
1137 std::fs::write(dir.join("sentinel"), b"keep")?;
1138 Ok(dir)
1139 }
1140
1141 #[test]
1142 fn create_makes_a_locked_marked_directory_inside_the_parent() -> TestResult {
1143 let temp = tempfile::tempdir()?;
1144 let parent = temp.path().join("not").join("there").join("yet");
1145
1146 let run = RunDir::create(&parent, false)?;
1147
1148 assert_eq!(
1149 run.path().parent().map(std::fs::canonicalize).transpose()?,
1150 Some(std::fs::canonicalize(&parent)?)
1151 );
1152 #[cfg(windows)]
1153 assert!(
1154 !run.path().to_string_lossy().starts_with(r"\\?\"),
1155 "{}",
1156 run.path().display()
1157 );
1158 let name = run
1159 .path()
1160 .file_name()
1161 .and_then(|name| name.to_str())
1162 .ok_or("no name")?;
1163 assert!(is_run_name(name), "{name}");
1164 let marker = marker_in(run.path())?;
1165 assert_eq!(marker.pid, std::process::id());
1166 assert_eq!(marker.run_id, run.run_id);
1167 assert_eq!(marker.file_id, run.run.id()?.file);
1168 assert_eq!(marker.lock_id, file_id(&run.lock)?.file);
1169 assert!(!marker.keep);
1170 assert!(!run.path().join(MARKER_TEMP_FILE).exists());
1171 assert!(
1172 !lock_is_free(run.path())?,
1173 "the lock is free while the run lasts"
1174 );
1175 Ok(())
1176 }
1177
1178 #[test]
1179 fn remove_deletes_the_run_directory_and_nothing_beside_it() -> TestResult {
1180 let temp = tempfile::tempdir()?;
1181 let parent = temp.path().join("devnets");
1182 std::fs::create_dir_all(parent.join("mine"))?;
1183 std::fs::write(parent.join("mine").join("sentinel"), b"keep")?;
1184 std::fs::write(temp.path().join("sentinel"), b"keep")?;
1185
1186 let run = RunDir::create(&parent, false)?;
1187 let path = run.path().to_path_buf();
1188 std::fs::create_dir_all(path.join("nodes").join("peer").join("deeper"))?;
1189 std::fs::write(
1190 path.join("nodes").join("peer").join("deeper").join("f"),
1191 b"x",
1192 )?;
1193 run.remove()?;
1194
1195 assert!(!path.exists());
1196 assert!(parent.is_dir(), "the parent is not the run's to delete");
1197 assert!(parent.join("mine").join("sentinel").is_file());
1198 assert!(temp.path().join("sentinel").is_file());
1199 Ok(())
1200 }
1201
1202 #[test]
1203 fn remove_refuses_a_directory_another_run_has_marked() -> TestResult {
1204 let temp = tempfile::tempdir()?;
1205 let run = RunDir::create(temp.path(), false)?;
1206 let path = run.path().to_path_buf();
1207 let mut marker = marker_in(&path)?;
1208 marker.run_id = "someone-else".to_string();
1209 std::fs::write(path.join(MARKER_FILE), serde_json::to_vec(&marker)?)?;
1210
1211 assert!(run.remove().is_err());
1212 assert!(path.join(MARKER_FILE).is_file());
1213 Ok(())
1214 }
1215
1216 #[cfg(unix)]
1220 #[test]
1221 fn remove_refuses_a_replacement_carrying_a_copy_of_the_marker() -> TestResult {
1222 let temp = tempfile::tempdir()?;
1223 let run = RunDir::create(temp.path(), false)?;
1224 let path = run.path().to_path_buf();
1225 std::fs::write(path.join("data"), b"the run's")?;
1226 let moved = temp.path().join("moved");
1227 std::fs::rename(&path, &moved)?;
1228 std::fs::create_dir(&path)?;
1229 std::fs::copy(moved.join(MARKER_FILE), path.join(MARKER_FILE))?;
1230 std::fs::copy(moved.join(LOCK_FILE), path.join(LOCK_FILE))?;
1231 std::fs::write(path.join("sentinel"), b"not the run's")?;
1232
1233 assert!(run.remove().is_err());
1234 assert!(path.join("sentinel").is_file());
1235 assert!(path.join(MARKER_FILE).is_file());
1236 assert!(moved.join("data").is_file());
1237 Ok(())
1238 }
1239
1240 #[cfg(windows)]
1245 #[test]
1246 fn a_run_directory_and_every_directory_above_it_cannot_be_moved_while_the_run_lasts(
1247 ) -> TestResult {
1248 let temp = tempfile::tempdir()?;
1249 let above = temp.path().join("above");
1250 let parent = above.join("devnets");
1251 let run = RunDir::create(&parent, false)?;
1252 let path = run.path().to_path_buf();
1253
1254 assert!(std::fs::rename(&path, parent.join("moved")).is_err());
1255 assert!(std::fs::rename(&parent, above.join("moved")).is_err());
1256 assert!(std::fs::rename(&above, temp.path().join("moved")).is_err());
1257 let temp_moved = temp.path().with_extension("moved");
1258 assert!(std::fs::rename(temp.path(), &temp_moved).is_err());
1259
1260 run.remove()?;
1261 assert!(!path.exists());
1262 Ok(())
1263 }
1264
1265 #[test]
1266 fn the_next_run_sweeps_a_finished_run() -> TestResult {
1267 let temp = tempfile::tempdir()?;
1268 let old = finished(temp.path(), false)?;
1269 assert!(old.is_dir());
1270
1271 let run = RunDir::create(temp.path(), false)?;
1272
1273 assert!(!old.exists(), "{} was not swept", old.display());
1274 assert!(run.path().is_dir());
1275 Ok(())
1276 }
1277
1278 #[test]
1282 fn a_removal_that_stops_part_way_is_finished_by_the_next_run() -> TestResult {
1283 let temp = tempfile::tempdir()?;
1284 let run = RunDir::create(temp.path(), false)?;
1285 let path = run.path().to_path_buf();
1286 for i in 0..4 {
1287 std::fs::create_dir_all(path.join(format!("node-{i}")))?;
1288 std::fs::write(path.join(format!("node-{i}")).join("chunk"), b"data")?;
1289 }
1290
1291 FAIL_AFTER.with(|left| left.set(Some(2)));
1292 let stopped = run.remove();
1293 FAIL_AFTER.with(|left| left.set(None));
1294
1295 assert!(stopped.is_err());
1296 assert!(path.join(MARKER_FILE).is_file());
1297 assert!(path.join(LOCK_FILE).is_file());
1298 let _next = RunDir::create(temp.path(), false)?;
1299 assert!(!path.exists(), "{} was not swept", path.display());
1300 Ok(())
1301 }
1302
1303 #[test]
1304 fn a_live_run_is_never_swept() -> TestResult {
1305 let temp = tempfile::tempdir()?;
1306 let first = RunDir::create(temp.path(), false)?;
1307 let second = RunDir::create(temp.path(), false)?;
1308
1309 assert!(first.path().join(MARKER_FILE).is_file());
1310 assert!(second.path().join(MARKER_FILE).is_file());
1311 assert_ne!(first.path(), second.path());
1312 Ok(())
1313 }
1314
1315 #[test]
1316 fn a_run_kept_locked_until_exit_is_never_swept() -> TestResult {
1317 let temp = tempfile::tempdir()?;
1318 let run = RunDir::create(temp.path(), false)?;
1319 let path = run.path().to_path_buf();
1320 run.keep_locked_until_exit();
1321
1322 let _next = RunDir::create(temp.path(), false)?;
1323
1324 assert!(path.join(MARKER_FILE).is_file());
1325 assert!(!lock_is_free(&path)?);
1326 Ok(())
1327 }
1328
1329 #[test]
1333 fn a_live_run_whose_lock_file_is_replaced_is_never_swept() -> TestResult {
1334 let temp = tempfile::tempdir()?;
1335 let run = RunDir::create(temp.path(), false)?;
1336 let path = run.path().to_path_buf();
1337 std::fs::write(path.join("data"), b"the run's")?;
1338 std::fs::rename(path.join(LOCK_FILE), path.join("moved.lock"))?;
1339 std::fs::write(path.join(LOCK_FILE), b"")?;
1340 assert!(lock_is_free(&path)?);
1341
1342 let _next = RunDir::create(temp.path(), false)?;
1343
1344 assert!(path.join("data").is_file(), "{} was swept", path.display());
1345 drop(run);
1346 Ok(())
1347 }
1348
1349 #[test]
1354 fn a_directory_put_in_place_of_a_new_run_directory_is_left_alone() -> TestResult {
1355 for with_lock in [false, true] {
1356 let temp = tempfile::tempdir()?;
1357 let parent = temp.path().join("devnets");
1358 let moved = temp.path().join("moved");
1359 let replaced = std::rc::Rc::new(std::cell::RefCell::new(None));
1360 let record = std::rc::Rc::clone(&replaced);
1361 AFTER_CREATE.with(|act| {
1362 *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1363 std::fs::rename(path, &moved)?;
1364 std::fs::create_dir(path)?;
1365 std::fs::write(path.join("sentinel"), b"not the run's")?;
1366 if with_lock {
1367 std::fs::write(path.join(LOCK_FILE), b"not the run's")?;
1368 }
1369 *record.borrow_mut() = Some(path.to_path_buf());
1370 Ok(())
1371 }));
1372 });
1373
1374 let created = RunDir::create(&parent, false);
1375 AFTER_CREATE.with(|act| act.borrow_mut().take());
1376
1377 assert!(created.is_err(), "with_lock: {with_lock}");
1378 let path = replaced.borrow_mut().take().ok_or("never replaced")?;
1379 assert!(path.join("sentinel").is_file(), "with_lock: {with_lock}");
1380 assert!(!path.join(MARKER_FILE).exists(), "with_lock: {with_lock}");
1381 assert_eq!(path.join(LOCK_FILE).is_file(), with_lock);
1382 }
1383 Ok(())
1384 }
1385
1386 #[test]
1387 fn a_kept_run_is_never_swept() -> TestResult {
1388 let temp = tempfile::tempdir()?;
1389 let kept = finished(temp.path(), true)?;
1390 assert!(marker_in(&kept)?.keep);
1391
1392 let _run = RunDir::create(temp.path(), false)?;
1393
1394 assert!(kept.join("nodes").join("peer").join("chunk").is_file());
1395 Ok(())
1396 }
1397
1398 #[test]
1402 fn a_copy_of_a_finished_runs_marker_is_never_swept() -> TestResult {
1403 let temp = tempfile::tempdir()?;
1404 let old = finished(temp.path(), false)?;
1405 let moved = temp.path().join("moved");
1406 std::fs::rename(&old, &moved)?;
1407 std::fs::create_dir(&old)?;
1408 std::fs::copy(moved.join(MARKER_FILE), old.join(MARKER_FILE))?;
1409 std::fs::rename(moved.join(LOCK_FILE), old.join(LOCK_FILE))?;
1410 std::fs::write(old.join("sentinel"), b"keep")?;
1411
1412 let _run = RunDir::create(temp.path(), false)?;
1413
1414 assert!(old.join("sentinel").is_file());
1415 assert!(moved.join("nodes").join("peer").join("chunk").is_file());
1416 Ok(())
1417 }
1418
1419 #[test]
1423 fn a_finished_run_moved_once_it_is_found_is_left() -> TestResult {
1424 let temp = tempfile::tempdir()?;
1425 let old = finished(temp.path(), false)?;
1426 let moved = temp.path().join("moved");
1427 let to = moved.clone();
1428 let outcome = std::rc::Rc::new(std::cell::RefCell::new(None));
1429 let record = std::rc::Rc::clone(&outcome);
1430 AFTER_FOUND.with(|act| {
1431 *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1432 *record.borrow_mut() = Some(std::fs::rename(path, &to).is_ok());
1433 }));
1434 });
1435
1436 let created = RunDir::create(temp.path(), false);
1437 AFTER_FOUND.with(|act| act.borrow_mut().take());
1438 let _run = created?;
1439
1440 let was_moved = outcome.borrow_mut().take().ok_or("never found")?;
1441 if cfg!(windows) {
1442 assert!(!was_moved, "moved while the sweep held it");
1443 assert!(!old.exists(), "{} was not swept", old.display());
1444 } else {
1445 assert!(was_moved);
1446 assert!(
1447 moved.join("nodes").join("peer").join("chunk").is_file(),
1448 "emptied where it was moved to"
1449 );
1450 assert!(moved.join(MARKER_FILE).is_file());
1451 }
1452 Ok(())
1453 }
1454
1455 #[test]
1456 fn directories_without_a_matching_marker_are_never_swept() -> TestResult {
1457 let temp = tempfile::tempdir()?;
1458 let parent = temp.path();
1459 let pid = std::process::id();
1460 let survivors = [
1461 {
1463 let dir = parent.join("1-deadbeef");
1464 std::fs::create_dir_all(&dir)?;
1465 std::fs::write(dir.join("sentinel"), b"keep")?;
1466 dir
1467 },
1468 forged(parent, "other", |_| {})?,
1470 forged(parent, &format!("{pid}-DEADBEEF"), |_| {})?,
1471 forged(parent, &format!("{pid}-deadbeef0"), |_| {})?,
1472 forged(parent, &format!("{}-deadbeef", pid.wrapping_add(1)), |_| {})?,
1474 forged(parent, &format!("{pid}-d1ffe4e7"), |marker| {
1476 marker.file_id = marker.file_id.wrapping_add(1);
1477 })?,
1478 forged(parent, &format!("{pid}-10c4ed00"), |marker| {
1480 marker.lock_id = marker.lock_id.wrapping_add(1);
1481 })?,
1482 forged(parent, &format!("{pid}-cee9cee9"), |marker| {
1484 marker.keep = true;
1485 })?,
1486 {
1488 let dir = forged(parent, &format!("{pid}-0badf00d"), |_| {})?;
1489 std::fs::write(dir.join(MARKER_FILE), b"{ not json")?;
1490 dir
1491 },
1492 {
1493 let dir = forged(parent, &format!("{pid}-0ddba11a"), |_| {})?;
1494 let mut big = std::fs::read(dir.join(MARKER_FILE))?;
1495 big.resize(MAX_MARKER_LEN + 1, b' ');
1496 std::fs::write(dir.join(MARKER_FILE), big)?;
1497 dir
1498 },
1499 {
1501 let dir = forged(parent, &format!("{pid}-ca11ab1e"), |_| {})?;
1502 std::fs::remove_file(dir.join(LOCK_FILE))?;
1503 dir
1504 },
1505 ];
1506 let control = forged(parent, &format!("{pid}-c0ffee00"), |_| {})?;
1509
1510 let _run = RunDir::create(parent, false)?;
1511
1512 for dir in &survivors {
1513 assert!(
1514 dir.join("sentinel").is_file(),
1515 "{} was swept",
1516 dir.display()
1517 );
1518 }
1519 assert!(!control.exists(), "{} was not swept", control.display());
1520 Ok(())
1521 }
1522
1523 #[test]
1524 fn run_names() {
1525 assert!(is_run_name("1-deadbeef"));
1526 assert!(is_run_name("123456-0000000a"));
1527 for name in [
1528 "",
1529 "-deadbeef",
1530 "1-",
1531 "1-deadbee",
1532 "1-deadbeef0",
1533 "1-DEADBEEF",
1534 "a-deadbeef",
1535 "1_deadbeef",
1536 "1-deadbeeg",
1537 "1-dead-bee",
1538 ] {
1539 assert!(!is_run_name(name), "{name}");
1540 }
1541 }
1542
1543 #[cfg(unix)]
1547 #[test]
1548 fn removal_does_not_cross_into_another_mount() -> TestResult {
1549 let temp = tempfile::tempdir()?;
1550 let run = RunDir::create(temp.path(), false)?;
1551 let path = run.path().to_path_buf();
1552 let mounted = path.join("nodes").join("mounted");
1553 std::fs::create_dir_all(&mounted)?;
1554 std::fs::write(mounted.join("data"), b"not the run's")?;
1555
1556 MOUNT_POINT.with(|mount| *mount.borrow_mut() = Some("mounted".to_string()));
1557 let removed = run.remove();
1558 MOUNT_POINT.with(|mount| mount.borrow_mut().take());
1559
1560 assert!(removed.is_err());
1561 assert!(mounted.join("data").is_file());
1562 assert!(path.join(MARKER_FILE).is_file());
1563 Ok(())
1564 }
1565
1566 #[cfg(target_os = "linux")]
1568 fn sudo(args: &[&std::ffi::OsStr], path: &Path) -> io::Result<()> {
1569 let status = std::process::Command::new("sudo")
1570 .arg("-n")
1571 .args(args)
1572 .arg(path)
1573 .status()?;
1574 if status.success() {
1575 Ok(())
1576 } else {
1577 Err(io::Error::other(format!(
1578 "sudo {args:?} {} failed",
1579 path.display()
1580 )))
1581 }
1582 }
1583
1584 #[cfg(target_os = "linux")]
1586 struct Mounted(PathBuf);
1587
1588 #[cfg(target_os = "linux")]
1589 impl Mounted {
1590 fn new(at: &Path, how: &[&std::ffi::OsStr]) -> io::Result<Self> {
1591 sudo(&[&[std::ffi::OsStr::new("mount")], how].concat(), at)?;
1592 Ok(Self(at.to_path_buf()))
1593 }
1594 }
1595
1596 #[cfg(target_os = "linux")]
1597 impl Drop for Mounted {
1598 fn drop(&mut self) {
1599 if let Err(e) = sudo(&[std::ffi::OsStr::new("umount")], &self.0) {
1600 eprintln!("{e}");
1601 }
1602 }
1603 }
1604
1605 #[cfg(target_os = "linux")]
1607 fn nobody_moves(from: &Path, to: &Path) -> io::Result<bool> {
1608 Ok(std::process::Command::new("sudo")
1609 .args(["-n", "-u", "nobody", "mv"])
1610 .arg(from)
1611 .arg(to)
1612 .stderr(std::process::Stdio::null())
1613 .status()?
1614 .success())
1615 }
1616
1617 #[cfg(target_os = "linux")]
1622 #[test]
1623 #[ignore = "mounts through sudo; CI runs it"]
1624 fn with_sudo_mounts_inside_a_run_directory_are_not_crossed() -> TestResult {
1625 use std::ffi::OsStr;
1626 for bind in [false, true] {
1627 let temp = tempfile::tempdir()?;
1628 let source = temp.path().join("source");
1629 std::fs::create_dir(&source)?;
1630 std::fs::write(source.join("data"), b"not the run's")?;
1631 let run = RunDir::create(&temp.path().join("devnets"), false)?;
1632 let path = run.path().to_path_buf();
1633 let at = path.join("nodes").join("mounted");
1634 std::fs::create_dir_all(&at)?;
1635 let _mounted = if bind {
1636 Mounted::new(&at, &[OsStr::new("--bind"), source.as_os_str()])?
1637 } else {
1638 let tmpfs = ["-t", "tmpfs", "-o", "mode=1777", "none"].map(OsStr::new);
1639 let mounted = Mounted::new(&at, &tmpfs)?;
1640 std::fs::write(at.join("data"), b"not the run's")?;
1641 mounted
1642 };
1643
1644 assert!(run.remove().is_err(), "bind: {bind}");
1645 assert!(at.join("data").is_file(), "bind: {bind}");
1646 assert!(source.join("data").is_file(), "bind: {bind}");
1647 assert!(path.join(MARKER_FILE).is_file(), "bind: {bind}");
1648 }
1649 Ok(())
1650 }
1651
1652 #[cfg(target_os = "linux")]
1657 #[test]
1658 #[ignore = "mounts through sudo; CI runs it"]
1659 fn with_sudo_a_mount_wearing_a_finished_runs_name_is_not_swept() -> TestResult {
1660 let temp = tempfile::tempdir()?;
1661 let outside = finished(&temp.path().join("outside"), false)?;
1662 let parent = temp.path().join("devnets");
1663 let at = parent.join(outside.file_name().ok_or("no name")?);
1664 std::fs::create_dir_all(&at)?;
1665 let _mounted = Mounted::new(&at, &[std::ffi::OsStr::new("--bind"), outside.as_os_str()])?;
1666 assert!(at.join(MARKER_FILE).is_file());
1667
1668 let _run = RunDir::create(&parent, false)?;
1669
1670 assert!(
1671 outside.join("nodes").join("peer").join("chunk").is_file(),
1672 "swept through the mount"
1673 );
1674 Ok(())
1675 }
1676
1677 #[cfg(target_os = "linux")]
1681 #[test]
1682 #[ignore = "makes a directory another user owns through sudo; CI runs it"]
1683 fn with_sudo_an_empty_directory_of_another_user_is_not_claimed() -> TestResult {
1684 let temp = tempfile::tempdir()?;
1685 let parent = temp.path().join("devnets");
1686 let moved = temp.path().join("moved");
1687 let replaced = std::rc::Rc::new(std::cell::RefCell::new(None));
1688 let record = std::rc::Rc::clone(&replaced);
1689 AFTER_CREATE.with(|act| {
1690 *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1691 std::fs::rename(path, &moved)?;
1692 sudo(&["mkdir", "-m", "0777"].map(std::ffi::OsStr::new), path)?;
1694 *record.borrow_mut() = Some(path.to_path_buf());
1695 Ok(())
1696 }));
1697 });
1698
1699 let created = RunDir::create(&parent, false);
1700 AFTER_CREATE.with(|act| act.borrow_mut().take());
1701
1702 assert!(created.is_err());
1703 let path = replaced.borrow_mut().take().ok_or("never replaced")?;
1704 assert!(!path.join(MARKER_FILE).exists());
1705 assert!(!path.join(LOCK_FILE).exists());
1706 Ok(())
1707 }
1708
1709 #[cfg(target_os = "linux")]
1715 #[test]
1716 #[ignore = "acts as another user through sudo; CI runs it"]
1717 fn with_sudo_another_user_cannot_redirect_what_a_run_writes() -> TestResult {
1718 use std::ffi::OsStr;
1719 use std::os::unix::fs::PermissionsExt;
1720 let temp = tempfile::tempdir()?;
1721 std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o755))?;
1723
1724 let open = temp.path().join("open");
1726 sudo(&["mkdir", "-m", "0777"].map(OsStr::new), &open)?;
1727 std::fs::create_dir(open.join("mine"))?;
1728 assert!(nobody_moves(&open.join("mine"), &open.join("moved"))?);
1729 let refused = RunDir::create(&open.join("moved").join("devnets"), false);
1730 assert_eq!(
1731 refused.err().map(|e| e.kind()),
1732 Some(io::ErrorKind::PermissionDenied)
1733 );
1734
1735 let sticky = temp.path().join("sticky");
1737 sudo(&["mkdir", "-m", "1777"].map(OsStr::new), &sticky)?;
1738 let mine = sticky.join("mine");
1739 let run = RunDir::create(&mine.join("devnets"), false)?;
1740 assert!(!nobody_moves(&mine, &sticky.join("moved"))?);
1741 std::fs::write(run.path().join("written"), b"the run's")?;
1742 let name = run.path().file_name().ok_or("no name")?;
1743 assert!(mine.join("devnets").join(name).join("written").is_file());
1744 run.remove()?;
1745 Ok(())
1746 }
1747
1748 #[cfg(target_os = "linux")]
1751 #[test]
1752 #[ignore = "makes directories another user owns through sudo; CI runs it"]
1753 fn with_sudo_a_parent_below_another_users_or_groups_directory_is_refused() -> TestResult {
1754 use std::ffi::OsStr;
1755 let temp = tempfile::tempdir()?;
1756 let me = rustix::process::geteuid().as_raw().to_string();
1757 for (name, how) in [
1758 ("theirs", ["-o", "65534", "-m", "0755"]),
1759 ("their-group", ["-g", "65534", "-m", "0775"]),
1760 ] {
1761 let above = temp.path().join(name);
1762 let parent = above.join("devnets");
1763 let make: Vec<&OsStr> = ["install", "-d"]
1764 .into_iter()
1765 .chain(how)
1766 .map(OsStr::new)
1767 .collect();
1768 sudo(&make, &above)?;
1769 sudo(
1770 &["install", "-d", "-o", me.as_str()].map(OsStr::new),
1771 &parent,
1772 )?;
1773
1774 let refused = RunDir::create(&parent, false);
1775
1776 assert_eq!(
1777 refused.err().map(|e| e.kind()),
1778 Some(io::ErrorKind::PermissionDenied),
1779 "{name}"
1780 );
1781 assert!(std::fs::read_dir(&parent)?.next().is_none(), "{name}");
1782 }
1783 Ok(())
1784 }
1785
1786 #[cfg(target_os = "linux")]
1791 #[test]
1792 #[ignore = "hands a directory to another user through sudo; CI runs it"]
1793 fn with_sudo_another_users_finished_run_is_not_swept() -> TestResult {
1794 use std::ffi::OsStr;
1795 let temp = tempfile::tempdir()?;
1796 let old = finished(temp.path(), false)?;
1797 sudo(&["chown", "-R", "65534"].map(OsStr::new), &old)?;
1798 sudo(&["chmod", "-R", "a+rwX"].map(OsStr::new), &old)?;
1799
1800 let _run = RunDir::create(temp.path(), false)?;
1801
1802 assert!(old.join("nodes").join("peer").join("chunk").is_file());
1803 Ok(())
1804 }
1805
1806 #[cfg(any(target_os = "linux", target_os = "macos"))]
1809 #[test]
1810 fn a_directory_on_another_mount_is_told_apart() -> TestResult {
1811 use rustix::fs::{Mode, OFlags};
1812 let open = |path: &Path| {
1813 rustix::fs::open(
1814 path,
1815 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
1816 Mode::empty(),
1817 )
1818 };
1819 let temp = tempfile::tempdir()?;
1820 std::fs::create_dir(temp.path().join("sub"))?;
1821 let other = if cfg!(target_os = "linux") {
1823 "/proc"
1824 } else {
1825 "/dev"
1826 };
1827
1828 let here = unix::mount_of(&open(temp.path())?)?;
1829 assert_eq!(unix::mount_of(&open(&temp.path().join("sub"))?)?, here);
1830 assert_ne!(unix::mount_of(&open(Path::new(other))?)?, here);
1831 Ok(())
1832 }
1833
1834 #[cfg(unix)]
1837 #[test]
1838 fn a_parent_behind_a_dangling_symlink_fails_closed() -> TestResult {
1839 let temp = tempfile::tempdir()?;
1840 let victim = temp.path().join("victim");
1841 std::fs::create_dir_all(&victim)?;
1842 std::fs::write(victim.join("sentinel"), b"keep")?;
1843 std::os::unix::fs::symlink(victim.join("not-yet"), temp.path().join("alias"))?;
1844
1845 assert!(RunDir::create(&temp.path().join("alias").join("devnets"), false).is_err());
1846
1847 assert!(victim.join("sentinel").is_file());
1848 assert!(!victim.join("not-yet").exists());
1849 Ok(())
1850 }
1851
1852 #[cfg(unix)]
1855 fn parent_with(
1856 which: &str,
1857 mode: u32,
1858 ) -> std::result::Result<(tempfile::TempDir, PathBuf), Box<dyn std::error::Error>> {
1859 use std::os::unix::fs::PermissionsExt;
1860 let temp = tempfile::tempdir()?;
1861 let above = temp.path().join("above");
1862 let parent = above.join("devnets");
1863 std::fs::create_dir_all(&parent)?;
1864 let dir = if which == "above" { &above } else { &parent };
1865 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode))?;
1866 Ok((temp, parent))
1867 }
1868
1869 #[cfg(unix)]
1873 #[test]
1874 fn a_parent_another_user_could_change_is_refused() -> TestResult {
1875 let mut cases = vec![("above", 0o777), ("parent", 0o777)];
1876 if cfg!(not(target_os = "linux")) {
1878 cases.push(("above", 0o775));
1879 }
1880 for (which, mode) in cases {
1881 let (_temp, parent) = parent_with(which, mode)?;
1882
1883 let refused = RunDir::create(&parent, false);
1884
1885 assert_eq!(
1886 refused.err().map(|e| e.kind()),
1887 Some(io::ErrorKind::PermissionDenied),
1888 "{which} {mode:o}"
1889 );
1890 assert!(
1891 std::fs::read_dir(&parent)?.next().is_none(),
1892 "{which} {mode:o}"
1893 );
1894 }
1895 Ok(())
1896 }
1897
1898 #[cfg(unix)]
1902 #[test]
1903 fn a_parent_only_this_user_can_change_is_accepted() -> TestResult {
1904 let mut cases = vec![("above", 0o1777), ("parent", 0o1777)];
1905 if cfg!(target_os = "linux") {
1906 cases.push(("above", 0o775));
1907 }
1908 for (which, mode) in cases {
1909 let (_temp, parent) = parent_with(which, mode)?;
1910
1911 let run =
1912 RunDir::create(&parent, false).map_err(|e| format!("{which} {mode:o}: {e}"))?;
1913
1914 assert!(run.path().join(MARKER_FILE).is_file(), "{which} {mode:o}");
1915 }
1916 Ok(())
1917 }
1918
1919 #[cfg(target_os = "linux")]
1923 #[test]
1924 fn a_parent_below_a_directory_with_an_acl_is_refused() -> TestResult {
1925 let (_temp, parent) = parent_with("above", 0o755)?;
1926 let above = parent.parent().ok_or("no parent")?;
1927 let mut acl = 2_u32.to_le_bytes().to_vec();
1930 for (tag, perm, id) in [
1931 (0x01_u16, 7_u16, u32::MAX),
1932 (0x02, 7, 65534),
1933 (0x04, 5, u32::MAX),
1934 (0x10, 7, u32::MAX),
1935 (0x20, 5, u32::MAX),
1936 ] {
1937 acl.extend_from_slice(&tag.to_le_bytes());
1938 acl.extend_from_slice(&perm.to_le_bytes());
1939 acl.extend_from_slice(&id.to_le_bytes());
1940 }
1941 rustix::fs::lsetxattr(
1942 above,
1943 "system.posix_acl_access",
1944 &acl,
1945 rustix::fs::XattrFlags::empty(),
1946 )?;
1947 let mode = rustix::fs::Mode::from_raw_mode(rustix::fs::lstat(above)?.st_mode);
1948 assert!(mode.contains(rustix::fs::Mode::WGRP), "{mode:?}");
1949
1950 let refused = RunDir::create(&parent, false);
1951
1952 assert_eq!(
1953 refused.err().map(|e| e.kind()),
1954 Some(io::ErrorKind::PermissionDenied)
1955 );
1956 Ok(())
1957 }
1958
1959 #[cfg(unix)]
1961 #[test]
1962 fn a_link_named_like_a_run_is_never_followed() -> TestResult {
1963 let temp = tempfile::tempdir()?;
1964 let parent = temp.path().join("devnets");
1965 let outside = finished(&temp.path().join("outside"), false)?;
1966 std::fs::write(outside.join("sentinel"), b"keep")?;
1967 std::fs::create_dir_all(&parent)?;
1968 let link = parent.join(outside.file_name().ok_or("no name")?);
1969 std::os::unix::fs::symlink(&outside, &link)?;
1970
1971 let _run = RunDir::create(&parent, false)?;
1972
1973 assert!(outside.join("sentinel").is_file());
1974 assert!(std::fs::symlink_metadata(&link)?.file_type().is_symlink());
1975 Ok(())
1976 }
1977
1978 #[cfg(unix)]
1982 #[test]
1983 fn retargeting_a_symlink_above_the_run_does_not_redirect_removal() -> TestResult {
1984 let temp = tempfile::tempdir()?;
1985 let first = temp.path().join("first");
1986 let second = temp.path().join("second");
1987 std::fs::create_dir_all(&first)?;
1988 std::fs::create_dir_all(&second)?;
1989 let link = temp.path().join("link");
1990 std::os::unix::fs::symlink(&first, &link)?;
1991
1992 let run = RunDir::create(&link.join("devnets"), false)?;
1993 let name = run.path().file_name().ok_or("no name")?.to_owned();
1994 let decoy = second.join("devnets").join(&name);
1995 std::fs::create_dir_all(&decoy)?;
1996 std::fs::copy(run.path().join(MARKER_FILE), decoy.join(MARKER_FILE))?;
1997 std::fs::write(decoy.join("sentinel"), b"keep")?;
1998 std::fs::remove_file(&link)?;
1999 std::os::unix::fs::symlink(&second, &link)?;
2000
2001 std::fs::write(run.path().join("written"), b"the run's")?;
2003 assert!(first.join("devnets").join(&name).join("written").is_file());
2004 assert!(!decoy.join("written").exists(), "path() followed the link");
2005 run.remove()?;
2006
2007 assert!(!first.join("devnets").join(&name).exists());
2008 assert!(
2009 decoy.join("sentinel").is_file(),
2010 "the removal followed the retargeted link"
2011 );
2012 Ok(())
2013 }
2014
2015 #[cfg(windows)]
2020 fn junction(link: &Path, target: &Path) -> TestResult {
2021 use std::os::windows::process::CommandExt;
2022 let status = std::process::Command::new("cmd")
2023 .raw_arg(r#"/D /V:OFF /S /C "mklink /J "%ANT_TEST_LINK%" "%ANT_TEST_TARGET%"""#)
2024 .env("ANT_TEST_LINK", link)
2025 .env("ANT_TEST_TARGET", target)
2026 .stdout(std::process::Stdio::null())
2027 .status()?;
2028 if status.success() {
2029 Ok(())
2030 } else {
2031 Err(format!("mklink /J {} {} failed", link.display(), target.display()).into())
2032 }
2033 }
2034
2035 #[cfg(windows)]
2037 #[test]
2038 fn retargeting_a_junction_above_the_run_does_not_redirect_removal() -> TestResult {
2039 let temp = tempfile::tempdir()?;
2040 let first = temp.path().join("first & %USERNAME% ^(1)!");
2042 let second = temp.path().join("second ; %PATH% = ^&");
2043 std::fs::create_dir_all(&first)?;
2044 std::fs::create_dir_all(&second)?;
2045 let link = temp.path().join("link & %TEMP%");
2046 junction(&link, &first)?;
2047
2048 let run = RunDir::create(&link.join("devnets"), false)?;
2049 let name = run.path().file_name().ok_or("no name")?.to_owned();
2050 let decoy = second.join("devnets").join(&name);
2051 std::fs::create_dir_all(&decoy)?;
2052 std::fs::copy(run.path().join(MARKER_FILE), decoy.join(MARKER_FILE))?;
2053 std::fs::write(decoy.join("sentinel"), b"keep")?;
2054 std::fs::remove_dir(&link)?;
2055 junction(&link, &second)?;
2056
2057 std::fs::write(run.path().join("written"), b"the run's")?;
2058 assert!(first.join("devnets").join(&name).join("written").is_file());
2059 assert!(
2060 !decoy.join("written").exists(),
2061 "path() followed the junction"
2062 );
2063 run.remove()?;
2064
2065 assert!(!first.join("devnets").join(&name).exists());
2066 assert!(
2067 decoy.join("sentinel").is_file(),
2068 "the removal followed the retargeted junction"
2069 );
2070 Ok(())
2071 }
2072}