1use std::ffi::{CStr, OsStr};
10use std::num::NonZeroUsize;
11use std::os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd};
12use std::os::unix::ffi::OsStrExt;
13use std::path::Path;
14use std::sync::Arc;
15
16use std::os::unix::io::{AsRawFd, RawFd};
17
18use nix::fcntl::{AT_FDCWD, AtFlags, OFlag, openat, readlinkat};
19use nix::sys::stat::{FileStat, Mode, fchmod, fstat, fstatat, futimens, mkdirat};
20use nix::sys::time::TimeSpec;
21use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, linkat, symlinkat, unlinkat};
22
23use crate::timing::metadata::{Phase as MetadataTimingPhase, scope as metadata_timing_scope};
24use crate::walk::EntryKind;
25
26pub(crate) mod overlap;
27
28#[cfg(test)]
29mod resource_tests;
30#[cfg(test)]
31mod timing_tests;
32
33pub const DST_FILE_CREATE_MODE: u32 = 0o600;
56
57pub const DST_DIR_CREATE_MODE: u32 = 0o700;
63
64static STRICT_OPERAND_RESOLUTION: std::sync::atomic::AtomicBool =
79 std::sync::atomic::AtomicBool::new(false);
80
81tokio::task_local! {
82 static FD_ADMISSION: throttle::FdAdmission;
84}
85
86pub async fn with_fd_admission<F>(admission: throttle::FdAdmission, future: F) -> F::Output
97where
98 F: std::future::Future,
99{
100 FD_ADMISSION.scope(admission, future).await
101}
102
103pub(crate) async fn with_optional_fd_admission<F>(
105 admission: Option<throttle::FdAdmission>,
106 future: F,
107) -> F::Output
108where
109 F: std::future::Future,
110{
111 match admission {
112 Some(admission) => with_fd_admission(admission, future).await,
113 None => future.await,
114 }
115}
116
117pub fn enable_strict_operand_resolution() {
122 STRICT_OPERAND_RESOLUTION.store(true, std::sync::atomic::Ordering::Release);
123}
124
125#[must_use]
127pub fn strict_operand_resolution() -> bool {
128 STRICT_OPERAND_RESOLUTION.load(std::sync::atomic::Ordering::Acquire)
129}
130
131#[cfg(target_os = "linux")]
135fn openat2_no_symlinks(path: &Path, flags: OFlag) -> nix::Result<OwnedFd> {
136 use nix::fcntl::{OpenHow, ResolveFlag, openat2};
137 let how = OpenHow::new()
138 .flags(flags)
139 .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS);
140 let mut attempts = 0;
144 loop {
145 match openat2(AT_FDCWD, path, how) {
146 Err(nix::errno::Errno::EAGAIN) if attempts < 4 => attempts += 1,
147 other => return other,
148 }
149 }
150}
151
152#[cfg(target_os = "linux")]
157#[must_use]
158pub fn openat2_available() -> bool {
159 static PROBE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
160 *PROBE.get_or_init(|| {
161 !matches!(
163 openat2_no_symlinks(Path::new("/"), OFlag::O_PATH | OFlag::O_CLOEXEC),
164 Err(nix::errno::Errno::ENOSYS)
165 )
166 })
167}
168
169#[cfg(not(target_os = "linux"))]
173#[must_use]
174pub fn openat2_available() -> bool {
175 false
176}
177
178#[derive(Clone, Debug)]
185pub struct FileMeta {
186 uid: u32,
187 gid: u32,
188 atime: i64,
189 atime_nsec: i64,
190 mtime: i64,
191 mtime_nsec: i64,
192 ctime: i64,
193 ctime_nsec: i64,
194 mode: u32,
195 size: u64,
196 dev: u64,
197 ino: u64,
198}
199
200impl FileMeta {
201 fn from_stat(st: &FileStat) -> Self {
202 Self {
203 uid: st.st_uid,
204 gid: st.st_gid,
205 atime: st.st_atime,
206 atime_nsec: st.st_atime_nsec,
207 mtime: st.st_mtime,
208 mtime_nsec: st.st_mtime_nsec,
209 ctime: st.st_ctime,
210 ctime_nsec: st.st_ctime_nsec,
211 mode: st.st_mode,
212 size: st.st_size as u64,
213 dev: st.st_dev,
214 ino: st.st_ino,
215 }
216 }
217
218 #[must_use]
220 pub fn dev(&self) -> u64 {
221 self.dev
222 }
223
224 #[must_use]
226 pub fn ino(&self) -> u64 {
227 self.ino
228 }
229}
230
231impl crate::preserve::Metadata for FileMeta {
232 fn uid(&self) -> u32 {
233 self.uid
234 }
235 fn gid(&self) -> u32 {
236 self.gid
237 }
238 fn atime(&self) -> i64 {
239 self.atime
240 }
241 fn atime_nsec(&self) -> i64 {
242 self.atime_nsec
243 }
244 fn mtime(&self) -> i64 {
245 self.mtime
246 }
247 fn mtime_nsec(&self) -> i64 {
248 self.mtime_nsec
249 }
250 fn permissions(&self) -> std::fs::Permissions {
251 use std::os::unix::fs::PermissionsExt;
252 std::fs::Permissions::from_mode(self.mode)
253 }
254 fn ctime(&self) -> i64 {
255 self.ctime
256 }
257 fn ctime_nsec(&self) -> i64 {
258 self.ctime_nsec
259 }
260 fn size(&self) -> u64 {
261 self.size
262 }
263}
264
265fn kind_from_stat(st: &FileStat) -> EntryKind {
268 let mode = st.st_mode;
269 let ifmt = mode & libc::S_IFMT;
272 match ifmt {
273 libc::S_IFREG => EntryKind::File,
274 libc::S_IFDIR => EntryKind::Dir,
275 libc::S_IFLNK => EntryKind::Symlink,
276 _ => EntryKind::Special,
277 }
278}
279
280#[derive(Debug)]
289pub struct Handle {
290 fd: OwnedFd,
291 kind: EntryKind,
292 dev: u64,
293 ino: u64,
294 meta: FileMeta,
295}
296
297#[derive(Clone, Copy, Debug)]
304pub struct RemovalSnapshot {
305 kind: EntryKind,
306 identity: (u64, u64),
307 size: u64,
308}
309
310impl RemovalSnapshot {
311 #[must_use]
313 pub fn kind(self) -> EntryKind {
314 self.kind
315 }
316
317 pub(crate) fn identity(self) -> (u64, u64) {
318 self.identity
319 }
320
321 #[must_use]
323 pub fn size(self) -> u64 {
324 self.size
325 }
326}
327
328impl Handle {
329 #[must_use]
331 pub fn kind(&self) -> EntryKind {
332 self.kind
333 }
334
335 #[must_use]
337 pub fn dev(&self) -> u64 {
338 self.dev
339 }
340
341 #[must_use]
343 pub fn ino(&self) -> u64 {
344 self.ino
345 }
346
347 #[must_use]
349 pub fn meta(&self) -> &FileMeta {
350 &self.meta
351 }
352
353 #[must_use]
355 pub fn into_removal_snapshot(self) -> RemovalSnapshot {
356 RemovalSnapshot {
357 kind: self.kind,
358 identity: (self.dev, self.ino),
359 size: self.meta.size,
360 }
361 }
362
363 #[must_use]
365 pub fn as_fd(&self) -> BorrowedFd<'_> {
366 self.fd.as_fd()
367 }
368
369 pub fn try_clone(&self) -> std::io::Result<Handle> {
380 Ok(Handle {
381 fd: self.fd.try_clone()?,
382 kind: self.kind,
383 dev: self.dev,
384 ino: self.ino,
385 meta: self.meta.clone(),
386 })
387 }
388
389 pub async fn read_symlink(
395 &self,
396 side: congestion::Side,
397 ) -> std::io::Result<(std::path::PathBuf, FileMeta)> {
398 let target = read_link_handle(self, side).await?;
399 Ok((target, self.meta.clone()))
400 }
401}
402
403#[derive(Debug)]
423pub struct Dir {
424 captured_identity: Option<(u64, u64)>,
426 fd: Arc<DirectoryDescriptor>,
427 side: congestion::Side,
429 children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
450}
451
452#[derive(Debug)]
456struct DirectoryDescriptor {
457 fd: OwnedFd,
458 credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
459}
460
461impl DirectoryDescriptor {
462 fn reopen(&self) -> std::io::Result<OwnedFd> {
463 self.reopen_with_proc_open(|path, flags| openat(AT_FDCWD, path, flags, Mode::empty()))
464 }
465
466 fn reopen_with_proc_open(
467 &self,
468 open_proc: impl FnOnce(&str, OFlag) -> nix::Result<OwnedFd>,
469 ) -> std::io::Result<OwnedFd> {
470 let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
471 match openat(self.as_fd(), c".", flags, Mode::empty()) {
472 Err(permission @ nix::errno::Errno::EACCES) => {
473 let path = format!("/proc/self/fd/{}", self.as_raw_fd());
478 open_proc(&path, flags).map_err(|error| match error {
479 nix::errno::Errno::ENOENT
482 | nix::errno::Errno::ENOTDIR
483 | nix::errno::Errno::ELOOP => permission,
484 error => error,
485 })
486 }
487 result => result,
488 }
489 .map_err(nix_to_io)
490 }
491
492 fn listing_fd_with_seek(
493 &self,
494 seek: impl FnOnce(BorrowedFd<'_>) -> nix::Result<libc::off_t>,
495 ) -> std::io::Result<OwnedFd> {
496 match seek(self.as_fd()) {
497 Ok(_) => self.fd.try_clone(),
498 Err(nix::errno::Errno::ESPIPE) => {
499 self.reopen()
503 }
504 Err(error) => Err(nix_to_io(error)),
505 }
506 }
507}
508
509impl AsFd for DirectoryDescriptor {
510 fn as_fd(&self) -> BorrowedFd<'_> {
511 self.fd.as_fd()
512 }
513}
514
515impl AsRawFd for DirectoryDescriptor {
516 fn as_raw_fd(&self) -> RawFd {
517 self.fd.as_raw_fd()
518 }
519}
520
521#[derive(Debug)]
525pub struct DirectoryEntry {
526 pub name: std::ffi::OsString,
527 pub kind_hint: Option<EntryKind>,
528}
529
530#[cfg(test)]
531type CursorReadHook = Box<dyn FnMut(usize, RawFd) -> std::io::Result<()> + Send>;
532
533pub struct DirectoryCursor {
535 iterator: Option<OwnedDirectoryStream>,
536 first_read: bool,
537 exhausted: bool,
538 #[cfg(test)]
539 read_hook: Option<CursorReadHook>,
540}
541
542impl DirectoryCursor {
543 fn new(iterator: OwnedDirectoryStream) -> Self {
544 Self {
545 iterator: Some(iterator),
546 first_read: true,
547 exhausted: false,
548 #[cfg(test)]
549 read_hook: None,
550 }
551 }
552
553 pub async fn read_acls(&mut self, side: congestion::Side) -> std::io::Result<Acls> {
558 let iterator = self
559 .iterator
560 .take()
561 .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
562 let (iterator, acls) = read_acls_owned(iterator, side, true).await?;
563 self.iterator = Some(iterator);
564 Ok(acls)
565 }
566
567 pub async fn open_following_symlinks(
569 path: &Path,
570 side: congestion::Side,
571 credit: Arc<dyn std::fmt::Debug + Send + Sync>,
572 ) -> std::io::Result<Self> {
573 let path = path.to_owned();
574 let iterator = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
575 if strict_operand_resolution() {
576 return Err(std::io::Error::new(
577 std::io::ErrorKind::InvalidInput,
578 "following directory symlinks is incompatible with strict operand resolution",
579 ));
580 }
581 let fd = openat(
582 AT_FDCWD,
583 &path,
584 OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
585 Mode::empty(),
586 )
587 .map_err(nix_to_io)?;
588 let iterator = OwnedDirectoryStream::from_fd(fd, Some(credit))?;
589 #[cfg(test)]
590 let _visit = resource_tests::gate_opened_descriptor(iterator.as_raw_fd())?;
591 Ok(iterator)
592 })
593 .await?;
594 Ok(Self::new(iterator))
595 }
596
597 pub async fn next_batch(
608 &mut self,
609 limit: NonZeroUsize,
610 ) -> std::io::Result<Vec<DirectoryEntry>> {
611 self.next_batch_with_seek(limit, |fd| {
612 nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
613 })
614 .await
615 }
616
617 async fn next_batch_with_seek(
618 &mut self,
619 limit: NonZeroUsize,
620 seek: impl FnOnce(BorrowedFd<'_>) -> nix::Result<libc::off_t> + Send + 'static,
621 ) -> std::io::Result<Vec<DirectoryEntry>> {
622 if self.exhausted && self.iterator.is_some() {
624 return Ok(Vec::new());
625 }
626 throttle::get_ops_token().await;
627 let mut iterator = self
628 .iterator
629 .take()
630 .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
631 let first_read = std::mem::take(&mut self.first_read);
632 #[cfg(test)]
633 let mut read_hook = self.read_hook.take();
634 let (returned, entries, exhausted) = run_fd_admitted_blocking(move || {
635 if first_read {
636 match seek(iterator.as_fd()) {
639 Ok(_) => {}
640 Err(nix::errno::Errno::ESPIPE) => {}
642 Err(error) => return Err(nix_to_io(error)),
643 }
644 }
645 let mut entries = Vec::with_capacity(limit.get());
646 let mut exhausted = false;
647 while entries.len() < limit.get() {
648 #[cfg(test)]
649 if let Some(read_hook) = read_hook.as_mut() {
650 read_hook(entries.len(), iterator.as_raw_fd())?;
651 }
652 let Some(entry) = iterator.next_raw_entry()? else {
653 exhausted = true;
654 break;
655 };
656 if entry.name == "." || entry.name == ".." {
657 continue;
658 }
659 entries.push(entry);
660 }
661 Ok((iterator, entries, exhausted))
662 })
663 .await?;
664 self.iterator = Some(returned);
665 self.exhausted = exhausted;
666 Ok(entries)
667 }
668}
669
670#[derive(Debug)]
672struct OwnedDirectoryStream {
673 dir: std::ptr::NonNull<libc::DIR>,
674 _credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
676}
677
678unsafe impl Send for OwnedDirectoryStream {}
681
682impl OwnedDirectoryStream {
683 fn from_fd(
684 fd: OwnedFd,
685 credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
686 ) -> std::io::Result<Self> {
687 let owner = DirectoryDescriptor { fd, credit };
688 let dir = std::ptr::NonNull::new(unsafe { libc::fdopendir(owner.as_raw_fd()) })
691 .ok_or_else(std::io::Error::last_os_error)?;
692 let _ = owner.fd.into_raw_fd();
693 Ok(Self {
694 dir,
695 _credit: owner.credit,
696 })
697 }
698
699 fn next_raw_entry(&mut self) -> std::io::Result<Option<DirectoryEntry>> {
700 nix::errno::Errno::clear();
701 let raw = unsafe { libc::readdir(self.dir.as_ptr()) };
704 if raw.is_null() {
705 let errno = nix::errno::Errno::last_raw();
706 return if errno == 0 {
707 Ok(None)
708 } else {
709 Err(std::io::Error::from_raw_os_error(errno))
710 };
711 }
712 Ok(Some(unsafe { directory_entry_from_raw(raw) }))
717 }
718}
719
720unsafe fn directory_entry_from_raw(raw: *const libc::dirent) -> DirectoryEntry {
729 let name = unsafe { CStr::from_ptr((&raw const (*raw).d_name).cast()) };
732 let dtype = unsafe { (*raw).d_type };
733 DirectoryEntry {
734 name: OsStr::from_bytes(name.to_bytes()).to_owned(),
735 kind_hint: kind_hint_from_dtype(dtype),
736 }
737}
738
739fn kind_hint_from_dtype(dtype: libc::c_uchar) -> Option<EntryKind> {
740 match dtype {
741 libc::DT_DIR => Some(EntryKind::Dir),
742 libc::DT_LNK => Some(EntryKind::Symlink),
743 libc::DT_REG => Some(EntryKind::File),
744 libc::DT_FIFO | libc::DT_CHR | libc::DT_BLK | libc::DT_SOCK => Some(EntryKind::Special),
745 _ => None,
746 }
747}
748
749impl AsRawFd for OwnedDirectoryStream {
750 fn as_raw_fd(&self) -> RawFd {
751 unsafe { libc::dirfd(self.dir.as_ptr()) }
753 }
754}
755
756impl AsFd for OwnedDirectoryStream {
757 fn as_fd(&self) -> BorrowedFd<'_> {
758 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
760 }
761}
762
763impl Drop for OwnedDirectoryStream {
764 fn drop(&mut self) {
765 unsafe { libc::closedir(self.dir.as_ptr()) };
767 }
768}
769
770impl Dir {
771 fn opened(fd: OwnedFd, side: congestion::Side) -> Dir {
774 Self::opened_with_credit(fd, side, None)
775 }
776
777 fn opened_with_credit(
778 fd: OwnedFd,
779 side: congestion::Side,
780 credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
781 ) -> Dir {
782 Dir {
783 captured_identity: None,
784 fd: Arc::new(DirectoryDescriptor { fd, credit }),
785 side,
786 children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
787 }
788 }
789
790 fn mark_children_cannot_inherit(&self) {
794 self.children_may_inherit
795 .store(false, std::sync::atomic::Ordering::Relaxed);
796 }
797
798 #[must_use]
800 pub fn side(&self) -> congestion::Side {
801 self.side
802 }
803
804 pub async fn open_root_dir(
816 path: &Path,
817 dereference: bool,
818 side: congestion::Side,
819 ) -> std::io::Result<Dir> {
820 let path = path.to_owned();
821 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
824 let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
825 let mode = Mode::empty();
826 #[cfg(target_os = "linux")]
827 {
828 if strict_operand_resolution() {
829 if dereference {
833 return Err(std::io::Error::new(
834 std::io::ErrorKind::InvalidInput,
835 "--dereference cannot be combined with strict operand resolution",
836 ));
837 }
838 return openat2_no_symlinks(&path, flags)
839 .map(|fd| Dir::opened(fd, side))
840 .map_err(nix_to_io);
841 }
842 }
843 match openat(AT_FDCWD, &path, flags, mode) {
844 Ok(fd) => Ok(Dir::opened(fd, side)),
845 Err(nix::errno::Errno::ELOOP) if dereference => {
846 let follow_flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
848 openat(AT_FDCWD, &path, follow_flags, mode)
849 .map(|fd| Dir::opened(fd, side))
850 .map_err(nix_to_io)
851 }
852 Err(e) => Err(nix_to_io(e)),
853 }
854 })
855 .await
856 }
857
858 pub async fn open_parent_dir(
886 path: &Path,
887 side: congestion::Side,
888 ) -> std::io::Result<TrustedDir> {
889 let path = path.to_owned();
890 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
891 let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
892 #[cfg(target_os = "linux")]
893 {
894 if strict_operand_resolution() {
895 return openat2_no_symlinks(&path, flags)
896 .map(|fd| TrustedDir(Dir::opened(fd, side)))
897 .map_err(nix_to_io);
898 }
899 }
900 openat(AT_FDCWD, &path, flags, Mode::empty())
903 .map(|fd| TrustedDir(Dir::opened(fd, side)))
904 .map_err(nix_to_io)
905 })
906 .await
907 }
908
909 pub async fn open_dir(&self, name: &OsStr) -> std::io::Result<Dir> {
915 self.open_dir_with_credit(name, None, Ok).await
916 }
917
918 pub(crate) async fn open_dir_with_meta(
923 &self,
924 name: &OsStr,
925 ) -> std::io::Result<(Dir, FileMeta)> {
926 self.open_dir_with_credit(name, None, Self::with_metadata_snapshot)
927 .await
928 }
929
930 pub async fn open_dir_admitted(
935 &self,
936 name: &OsStr,
937 credit: Arc<dyn std::fmt::Debug + Send + Sync>,
938 ) -> std::io::Result<Dir> {
939 self.open_dir_with_credit(name, Some(credit), Ok).await
940 }
941
942 async fn open_dir_with_credit<T, F>(
943 &self,
944 name: &OsStr,
945 credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
946 finish: F,
947 ) -> std::io::Result<T>
948 where
949 T: Send + 'static,
950 F: FnOnce(Dir) -> std::io::Result<T> + Send + 'static,
951 {
952 if !is_single_component(name) {
956 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
957 }
958 let dir = self.fd.clone();
963 let side = self.side;
964 let name = name.to_owned();
965 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
966 let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
967 let fd =
968 openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
969 let opened = Dir::opened_with_credit(fd, side, credit);
970 #[cfg(test)]
971 let _visit = resource_tests::gate_opened_descriptor(opened.fd.as_raw_fd())?;
972 finish(opened)
973 })
974 .await
975 }
976
977 fn with_metadata_snapshot(mut self) -> std::io::Result<(Dir, FileMeta)> {
978 let meta = snapshot_directory_meta(self.fd.as_fd())?;
979 self.captured_identity = Some((meta.dev(), meta.ino()));
980 Ok((self, meta))
981 }
982
983 pub async fn open_file_read(&self, name: &OsStr) -> std::io::Result<(std::fs::File, FileMeta)> {
1004 if !is_single_component(name) {
1005 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1006 }
1007 let dir = self.fd.clone();
1008 let side = self.side;
1009 let name = name.to_owned();
1010 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1011 let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC;
1012 let fd =
1013 openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
1014 let st = fstat(&fd).map_err(nix_to_io)?;
1017 if kind_from_stat(&st) != EntryKind::File {
1018 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1020 }
1021 let meta = FileMeta::from_stat(&st);
1022 let file = std::fs::File::from(fd);
1023 Ok((file, meta))
1024 })
1025 .await
1026 }
1027
1028 pub async fn meta(&self) -> std::io::Result<FileMeta> {
1036 let dir = self.fd.clone();
1037 let side = self.side;
1038 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1039 let st = fstat(dir.as_fd()).map_err(nix_to_io)?;
1040 Ok(FileMeta::from_stat(&st))
1041 })
1042 .await
1043 }
1044
1045 pub async fn read_acls(&self) -> std::io::Result<Acls> {
1053 #[cfg(test)]
1054 let _visit = resource_tests::gate_directory_acl(self.fd.as_raw_fd())?;
1055 read_acls_owned(self.fd.clone(), self.side, true)
1056 .await
1057 .map(|(_, acls)| acls)
1058 }
1059
1060 pub(crate) async fn child_kind(&self, name: &OsStr) -> std::io::Result<EntryKind> {
1065 if !is_single_component(name) {
1066 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1067 }
1068 let dir = self.fd.clone();
1069 let side = self.side;
1070 let name = name.to_owned();
1071 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1072 let st = fstatat(dir.as_fd(), name.as_bytes(), AtFlags::AT_SYMLINK_NOFOLLOW)
1073 .map_err(nix_to_io)?;
1074 Ok(kind_from_stat(&st))
1075 })
1076 .await
1077 }
1078
1079 pub async fn child(&self, name: &OsStr) -> std::io::Result<Handle> {
1085 if !is_single_component(name) {
1089 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1090 }
1091 let dir = self.fd.clone();
1096 let side = self.side;
1097 let name = name.to_owned();
1098 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1099 let flags = OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
1100 let fd =
1101 openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
1102 let st = fstatat(&fd, "", AtFlags::AT_EMPTY_PATH).map_err(nix_to_io)?;
1104 let kind = kind_from_stat(&st);
1105 let dev = st.st_dev;
1106 let ino = st.st_ino;
1107 let meta = FileMeta::from_stat(&st);
1108 #[cfg(test)]
1109 let _gate = resource_tests::gate_classified_entry(fd.as_raw_fd())?;
1110 Ok(Handle {
1111 fd,
1112 kind,
1113 dev,
1114 ino,
1115 meta,
1116 })
1117 })
1118 .await
1119 }
1120
1121 pub async fn verify_same_inode(&self, handle: &Handle) -> std::io::Result<()> {
1132 let identity = self.identity().await?;
1133 if identity == (handle.dev(), handle.ino()) {
1134 Ok(())
1135 } else {
1136 Err(std::io::Error::from_raw_os_error(libc::ESTALE))
1137 }
1138 }
1139
1140 pub(crate) async fn identity(&self) -> std::io::Result<(u64, u64)> {
1142 Ok(match self.captured_identity {
1143 Some(identity) => identity,
1144 None => {
1145 let meta = self.meta().await?;
1146 (meta.dev(), meta.ino())
1147 }
1148 })
1149 }
1150
1151 pub async fn secure_as_copier(
1188 &self,
1189 mode: u32,
1190 orig_uid: u32,
1191 orig_gid: u32,
1192 ) -> std::io::Result<()> {
1193 self.secure_as_copier_with(mode, orig_uid, orig_gid, || {})
1194 .await
1195 }
1196
1197 async fn secure_as_copier_with(
1198 &self,
1199 mode: u32,
1200 orig_uid: u32,
1201 orig_gid: u32,
1202 on_mutation: impl FnOnce() + Send + 'static,
1203 ) -> std::io::Result<()> {
1204 let fd = self.fd.clone();
1205 let euid = nix::unistd::geteuid().as_raw();
1206 run_metadata_probed_blocking(self.side, congestion::MetadataOp::Chmod, move || {
1207 let raw = fd.as_fd();
1208 #[cfg(test)]
1209 let _gate = resource_tests::gate_directory_lockdown(raw.as_raw_fd())?;
1210 fchown(raw, Some(Uid::from_raw(euid)), None).map_err(nix_to_io)?;
1213 on_mutation();
1216 if let Err(chmod_err) = fchmod(raw, Mode::from_bits_truncate(0o700)).map_err(nix_to_io)
1222 {
1223 match fchown(raw, Some(Uid::from_raw(orig_uid)), None)
1227 .map_err(nix_to_io)
1228 .and_then(|()| fstat(raw).map_err(nix_to_io))
1229 {
1230 Ok(st) if st.st_uid == orig_uid => return Err(chmod_err),
1233 Ok(st) => {
1235 return Err(std::io::Error::new(
1236 std::io::ErrorKind::PermissionDenied,
1237 format!(
1238 "reused-directory lockdown could not restrict the directory (chmod: \
1239 {chmod_err}); the ownership rollback did not take effect (directory \
1240 shows uid={}, expected {orig_uid}) — it is left copier-owned at its \
1241 original mode, refusing to descend (the filesystem may not honor \
1242 chown/chmod)",
1243 st.st_uid,
1244 ),
1245 ));
1246 }
1247 Err(rb) => {
1248 return Err(std::io::Error::new(
1249 std::io::ErrorKind::PermissionDenied,
1250 format!(
1251 "reused-directory lockdown could not restrict the directory (chmod: \
1252 {chmod_err}) and could not roll ownership back (chown/stat: {rb}); \
1253 it is left owned by the copier at its original mode — refusing to \
1254 descend (the destination filesystem may be read-only or failing)"
1255 ),
1256 ));
1257 }
1258 }
1259 }
1260 let st = fstat(raw).map_err(nix_to_io)?;
1266 if st.st_uid != euid || (st.st_mode & 0o7777) != 0o700 {
1267 return Err(std::io::Error::new(
1268 std::io::ErrorKind::PermissionDenied,
1269 format!(
1270 "reused-directory lockdown could not be verified: after chown+chmod the \
1271 directory shows uid={} mode={:#o} (expected uid={} mode={:#o}); the \
1272 filesystem may not honor chown/chmod (e.g. CIFS without unix extensions) — \
1273 refusing to descend",
1274 st.st_uid,
1275 st.st_mode & 0o7777,
1276 euid,
1277 0o700,
1278 ),
1279 ));
1280 }
1281 if st.st_gid != orig_gid {
1287 fchown(raw, None, Some(Gid::from_raw(orig_gid))).map_err(nix_to_io)?;
1288 }
1289 if mode != 0o700 {
1294 fchmod(raw, Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
1295 }
1296 let st = fstat(raw).map_err(nix_to_io)?;
1298 if st.st_uid != euid || st.st_gid != orig_gid || (st.st_mode & 0o7777) != mode {
1299 return Err(std::io::Error::new(
1300 std::io::ErrorKind::PermissionDenied,
1301 format!(
1302 "reused-directory lockdown could not be verified: after takeover the \
1303 directory shows uid={} gid={} mode={:#o} (expected uid={} gid={} \
1304 mode={:#o}); the filesystem may not honor chown/chmod (e.g. CIFS without \
1305 unix extensions), or the copier is not in the directory's group and lacks \
1306 CAP_FSETID to keep setgid — refusing to descend",
1307 st.st_uid,
1308 st.st_gid,
1309 st.st_mode & 0o7777,
1310 euid,
1311 orig_gid,
1312 mode,
1313 ),
1314 ));
1315 }
1316 Ok(())
1317 })
1318 .await
1319 }
1320
1321 pub async fn make_dir(&self, name: &OsStr, mode: u32) -> std::io::Result<Dir> {
1374 self.make_dir_with_credit(name, mode, None, |_| Ok(()))
1375 .await
1376 }
1377
1378 pub(crate) async fn make_dir_checked(
1384 &self,
1385 name: &OsStr,
1386 mode: u32,
1387 check: impl FnOnce(&FileMeta) -> std::io::Result<()> + Send + 'static,
1388 ) -> std::io::Result<Dir> {
1389 self.make_dir_with_credit(name, mode, None, move |dir| {
1390 let meta = snapshot_directory_meta(dir.fd.as_fd())?;
1391 dir.captured_identity = Some((meta.dev(), meta.ino()));
1392 check(&meta)
1393 })
1394 .await
1395 }
1396
1397 pub async fn make_dir_admitted(
1399 &self,
1400 name: &OsStr,
1401 mode: u32,
1402 credit: Arc<dyn std::fmt::Debug + Send + Sync>,
1403 ) -> std::io::Result<Dir> {
1404 self.make_dir_with_credit(name, mode, Some(credit), |_| Ok(()))
1405 .await
1406 }
1407
1408 async fn make_dir_with_credit(
1409 &self,
1410 name: &OsStr,
1411 mode: u32,
1412 credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
1413 check: impl FnOnce(&mut Dir) -> std::io::Result<()> + Send + 'static,
1414 ) -> std::io::Result<Dir> {
1415 if !is_single_component(name) {
1416 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1417 }
1418 let dir = self.fd.clone();
1419 let side = self.side;
1420 let name_owned = name.to_owned();
1421 let strict = strict_operand_resolution();
1422 run_metadata_probed_blocking(side, congestion::MetadataOp::MkDir, move || {
1423 mkdirat(
1424 dir.as_fd(),
1425 name_owned.as_bytes(),
1426 Mode::from_bits_truncate(mode),
1427 )
1428 .map_err(nix_to_io)?;
1429 let result = (|| {
1430 let open_flags =
1431 OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
1432 let fd = openat(
1433 dir.as_fd(),
1434 name_owned.as_bytes(),
1435 open_flags,
1436 Mode::empty(),
1437 )
1438 .map_err(nix_to_io)?;
1439 let mut created = Dir {
1442 captured_identity: None,
1443 fd: Arc::new(DirectoryDescriptor { fd, credit }),
1444 side,
1445 children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(!strict)),
1446 };
1447 #[cfg(test)]
1448 let _visit = resource_tests::gate_opened_descriptor(created.fd.as_raw_fd())?;
1449 check(&mut created)?;
1450 if strict {
1451 apply_one_acl(created.fd.as_raw_fd(), ACL_DEFAULT_XATTR, None)?;
1453 apply_one_acl(created.fd.as_raw_fd(), ACL_ACCESS_XATTR, None)?;
1454 }
1455 Ok(created)
1456 })();
1457 if result.is_err() {
1458 let _ = unlinkat(dir.as_fd(), name_owned.as_bytes(), UnlinkatFlags::RemoveDir);
1462 }
1463 result
1464 })
1465 .await
1466 }
1467
1468 pub async fn entries(&self) -> std::io::Result<DirectoryCursor> {
1475 let dir = Arc::clone(&self.fd);
1476 let iterator = run_fd_admitted_blocking(move || {
1477 OwnedDirectoryStream::from_fd(dir.reopen()?, dir.credit.clone())
1478 })
1479 .await?;
1480 Ok(DirectoryCursor::new(iterator))
1481 }
1482
1483 pub async fn read_entries(
1496 &self,
1497 ) -> std::io::Result<Vec<(std::ffi::OsString, Option<EntryKind>)>> {
1498 Ok(self
1499 .read_entries_capped(usize::MAX)
1500 .await?
1501 .expect("an unbounded listing cannot exceed usize::MAX entries"))
1502 }
1503
1504 pub async fn read_entries_capped(
1510 &self,
1511 cap: usize,
1512 ) -> std::io::Result<Option<Vec<(std::ffi::OsString, Option<EntryKind>)>>> {
1513 throttle::get_ops_token().await;
1514 let dir = self.fd.clone();
1515 run_fd_admitted_blocking(move || {
1516 let fd = dir.listing_fd_with_seek(|fd| {
1520 nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
1521 })?;
1522 let mut stream = OwnedDirectoryStream::from_fd(fd, dir.credit.clone())?;
1524 let mut entries = Vec::new();
1525 while let Some(entry) = stream.next_raw_entry()? {
1526 if entry.name == "." || entry.name == ".." {
1527 continue;
1528 }
1529 if entries.len() >= cap {
1530 return Ok(None);
1531 }
1532 entries.push((entry.name, entry.kind_hint));
1533 }
1534 Ok(Some(entries))
1535 })
1536 .await
1537 }
1538
1539 pub async fn unlink_at(&self, name: &OsStr) -> std::io::Result<()> {
1546 self.unlink_at_on(name, self.side).await
1547 }
1548
1549 pub(crate) async fn unlink_at_with(
1554 &self,
1555 name: &OsStr,
1556 after_unlink: impl FnOnce() + Send + 'static,
1557 ) -> std::io::Result<()> {
1558 self.unlink_at_on_with(name, self.side, after_unlink).await
1559 }
1560
1561 pub(crate) async fn unlink_at_on(
1569 &self,
1570 name: &OsStr,
1571 side: congestion::Side,
1572 ) -> std::io::Result<()> {
1573 self.unlink_at_on_with(name, side, || {}).await
1574 }
1575
1576 async fn unlink_at_on_with(
1577 &self,
1578 name: &OsStr,
1579 side: congestion::Side,
1580 after_unlink: impl FnOnce() + Send + 'static,
1581 ) -> std::io::Result<()> {
1582 if !is_single_component(name) {
1583 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1584 }
1585 let dir = self.fd.clone();
1586 let name = name.to_owned();
1587 run_metadata_probed_blocking(side, congestion::MetadataOp::Unlink, move || {
1588 #[cfg(test)]
1589 let _visit = tests::gate_unlink(dir.as_raw_fd(), &name)?;
1590 unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir)
1591 .map_err(nix_to_io)?;
1592 after_unlink();
1593 Ok(())
1594 })
1595 .await
1596 }
1597
1598 pub async fn rmdir_at(&self, name: &OsStr) -> std::io::Result<()> {
1603 self.rmdir_at_on(name, self.side).await
1604 }
1605
1606 pub(crate) async fn rmdir_at_on(
1610 &self,
1611 name: &OsStr,
1612 side: congestion::Side,
1613 ) -> std::io::Result<()> {
1614 if !is_single_component(name) {
1615 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1616 }
1617 let dir = self.fd.clone();
1618 let name = name.to_owned();
1619 run_metadata_probed_blocking(side, congestion::MetadataOp::RmDir, move || {
1620 unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::RemoveDir).map_err(nix_to_io)
1621 })
1622 .await
1623 }
1624
1625 pub async fn symlink_at(&self, name: &OsStr, target: &Path) -> std::io::Result<Handle> {
1635 if !is_single_component(name) {
1636 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1637 }
1638 let dir = self.fd.clone();
1639 let side = self.side;
1640 let name = name.to_owned();
1641 let target = target.to_owned();
1642 let name_for_child = name.clone();
1644 run_metadata_probed_blocking(side, congestion::MetadataOp::Symlink, move || {
1645 symlinkat(target.as_os_str().as_bytes(), dir.as_fd(), name.as_bytes())
1647 .map_err(nix_to_io)
1648 })
1649 .await?;
1650 let handle = self.child(&name_for_child).await?;
1653 if handle.kind() != EntryKind::Symlink {
1654 return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
1657 }
1658 Ok(handle)
1659 }
1660
1661 pub async fn read_link_at(&self, name: &OsStr) -> std::io::Result<std::path::PathBuf> {
1666 if !is_single_component(name) {
1667 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1668 }
1669 let dir = self.fd.clone();
1670 let side = self.side;
1671 let name = name.to_owned();
1672 run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
1673 readlinkat(dir.as_fd(), name.as_bytes())
1674 .map(std::path::PathBuf::from)
1675 .map_err(nix_to_io)
1676 })
1677 .await
1678 }
1679
1680 pub async fn hard_link_at(
1689 &self,
1690 name: &OsStr,
1691 dst: &Dir,
1692 dst_name: &OsStr,
1693 ) -> std::io::Result<()> {
1694 if !is_single_component(name) {
1695 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1696 }
1697 if !is_single_component(dst_name) {
1698 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1699 }
1700 let src_dir = self.fd.clone();
1701 let dst_dir = dst.fd.clone();
1702 let side = dst.side;
1703 let name = name.to_owned();
1704 let dst_name = dst_name.to_owned();
1705 run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1706 linkat(
1707 src_dir.as_fd(),
1708 name.as_bytes(),
1709 dst_dir.as_fd(),
1710 dst_name.as_bytes(),
1711 AtFlags::empty(),
1712 )
1713 .map_err(nix_to_io)
1714 })
1715 .await
1716 }
1717
1718 pub async fn hard_link_handle_at(
1757 &self,
1758 src_handle: &Handle,
1759 dst_name: &OsStr,
1760 ) -> std::io::Result<()> {
1761 if !is_single_component(dst_name) {
1762 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1763 }
1764 let src_owned = src_handle.as_fd().try_clone_to_owned()?;
1769 let dst_dir = self.fd.clone();
1770 let side = self.side;
1771 let dst_name = dst_name.to_owned();
1772 run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1773 let proc_path = format!("/proc/self/fd/{}", src_owned.as_raw_fd());
1774 linkat(
1778 AT_FDCWD,
1779 proc_path.as_str(),
1780 dst_dir.as_fd(),
1781 dst_name.as_bytes(),
1782 AtFlags::AT_SYMLINK_FOLLOW,
1783 )
1784 .map_err(nix_to_io)
1785 })
1786 .await
1787 }
1788
1789 pub async fn create_file(&self, name: &OsStr) -> std::io::Result<std::fs::File> {
1819 let operation = self.file_create_operation(name, strict_operand_resolution())?;
1820 run_metadata_probed_blocking(self.side, congestion::MetadataOp::OpenCreate, operation).await
1821 }
1822
1823 pub(crate) async fn create_file_and_then<C, T>(
1831 &self,
1832 name: &OsStr,
1833 continuation: C,
1834 ) -> std::io::Result<T>
1835 where
1836 C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
1837 T: Send + 'static,
1838 {
1839 let operation = match self.file_create_operation(name, strict_operand_resolution()) {
1840 Ok(operation) => operation,
1841 Err(error) => return Ok(continuation(Err(error))),
1842 };
1843 run_file_create_and_then(self.side, operation, continuation).await
1844 }
1845
1846 fn file_create_operation(
1847 &self,
1848 name: &OsStr,
1849 strict: bool,
1850 ) -> std::io::Result<impl FnOnce() -> std::io::Result<std::fs::File> + Send + 'static + use<>>
1851 {
1852 if !is_single_component(name) {
1853 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1854 }
1855 let dir = self.fd.clone();
1856 let name = name.to_owned();
1857 let may_inherit = Arc::clone(&self.children_may_inherit);
1864 Ok(move || {
1865 let flags = OFlag::O_CREAT
1866 | OFlag::O_EXCL
1867 | OFlag::O_WRONLY
1868 | OFlag::O_NOFOLLOW
1869 | OFlag::O_CLOEXEC;
1870 let file_mode = Mode::from_bits_truncate(DST_FILE_CREATE_MODE);
1871 let file = openat(dir.as_fd(), name.as_bytes(), flags, file_mode)
1872 .map(std::fs::File::from)
1873 .map_err(nix_to_io)?;
1874 #[cfg(test)]
1875 let _visit = tests::gate_file_create_stage(file.as_raw_fd(), "before-sanitation");
1876 if strict && may_inherit.load(std::sync::atomic::Ordering::SeqCst) {
1877 if let Err(err) = apply_one_acl(file.as_raw_fd(), ACL_ACCESS_XATTR, None) {
1883 let _ = unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir);
1884 return Err(err);
1885 }
1886 }
1887 Ok(file)
1888 })
1889 }
1890}
1891
1892#[derive(Debug)]
1917pub struct TrustedDir(Dir);
1918
1919impl TrustedDir {
1920 #[must_use]
1925 pub fn into_tree(self) -> Dir {
1926 self.0
1927 }
1928}
1929
1930pub(crate) fn split_parent_and_name(path: &Path) -> Option<(&Path, &OsStr)> {
1945 let name = path.file_name()?;
1946 let parent = match path.parent() {
1947 Some(parent) if !parent.as_os_str().is_empty() => parent,
1948 _ => Path::new("."),
1950 };
1951 Some((parent, name))
1952}
1953
1954pub(crate) async fn open_preview_operand_parent(
1960 path: &Path,
1961 side: congestion::Side,
1962) -> std::io::Result<Dir> {
1963 let path = path.to_owned();
1964 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1965 let flags = OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
1966 #[cfg(target_os = "linux")]
1967 if strict_operand_resolution() {
1968 return openat2_no_symlinks(&path, flags)
1969 .map(|fd| Dir::opened(fd, side))
1970 .map_err(nix_to_io);
1971 }
1972 openat(AT_FDCWD, &path, flags, Mode::empty())
1973 .map(|fd| Dir::opened(fd, side))
1974 .map_err(nix_to_io)
1975 })
1976 .await
1977}
1978
1979fn snapshot_directory_meta(fd: BorrowedFd<'_>) -> std::io::Result<FileMeta> {
1980 let result = (|| {
1981 #[cfg(test)]
1982 let _visit = resource_tests::gate_directory_stat(fd.as_raw_fd())?;
1983 let stat = fstat(fd).map_err(nix_to_io)?;
1984 Ok(FileMeta::from_stat(&stat))
1985 })();
1986 result.map_err(|error: std::io::Error| {
1987 std::io::Error::new(error.kind(), DirectoryStatError(error))
1988 })
1989}
1990
1991#[derive(Debug)]
1992struct DirectoryStatError(std::io::Error);
1993
1994impl std::fmt::Display for DirectoryStatError {
1995 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1996 f.write_str("cannot fstat opened directory")
1997 }
1998}
1999
2000impl std::error::Error for DirectoryStatError {
2001 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2002 Some(&self.0)
2003 }
2004}
2005
2006#[derive(Debug)]
2008pub(crate) struct PreviewDirectory {
2009 dir: Arc<Dir>,
2010 pub(crate) meta: FileMeta,
2011 readable: bool,
2012}
2013
2014#[derive(Clone, Debug)]
2015pub(crate) enum PreviewEntry {
2016 Directory(Arc<PreviewDirectory>),
2017 Missing,
2018 NonDirectory,
2019 Unavailable,
2020}
2021
2022impl PreviewDirectory {
2023 pub(crate) fn readable(&self) -> Option<Arc<Dir>> {
2024 self.readable.then(|| Arc::clone(&self.dir))
2025 }
2026
2027 pub(crate) async fn child(
2028 &self,
2029 name: &OsStr,
2030 readable: bool,
2031 ) -> std::io::Result<PreviewEntry> {
2032 open_preview_entry(&self.dir, name, readable).await
2033 }
2034}
2035
2036#[cfg(test)]
2037pub(crate) async fn preview_from_readable(dir: Arc<Dir>) -> std::io::Result<PreviewEntry> {
2038 let meta = dir.meta().await?;
2039 Ok(PreviewEntry::Directory(Arc::new(PreviewDirectory {
2040 dir,
2041 meta,
2042 readable: true,
2043 })))
2044}
2045
2046pub(crate) async fn open_preview_entry(
2049 parent: &Dir,
2050 name: &OsStr,
2051 readable: bool,
2052) -> std::io::Result<PreviewEntry> {
2053 if !is_single_component(name) {
2054 return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
2055 }
2056 let parent_fd = Arc::clone(&parent.fd);
2057 let side = parent.side;
2058 let name = name.to_owned();
2059 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2060 let access = if readable {
2061 OFlag::O_RDONLY
2062 } else {
2063 OFlag::O_PATH
2064 };
2065 let flags = access | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
2066 let fd = match openat(parent_fd.as_fd(), name.as_bytes(), flags, Mode::empty()) {
2067 Ok(fd) => fd,
2068 Err(nix::errno::Errno::ENOENT) => return Ok(PreviewEntry::Missing),
2069 Err(nix::errno::Errno::ENOTDIR | nix::errno::Errno::ELOOP) => {
2070 return Ok(PreviewEntry::NonDirectory);
2071 }
2072 Err(nix::errno::Errno::EACCES) if !readable => return Ok(PreviewEntry::Unavailable),
2073 Err(error) => return Err(nix_to_io(error)),
2074 };
2075 let dir = Dir::opened_with_credit(fd, side, parent_fd.credit.clone());
2076 #[cfg(test)]
2077 let _visit = resource_tests::gate_opened_descriptor(dir.fd.as_raw_fd())?;
2078 let (dir, meta) = dir.with_metadata_snapshot()?;
2079 Ok(PreviewEntry::Directory(Arc::new(PreviewDirectory {
2080 dir: Arc::new(dir),
2081 meta,
2082 readable,
2083 })))
2084 })
2085 .await
2086}
2087
2088pub async fn strict_probe_dst_kind(
2099 path: &Path,
2100 side: congestion::Side,
2101) -> std::io::Result<Option<EntryKind>> {
2102 let Some((parent, name)) = split_parent_and_name(path) else {
2103 return Ok(None);
2104 };
2105 match Dir::open_parent_dir(parent, side).await {
2106 Ok(parent) => match parent.into_tree().child(name).await {
2107 Ok(handle) => Ok(Some(handle.kind())),
2108 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
2109 Err(err) => Err(err),
2110 },
2111 Err(err)
2112 if err.kind() == std::io::ErrorKind::NotFound
2113 || err.raw_os_error() == Some(libc::ENOTDIR) =>
2114 {
2115 Ok(None)
2116 }
2117 Err(err) => Err(err),
2118 }
2119}
2120
2121#[derive(Debug)]
2198enum DefaultAclGuard {
2199 Armed { original: Option<Vec<u8>> },
2203 Disarmed,
2206}
2207
2208#[derive(Debug)]
2209pub struct ReusedDirLock {
2210 pub restore_owner: (u32, u32),
2212 state: Arc<std::sync::Mutex<DefaultAclGuard>>,
2215 fd: Arc<DirectoryDescriptor>,
2220 children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
2225}
2226
2227impl ReusedDirLock {
2228 fn original_default_acl(&self) -> Option<Vec<u8>> {
2231 match &*self.state.lock().unwrap() {
2232 DefaultAclGuard::Armed { original } => original.clone(),
2233 DefaultAclGuard::Disarmed => None,
2234 }
2235 }
2236
2237 fn disarm(&self) {
2241 *self.state.lock().unwrap() = DefaultAclGuard::Disarmed;
2242 }
2243
2244 async fn write_default_acl_guarded(
2254 &self,
2255 side: congestion::Side,
2256 blob: Vec<u8>,
2257 ) -> std::io::Result<()> {
2258 let state = Arc::clone(&self.state);
2259 let fd = Arc::clone(&self.fd);
2260 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2261 let guard = state.lock().unwrap();
2262 match &*guard {
2263 DefaultAclGuard::Armed { .. } => {
2264 apply_one_acl(fd.as_raw_fd(), ACL_DEFAULT_XATTR, Some(&blob))
2265 }
2266 DefaultAclGuard::Disarmed => {
2267 tracing::debug!(
2270 "skipped a default-ACL write that lost its race against the lockdown \
2271 guard's restore ({} bytes)",
2272 blob.len(),
2273 );
2274 Ok(())
2275 }
2276 }
2277 })
2278 .await
2279 }
2280}
2281
2282impl Drop for ReusedDirLock {
2283 fn drop(&mut self) {
2284 self.children_may_inherit
2290 .store(true, std::sync::atomic::Ordering::SeqCst);
2291 let state = match self.state.try_lock() {
2301 Ok(guard) => guard,
2302 Err(std::sync::TryLockError::WouldBlock) => {
2303 let state = Arc::clone(&self.state);
2304 let fd = Arc::clone(&self.fd);
2305 let flag_note = "detached (a guarded write held the rollback mutex)";
2306 std::thread::spawn(move || {
2307 let guard = state
2310 .lock()
2311 .unwrap_or_else(|poisoned| poisoned.into_inner());
2312 rollback_default_acl(guard, &fd, flag_note);
2313 });
2314 return;
2315 }
2316 Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
2318 };
2319 rollback_default_acl(state, &self.fd, "inline");
2320 }
2321}
2322
2323fn rollback_default_acl(
2328 mut state: std::sync::MutexGuard<'_, DefaultAclGuard>,
2329 fd: &DirectoryDescriptor,
2330 how: &str,
2331) {
2332 {
2333 let DefaultAclGuard::Armed { original } =
2334 std::mem::replace(&mut *state, DefaultAclGuard::Disarmed)
2335 else {
2336 return;
2337 };
2338 let raw = fd.as_raw_fd();
2339 let _ = how;
2340 let path = std::fs::read_link(format!("/proc/self/fd/{raw}"))
2344 .map_or_else(|_| format!("<fd {raw}>"), |p| p.display().to_string());
2345 let restore = apply_one_acl(raw, ACL_DEFAULT_XATTR, original.as_deref());
2346 match (restore, &original) {
2347 (Ok(()), Some(blob)) => tracing::debug!(
2348 "restored the default ACL of reused destination directory {} after an aborted \
2349 copy ({} bytes)",
2350 path,
2351 blob.len(),
2352 ),
2353 (Ok(()), None) => tracing::debug!(
2354 "ensured reused destination directory {} carries no default ACL after an aborted \
2355 copy (it had none before it)",
2356 path,
2357 ),
2358 (Err(error), Some(blob)) => tracing::warn!(
2359 "could not restore the default ACL of reused destination directory {} after an \
2360 aborted copy: {:#}. It is left with NO default ACL; it had {} bytes ({:02x?}), \
2361 which must be re-applied by hand to restore what entries created beneath it \
2362 inherit.",
2363 path,
2364 &error,
2365 blob.len(),
2366 blob,
2367 ),
2368 (Err(error), None) => tracing::warn!(
2369 "could not remove a partially-applied default ACL from reused destination \
2370 directory {} after an aborted copy: {:#}. The directory had NO default ACL \
2371 before the copy; whatever the aborted finalize installed remains and must be \
2372 removed by hand.",
2373 path,
2374 &error,
2375 ),
2376 }
2377 }
2378}
2379
2380pub async fn lockdown_reused_dir(
2434 dir: &Dir,
2435 handle: &Handle,
2436) -> std::io::Result<Option<ReusedDirLock>> {
2437 lockdown_reused_dir_with(dir, handle, || {}).await
2438}
2439
2440pub(crate) async fn lockdown_reused_dir_with(
2444 dir: &Dir,
2445 handle: &Handle,
2446 on_mutation: impl FnOnce() + Send + 'static,
2447) -> std::io::Result<Option<ReusedDirLock>> {
2448 if !strict_operand_resolution() {
2449 return Ok(None);
2450 }
2451 use crate::preserve::Metadata as _;
2452 use std::os::unix::fs::PermissionsExt as _;
2453 let orig_meta = handle.meta();
2454 let restore_owner = (orig_meta.uid(), orig_meta.gid());
2455 dir.verify_same_inode(handle).await?;
2456 let want_setgid = orig_meta.permissions().mode() & 0o2000 != 0;
2466 let interim_mode = if want_setgid { 0o2700 } else { 0o700 };
2467 dir.secure_as_copier_with(interim_mode, orig_meta.uid(), orig_meta.gid(), on_mutation)
2468 .await?;
2469 let original = read_acls_fd(dir.fd.as_fd(), dir.side, true).await?.default;
2474 let needs_strip = original.is_some();
2475 let lock = ReusedDirLock {
2481 restore_owner,
2482 state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed { original })),
2483 fd: Arc::clone(&dir.fd),
2484 children_may_inherit: Arc::clone(&dir.children_may_inherit),
2485 };
2486 if needs_strip {
2487 let raw = dir.fd.as_raw_fd();
2488 crate::walk::run_metadata_probed(dir.side, congestion::MetadataOp::Chmod, async {
2504 apply_one_acl(raw, ACL_DEFAULT_XATTR, None)
2505 })
2506 .await?;
2507 }
2511 dir.mark_children_cannot_inherit();
2515 Ok(Some(lock))
2516}
2517
2518const ACL_ACCESS_XATTR: &CStr = c"system.posix_acl_access";
2531
2532const ACL_DEFAULT_XATTR: &CStr = c"system.posix_acl_default";
2535
2536#[derive(Clone, Debug, Default, PartialEq, Eq)]
2543pub struct Acls {
2544 pub access: Option<Vec<u8>>,
2546 pub default: Option<Vec<u8>>,
2548}
2549
2550pub async fn read_acls_fd(
2566 fd: BorrowedFd<'_>,
2567 side: congestion::Side,
2568 want_default: bool,
2569) -> std::io::Result<Acls> {
2570 let owned = fd.try_clone_to_owned()?;
2573 read_acls_owned(owned, side, want_default)
2574 .await
2575 .map(|(_, acls)| acls)
2576}
2577
2578pub(crate) async fn read_acls_owned<F: AsRawFd + Send + 'static>(
2582 owned: F,
2583 side: congestion::Side,
2584 want_default: bool,
2585) -> std::io::Result<(F, Acls)> {
2586 let (owned, names) =
2587 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2588 #[cfg(test)]
2589 let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
2590 let names = flistxattr_names(owned.as_raw_fd())?;
2591 Ok((owned, names))
2592 })
2593 .await?;
2594 let (owned, access) = if names_contain(&names, ACL_ACCESS_XATTR) {
2595 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2596 let access = fgetxattr_blob(owned.as_raw_fd(), ACL_ACCESS_XATTR)?;
2597 Ok((owned, access))
2598 })
2599 .await?
2600 } else {
2601 (owned, None)
2602 };
2603 let (owned, default) = if want_default && names_contain(&names, ACL_DEFAULT_XATTR) {
2604 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2605 let default = fgetxattr_blob(owned.as_raw_fd(), ACL_DEFAULT_XATTR)?;
2606 Ok((owned, default))
2607 })
2608 .await?
2609 } else {
2610 (owned, None)
2611 };
2612 Ok((owned, Acls { access, default }))
2613}
2614
2615pub async fn apply_acls_fd(
2628 fd: BorrowedFd<'_>,
2629 side: congestion::Side,
2630 acls: &Acls,
2631 want_default: bool,
2632) -> std::io::Result<()> {
2633 if want_default {
2634 set_or_remove_acl_fd(fd, side, ACL_DEFAULT_XATTR, acls.default.clone()).await?;
2635 }
2636 set_or_remove_acl_fd(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await
2637}
2638
2639async fn set_or_remove_acl_fd(
2649 fd: BorrowedFd<'_>,
2650 side: congestion::Side,
2651 name: &'static CStr,
2652 blob: Option<Vec<u8>>,
2653) -> std::io::Result<()> {
2654 set_or_remove_acl_owned(fd.try_clone_to_owned()?, side, name, blob)
2655 .await
2656 .map(drop)
2657}
2658
2659async fn set_or_remove_acl_owned(
2660 owned: OwnedFd,
2661 side: congestion::Side,
2662 name: &'static CStr,
2663 blob: Option<Vec<u8>>,
2664) -> std::io::Result<OwnedFd> {
2665 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2666 apply_one_acl(owned.as_raw_fd(), name, blob.as_deref())?;
2667 Ok(owned)
2668 })
2669 .await
2670}
2671
2672fn acls_to_apply(want: bool, acls: Option<&Acls>) -> std::io::Result<Option<&Acls>> {
2686 match (want, acls) {
2687 (false, _) => Ok(None),
2688 (true, Some(acls)) => Ok(Some(acls)),
2689 (true, None) => Err(std::io::Error::new(
2690 std::io::ErrorKind::Unsupported,
2691 "ACL preservation was requested but this copy path does not carry the source's ACLs",
2692 )),
2693 }
2694}
2695
2696fn listxattr_retry(
2703 mut call: impl FnMut(*mut libc::c_char, usize) -> isize,
2704) -> std::io::Result<Vec<u8>> {
2705 let mut buf = [0u8; 256];
2708 let n = call(buf.as_mut_ptr().cast(), buf.len());
2709 if n >= 0 {
2710 return Ok(buf[..n as usize].to_vec());
2711 }
2712 let err = std::io::Error::last_os_error();
2713 match err.raw_os_error() {
2714 Some(libc::EOPNOTSUPP) => Ok(Vec::new()),
2715 Some(libc::ERANGE) => {
2716 let size = call(std::ptr::null_mut(), 0);
2717 if size < 0 {
2718 return Err(std::io::Error::last_os_error());
2719 }
2720 let mut heap = vec![0u8; size as usize];
2721 if heap.is_empty() {
2722 return Ok(heap);
2723 }
2724 let n = call(heap.as_mut_ptr().cast(), heap.len());
2725 if n < 0 {
2726 return Err(std::io::Error::last_os_error());
2729 }
2730 heap.truncate(n as usize);
2731 Ok(heap)
2732 }
2733 _ => Err(err),
2734 }
2735}
2736
2737fn flistxattr_names(fd: RawFd) -> std::io::Result<Vec<u8>> {
2739 listxattr_retry(|buf, len| unsafe { libc::flistxattr(fd, buf, len) })
2742}
2743
2744fn listxattr_names_at_path(path: &CStr) -> std::io::Result<Vec<u8>> {
2749 let probe = |buf, len| {
2754 unsafe { libc::listxattr(path.as_ptr(), buf, len) } };
2756 listxattr_retry(probe)
2757}
2758
2759fn names_contain(list: &[u8], name: &CStr) -> bool {
2761 list.split(|byte| *byte == 0).any(|n| n == name.to_bytes())
2762}
2763
2764fn fgetxattr_blob(fd: RawFd, name: &CStr) -> std::io::Result<Option<Vec<u8>>> {
2769 let mut buf = [0u8; 512];
2772 let n = unsafe { libc::fgetxattr(fd, name.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
2775 if n >= 0 {
2776 return Ok(Some(buf[..n as usize].to_vec()));
2777 }
2778 let err = std::io::Error::last_os_error();
2779 match err.raw_os_error() {
2780 Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(None),
2781 Some(libc::ERANGE) => {
2782 let size = unsafe { libc::fgetxattr(fd, name.as_ptr(), std::ptr::null_mut(), 0) };
2785 if size < 0 {
2786 return Err(std::io::Error::last_os_error());
2787 }
2788 let mut heap = vec![0u8; size as usize];
2789 if heap.is_empty() {
2790 return Ok(Some(heap));
2791 }
2792 let n =
2794 unsafe { libc::fgetxattr(fd, name.as_ptr(), heap.as_mut_ptr().cast(), heap.len()) };
2795 if n < 0 {
2796 return Err(std::io::Error::last_os_error());
2799 }
2800 heap.truncate(n as usize);
2801 Ok(Some(heap))
2802 }
2803 _ => Err(err),
2804 }
2805}
2806
2807fn apply_one_acl(fd: RawFd, name: &CStr, blob: Option<&[u8]>) -> std::io::Result<()> {
2820 let Some(blob) = blob else {
2821 if unsafe { libc::fremovexattr(fd, name.as_ptr()) } == 0 {
2824 return Ok(());
2825 }
2826 let err = std::io::Error::last_os_error();
2827 return match err.raw_os_error() {
2828 Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(()),
2829 _ => Err(err),
2830 };
2831 };
2832 let rc = unsafe {
2835 libc::fsetxattr(
2836 fd,
2837 name.as_ptr(),
2838 blob.as_ptr().cast(),
2839 blob.len(),
2840 0, )
2842 };
2843 if rc == 0 {
2844 Ok(())
2845 } else {
2846 Err(std::io::Error::last_os_error())
2847 }
2848}
2849
2850static ROOT_ACL_PROBED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2870
2871#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2877pub struct RootAclNotice {
2878 pub wanted: bool,
2888 pub file_acl_preserved: bool,
2892 pub dir_acl_preserved: bool,
2894}
2895
2896impl RootAclNotice {
2897 #[must_use]
2899 pub fn for_preserve(preserve: &crate::preserve::Settings) -> Self {
2900 Self {
2901 wanted: preserve.requests_preservation(),
2902 file_acl_preserved: preserve.file.acl,
2903 dir_acl_preserved: preserve.dir.acl,
2904 }
2905 }
2906
2907 fn could_warn_for(self, kind: EntryKind) -> bool {
2918 self.could_warn_for_strict(kind, strict_operand_resolution())
2919 }
2920
2921 fn could_warn_for_strict(self, kind: EntryKind, strict: bool) -> bool {
2924 (self.wanted || strict)
2925 && match kind {
2926 EntryKind::File => !self.file_acl_preserved,
2927 EntryKind::Dir => !self.dir_acl_preserved,
2928 EntryKind::Symlink | EntryKind::Special => false,
2929 }
2930 }
2931
2932 fn could_warn(self) -> bool {
2935 self.could_warn_for(EntryKind::File) || self.could_warn_for(EntryKind::Dir)
2936 }
2937}
2938
2939async fn has_acl_via_proc_fd(handle: &Handle, side: congestion::Side) -> std::io::Result<bool> {
2952 let owned = handle.as_fd().try_clone_to_owned()?;
2955 let names = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2956 let proc_path = std::ffi::CString::new(format!("/proc/self/fd/{}", owned.as_raw_fd()))
2957 .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
2958 listxattr_names_at_path(&proc_path)
2959 })
2960 .await?;
2961 Ok(names_contain(&names, ACL_ACCESS_XATTR) || names_contain(&names, ACL_DEFAULT_XATTR))
2962}
2963
2964#[must_use]
2973pub fn root_acl_probe_worth_reaching(notice: RootAclNotice) -> bool {
2974 if !notice.could_warn() {
2975 return false;
2976 }
2977 !ROOT_ACL_PROBED.load(std::sync::atomic::Ordering::Relaxed)
2978}
2979
2980fn claim_root_acl_probe() -> bool {
2989 !ROOT_ACL_PROBED.swap(true, std::sync::atomic::Ordering::Relaxed)
2990}
2991
2992async fn warn_root_acl(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
3001 if !notice.could_warn_for(handle.kind()) {
3002 return;
3003 }
3004 if !claim_root_acl_probe() {
3007 return;
3008 }
3009 match has_acl_via_proc_fd(handle, congestion::Side::Source).await {
3013 Ok(false) => {}
3014 Ok(true) if strict_operand_resolution() => tracing::warn!(
3015 target: crate::NOTICE_TARGET,
3016 "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
3017 (`--preserve-settings` does not request `acl`). --require-toctou-safe stops the \
3018 DESTINATION tree's ACLs from being inherited, but it does not carry the SOURCE's \
3019 across, so the copy can still end up more permissive than what it copied. Use \
3020 `--preserve-settings=all+acl`. Only the root was checked - entries beneath it may \
3021 carry ACLs this says nothing about."
3022 ),
3023 Ok(true) => tracing::warn!(
3024 target: crate::NOTICE_TARGET,
3025 "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
3026 (`--preserve-settings` does not request `acl`), so the destination may end up more \
3027 permissive than its source. Use `--preserve-settings=all+acl`. Only the root was \
3028 checked - entries beneath it may carry ACLs this says nothing about."
3029 ),
3030 Err(err) => {
3031 tracing::debug!("cannot probe {src_root:?} for a POSIX ACL: {err:#}");
3032 }
3033 }
3034}
3035
3036pub async fn warn_if_root_acl_unpreserved(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
3047 if !root_acl_probe_worth_reaching(notice) {
3048 return;
3049 }
3050 warn_root_acl(handle, src_root, notice).await;
3051}
3052
3053pub async fn warn_if_root_acl_unpreserved_at(
3063 parent: &Dir,
3064 name: &OsStr,
3065 src_root: &Path,
3066 notice: RootAclNotice,
3067) {
3068 if !root_acl_probe_worth_reaching(notice) {
3069 return;
3070 }
3071 match parent.child(name).await {
3072 Ok(handle) => warn_root_acl(&handle, src_root, notice).await,
3073 Err(err) => {
3074 tracing::debug!("cannot open source root {src_root:?} for a POSIX ACL probe: {err:#}");
3075 }
3076 }
3077}
3078
3079async fn fchown_fd(
3103 fd: BorrowedFd<'_>,
3104 side: congestion::Side,
3105 uid: Option<u32>,
3106 gid: Option<u32>,
3107) -> std::io::Result<()> {
3108 fchown_owned(fd.try_clone_to_owned()?, side, uid, gid)
3109 .await
3110 .map(drop)
3111}
3112
3113async fn fchown_owned(
3114 owned: OwnedFd,
3115 side: congestion::Side,
3116 uid: Option<u32>,
3117 gid: Option<u32>,
3118) -> std::io::Result<OwnedFd> {
3119 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3120 #[cfg(test)]
3121 let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
3122 fchown(
3123 owned.as_fd(),
3124 uid.map(Uid::from_raw),
3125 gid.map(Gid::from_raw),
3126 )
3127 .map_err(nix_to_io)?;
3128 Ok(owned)
3129 })
3130 .await
3131}
3132
3133async fn fchmod_fd(fd: BorrowedFd<'_>, side: congestion::Side, mode: u32) -> std::io::Result<()> {
3141 fchmod_owned(fd.try_clone_to_owned()?, side, mode)
3142 .await
3143 .map(drop)
3144}
3145
3146async fn fchmod_owned(
3147 owned: OwnedFd,
3148 side: congestion::Side,
3149 mode: u32,
3150) -> std::io::Result<OwnedFd> {
3151 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3152 fchmod(owned.as_fd(), Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
3153 Ok(owned)
3154 })
3155 .await
3156}
3157
3158async fn futimens_fd(
3160 fd: BorrowedFd<'_>,
3161 side: congestion::Side,
3162 atime: i64,
3163 atime_nsec: i64,
3164 mtime: i64,
3165 mtime_nsec: i64,
3166) -> std::io::Result<()> {
3167 futimens_owned(
3168 fd.try_clone_to_owned()?,
3169 side,
3170 atime,
3171 atime_nsec,
3172 mtime,
3173 mtime_nsec,
3174 )
3175 .await
3176 .map(drop)
3177}
3178
3179async fn futimens_owned(
3180 owned: OwnedFd,
3181 side: congestion::Side,
3182 atime: i64,
3183 atime_nsec: i64,
3184 mtime: i64,
3185 mtime_nsec: i64,
3186) -> std::io::Result<OwnedFd> {
3187 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3188 let atime_spec = TimeSpec::new(atime, atime_nsec);
3189 let mtime_spec = TimeSpec::new(mtime, mtime_nsec);
3190 futimens(owned.as_fd(), &atime_spec, &mtime_spec).map_err(nix_to_io)?;
3191 Ok(owned)
3192 })
3193 .await
3194}
3195
3196pub(crate) async fn fchown_handle(
3206 handle: &Handle,
3207 side: congestion::Side,
3208 uid: Option<u32>,
3209 gid: Option<u32>,
3210) -> std::io::Result<()> {
3211 let owned = handle.as_fd().try_clone_to_owned()?;
3212 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3213 fchownat(
3214 owned.as_fd(),
3215 "",
3216 uid.map(Uid::from_raw),
3217 gid.map(Gid::from_raw),
3218 AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_NOFOLLOW,
3219 )
3220 .map_err(nix_to_io)
3221 })
3222 .await
3223}
3224
3225pub(crate) async fn chmod_via_proc_fd(
3262 handle: &Handle,
3263 side: congestion::Side,
3264 mode: u32,
3265) -> std::io::Result<()> {
3266 let owned = handle.as_fd().try_clone_to_owned()?;
3271 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3272 let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3273 nix::sys::stat::fchmodat(
3277 AT_FDCWD,
3278 proc_path.as_str(),
3279 Mode::from_bits_truncate(mode),
3280 nix::sys::stat::FchmodatFlags::FollowSymlink,
3281 )
3282 .map_err(nix_to_io)
3283 })
3284 .await
3285}
3286
3287pub(crate) async fn stat_meta_via_proc_fd(
3298 handle: &Handle,
3299 side: congestion::Side,
3300) -> std::io::Result<std::fs::Metadata> {
3301 let owned = handle.as_fd().try_clone_to_owned()?;
3302 run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
3303 let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3304 std::fs::metadata(proc_path)
3305 })
3306 .await
3307}
3308
3309pub async fn read_link_handle(
3323 handle: &Handle,
3324 side: congestion::Side,
3325) -> std::io::Result<std::path::PathBuf> {
3326 use std::os::unix::ffi::OsStringExt;
3327 let owned = handle.as_fd().try_clone_to_owned()?;
3328 run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
3329 let mut buf = vec![0u8; libc::PATH_MAX as usize];
3331 let n = unsafe {
3334 libc::readlinkat(
3335 owned.as_raw_fd(),
3336 c"".as_ptr(),
3337 buf.as_mut_ptr().cast::<libc::c_char>(),
3338 buf.len(),
3339 )
3340 };
3341 if n < 0 {
3342 return Err(std::io::Error::last_os_error());
3343 }
3344 buf.truncate(n as usize);
3345 Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(buf)))
3346 })
3347 .await
3348}
3349
3350async fn symlink_utimes_fd(
3357 handle: &Handle,
3358 side: congestion::Side,
3359 atime: i64,
3360 atime_nsec: i64,
3361 mtime: i64,
3362 mtime_nsec: i64,
3363) -> std::io::Result<()> {
3364 let owned = handle.as_fd().try_clone_to_owned()?;
3365 run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3366 let times: [libc::timespec; 2] = [
3367 libc::timespec {
3368 tv_sec: atime,
3369 tv_nsec: atime_nsec,
3370 },
3371 libc::timespec {
3372 tv_sec: mtime,
3373 tv_nsec: mtime_nsec,
3374 },
3375 ];
3376 let res = unsafe {
3379 libc::utimensat(
3380 owned.as_raw_fd(),
3381 c"".as_ptr(),
3382 times.as_ptr(),
3383 libc::AT_EMPTY_PATH,
3384 )
3385 };
3386 if res == 0 {
3387 Ok(())
3388 } else {
3389 Err(std::io::Error::last_os_error())
3390 }
3391 })
3392 .await
3393}
3394
3395pub async fn set_file_metadata_owned<Meta: crate::preserve::Metadata>(
3444 settings: &crate::preserve::Settings,
3445 meta: &Meta,
3446 acls: Option<&Acls>,
3447 fd: OwnedFd,
3448 side: congestion::Side,
3449) -> std::io::Result<()> {
3450 let ut = &settings.file.user_and_time;
3451 let fd = if ut.uid || ut.gid {
3452 let uid = if ut.uid { Some(meta.uid()) } else { None };
3453 let gid = if ut.gid { Some(meta.gid()) } else { None };
3454 fchown_owned(fd, side, uid, gid).await?
3455 } else {
3456 fd
3457 };
3458 let fd = if ut.time {
3459 futimens_owned(
3460 fd,
3461 side,
3462 meta.atime(),
3463 meta.atime_nsec(),
3464 meta.mtime(),
3465 meta.mtime_nsec(),
3466 )
3467 .await?
3468 } else {
3469 fd
3470 };
3471 let acls = acls_to_apply(settings.file.acl, acls)?;
3472 let mode = crate::preserve::masked_mode(settings.file.mode_mask, meta);
3473 if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3474 let fd = fchmod_owned(fd, side, (mode & 0o7000) | DST_FILE_CREATE_MODE).await?;
3476 set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?;
3477 } else {
3478 let fd = if let Some(acls) = acls {
3480 set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?
3481 } else {
3482 fd
3483 };
3484 fchmod_owned(fd, side, mode).await?;
3485 }
3486 Ok(())
3487}
3488
3489pub async fn set_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3514 settings: &crate::preserve::Settings,
3515 meta: &Meta,
3516 acls: Option<&Acls>,
3517 dir: &Dir,
3518) -> std::io::Result<()> {
3519 set_dir_metadata_fd_inner(settings, meta, acls, dir, true).await
3520}
3521
3522async fn set_dir_metadata_fd_inner<Meta: crate::preserve::Metadata>(
3529 settings: &crate::preserve::Settings,
3530 meta: &Meta,
3531 acls: Option<&Acls>,
3532 dir: &Dir,
3533 apply_default: bool,
3534) -> std::io::Result<()> {
3535 let side = dir.side();
3536 let fd = dir.fd.as_fd();
3537 let ut = &settings.dir.user_and_time;
3538 if ut.uid || ut.gid {
3539 let uid = if ut.uid { Some(meta.uid()) } else { None };
3540 let gid = if ut.gid { Some(meta.gid()) } else { None };
3541 fchown_fd(fd, side, uid, gid).await?;
3542 }
3543 let acls = acls_to_apply(settings.dir.acl, acls)?;
3544 let mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3545 if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3546 fchmod_fd(fd, side, (mode & 0o7000) | DST_DIR_CREATE_MODE).await?;
3548 apply_acls_fd(fd, side, acls, apply_default).await?;
3549 } else {
3550 if let Some(acls) = acls {
3555 apply_acls_fd(fd, side, acls, apply_default).await?;
3556 }
3557 fchmod_fd(fd, side, mode).await?;
3558 }
3559 if ut.time {
3560 futimens_fd(
3561 fd,
3562 side,
3563 meta.atime(),
3564 meta.atime_nsec(),
3565 meta.mtime(),
3566 meta.mtime_nsec(),
3567 )
3568 .await?;
3569 }
3570 Ok(())
3571}
3572
3573pub async fn set_reused_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3638 settings: &crate::preserve::Settings,
3639 meta: &Meta,
3640 acls: Option<&Acls>,
3641 lock: Option<ReusedDirLock>,
3642 dir: &Dir,
3643) -> std::io::Result<()> {
3644 let Some(lock) = lock else {
3652 return set_dir_metadata_fd(settings, meta, acls, dir).await;
3653 };
3654 let (orig_uid, orig_gid) = lock.restore_owner;
3655 let final_default = if settings.dir.acl {
3660 acls_to_apply(true, acls)?.and_then(|acls| acls.default.clone())
3662 } else {
3663 lock.original_default_acl()
3664 };
3665 if let Some(blob) = final_default {
3666 lock.write_default_acl_guarded(dir.side, blob).await?;
3667 }
3668 let ut = &settings.dir.user_and_time;
3669 {
3670 let uid = (!ut.uid).then_some(orig_uid);
3671 let gid = (!ut.gid).then_some(orig_gid);
3672 if uid.is_some() || gid.is_some() {
3673 fchown_fd(dir.fd.as_fd(), dir.side, uid, gid).await?;
3674 }
3675 }
3676 set_dir_metadata_fd_inner(settings, meta, acls, dir, false).await?;
3679 use crate::preserve::Metadata as _;
3701 use std::os::unix::fs::PermissionsExt as _;
3702 let want_uid = if ut.uid { meta.uid() } else { orig_uid };
3703 let want_gid = if ut.gid { meta.gid() } else { orig_gid };
3704 let want_mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3705 let got = dir.meta().await?;
3706 let got_mode = got.permissions().mode() & 0o7777;
3707 if got.uid() != want_uid || got.gid() != want_gid {
3708 return Err(std::io::Error::new(
3709 std::io::ErrorKind::PermissionDenied,
3710 format!(
3711 "reused-directory finalize could not be verified: the directory shows uid={} gid={} \
3712 (expected uid={} gid={}); the filesystem may not honor chown/chmod",
3713 got.uid(),
3714 got.gid(),
3715 want_uid,
3716 want_gid,
3717 ),
3718 ));
3719 }
3720 if got_mode != want_mode {
3721 if want_mode & 0o2000 != 0 && want_mode & !0o2000 == got_mode {
3722 tracing::warn!(
3724 "setgid not applied to reused directory (final mode {:#o} vs source {:#o}): the \
3725 copier is not in the directory's group and lacks CAP_FSETID",
3726 got_mode,
3727 want_mode,
3728 );
3729 } else {
3730 return Err(std::io::Error::new(
3731 std::io::ErrorKind::PermissionDenied,
3732 format!(
3733 "reused-directory finalize could not be verified: the directory shows \
3734 mode={:#o} (expected {:#o}); the filesystem may not honor chmod",
3735 got_mode, want_mode,
3736 ),
3737 ));
3738 }
3739 }
3740 lock.disarm();
3744 Ok(())
3745}
3746
3747pub async fn set_symlink_metadata_fd<Meta: crate::preserve::Metadata>(
3753 settings: &crate::preserve::Settings,
3754 meta: &Meta,
3755 handle: &Handle,
3756 side: congestion::Side,
3757) -> std::io::Result<()> {
3758 let ut = &settings.symlink.user_and_time;
3759 if ut.uid || ut.gid {
3760 let uid = if ut.uid { Some(meta.uid()) } else { None };
3761 let gid = if ut.gid { Some(meta.gid()) } else { None };
3762 fchown_handle(handle, side, uid, gid).await?;
3765 }
3766 if ut.time {
3767 symlink_utimes_fd(
3768 handle,
3769 side,
3770 meta.atime(),
3771 meta.atime_nsec(),
3772 meta.mtime(),
3773 meta.mtime_nsec(),
3774 )
3775 .await?;
3776 }
3777 Ok(())
3778}
3779
3780struct BlockingJob<F> {
3787 work: F,
3788 admission: Option<throttle::BlockingFdAdmissionLease>,
3789}
3790
3791type BlockingJobOutput<T> = (
3792 std::io::Result<T>,
3793 Option<throttle::BlockingFdAdmissionLease>,
3794);
3795
3796impl<F> BlockingJob<F> {
3797 fn run<T>(self) -> BlockingJobOutput<T>
3798 where
3799 F: FnOnce() -> std::io::Result<T>,
3800 {
3801 let Self { work, admission } = self;
3802 (work(), admission)
3803 }
3804}
3805
3806fn take_blocking_job<F>(
3807 shared_job: &std::sync::Mutex<Option<BlockingJob<F>>>,
3808) -> Option<BlockingJob<F>> {
3809 shared_job
3810 .lock()
3811 .unwrap_or_else(std::sync::PoisonError::into_inner)
3812 .take()
3813}
3814
3815struct BlockingJobWaiter<F, T> {
3817 shared_job: Arc<std::sync::Mutex<Option<BlockingJob<F>>>>,
3818 handle: tokio::task::JoinHandle<Option<BlockingJobOutput<T>>>,
3819}
3820
3821impl<F, T> std::future::Future for BlockingJobWaiter<F, T> {
3822 type Output = Result<Option<BlockingJobOutput<T>>, tokio::task::JoinError>;
3823
3824 fn poll(
3825 self: std::pin::Pin<&mut Self>,
3826 cx: &mut std::task::Context<'_>,
3827 ) -> std::task::Poll<Self::Output> {
3828 let this = self.get_mut();
3829 std::future::Future::poll(std::pin::Pin::new(&mut this.handle), cx)
3830 }
3831}
3832
3833impl<F, T> Drop for BlockingJobWaiter<F, T> {
3834 fn drop(&mut self) {
3835 let queued_job = take_blocking_job(&self.shared_job);
3836 drop(queued_job);
3837 self.handle.abort();
3838 }
3839}
3840
3841pub(crate) async fn run_fd_admitted_blocking<F, T>(f: F) -> std::io::Result<T>
3843where
3844 F: FnOnce() -> std::io::Result<T> + Send + 'static,
3845 T: Send + 'static,
3846{
3847 let blocking_admission = FD_ADMISSION
3851 .try_with(throttle::FdAdmission::blocking_lease)
3852 .ok();
3853 run_blocking_job(BlockingJob {
3854 work: f,
3855 admission: blocking_admission,
3856 })
3857 .await
3858}
3859
3860pub async fn run_fd_admitted_blocking_with<F, T>(
3872 admission: &throttle::OpenFileGuard,
3873 f: F,
3874) -> std::io::Result<T>
3875where
3876 F: FnOnce() -> std::io::Result<T> + Send + 'static,
3877 T: Send + 'static,
3878{
3879 run_blocking_job(BlockingJob {
3880 work: f,
3881 admission: Some(admission.admission().blocking_lease()),
3882 })
3883 .await
3884}
3885
3886async fn run_blocking_job<F, T>(job: BlockingJob<F>) -> std::io::Result<T>
3887where
3888 F: FnOnce() -> std::io::Result<T> + Send + 'static,
3889 T: Send + 'static,
3890{
3891 let shared_job = Arc::new(std::sync::Mutex::new(Some(job)));
3892 let worker_job = Arc::clone(&shared_job);
3893 #[cfg(test)]
3894 crate::testutils::record_blocking_submission();
3895 let handle =
3896 tokio::task::spawn_blocking(move || take_blocking_job(&worker_job).map(BlockingJob::run));
3897 let (result, _blocking_admission) = BlockingJobWaiter { shared_job, handle }
3898 .await
3899 .map_err(std::io::Error::other)?
3900 .expect("blocking job disappeared while its waiter was alive");
3901 result
3902}
3903
3904struct PendingContinuation<C>(Option<Arc<std::sync::Mutex<Option<C>>>>);
3906
3907impl<C> PendingContinuation<C> {
3908 fn claim(&mut self) -> Option<C> {
3909 let shared = self
3910 .0
3911 .take()
3912 .expect("continuation already claimed or cancelled");
3913 shared
3914 .lock()
3915 .unwrap_or_else(std::sync::PoisonError::into_inner)
3916 .take()
3917 }
3918
3919 fn cancel(&mut self) {
3920 let Some(shared) = self.0.take() else {
3921 return;
3922 };
3923 let mut pending = shared
3924 .lock()
3925 .unwrap_or_else(std::sync::PoisonError::into_inner);
3926 drop(pending.take());
3929 }
3930
3931 fn disarm(&mut self) {
3932 self.0 = None;
3933 }
3934}
3935
3936impl<C> Drop for PendingContinuation<C> {
3937 fn drop(&mut self) {
3938 self.cancel();
3939 }
3940}
3941
3942pin_project_lite::pin_project! {
3943 struct ContinuationWaiter<F, C> {
3945 continuation: PendingContinuation<C>,
3946 #[pin]
3947 future: F,
3948 }
3949
3950 impl<F, C> PinnedDrop for ContinuationWaiter<F, C> {
3951 fn drop(this: Pin<&mut Self>) {
3952 this.project().continuation.cancel();
3953 }
3954 }
3955}
3956
3957impl<F, C> std::future::Future for ContinuationWaiter<F, C>
3958where
3959 F: std::future::Future,
3960{
3961 type Output = F::Output;
3962
3963 fn poll(
3964 self: std::pin::Pin<&mut Self>,
3965 cx: &mut std::task::Context<'_>,
3966 ) -> std::task::Poll<Self::Output> {
3967 let this = self.project();
3968 let output = this.future.poll(cx);
3969 if output.is_ready() {
3970 this.continuation.disarm();
3972 }
3973 output
3974 }
3975}
3976
3977async fn run_file_create_and_then<F, C, T>(
3978 side: congestion::Side,
3979 operation: F,
3980 continuation: C,
3981) -> std::io::Result<T>
3982where
3983 F: FnOnce() -> std::io::Result<std::fs::File> + Send + 'static,
3984 C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
3985 T: Send + 'static,
3986{
3987 let operation =
3988 prepare_metadata_operation(side, congestion::MetadataOp::OpenCreate, operation).await;
3989 let pending = Arc::new(std::sync::Mutex::new(Some(continuation)));
3990 let mut worker_continuation = PendingContinuation(Some(Arc::clone(&pending)));
3993 let future = run_fd_admitted_blocking(move || {
3994 let created = operation();
3995 #[cfg(test)]
3996 let _visit = created.as_ref().ok().and_then(|file| {
3997 tests::gate_file_create_stage(file.as_raw_fd(), "before-continuation")
3998 });
3999 Ok(worker_continuation
4001 .claim()
4002 .map(|continuation| continuation(created)))
4003 });
4004 ContinuationWaiter {
4005 continuation: PendingContinuation(Some(pending)),
4006 future,
4007 }
4008 .await
4009 .map(|output| output.expect("continuation disappeared while its waiter was alive"))
4010}
4011
4012pub async fn run_metadata_probed_blocking<F, T>(
4021 side: congestion::Side,
4022 op: congestion::MetadataOp,
4023 f: F,
4024) -> std::io::Result<T>
4025where
4026 F: FnOnce() -> std::io::Result<T> + Send + 'static,
4027 T: Send + 'static,
4028{
4029 let operation = prepare_metadata_operation(side, op, f).await;
4030 run_fd_admitted_blocking(operation).await
4031}
4032
4033async fn prepare_metadata_operation<F, T>(
4034 side: congestion::Side,
4035 op: congestion::MetadataOp,
4036 f: F,
4037) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
4038where
4039 F: FnOnce() -> std::io::Result<T> + Send + 'static,
4040 T: Send + 'static,
4041{
4042 let rate = metadata_timing_scope(side, op, MetadataTimingPhase::Rate);
4043 throttle::get_ops_token().await;
4044 rate.finish();
4045 prepare_metadata_operation_no_rate(side, op, f).await
4046}
4047
4048pub async fn run_metadata_probed_blocking_no_rate<F, T>(
4051 side: congestion::Side,
4052 op: congestion::MetadataOp,
4053 f: F,
4054) -> std::io::Result<T>
4055where
4056 F: FnOnce() -> std::io::Result<T> + Send + 'static,
4057 T: Send + 'static,
4058{
4059 let operation = prepare_metadata_operation_no_rate(side, op, f).await;
4060 run_fd_admitted_blocking(operation).await
4061}
4062
4063async fn prepare_metadata_operation_no_rate<F, T>(
4064 side: congestion::Side,
4065 op: congestion::MetadataOp,
4066 f: F,
4067) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
4068where
4069 F: FnOnce() -> std::io::Result<T> + Send + 'static,
4070 T: Send + 'static,
4071{
4072 let admission = metadata_timing_scope(side, op, MetadataTimingPhase::Admission);
4073 let ops_permit = throttle::ops_in_flight_permit(crate::walk::meta_resource(side, op)).await;
4074 admission.finish();
4075 let probe = congestion::Probe::start_metadata(side, op);
4076 let timing_dispatch = tracing::enabled!(target: "rcp::timing", tracing::Level::TRACE)
4080 .then(|| tracing::dispatcher::get_default(Clone::clone));
4081 let queue = metadata_timing_scope(side, op, MetadataTimingPhase::Queue);
4082 move || {
4083 queue.finish();
4084 let execution = timing_dispatch.as_ref().map(|dispatch| {
4085 tracing::dispatcher::with_default(dispatch, || {
4086 metadata_timing_scope(side, op, MetadataTimingPhase::Execute)
4087 })
4088 });
4089 let result = f();
4090 match &result {
4091 Ok(_) => probe.complete_ok(0),
4092 Err(_) => probe.discard(),
4093 }
4094 drop(ops_permit);
4098 if let Some(execution) = execution {
4099 execution.finish();
4100 }
4101 result
4102 }
4103}
4104
4105fn nix_to_io(e: nix::errno::Errno) -> std::io::Error {
4107 std::io::Error::from_raw_os_error(e as i32)
4108}
4109
4110fn is_single_component(name: &OsStr) -> bool {
4113 if name.is_empty() || name == "." || name == ".." {
4114 return false;
4115 }
4116 !name.as_bytes().contains(&b'/')
4117}
4118
4119#[cfg(test)]
4122mod tests {
4123 use super::*;
4124 use crate::preserve::Metadata;
4125 use crate::testutils;
4126 use std::io::Read;
4127 use std::num::NonZeroUsize;
4128
4129 fn read_directory_record(name: &[u8], dtype: libc::c_uchar) -> (DirectoryEntry, usize) {
4130 let name_offset = std::mem::offset_of!(libc::dirent, d_name);
4131 let words = (name_offset + name.len() + 1).div_ceil(std::mem::size_of::<u64>());
4132 let mut storage = vec![0_u64; words].into_boxed_slice();
4133 let allocation_len = std::mem::size_of_val(storage.as_ref());
4134 const { assert!(std::mem::align_of::<u64>() >= std::mem::align_of::<libc::dirent>()) };
4135 let raw = storage.as_mut_ptr().cast::<libc::dirent>();
4136 let entry = unsafe {
4139 (*raw).d_type = dtype;
4140 std::ptr::copy_nonoverlapping(
4141 name.as_ptr(),
4142 (&raw mut (*raw).d_name).cast::<u8>(),
4143 name.len(),
4144 );
4145 directory_entry_from_raw(raw)
4146 };
4147 (entry, allocation_len)
4149 }
4150
4151 #[test]
4152 fn raw_directory_entry_accepts_short_records() {
4153 let (entry, allocation_len) = read_directory_record(b"f\xff", libc::DT_REG);
4154 assert!(allocation_len < std::mem::size_of::<libc::dirent>());
4155 assert_eq!(entry.name.as_bytes(), b"f\xff");
4156 assert_eq!(entry.kind_hint, Some(EntryKind::File));
4157 }
4158
4159 #[test]
4160 fn raw_directory_entry_accepts_names_beyond_declared_array() {
4161 let mut name = vec![b'x'; 300];
4162 name[7] = 0xff;
4163 let (entry, allocation_len) = read_directory_record(&name, libc::DT_DIR);
4164 assert!(allocation_len > std::mem::size_of::<libc::dirent>());
4165 assert_eq!(entry.name.as_bytes(), name);
4166 assert_eq!(entry.kind_hint, Some(EntryKind::Dir));
4167 }
4168
4169 #[test]
4170 fn failed_stream_construction_closes_the_owned_fd() -> anyhow::Result<()> {
4171 let root_path = tempfile::tempdir()?;
4172 let file_path = root_path.path().join("regular-file");
4173 std::fs::write(&file_path, b"x")?;
4174 let fd: OwnedFd = std::fs::File::open(file_path)?.into();
4175 let raw_fd = fd.as_raw_fd();
4176 let error = OwnedDirectoryStream::from_fd(fd, None).unwrap_err();
4177 assert_eq!(error.raw_os_error(), Some(libc::ENOTDIR));
4178 assert_eq!(unsafe { libc::fcntl(raw_fd, libc::F_GETFD) }, -1);
4179 assert_eq!(
4180 std::io::Error::last_os_error().raw_os_error(),
4181 Some(libc::EBADF)
4182 );
4183 Ok(())
4184 }
4185
4186 #[test]
4187 fn cursor_refreshes_after_waiting_for_the_blocking_pool() -> anyhow::Result<()> {
4188 static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4189 std::sync::LazyLock::new(crate::progress::Progress::new);
4190 tokio::runtime::Builder::new_current_thread()
4191 .enable_all()
4192 .max_blocking_threads(1)
4193 .build()?
4194 .block_on(async {
4195 let tmp = tempfile::tempdir()?;
4196 crate::filegen::write_file(&PROGRESS, tmp.path().join("entry"), 1, 1, 0)
4197 .await
4198 .map_err(|error| error.source)?;
4199 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4200 for dereference in [false, true] {
4201 let mut cursor = if dereference {
4202 DirectoryCursor::open_following_symlinks(
4203 tmp.path(),
4204 congestion::Side::Source,
4205 Arc::new(()),
4206 )
4207 .await?
4208 } else {
4209 root.entries().await?
4210 };
4211 let stream = cursor.iterator.as_ref().unwrap();
4212 let fd = stream.as_fd().try_clone_to_owned()?;
4213 match nix::unistd::lseek(&fd, 0, nix::unistd::Whence::SeekCur) {
4215 Err(nix::errno::Errno::ESPIPE) => continue,
4216 result => {
4217 result?;
4218 }
4219 }
4220 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4221 let (release_tx, release_rx) = std::sync::mpsc::channel();
4222 let blocker = tokio::task::spawn_blocking(move || {
4223 let _ = started_tx.send(());
4224 let _ = release_rx.recv();
4225 });
4226 started_rx.await?;
4227 let limit = NonZeroUsize::new(1).unwrap();
4228 let mut read = Box::pin(cursor.next_batch(limit));
4229 assert!(futures::poll!(read.as_mut()).is_pending());
4230 assert_eq!(stream_names(fd.try_clone()?)?, ["entry"]);
4233 assert_ne!(nix::unistd::lseek(&fd, 0, nix::unistd::Whence::SeekCur)?, 0);
4234 release_tx.send(())?;
4235 let batch = read.await?;
4236 blocker.await?;
4237 assert_eq!(batch.len(), 1, "dereference={dereference}");
4238 assert_eq!(batch[0].name, "entry");
4239 assert!(cursor.next_batch(limit).await?.is_empty());
4240 }
4241 anyhow::Ok(())
4242 })
4243 }
4244
4245 #[tokio::test]
4246 async fn cursor_sees_replacement_before_first_batch() -> anyhow::Result<()> {
4247 static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4248 std::sync::LazyLock::new(crate::progress::Progress::new);
4249 let tmp = tempfile::tempdir()?;
4250 let source = tmp.path().join("source");
4251 std::fs::create_dir(&source)?;
4252 let entry = source.join("entry");
4253 crate::filegen::write_file(&PROGRESS, entry.clone(), 1, 1, 0)
4254 .await
4255 .map_err(|error| error.source)?;
4256 let root = Dir::open_root_dir(&source, false, congestion::Side::Source).await?;
4257 for dereference in [false, true] {
4258 let mut cursor = if dereference {
4259 DirectoryCursor::open_following_symlinks(
4260 &source,
4261 congestion::Side::Source,
4262 Arc::new(()),
4263 )
4264 .await?
4265 } else {
4266 root.entries().await?
4267 };
4268 cursor.read_acls(congestion::Side::Source).await?;
4269 let replacement = tmp.path().join("replacement");
4270 crate::filegen::write_file(&PROGRESS, replacement.clone(), 2, 2, 0)
4271 .await
4272 .map_err(|error| error.source)?;
4273 std::fs::rename(replacement, &entry)?;
4274 let batch = cursor.next_batch(NonZeroUsize::new(64).unwrap()).await?;
4275 assert_eq!(batch.len(), 1, "dereference={dereference}");
4276 assert_eq!(batch[0].name, "entry");
4277 }
4278 Ok(())
4279 }
4280
4281 #[tokio::test]
4282 async fn cursor_reads_nonseekable_stream_without_reopening_or_restarting() -> anyhow::Result<()>
4283 {
4284 static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4285 std::sync::LazyLock::new(crate::progress::Progress::new);
4286 let tmp = tempfile::tempdir()?;
4287 for name in ["first", "second"] {
4288 crate::filegen::write_file(&PROGRESS, tmp.path().join(name), 1, 1, 0)
4289 .await
4290 .map_err(|error| error.source)?;
4291 }
4292 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4293 let mut cursor = root.entries().await?;
4294 let held_fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4295 let limit = NonZeroUsize::new(1).unwrap();
4296 let first = cursor
4297 .next_batch_with_seek(limit, move |fd| {
4298 assert_eq!(fd.as_raw_fd(), held_fd);
4299 Err(nix::errno::Errno::ESPIPE)
4300 })
4301 .await?;
4302 assert_eq!(cursor.iterator.as_ref().unwrap().as_raw_fd(), held_fd);
4303 let second = cursor
4304 .next_batch_with_seek(limit, |_| panic!("continuing a cursor must not seek again"))
4305 .await?;
4306 let mut names: Vec<_> = first
4307 .into_iter()
4308 .chain(second)
4309 .map(|entry| entry.name)
4310 .collect();
4311 names.sort();
4312 assert_eq!(names, ["first", "second"]);
4313 assert!(
4314 cursor
4315 .next_batch_with_seek(limit, |_| {
4316 panic!("reaching EOF must not restart the cursor")
4317 })
4318 .await?
4319 .is_empty()
4320 );
4321 Ok(())
4322 }
4323
4324 #[tokio::test]
4325 async fn cursor_seek_failure_releases_credit_and_prevents_restart() -> anyhow::Result<()> {
4326 let tmp = tempfile::tempdir()?;
4327 let credit = Arc::new(());
4328 let remaining = Arc::downgrade(&credit);
4329 let mut cursor =
4330 DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4331 .await?;
4332 let limit = NonZeroUsize::new(1).unwrap();
4333 assert_eq!(
4334 cursor
4335 .next_batch_with_seek(limit, |_| Err(nix::errno::Errno::EIO))
4336 .await
4337 .unwrap_err()
4338 .raw_os_error(),
4339 Some(libc::EIO)
4340 );
4341 assert!(
4342 remaining.upgrade().is_none(),
4343 "failed seek retained descriptor credit"
4344 );
4345 assert!(
4346 cursor.next_batch(limit).await.is_err(),
4347 "failed cursor restarted"
4348 );
4349 Ok(())
4350 }
4351
4352 #[tokio::test]
4353 async fn cursor_eof_never_reads_again_after_empty_short_or_full_batches() -> anyhow::Result<()>
4354 {
4355 for (count, limit, sizes) in [
4356 (0, 3, vec![0]),
4357 (1, 3, vec![1]),
4358 (3, 3, vec![3, 0]),
4359 (4, 3, vec![3, 1]),
4360 (6, 3, vec![3, 3, 0]),
4361 (7, 3, vec![3, 3, 1]),
4362 (150, 64, vec![64, 64, 22]),
4363 ] {
4364 let tmp = tempfile::tempdir()?;
4365 let expected: Vec<_> = (0..count)
4366 .map(|index| std::ffi::OsString::from(format!("file-{index:03}")))
4367 .collect();
4368 for name in &expected {
4369 crate::filegen::write_file(crate::get_progress(), tmp.path().join(name), 1, 1, 0)
4370 .await
4371 .map_err(|error| error.source)?;
4372 }
4373 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4374 let mut cursor = root.entries().await?;
4375 let limit = NonZeroUsize::new(limit).unwrap();
4376 let mut names = Vec::new();
4377 for size in sizes {
4378 let batch = cursor.next_batch(limit).await?;
4379 assert_eq!(batch.len(), size, "entry count={count}");
4380 names.extend(batch.into_iter().map(|entry| entry.name));
4381 }
4382 names.sort();
4383 assert_eq!(names, expected);
4384 cursor.read_hook = Some(Box::new(|_, _| {
4385 Err(std::io::Error::other(
4386 "an EOF cursor issued another directory read",
4387 ))
4388 }));
4389 let submissions = testutils::BlockingSubmissions::start();
4390 for _ in 0..3 {
4391 assert!(cursor.next_batch(limit).await?.is_empty());
4392 }
4393 assert_eq!(submissions.count(), 0, "entry count={count}, limit={limit}");
4394 }
4395 Ok(())
4396 }
4397
4398 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
4399 #[tokio::test]
4400 async fn cursor_eof_retains_its_descriptor_and_credit_for_acl_reads() -> anyhow::Result<()> {
4401 let tmp = tempfile::tempdir()?;
4402 let access = restrictive_access_acl();
4403 let default = permissive_acl();
4404 set_xattr_at(tmp.path(), ACL_ACCESS_XATTR, &access);
4405 set_xattr_at(tmp.path(), ACL_DEFAULT_XATTR, &default);
4406 let credit = Arc::new(());
4407 let remaining = Arc::downgrade(&credit);
4408 let mut cursor =
4409 DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4410 .await?;
4411 let fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4412 let identity = testutils::FdIdentityProbe::capture(fd)?;
4413 let limit = NonZeroUsize::new(64).unwrap();
4414 assert!(cursor.next_batch(limit).await?.is_empty());
4415 assert!(!identity.original_is_closed()?);
4416 assert!(remaining.upgrade().is_some());
4417 let acls = cursor.read_acls(congestion::Side::Source).await?;
4418 assert_eq!(acls.access, Some(access));
4419 assert_eq!(acls.default, Some(default));
4420 assert_eq!(cursor.iterator.as_ref().unwrap().as_raw_fd(), fd);
4421 cursor.read_hook = Some(Box::new(|_, _| {
4422 Err(std::io::Error::other(
4423 "an ACL read cleared the cursor's EOF",
4424 ))
4425 }));
4426 assert!(cursor.next_batch(limit).await?.is_empty());
4427 drop(cursor);
4428 assert!(identity.original_is_closed()?);
4429 assert!(remaining.upgrade().is_none());
4430 Ok(())
4431 }
4432
4433 #[tokio::test]
4434 async fn cursor_eof_does_not_hide_a_later_acl_failure() -> anyhow::Result<()> {
4435 let tmp = tempfile::tempdir()?;
4436 let credit = Arc::new(());
4437 let remaining = Arc::downgrade(&credit);
4438 let mut cursor =
4439 DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4440 .await?;
4441 let identity =
4442 testutils::FdIdentityProbe::capture(cursor.iterator.as_ref().unwrap().as_raw_fd())?;
4443 let limit = NonZeroUsize::new(64).unwrap();
4444 assert!(cursor.next_batch(limit).await?.is_empty());
4445 let _failure = testutils::BlockingPathGate::fail_once(tmp.path(), libc::EIO);
4446 assert_eq!(
4447 cursor
4448 .read_acls(congestion::Side::Source)
4449 .await
4450 .unwrap_err()
4451 .raw_os_error(),
4452 Some(libc::EIO)
4453 );
4454 assert!(identity.original_is_closed()?);
4455 assert!(remaining.upgrade().is_none());
4456 assert!(
4457 cursor.next_batch(limit).await.is_err(),
4458 "failed cursor became successful EOF"
4459 );
4460 Ok(())
4461 }
4462
4463 #[tokio::test]
4464 async fn cursor_eof_does_not_hide_a_cancelled_acl_read() -> anyhow::Result<()> {
4465 let tmp = tempfile::tempdir()?;
4466 let credits = Arc::new(tokio::sync::Semaphore::new(1));
4467 let credit = Arc::new(credits.clone().acquire_owned().await?);
4468 let mut cursor =
4469 DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4470 .await?;
4471 let identity =
4472 testutils::FdIdentityProbe::capture(cursor.iterator.as_ref().unwrap().as_raw_fd())?;
4473 let limit = NonZeroUsize::new(64).unwrap();
4474 assert!(cursor.next_batch(limit).await?.is_empty());
4475 let mut gate = testutils::BlockingPathGate::install(tmp.path());
4476 let mut read = Box::pin(cursor.read_acls(congestion::Side::Source));
4477 assert!(futures::poll!(read.as_mut()).is_pending());
4478 tokio::time::timeout(std::time::Duration::from_secs(20), gate.wait_started()).await??;
4479 drop(read);
4480 let descriptor_retained = !identity.original_is_closed()?;
4481 let credit_retained = credits.available_permits() == 0;
4482 let result = cursor.next_batch(limit).await;
4483 gate.release_all();
4484 let returned =
4485 tokio::time::timeout(std::time::Duration::from_secs(20), credits.acquire()).await??;
4486 assert!(descriptor_retained, "started ACL read lost its descriptor");
4487 assert!(credit_retained, "started ACL read lost its credit");
4488 assert!(result.is_err(), "cancelled cursor became successful EOF");
4489 assert!(identity.original_is_closed()?);
4490 drop(returned);
4491 Ok(())
4492 }
4493
4494 #[tokio::test]
4495 async fn cursor_handles_empty_and_non_utf8_names() -> anyhow::Result<()> {
4496 use std::os::unix::ffi::OsStringExt;
4497
4498 let root_path = testutils::create_temp_dir().await?;
4499 let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4500 let mut empty = root.entries().await?;
4501 assert!(
4502 empty
4503 .next_batch(NonZeroUsize::new(1).unwrap())
4504 .await?
4505 .is_empty()
4506 );
4507
4508 let name = std::ffi::OsString::from_vec(vec![b'n', 0xff]);
4509 tokio::fs::write(root_path.join(&name), b"x").await?;
4510 let mut cursor = root.entries().await?;
4511 let batch = cursor.next_batch(NonZeroUsize::new(1).unwrap()).await?;
4512 assert_eq!(batch.len(), 1);
4513 assert_eq!(batch[0].name, name);
4514 assert_eq!(batch[0].kind_hint, Some(EntryKind::File));
4515 assert!(
4516 cursor
4517 .next_batch(NonZeroUsize::new(1).unwrap())
4518 .await?
4519 .is_empty()
4520 );
4521 Ok(())
4522 }
4523
4524 struct RestoreDirectoryAccess<'a>(&'a Dir);
4525
4526 impl Drop for RestoreDirectoryAccess<'_> {
4527 fn drop(&mut self) {
4528 let _ = fchmod(self.0.fd.as_fd(), Mode::from_bits_truncate(0o700));
4530 }
4531 }
4532
4533 fn directory_search_permission_is_enforced(dir: &Dir) -> anyhow::Result<bool> {
4534 match openat(
4535 dir.fd.as_fd(),
4536 c".",
4537 OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
4538 Mode::empty(),
4539 ) {
4540 Err(nix::errno::Errno::EACCES) => Ok(true),
4541 Err(error) => Err(error.into()),
4542 Ok(_) => {
4543 eprintln!("skipping: capability overrides bypass directory search permission");
4544 Ok(false)
4545 }
4546 }
4547 }
4548
4549 #[tokio::test]
4550 async fn reopen_fails_when_read_permission_is_revoked() -> anyhow::Result<()> {
4551 let tmp = tempfile::tempdir()?;
4552 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4553 let _restore = RestoreDirectoryAccess(&root);
4554 fchmod(root.fd.as_fd(), Mode::empty())?;
4555 if !directory_search_permission_is_enforced(&root)? {
4556 return Ok(());
4557 }
4558 let error = root
4559 .entries()
4560 .await
4561 .err()
4562 .expect("unreadable directory reopened");
4563 assert_eq!(error.raw_os_error(), Some(libc::EACCES));
4564 let error = root
4565 .fd
4566 .listing_fd_with_seek(|_| Err(nix::errno::Errno::ESPIPE))
4567 .unwrap_err();
4568 assert_eq!(error.raw_os_error(), Some(libc::EACCES));
4569 Ok(())
4570 }
4571
4572 #[tokio::test]
4573 async fn reopen_distinguishes_unusable_proc_from_operational_failures() -> anyhow::Result<()> {
4574 use nix::errno::Errno;
4575
4576 let tmp = tempfile::tempdir()?;
4577 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4578 let _restore = RestoreDirectoryAccess(&root);
4579 fchmod(root.fd.as_fd(), Mode::from_bits_truncate(0o444))?;
4580 if !directory_search_permission_is_enforced(&root)? {
4581 return Ok(());
4582 }
4583 for (proc_error, expected) in [
4586 (Errno::ENOENT, Errno::EACCES),
4587 (Errno::ENOTDIR, Errno::EACCES),
4588 (Errno::ELOOP, Errno::EACCES),
4589 (Errno::EACCES, Errno::EACCES),
4590 (Errno::EMFILE, Errno::EMFILE),
4591 (Errno::ENFILE, Errno::ENFILE),
4592 (Errno::ENOMEM, Errno::ENOMEM),
4593 (Errno::EIO, Errno::EIO),
4594 ] {
4595 let error = root
4596 .fd
4597 .reopen_with_proc_open(|_, _| Err(proc_error))
4598 .unwrap_err();
4599 assert_eq!(error.raw_os_error(), Some(expected as i32), "{proc_error}");
4600 }
4601 Ok(())
4602 }
4603
4604 #[tokio::test]
4605 async fn independent_cursors_do_not_share_directory_offsets() -> anyhow::Result<()> {
4606 let expected: Vec<_> = (0..80)
4607 .map(|index| std::ffi::OsString::from(format!("file-{index:02}")))
4608 .collect();
4609 for mode in [None, Some(0o444)] {
4610 let tmp = tempfile::tempdir()?;
4611 for name in &expected {
4612 std::fs::write(tmp.path().join(name), b"content")?;
4613 }
4614 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4615 let _restore = RestoreDirectoryAccess(&root);
4616 exhaust_shared_directory_offset(&root)?;
4617 let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
4618 if let Some(mode) = mode {
4619 fchmod(root.fd.as_fd(), Mode::from_bits_truncate(mode))?;
4620 if !directory_search_permission_is_enforced(&root)? {
4621 continue;
4622 }
4623 }
4624 let mut first = root.entries().await?;
4625 let mut second = root.entries().await?;
4626 let position = |cursor: &DirectoryCursor| {
4628 nix::unistd::lseek(
4629 cursor.iterator.as_ref().unwrap().as_fd(),
4630 0,
4631 nix::unistd::Whence::SeekCur,
4632 )
4633 };
4634 let first_start = position(&first);
4635 let second_start = position(&second);
4636 for (name, start) in [("first", first_start), ("second", second_start)] {
4637 if start != Err(nix::errno::Errno::ESPIPE) {
4638 assert_eq!(
4639 start,
4640 Ok(0),
4641 "{name} cursor inherited an offset, mode={mode:?}"
4642 );
4643 }
4644 }
4645 let limit = NonZeroUsize::new(64).unwrap();
4646 let first_batch = first.next_batch(limit).await?;
4647 assert_eq!(
4648 position(&second),
4649 second_start,
4650 "reading the first cursor moved the second, mode={mode:?}"
4651 );
4652 let second_batch = second.next_batch(limit).await?;
4653 for (mut cursor, batch) in [(first, first_batch), (second, second_batch)] {
4654 let rest = cursor.next_batch(limit).await?;
4655 let mut names: Vec<_> = batch
4656 .into_iter()
4657 .chain(rest)
4658 .map(|entry| entry.name)
4659 .collect();
4660 names.sort();
4661 assert_eq!(names, expected, "mode={mode:?}");
4662 assert!(cursor.next_batch(limit).await?.is_empty());
4663 }
4664 assert_eq!(
4665 nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
4666 end
4667 );
4668 }
4669 Ok(())
4670 }
4671
4672 #[tokio::test]
4673 async fn cursor_failure_after_a_partial_read_does_not_restart() -> anyhow::Result<()> {
4674 let root_path = testutils::create_temp_dir().await?;
4675 for index in 0..3 {
4676 tokio::fs::write(root_path.join(format!("file-{index}")), b"x").await?;
4677 }
4678 let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4679 let mut cursor = root.entries().await?;
4680 let fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4681 cursor.read_hook = Some(Box::new(|accepted, _| {
4682 if accepted == 1 {
4683 Err(std::io::Error::from_raw_os_error(libc::EIO))
4684 } else {
4685 Ok(())
4686 }
4687 }));
4688 let limit = NonZeroUsize::new(64).unwrap();
4689 assert_eq!(
4690 cursor.next_batch(limit).await.unwrap_err().raw_os_error(),
4691 Some(libc::EIO)
4692 );
4693 assert!(
4694 cursor.next_batch(limit).await.is_err(),
4695 "a failed cursor restarted"
4696 );
4697 assert_eq!(
4698 unsafe { libc::fcntl(fd, libc::F_GETFD) },
4699 -1,
4700 "failed cursor leaked its fd"
4701 );
4702
4703 let mut independent = root.entries().await?;
4704 assert_eq!(independent.next_batch(limit).await?.len(), 3);
4705 Ok(())
4706 }
4707
4708 #[tokio::test]
4709 async fn cancelled_admitted_batch_retains_its_fd_and_admission_until_exit() -> anyhow::Result<()>
4710 {
4711 use anyhow::Context;
4712 use std::time::Duration;
4713
4714 let root_path = testutils::create_temp_dir().await?;
4715 let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4716 let mut inspect = root.entries().await?;
4717 let mut raw_names = [
4718 inspect
4719 .iterator
4720 .as_mut()
4721 .unwrap()
4722 .next_raw_entry()?
4723 .unwrap()
4724 .name,
4725 inspect
4726 .iterator
4727 .as_mut()
4728 .unwrap()
4729 .next_raw_entry()?
4730 .unwrap()
4731 .name,
4732 ];
4733 raw_names.sort();
4734 assert_eq!(
4735 raw_names,
4736 [
4737 std::ffi::OsString::from("."),
4738 std::ffi::OsString::from("..")
4739 ]
4740 );
4741 assert!(
4742 inspect
4743 .iterator
4744 .as_mut()
4745 .unwrap()
4746 .next_raw_entry()?
4747 .is_none()
4748 );
4749 let mut cursor = root.entries().await?;
4750 let admission = testutils::AdmissionLimit::new().await;
4751 admission.set_files_in_flight(1);
4752 let guard = throttle::open_file_permit().await;
4753 let fd_admission = guard.admission();
4754 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4755 let (release_tx, release_rx) = std::sync::mpsc::channel();
4756 let mut started_tx = Some(started_tx);
4757 let raw_reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
4758 let observed_raw_reads = Arc::clone(&raw_reads);
4759 cursor.read_hook = Some(Box::new(move |_, fd| {
4760 observed_raw_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4761 if let Some(started_tx) = started_tx.take() {
4762 let _ = started_tx.send(fd);
4763 release_rx.recv().map_err(std::io::Error::other)?;
4764 }
4765 Ok(())
4766 }));
4767 let task = tokio::spawn(async move {
4768 with_fd_admission(fd_admission, async move {
4769 let _guard = guard;
4770 cursor.next_batch(NonZeroUsize::new(1).unwrap()).await
4771 })
4772 .await
4773 });
4774 let fd = started_rx.await.context("blocking batch did not start")?;
4775 task.abort();
4776 assert!(task.await.unwrap_err().is_cancelled());
4777 assert_ne!(
4778 unsafe { libc::fcntl(fd, libc::F_GETFD) },
4779 -1,
4780 "cancelled batch lost its owned fd"
4781 );
4782 let mut second = Box::pin(throttle::open_file_permit());
4783 assert!(
4784 futures::poll!(second.as_mut()).is_pending(),
4785 "admission released before read exited"
4786 );
4787 release_tx
4788 .send(())
4789 .context("blocking batch ended before release")?;
4790 let permit = admission
4791 .run_with_timeout(Duration::from_secs(20), second)
4792 .await
4793 .context("admission was not released after blocking batch exited")?;
4794 drop(permit);
4795 assert_eq!(
4796 unsafe { libc::fcntl(fd, libc::F_GETFD) },
4797 -1,
4798 "cancelled batch leaked its fd"
4799 );
4800 assert!(
4801 raw_reads.load(std::sync::atomic::Ordering::SeqCst) >= 3,
4802 "the blocking job stopped before reading past dot entries; raw reads: {}",
4803 raw_reads.load(std::sync::atomic::Ordering::SeqCst)
4804 );
4805 Ok(())
4806 }
4807
4808 const EVERY_KIND: [EntryKind; 4] = [
4809 EntryKind::File,
4810 EntryKind::Dir,
4811 EntryKind::Symlink,
4812 EntryKind::Special,
4813 ];
4814
4815 pub(super) fn gate_file_create_stage(
4816 fd: RawFd,
4817 stage: &str,
4818 ) -> Option<testutils::BlockingPathGateVisit> {
4819 let path = std::fs::read_link(format!("/proc/self/fd/{fd}")).ok()?;
4820 testutils::wait_on_blocking_path_gate(&path.join(stage), fd)
4821 }
4822
4823 pub(super) fn gate_unlink(
4824 fd: RawFd,
4825 name: &OsStr,
4826 ) -> std::io::Result<Option<testutils::BlockingPathGateVisit>> {
4827 let path = std::fs::read_link(format!("/proc/self/fd/{fd}"))?;
4828 testutils::wait_on_blocking_path_gate(&path.join(name).join(".rcp-unlink"), fd)
4829 .map(testutils::BlockingPathGateVisit::into_result)
4830 .transpose()
4831 }
4832
4833 mod max_files_in_flight_tests {
4834 use super::*;
4835 use anyhow::Context as _;
4836 use futures::FutureExt as _;
4837
4838 struct BlockingDropFd {
4839 _file: std::fs::File,
4840 drop_started: Option<tokio::sync::oneshot::Sender<()>>,
4841 release_drop: std::sync::mpsc::Receiver<()>,
4842 _completion: crate::testutils::CompletionSignal,
4843 }
4844
4845 impl AsRawFd for BlockingDropFd {
4846 fn as_raw_fd(&self) -> RawFd {
4847 self._file.as_raw_fd()
4848 }
4849 }
4850
4851 impl Drop for BlockingDropFd {
4852 fn drop(&mut self) {
4853 if let Some(drop_started) = self.drop_started.take() {
4854 let _ = drop_started.send(());
4855 }
4856 self.release_drop
4857 .recv()
4858 .expect("drop release sender must stay alive");
4859 }
4860 }
4861
4862 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4863 struct QueuedFdDropObservation {
4864 fd_was_closed: bool,
4865 admission_was_retained: bool,
4866 }
4867
4868 struct QueuedFdCapture {
4869 file: Option<std::fs::File>,
4870 probe: crate::testutils::FdIdentityProbe,
4871 observation: Arc<std::sync::Mutex<Option<std::io::Result<QueuedFdDropObservation>>>>,
4872 }
4873
4874 impl AsRawFd for QueuedFdCapture {
4875 fn as_raw_fd(&self) -> RawFd {
4876 self.file
4877 .as_ref()
4878 .expect("captured file must be present")
4879 .as_raw_fd()
4880 }
4881 }
4882
4883 impl Drop for QueuedFdCapture {
4884 fn drop(&mut self) {
4885 drop(self.file.take());
4886 let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
4887 *self
4888 .observation
4889 .lock()
4890 .expect("queued fd drop observation lock poisoned") =
4891 Some(self.probe.original_is_closed().map(|fd_was_closed| {
4892 QueuedFdDropObservation {
4893 fd_was_closed,
4894 admission_was_retained,
4895 }
4896 }));
4897 }
4898 }
4899
4900 async fn assert_queued_owner_closes_before_admission<Fut>(
4901 operation: impl FnOnce(QueuedFdCapture) -> Fut,
4902 ) -> anyhow::Result<()>
4903 where
4904 Fut: std::future::Future,
4905 {
4906 let source = tempfile::tempfile()?;
4907 let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4908 let observation = Arc::new(std::sync::Mutex::new(None));
4909 let capture = QueuedFdCapture {
4910 file: Some(source),
4911 probe,
4912 observation: Arc::clone(&observation),
4913 };
4914 let limits = testutils::AdmissionLimit::new().await;
4915 limits.set_files_in_flight(1);
4916 let guard = throttle::open_file_permit().await;
4917 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4918 let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4919 let blocker = tokio::task::spawn_blocking(move || {
4920 let _ = started_tx.send(());
4921 let _ = release_rx.recv();
4922 });
4923 started_rx.await?;
4924 let mut work = Box::pin(with_fd_admission(guard.admission(), operation(capture)));
4925 let queued = futures::poll!(work.as_mut()).is_pending();
4926 drop(guard);
4928 drop(work);
4929 let closed_before_release = probe.original_is_closed();
4930 let drop_observation = observation.lock().unwrap().take().transpose();
4931 let mut next_file = Box::pin(throttle::open_file_permit());
4932 let returned = next_file.as_mut().now_or_never();
4933 let capacity_returned_before_release = returned.is_some();
4934 drop(release_tx);
4936 blocker.await?;
4937 tokio::task::spawn_blocking(|| ()).await?;
4938 let permit = match returned {
4939 Some(permit) => permit,
4940 None => tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?,
4941 };
4942 drop(permit);
4943 assert!(
4944 queued,
4945 "the operation must queue behind the occupied worker"
4946 );
4947 assert!(
4948 closed_before_release?,
4949 "queued cancellation retained its fd"
4950 );
4951 assert!(capacity_returned_before_release);
4952 assert_eq!(
4953 drop_observation?,
4954 Some(QueuedFdDropObservation {
4955 fd_was_closed: true,
4956 admission_was_retained: true,
4957 }),
4958 "queued cancellation must close its fd before returning admission"
4959 );
4960 Ok(())
4961 }
4962
4963 #[test]
4964 fn cancelled_queued_owned_acl_read_closes_source_before_returning_admission()
4965 -> anyhow::Result<()> {
4966 tokio::runtime::Builder::new_current_thread()
4967 .max_blocking_threads(1)
4968 .enable_all()
4969 .build()?
4970 .block_on(assert_queued_owner_closes_before_admission(|owner| {
4971 read_acls_owned(owner, congestion::Side::Source, false)
4972 }))
4973 }
4974
4975 async fn assert_abandoned_output_closes_before_admission<Fut, T>(
4976 operation: impl FnOnce(BlockingDropFd) -> Fut + Send + 'static,
4977 ) -> anyhow::Result<()>
4978 where
4979 Fut: std::future::Future<Output = T> + Send + 'static,
4980 T: Send + 'static,
4981 {
4982 let tmp = tempfile::tempdir()?;
4983 let path = tmp.path().join("returned-owner");
4984 std::fs::write(&path, b"payload")?;
4985 let file = std::fs::File::open(&path)?;
4986 let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
4987 let mut gate = testutils::BlockingPathGate::install(&path);
4988 let limits = testutils::AdmissionLimit::new().await;
4989 limits.set_files_in_flight(1);
4990 let guard = throttle::open_file_permit().await;
4991 let (drop_started_tx, drop_started_rx) = tokio::sync::oneshot::channel();
4992 let (release_drop_tx, release_drop_rx) = std::sync::mpsc::channel();
4993 let (completion, completion_rx) = testutils::CompletionSignal::new();
4994 let owner = BlockingDropFd {
4995 _file: file,
4996 drop_started: Some(drop_started_tx),
4997 release_drop: release_drop_rx,
4998 _completion: completion,
4999 };
5000 let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
5001 let _guard = guard;
5002 operation(owner).await
5003 }));
5004 let started = gate.wait_started().await;
5005 task.abort();
5006 let cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5007 gate.release_all();
5008 let dropping = drop_started_rx.await;
5009 let admission_retained = throttle::open_file_permit().now_or_never().is_none();
5010 let fd_retained = probe.original_is_closed().map(|closed| !closed);
5011 let released = release_drop_tx.send(());
5012 let (completed, permit) = testutils::await_completion_and_capacity(
5013 completion_rx,
5014 throttle::open_file_permit(),
5015 )
5016 .await;
5017 drop(permit);
5018 started?;
5019 dropping?;
5020 released?;
5021 completed?;
5022 assert!(cancelled, "the async waiter must observe cancellation");
5023 assert!(
5024 admission_retained,
5025 "admission was released before the abandoned returned fd was dropped"
5026 );
5027 assert!(fd_retained?);
5028 assert!(probe.original_is_closed()?);
5029 Ok(())
5030 }
5031
5032 #[tokio::test]
5033 async fn abandoned_owned_acl_output_closes_source_before_returning_admission()
5034 -> anyhow::Result<()> {
5035 assert_abandoned_output_closes_before_admission(|owner| {
5036 read_acls_owned(owner, congestion::Side::Source, false)
5037 })
5038 .await
5039 }
5040
5041 #[test]
5042 fn cancelled_queued_file_creation_drops_payload_before_admission_without_creating()
5043 -> anyhow::Result<()> {
5044 let runtime = tokio::runtime::Builder::new_current_thread()
5045 .max_blocking_threads(1)
5046 .enable_all()
5047 .build()?;
5048 runtime.block_on(async {
5049 let tmp = tempfile::tempdir()?;
5050 let root =
5051 Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5052 let destination = tmp.path().join("destination");
5053 let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5054 let continuation_called = Arc::clone(&called);
5055 assert_queued_owner_closes_before_admission(|owner| async move {
5056 root.create_file_and_then(OsStr::new("destination"), move |created| {
5057 let _owner = owner;
5058 continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5059 created
5060 })
5061 .await
5062 })
5063 .await?;
5064 assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5065 assert!(
5066 !destination.exists(),
5067 "cancelled queued work created a destination"
5068 );
5069 Ok(())
5070 })
5071 }
5072
5073 async fn cancelled_unclaimed_file_continuation_case(
5074 stage: &str,
5075 strict: bool,
5076 ) -> anyhow::Result<()> {
5077 use std::os::unix::fs::PermissionsExt as _;
5078 let tmp = tempfile::tempdir()?;
5079 if strict {
5080 set_xattr_at(tmp.path(), ACL_DEFAULT_XATTR, &permissive_acl());
5081 }
5082 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5083 let destination = tmp.path().join("destination");
5084 let source = tempfile::tempfile()?;
5085 let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5086 let observation = Arc::new(std::sync::Mutex::new(None));
5087 let capture = QueuedFdCapture {
5088 file: Some(source),
5089 probe: source_probe,
5090 observation: Arc::clone(&observation),
5091 };
5092 let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5093 let continuation_called = Arc::clone(&called);
5094 let gate = testutils::BlockingPathGate::install(destination.join(stage));
5095 let limits = testutils::AdmissionLimit::new().await;
5096 limits.set_files_in_flight(1);
5097 let resource = throttle::Resource::meta(
5098 throttle::Side::Destination,
5099 throttle::MetadataOp::OpenCreate,
5100 );
5101 limits.set_max_ops_in_flight(resource, 1);
5102 let samples = Arc::new(congestion::testing::CollectingSink::new());
5103 congestion::install_sample_sink(samples.clone());
5104 let guard = throttle::open_file_permit().await;
5105 let admission = guard.admission();
5106 let task = tokio::spawn(with_fd_admission(admission, async move {
5107 let _guard = guard;
5108 let continuation = move |created| {
5109 let _capture = capture;
5110 continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5111 created
5112 };
5113 if strict {
5114 let operation = root.file_create_operation(OsStr::new("destination"), true)?;
5115 run_file_create_and_then(congestion::Side::Destination, operation, continuation)
5116 .await
5117 } else {
5118 root.create_file_and_then(OsStr::new("destination"), continuation)
5119 .await
5120 }
5121 }));
5122 let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
5123 let (
5124 cancelled,
5125 (
5126 created_probe,
5127 source_closed,
5128 mode,
5129 acquired_operation,
5130 sample_count,
5131 inherited_acl,
5132 ),
5133 ) = testutils::cancel_at_blocking_path(
5134 limits,
5135 gate,
5136 task,
5137 std::time::Duration::from_secs(20),
5138 |fd| {
5139 (
5140 testutils::FdIdentityProbe::capture(fd),
5141 source_probe.original_is_closed(),
5142 std::fs::metadata(&destination)
5143 .map(|meta| meta.permissions().mode() & 0o7777),
5144 next_operation.as_mut().now_or_never(),
5145 samples.metadata_count(),
5146 strict.then(|| get_xattr_at(&destination, ACL_ACCESS_XATTR).is_some()),
5147 )
5148 },
5149 )
5150 .await?;
5151 let operation_was_finished = acquired_operation.is_some();
5152 let permit = match acquired_operation {
5153 Some(permit) => permit,
5154 None => {
5155 tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?
5156 }
5157 };
5158 drop(permit);
5159 assert!(cancelled.waiter_was_cancelled);
5160 assert!(cancelled.admission_was_retained_while_work_gated);
5161 assert!(cancelled.fd_was_open_while_work_gated);
5162 assert!(
5163 source_closed?,
5164 "unclaimed payload retained its captured source after cancellation"
5165 );
5166 assert_eq!(mode?, DST_FILE_CREATE_MODE);
5167 assert_eq!(operation_was_finished, stage == "before-continuation");
5168 assert_eq!(sample_count, usize::from(stage == "before-continuation"));
5169 assert_eq!(samples.metadata_count(), 1);
5170 assert!(created_probe?.original_is_closed()?);
5171 assert_eq!(
5172 observation.lock().unwrap().take().transpose()?,
5173 Some(QueuedFdDropObservation {
5174 fd_was_closed: true,
5175 admission_was_retained: true,
5176 })
5177 );
5178 assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5179 assert_eq!(cancelled.final_hit_count, 1);
5180 assert_eq!(
5181 std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
5182 DST_FILE_CREATE_MODE
5183 );
5184 assert_eq!(std::fs::metadata(&destination)?.len(), 0);
5185 if strict {
5186 assert_eq!(inherited_acl, Some(stage == "before-sanitation"));
5187 assert_eq!(get_xattr_at(&destination, ACL_ACCESS_XATTR), None);
5188 }
5189 Ok(())
5190 }
5191
5192 #[tokio::test]
5193 async fn cancelled_created_file_never_starts_an_unclaimed_payload() -> anyhow::Result<()> {
5194 for stage in ["before-sanitation", "before-continuation"] {
5195 cancelled_unclaimed_file_continuation_case(stage, false).await?;
5196 }
5197 Ok(())
5198 }
5199
5200 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
5201 #[tokio::test]
5202 async fn cancelled_file_creation_finishes_acl_sanitation_without_starting_payload()
5203 -> anyhow::Result<()> {
5204 for stage in ["before-sanitation", "before-continuation"] {
5205 cancelled_unclaimed_file_continuation_case(stage, true).await?;
5206 }
5207 Ok(())
5208 }
5209
5210 async fn cancelled_claimed_file_continuation_case(
5211 fail_payload: bool,
5212 ) -> anyhow::Result<()> {
5213 use std::io::{Seek as _, Write as _};
5214 use std::os::unix::fs::PermissionsExt as _;
5215 let tmp = tempfile::tempdir()?;
5216 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5217 let destination = tmp.path().join("destination");
5218 let mut source = tempfile::tempfile()?;
5219 source.write_all(b"complete payload")?;
5220 source.rewind()?;
5221 let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5222 let gate = testutils::BlockingPathGate::install(&destination);
5223 let limits = testutils::AdmissionLimit::new().await;
5224 limits.set_files_in_flight(1);
5225 let resource = throttle::Resource::meta(
5226 throttle::Side::Destination,
5227 throttle::MetadataOp::OpenCreate,
5228 );
5229 limits.set_max_ops_in_flight(resource, 1);
5230 let samples = Arc::new(congestion::testing::CollectingSink::new());
5231 congestion::install_sample_sink(samples.clone());
5232 let guard = throttle::open_file_permit().await;
5233 let admission = guard.admission();
5234 let data_path = destination.clone();
5235 let task = tokio::spawn(with_fd_admission(admission, async move {
5236 let _guard = guard;
5237 root.create_file_and_then(OsStr::new("destination"), move |created| {
5238 let mut file = created?;
5239 let visit = testutils::wait_on_blocking_path_gate(&data_path, file.as_raw_fd());
5240 let copied = if fail_payload {
5241 file.write_all(b"partial")
5242 .and_then(|()| Err(std::io::Error::from_raw_os_error(libc::EIO)))
5243 } else {
5244 std::io::copy(&mut source, &mut file).map(|_| ())
5245 };
5246 std::io::Result::Ok((copied, source, file, visit))
5247 })
5248 .await
5249 }));
5250 let (cancelled, (source_open, mode, operation_available, sample_count)) =
5251 testutils::cancel_at_blocking_path(
5252 limits,
5253 gate,
5254 task,
5255 std::time::Duration::from_secs(20),
5256 |_| {
5257 (
5258 source_probe.original_is_closed().map(|closed| !closed),
5259 std::fs::metadata(&destination)
5260 .map(|meta| meta.permissions().mode() & 0o7777),
5261 throttle::ops_in_flight_permit(resource)
5262 .now_or_never()
5263 .is_some(),
5264 samples.metadata_count(),
5265 )
5266 },
5267 )
5268 .await?;
5269 assert!(cancelled.waiter_was_cancelled);
5270 assert!(cancelled.admission_was_retained_while_work_gated);
5271 assert!(cancelled.fd_was_open_while_work_gated && source_open?);
5272 assert!(cancelled.fd_was_closed_at_output_drop_start);
5273 assert!(cancelled.admission_was_retained_at_output_drop_start);
5274 assert!(source_probe.original_is_closed()?);
5275 assert!(
5276 operation_available,
5277 "payload retained the OpenCreate operation permit"
5278 );
5279 assert_eq!(
5280 sample_count, 1,
5281 "payload started before its metadata probe finished"
5282 );
5283 assert_eq!(samples.metadata_count(), 1);
5284 assert_eq!(cancelled.final_hit_count, 1);
5285 assert_eq!(mode?, DST_FILE_CREATE_MODE);
5286 assert_eq!(
5287 std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
5288 DST_FILE_CREATE_MODE
5289 );
5290 assert_eq!(
5291 std::fs::read(destination)?,
5292 if fail_payload {
5293 b"partial".as_slice()
5294 } else {
5295 b"complete payload".as_slice()
5296 }
5297 );
5298 Ok(())
5299 }
5300
5301 #[tokio::test]
5302 async fn cancelled_started_file_continuation_keeps_fds_until_abandoned_output_drops()
5303 -> anyhow::Result<()> {
5304 cancelled_claimed_file_continuation_case(false).await
5305 }
5306
5307 #[tokio::test]
5308 async fn cancelled_failed_file_continuation_keeps_fds_until_abandoned_output_drops()
5309 -> anyhow::Result<()> {
5310 cancelled_claimed_file_continuation_case(true).await
5311 }
5312
5313 #[tokio::test]
5314 async fn panicking_file_create_closes_unclaimed_payload_before_its_admission_lease()
5315 -> anyhow::Result<()> {
5316 let source = tempfile::tempfile()?;
5317 let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5318 let observation = Arc::new(std::sync::Mutex::new(None));
5319 let capture = QueuedFdCapture {
5320 file: Some(source),
5321 probe,
5322 observation: Arc::clone(&observation),
5323 };
5324 let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5325 let continuation_called = Arc::clone(&called);
5326 let limits = testutils::AdmissionLimit::new().await;
5327 limits.set_files_in_flight(1);
5328 let guard = throttle::open_file_permit().await;
5329 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5330 let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
5331 let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5332 run_file_create_and_then(
5333 congestion::Side::Destination,
5334 move || -> std::io::Result<std::fs::File> {
5335 let _ = started_tx.send(());
5336 let _ = release_rx.recv();
5337 panic!("injected file-create panic");
5338 },
5339 move |_created| {
5340 let _capture = capture;
5341 continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5342 },
5343 )
5344 .await
5345 }));
5346 let pending = futures::poll!(work.as_mut()).is_pending();
5347 drop(guard);
5348 let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
5349 drop(release_tx);
5350 let result = work.await;
5351 assert!(pending);
5352 started??;
5353 assert!(result.is_err(), "worker panic must fail the create waiter");
5354 assert!(probe.original_is_closed()?);
5355 assert_eq!(
5356 observation.lock().unwrap().take().transpose()?,
5357 Some(QueuedFdDropObservation {
5358 fd_was_closed: true,
5359 admission_was_retained: true,
5360 })
5361 );
5362 assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5363 let permit = tokio::time::timeout(
5364 std::time::Duration::from_secs(5),
5365 throttle::open_file_permit(),
5366 )
5367 .await?;
5368 drop(permit);
5369 Ok(())
5370 }
5371
5372 #[tokio::test]
5373 async fn cancelled_file_creation_waiting_for_opencreate_never_submits_or_runs_payload()
5374 -> anyhow::Result<()> {
5375 let tmp = tempfile::tempdir()?;
5376 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5377 let destination = tmp.path().join("destination");
5378 let source = tempfile::tempfile()?;
5379 let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5380 let observation = Arc::new(std::sync::Mutex::new(None));
5381 let capture = QueuedFdCapture {
5382 file: Some(source),
5383 probe,
5384 observation: Arc::clone(&observation),
5385 };
5386 let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5387 let continuation_called = Arc::clone(&called);
5388 let limits = testutils::AdmissionLimit::new().await;
5389 limits.set_files_in_flight(1);
5390 let resource = throttle::Resource::meta(
5391 throttle::Side::Destination,
5392 throttle::MetadataOp::OpenCreate,
5393 );
5394 limits.set_max_ops_in_flight(resource, 1);
5395 let occupied = throttle::ops_in_flight_permit(resource).await;
5396 let guard = throttle::open_file_permit().await;
5397 let submissions = testutils::BlockingSubmissions::start();
5398 let samples = Arc::new(congestion::testing::CollectingSink::new());
5399 congestion::install_sample_sink(samples.clone());
5400 let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5401 root.create_file_and_then(OsStr::new("destination"), move |created| {
5402 let _capture = capture;
5403 continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5404 created
5405 })
5406 .await
5407 }));
5408 let waiting = futures::poll!(work.as_mut()).is_pending();
5409 let source_was_open = probe.original_is_closed().map(|closed| !closed);
5410 drop(work);
5411 let source_closed_while_outer_admitted = probe.original_is_closed();
5412 let outer_admission_retained = throttle::open_file_permit().now_or_never().is_none();
5413 let drop_observation = observation.lock().unwrap().take().transpose();
5414 drop(occupied);
5415 drop(guard);
5416 let permit = tokio::time::timeout(
5417 std::time::Duration::from_secs(5),
5418 throttle::open_file_permit(),
5419 )
5420 .await?;
5421 drop(permit);
5422 assert!(waiting && source_was_open?);
5423 assert!(source_closed_while_outer_admitted?);
5424 assert!(outer_admission_retained);
5425 assert_eq!(
5426 drop_observation?,
5427 Some(QueuedFdDropObservation {
5428 fd_was_closed: true,
5429 admission_was_retained: true,
5430 })
5431 );
5432 assert_eq!(submissions.count(), 0);
5433 assert_eq!(samples.metadata_count(), 0);
5434 assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5435 assert!(!destination.exists());
5436 Ok(())
5437 }
5438
5439 #[tokio::test]
5440 async fn panicking_claimed_file_continuation_closes_both_fds_before_admission()
5441 -> anyhow::Result<()> {
5442 use std::os::unix::fs::PermissionsExt as _;
5443 let tmp = tempfile::tempdir()?;
5444 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5445 let destination = tmp.path().join("destination");
5446 let source = tempfile::tempfile()?;
5447 let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5448 let source_observation = Arc::new(std::sync::Mutex::new(None));
5449 let destination_observation = Arc::new(std::sync::Mutex::new(None));
5450 let payload_destination_observation = Arc::clone(&destination_observation);
5451 let source_capture = QueuedFdCapture {
5452 file: Some(source),
5453 probe: source_probe,
5454 observation: Arc::clone(&source_observation),
5455 };
5456 let limits = testutils::AdmissionLimit::new().await;
5457 limits.set_files_in_flight(1);
5458 let guard = throttle::open_file_permit().await;
5459 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5460 let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
5461 let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5462 root.create_file_and_then(
5463 OsStr::new("destination"),
5464 move |created| -> std::io::Result<()> {
5465 let _source = source_capture;
5466 let file = created?;
5467 let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
5468 let _destination = QueuedFdCapture {
5469 file: Some(file),
5470 probe,
5471 observation: payload_destination_observation,
5472 };
5473 let _ = started_tx.send(probe);
5474 let _ = release_rx.recv();
5475 panic!("injected claimed file-continuation panic");
5476 },
5477 )
5478 .await
5479 }));
5480 let pending = futures::poll!(work.as_mut()).is_pending();
5481 drop(guard);
5482 let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
5483 let source_was_open = source_probe.original_is_closed().map(|closed| !closed);
5484 let destination_was_open = match &started {
5485 Ok(Ok(probe)) => Some(probe.original_is_closed().map(|closed| !closed)),
5486 _ => None,
5487 };
5488 let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
5489 drop(release_tx);
5490 let result = work.await;
5491 let destination_probe = started??;
5492 assert!(pending);
5493 assert!(source_was_open? && destination_was_open.transpose()?.unwrap());
5494 assert!(admission_was_retained);
5495 assert!(
5496 result.is_err(),
5497 "claimed continuation panic must fail the waiter"
5498 );
5499 assert!(source_probe.original_is_closed()? && destination_probe.original_is_closed()?);
5500 for observation in [source_observation, destination_observation] {
5501 assert_eq!(
5502 observation.lock().unwrap().take().transpose()?,
5503 Some(QueuedFdDropObservation {
5504 fd_was_closed: true,
5505 admission_was_retained: true,
5506 })
5507 );
5508 }
5509 assert_eq!(
5510 std::fs::metadata(destination)?.permissions().mode() & 0o7777,
5511 DST_FILE_CREATE_MODE
5512 );
5513 let permit = tokio::time::timeout(
5514 std::time::Duration::from_secs(5),
5515 throttle::open_file_permit(),
5516 )
5517 .await?;
5518 drop(permit);
5519 Ok(())
5520 }
5521
5522 #[test]
5525 fn dropping_queued_blocking_work_closes_fd_before_returning_admission() -> anyhow::Result<()>
5526 {
5527 let runtime = tokio::runtime::Builder::new_multi_thread()
5528 .worker_threads(1)
5529 .max_blocking_threads(1)
5530 .enable_all()
5531 .build()?;
5532 runtime.block_on(async {
5533 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5534 assert_queued_owner_closes_before_admission(|owner| async move {
5535 run_fd_admitted_blocking(move || {
5536 let _owner = owner;
5537 let _ = started_tx.send(());
5538 Ok(())
5539 })
5540 .await
5541 })
5542 .await?;
5543 assert!(
5544 matches!(
5545 tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await,
5546 Ok(Err(_))
5547 ),
5548 "the dropped queued blocking work started"
5549 );
5550 Ok(())
5551 })
5552 }
5553
5554 #[tokio::test]
5559 async fn cancelled_unprobed_waiter_keeps_admission_until_fd_owner_finishes()
5560 -> anyhow::Result<()> {
5561 let root = crate::testutils::create_temp_dir().await?;
5562 let file_path = root.join("held-unprobed");
5563 tokio::fs::write(&file_path, b"x").await?;
5564 let admission = crate::testutils::AdmissionLimit::new().await;
5565 admission.set_files_in_flight(1);
5566 let open_file_guard = throttle::open_file_permit().await;
5567 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5568 let (release_tx, release_rx) = std::sync::mpsc::channel();
5569 let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
5570 let task = tokio::spawn(async move {
5571 let admission = open_file_guard.admission();
5572 with_fd_admission(admission, async move {
5573 let _open_file_guard = open_file_guard;
5574 run_fd_admitted_blocking(move || {
5575 let _completion = completion;
5576 let _file = std::fs::File::open(file_path)?;
5577 let _ = started_tx.send(());
5578 release_rx.recv().map_err(std::io::Error::other)?;
5579 Ok(())
5580 })
5581 .await
5582 })
5583 .await
5584 });
5585 let started_result = started_rx.await;
5586 task.abort();
5587 let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5588
5589 let mut second_permit = Box::pin(throttle::open_file_permit());
5590 let admission_was_retained =
5591 started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
5592 let release_result = release_tx.send(());
5593 let (completion_result, permit) = crate::testutils::await_completion_and_capacity(
5594 completion_rx,
5595 second_permit.as_mut(),
5596 )
5597 .await;
5598 started_result.context("detached unprobed work did not start")?;
5599 release_result.context("detached unprobed work ended before its release")?;
5600 completion_result.context("detached unprobed work did not report completion")?;
5601 drop(permit);
5602 assert!(waiter_was_cancelled);
5603 assert!(
5604 admission_was_retained,
5605 "cancelling the waiter released admission while detached work held an fd"
5606 );
5607 Ok(())
5608 }
5609
5610 #[tokio::test]
5613 async fn cancelled_metadata_waiter_keeps_admission_until_fd_owner_finishes()
5614 -> anyhow::Result<()> {
5615 let root = crate::testutils::create_temp_dir().await?;
5616 let file_path = root.join("held");
5617 tokio::fs::write(&file_path, b"x").await?;
5618 let admission = crate::testutils::AdmissionLimit::new().await;
5619 admission.set_files_in_flight(1);
5620 let stat_resource =
5621 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
5622 admission.set_max_ops_in_flight(stat_resource, 1);
5623 let open_file_guard = throttle::open_file_permit().await;
5624 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5625 let (release_tx, release_rx) = std::sync::mpsc::channel();
5626 let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
5627 let task = tokio::spawn(async move {
5628 let admission = open_file_guard.admission();
5629 with_fd_admission(admission, async move {
5630 let _open_file_guard = open_file_guard;
5631 run_metadata_probed_blocking(
5632 congestion::Side::Source,
5633 congestion::MetadataOp::Stat,
5634 move || {
5635 let _completion = completion;
5636 let _file = std::fs::File::open(file_path)?;
5637 let _ = started_tx.send(());
5638 release_rx.recv().map_err(std::io::Error::other)?;
5639 Ok(())
5640 },
5641 )
5642 .await
5643 })
5644 .await
5645 });
5646 let started_result = started_rx.await;
5647 task.abort();
5648 let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5649
5650 let second_permit = throttle::open_file_permit();
5651 tokio::pin!(second_permit);
5652 let admission_was_retained =
5653 started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
5654 let second_stat_permit = throttle::ops_in_flight_permit(stat_resource);
5655 tokio::pin!(second_stat_permit);
5656 let metadata_was_retained =
5657 started_result.is_ok() && futures::poll!(second_stat_permit.as_mut()).is_pending();
5658 let release_result = release_tx.send(());
5659 let (completion_result, (permit, stat_permit)) =
5660 crate::testutils::await_completion_and_capacity(
5661 completion_rx,
5662 futures::future::join(second_permit.as_mut(), second_stat_permit.as_mut()),
5663 )
5664 .await;
5665 started_result.context("detached metadata work did not start")?;
5666 release_result.context("detached metadata work ended before its release")?;
5667 completion_result.context("detached metadata work did not report completion")?;
5668 drop(permit);
5669 drop(stat_permit);
5670 assert!(waiter_was_cancelled);
5671 assert!(
5672 admission_was_retained,
5673 "cancelling the waiter released admission while detached work held an fd"
5674 );
5675 assert!(
5676 metadata_was_retained,
5677 "cancelling the waiter released metadata capacity while its syscall was live"
5678 );
5679 Ok(())
5680 }
5681
5682 #[tokio::test]
5685 async fn abandoned_metadata_output_keeps_admission_until_returned_fd_drops()
5686 -> anyhow::Result<()> {
5687 assert_abandoned_output_closes_before_admission(|owner| async move {
5688 run_metadata_probed_blocking(
5689 congestion::Side::Source,
5690 congestion::MetadataOp::Stat,
5691 move || {
5692 let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5693 Ok(owner)
5694 },
5695 )
5696 .await
5697 })
5698 .await
5699 }
5700
5701 #[tokio::test]
5704 async fn abandoned_unprobed_output_keeps_admission_until_returned_fd_drops()
5705 -> anyhow::Result<()> {
5706 assert_abandoned_output_closes_before_admission(|owner| async move {
5707 run_fd_admitted_blocking(move || {
5708 let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5709 Ok(owner)
5710 })
5711 .await
5712 })
5713 .await
5714 }
5715 }
5716
5717 #[test]
5718 fn a_run_that_asked_for_nothing_wants_no_root_acl_notice() {
5719 let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5723 assert!(!notice.wanted);
5724 for kind in EVERY_KIND {
5725 assert!(
5726 !notice.could_warn_for_strict(kind, false),
5727 "a {kind:?} root warned under settings that asked for no preservation"
5728 );
5729 }
5730 }
5731
5732 #[test]
5733 fn strict_resolution_arms_the_notice_on_its_own() {
5734 let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5738 assert!(notice.could_warn_for_strict(EntryKind::Dir, true));
5739 assert!(notice.could_warn_for_strict(EntryKind::File, true));
5740 }
5741
5742 #[test]
5743 fn the_notice_consults_the_setting_for_the_roots_own_kind() {
5744 let file_only = RootAclNotice {
5748 wanted: true,
5749 file_acl_preserved: true,
5750 dir_acl_preserved: false,
5751 };
5752 assert!(!file_only.could_warn_for_strict(EntryKind::File, false));
5753 assert!(file_only.could_warn_for_strict(EntryKind::Dir, false));
5754 assert!(
5755 file_only.could_warn(),
5756 "a directory root can still warn, so the kind-unknown pre-check must not skip the probe"
5757 );
5758 }
5759
5760 #[test]
5761 fn a_root_that_cannot_carry_an_acl_never_warns() {
5762 let armed = RootAclNotice {
5765 wanted: true,
5766 file_acl_preserved: false,
5767 dir_acl_preserved: false,
5768 };
5769 for kind in [EntryKind::Symlink, EntryKind::Special] {
5770 assert!(!armed.could_warn_for_strict(kind, true));
5771 }
5772 }
5773
5774 #[test]
5775 fn preserving_both_kinds_acls_leaves_nothing_to_warn_about() {
5776 let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_all_with_acls());
5777 assert!(notice.wanted, "`all+acl` did ask for preservation");
5778 assert!(
5779 !notice.could_warn(),
5780 "both kinds' ACLs are carried across, so even an armed run has nothing to say — and \
5781 must not pay the probe to find that out"
5782 );
5783 }
5784
5785 #[tokio::test]
5786 async fn child_classifies_file_dir_symlink_and_rejects_nofollow() -> anyhow::Result<()> {
5787 let tmp = testutils::setup_test_dir().await?;
5788 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5790 assert_eq!(
5791 root.child(OsStr::new("0.txt")).await?.kind(),
5792 EntryKind::File
5793 );
5794 assert_eq!(root.child(OsStr::new("bar")).await?.kind(), EntryKind::Dir);
5795 tokio::fs::symlink("0.txt", tmp.join("foo/lnk")).await?;
5796 assert_eq!(
5797 root.child(OsStr::new("lnk")).await?.kind(),
5798 EntryKind::Symlink
5799 );
5800 tokio::fs::symlink("/etc", tmp.join("foo/evil")).await?;
5802 assert!(root.open_dir(OsStr::new("evil")).await.is_err());
5803 Ok(())
5804 }
5805
5806 #[tokio::test]
5807 async fn open_dir_succeeds_on_real_directory() -> anyhow::Result<()> {
5808 let tmp = testutils::setup_test_dir().await?;
5809 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5810 let bar = root.open_dir(OsStr::new("bar")).await?;
5812 assert_eq!(
5814 bar.child(OsStr::new("1.txt")).await?.kind(),
5815 EntryKind::File
5816 );
5817 Ok(())
5818 }
5819
5820 #[tokio::test]
5821 async fn directory_metadata_snapshot_uses_the_opened_inode_after_a_name_swap()
5822 -> anyhow::Result<()> {
5823 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
5824 for create in [false, true] {
5825 let tmp = tempfile::tempdir()?;
5826 let path = tmp.path().join("child");
5827 let moved = tmp.path().join("moved");
5828 if !create {
5829 std::fs::create_dir(&path)?;
5830 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?;
5831 }
5832 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
5833 let mut gate = testutils::BlockingPathGate::install(&path);
5834 let task = tokio::spawn(async move {
5835 if create {
5836 let (sender, snapshot) = tokio::sync::oneshot::channel();
5837 let dir = root
5838 .make_dir_checked(OsStr::new("child"), 0o700, move |meta| {
5839 let _ = sender.send(meta.clone());
5840 Ok(())
5841 })
5842 .await?;
5843 Ok((dir, snapshot.await.map_err(std::io::Error::other)?))
5844 } else {
5845 root.open_dir_with_meta(OsStr::new("child")).await
5846 }
5847 });
5848 tokio::time::timeout(std::time::Duration::from_secs(5), gate.wait_started()).await??;
5849 let before = std::fs::metadata(&path)?;
5850 std::fs::rename(&path, &moved)?;
5851 std::fs::create_dir(&path)?;
5852 let replacement = std::fs::metadata(&path)?;
5853 gate.release_all();
5854 let (dir, snapshot) = task.await??;
5855 assert_eq!(
5856 (snapshot.dev(), snapshot.ino()),
5857 (before.dev(), before.ino())
5858 );
5859 assert_ne!(
5860 (snapshot.dev(), snapshot.ino()),
5861 (replacement.dev(), replacement.ino())
5862 );
5863 assert_eq!(snapshot.permissions().mode() & 0o7777, 0o700);
5864 std::fs::set_permissions(&moved, std::fs::Permissions::from_mode(0o500))?;
5865 let live = dir.meta().await?;
5866 assert_eq!((live.dev(), live.ino()), (snapshot.dev(), snapshot.ino()));
5867 assert_eq!(live.permissions().mode() & 0o7777, 0o500);
5868 assert_eq!(snapshot.permissions().mode() & 0o7777, 0o700);
5869 }
5870 Ok(())
5871 }
5872
5873 #[tokio::test]
5874 async fn rejected_created_directory_removes_the_empty_slot() -> anyhow::Result<()> {
5875 let tmp = tempfile::tempdir()?;
5876 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5877 let error = root
5878 .make_dir_checked(OsStr::new("child"), 0o700, |_meta| {
5879 Err(std::io::Error::from_raw_os_error(libc::EIO))
5880 })
5881 .await
5882 .unwrap_err();
5883 assert_eq!(error.raw_os_error(), Some(libc::EIO));
5884 assert!(!tmp.path().join("child").exists());
5885 Ok(())
5886 }
5887
5888 #[cfg_attr(
5889 rcp_nix_sandbox,
5890 ignore = "Nix sandbox cannot change ownership or set-id modes"
5891 )]
5892 #[tokio::test]
5893 async fn secure_as_copier_takes_ownership_restricts_mode_and_preserves_gid()
5894 -> anyhow::Result<()> {
5895 use std::os::unix::fs::PermissionsExt as _;
5896 let tmp = testutils::setup_test_dir().await?;
5897 let root =
5898 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5899
5900 let plain = root.make_dir(OsStr::new("reused_plain"), 0o755).await?;
5903 let before = plain.meta().await?;
5904 plain
5905 .secure_as_copier(0o700, before.uid(), before.gid())
5906 .await?;
5907 let after = plain.meta().await?;
5908 assert_eq!(
5909 after.permissions().mode() & 0o7777,
5910 0o700,
5911 "mode restricted"
5912 );
5913 assert_eq!(
5914 after.uid(),
5915 nix::unistd::geteuid().as_raw(),
5916 "owned by copier"
5917 );
5918 assert_eq!(after.gid(), before.gid(), "gid unchanged when it matches");
5919
5920 let sg = root.make_dir(OsStr::new("reused_setgid"), 0o755).await?;
5923 std::fs::set_permissions(
5924 tmp.join("foo/reused_setgid"),
5925 std::fs::Permissions::from_mode(0o2755),
5926 )?;
5927 let sg_before = sg.meta().await?;
5928 assert_eq!(
5929 sg_before.permissions().mode() & 0o2000,
5930 0o2000,
5931 "test setup: S_ISGID is set before lockdown"
5932 );
5933 sg.secure_as_copier(0o2700, sg_before.uid(), sg_before.gid())
5934 .await?;
5935 let sg_after = sg.meta().await?;
5936 assert_eq!(
5937 sg_after.permissions().mode() & 0o7777,
5938 0o2700,
5939 "S_ISGID + 0o700 both preserved"
5940 );
5941 assert_eq!(
5942 sg_after.gid(),
5943 sg_before.gid(),
5944 "gid preserved under setgid"
5945 );
5946 Ok(())
5947 }
5948
5949 #[tokio::test]
5954 async fn open_parent_dir_follows_symlinked_prefix_but_descendants_stay_hardened()
5955 -> anyhow::Result<()> {
5956 let tmp = testutils::setup_test_dir().await?;
5957 tokio::fs::symlink("foo", tmp.join("foo_link")).await?;
5959 let parent = Dir::open_parent_dir(&tmp.join("foo_link"), congestion::Side::Source).await?;
5962 let tree = parent.into_tree();
5963 assert_eq!(
5965 tree.child(OsStr::new("0.txt")).await?.kind(),
5966 EntryKind::File
5967 );
5968 assert!(
5972 Dir::open_root_dir(&tmp.join("foo_link"), false, congestion::Side::Source)
5973 .await
5974 .is_err()
5975 );
5976 tokio::fs::symlink("/etc", tmp.join("foo/evil_below")).await?;
5979 assert!(tree.open_dir(OsStr::new("evil_below")).await.is_err());
5980 Ok(())
5981 }
5982
5983 #[tokio::test]
5984 async fn rejects_multi_component_names() -> anyhow::Result<()> {
5985 let tmp = testutils::setup_test_dir().await?;
5986 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5987 for bad in ["bar/1.txt", "..", ".", ""] {
5990 let child_err = root.child(OsStr::new(bad)).await.unwrap_err();
5991 assert_eq!(child_err.raw_os_error(), Some(libc::EINVAL));
5992 let dir_err = root.open_dir(OsStr::new(bad)).await.unwrap_err();
5993 assert_eq!(dir_err.raw_os_error(), Some(libc::EINVAL));
5994 let file_err = root.open_file_read(OsStr::new(bad)).await.unwrap_err();
5995 assert_eq!(file_err.raw_os_error(), Some(libc::EINVAL));
5996 let create_err = root.create_file(OsStr::new(bad)).await.unwrap_err();
5997 assert_eq!(create_err.raw_os_error(), Some(libc::EINVAL));
5998 }
5999 Ok(())
6000 }
6001
6002 #[tokio::test]
6008 async fn operations_remain_valid_after_original_dir_dropped() -> anyhow::Result<()> {
6009 let tmp = testutils::setup_test_dir().await?;
6010 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6011 let shared = Dir {
6013 captured_identity: root.captured_identity,
6014 fd: root.fd.clone(),
6015 side: root.side,
6016 children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
6017 };
6018 drop(root);
6019 assert_eq!(
6021 shared.child(OsStr::new("0.txt")).await?.kind(),
6022 EntryKind::File
6023 );
6024 let bar = shared.open_dir(OsStr::new("bar")).await?;
6025 assert_eq!(
6026 bar.child(OsStr::new("2.txt")).await?.kind(),
6027 EntryKind::File
6028 );
6029 Ok(())
6030 }
6031
6032 #[tokio::test]
6035 async fn open_file_read_reads_regular_file() -> anyhow::Result<()> {
6036 let tmp = testutils::setup_test_dir().await?;
6037 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6038 let (mut file, meta) = root.open_file_read(OsStr::new("0.txt")).await?;
6039 assert_eq!(meta.size(), 1);
6041 let mut buf = String::new();
6042 file.read_to_string(&mut buf)?;
6043 assert_eq!(buf, "0");
6044 Ok(())
6045 }
6046
6047 #[tokio::test]
6050 async fn open_file_read_rejects_fifo_without_blocking() -> anyhow::Result<()> {
6051 let tmp = testutils::setup_test_dir().await?;
6052 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6053 let fifo_path = tmp.join("foo/test.fifo");
6054 nix::unistd::mkfifo(
6055 &fifo_path,
6056 nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
6057 )?;
6058 let result = tokio::time::timeout(
6060 std::time::Duration::from_secs(5),
6061 root.open_file_read(OsStr::new("test.fifo")),
6062 )
6063 .await;
6064 assert!(result.is_ok(), "open_file_read blocked on FIFO (timed out)");
6065 assert!(
6066 result.unwrap().is_err(),
6067 "open_file_read must reject a FIFO"
6068 );
6069 Ok(())
6070 }
6071
6072 #[tokio::test]
6074 async fn open_file_read_rejects_symlink() -> anyhow::Result<()> {
6075 let tmp = testutils::setup_test_dir().await?;
6076 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6077 tokio::fs::symlink("0.txt", tmp.join("foo/link_to_0")).await?;
6079 let result = root.open_file_read(OsStr::new("link_to_0")).await;
6080 assert!(result.is_err(), "open_file_read must reject a symlink");
6081 Ok(())
6082 }
6083
6084 #[tokio::test]
6086 async fn create_file_creates_new_writable_file() -> anyhow::Result<()> {
6087 let tmp = testutils::setup_test_dir().await?;
6088 let root =
6090 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6091 let mut file = root.create_file(OsStr::new("new.txt")).await?;
6092 use std::io::Write;
6093 file.write_all(b"hello safedir")?;
6094 drop(file);
6095 let content = std::fs::read(tmp.join("foo/new.txt"))?;
6097 assert_eq!(content, b"hello safedir");
6098 Ok(())
6099 }
6100
6101 #[tokio::test]
6103 async fn create_file_fails_if_exists() -> anyhow::Result<()> {
6104 let tmp = testutils::setup_test_dir().await?;
6105 let root =
6106 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6107 let err = root.create_file(OsStr::new("0.txt")).await.unwrap_err();
6109 assert_eq!(
6110 err.raw_os_error(),
6111 Some(libc::EEXIST),
6112 "expected EEXIST, got {err:#}"
6113 );
6114 Ok(())
6115 }
6116
6117 #[tokio::test]
6119 async fn make_dir_creates_and_returns_usable_dir() -> anyhow::Result<()> {
6120 let tmp = testutils::setup_test_dir().await?;
6121 let root =
6122 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6123 let sub = root.make_dir(OsStr::new("sub"), 0o755).await?;
6124 sub.create_file(OsStr::new("child.txt")).await?;
6126 let entries = sub.read_entries().await?;
6128 let names: Vec<_> = entries
6129 .iter()
6130 .map(|(n, _)| n.to_string_lossy().into_owned())
6131 .collect();
6132 assert!(
6133 names.contains(&"child.txt".to_string()),
6134 "child.txt not found in {names:?}"
6135 );
6136 Ok(())
6137 }
6138
6139 #[tokio::test]
6141 async fn make_dir_rejects_multi_component_names() -> anyhow::Result<()> {
6142 let tmp = testutils::setup_test_dir().await?;
6143 let root =
6144 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6145 for bad in ["a/b", "..", ".", ""] {
6146 let err = root.make_dir(OsStr::new(bad), 0o755).await.unwrap_err();
6147 assert_eq!(
6148 err.raw_os_error(),
6149 Some(libc::EINVAL),
6150 "expected EINVAL for {:?}, got {err:#}",
6151 bad
6152 );
6153 }
6154 Ok(())
6155 }
6156
6157 #[test]
6158 fn dtype_hints_only_classify_named_types() {
6159 let named = [
6160 (libc::DT_DIR, EntryKind::Dir),
6161 (libc::DT_LNK, EntryKind::Symlink),
6162 (libc::DT_REG, EntryKind::File),
6163 (libc::DT_FIFO, EntryKind::Special),
6164 (libc::DT_CHR, EntryKind::Special),
6165 (libc::DT_BLK, EntryKind::Special),
6166 (libc::DT_SOCK, EntryKind::Special),
6167 ];
6168 for dtype in libc::c_uchar::MIN..=libc::c_uchar::MAX {
6169 let expected = named
6170 .iter()
6171 .find(|(value, _)| *value == dtype)
6172 .map(|(_, kind)| *kind);
6173 assert_eq!(kind_hint_from_dtype(dtype), expected, "d_type={dtype}");
6174 }
6175 }
6176
6177 #[tokio::test]
6179 async fn read_entries_lists_children_with_dtype_hints() -> anyhow::Result<()> {
6180 use std::collections::HashMap;
6181 let tmp = testutils::setup_test_dir().await?;
6182 let fixture = tmp.join("foo/fixture_dir");
6185 tokio::fs::create_dir(&fixture).await?;
6186 tokio::fs::write(fixture.join("afile.txt"), "x").await?;
6187 tokio::fs::create_dir(fixture.join("asubdir")).await?;
6188 tokio::fs::symlink("afile.txt", fixture.join("alink")).await?;
6189
6190 let root = Dir::open_root_dir(&fixture, false, congestion::Side::Source).await?;
6191 let entries = root.read_entries().await?;
6192 let map: HashMap<String, Option<EntryKind>> = entries
6193 .into_iter()
6194 .map(|(n, k)| (n.to_string_lossy().into_owned(), k))
6195 .collect();
6196
6197 assert_eq!(map.len(), 3, "expected 3 entries, got {map:?}");
6198 assert_eq!(
6199 map.get("afile.txt"),
6200 Some(&Some(EntryKind::File)),
6201 "afile.txt wrong"
6202 );
6203 assert_eq!(
6204 map.get("asubdir"),
6205 Some(&Some(EntryKind::Dir)),
6206 "asubdir wrong"
6207 );
6208 assert_eq!(
6209 map.get("alink"),
6210 Some(&Some(EntryKind::Symlink)),
6211 "alink wrong"
6212 );
6213 Ok(())
6214 }
6215
6216 #[tokio::test]
6217 async fn read_entries_sees_children_created_after_open_and_between_reads() -> anyhow::Result<()>
6218 {
6219 let tmp = tempfile::tempdir()?;
6220 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6221 for name in ["first", "second"] {
6222 std::fs::write(tmp.path().join(name), b"content")?;
6223 let names = sorted_names(root.read_entries().await?);
6224 let expected = if name == "first" {
6225 vec!["first"]
6226 } else {
6227 vec!["first", "second"]
6228 };
6229 assert_eq!(names, expected);
6230 }
6231 Ok(())
6232 }
6233
6234 fn exhaust_shared_directory_offset(root: &Dir) -> anyhow::Result<()> {
6235 let mut stream = OwnedDirectoryStream::from_fd(root.fd.fd.try_clone()?, None)?;
6236 while stream.next_raw_entry()?.is_some() {}
6237 let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
6240 if let Ok(offset) = end {
6241 assert_ne!(
6242 offset, 0,
6243 "exhausting the stream did not advance its offset"
6244 );
6245 } else {
6246 assert_eq!(end, Err(nix::errno::Errno::ESPIPE));
6247 }
6248 drop(stream);
6249 assert_eq!(
6250 nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
6251 end,
6252 "closing the stream changed the shared offset"
6253 );
6254 Ok(())
6255 }
6256
6257 fn sorted_names(
6258 entries: Vec<(std::ffi::OsString, Option<EntryKind>)>,
6259 ) -> Vec<std::ffi::OsString> {
6260 let mut names: Vec<_> = entries.into_iter().map(|(name, _)| name).collect();
6261 names.sort();
6262 names
6263 }
6264
6265 fn stream_names(fd: OwnedFd) -> anyhow::Result<Vec<std::ffi::OsString>> {
6266 let mut stream = OwnedDirectoryStream::from_fd(fd, None)?;
6267 let mut names = Vec::new();
6268 while let Some(entry) = stream.next_raw_entry()? {
6269 if entry.name != "." && entry.name != ".." {
6270 names.push(entry.name);
6271 }
6272 }
6273 names.sort();
6274 Ok(names)
6275 }
6276
6277 #[tokio::test]
6278 async fn listing_fd_shares_the_refreshed_description_on_seek_success() -> anyhow::Result<()> {
6279 let tmp = tempfile::tempdir()?;
6280 std::fs::write(tmp.path().join("entry"), b"content")?;
6281 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6282 exhaust_shared_directory_offset(&root)?;
6283 let fd = root.fd.listing_fd_with_seek(|fd| {
6284 assert_eq!(fd.as_raw_fd(), root.fd.as_raw_fd());
6285 nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
6286 })?;
6287 assert_eq!(
6288 nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur)?,
6289 0
6290 );
6291 assert_eq!(stream_names(fd)?, ["entry"]);
6292 assert_ne!(
6293 nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur)?,
6294 0
6295 );
6296 Ok(())
6297 }
6298
6299 #[tokio::test]
6300 async fn listing_fd_reopens_the_held_directory_on_espipe() -> anyhow::Result<()> {
6301 for mode in [None, Some(0o444)] {
6302 let tmp = tempfile::tempdir()?;
6303 let parent = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6304 let _restore_parent = RestoreDirectoryAccess(&parent);
6305 let source = tmp.path().join("source");
6306 std::fs::create_dir(&source)?;
6307 std::fs::write(source.join("entry"), b"content")?;
6308 let root = Dir::open_root_dir(&source, false, congestion::Side::Source).await?;
6309 let _restore = RestoreDirectoryAccess(&root);
6310 exhaust_shared_directory_offset(&root)?;
6311 let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
6312 if let Some(mode) = mode {
6313 fchmod(root.fd.as_fd(), Mode::from_bits_truncate(mode))?;
6314 if !directory_search_permission_is_enforced(&root)? {
6315 continue;
6316 }
6317 }
6318 std::fs::rename(&source, tmp.path().join("moved"))?;
6320 let replacement = tmp.path().join("replacement");
6321 std::fs::create_dir(&replacement)?;
6322 std::fs::write(replacement.join("sentinel"), b"other")?;
6323 std::os::unix::fs::symlink(&replacement, &source)?;
6324 if mode.is_some() {
6325 fchmod(parent.fd.as_fd(), Mode::empty())?;
6328 let path = std::fs::read_link(format!("/proc/self/fd/{}", root.fd.as_raw_fd()))?;
6329 assert_eq!(
6330 std::fs::File::open(path).unwrap_err().raw_os_error(),
6331 Some(libc::EACCES)
6332 );
6333 }
6334 for _ in 0..2 {
6335 let fd = root.fd.listing_fd_with_seek(|fd| {
6336 assert_eq!(fd.as_raw_fd(), root.fd.as_raw_fd());
6337 Err(nix::errno::Errno::ESPIPE)
6338 })?;
6339 assert_eq!(stream_names(fd)?, ["entry"], "mode={mode:?}");
6340 assert_eq!(
6341 nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
6342 end
6343 );
6344 }
6345 }
6346 Ok(())
6347 }
6348
6349 #[tokio::test]
6350 async fn listing_fd_propagates_other_seek_errors() -> anyhow::Result<()> {
6351 let tmp = tempfile::tempdir()?;
6352 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6353 for error in [
6354 nix::errno::Errno::EIO,
6355 nix::errno::Errno::EACCES,
6356 nix::errno::Errno::EINVAL,
6357 ] {
6358 let result = root.fd.listing_fd_with_seek(|_| Err(error));
6359 assert_eq!(result.unwrap_err().raw_os_error(), Some(error as i32));
6360 }
6361 assert!(root.read_entries().await?.is_empty());
6362 Ok(())
6363 }
6364
6365 #[tokio::test]
6366 async fn read_entries_refreshes_an_exhausted_shared_offset() -> anyhow::Result<()> {
6367 let tmp = tempfile::tempdir()?;
6368 for name in ["first", "second"] {
6369 std::fs::write(tmp.path().join(name), b"content")?;
6370 }
6371 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6372 exhaust_shared_directory_offset(&root)?;
6373 let names = sorted_names(root.read_entries().await?);
6374 assert_eq!(names, ["first", "second"]);
6375 Ok(())
6376 }
6377
6378 #[tokio::test]
6379 async fn capped_entries_refreshes_an_exhausted_shared_offset() -> anyhow::Result<()> {
6380 let tmp = tempfile::tempdir()?;
6381 for name in ["first", "second", "third"] {
6382 std::fs::write(tmp.path().join(name), b"content")?;
6383 }
6384 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6385 exhaust_shared_directory_offset(&root)?;
6386 assert!(root.read_entries_capped(2).await?.is_none());
6387 let names = sorted_names(
6388 root.read_entries_capped(3)
6389 .await?
6390 .expect("three entries fit the cap"),
6391 );
6392 assert_eq!(names, ["first", "second", "third"]);
6393 Ok(())
6394 }
6395
6396 #[tokio::test]
6397 async fn capped_entries_refresh_after_creation_and_over_cap_reads() -> anyhow::Result<()> {
6398 let tmp = tempfile::tempdir()?;
6399 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6400 assert_eq!(root.read_entries_capped(0).await?, Some(Vec::new()));
6401 std::fs::write(tmp.path().join("first"), b"content")?;
6402 let first = root
6403 .read_entries_capped(1)
6404 .await?
6405 .expect("one entry fits the cap");
6406 assert_eq!(
6407 first.into_iter().map(|(name, _)| name).collect::<Vec<_>>(),
6408 ["first"]
6409 );
6410 std::fs::write(tmp.path().join("second"), b"content")?;
6411 assert!(root.read_entries_capped(1).await?.is_none());
6412 std::fs::write(tmp.path().join("third"), b"content")?;
6413 let names = sorted_names(
6414 root.read_entries_capped(3)
6415 .await?
6416 .expect("three entries fit the cap"),
6417 );
6418 assert_eq!(names, ["first", "second", "third"]);
6419 assert!(root.read_entries_capped(0).await?.is_none());
6420 Ok(())
6421 }
6422
6423 #[tokio::test]
6425 async fn read_entries_does_not_close_self_fd() -> anyhow::Result<()> {
6426 let tmp = testutils::setup_test_dir().await?;
6427 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6428 let first = root.read_entries().await?;
6430 assert!(!first.is_empty(), "first read_entries returned empty");
6431 let second = root.read_entries().await?;
6434 let mut first_names: Vec<_> = first.iter().map(|(name, _)| name.clone()).collect();
6435 let mut second_names: Vec<_> = second.iter().map(|(name, _)| name.clone()).collect();
6436 first_names.sort();
6437 second_names.sort();
6438 assert_eq!(
6439 first_names, second_names,
6440 "second read_entries differs from first"
6441 );
6442 root.child(OsStr::new("0.txt")).await?;
6444 Ok(())
6445 }
6446
6447 #[tokio::test]
6449 async fn create_file_refuses_existing_symlink() -> anyhow::Result<()> {
6450 let tmp = testutils::setup_test_dir().await?;
6451 let root =
6452 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6453 let link_path = tmp.join("foo/evil_link");
6455 let target_path = tmp.join("foo/should_not_be_created");
6456 tokio::fs::symlink(&target_path, &link_path).await?;
6457 let err = root.create_file(OsStr::new("evil_link")).await.unwrap_err();
6459 assert_eq!(
6461 err.raw_os_error(),
6462 Some(libc::EEXIST),
6463 "expected EEXIST, got {err:#}"
6464 );
6465 assert!(
6467 !target_path.exists(),
6468 "symlink target was unexpectedly created"
6469 );
6470 Ok(())
6471 }
6472
6473 #[tokio::test]
6475 async fn unlink_at_removes_file() -> anyhow::Result<()> {
6476 let tmp = testutils::setup_test_dir().await?;
6477 let root =
6478 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6479 root.unlink_at(OsStr::new("0.txt")).await?;
6481 let err = root.child(OsStr::new("0.txt")).await.unwrap_err();
6483 assert_eq!(
6484 err.raw_os_error(),
6485 Some(libc::ENOENT),
6486 "expected ENOENT after unlink, got {err:#}"
6487 );
6488 Ok(())
6489 }
6490
6491 #[tokio::test]
6493 async fn unlink_at_on_symlink_removes_link_not_target() -> anyhow::Result<()> {
6494 let tmp = testutils::setup_test_dir().await?;
6495 let root =
6496 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6497 tokio::fs::write(tmp.join("foo/sentinel.txt"), b"alive").await?;
6499 tokio::fs::symlink("sentinel.txt", tmp.join("foo/lnk")).await?;
6500 root.unlink_at(OsStr::new("lnk")).await?;
6502 let err = root.child(OsStr::new("lnk")).await.unwrap_err();
6504 assert_eq!(
6505 err.raw_os_error(),
6506 Some(libc::ENOENT),
6507 "expected ENOENT for removed link, got {err:#}"
6508 );
6509 let content = tokio::fs::read(tmp.join("foo/sentinel.txt")).await?;
6511 assert_eq!(content, b"alive", "sentinel.txt was unexpectedly removed");
6512 Ok(())
6513 }
6514
6515 #[tokio::test]
6518 async fn rmdir_at_removes_empty_dir_and_rejects_nonempty() -> anyhow::Result<()> {
6519 let tmp = testutils::setup_test_dir().await?;
6520 let root =
6521 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6522 tokio::fs::create_dir(tmp.join("foo/empty_sub")).await?;
6524 root.rmdir_at(OsStr::new("empty_sub")).await?;
6525 let err = root.child(OsStr::new("empty_sub")).await.unwrap_err();
6526 assert_eq!(
6527 err.raw_os_error(),
6528 Some(libc::ENOENT),
6529 "expected ENOENT after rmdir, got {err:#}"
6530 );
6531 let err = root.rmdir_at(OsStr::new("bar")).await.unwrap_err();
6533 assert_eq!(
6534 err.raw_os_error(),
6535 Some(libc::ENOTEMPTY),
6536 "expected ENOTEMPTY for non-empty dir, got {err:#}"
6537 );
6538 let err = root.rmdir_at(OsStr::new("0.txt")).await.unwrap_err();
6540 assert_eq!(
6541 err.raw_os_error(),
6542 Some(libc::ENOTDIR),
6543 "expected ENOTDIR for regular file, got {err:#}"
6544 );
6545 Ok(())
6546 }
6547
6548 #[tokio::test]
6551 async fn symlink_at_creates_link_and_returns_pinned_handle() -> anyhow::Result<()> {
6552 let tmp = testutils::setup_test_dir().await?;
6553 let root =
6554 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6555 let target = std::path::Path::new("some/arbitrary/target");
6556 let handle = root.symlink_at(OsStr::new("mylink"), target).await?;
6557 assert_eq!(
6558 handle.kind(),
6559 EntryKind::Symlink,
6560 "symlink_at must return a Symlink handle"
6561 );
6562 let read_back = root.read_link_at(OsStr::new("mylink")).await?;
6564 assert_eq!(
6565 read_back, target,
6566 "read_link_at returned wrong target: {read_back:?}"
6567 );
6568 Ok(())
6569 }
6570
6571 #[tokio::test]
6575 async fn read_link_handle_reads_target_from_pinned_handle() -> anyhow::Result<()> {
6576 let tmp = testutils::setup_test_dir().await?;
6577 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6578 let target = std::path::Path::new("some/arbitrary/target");
6579 tokio::fs::symlink(target, tmp.join("foo/mylink")).await?;
6580 let handle = root.child(OsStr::new("mylink")).await?;
6582 assert_eq!(handle.kind(), EntryKind::Symlink);
6583 let read_back = read_link_handle(&handle, congestion::Side::Source).await?;
6584 assert_eq!(read_back, target, "wrong target: {read_back:?}");
6585 let file_handle = root.child(OsStr::new("0.txt")).await?;
6589 assert!(
6590 read_link_handle(&file_handle, congestion::Side::Source)
6591 .await
6592 .is_err(),
6593 "read_link_handle on a non-symlink must fail"
6594 );
6595 Ok(())
6596 }
6597
6598 #[tokio::test]
6601 async fn read_symlink_returns_target_and_meta_from_one_handle() -> anyhow::Result<()> {
6602 use crate::preserve::Metadata as _;
6603 let tmp = testutils::setup_test_dir().await?;
6604 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6605 let target = std::path::Path::new("some/target");
6606 tokio::fs::symlink(target, tmp.join("foo/lnk")).await?;
6607 let handle = root.child(OsStr::new("lnk")).await?;
6608 let (read_target, meta) = handle.read_symlink(congestion::Side::Source).await?;
6609 assert_eq!(read_target, target);
6610 assert_eq!(meta.uid(), handle.meta().uid());
6612 assert_eq!(meta.mtime(), handle.meta().mtime());
6613 Ok(())
6614 }
6615
6616 #[tokio::test]
6618 async fn dir_meta_returns_opened_dir_fstat() -> anyhow::Result<()> {
6619 use crate::preserve::Metadata as _;
6620 let tmp = testutils::setup_test_dir().await?;
6621 let bar = Dir::open_root_dir(&tmp.join("foo/bar"), false, congestion::Side::Source).await?;
6622 let meta = bar.meta().await?;
6623 let std_meta = std::fs::metadata(tmp.join("foo/bar"))?;
6624 assert_eq!(meta.uid(), std::os::unix::fs::MetadataExt::uid(&std_meta));
6627 assert_eq!(meta.gid(), std::os::unix::fs::MetadataExt::gid(&std_meta));
6628 Ok(())
6629 }
6630
6631 #[tokio::test]
6633 async fn hard_link_at_creates_hardlink() -> anyhow::Result<()> {
6634 let tmp = testutils::setup_test_dir().await?;
6635 tokio::fs::create_dir(tmp.join("foo/src_sub")).await?;
6637 tokio::fs::create_dir(tmp.join("foo/dst_sub")).await?;
6638 tokio::fs::write(tmp.join("foo/src_sub/orig.txt"), b"hardlink test").await?;
6639
6640 let src =
6641 Dir::open_root_dir(&tmp.join("foo/src_sub"), false, congestion::Side::Source).await?;
6642 let dst = Dir::open_root_dir(
6643 &tmp.join("foo/dst_sub"),
6644 false,
6645 congestion::Side::Destination,
6646 )
6647 .await?;
6648
6649 src.hard_link_at(OsStr::new("orig.txt"), &dst, OsStr::new("link.txt"))
6650 .await?;
6651
6652 let orig_handle = src.child(OsStr::new("orig.txt")).await?;
6654 let link_handle = dst.child(OsStr::new("link.txt")).await?;
6655 assert_eq!(orig_handle.kind(), EntryKind::File, "orig must be a file");
6656 assert_eq!(link_handle.kind(), EntryKind::File, "link must be a file");
6657 assert_eq!(
6658 orig_handle.ino(),
6659 link_handle.ino(),
6660 "hard link must share the inode"
6661 );
6662 Ok(())
6663 }
6664
6665 #[tokio::test]
6669 async fn hard_link_at_does_not_follow_source_symlink() -> anyhow::Result<()> {
6670 let tmp = testutils::setup_test_dir().await?;
6671 tokio::fs::create_dir(tmp.join("foo/src_hl")).await?;
6672 tokio::fs::create_dir(tmp.join("foo/dst_hl")).await?;
6673 tokio::fs::write(tmp.join("foo/src_hl/real.txt"), b"target").await?;
6675 tokio::fs::symlink("real.txt", tmp.join("foo/src_hl/sym.txt")).await?;
6676
6677 let src =
6678 Dir::open_root_dir(&tmp.join("foo/src_hl"), false, congestion::Side::Source).await?;
6679 let dst = Dir::open_root_dir(
6680 &tmp.join("foo/dst_hl"),
6681 false,
6682 congestion::Side::Destination,
6683 )
6684 .await?;
6685
6686 let result = src
6690 .hard_link_at(OsStr::new("sym.txt"), &dst, OsStr::new("new_link.txt"))
6691 .await;
6692 match result {
6693 Ok(()) => {
6694 let new_handle = dst.child(OsStr::new("new_link.txt")).await?;
6697 assert_eq!(
6698 new_handle.kind(),
6699 EntryKind::Symlink,
6700 "hard_link_at must link the symlink itself, not its target"
6701 );
6702 let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
6704 use std::os::unix::fs::MetadataExt;
6705 assert_eq!(
6706 real_meta.nlink(),
6707 1,
6708 "real.txt must not gain a new hard link"
6709 );
6710 }
6711 Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => {
6712 let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
6716 use std::os::unix::fs::MetadataExt;
6717 assert_eq!(
6718 real_meta.nlink(),
6719 1,
6720 "real.txt must not gain a new hard link"
6721 );
6722 }
6723 Err(e) => {
6724 return Err(anyhow::anyhow!(
6725 "unexpected error from hard_link_at on symlink: {e:#}"
6726 ));
6727 }
6728 }
6729 Ok(())
6730 }
6731
6732 #[tokio::test]
6739 async fn hard_link_handle_at_links_pinned_inode_after_name_swap() -> anyhow::Result<()> {
6740 use std::os::unix::fs::MetadataExt;
6741 let tmp = testutils::create_temp_dir().await?;
6742 tokio::fs::create_dir(tmp.join("src")).await?;
6743 tokio::fs::create_dir(tmp.join("dst")).await?;
6744 tokio::fs::write(tmp.join("src/entry"), b"ORIGINAL").await?;
6745 let orig_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
6746
6747 let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6748 let dst =
6749 Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6750 let handle = src.child(OsStr::new("entry")).await?;
6752 assert_eq!(handle.kind(), EntryKind::File);
6753
6754 tokio::fs::write(tmp.join("src/decoy"), b"DECOY_SECRET").await?;
6758 tokio::fs::rename(tmp.join("src/decoy"), tmp.join("src/entry")).await?;
6759 let decoy_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
6760 assert_ne!(orig_ino, decoy_ino, "decoy must be a different inode");
6761
6762 match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
6764 Ok(()) => {
6765 let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
6766 assert!(
6767 lm.file_type().is_file(),
6768 "linked entry must be a regular file"
6769 );
6770 assert_eq!(
6771 lm.ino(),
6772 orig_ino,
6773 "hard_link_handle_at must link the PINNED original inode, never the \
6774 swapped-in decoy (the by-name link would have linked the decoy here)"
6775 );
6776 let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
6777 assert_eq!(
6778 content, "ORIGINAL",
6779 "must reflect the original inode's content"
6780 );
6781 assert_ne!(content, "DECOY_SECRET");
6782 }
6783 Err(e) => {
6784 assert!(
6787 !tmp.join("dst/linked").exists(),
6788 "no destination entry may exist when the link failed closed (got {e:#})"
6789 );
6790 }
6791 }
6792 Ok(())
6793 }
6794
6795 #[tokio::test]
6798 async fn hard_link_handle_at_refuses_directory() -> anyhow::Result<()> {
6799 let tmp = testutils::create_temp_dir().await?;
6800 tokio::fs::create_dir(tmp.join("src")).await?;
6801 tokio::fs::create_dir(tmp.join("dst")).await?;
6802 tokio::fs::create_dir(tmp.join("src/adir")).await?;
6803 let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6804 let dst =
6805 Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6806 let dir_handle = src.child(OsStr::new("adir")).await?;
6807 assert_eq!(dir_handle.kind(), EntryKind::Dir);
6808 let result = dst
6809 .hard_link_handle_at(&dir_handle, OsStr::new("linked_dir"))
6810 .await;
6811 assert!(
6812 result.is_err(),
6813 "hard_link_handle_at must refuse to hard-link a directory"
6814 );
6815 assert!(
6816 !tmp.join("dst/linked_dir").exists(),
6817 "no destination entry may be created for a directory hard link"
6818 );
6819 Ok(())
6820 }
6821
6822 #[tokio::test]
6827 async fn hard_link_handle_at_never_links_swapped_in_fifo() -> anyhow::Result<()> {
6828 use std::os::unix::fs::FileTypeExt;
6829 let tmp = testutils::create_temp_dir().await?;
6830 tokio::fs::create_dir(tmp.join("src")).await?;
6831 tokio::fs::create_dir(tmp.join("dst")).await?;
6832 tokio::fs::write(tmp.join("src/entry"), b"REALFILE").await?;
6833 let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6834 let dst =
6835 Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6836 let handle = src.child(OsStr::new("entry")).await?;
6838 assert_eq!(handle.kind(), EntryKind::File);
6839 tokio::fs::remove_file(tmp.join("src/entry")).await?;
6841 nix::unistd::mkfifo(
6842 &tmp.join("src/entry"),
6843 nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
6844 )?;
6845 match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
6846 Ok(()) => {
6847 let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
6848 assert!(
6849 lm.file_type().is_file(),
6850 "linked entry must be the pinned regular file, never the swapped-in FIFO"
6851 );
6852 assert!(
6853 !lm.file_type().is_fifo(),
6854 "the destination must never be a special (the by-name link would link the FIFO)"
6855 );
6856 let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
6857 assert_eq!(content, "REALFILE");
6858 }
6859 Err(_) => {
6860 assert!(
6862 !tmp.join("dst/linked").exists(),
6863 "no destination entry may exist when the link failed closed"
6864 );
6865 }
6866 }
6867 Ok(())
6868 }
6869
6870 #[tokio::test]
6873 async fn hard_link_handle_at_stable_file_happy_path() -> anyhow::Result<()> {
6874 let tmp = testutils::create_temp_dir().await?;
6875 tokio::fs::create_dir(tmp.join("src")).await?;
6876 tokio::fs::create_dir(tmp.join("dst")).await?;
6877 tokio::fs::write(tmp.join("src/f"), b"STABLE").await?;
6878 let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6879 let dst =
6880 Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6881 let handle = src.child(OsStr::new("f")).await?;
6882 dst.hard_link_handle_at(&handle, OsStr::new("f_link"))
6883 .await?;
6884 let orig = src.child(OsStr::new("f")).await?;
6885 let linked = dst.child(OsStr::new("f_link")).await?;
6886 assert_eq!(linked.kind(), EntryKind::File);
6887 assert_eq!(orig.ino(), linked.ino(), "hard link must share the inode");
6888 let content = tokio::fs::read_to_string(tmp.join("dst/f_link")).await?;
6889 assert_eq!(content, "STABLE");
6890 Ok(())
6891 }
6892
6893 #[tokio::test]
6896 async fn owned_file_metadata_follows_the_created_inode_after_name_replacement()
6897 -> anyhow::Result<()> {
6898 use std::io::Write as _;
6899 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
6900 let tmp = tempfile::tempdir()?;
6901 let source = tmp.path().join("source");
6902 std::fs::write(&source, b"source")?;
6903 std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o751))?;
6904 filetime::set_file_times(
6905 &source,
6906 filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789),
6907 filetime::FileTime::from_unix_time(1_000_000_500, 987_654_321),
6908 )?;
6909 let source_meta = std::fs::metadata(&source)?;
6910 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
6911 let path = tmp.path().join("destination");
6912 let saved = tmp.path().join("saved-destination");
6913 let mut file = root.create_file(OsStr::new("destination")).await?;
6914 file.write_all(b"copied payload")?;
6915 let created = file.metadata()?;
6916 let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6917 std::fs::rename(&path, &saved)?;
6918 std::fs::write(&path, b"replacement")?;
6919 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640))?;
6920 let replacement_before = std::fs::metadata(&path)?;
6921 set_file_metadata_owned(
6922 &crate::preserve::preserve_all(),
6923 &source_meta,
6924 None,
6925 file.into(),
6926 congestion::Side::Destination,
6927 )
6928 .await?;
6929 assert!(
6930 identity.original_is_closed()?,
6931 "metadata retained its consumed descriptor"
6932 );
6933 let applied = std::fs::metadata(&saved)?;
6934 assert_eq!(
6935 (applied.dev(), applied.ino()),
6936 (created.dev(), created.ino())
6937 );
6938 assert_eq!(applied.permissions().mode() & 0o7777, 0o751);
6939 assert_eq!(
6940 std::os::unix::fs::MetadataExt::uid(&applied),
6941 std::os::unix::fs::MetadataExt::uid(&source_meta)
6942 );
6943 assert_eq!(
6944 std::os::unix::fs::MetadataExt::gid(&applied),
6945 std::os::unix::fs::MetadataExt::gid(&source_meta)
6946 );
6947 assert_eq!(
6948 std::os::unix::fs::MetadataExt::atime(&applied),
6949 1_000_000_000
6950 );
6951 assert_eq!(
6952 std::os::unix::fs::MetadataExt::atime_nsec(&applied),
6953 123_456_789
6954 );
6955 assert_eq!(
6956 std::os::unix::fs::MetadataExt::mtime(&applied),
6957 1_000_000_500
6958 );
6959 assert_eq!(
6960 std::os::unix::fs::MetadataExt::mtime_nsec(&applied),
6961 987_654_321
6962 );
6963 let replacement_after = std::fs::metadata(&path)?;
6964 assert_eq!(
6965 (replacement_after.dev(), replacement_after.ino()),
6966 (replacement_before.dev(), replacement_before.ino())
6967 );
6968 assert_eq!(
6969 replacement_after.permissions().mode(),
6970 replacement_before.permissions().mode()
6971 );
6972 assert_eq!(
6973 std::os::unix::fs::MetadataExt::mtime(&replacement_after),
6974 std::os::unix::fs::MetadataExt::mtime(&replacement_before)
6975 );
6976 assert_eq!(
6977 std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_after),
6978 std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_before)
6979 );
6980 assert_eq!(std::fs::read(&saved)?, b"copied payload");
6981 assert_eq!(std::fs::read(&path)?, b"replacement");
6982 Ok(())
6983 }
6984
6985 async fn assert_cancelled_owned_operation_keeps_resources<Fut, T, O>(
6986 file: std::fs::File,
6987 path: &Path,
6988 resource: throttle::Resource,
6989 operation: impl FnOnce(std::fs::File) -> Fut + Send + 'static,
6990 observe_while_gated: impl FnOnce() -> O,
6991 ) -> anyhow::Result<O>
6992 where
6993 Fut: std::future::Future<Output = T> + Send + 'static,
6994 T: Send + 'static,
6995 {
6996 use futures::FutureExt as _;
6997 let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6998 let gate = testutils::BlockingPathGate::install(path);
6999 let limits = testutils::AdmissionLimit::new().await;
7000 limits.set_files_in_flight(1);
7001 limits.set_max_ops_in_flight(resource, 1);
7002 let guard = throttle::open_file_permit().await;
7003 let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
7004 let _guard = guard;
7005 operation(file).await
7006 }));
7007 let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
7008 let (observations, (acquired_operation, observed)) = testutils::cancel_at_blocking_path(
7009 limits,
7010 gate,
7011 task,
7012 std::time::Duration::from_secs(20),
7013 |_| {
7014 (
7015 next_operation.as_mut().now_or_never(),
7016 observe_while_gated(),
7017 )
7018 },
7019 )
7020 .await?;
7021 let operation_retained = acquired_operation.is_none();
7022 let permit = match acquired_operation {
7023 Some(permit) => permit,
7024 None => tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?,
7025 };
7026 drop(permit);
7027 assert!(observations.waiter_was_cancelled);
7028 assert!(observations.admission_was_retained_while_work_gated);
7029 assert!(observations.fd_was_open_while_work_gated);
7030 assert!(
7031 operation_retained,
7032 "started work released its operation permit after cancellation"
7033 );
7034 assert_eq!(observations.final_hit_count, 1);
7035 assert!(
7036 identity.original_is_closed()?,
7037 "started work returned capacity before closing its owned descriptor"
7038 );
7039 Ok(observed)
7040 }
7041
7042 #[tokio::test]
7043 async fn cancelled_owned_acl_read_retains_source_and_permits_until_started_work_finishes()
7044 -> anyhow::Result<()> {
7045 let tmp = tempfile::tempdir()?;
7046 let path = tmp.path().join("source");
7047 std::fs::write(&path, b"payload")?;
7048 let file = std::fs::File::open(&path)?;
7049 assert_cancelled_owned_operation_keeps_resources(
7050 file,
7051 &path,
7052 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat),
7053 |file| read_acls_owned(file, congestion::Side::Source, false),
7054 || (),
7055 )
7056 .await
7057 }
7058
7059 #[tokio::test]
7060 async fn cancelled_owned_metadata_waiting_for_admission_closes_the_file_without_widening()
7061 -> anyhow::Result<()> {
7062 use std::os::unix::fs::PermissionsExt as _;
7063 let tmp = tempfile::tempdir()?;
7064 let source = tmp.path().join("source");
7065 std::fs::write(&source, b"source")?;
7066 std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
7067 let source_meta = std::fs::metadata(&source)?;
7068 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
7069 let path = tmp.path().join("destination");
7070 let file = root.create_file(OsStr::new("destination")).await?;
7071 let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
7072 let limits = testutils::AdmissionLimit::new().await;
7073 limits.set_files_in_flight(1);
7074 let resource =
7075 throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
7076 limits.set_max_ops_in_flight(resource, 1);
7077 let occupied = throttle::ops_in_flight_permit(resource).await;
7078 let guard = throttle::open_file_permit().await;
7079 let admission = guard.admission();
7080 let mut work = Box::pin(with_fd_admission(admission, async move {
7081 let _guard = guard;
7082 set_file_metadata_owned(
7083 &crate::preserve::preserve_all(),
7084 &source_meta,
7085 None,
7086 file.into(),
7087 congestion::Side::Destination,
7088 )
7089 .await
7090 }));
7091 let waiting = futures::poll!(work.as_mut()).is_pending();
7092 let fd_retained = !identity.original_is_closed()?;
7093 let mut next_file = Box::pin(throttle::open_file_permit());
7094 assert!(
7095 futures::poll!(next_file.as_mut()).is_pending(),
7096 "waiting metadata released file admission"
7097 );
7098 drop(work);
7099 let closed = identity.original_is_closed()?;
7100 let file_permit =
7101 tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?;
7102 drop(file_permit);
7103 drop(occupied);
7104 assert!(
7105 waiting,
7106 "metadata did not wait for its occupied operation permit"
7107 );
7108 assert!(fd_retained);
7109 assert!(
7110 closed,
7111 "cancelled metadata admission retained its owned descriptor"
7112 );
7113 assert_eq!(
7114 std::fs::metadata(path)?.permissions().mode() & 0o7777,
7115 DST_FILE_CREATE_MODE
7116 );
7117 Ok(())
7118 }
7119
7120 #[tokio::test]
7121 async fn cancelled_owned_metadata_retains_the_file_and_permits_until_started_work_finishes()
7122 -> anyhow::Result<()> {
7123 use std::os::unix::fs::PermissionsExt as _;
7124 let tmp = tempfile::tempdir()?;
7125 let source = tmp.path().join("source");
7126 std::fs::write(&source, b"source")?;
7127 std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
7128 let source_meta = std::fs::metadata(&source)?;
7129 let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
7130 let path = tmp.path().join("destination");
7131 let file = root.create_file(OsStr::new("destination")).await?;
7132 let mode_while_gated = assert_cancelled_owned_operation_keeps_resources(
7133 file,
7134 &path,
7135 throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod),
7136 |file| async move {
7137 set_file_metadata_owned(
7138 &crate::preserve::preserve_all(),
7139 &source_meta,
7140 None,
7141 file.into(),
7142 congestion::Side::Destination,
7143 )
7144 .await
7145 },
7146 || std::fs::metadata(&path).map(|meta| meta.permissions().mode() & 0o7777),
7147 )
7148 .await?;
7149 assert_eq!(mode_while_gated?, DST_FILE_CREATE_MODE);
7150 assert_eq!(
7151 std::fs::metadata(path)?.permissions().mode() & 0o7777,
7152 DST_FILE_CREATE_MODE
7153 );
7154 Ok(())
7155 }
7156
7157 #[tokio::test]
7161 async fn set_file_metadata_owned_applies_owner_mode_time() -> anyhow::Result<()> {
7162 use std::io::Write;
7163 use std::os::unix::fs::PermissionsExt;
7164 let tmp = testutils::setup_test_dir().await?;
7165 let src_path = tmp.join("foo/src_meta.txt");
7167 tokio::fs::write(&src_path, b"source").await?;
7168 std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o741))?;
7169 let src_mtime = filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789);
7170 filetime::set_file_mtime(&src_path, src_mtime)?;
7171 filetime::set_file_atime(
7172 &src_path,
7173 filetime::FileTime::from_unix_time(1_000_000_500, 0),
7174 )?;
7175
7176 let root =
7177 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7178 let src_handle = root.child(OsStr::new("src_meta.txt")).await?;
7180 let src_meta = src_handle.meta().clone();
7181
7182 let mut dst_file = root.create_file(OsStr::new("dst_meta.txt")).await?;
7184 dst_file.write_all(b"destination")?;
7185 dst_file.flush()?;
7186
7187 let settings = crate::preserve::preserve_all();
7189 set_file_metadata_owned(
7190 &settings,
7191 &src_meta,
7192 None,
7193 dst_file.into(),
7194 congestion::Side::Destination,
7195 )
7196 .await?;
7197
7198 let dst_md = std::fs::metadata(tmp.join("foo/dst_meta.txt"))?;
7200 assert_eq!(
7201 dst_md.permissions().mode() & 0o7777,
7202 0o741,
7203 "destination mode mismatch"
7204 );
7205 use std::os::unix::fs::MetadataExt;
7207 assert_eq!(
7208 MetadataExt::mtime(&dst_md),
7209 1_000_000_000,
7210 "mtime seconds mismatch"
7211 );
7212 assert_eq!(
7213 MetadataExt::mtime_nsec(&dst_md),
7214 123_456_789,
7215 "mtime nanos mismatch"
7216 );
7217 assert_eq!(MetadataExt::uid(&dst_md), src_meta.uid(), "uid mismatch");
7219 assert_eq!(MetadataExt::gid(&dst_md), src_meta.gid(), "gid mismatch");
7220 Ok(())
7221 }
7222
7223 #[cfg_attr(
7227 rcp_nix_sandbox,
7228 ignore = "Nix sandbox cannot change ownership or set-id modes"
7229 )]
7230 #[tokio::test]
7231 async fn set_file_metadata_owned_ordering_preserves_setuid() -> anyhow::Result<()> {
7232 use std::io::Write;
7233 use std::os::unix::fs::PermissionsExt;
7234 let tmp = testutils::setup_test_dir().await?;
7235 let src_path = tmp.join("foo/setuid_src");
7237 tokio::fs::write(&src_path, b"x").await?;
7238 std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7239
7240 let root =
7241 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7242 let src_handle = root.child(OsStr::new("setuid_src")).await?;
7243 let src_meta = src_handle.meta().clone();
7244 assert_eq!(
7245 src_meta.permissions().mode() & 0o7777,
7246 0o4755,
7247 "source setuid bit was not set up correctly"
7248 );
7249
7250 let mut dst_file = root.create_file(OsStr::new("setuid_dst")).await?;
7252 dst_file.write_all(b"x")?;
7253 dst_file.flush()?;
7254
7255 let settings = crate::preserve::preserve_all();
7258 set_file_metadata_owned(
7259 &settings,
7260 &src_meta,
7261 None,
7262 dst_file.into(),
7263 congestion::Side::Destination,
7264 )
7265 .await?;
7266
7267 let dst_md = std::fs::metadata(tmp.join("foo/setuid_dst"))?;
7268 assert_eq!(
7269 dst_md.permissions().mode() & 0o7777,
7270 0o4755,
7271 "setuid bit was lost — chown must run before chmod"
7272 );
7273 Ok(())
7274 }
7275
7276 #[tokio::test]
7282 async fn set_file_metadata_owned_keeps_the_file_owner_only_when_utimens_fails()
7283 -> anyhow::Result<()> {
7284 use std::os::unix::fs::PermissionsExt;
7285
7286 struct RejectedTimestamps;
7287 impl crate::preserve::Metadata for RejectedTimestamps {
7288 fn uid(&self) -> u32 {
7289 unsafe { libc::getuid() }
7291 }
7292 fn gid(&self) -> u32 {
7293 unsafe { libc::getgid() }
7295 }
7296 fn atime(&self) -> i64 {
7297 0
7298 }
7299 fn atime_nsec(&self) -> i64 {
7300 0
7301 }
7302 fn mtime(&self) -> i64 {
7303 0
7304 }
7305 fn mtime_nsec(&self) -> i64 {
7308 2_000_000_000
7309 }
7310 fn permissions(&self) -> std::fs::Permissions {
7311 std::fs::Permissions::from_mode(0o4755)
7312 }
7313 }
7314
7315 let tmp = testutils::setup_test_dir().await?;
7316 let root =
7317 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7318 let dst_file = root.create_file(OsStr::new("late_chmod")).await?;
7319 let dst_path = tmp.join("foo/late_chmod");
7320 assert_eq!(
7321 std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
7322 DST_FILE_CREATE_MODE,
7323 "every destination file starts owner-only"
7324 );
7325
7326 let error = set_file_metadata_owned(
7329 &crate::preserve::preserve_all(),
7330 &RejectedTimestamps,
7331 None,
7332 dst_file.into(),
7333 congestion::Side::Destination,
7334 )
7335 .await
7336 .expect_err("an out-of-range nanosecond field must fail futimens");
7337 assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
7338
7339 assert_eq!(
7340 std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
7341 DST_FILE_CREATE_MODE,
7342 "a failure during metadata application must not leave the final mode behind"
7343 );
7344 Ok(())
7345 }
7346
7347 #[cfg_attr(
7350 rcp_nix_sandbox,
7351 ignore = "Nix sandbox cannot change ownership or set-id modes"
7352 )]
7353 #[tokio::test]
7354 async fn set_dir_metadata_fd_applies() -> anyhow::Result<()> {
7355 use std::os::unix::fs::{MetadataExt, PermissionsExt};
7356 let tmp = testutils::setup_test_dir().await?;
7357 let src_dir_path = tmp.join("foo/src_dir");
7359 tokio::fs::create_dir(&src_dir_path).await?;
7360 std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2750))?;
7361 filetime::set_file_mtime(
7362 &src_dir_path,
7363 filetime::FileTime::from_unix_time(1_111_111_111, 222_000_000),
7364 )?;
7365
7366 let root =
7367 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7368 let src_handle = root.child(OsStr::new("src_dir")).await?;
7369 let src_meta = src_handle.meta().clone();
7370
7371 let dst_dir = root.make_dir(OsStr::new("dst_dir"), 0o700).await?;
7373 let settings = crate::preserve::preserve_all();
7374 set_dir_metadata_fd(&settings, &src_meta, None, &dst_dir).await?;
7375
7376 let dst_md = std::fs::metadata(tmp.join("foo/dst_dir"))?;
7377 assert_eq!(
7378 dst_md.permissions().mode() & 0o7777,
7379 0o2750,
7380 "destination dir mode mismatch"
7381 );
7382 assert_eq!(
7383 MetadataExt::mtime(&dst_md),
7384 1_111_111_111,
7385 "dir mtime seconds mismatch"
7386 );
7387 assert_eq!(
7388 MetadataExt::mtime_nsec(&dst_md),
7389 222_000_000,
7390 "dir mtime nanos mismatch"
7391 );
7392 Ok(())
7393 }
7394
7395 #[tokio::test]
7399 async fn set_symlink_metadata_fd_changes_link_not_target() -> anyhow::Result<()> {
7400 use std::os::unix::fs::MetadataExt;
7401 let tmp = testutils::setup_test_dir().await?;
7402 let root =
7403 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7404
7405 let target_path = tmp.join("foo/sentinel_target.txt");
7407 tokio::fs::write(&target_path, b"keep my mtime").await?;
7408 let target_mtime = filetime::FileTime::from_unix_time(1_500_000_000, 0);
7409 filetime::set_file_mtime(&target_path, target_mtime)?;
7410 let target_before = std::fs::metadata(&target_path)?;
7411
7412 let link = root
7414 .symlink_at(
7415 OsStr::new("the_link"),
7416 std::path::Path::new("sentinel_target.txt"),
7417 )
7418 .await?;
7419
7420 let src_link_path = tmp.join("foo/src_link");
7423 tokio::fs::symlink("sentinel_target.txt", &src_link_path).await?;
7424 let src_link_mtime = filetime::FileTime::from_unix_time(1_234_567_890, 0);
7425 filetime::set_symlink_file_times(
7427 &src_link_path,
7428 filetime::FileTime::from_unix_time(1_234_500_000, 0),
7429 src_link_mtime,
7430 )?;
7431 let src_meta = root.child(OsStr::new("src_link")).await?.meta().clone();
7432
7433 let settings = crate::preserve::preserve_all();
7434 set_symlink_metadata_fd(&settings, &src_meta, &link, congestion::Side::Destination).await?;
7435
7436 let link_md = std::fs::symlink_metadata(tmp.join("foo/the_link"))?;
7438 assert_eq!(
7439 MetadataExt::mtime(&link_md),
7440 1_234_567_890,
7441 "link's own mtime was not applied"
7442 );
7443 let target_after = std::fs::metadata(&target_path)?;
7445 assert_eq!(
7446 MetadataExt::mtime(&target_after),
7447 MetadataExt::mtime(&target_before),
7448 "target mtime changed — utimensat followed the symlink!"
7449 );
7450 assert_eq!(
7451 MetadataExt::mtime_nsec(&target_after),
7452 MetadataExt::mtime_nsec(&target_before),
7453 "target mtime_nsec changed — utimensat followed the symlink!"
7454 );
7455 Ok(())
7456 }
7457
7458 #[tokio::test]
7460 async fn new_methods_reject_multi_component_names() -> anyhow::Result<()> {
7461 let tmp = testutils::setup_test_dir().await?;
7462 let root =
7463 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7464 let dst =
7466 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7467 for bad in ["a/b", "..", ".", ""] {
7468 let bad_os = OsStr::new(bad);
7469
7470 let err = root.unlink_at(bad_os).await.unwrap_err();
7471 assert_eq!(
7472 err.raw_os_error(),
7473 Some(libc::EINVAL),
7474 "unlink_at: expected EINVAL for {bad:?}, got {err:#}"
7475 );
7476
7477 let err = root.rmdir_at(bad_os).await.unwrap_err();
7478 assert_eq!(
7479 err.raw_os_error(),
7480 Some(libc::EINVAL),
7481 "rmdir_at: expected EINVAL for {bad:?}, got {err:#}"
7482 );
7483
7484 let err = root
7486 .symlink_at(bad_os, std::path::Path::new("irrelevant"))
7487 .await
7488 .unwrap_err();
7489 assert_eq!(
7490 err.raw_os_error(),
7491 Some(libc::EINVAL),
7492 "symlink_at(name): expected EINVAL for {bad:?}, got {err:#}"
7493 );
7494
7495 let err = root.read_link_at(bad_os).await.unwrap_err();
7496 assert_eq!(
7497 err.raw_os_error(),
7498 Some(libc::EINVAL),
7499 "read_link_at: expected EINVAL for {bad:?}, got {err:#}"
7500 );
7501
7502 let err = root
7504 .hard_link_at(bad_os, &dst, OsStr::new("good"))
7505 .await
7506 .unwrap_err();
7507 assert_eq!(
7508 err.raw_os_error(),
7509 Some(libc::EINVAL),
7510 "hard_link_at(name): expected EINVAL for {bad:?}, got {err:#}"
7511 );
7512
7513 let err = root
7514 .hard_link_at(OsStr::new("good"), &dst, bad_os)
7515 .await
7516 .unwrap_err();
7517 assert_eq!(
7518 err.raw_os_error(),
7519 Some(libc::EINVAL),
7520 "hard_link_at(dst_name): expected EINVAL for {bad:?}, got {err:#}"
7521 );
7522 }
7523 Ok(())
7524 }
7525
7526 #[tokio::test]
7532 async fn chmod_via_proc_fd_changes_mode_of_zero_mode_file() -> anyhow::Result<()> {
7533 use std::os::unix::fs::PermissionsExt;
7534 let tmp = testutils::setup_test_dir().await?;
7535 let root =
7536 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7537 let path = tmp.join("foo/locked.txt");
7539 tokio::fs::write(&path, b"locked").await?;
7540 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))?;
7541 let handle = root.child(OsStr::new("locked.txt")).await?;
7543 assert_eq!(handle.kind(), EntryKind::File, "fixture must be a file");
7544 chmod_via_proc_fd(&handle, congestion::Side::Destination, 0o640).await?;
7546 let md = std::fs::symlink_metadata(&path)?;
7548 assert_eq!(
7549 md.permissions().mode() & 0o7777,
7550 0o640,
7551 "chmod_via_proc_fd must change the mode of a 0000-mode file"
7552 );
7553 Ok(())
7554 }
7555
7556 #[tokio::test]
7563 async fn stat_meta_via_proc_fd_on_symlink_resolves_link_not_target() -> anyhow::Result<()> {
7564 use std::os::unix::fs::MetadataExt;
7565 let tmp = testutils::setup_test_dir().await?;
7566 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7567
7568 let target_path = tmp.join("foo/stat_target.txt");
7570 tokio::fs::write(&target_path, b"target body").await?;
7571 filetime::set_file_mtime(
7572 &target_path,
7573 filetime::FileTime::from_unix_time(1_700_000_000, 0),
7574 )?;
7575
7576 let link_path = tmp.join("foo/stat_link");
7578 tokio::fs::symlink("stat_target.txt", &link_path).await?;
7579 filetime::set_symlink_file_times(
7580 &link_path,
7581 filetime::FileTime::from_unix_time(1_600_000_000, 0),
7582 filetime::FileTime::from_unix_time(1_600_000_123, 0),
7583 )?;
7584
7585 let handle = root.child(OsStr::new("stat_link")).await?;
7587 assert_eq!(
7588 handle.kind(),
7589 EntryKind::Symlink,
7590 "fixture must classify as a symlink"
7591 );
7592
7593 let md = stat_meta_via_proc_fd(&handle, congestion::Side::Source).await?;
7594 assert!(
7596 md.file_type().is_symlink(),
7597 "stat_meta_via_proc_fd followed the symlink to its target (got a non-symlink)"
7598 );
7599 assert_eq!(
7600 MetadataExt::mtime(&md),
7601 1_600_000_123,
7602 "expected the LINK's own mtime; a target-following stat would return 1_700_000_000"
7603 );
7604 Ok(())
7605 }
7606
7607 #[test]
7615 fn openat2_probe_is_stable() {
7616 let first = openat2_available();
7620 assert_eq!(first, openat2_available(), "probe must be stable");
7621 if !first {
7622 eprintln!("this kernel lacks openat2(2); strict-mode tests skip themselves");
7623 }
7624 }
7625
7626 use crate::testutils::acl::*;
7629
7630 fn mode_of(path: &std::path::Path) -> u32 {
7631 use std::os::unix::fs::PermissionsExt as _;
7632 std::fs::metadata(path).unwrap().permissions().mode() & 0o7777
7633 }
7634
7635 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7636 #[tokio::test]
7637 async fn read_acls_owned_returns_the_same_source_descriptor_after_name_replacement()
7638 -> anyhow::Result<()> {
7639 use std::io::Read as _;
7640 let tmp = tempfile::tempdir()?;
7641 let path = tmp.path().join("source");
7642 std::fs::write(&path, b"original")?;
7643 let blob = restrictive_access_acl();
7644 set_xattr_at(&path, ACL_ACCESS_XATTR, &blob);
7645 let file = std::fs::File::open(&path)?;
7646 let raw_fd = file.as_raw_fd();
7647 std::fs::rename(&path, tmp.path().join("original"))?;
7648 std::fs::write(&path, b"replacement")?;
7649 set_xattr_at(&path, ACL_ACCESS_XATTR, &permissive_acl());
7650 let (mut file, acls) = read_acls_owned(file, congestion::Side::Source, false).await?;
7651 assert_eq!(file.as_raw_fd(), raw_fd);
7652 assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7653 assert_eq!(acls.default, None);
7654 let mut bytes = Vec::new();
7655 file.read_to_end(&mut bytes)?;
7656 assert_eq!(bytes, b"original");
7657 Ok(())
7658 }
7659
7660 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7661 #[tokio::test]
7662 async fn read_acls_fd_round_trips_an_access_acl() -> anyhow::Result<()> {
7663 let tmp = testutils::setup_test_dir().await?;
7664 let src_path = tmp.join("foo/acl_src");
7665 tokio::fs::write(&src_path, b"x").await?;
7666 let blob = restrictive_access_acl();
7667 set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7668 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7669 let (file, _) = root.open_file_read(OsStr::new("acl_src")).await?;
7670 let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7671 assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7673 assert_eq!(acls.default, None, "a file has no default ACL to read");
7674 Ok(())
7675 }
7676
7677 #[cfg_attr(
7684 rcp_nix_sandbox,
7685 ignore = "Nix sandbox cannot provide both POSIX ACL and user xattrs this test requires"
7686 )]
7687 #[tokio::test]
7688 async fn read_acls_fd_reads_an_acl_larger_than_the_stack_buffers() -> anyhow::Result<()> {
7689 let tmp = testutils::setup_test_dir().await?;
7690 let src_path = tmp.join("foo/big_acl");
7691 tokio::fs::write(&src_path, b"x").await?;
7692 let mut entries = vec![(ACL_USER_OBJ, 7, ACL_UNDEFINED_ID)];
7695 entries.extend((0..80).map(|i| (ACL_USER, 5, 100_000 + i)));
7696 entries.extend([
7697 (ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
7698 (ACL_MASK, 5, ACL_UNDEFINED_ID),
7699 (ACL_OTHER, 0, ACL_UNDEFINED_ID),
7700 ]);
7701 let blob = encode_acl(&entries);
7702 assert!(blob.len() > 512, "fixture must overflow the read buffer");
7703 set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7704 for i in 0..30 {
7706 let name = std::ffi::CString::new(format!("user.padding_attribute_number_{i:03}"))?;
7707 set_xattr_at(&src_path, &name, b"v");
7708 }
7709 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7710 let (file, _) = root.open_file_read(OsStr::new("big_acl")).await?;
7711 let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7712 assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7713 Ok(())
7714 }
7715
7716 #[tokio::test]
7717 async fn read_acls_fd_reports_no_acl_when_there_is_none() -> anyhow::Result<()> {
7718 let tmp = testutils::setup_test_dir().await?;
7719 let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7720 let (file, _) = root.open_file_read(OsStr::new("0.txt")).await?;
7721 let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7722 assert_eq!(acls, Acls::default(), "an entry with no xattrs has no ACL");
7723 Ok(())
7724 }
7725
7726 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7727 #[tokio::test]
7728 async fn read_acls_fd_reads_a_directorys_default_acl_only_when_asked() -> anyhow::Result<()> {
7729 let tmp = testutils::setup_test_dir().await?;
7730 let dir_path = tmp.join("foo/acl_dir");
7731 tokio::fs::create_dir(&dir_path).await?;
7732 let access = restrictive_access_acl();
7733 let default = permissive_acl();
7734 set_xattr_at(&dir_path, ACL_ACCESS_XATTR, &access);
7735 set_xattr_at(&dir_path, ACL_DEFAULT_XATTR, &default);
7736 let dir = Dir::open_root_dir(&dir_path, false, congestion::Side::Source).await?;
7737 let both = dir.read_acls().await?;
7738 assert_eq!(both.access.as_deref(), Some(access.as_slice()));
7739 assert_eq!(both.default.as_deref(), Some(default.as_slice()));
7740 let access_only = read_acls_fd(dir.fd.as_fd(), congestion::Side::Source, false).await?;
7742 assert_eq!(access_only.access.as_deref(), Some(access.as_slice()));
7743 assert_eq!(access_only.default, None);
7744 Ok(())
7745 }
7746
7747 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7748 #[tokio::test]
7749 async fn apply_acls_fd_installs_the_source_acl_and_clears_what_the_source_lacked()
7750 -> anyhow::Result<()> {
7751 let tmp = testutils::setup_test_dir().await?;
7752 let dst_path = tmp.join("foo/applied");
7753 tokio::fs::write(&dst_path, b"x").await?;
7754 let root =
7755 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7756 let (file, _) = root.open_file_read(OsStr::new("applied")).await?;
7757 let blob = restrictive_access_acl();
7758 apply_acls_fd(
7759 file.as_fd(),
7760 congestion::Side::Destination,
7761 &Acls {
7762 access: Some(blob.clone()),
7763 default: None,
7764 },
7765 false,
7766 )
7767 .await?;
7768 assert_eq!(
7769 get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7770 Some(blob.as_slice())
7771 );
7772 apply_acls_fd(
7774 file.as_fd(),
7775 congestion::Side::Destination,
7776 &Acls::default(),
7777 false,
7778 )
7779 .await?;
7780 assert_eq!(get_xattr_at(&dst_path, ACL_ACCESS_XATTR), None);
7781 apply_acls_fd(
7783 file.as_fd(),
7784 congestion::Side::Destination,
7785 &Acls::default(),
7786 false,
7787 )
7788 .await?;
7789 Ok(())
7790 }
7791
7792 #[tokio::test]
7793 async fn apply_acls_fd_fails_a_set_the_filesystem_cannot_hold_but_not_a_remove()
7794 -> anyhow::Result<()> {
7795 let probe = std::fs::File::open("/proc/self/environ")?;
7798 let error = apply_acls_fd(
7799 probe.as_fd(),
7800 congestion::Side::Destination,
7801 &Acls {
7802 access: Some(restrictive_access_acl()),
7803 default: None,
7804 },
7805 false,
7806 )
7807 .await
7808 .expect_err("a destination that cannot hold the source's ACL must fail the entry");
7809 assert_eq!(error.raw_os_error(), Some(libc::EOPNOTSUPP));
7810 apply_acls_fd(
7812 probe.as_fd(),
7813 congestion::Side::Destination,
7814 &Acls::default(),
7815 false,
7816 )
7817 .await
7818 .expect("clearing an ACL a filesystem cannot hold is already satisfied");
7819 Ok(())
7820 }
7821
7822 #[cfg_attr(
7825 rcp_nix_sandbox,
7826 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7827 )]
7828 #[tokio::test]
7829 async fn set_file_metadata_owned_applies_a_setuid_source_mode_and_its_acl() -> anyhow::Result<()>
7830 {
7831 use std::io::Write;
7832 use std::os::unix::fs::PermissionsExt;
7833 let tmp = testutils::setup_test_dir().await?;
7834 let src_path = tmp.join("foo/acl_setuid_src");
7835 tokio::fs::write(&src_path, b"x").await?;
7836 std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4700))?;
7837 let blob = restrictive_access_acl();
7838 set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7839 assert_eq!(mode_of(&src_path), 0o4755, "fixture source mode");
7842 let root =
7843 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7844 let src_handle = root.child(OsStr::new("acl_setuid_src")).await?;
7845 let src_meta = src_handle.meta().clone();
7846 let mut dst_file = root.create_file(OsStr::new("acl_setuid_dst")).await?;
7847 dst_file.write_all(b"x")?;
7848 dst_file.flush()?;
7849 set_file_metadata_owned(
7850 &crate::preserve::preserve_all_with_acls(),
7851 &src_meta,
7852 Some(&Acls {
7853 access: Some(blob.clone()),
7854 default: None,
7855 }),
7856 dst_file.into(),
7857 congestion::Side::Destination,
7858 )
7859 .await?;
7860 let dst_path = tmp.join("foo/acl_setuid_dst");
7861 assert_eq!(
7862 mode_of(&dst_path),
7863 mode_of(&src_path),
7864 "the special bits come from the chmod and the rwx bits from the ACL; both must land"
7865 );
7866 assert_eq!(mode_of(&dst_path), 0o4755);
7867 assert_eq!(
7868 get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7869 Some(blob.as_slice()),
7870 "the destination must not be more permissive than its source"
7871 );
7872 Ok(())
7873 }
7874
7875 #[cfg_attr(
7880 rcp_nix_sandbox,
7881 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7882 )]
7883 #[tokio::test]
7884 async fn set_file_metadata_owned_keeps_the_file_owner_only_when_the_acl_fails()
7885 -> anyhow::Result<()> {
7886 use std::os::unix::fs::PermissionsExt;
7887 let tmp = testutils::setup_test_dir().await?;
7888 let src_path = tmp.join("foo/acl_fail_src");
7889 tokio::fs::write(&src_path, b"x").await?;
7890 std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7891 let root =
7892 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7893 let src_meta = root.child(OsStr::new("acl_fail_src")).await?.meta().clone();
7894 let dst_file = root.create_file(OsStr::new("acl_fail_dst")).await?;
7895 let dst_path = tmp.join("foo/acl_fail_dst");
7896 let error = set_file_metadata_owned(
7897 &crate::preserve::preserve_all_with_acls(),
7898 &src_meta,
7899 Some(&Acls {
7900 access: Some(rejected_access_acl()),
7901 default: None,
7902 }),
7903 dst_file.into(),
7904 congestion::Side::Destination,
7905 )
7906 .await
7907 .expect_err("an ACL the kernel rejects must fail the entry");
7908 assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
7909 assert_eq!(
7910 mode_of(&dst_path),
7911 0o4000 | DST_FILE_CREATE_MODE,
7912 "the chmod preceding a source ACL must carry the special bits ALONE — a failed ACL \
7913 application left the file at a mode it had not earned"
7914 );
7915 Ok(())
7916 }
7917
7918 #[cfg_attr(
7922 rcp_nix_sandbox,
7923 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7924 )]
7925 #[tokio::test]
7926 async fn set_file_metadata_owned_clears_an_inherited_acl_and_still_applies_the_full_mode()
7927 -> anyhow::Result<()> {
7928 use std::io::Write;
7929 use std::os::unix::fs::PermissionsExt;
7930 let tmp = testutils::setup_test_dir().await?;
7931 let src_path = tmp.join("foo/plain_setuid_src");
7932 tokio::fs::write(&src_path, b"x").await?;
7933 std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7934 let root =
7935 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7936 let src_meta = root
7937 .child(OsStr::new("plain_setuid_src"))
7938 .await?
7939 .meta()
7940 .clone();
7941 let mut dst_file = root.create_file(OsStr::new("plain_setuid_dst")).await?;
7942 dst_file.write_all(b"x")?;
7943 dst_file.flush()?;
7944 let dst_path = tmp.join("foo/plain_setuid_dst");
7945 set_xattr_at(&dst_path, ACL_ACCESS_XATTR, &permissive_acl());
7947 set_file_metadata_owned(
7948 &crate::preserve::preserve_all_with_acls(),
7949 &src_meta,
7950 Some(&Acls::default()),
7951 dst_file.into(),
7952 congestion::Side::Destination,
7953 )
7954 .await?;
7955 assert_eq!(
7956 get_xattr_at(&dst_path, ACL_ACCESS_XATTR),
7957 None,
7958 "a source with no ACL must leave the destination with no ACL"
7959 );
7960 assert_eq!(
7961 mode_of(&dst_path),
7962 0o4755,
7963 "without a source ACL the chmod is the widening step and applies the FULL mode"
7964 );
7965 Ok(())
7966 }
7967
7968 #[cfg_attr(
7969 rcp_nix_sandbox,
7970 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7971 )]
7972 #[tokio::test]
7973 async fn set_dir_metadata_fd_installs_access_and_default_acls() -> anyhow::Result<()> {
7974 let tmp = testutils::setup_test_dir().await?;
7975 let root =
7976 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7977 let src_dir_path = tmp.join("foo/acl_src_dir");
7978 tokio::fs::create_dir(&src_dir_path).await?;
7979 let access = restrictive_access_acl();
7980 let default = permissive_acl();
7981 set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
7982 set_xattr_at(&src_dir_path, ACL_DEFAULT_XATTR, &default);
7983 let src_meta = root.child(OsStr::new("acl_src_dir")).await?.meta().clone();
7984 let dst_dir = root.make_dir(OsStr::new("acl_dst_dir"), 0o700).await?;
7985 let dst_path = tmp.join("foo/acl_dst_dir");
7986 set_dir_metadata_fd(
7987 &crate::preserve::preserve_all_with_acls(),
7988 &src_meta,
7989 Some(&Acls {
7990 access: Some(access.clone()),
7991 default: Some(default.clone()),
7992 }),
7993 &dst_dir,
7994 )
7995 .await?;
7996 assert_eq!(
7997 get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7998 Some(access.as_slice())
7999 );
8000 assert_eq!(
8001 get_xattr_at(&dst_path, ACL_DEFAULT_XATTR).as_deref(),
8002 Some(default.as_slice()),
8003 "the default ACL decides what CHILDREN inherit; dropping it changes the destination \
8004 tree's inheritance policy"
8005 );
8006 assert_eq!(mode_of(&dst_path), mode_of(&src_dir_path));
8007 assert_eq!(mode_of(&dst_path), 0o755);
8008 Ok(())
8009 }
8010
8011 #[cfg_attr(
8015 rcp_nix_sandbox,
8016 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
8017 )]
8018 #[tokio::test]
8019 async fn set_dir_metadata_fd_keeps_the_dir_owner_only_when_the_default_acl_fails()
8020 -> anyhow::Result<()> {
8021 use std::os::unix::fs::PermissionsExt;
8022 let tmp = testutils::setup_test_dir().await?;
8023 let root =
8024 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8025 let src_dir_path = tmp.join("foo/acl_dfail_src");
8026 tokio::fs::create_dir(&src_dir_path).await?;
8027 std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o755))?;
8028 let src_meta = root
8029 .child(OsStr::new("acl_dfail_src"))
8030 .await?
8031 .meta()
8032 .clone();
8033 let dst_dir = root.make_dir(OsStr::new("acl_dfail_dst"), 0o700).await?;
8034 let error = set_dir_metadata_fd(
8035 &crate::preserve::preserve_all_with_acls(),
8036 &src_meta,
8037 Some(&Acls {
8038 access: Some(permissive_acl()),
8039 default: Some(rejected_access_acl()),
8040 }),
8041 &dst_dir,
8042 )
8043 .await
8044 .expect_err("a default ACL the kernel rejects must fail the entry");
8045 assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
8046 assert_eq!(
8047 mode_of(&tmp.join("foo/acl_dfail_dst")),
8048 DST_DIR_CREATE_MODE,
8049 "the access ACL must be applied LAST: a failing default apply left the directory wider"
8050 );
8051 Ok(())
8052 }
8053
8054 #[cfg_attr(
8060 rcp_nix_sandbox,
8061 ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
8062 )]
8063 #[tokio::test]
8064 async fn set_reused_dir_metadata_fd_verifies_a_setgid_source_with_an_acl() -> anyhow::Result<()>
8065 {
8066 use std::os::unix::fs::PermissionsExt;
8067 let tmp = testutils::setup_test_dir().await?;
8068 let root =
8069 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8070 let src_dir_path = tmp.join("foo/setgid_acl_src");
8071 tokio::fs::create_dir(&src_dir_path).await?;
8072 std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2700))?;
8073 let access = restrictive_access_acl();
8074 set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
8075 let src_meta = root
8076 .child(OsStr::new("setgid_acl_src"))
8077 .await?
8078 .meta()
8079 .clone();
8080 assert_eq!(
8081 mode_of(&src_dir_path),
8082 0o2755,
8083 "fixture must keep setgid alongside the ACL (whose MASK set the group bits)"
8084 );
8085 let dst_dir = root.make_dir(OsStr::new("setgid_acl_dst"), 0o700).await?;
8086 let (uid, gid) = {
8087 let meta = dst_dir.meta().await?;
8088 use crate::preserve::Metadata as _;
8089 (meta.uid(), meta.gid())
8090 };
8091 set_reused_dir_metadata_fd(
8095 &crate::preserve::preserve_all_with_acls(),
8096 &src_meta,
8097 Some(&Acls {
8098 access: Some(access.clone()),
8099 default: None,
8100 }),
8101 Some(ReusedDirLock {
8102 restore_owner: (uid, gid),
8103 state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed {
8104 original: None,
8105 })),
8106 fd: Arc::clone(&dst_dir.fd),
8107 children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
8108 }),
8109 &dst_dir,
8110 )
8111 .await?;
8112 let dst_path = tmp.join("foo/setgid_acl_dst");
8113 assert_eq!(
8114 mode_of(&dst_path),
8115 0o2755,
8116 "setgid from the chmod, rwx from the ACL"
8117 );
8118 assert_eq!(
8119 get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
8120 Some(access.as_slice())
8121 );
8122 Ok(())
8123 }
8124
8125 #[tokio::test]
8126 async fn appliers_refuse_a_call_site_that_did_not_carry_acls() -> anyhow::Result<()> {
8127 let tmp = testutils::setup_test_dir().await?;
8128 let root =
8129 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8130 let src_meta = root.child(OsStr::new("0.txt")).await?.meta().clone();
8131 let dst_file = root.create_file(OsStr::new("no_acls_carried")).await?;
8132 let error = set_file_metadata_owned(
8135 &crate::preserve::preserve_all_with_acls(),
8136 &src_meta,
8137 None,
8138 dst_file.into(),
8139 congestion::Side::Destination,
8140 )
8141 .await
8142 .expect_err("requesting ACL preservation on a path that carries no ACLs must fail");
8143 assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
8144 let dst_file = root.create_file(OsStr::new("acls_not_requested")).await?;
8146 set_file_metadata_owned(
8147 &crate::preserve::preserve_all(),
8148 &src_meta,
8149 None,
8150 dst_file.into(),
8151 congestion::Side::Destination,
8152 )
8153 .await?;
8154 Ok(())
8155 }
8156
8157 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
8158 #[tokio::test]
8159 async fn guarded_default_acl_write_is_skipped_once_disarmed() -> anyhow::Result<()> {
8160 let tmp = testutils::setup_test_dir().await?;
8161 let root =
8162 Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8163 let dir = root.make_dir(OsStr::new("locked"), 0o700).await?;
8164 let lock = ReusedDirLock {
8168 restore_owner: (0, 0),
8169 state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Disarmed)),
8170 fd: Arc::clone(&dir.fd),
8171 children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
8172 };
8173 lock.write_default_acl_guarded(congestion::Side::Destination, restrictive_access_acl())
8174 .await?;
8175 assert_eq!(
8176 get_xattr_at(&tmp.join("foo/locked"), ACL_DEFAULT_XATTR),
8177 None,
8178 "a disarmed guard must refuse the write — landing it would undo the restore"
8179 );
8180 Ok(())
8181 }
8182}