1#![cfg_attr(
34 not(any(unix, windows)),
35 allow(
36 unused_variables,
37 dead_code,
38 reason = "with no strategy no tree is built, so the calls are compiled but never reached"
39 )
40)]
41
42use std::fs::Metadata;
43use std::io::Read;
44use std::path::{Path, PathBuf};
45
46use super::{Entry, EntryKind, FileId, Opened, Tree};
47use crate::error::TreeError;
48use crate::path::RelPath;
49
50mod capture;
51pub use capture::{CapturedDirectory, CapturedFile, CapturedLink};
52
53pub(super) fn canonical_root(root: &Path) -> std::io::Result<PathBuf> {
55 std::fs::canonicalize(root)
56}
57
58#[cfg(test)]
60type Hook = Box<dyn Fn() + Send + Sync>;
61
62macro_rules! hook {
64 ($tree:expr, $hook:ident) => {
65 #[cfg(test)]
66 if let Some(hook) = &$tree.$hook {
67 hook();
68 }
69 };
70}
71
72macro_rules! each {
74 ($handle:expr, $inner:ident => $body:expr) => {
75 match *$handle {
76 #[cfg(target_os = "linux")]
77 Handle::Linux(ref $inner) => $body,
78 #[cfg(all(unix, not(target_os = "linux")))]
79 Handle::OtherUnix(ref $inner) => $body,
80 #[cfg(windows)]
81 Handle::Windows(ref $inner) => $body,
82 }
83 };
84}
85
86#[cfg(windows)]
87mod final_path;
88#[cfg(windows)]
89mod handle_path;
90#[cfg(target_os = "linux")]
91mod linux;
92#[cfg(all(unix, not(target_os = "linux")))]
93mod other_unix;
94#[cfg(unix)]
95mod unix_root;
96#[cfg(all(test, any(unix, windows)))]
98mod tests;
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104enum Strategy {
105 #[cfg(target_os = "linux")]
107 Linux,
108 #[cfg(all(unix, not(target_os = "linux")))]
110 OtherUnix,
111 #[cfg(windows)]
114 Windows,
115}
116
117impl Strategy {
118 #[cfg(target_os = "linux")]
120 #[expect(
121 clippy::unnecessary_wraps,
122 reason = "the signature is shared with the platforms that have no strategy"
123 )]
124 fn native(_shown: &str) -> Result<Self, TreeError> {
125 Ok(Self::Linux)
126 }
127
128 #[cfg(all(unix, not(target_os = "linux")))]
130 #[expect(
131 clippy::unnecessary_wraps,
132 reason = "the signature is shared with the platforms that have no strategy"
133 )]
134 fn native(_shown: &str) -> Result<Self, TreeError> {
135 Ok(Self::OtherUnix)
136 }
137
138 #[cfg(windows)]
140 #[expect(
141 clippy::unnecessary_wraps,
142 reason = "the signature is shared with the platforms that have no strategy"
143 )]
144 fn native(_shown: &str) -> Result<Self, TreeError> {
145 Ok(Self::Windows)
146 }
147
148 #[cfg(not(any(unix, windows)))]
150 fn native(shown: &str) -> Result<Self, TreeError> {
151 Err(TreeError::Io {
152 path: shown.to_owned(),
153 source: std::io::Error::new(
154 std::io::ErrorKind::Unsupported,
155 "this platform cannot verify a handle against the root",
156 ),
157 })
158 }
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Want {
164 File,
166 Dir,
168 Listing,
170}
171
172impl Want {
173 fn require(self, metadata: &Metadata, shown: &str) -> Result<(), TreeError> {
175 let file_type = metadata.file_type();
176 let fits = match self {
177 Self::File => file_type.is_file(),
178 Self::Dir | Self::Listing => file_type.is_dir(),
179 };
180 if fits {
181 Ok(())
182 } else {
183 Err(not_regular(shown))
184 }
185 }
186}
187
188enum Handle {
190 #[cfg(target_os = "linux")]
191 Linux(linux::Handle),
192 #[cfg(all(unix, not(target_os = "linux")))]
193 OtherUnix(other_unix::Handle),
194 #[cfg(windows)]
195 Windows(handle_path::Handle),
196}
197
198impl Handle {
199 fn metadata(&self, shown: &str) -> Result<Metadata, TreeError> {
201 each!(self, inner => inner.metadata(shown))
202 }
203
204 fn link(
206 &self,
207 name: &str,
208 shown: &str,
209 between: impl FnOnce(),
210 ) -> Result<(FileId, PathBuf), TreeError> {
211 each!(self, inner => inner.link(name, shown, between))
212 }
213
214 fn identity(&self, root: &Path, shown: &str) -> Result<FileId, TreeError> {
216 each!(self, inner => inner.identity(root, shown))
217 }
218
219 fn read(&self, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
221 each!(self, inner => inner.read(max_bytes, shown))
222 }
223
224 fn entries(&self, shown: &str) -> Result<Vec<Entry>, TreeError> {
226 self.entries_bounded(shown, usize::MAX)
227 }
228
229 fn entries_bounded(&self, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
230 each!(self, inner => inner.entries(shown, max_entries))
231 }
232
233 fn lookup(&self, name: &str, shown: &str) -> Result<Option<EntryKind>, TreeError> {
235 each!(self, inner => inner.lookup(name, shown))
236 }
237
238 fn recheck(&self, tree: &DiskTree, shown: &str) -> Result<(), TreeError> {
240 match *self {
241 #[cfg(target_os = "linux")]
242 Handle::Linux(ref inner) => inner.recheck(tree, shown),
243 #[cfg(all(unix, not(target_os = "linux")))]
244 Handle::OtherUnix(ref inner) => inner.recheck(&tree.root_directory, shown),
245 #[cfg(windows)]
246 Handle::Windows(ref inner) => inner.recheck(&tree.root, shown),
247 }
248 }
249}
250
251#[cfg(all(test, unix))]
255fn never_blocks(flags: u32) -> bool {
256 #[cfg(target_os = "linux")]
257 let path = libc::O_PATH.cast_unsigned();
258 #[cfg(not(target_os = "linux"))]
259 let path = 0;
260 flags & (path | libc::O_NONBLOCK.cast_unsigned()) != 0
261}
262
263pub struct DiskTree {
270 root: PathBuf,
271 strategy: Strategy,
272 #[cfg(unix)]
274 root_directory: unix_root::Root,
275 #[cfg(test)]
277 before_open: Option<Hook>,
278 #[cfg(test)]
280 after_open: Option<Hook>,
281 #[cfg(test)]
283 after_verify: Option<Hook>,
284 #[cfg(test)]
286 after_observation: Option<Hook>,
287 #[cfg(all(test, unix, not(target_os = "linux")))]
290 mid_step: Option<Hook>,
291 #[cfg(all(test, unix))]
293 opens: std::sync::Mutex<Vec<u32>>,
294}
295
296impl std::fmt::Debug for DiskTree {
297 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298 f.debug_struct("DiskTree")
299 .field("root", &self.root)
300 .finish_non_exhaustive()
301 }
302}
303
304impl DiskTree {
305 pub(crate) fn root_path_bytes(&self) -> usize {
307 self.root.as_os_str().len()
308 }
309
310 fn directory_identity(&self, path: &RelPath) -> Result<FileId, TreeError> {
311 let shown = path.to_string();
312 let handle = self.open(path, Want::Dir, &shown)?;
313 self.used(&handle, &shown, |handle| {
314 handle.identity(&self.root, &shown)
315 })
316 }
317
318 pub(crate) fn dependency_directory_matches(
320 &self,
321 base_manifest: &RelPath,
322 relative: &str,
323 destination: &Self,
324 destination_manifest: &RelPath,
325 ) -> Result<bool, TreeError> {
326 super::require_first_party(base_manifest)?;
327 super::require_first_party(destination_manifest)?;
328 let missing_parent = |path: &RelPath| TreeError::NotRegular {
329 path: path.to_string(),
330 };
331 let base = base_manifest
332 .parent()
333 .ok_or_else(|| missing_parent(base_manifest))?;
334 let target = destination_manifest
335 .parent()
336 .ok_or_else(|| missing_parent(destination_manifest))?;
337 let before = self.directory_identity(&base)?;
338 let declared = self.directory_tree_at(&PathBuf::from(base.as_str()).join(relative))?;
339 let expected = declared.directory_identity(&RelPath::root())?;
340 let target_identity = destination.directory_identity(&target)?;
341 let actual = destination.directory_tree_at(Path::new(target.as_str()))?;
342 let same_directory = actual.directory_identity(&RelPath::root())? == target_identity
343 && expected == target_identity
344 && declared.root == actual.root;
345 if self.directory_identity(&base)? != before {
346 return Err(TreeError::from_io(
347 &base_manifest.to_string(),
348 std::io::Error::other("owning directory changed while checking a reference path"),
349 ));
350 }
351 Ok(same_directory)
352 }
353
354 pub fn new(root: impl AsRef<Path>) -> Result<Self, TreeError> {
365 let given = root.as_ref();
366 let shown = given.display().to_string();
367 let root = canonical_root(given).map_err(|e| TreeError::from_io(&shown, e))?;
368 let metadata = std::fs::metadata(&root).map_err(|e| TreeError::from_io(&shown, e))?;
369 Self::from_observed_root(root, &metadata, &shown)
370 }
371
372 fn from_observed_root(
373 root: PathBuf,
374 metadata: &Metadata,
375 shown: &str,
376 ) -> Result<Self, TreeError> {
377 if !metadata.is_dir() {
378 return Err(TreeError::NotRegular { path: shown.into() });
379 }
380 let strategy = Strategy::native(shown)?;
381 #[cfg(unix)]
382 let root_directory = unix_root::Root::open(&root, shown)?;
383 #[cfg(target_os = "linux")]
384 if root_directory.identity() != device_identity(metadata) {
385 return Err(outside(shown));
386 }
387 let tree = Self::from_parts(
388 root,
389 strategy,
390 #[cfg(unix)]
391 root_directory,
392 );
393 #[cfg(target_os = "linux")]
394 linux::verify_root(&tree, shown)?;
395 Ok(tree)
396 }
397
398 fn from_parts(
399 root: PathBuf,
400 strategy: Strategy,
401 #[cfg(unix)] root_directory: unix_root::Root,
402 ) -> Self {
403 Self {
404 root,
405 strategy,
406 #[cfg(unix)]
407 root_directory,
408 #[cfg(test)]
409 before_open: None,
410 #[cfg(test)]
411 after_open: None,
412 #[cfg(test)]
413 after_verify: None,
414 #[cfg(test)]
415 after_observation: None,
416 #[cfg(all(test, unix, not(target_os = "linux")))]
417 mid_step: None,
418 #[cfg(all(test, unix))]
419 opens: std::sync::Mutex::new(Vec::new()),
420 }
421 }
422
423 #[cfg(target_os = "linux")]
435 pub fn directory_handle(&self) -> Result<std::fs::File, TreeError> {
436 linux::verify_root(self, &self.root.display().to_string())?;
437 self.root_directory
438 .dir
439 .try_clone()
440 .map(std::fs::File::from)
441 .map_err(|e| TreeError::from_io(&self.root.display().to_string(), e))
442 }
443
444 fn directory_tree_at(&self, path: &Path) -> Result<Self, TreeError> {
445 #[cfg(target_os = "linux")]
446 {
447 let shown = path.display().to_string();
448 let relative = if path.as_os_str().is_empty() {
450 Path::new(".")
451 } else {
452 path
453 };
454 let root_directory =
455 unix_root::Root::open_at(&self.root_directory.dir, relative, &shown)?;
456 let root = std::fs::read_link(descriptor_path(&root_directory.dir))
457 .map_err(|e| link_read_error(&shown, e))?;
458 Ok(Self::from_parts(root, self.strategy, root_directory))
459 }
460 #[cfg(not(target_os = "linux"))]
461 Self::new(self.root.join(path))
462 }
463
464 pub(crate) fn byte_len(&self, path: &RelPath) -> Result<u64, TreeError> {
466 super::require_first_party(path)?;
467 let shown = path.to_string();
468 let handle = self.open(path, Want::File, &shown)?;
469 self.used(&handle, &shown, |handle| Ok(handle.metadata(&shown)?.len()))
470 }
471
472 pub fn read_unseen_bytes(
481 &self,
482 path: &RelPath,
483 max_bytes: u64,
484 seen: &dyn Fn(&FileId) -> bool,
485 ) -> Result<super::OpenedBytes, TreeError> {
486 super::require_first_party(path)?;
487 let shown = path.to_string();
488 let handle = self.open(path, Want::File, &shown)?;
489 let id = handle.identity(&self.root, &shown)?;
490 if seen(&id) {
491 return Ok(super::OpenedBytes::Seen(id));
492 }
493 let bytes = self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))?;
494 Ok(super::OpenedBytes::Read { id, bytes })
495 }
496
497 #[cfg(all(test, unix))]
502 fn note_open(&self, flags: u32) {
503 assert!(
504 never_blocks(flags),
505 "an open of a name below the root could block: flags {flags:#o}"
506 );
507 self.opens.lock().expect("the open record").push(flags);
508 }
509
510 #[cfg(all(test, unix))]
512 fn recorded_opens(&self) -> Vec<u32> {
513 self.opens.lock().expect("the open record").clone()
514 }
515
516 #[cfg(any(target_os = "linux", windows))]
518 fn candidate(&self, path: &RelPath) -> PathBuf {
519 #[cfg(target_os = "linux")]
520 let root = descriptor_path(&self.root_directory.dir).join(".");
521 #[cfg(windows)]
522 let root = self.root.clone();
523 if path.is_root() {
524 root
525 } else {
526 root.join(path.as_str())
527 }
528 }
529
530 #[cfg(any(target_os = "linux", windows))]
532 fn contain(&self, candidate: &Path, shown: &str) -> Result<PathBuf, TreeError> {
533 let canonical =
534 std::fs::canonicalize(candidate).map_err(|e| TreeError::from_io(shown, e))?;
535 if canonical.starts_with(&self.root) {
536 Ok(canonical)
537 } else {
538 Err(outside(shown))
539 }
540 }
541
542 fn open(&self, path: &RelPath, want: Want, shown: &str) -> Result<Handle, TreeError> {
544 refuse_windows_names(path, shown)?;
545 match self.strategy {
546 #[cfg(target_os = "linux")]
547 Strategy::Linux => linux::open(self, path, want, shown).map(Handle::Linux),
548 #[cfg(all(unix, not(target_os = "linux")))]
549 Strategy::OtherUnix => other_unix::open(self, path, want, shown).map(Handle::OtherUnix),
550 #[cfg(windows)]
551 Strategy::Windows => handle_path::open(self, path, want, shown).map(Handle::Windows),
552 }
553 }
554
555 fn used<T>(
558 &self,
559 handle: &Handle,
560 shown: &str,
561 work: impl FnOnce(&Handle) -> Result<T, TreeError>,
562 ) -> Result<T, TreeError> {
563 hook!(self, after_verify);
564 let result = work(handle);
565 handle.recheck(self, shown)?;
566 result
567 }
568
569 #[cfg(test)]
571 fn observed(&self) {
572 hook!(self, after_observation);
573 }
574}
575
576impl Tree for DiskTree {
577 fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
578 text(self.read_bytes(path, max_bytes)?, path)
579 }
580
581 fn read_bytes(&self, path: &RelPath, max_bytes: u64) -> Result<Vec<u8>, TreeError> {
585 super::require_first_party(path)?;
586 let shown = path.to_string();
587 let handle = self.open(path, Want::File, &shown)?;
588 self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))
589 }
590
591 fn read_unseen(
595 &self,
596 path: &RelPath,
597 max_bytes: u64,
598 seen: &dyn Fn(&FileId) -> bool,
599 ) -> Result<Opened, TreeError> {
600 match self.read_unseen_bytes(path, max_bytes, seen)? {
601 super::OpenedBytes::Seen(id) => Ok(Opened::Seen(id)),
602 super::OpenedBytes::Read { id, bytes } => Ok(Opened::Read {
603 id,
604 text: text(bytes, path)?,
605 }),
606 }
607 }
608
609 fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
610 super::require_first_party(path)?;
611 let shown = path.to_string();
612 let handle = self.open(path, Want::Listing, &shown)?;
613 let mut entries = self.used(&handle, &shown, |handle| handle.entries(&shown))?;
614 entries.sort();
615 Ok(entries)
616 }
617
618 fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
619 super::require_first_party(path)?;
620 let shown = path.to_string();
621 refuse_windows_names(path, &shown)?;
622 let (Some(name), Some(parent)) = (path.file_name(), path.parent()) else {
623 return Ok(Some(EntryKind::Dir));
624 };
625 let climbs = name == "..";
628 let directory = if climbs { path } else { &parent };
629 let handle = match self.open(directory, Want::Dir, &shown) {
630 Ok(handle) => handle,
631 Err(TreeError::NotFound { .. } | TreeError::NotRegular { .. }) => return Ok(None),
632 Err(other) => return Err(other),
633 };
634 self.used(&handle, &shown, |handle| {
635 if climbs {
636 Ok(Some(EntryKind::Dir))
637 } else {
638 handle.lookup(name, &shown)
639 }
640 })
641 }
642}
643
644#[cfg(any(target_os = "linux", windows))]
646fn kind_of(file_type: std::fs::FileType) -> EntryKind {
647 if file_type.is_symlink() {
648 EntryKind::Symlink
649 } else if file_type.is_dir() {
650 EntryKind::Dir
651 } else if file_type.is_file() {
652 EntryKind::File
653 } else {
654 EntryKind::Other
655 }
656}
657
658#[cfg(any(target_os = "linux", windows))]
660fn lookup(path: &Path, shown: &str) -> Result<Option<EntryKind>, TreeError> {
661 match std::fs::symlink_metadata(path) {
662 Ok(metadata) => Ok(Some(kind_of(metadata.file_type()))),
663 Err(e)
664 if matches!(
665 e.kind(),
666 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
667 ) =>
668 {
669 Ok(None)
670 }
671 Err(e) => Err(TreeError::from_io(shown, e)),
672 }
673}
674
675#[cfg(any(target_os = "linux", windows))]
677fn read_entries(listing: &Path, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
678 let mut entries = Vec::new();
679 for item in std::fs::read_dir(listing).map_err(|e| TreeError::from_io(shown, e))? {
680 let item = item.map_err(|e| TreeError::from_io(shown, e))?;
681 entry_room(entries.len(), max_entries, shown)?;
682 let name = item
683 .file_name()
684 .into_string()
685 .map_err(|raw| TreeError::NonUtf8Name {
686 path: shown.to_owned(),
687 name: raw.to_string_lossy().into_owned(),
688 })?;
689 let file_type = item.file_type().map_err(|e| TreeError::from_io(shown, e))?;
690 entries.push(Entry {
691 name,
692 kind: kind_of(file_type),
693 });
694 }
695 Ok(entries)
696}
697
698fn entry_room(count: usize, max_entries: usize, shown: &str) -> Result<(), TreeError> {
699 if count < max_entries {
700 Ok(())
701 } else {
702 Err(TreeError::from_io(
703 shown,
704 std::io::Error::new(
705 std::io::ErrorKind::InvalidData,
706 format!(
707 "directory entry limit {max_entries} exceeded; increase the admitted capture budget"
708 ),
709 ),
710 ))
711 }
712}
713
714#[cfg(any(target_os = "linux", windows))]
717fn refuse_unless_directory(candidate: &Path, shown: &str) -> Result<(), TreeError> {
718 let own = std::fs::symlink_metadata(candidate).map_err(|e| TreeError::from_io(shown, e))?;
719 if own.is_dir() {
720 Ok(())
721 } else {
722 Err(not_regular(shown))
723 }
724}
725
726#[cfg(any(target_os = "linux", windows))]
729fn open_error(shown: &str, error: std::io::Error) -> TreeError {
730 if crate::error::is_symlink_loop(&error) {
731 not_regular(shown)
732 } else {
733 TreeError::from_io(shown, error)
734 }
735}
736
737#[cfg(any(target_os = "linux", windows))]
740fn link_read_error(shown: &str, source: std::io::Error) -> TreeError {
741 TreeError::Io {
742 path: shown.to_owned(),
743 source,
744 }
745}
746
747#[cfg(any(target_os = "linux", windows))]
749fn verify_handle_path(root: &Path, handle_path: &Path, shown: &str) -> Result<(), TreeError> {
750 if handle_path.starts_with(root) {
751 Ok(())
752 } else {
753 Err(outside(shown))
754 }
755}
756
757#[cfg(target_os = "linux")]
762fn verify_linux_link(root: &Path, handle_link: &Path, shown: &str) -> Result<(), TreeError> {
763 let target = std::fs::read_link(handle_link).map_err(|e| link_read_error(shown, e))?;
764 verify_handle_path(root, &target, shown)
765}
766
767#[cfg(target_os = "linux")]
769fn descriptor_path(handle: &impl std::os::fd::AsRawFd) -> PathBuf {
770 PathBuf::from(format!("/proc/self/fd/{}", handle.as_raw_fd()))
771}
772
773fn read_capped(source: impl Read, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
775 let mut bytes = Vec::new();
776 source
777 .take(max_bytes.saturating_add(1))
778 .read_to_end(&mut bytes)
779 .map_err(|e| TreeError::from_io(shown, e))?;
780 if u64::try_from(bytes.len()).map_or(true, |len| len > max_bytes) {
781 return Err(TreeError::TooLarge {
782 path: shown.to_owned(),
783 limit: max_bytes,
784 });
785 }
786 Ok(bytes)
787}
788
789fn text(bytes: Vec<u8>, path: &RelPath) -> Result<String, TreeError> {
790 String::from_utf8(bytes).map_err(|_| TreeError::NotUtf8 {
791 path: path.to_string(),
792 })
793}
794
795fn outside(shown: &str) -> TreeError {
796 TreeError::OutsideRoot {
797 path: shown.to_owned(),
798 }
799}
800
801fn not_regular(shown: &str) -> TreeError {
802 TreeError::NotRegular {
803 path: shown.to_owned(),
804 }
805}
806
807#[cfg(unix)]
809fn device_identity(metadata: &Metadata) -> FileId {
810 use std::os::unix::fs::MetadataExt as _;
811 FileId::from_device(metadata.dev(), metadata.ino())
812}
813
814#[cfg(windows)]
817fn refuse_windows_names(path: &RelPath, shown: &str) -> Result<(), TreeError> {
818 if path.segments().any(is_ambiguous_on_windows) {
819 Err(outside(shown))
820 } else {
821 Ok(())
822 }
823}
824
825#[cfg(not(windows))]
827#[expect(
828 clippy::unnecessary_wraps,
829 reason = "the signature is shared with Windows, where the call can refuse"
830)]
831fn refuse_windows_names(_path: &RelPath, _shown: &str) -> Result<(), TreeError> {
832 Ok(())
833}
834
835#[cfg(windows)]
840fn is_ambiguous_on_windows(segment: &str) -> bool {
841 if segment == ".." {
842 return false;
843 }
844 if segment.ends_with(['.', ' ']) || segment.contains(':') {
845 return true;
846 }
847 let stem = segment
848 .split('.')
849 .next()
850 .unwrap_or(segment)
851 .trim_end_matches(' ')
852 .to_ascii_uppercase();
853 let numbered = |prefix: &str| {
854 stem.strip_prefix(prefix).is_some_and(|digit| {
855 matches!(
856 digit,
857 "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
858 )
859 })
860 };
861 matches!(
862 stem.as_str(),
863 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
864 ) || numbered("COM")
865 || numbered("LPT")
866}