1use crate::path::{Path, PathBuf, PathExt};
2use std::cell::Cell;
3use std::collections::{BTreeSet, HashMap, HashSet};
4use std::fmt::Display;
5use std::fs;
6use std::fs::File;
7use std::io::{BufReader, Read, Write};
8#[cfg(unix)]
9use std::os::unix::fs::symlink;
10#[cfg(unix)]
11use std::os::unix::prelude::*;
12use std::rc::Rc;
13use std::sync::Mutex;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::time::{Duration, SystemTime};
16
17use bzip2::read::BzDecoder;
18use eyre::bail;
19use eyre::{Context, Result};
20use flate2::read::GzDecoder;
21use itertools::Itertools;
22use jdx_tar::{Archive, EntryType, UnpackOptions};
23use path_absolutize::Absolutize;
24use sha2::{Digest, Sha256};
25use std::sync::LazyLock as Lazy;
26use walkdir::WalkDir;
27use zip::ZipArchive;
28
29use crate::progress::SingleReport;
30use crate::{dirs, env};
31use mise_settings::Settings;
32
33pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
34 let path = path.as_ref();
35 trace!("open {}", display_path(path));
36 File::open(path).wrap_err_with(|| format!("failed open: {}", display_path(path)))
37}
38
39pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
40 let path = path.as_ref();
41 trace!("cat {}", display_path(path));
42 fs::read(path).wrap_err_with(|| format!("failed read: {}", display_path(path)))
43}
44
45pub fn size<P: AsRef<Path>>(path: P) -> Result<u64> {
46 let path = path.as_ref();
47 trace!("du -b {}", display_path(path));
48 path.metadata()
49 .map(|m| m.len())
50 .wrap_err_with(|| format!("failed size: {}", display_path(path)))
51}
52
53pub fn append<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
54 let path = path.as_ref();
55 trace!("append {}", display_path(path));
56 fs::OpenOptions::new()
57 .append(true)
58 .create(true)
59 .open(path)
60 .and_then(|mut f| f.write_all(contents.as_ref()))
61 .wrap_err_with(|| format!("failed append: {}", display_path(path)))
62}
63
64#[cfg(windows)]
73pub const MAX_PATH: usize = 260;
74
75#[cfg(windows)]
87fn windows_io_hint(path: &Path, err: &std::io::Error) -> Option<String> {
88 use std::os::windows::ffi::OsStrExt;
89
90 let in_use = err.kind() == std::io::ErrorKind::PermissionDenied
94 || matches!(err.raw_os_error(), Some(5) | Some(32));
95 if in_use {
96 return Some(
97 "A file under it is in use. A program started from this directory — the tool itself, \
98 an editor, or a shell sitting in it — is probably still running."
99 .to_string(),
100 );
101 }
102 if !matches!(err.raw_os_error(), Some(3) | Some(123) | Some(206)) {
111 return None;
112 }
113 let units = path.as_os_str().encode_wide().count();
116 if units < MAX_PATH - 16 {
117 return None;
118 }
119 Some(format!(
123 "The path is {units} characters, at or near Windows' {MAX_PATH}-character limit, which \
124 may be the real cause rather than a missing directory. mise writes through a temporary \
125 file whose name is longer than the final one, so it crosses the limit first. Try a \
126 shorter directory."
127 ))
128}
129
130#[cfg(not(windows))]
131fn windows_io_hint(_path: &Path, _err: &std::io::Error) -> Option<String> {
132 None
133}
134
135pub fn with_io_hint(msg: String, path: &Path, err: &std::io::Error) -> String {
142 match windows_io_hint(path, err) {
143 Some(hint) => format!("{msg}\n{hint}"),
144 None => msg,
145 }
146}
147
148pub fn remove_all<P: AsRef<Path>>(path: P) -> Result<()> {
149 let path = path.as_ref();
150 match fs::symlink_metadata(path).map(|m| m.file_type()) {
156 Ok(x) if x.is_symlink() => {
161 remove_symlink_or_junction(path)?;
162 }
163 Ok(x) if x.is_file() => {
164 remove_file(path)?;
165 }
166 Ok(x) if x.is_dir() => {
167 trace!("rm -rf {}", display_path(path));
168 remove_dir_all_restoring_owner_access(path).map_err(|e| {
171 let msg = with_io_hint(
172 format!("failed to remove: {}", display_path(path)),
175 path,
176 &e,
177 );
178 eyre::eyre!(e).wrap_err(msg)
179 })?;
180 }
181 _ => {}
182 };
183 Ok(())
184}
185
186fn remove_dir_all_restoring_owner_access(path: &Path) -> std::io::Result<()> {
191 let result = fs::remove_dir_all(path);
192 #[cfg(unix)]
193 if let Err(err) = &result
194 && err.kind() == std::io::ErrorKind::PermissionDenied
195 && restore_owner_access(path).is_ok()
196 {
197 return fs::remove_dir_all(path);
198 }
199 result
200}
201
202#[cfg(unix)]
203fn restore_owner_access(path: &Path) -> Result<()> {
204 let parent = match path.parent() {
205 Some(parent) if !parent.as_os_str().is_empty() => parent,
206 _ => Path::new("."),
207 };
208 let Some(name) = path.file_name() else {
209 bail!("no directory name in {}", display_path(path));
210 };
211 restore_owner_access_at(File::open(parent)?, name)
212}
213
214#[cfg(unix)]
220fn restore_owner_access_at<Fd: std::os::fd::AsFd>(
221 parent: Fd,
222 name: &std::ffi::OsStr,
223) -> Result<()> {
224 let fd = nix::fcntl::openat(
225 &parent,
226 name,
227 nix::fcntl::OFlag::O_RDONLY
228 | nix::fcntl::OFlag::O_DIRECTORY
229 | nix::fcntl::OFlag::O_NOFOLLOW
230 | nix::fcntl::OFlag::O_CLOEXEC,
231 nix::sys::stat::Mode::empty(),
232 )?;
233 let mode = nix::sys::stat::fstat(&fd)?.st_mode;
234 if mode & 0o700 != 0o700 {
235 nix::sys::stat::fchmod(&fd, nix::sys::stat::Mode::from_bits_truncate(mode | 0o700))?;
236 }
237 let mut directory = nix::dir::Dir::from_fd(fd)?;
238 let entries = directory
239 .iter()
240 .map(|entry| entry.map(|entry| entry.file_name().to_owned()))
241 .collect::<std::result::Result<Vec<_>, _>>()?;
242 for entry in entries {
243 let entry = std::ffi::OsStr::from_bytes(entry.to_bytes());
244 if entry == "." || entry == ".." {
245 continue;
246 }
247 let stat =
248 nix::sys::stat::fstatat(&directory, entry, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW)?;
249 let kind = nix::sys::stat::SFlag::from_bits_truncate(stat.st_mode & nix::libc::S_IFMT);
250 if kind == nix::sys::stat::SFlag::S_IFDIR {
251 restore_owner_access_at(&directory, entry)?;
252 }
253 }
254 Ok(())
255}
256
257#[cfg(unix)]
265pub fn remove_all_at<Fd: std::os::fd::AsFd>(parent: Fd, name: &std::ffi::OsStr) -> Result<()> {
266 let stat =
267 match nix::sys::stat::fstatat(&parent, name, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
268 Ok(stat) => stat,
269 Err(nix::errno::Errno::ENOENT) => return Ok(()),
270 Err(err) => return Err(err.into()),
271 };
272 let kind = nix::sys::stat::SFlag::from_bits_truncate(stat.st_mode & nix::libc::S_IFMT);
275 if kind == nix::sys::stat::SFlag::S_IFDIR {
276 let fd = nix::fcntl::openat(
277 &parent,
278 name,
279 nix::fcntl::OFlag::O_RDONLY
280 | nix::fcntl::OFlag::O_DIRECTORY
281 | nix::fcntl::OFlag::O_NOFOLLOW
282 | nix::fcntl::OFlag::O_CLOEXEC,
283 nix::sys::stat::Mode::empty(),
284 )?;
285 let mut directory = nix::dir::Dir::from_fd(fd)?;
286 let entries = directory
287 .iter()
288 .map(|entry| entry.map(|entry| entry.file_name().to_owned()))
289 .collect::<std::result::Result<Vec<_>, _>>()?;
290 for entry in entries {
291 if entry.as_bytes() != b"." && entry.as_bytes() != b".." {
292 remove_all_at(&directory, std::ffi::OsStr::from_bytes(entry.to_bytes()))?;
293 }
294 }
295 nix::unistd::unlinkat(parent, name, nix::unistd::UnlinkatFlags::RemoveDir)?;
296 } else {
297 nix::unistd::unlinkat(parent, name, nix::unistd::UnlinkatFlags::NoRemoveDir)?;
298 }
299 Ok(())
300}
301
302pub fn remove_all_with_retry<P: AsRef<Path>>(path: P) -> Result<()> {
308 let path = path.as_ref();
309 retry_remove_all(|| remove_all(path))
310}
311
312fn retry_remove_all(mut remove: impl FnMut() -> Result<()>) -> Result<()> {
313 const MAX_RETRIES: u32 = 4;
314
315 for retry in 0..MAX_RETRIES {
316 match remove() {
317 Ok(()) => return Ok(()),
318 Err(err)
319 if err
320 .downcast_ref::<std::io::Error>()
321 .is_some_and(|err| err.kind() == std::io::ErrorKind::DirectoryNotEmpty) =>
322 {
323 std::thread::sleep(Duration::from_millis(10 * (1 << retry)));
324 }
325 Err(err) => return Err(err),
326 }
327 }
328 remove()
329}
330
331#[cfg(unix)]
337pub fn remove_file_or_dir<P: AsRef<Path>>(path: P) -> Result<()> {
338 let path = path.as_ref();
339 match path.metadata().map(|m| m.file_type()) {
340 Ok(x) if x.is_dir() => {
341 remove_dir(path)?;
342 }
343 _ => {
344 remove_file(path)?;
345 }
346 };
347 Ok(())
348}
349
350pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
351 let path = path.as_ref();
352 trace!("rm {}", display_path(path));
353 fs::remove_file(path).wrap_err_with(|| format!("failed rm: {}", display_path(path)))
354}
355
356pub async fn remove_file_async_if_exists<P: AsRef<Path>>(path: P) -> Result<()> {
357 let path = path.as_ref();
358 trace!("rm {}", display_path(path));
359 match tokio::fs::remove_file(path).await {
360 Ok(()) => Ok(()),
361 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
362 Err(e) => Err(e).wrap_err_with(|| format!("failed rm: {}", display_path(path))),
363 }
364}
365
366pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
367 let path = path.as_ref();
368 (|| -> Result<()> {
369 if path.exists() && is_empty_dir(path)? {
370 trace!("rmdir {}", display_path(path));
371 fs::remove_dir(path)?;
372 }
373 Ok(())
374 })()
375 .wrap_err_with(|| format!("failed to remove_dir: {}", display_path(path)))
376}
377
378pub fn remove_dir_ignore<P: AsRef<Path>>(path: P, is_empty_ignore_files: Vec<&str>) -> Result<()> {
379 let path = path.as_ref();
380 (|| -> Result<()> {
381 if path.exists() && is_empty_dir_ignore(path, is_empty_ignore_files)? {
382 trace!("rm -rf {}", display_path(path));
383 remove_all_with_warning(path)?;
384 }
385 Ok(())
386 })()
387 .wrap_err_with(|| format!("failed to remove_dir: {}", display_path(path)))
388}
389
390pub fn remove_all_with_warning<P: AsRef<Path>>(path: P) -> Result<()> {
391 remove_all(&path).map_err(|e| {
392 warn!("failed to remove {}: {}", path.as_ref().display(), e);
393 e
394 })
395}
396
397pub fn entry_exists<P: AsRef<Path>>(path: P) -> bool {
403 fs::symlink_metadata(path.as_ref()).is_ok()
404}
405
406pub fn remove_all_with_progress<P: AsRef<Path>>(path: P, pr: &dyn SingleReport) -> Result<()> {
407 let path = path.as_ref();
408 if !entry_exists(path) {
411 return Ok(());
412 }
413 pr.set_message(format!("remove {}", display_path(path)));
414 remove_all_with_warning(path)
415}
416
417pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
427 let from = from.as_ref();
428 let to = to.as_ref();
429 try_rename(from, to).wrap_err_with(|| {
430 format!(
431 "failed rename: {} -> {}",
432 display_path(from),
433 display_path(to)
434 )
435 })
436}
437
438pub fn try_rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> std::io::Result<()> {
439 let from = from.as_ref();
440 let to = to.as_ref();
441 trace!("mv {} {}", from.display(), to.display());
442 do_rename(from, to)
443}
444
445#[cfg(windows)]
446fn do_rename(from: &Path, to: &Path) -> std::io::Result<()> {
447 const MAX_ATTEMPTS: u32 = 20;
450 const MAX_DELAY_MS: u64 = 5000;
451 let mut last_err = None;
452 for attempt in 0..MAX_ATTEMPTS {
453 match fs::rename(from, to) {
454 Ok(()) => return Ok(()),
455 Err(e) if matches!(e.raw_os_error(), Some(5) | Some(32)) => {
456 last_err = Some(e);
460 if attempt + 1 < MAX_ATTEMPTS {
461 let delay = (50u64 << attempt).min(MAX_DELAY_MS);
462 std::thread::sleep(std::time::Duration::from_millis(delay));
463 }
464 }
465 Err(e) => return Err(e),
466 }
467 }
468 Err(last_err.unwrap())
469}
470
471#[cfg(not(windows))]
472fn do_rename(from: &Path, to: &Path) -> std::io::Result<()> {
473 fs::rename(from, to)
474}
475
476pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
483 let from = from.as_ref();
484 let to = to.as_ref();
485
486 match try_rename(from, to) {
487 Ok(()) => Ok(()),
488 Err(err) if err.kind() == std::io::ErrorKind::CrossesDevices => {
489 if from.is_dir() {
490 create_dir_all(to)?;
491 copy_dir_all_preserve_symlinks(from, to)?;
492 remove_all(from)?;
493 } else {
494 copy(from, to)?;
495 remove_file(from)?;
496 }
497 Ok(())
498 }
499 Err(err) => Err(err).wrap_err_with(|| {
500 format!(
501 "failed move: {} -> {}",
502 display_path(from),
503 display_path(to)
504 )
505 }),
506 }
507}
508
509pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
510 let from = from.as_ref();
511 let to = to.as_ref();
512 trace!("cp {} {}", from.display(), to.display());
513 fs::copy(from, to)
514 .wrap_err_with(|| {
515 format!(
516 "failed copy: {} -> {}",
517 display_path(from),
518 display_path(to)
519 )
520 })
521 .map(|_| ())
522}
523
524pub fn hard_link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
530 let from = from.as_ref();
531 let to = to.as_ref();
532 match fs::hard_link(from, to) {
533 Ok(()) => {
534 trace!("ln {} {}", from.display(), to.display());
535 Ok(())
536 }
537 Err(err) => {
538 trace!(
539 "ln {} {} failed ({err}), copying instead",
540 from.display(),
541 to.display()
542 );
543 copy(from, to)
544 }
545 }
546}
547
548pub fn copy_dir_all_preserve_symlinks(from: &Path, to: &Path) -> Result<()> {
549 copy_dir_all_preserve_symlinks_skipping(from, to, &[])
550}
551
552fn copy_dir_all_preserve_symlinks_skipping(
555 from: &Path,
556 to: &Path,
557 skip_top_level: &[&str],
558) -> Result<()> {
559 trace!("cp -a {} {}", from.display(), to.display());
560 let permissions = fs::metadata(from)?.permissions();
561 create_dir_all(to)?;
562 let mut directory_permissions = vec![(to.to_path_buf(), permissions)];
563 let entries = WalkDir::new(from)
564 .follow_links(false)
565 .min_depth(1)
566 .into_iter()
567 .filter_entry(|entry| {
568 entry.depth() != 1
569 || !entry
570 .file_name()
571 .to_str()
572 .is_some_and(|name| skip_top_level.contains(&name))
573 });
574 for entry in entries {
575 let entry = entry?;
576 let relative = entry.path().strip_prefix(from)?;
577 let dest = to.join(relative);
578 if entry.file_type().is_dir() {
579 create_dir_all(&dest)?;
580 directory_permissions.push((dest, entry.metadata()?.permissions()));
581 } else if entry.file_type().is_symlink() {
582 create_dir_all(dest.parent().unwrap())?;
583 make_symlink(&fs::read_link(entry.path())?, &dest)?;
584 } else if entry.file_type().is_file() {
585 create_dir_all(dest.parent().unwrap())?;
586 copy(entry.path(), &dest)?;
587 }
588 }
589 for (path, permissions) in directory_permissions.into_iter().rev() {
592 fs::set_permissions(path, permissions)?;
593 }
594 Ok(())
595}
596
597pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
598 let path = path.as_ref();
599 trace!("write {}", display_path(path));
600 fs::write(path, contents).wrap_err_with(|| format!("failed write: {}", display_path(path)))
601}
602
603pub struct PreparedAtomicWrite {
604 temporary: tempfile::NamedTempFile,
605 target: PathBuf,
606 parent: PathBuf,
607}
608
609impl PreparedAtomicWrite {
610 pub fn commit(self) -> Result<()> {
612 persist_atomic(self.temporary, &self.target).map_err(|e| {
617 let msg = format!("failed atomic write: {}", display_path(&self.target));
618 let msg = match e.downcast_ref::<std::io::Error>() {
621 Some(io) => with_io_hint(msg, &self.target, io),
622 None => msg,
623 };
624 e.wrap_err(msg)
625 })?;
626 sync_dir(&self.parent)?;
627 Ok(())
628 }
629}
630
631pub fn prepare_atomic_write<P: AsRef<Path>, C: AsRef<[u8]>>(
636 path: P,
637 contents: C,
638) -> Result<PreparedAtomicWrite> {
639 let path = path.as_ref();
640 trace!("prepare_atomic_write {}", display_path(path));
641 let mut prepared = prepare_replacement(path, contents)?;
642 prepared.temporary.as_file_mut().sync_all()?;
643 Ok(prepared)
644}
645
646pub fn write_atomic_unsynced<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
651 let path = path.as_ref();
652 trace!("write_atomic_unsynced {}", display_path(path));
653 let prepared = prepare_replacement(path, contents)?;
654 persist_atomic(prepared.temporary, &prepared.target)
655 .wrap_err_with(|| format!("failed atomic write: {}", display_path(&prepared.target)))
656}
657
658#[cfg(any(target_os = "linux", target_os = "android"))]
662pub fn sync_filesystem<P: AsRef<Path>>(path: P) -> Result<()> {
663 let path = path.as_ref();
664 trace!("sync filesystem of {}", display_path(path));
665 let dir = File::open(path)
666 .wrap_err_with(|| format!("failed to open dir for sync: {}", display_path(path)))?;
667 nix::unistd::syncfs(&dir)
668 .wrap_err_with(|| format!("failed to sync filesystem of {}", display_path(path)))
669}
670
671fn prepare_replacement<C: AsRef<[u8]>>(path: &Path, contents: C) -> Result<PreparedAtomicWrite> {
672 let target = atomic_write_target(path)?;
673 let path = target.as_path();
674 let parent = path
675 .parent()
676 .ok_or_else(|| eyre::eyre!("path has no parent: {}", display_path(path)))?;
677 let prefix = format!(
678 ".{}.",
679 path.file_name().unwrap_or_default().to_string_lossy()
680 );
681 let mut builder = tempfile::Builder::new();
682 builder.prefix(&prefix);
683
684 #[cfg(unix)]
685 let existing_permissions = match fs::metadata(path) {
686 Ok(metadata) => Some(metadata.permissions()),
687 Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
688 Err(err) => return Err(err.into()),
689 };
690
691 #[cfg(unix)]
692 if existing_permissions.is_none() {
693 builder.permissions(fs::Permissions::from_mode(0o666));
694 }
695
696 let mut temporary = builder.tempfile_in(parent)?;
697
698 #[cfg(unix)]
699 if let Some(permissions) = existing_permissions {
700 temporary.as_file().set_permissions(permissions)?;
701 }
702
703 temporary.write_all(contents.as_ref())?;
704
705 let parent = parent.to_path_buf();
706 Ok(PreparedAtomicWrite {
707 temporary,
708 target,
709 parent,
710 })
711}
712
713pub fn write_atomic<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
715 let path = path.as_ref();
716 trace!("write_atomic {}", display_path(path));
717 prepare_atomic_write(path, contents)?.commit()
718}
719
720pub fn atomic_write_target(path: &Path) -> Result<PathBuf> {
721 const MAX_SYMLINKS: usize = 40;
722
723 let mut target = path.to_path_buf();
724 for followed in 0..=MAX_SYMLINKS {
725 if !target.is_symlink() {
726 return Ok(desymlink_path(&target));
727 }
728 if followed == MAX_SYMLINKS {
729 break;
730 }
731 let link = fs::read_link(&target)
732 .wrap_err_with(|| format!("failed to read symlink: {}", display_path(&target)))?;
733 target = if link.is_absolute() {
734 link
735 } else {
736 target.parent().unwrap_or_else(|| Path::new("")).join(link)
737 };
738 }
739
740 bail!(
741 "too many symlinks while resolving atomic write target: {}",
742 display_path(path)
743 )
744}
745
746pub fn persist_atomic(mut temporary: tempfile::NamedTempFile, path: &Path) -> Result<()> {
747 const RETRIES: u32 = 20;
748
749 for attempt in 0..=RETRIES {
750 match temporary.persist(path) {
751 Ok(_) => return Ok(()),
752 Err(err) if should_retry_atomic_persist(&err.error) && attempt < RETRIES => {
753 temporary = err.file;
754 std::thread::sleep(Duration::from_millis(5 * u64::from(attempt + 1)));
755 }
756 Err(err) => return Err(err.error.into()),
757 }
758 }
759
760 unreachable!("atomic persist retry loop should always return");
761}
762
763#[cfg(windows)]
764fn should_retry_atomic_persist(err: &std::io::Error) -> bool {
765 err.kind() == std::io::ErrorKind::PermissionDenied
766 || matches!(err.raw_os_error(), Some(5) | Some(32))
767}
768
769#[cfg(not(windows))]
770fn should_retry_atomic_persist(_err: &std::io::Error) -> bool {
771 false
772}
773
774pub async fn write_async<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
775 let path = path.as_ref();
776 trace!("write {}", display_path(path));
777 tokio::fs::write(path, contents)
778 .await
779 .wrap_err_with(|| format!("failed write: {}", display_path(path)))
780}
781
782pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
783 let path = path.as_ref();
784 trace!("cat {}", path.display_user());
785 fs::read_to_string(path)
786 .wrap_err_with(|| format!("failed read_to_string: {}", path.display_user()))
787}
788
789pub const CONFIG_FILE_LIMIT: u64 = 16 * 1024 * 1024;
798
799fn config_file_too_large(path: &Path) -> eyre::Report {
800 eyre::eyre!(
801 "not reading {}: it is larger than {} MiB, the most mise reads from a config file",
802 path.display_user(),
803 CONFIG_FILE_LIMIT / 1024 / 1024
804 )
805}
806
807pub fn open_regular_file<P: AsRef<Path>>(path: P) -> std::io::Result<File> {
811 let mut options = fs::OpenOptions::new();
812 options.read(true);
813 #[cfg(unix)]
814 std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, nix::libc::O_NONBLOCK);
815 let file = options.open(path.as_ref())?;
816 if !file.metadata()?.is_file() {
817 return Err(std::io::Error::other("not a regular file"));
818 }
819 Ok(file)
820}
821
822pub fn read_config_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
825 let path = path.as_ref();
826 trace!("cat {}", path.display_user());
827 let file = open_regular_file(path).wrap_err_with(|| read_failed(path))?;
828 read_config_body(path, file)
829}
830
831pub fn read_config_to_string_if_exists<P: AsRef<Path>>(path: P) -> Result<Option<String>> {
836 let path = path.as_ref();
837 trace!("cat {}", path.display_user());
838 match open_regular_file(path) {
839 Ok(file) => read_config_body(path, file).map(Some),
840 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
841 Err(err) => Err(err).wrap_err_with(|| read_failed(path)),
842 }
843}
844
845fn read_failed(path: &Path) -> String {
846 format!("failed read_to_string: {}", path.display_user())
847}
848
849fn read_config_body(path: &Path, file: File) -> Result<String> {
850 let mut body = String::new();
851 file.take(CONFIG_FILE_LIMIT + 1)
852 .read_to_string(&mut body)
853 .wrap_err_with(|| read_failed(path))?;
854 if body.len() as u64 > CONFIG_FILE_LIMIT {
855 return Err(config_file_too_large(path));
856 }
857 Ok(body)
858}
859
860pub fn ensure_config_file_size<P: AsRef<Path>>(path: P) -> Result<()> {
864 let path = path.as_ref();
865 match fs::metadata(path) {
866 Ok(metadata) if metadata.len() > CONFIG_FILE_LIMIT => Err(config_file_too_large(path)),
867 _ => Ok(()),
868 }
869}
870
871pub async fn read_config_to_string_async<P: AsRef<Path>>(path: P) -> Result<String> {
874 let path = path.as_ref().to_path_buf();
875 tokio::task::spawn_blocking(move || read_config_to_string(&path))
876 .await
877 .wrap_err("config file read was cancelled")?
878}
879
880#[cfg(windows)]
882pub const UTF8_BOM_BYTES: [u8; 3] = [0xef, 0xbb, 0xbf];
883
884pub fn strip_utf8_bom(s: &str) -> &str {
891 s.strip_prefix('\u{feff}').unwrap_or(s)
892}
893
894pub fn decode_text(bytes: &[u8]) -> Result<String> {
905 fn from_utf16(bytes: &[u8], to_u16: fn([u8; 2]) -> u16, label: &str) -> Result<String> {
906 if !bytes.len().is_multiple_of(2) {
907 bail!(
908 "truncated {label} text: {} bytes is not a whole number of code units",
909 bytes.len()
910 );
911 }
912 let units = bytes
913 .as_chunks::<2>()
914 .0
915 .iter()
916 .map(|c| to_u16(*c))
917 .collect_vec();
918 String::from_utf16(&units).wrap_err_with(|| format!("invalid {label} text"))
919 }
920
921 match bytes {
922 [0xef, 0xbb, 0xbf, rest @ ..] => {
923 String::from_utf8(rest.to_vec()).wrap_err("invalid UTF-8 text after a UTF-8 BOM")
924 }
925 [0xff, 0xfe, rest @ ..] => from_utf16(rest, u16::from_le_bytes, "UTF-16LE"),
926 [0xfe, 0xff, rest @ ..] => from_utf16(rest, u16::from_be_bytes, "UTF-16BE"),
927 _ => String::from_utf8(bytes.to_vec())
928 .wrap_err("invalid UTF-8 text, and no byte-order mark identifying another encoding"),
929 }
930}
931
932#[cfg(any(windows, test))]
945pub fn utf16_bom(path: &Path) -> Option<&'static str> {
946 let bytes = std::fs::File::open(path)
949 .and_then(|f| {
950 use std::io::Read;
951 let mut buf = Vec::with_capacity(2);
952 f.take(2).read_to_end(&mut buf)?;
953 Ok(buf)
954 })
955 .ok()?;
956 match bytes[..] {
957 [0xff, 0xfe] => Some("UTF-16LE"),
958 [0xfe, 0xff] => Some("UTF-16BE"),
959 _ => None,
960 }
961}
962
963pub fn read_to_string_bom<P: AsRef<Path>>(path: P) -> Result<String> {
971 let path = path.as_ref();
972 trace!("cat {}", path.display_user());
973 let bytes = fs::read(path).wrap_err_with(|| format!("failed read: {}", path.display_user()))?;
974 decode_text(&bytes).wrap_err_with(|| format!("failed to decode {}", path.display_user()))
975}
976
977pub async fn read_to_string_async<P: AsRef<Path>>(path: P) -> Result<String> {
978 let path = path.as_ref();
979 trace!("cat {}", path.display_user());
980 tokio::fs::read_to_string(path)
981 .await
982 .wrap_err_with(|| format!("failed read_to_string: {}", path.display_user()))
983}
984
985pub fn create(path: &Path) -> Result<File> {
986 if let Some(parent) = path.parent() {
987 create_dir_all(parent)?;
988 }
989 trace!("touch {}", display_path(path));
990 File::create(path).wrap_err_with(|| format!("failed create: {}", display_path(path)))
991}
992
993pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
994 static LOCK: Lazy<Mutex<u8>> = Lazy::new(Default::default);
995 let _lock = LOCK.lock().unwrap();
996
997 let path = path.as_ref();
998 if !path.exists() {
999 trace!("mkdir -p {}", display_path(path));
1000 if let Err(err) = fs::create_dir_all(path) {
1001 if err.kind() != std::io::ErrorKind::AlreadyExists {
1003 return Err(err)
1004 .wrap_err_with(|| format!("failed create_dir_all: {}", display_path(path)));
1005 }
1006 }
1007 }
1008 Ok(())
1009}
1010
1011pub fn display_path<P: AsRef<Path>>(path: P) -> String {
1017 crate::path::settle_display_separators(path.as_ref().display_user())
1018}
1019
1020pub fn display_filename<P: AsRef<Path>>(path: P) -> String {
1021 let path = path.as_ref();
1022 path.file_name()
1023 .unwrap_or(path.as_os_str())
1024 .to_string_lossy()
1025 .into_owned()
1026}
1027
1028pub fn display_rel_path<P: AsRef<Path>>(path: P) -> String {
1029 let path = path.as_ref();
1030 match path.strip_prefix(dirs::CWD.as_ref().unwrap()) {
1031 Ok(rel) => format!(".{}{}", std::path::MAIN_SEPARATOR, display_path(rel)),
1035 Err(_) => display_path(path),
1036 }
1037}
1038
1039pub fn replace_paths_in_string<S: Display>(input: S) -> String {
1042 let home = env::HOME.to_string_lossy().to_string();
1043 input.to_string().replace(&home, "~")
1044}
1045
1046pub fn replace_path<P: AsRef<Path>>(path: P) -> PathBuf {
1066 let path = path.as_ref();
1067 match path.strip_prefix("~/") {
1068 Ok(rest) => {
1069 let mut expanded = dirs::HOME.to_path_buf();
1070 for component in rest.components() {
1071 expanded.push(component.as_os_str());
1072 }
1073 expanded
1074 }
1075 Err(_) => path.to_path_buf(),
1076 }
1077}
1078
1079pub fn paths_eq(a: &Path, b: &Path) -> bool {
1095 #[cfg(any(windows, target_os = "macos"))]
1096 {
1097 let normalize =
1098 |c: std::path::Component<'_>| c.as_os_str().to_string_lossy().to_lowercase();
1099 a.components()
1100 .map(normalize)
1101 .eq(b.components().map(normalize))
1102 }
1103 #[cfg(all(not(windows), not(target_os = "macos")))]
1104 {
1105 a == b
1106 }
1107}
1108
1109pub fn storage_paths_eq(a: &Path, b: &Path) -> bool {
1114 paths_eq(a, b) || same_file(a, b)
1115}
1116
1117pub fn touch_file(file: &Path) -> Result<()> {
1118 if !file.exists() {
1119 create(file)?;
1120 return Ok(());
1121 }
1122 trace!("touch_file {}", file.display());
1123 let now = SystemTime::now();
1124 set_times(file, Some(now), Some(now))
1125 .wrap_err_with(|| format!("failed to touch file: {}", display_path(file)))
1126}
1127
1128pub fn touch_dir(dir: &Path) -> Result<()> {
1129 trace!("touch {}", dir.display());
1130 let now = SystemTime::now();
1131 set_times(dir, Some(now), Some(now))
1132 .wrap_err_with(|| format!("failed to touch dir: {}", display_path(dir)))
1133}
1134
1135pub fn set_times(
1140 path: &Path,
1141 accessed: Option<SystemTime>,
1142 modified: Option<SystemTime>,
1143) -> std::io::Result<()> {
1144 set_path_times(path, accessed, modified, true)
1145}
1146
1147pub fn set_symlink_times(
1149 path: &Path,
1150 accessed: Option<SystemTime>,
1151 modified: Option<SystemTime>,
1152) -> std::io::Result<()> {
1153 set_path_times(path, accessed, modified, false)
1154}
1155
1156#[cfg(unix)]
1157fn set_path_times(
1158 path: &Path,
1159 accessed: Option<SystemTime>,
1160 modified: Option<SystemTime>,
1161 follow: bool,
1162) -> std::io::Result<()> {
1163 use nix::sys::stat::{UtimensatFlags, utimensat};
1164 use nix::sys::time::TimeSpec;
1165
1166 fn spec(time: Option<SystemTime>) -> TimeSpec {
1167 match time.map(|time| time.duration_since(SystemTime::UNIX_EPOCH)) {
1168 None => TimeSpec::UTIME_OMIT,
1169 Some(Ok(after)) => TimeSpec::from_duration(after),
1170 Some(Err(before)) => -TimeSpec::from_duration(before.duration()),
1171 }
1172 }
1173 let flag = if follow {
1174 UtimensatFlags::FollowSymlink
1175 } else {
1176 UtimensatFlags::NoFollowSymlink
1177 };
1178 utimensat(
1179 nix::fcntl::AT_FDCWD,
1180 path,
1181 &spec(accessed),
1182 &spec(modified),
1183 flag,
1184 )?;
1185 Ok(())
1186}
1187
1188#[cfg(windows)]
1189fn set_path_times(
1190 path: &Path,
1191 accessed: Option<SystemTime>,
1192 modified: Option<SystemTime>,
1193 follow: bool,
1194) -> std::io::Result<()> {
1195 use std::os::windows::fs::OpenOptionsExt;
1196 use windows_sys::Win32::Storage::FileSystem::{
1197 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_WRITE_ATTRIBUTES,
1198 };
1199
1200 let mut flags = FILE_FLAG_BACKUP_SEMANTICS;
1201 if !follow {
1202 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1203 }
1204 let file = fs::OpenOptions::new()
1205 .access_mode(FILE_WRITE_ATTRIBUTES)
1206 .custom_flags(flags)
1207 .open(path)?;
1208 let mut times = fs::FileTimes::new();
1209 if let Some(accessed) = accessed {
1210 times = times.set_accessed(accessed);
1211 }
1212 if let Some(modified) = modified {
1213 times = times.set_modified(modified);
1214 }
1215 file.set_times(times)
1216}
1217
1218#[cfg(unix)]
1235pub fn sync_dir<P: AsRef<Path>>(path: P) -> Result<()> {
1236 let path = path.as_ref();
1237 trace!("sync {}", display_path(path));
1238 let dir = File::open(path)
1239 .wrap_err_with(|| format!("failed to open dir for sync: {}", display_path(path)))?;
1240 dir.sync_all()
1241 .wrap_err_with(|| format!("failed to sync dir: {}", display_path(path)))
1242}
1243
1244#[cfg(windows)]
1245pub fn sync_dir<P: AsRef<Path>>(_path: P) -> Result<()> {
1246 Ok(())
1248}
1249
1250pub fn modified_duration(path: &Path) -> Result<Duration> {
1251 let metadata = path.metadata()?;
1252 let modified = metadata.modified()?;
1253 let duration = modified.elapsed().unwrap_or_default();
1254 Ok(duration)
1255}
1256
1257pub fn find_up<FN: AsRef<str>>(from: &Path, filenames: &[FN]) -> Option<PathBuf> {
1258 let mut current = from.to_path_buf();
1259 loop {
1260 for filename in filenames {
1261 let path = current.join(filename.as_ref());
1262 if path.exists() {
1263 return Some(path);
1264 }
1265 }
1266 if !current.pop() {
1267 return None;
1268 }
1269 }
1270}
1271
1272pub fn dir_subdirs(dir: &Path) -> Result<BTreeSet<String>> {
1276 let mut output = Default::default();
1277
1278 if !dir.exists() {
1279 return Ok(output);
1280 }
1281
1282 for entry in dir.read_dir()? {
1283 let entry = entry?;
1284 let ft = entry.file_type()?;
1286 if ft.is_dir() || (ft.is_symlink() && entry.path().is_dir()) {
1287 if let Ok(name) = entry.file_name().into_string() {
1289 output.insert(name);
1290 }
1291 }
1292 }
1293
1294 Ok(output)
1295}
1296
1297pub fn ls(dir: &Path) -> Result<BTreeSet<PathBuf>> {
1298 let mut output = Default::default();
1299
1300 if !dir.is_dir() {
1301 return Ok(output);
1302 }
1303
1304 for entry in dir.read_dir()? {
1305 let entry = entry?;
1306 output.insert(entry.path());
1307 }
1308
1309 Ok(output)
1310}
1311
1312#[cfg(unix)]
1313pub fn make_symlink(target: &Path, link: &Path) -> Result<(PathBuf, PathBuf)> {
1314 trace!("ln -sf {} {}", target.display(), link.display());
1315 static COUNTER: AtomicU64 = AtomicU64::new(0);
1323 let file_name = link
1324 .file_name()
1325 .and_then(|n| n.to_str())
1326 .unwrap_or("symlink");
1327 let tmp = link.with_file_name(format!(
1328 ".{file_name}.tmp.{}.{}",
1329 std::process::id(),
1330 COUNTER.fetch_add(1, Ordering::Relaxed)
1331 ));
1332 let _ = fs::remove_file(&tmp);
1333 symlink(target, &tmp)
1334 .wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()))?;
1335 if let Err(err) = fs::rename(&tmp, link) {
1336 let _ = fs::remove_file(&tmp);
1337 return Err(err)
1338 .wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()));
1339 }
1340 Ok((target.to_path_buf(), link.to_path_buf()))
1341}
1342
1343#[cfg(unix)]
1344pub fn make_symlink_or_copy(target: &Path, link: &Path) -> Result<()> {
1345 make_symlink(target, link)?;
1346 Ok(())
1347}
1348
1349#[cfg(windows)]
1350pub fn make_symlink_or_copy(target: &Path, link: &Path) -> Result<()> {
1351 copy(target, link)?;
1352 Ok(())
1353}
1354
1355#[cfg(windows)]
1356pub fn is_unc_path(path: &Path) -> bool {
1357 matches!(
1358 path.components().next(),
1359 Some(std::path::Component::Prefix(prefix))
1360 if matches!(
1361 prefix.kind(),
1362 std::path::Prefix::UNC(..) | std::path::Prefix::VerbatimUNC(..)
1363 )
1364 )
1365}
1366
1367#[cfg(windows)]
1368fn create_windows_unc_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
1369 std::os::windows::fs::symlink_dir(target, link).map_err(|err| {
1370 if err.kind() == std::io::ErrorKind::PermissionDenied {
1371 std::io::Error::new(
1372 err.kind(),
1373 format!(
1374 "{err}. Creating directory symlinks on Windows may require administrator privileges or Developer Mode"
1375 ),
1376 )
1377 } else {
1378 err
1379 }
1380 })
1381}
1382
1383#[cfg(windows)]
1384fn create_windows_dir_link(target: &Path, link: &Path) -> std::io::Result<()> {
1385 if is_unc_path(target) {
1386 return create_windows_unc_symlink(target, link);
1387 }
1388 let existed = fs::symlink_metadata(link).is_ok();
1389 let result = junction::create(target, link);
1390 if let Err(err) = &result
1397 && err.kind() != std::io::ErrorKind::AlreadyExists
1398 && !existed
1399 && junction::get_target(link).is_err()
1400 {
1401 let _ = fs::remove_dir(link);
1402 }
1403 result
1404}
1405
1406#[cfg(windows)]
1407pub fn make_symlink(target: &Path, link: &Path) -> Result<(PathBuf, PathBuf)> {
1408 if let Err(err) = create_windows_dir_link(target, link) {
1409 if err.kind() == std::io::ErrorKind::AlreadyExists {
1410 remove_symlink_or_junction(link)?;
1411 create_windows_dir_link(target, link)
1412 } else {
1413 Err(err)
1414 }
1415 } else {
1416 Ok(())
1417 }
1418 .wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()))?;
1419 Ok((target.to_path_buf(), link.to_path_buf()))
1420}
1421
1422#[cfg(windows)]
1423pub fn make_symlink_or_file(target: &Path, link: &Path) -> Result<()> {
1424 trace!("ln -sf {} {}", target.display(), link.display());
1425 if link.is_file() || link.is_symlink() {
1426 fs::remove_file(link)?;
1428 }
1429 xx::file::write(link, target.to_string_lossy().to_string())?;
1430 Ok(())
1431}
1432
1433pub fn resolve_symlink(link: &Path) -> Result<Option<PathBuf>> {
1434 let file_type = link.symlink_metadata().ok().map(|m| m.file_type());
1439 if file_type.is_some_and(|t| t.is_symlink()) {
1440 Ok(Some(fs::read_link(link)?))
1441 } else if let Some(target) = junction_target(link) {
1442 Ok(Some(target))
1443 } else if file_type.is_some_and(|t| t.is_file()) {
1444 Ok(Some(fs::read_to_string(link)?.into()))
1445 } else {
1446 Ok(None)
1447 }
1448}
1449
1450#[cfg(windows)]
1451fn junction_target(link: &Path) -> Option<PathBuf> {
1452 junction::get_target(link).ok()
1453}
1454
1455#[cfg(not(windows))]
1456fn junction_target(_link: &Path) -> Option<PathBuf> {
1457 None
1458}
1459
1460#[cfg(unix)]
1467pub fn make_dir_link(target: &Path, link: &Path) -> Result<()> {
1468 make_symlink(target, link)?;
1469 Ok(())
1470}
1471
1472#[cfg(windows)]
1473pub fn make_dir_link(target: &Path, link: &Path) -> Result<()> {
1474 static COUNTER: AtomicU64 = AtomicU64::new(0);
1475 let target = resolve_relative_link_target(link, target.to_path_buf());
1476 let target = target.absolutize()?.into_owned();
1477 if fs::symlink_metadata(link).is_err() {
1478 match make_symlink(&target, link) {
1479 Ok(_) => return Ok(()),
1480 Err(_) if fs::symlink_metadata(link).is_ok() => {}
1482 Err(err) => return Err(err),
1483 }
1484 }
1485 let name = link.file_name().and_then(|n| n.to_str()).unwrap_or("link");
1488 let tmp = link.with_file_name(format!(
1489 ".{name}.tmp.{}.{}",
1490 std::process::id(),
1491 COUNTER.fetch_add(1, Ordering::Relaxed)
1492 ));
1493 make_symlink(&target, &tmp)?;
1494 let previous = resolve_symlink(link)
1496 .ok()
1497 .flatten()
1498 .map(|old| resolve_relative_link_target(link, old));
1499 let swapped = remove_dir_link(link).and_then(|()| {
1500 rename(&tmp, link)
1502 });
1503 if swapped.is_err() {
1504 let _ = remove_symlink_or_junction(&tmp);
1505 if let Some(previous) = previous
1506 && fs::symlink_metadata(link).is_err()
1507 {
1508 let _ = make_symlink(&previous, link);
1509 }
1510 }
1511 swapped
1512}
1513
1514#[cfg(unix)]
1516pub fn remove_dir_link(link: &Path) -> Result<()> {
1517 if link.is_symlink() || link.is_file() {
1518 remove_file(link)?;
1519 }
1520 Ok(())
1521}
1522
1523#[cfg(windows)]
1524pub fn remove_dir_link(link: &Path) -> Result<()> {
1525 if is_symlink_or_junction(link) {
1526 remove_symlink_or_junction(link)
1527 } else if link.is_file() {
1528 remove_file(link)
1529 } else {
1530 Ok(())
1531 }
1532}
1533
1534pub fn is_symlink_to(link: &Path, target: &Path) -> bool {
1535 is_symlink_or_junction(link) && same_file::is_same_file(link, target).unwrap_or(false)
1536}
1537
1538#[cfg(unix)]
1539pub fn is_symlink_or_junction(path: &Path) -> bool {
1540 path.is_symlink()
1541}
1542
1543#[cfg(windows)]
1544pub fn is_symlink_or_junction(path: &Path) -> bool {
1545 path.is_symlink() || junction::get_target(path).is_ok()
1546}
1547
1548#[cfg(unix)]
1549pub fn make_symlink_or_file(target: &Path, link: &Path) -> Result<()> {
1550 make_symlink(target, link)?;
1551 Ok(())
1552}
1553
1554pub fn is_symlink_target_within(link: &Path, root: &Path) -> Result<bool> {
1555 let Some(target) = dir_link_target(link)? else {
1556 return Ok(false);
1557 };
1558 let target = target.absolutize()?;
1559 let root = root.absolutize()?;
1560 Ok(path_starts_with(&target, &root))
1561}
1562
1563#[cfg(unix)]
1564fn path_starts_with(path: &Path, root: &Path) -> bool {
1565 path.starts_with(root)
1566}
1567
1568#[cfg(unix)]
1571pub fn same_path_ignoring_case(a: &Path, b: &Path) -> bool {
1572 a == b
1573}
1574
1575#[cfg(windows)]
1579pub fn same_path_ignoring_case(a: &Path, b: &Path) -> bool {
1580 use std::os::windows::ffi::OsStrExt;
1581 use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
1582
1583 if a == b {
1584 return true;
1585 }
1586 let a = a.as_os_str().encode_wide().collect::<Vec<_>>();
1587 let b = b.as_os_str().encode_wide().collect::<Vec<_>>();
1588 let (Ok(a_len), Ok(b_len)) = (i32::try_from(a.len()), i32::try_from(b.len())) else {
1589 return false;
1590 };
1591 unsafe { CompareStringOrdinal(a.as_ptr(), a_len, b.as_ptr(), b_len, 1) == CSTR_EQUAL }
1592}
1593
1594#[cfg(windows)]
1595fn path_starts_with(path: &Path, root: &Path) -> bool {
1596 if path.starts_with(root) {
1597 return true;
1598 }
1599
1600 let root_component_count = root.components().count();
1601 let root = root.components().collect::<PathBuf>();
1602 let candidate = path
1603 .components()
1604 .take(root_component_count)
1605 .collect::<PathBuf>();
1606 if candidate.components().count() != root_component_count {
1607 return false;
1608 }
1609
1610 if !same_path_ignoring_case(&candidate, &root) {
1611 return false;
1612 }
1613
1614 match same_file::is_same_file(&candidate, &root) {
1615 Ok(same) => same,
1616 Err(_) => dangling_paths_share_case_insensitive_parent(&candidate, &root),
1617 }
1618}
1619
1620#[cfg(unix)]
1623pub fn same_location_ignoring_case(a: &Path, b: &Path) -> bool {
1624 a == b
1625}
1626
1627#[cfg(windows)]
1632pub fn same_location_ignoring_case(a: &Path, b: &Path) -> bool {
1633 if a == b {
1634 return true;
1635 }
1636 if !same_path_ignoring_case(a, b) {
1637 return false;
1638 }
1639 match same_file::is_same_file(a, b) {
1640 Ok(same) => same && !respelled_in_case_sensitive_dir(a, b),
1642 Err(_) => dangling_paths_share_case_insensitive_parent(a, b),
1643 }
1644}
1645
1646#[cfg(windows)]
1651fn respelled_in_case_sensitive_dir(a: &Path, b: &Path) -> bool {
1652 let mut dir = PathBuf::new();
1653 for (in_a, in_b) in a.components().zip(b.components()) {
1654 if in_a != in_b
1655 && !dir.as_os_str().is_empty()
1656 && directory_is_case_sensitive(&dir) == Some(true)
1657 {
1658 return true;
1659 }
1660 dir.push(in_a);
1661 }
1662 false
1663}
1664
1665#[cfg(windows)]
1666fn dangling_paths_share_case_insensitive_parent(path: &Path, root: &Path) -> bool {
1667 let Some((path_parent, path_missing_components)) = nearest_existing_directory(path) else {
1668 return false;
1669 };
1670 let Some((root_parent, root_missing_components)) = nearest_existing_directory(root) else {
1671 return false;
1672 };
1673
1674 path_missing_components == root_missing_components
1675 && same_file::is_same_file(&path_parent, &root_parent).unwrap_or(false)
1676 && directory_is_case_sensitive(&path_parent) == Some(false)
1677}
1678
1679#[cfg(windows)]
1680fn nearest_existing_directory(path: &Path) -> Option<(PathBuf, usize)> {
1681 let mut path = path;
1682 let mut missing_components = 0;
1683 loop {
1684 match fs::metadata(path) {
1685 Ok(metadata) if metadata.is_dir() => {
1686 return Some((path.to_path_buf(), missing_components));
1687 }
1688 Ok(_) => return None,
1689 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1690 path = path.parent()?;
1691 missing_components += 1;
1692 }
1693 Err(_) => return None,
1694 }
1695 }
1696}
1697
1698#[cfg(windows)]
1699fn directory_is_case_sensitive(path: &Path) -> Option<bool> {
1700 use std::os::windows::fs::OpenOptionsExt;
1701 use std::os::windows::io::AsRawHandle;
1702 use windows_sys::Win32::Storage::FileSystem::{
1703 FILE_CASE_SENSITIVE_INFO, FILE_FLAG_BACKUP_SEMANTICS, FileCaseSensitiveInfo,
1704 GetFileInformationByHandleEx,
1705 };
1706 use windows_sys::Win32::System::SystemServices::FILE_CS_FLAG_CASE_SENSITIVE_DIR;
1707
1708 let directory = fs::OpenOptions::new()
1709 .read(true)
1710 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1711 .open(path)
1712 .ok()?;
1713 let mut case_info = FILE_CASE_SENSITIVE_INFO::default();
1714 let inspected = unsafe {
1715 GetFileInformationByHandleEx(
1716 directory.as_raw_handle(),
1717 FileCaseSensitiveInfo,
1718 std::ptr::from_mut(&mut case_info).cast(),
1719 std::mem::size_of::<FILE_CASE_SENSITIVE_INFO>() as u32,
1720 )
1721 };
1722 (inspected != 0).then_some(case_info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0)
1723}
1724
1725#[cfg(unix)]
1726fn dir_link_target(link: &Path) -> Result<Option<PathBuf>> {
1727 let metadata = match fs::symlink_metadata(link) {
1728 Ok(metadata) => metadata,
1729 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1730 Err(err) => {
1731 return Err(err)
1732 .wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
1733 }
1734 };
1735 if !metadata.file_type().is_symlink() {
1736 return Ok(None);
1737 }
1738 let target = fs::read_link(link)
1739 .wrap_err_with(|| format!("failed to read link: {}", display_path(link)))?;
1740 Ok(Some(resolve_relative_link_target(link, target)))
1741}
1742
1743#[cfg(windows)]
1744fn dir_link_target(link: &Path) -> Result<Option<PathBuf>> {
1745 const ERROR_NOT_A_REPARSE_POINT: i32 = 4390;
1746
1747 let metadata = match fs::symlink_metadata(link) {
1748 Ok(metadata) => metadata,
1749 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1750 Err(err) => {
1751 return Err(err)
1752 .wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
1753 }
1754 };
1755 let target = if metadata.file_type().is_symlink() {
1756 fs::read_link(link)
1757 .wrap_err_with(|| format!("failed to read link: {}", display_path(link)))?
1758 } else {
1759 match junction::get_target(link) {
1760 Ok(target) => target,
1761 Err(err)
1762 if err.kind() == std::io::ErrorKind::NotFound
1763 || err.raw_os_error() == Some(ERROR_NOT_A_REPARSE_POINT)
1764 || (err.kind() == std::io::ErrorKind::Other
1765 && err.raw_os_error().is_none()) =>
1766 {
1767 return Ok(None);
1768 }
1769 Err(err) => {
1770 return Err(err).wrap_err_with(|| {
1771 format!("failed to inspect junction: {}", display_path(link))
1772 });
1773 }
1774 }
1775 };
1776 Ok(Some(resolve_relative_link_target(link, target)))
1777}
1778
1779fn resolve_relative_link_target(link: &Path, target: PathBuf) -> PathBuf {
1780 if target.is_absolute() {
1781 target
1782 } else {
1783 link.parent().unwrap_or(link).join(target)
1784 }
1785}
1786
1787#[cfg(unix)]
1788pub fn remove_symlink_or_junction(link: &Path) -> Result<()> {
1789 if dir_link_target(link)?.is_none() {
1793 bail!("refusing to remove non-link: {}", display_path(link));
1794 }
1795 fs::remove_file(link)
1796 .wrap_err_with(|| format!("failed to remove symlink: {}", display_path(link)))
1797}
1798
1799#[cfg(windows)]
1800pub fn remove_symlink_or_junction(link: &Path) -> Result<()> {
1801 let link_handle = open_link_for_removal(link)?;
1802 remove_open_link(link_handle)
1803 .wrap_err_with(|| format!("failed to remove link or junction: {}", display_path(link)))
1804}
1805
1806#[cfg(windows)]
1807fn open_link_for_removal(link: &Path) -> Result<File> {
1808 use std::os::windows::fs::OpenOptionsExt;
1809 use std::os::windows::io::AsRawHandle;
1810 use windows_sys::Win32::Storage::FileSystem::{
1811 DELETE, FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
1812 FileAttributeTagInfo, GetFileInformationByHandleEx,
1813 };
1814 use windows_sys::Win32::System::SystemServices::{
1815 IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK,
1816 };
1817
1818 let file = fs::OpenOptions::new()
1819 .access_mode(DELETE)
1820 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
1821 .open(link)
1822 .wrap_err_with(|| format!("failed to open link: {}", display_path(link)))?;
1823 let mut tag_info = FILE_ATTRIBUTE_TAG_INFO::default();
1824 let inspected = unsafe {
1825 GetFileInformationByHandleEx(
1826 file.as_raw_handle(),
1827 FileAttributeTagInfo,
1828 std::ptr::from_mut(&mut tag_info).cast(),
1829 std::mem::size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
1830 )
1831 };
1832 if inspected == 0 {
1833 return Err(std::io::Error::last_os_error())
1834 .wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
1835 }
1836 if !matches!(
1837 tag_info.ReparseTag,
1838 IO_REPARSE_TAG_SYMLINK | IO_REPARSE_TAG_MOUNT_POINT
1839 ) {
1840 bail!("refusing to remove non-link: {}", display_path(link));
1841 }
1842 Ok(file)
1843}
1844
1845#[cfg(windows)]
1846fn remove_open_link(file: File) -> std::io::Result<()> {
1847 use std::os::windows::io::AsRawHandle;
1848 use windows_sys::Win32::Storage::FileSystem::{
1849 FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
1850 };
1851
1852 let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
1853 let removed = unsafe {
1854 SetFileInformationByHandle(
1855 file.as_raw_handle(),
1856 FileDispositionInfo,
1857 std::ptr::from_ref(&disposition).cast(),
1858 std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
1859 )
1860 };
1861 if removed == 0 {
1862 return Err(std::io::Error::last_os_error());
1863 }
1864 drop(file);
1865 Ok(())
1866}
1867
1868#[cfg(unix)]
1869pub fn is_executable(path: &Path) -> bool {
1870 if let Ok(metadata) = path.metadata() {
1871 return metadata.permissions().mode() & 0o111 != 0;
1872 }
1873 false
1874}
1875
1876#[cfg(windows)]
1877pub fn is_executable(path: &Path) -> bool {
1878 if !path.is_file() {
1879 return false;
1880 }
1881 if has_known_executable_extension(path) {
1882 return true;
1883 }
1884 has_shebang(path)
1885}
1886
1887#[cfg(unix)]
1893pub fn make_executable_hint(path: &Path) -> String {
1894 format!("Run: chmod +x {}", display_path(path))
1895}
1896
1897#[cfg(windows)]
1898pub fn make_executable_hint(path: &Path) -> String {
1899 if let Some(encoding) = utf16_bom(path) {
1906 return format!(
1907 "{} is {encoding}. mise reads a shebang as bytes, so save it as UTF-8.",
1908 display_path(path),
1909 );
1910 }
1911 format!(
1912 "Add a shebang line to {}, or give it one of these extensions: {}",
1913 display_path(path),
1914 Settings::get().windows_executable_extensions.join(", ")
1918 )
1919}
1920
1921#[cfg(windows)]
1922pub fn has_known_executable_extension(path: &Path) -> bool {
1923 path.extension().map_or(
1924 Settings::get()
1925 .windows_executable_extensions
1926 .contains(&String::new()),
1927 |ext| {
1928 if let Some(str_val) = ext.to_str() {
1929 return Settings::get()
1930 .windows_executable_extensions
1931 .contains(&str_val.to_lowercase().to_string());
1932 }
1933 false
1934 },
1935 )
1936}
1937
1938#[cfg(windows)]
1951pub fn has_shebang(path: &Path) -> bool {
1952 std::fs::File::open(path)
1953 .and_then(|f| {
1954 use std::io::Read;
1955 let mut buf = Vec::with_capacity(UTF8_BOM_BYTES.len() + 2);
1956 f.take((UTF8_BOM_BYTES.len() + 2) as u64)
1957 .read_to_end(&mut buf)?;
1958 let bytes = buf.strip_prefix(UTF8_BOM_BYTES.as_slice()).unwrap_or(&buf);
1959 Ok(bytes.starts_with(b"#!"))
1960 })
1961 .unwrap_or(false)
1962}
1963
1964#[cfg(windows)]
1979pub const OS_LAUNCHABLE_EXTENSIONS: [&str; 4] = ["exe", "com", "bat", "cmd"];
1980
1981#[cfg(windows)]
1986pub fn os_can_launch_extension(ext: &str) -> bool {
1987 OS_LAUNCHABLE_EXTENSIONS
1988 .iter()
1989 .any(|known| ext.eq_ignore_ascii_case(known))
1990}
1991
1992pub fn can_execute_directly(path: &Path) -> bool {
2008 #[cfg(windows)]
2009 {
2010 has_known_executable_extension(path)
2011 && path
2012 .extension()
2013 .and_then(|ext| ext.to_str())
2014 .is_some_and(os_can_launch_extension)
2015 }
2016 #[cfg(not(windows))]
2017 {
2018 is_executable(path)
2019 }
2020}
2021
2022pub fn is_spawnable(path: &Path) -> bool {
2024 if cfg!(windows) && !path.is_file() {
2025 return false;
2026 }
2027 can_execute_directly(path)
2028}
2029
2030#[cfg(unix)]
2031pub fn make_executable<P: AsRef<Path>>(path: P) -> Result<()> {
2032 trace!("chmod +x {}", display_path(&path));
2033 let path = path.as_ref();
2034 let mut perms = path.metadata()?.permissions();
2035 perms.set_mode(executable_mode(perms.mode()));
2036 fs::set_permissions(path, perms)
2037 .wrap_err_with(|| format!("failed to chmod +x: {}", display_path(path)))?;
2038 Ok(())
2039}
2040
2041#[cfg(unix)]
2048fn executable_mode(mode: u32) -> u32 {
2049 mode | 0o111 | 0o444
2050}
2051
2052#[cfg(windows)]
2053pub fn make_executable<P: AsRef<Path>>(_path: P) -> Result<()> {
2054 Ok(())
2055}
2056
2057#[cfg(unix)]
2058pub async fn make_executable_async<P: AsRef<Path>>(path: P) -> Result<()> {
2059 trace!("chmod +x {}", display_path(&path));
2060 let path = path.as_ref();
2061 let mut perms = path.metadata()?.permissions();
2062 perms.set_mode(executable_mode(perms.mode()));
2063 tokio::fs::set_permissions(path, perms)
2064 .await
2065 .wrap_err_with(|| format!("failed to chmod +x: {}", display_path(path)))
2066}
2067
2068#[cfg(windows)]
2069pub async fn make_executable_async<P: AsRef<Path>>(_path: P) -> Result<()> {
2070 Ok(())
2071}
2072
2073pub fn ceiling_path_forms(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
2078 let path = replace_path(path);
2079 let resolved = dunce::canonicalize(&path).ok().filter(|p| *p != path);
2082 std::iter::once(path).chain(resolved)
2083}
2084
2085pub fn all_dirs<P: AsRef<Path>>(
2086 start_dir: P,
2087 ceiling_dirs: &HashSet<PathBuf>,
2088) -> Result<Vec<PathBuf>> {
2089 trace!(
2090 "file::all_dirs Collecting all ancestors of {} until ceiling {:?}",
2091 display_path(&start_dir),
2092 ceiling_dirs
2093 );
2094 Ok(start_dir
2095 .as_ref()
2096 .ancestors()
2097 .map_while(|p| {
2098 if ceiling_dirs.contains(p) || ceiling_dirs.contains(dunce::simplified(p)) {
2101 debug!(
2102 "file::all_dirs Reached ceiling directory: {}",
2103 display_path(p)
2104 );
2105 None
2106 } else {
2107 trace!(
2108 "file::all_dirs Adding ancestor directory: {}",
2109 display_path(p)
2110 );
2111 Some(p.to_path_buf())
2112 }
2113 })
2114 .collect())
2115}
2116
2117fn is_empty_dir(path: &Path) -> Result<bool> {
2118 path.read_dir()
2119 .map(|mut i| i.next().is_none())
2120 .wrap_err_with(|| format!("failed to read_dir: {}", display_path(path)))
2121}
2122
2123fn is_empty_dir_ignore(path: &Path, ignore_files: Vec<&str>) -> Result<bool> {
2124 path.read_dir()
2125 .map(|mut i| {
2126 i.all(|entry| match entry {
2127 Ok(entry) => ignore_files.iter().any(|ignore_file| {
2128 entry
2129 .file_name()
2130 .to_string_lossy()
2131 .eq_ignore_ascii_case(ignore_file)
2132 }),
2133 Err(_) => false,
2134 })
2135 })
2136 .wrap_err_with(|| format!("failed to read_dir: {}", display_path(path)))
2137}
2138
2139pub struct FindUp {
2140 current_dir: PathBuf,
2141 current_dir_filenames: Vec<String>,
2142 filenames: Vec<String>,
2143}
2144
2145impl FindUp {
2146 pub fn new(from: &Path, filenames: &[String]) -> Self {
2147 let filenames: Vec<String> = filenames.iter().map(|s| s.to_string()).collect();
2148 Self {
2149 current_dir: from.to_path_buf(),
2150 filenames: filenames.clone(),
2151 current_dir_filenames: filenames,
2152 }
2153 }
2154}
2155
2156impl Iterator for FindUp {
2157 type Item = PathBuf;
2158
2159 fn next(&mut self) -> Option<Self::Item> {
2160 while let Some(filename) = self.current_dir_filenames.pop() {
2161 let path = self.current_dir.join(filename);
2162 if path.is_file() {
2163 return Some(path);
2164 }
2165 }
2166 self.current_dir_filenames.clone_from(&self.filenames);
2167 if crate::testing::active() && self.current_dir == *dirs::HOME {
2168 return None; }
2170 if !self.current_dir.pop() {
2171 return None;
2172 }
2173 self.next()
2174 }
2175}
2176
2177pub fn which<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
2180 static CACHE: Lazy<Mutex<HashMap<PathBuf, Option<PathBuf>>>> = Lazy::new(Default::default);
2181
2182 let name = name.as_ref();
2183 if let Some(path) = CACHE.lock().unwrap().get(name) {
2184 return path.clone();
2185 }
2186 let path = _which(name, &env::PATH);
2187 CACHE
2188 .lock()
2189 .unwrap()
2190 .insert(name.to_path_buf(), path.clone());
2191 path
2192}
2193
2194pub fn which_spawnable(name: &str) -> Option<PathBuf> {
2197 _which_spawnable(name, &env::PATH)
2198}
2199
2200pub fn which_spawnable_in(name: &str, paths: &[PathBuf]) -> Option<PathBuf> {
2204 _which_spawnable(name, paths)
2205}
2206
2207fn _which_spawnable(name: &str, paths: &[PathBuf]) -> Option<PathBuf> {
2208 let names = executable_names(name);
2209 paths.iter().find_map(|dir| {
2210 names
2211 .iter()
2212 .map(|name| dir.join(name))
2213 .find(|candidate| is_spawnable(candidate))
2214 })
2215}
2216
2217pub fn which_non_pristine<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
2220 _which(name, &env::PATH_NON_PRISTINE)
2221}
2222
2223pub fn canonicalize_cached(path: &Path) -> Option<PathBuf> {
2229 static CACHE: Lazy<Mutex<HashMap<PathBuf, PathBuf>>> = Lazy::new(Default::default);
2230
2231 if !path.is_absolute() {
2232 return path.canonicalize().ok();
2233 }
2234 if let Some(path) = CACHE.lock().unwrap().get(path).cloned() {
2235 return Some(path);
2236 }
2237 let canonicalized = path.canonicalize().ok()?;
2238 CACHE
2239 .lock()
2240 .unwrap()
2241 .insert(path.to_path_buf(), canonicalized.clone());
2242 Some(canonicalized)
2243}
2244
2245pub fn canonicalize_path_entry(path: &Path) -> Option<PathBuf> {
2255 if in_wsl() && is_windows_drive_mount(path) {
2256 return Some(path.to_path_buf());
2257 }
2258 canonicalize_cached(path)
2259}
2260
2261pub fn canonicalize_path_entry_or_self(path: &Path) -> PathBuf {
2263 canonicalize_path_entry(path).unwrap_or_else(|| path.to_path_buf())
2264}
2265
2266fn in_wsl() -> bool {
2267 static WSL: Lazy<bool> = Lazy::new(|| {
2268 std::env::var_os("WSL_DISTRO_NAME").is_some() || std::env::var_os("WSL_INTEROP").is_some()
2269 });
2270 *WSL
2271}
2272
2273fn is_windows_drive_mount(path: &Path) -> bool {
2276 use std::path::Component;
2277 let mut components = path.components();
2278 if components.next() != Some(Component::RootDir) {
2279 return false;
2280 }
2281 if components.next() != Some(Component::Normal("mnt".as_ref())) {
2282 return false;
2283 }
2284 matches!(
2285 components.next(),
2286 Some(Component::Normal(drive))
2287 if drive.len() == 1 && drive.as_encoded_bytes()[0].is_ascii_alphabetic()
2288 ) && components.all(|c| c != Component::ParentDir)
2289}
2290
2291pub fn canonicalize_or_self(path: &Path) -> PathBuf {
2294 canonicalize_cached(path).unwrap_or_else(|| path.to_path_buf())
2295}
2296
2297pub fn is_mise_shims_dir(path: &Path) -> bool {
2309 let resolved = replace_path(path);
2310 let user_shims = dirs::shims();
2311 let sys_shims = dirs::system_shims();
2312 if paths_eq(&resolved, &user_shims) || paths_eq(&resolved, &sys_shims) {
2313 return true;
2314 }
2315 let canon_shims = [user_shims, sys_shims]
2319 .into_iter()
2320 .filter(|shims| shims.symlink_metadata().is_ok())
2321 .map(|shims| canonicalize_or_self(&shims))
2322 .collect::<Vec<_>>();
2323 if canon_shims.is_empty() {
2324 return false;
2325 }
2326 let canon_input = canonicalize_path_entry_or_self(&resolved);
2327 canon_shims
2328 .iter()
2329 .any(|shims| paths_eq(&canon_input, shims))
2330}
2331
2332pub fn is_active_mise_shim(path: &Path) -> bool {
2336 env::MISE_SHIM_PATH
2337 .read()
2338 .unwrap()
2339 .as_ref()
2340 .is_some_and(|active| paths_eq(&canonicalize_or_self(path), &canonicalize_or_self(active)))
2341}
2342
2343pub fn path_env_without_shims() -> std::ffi::OsString {
2352 let filtered: Vec<_> = env::PATH_NON_PRISTINE
2353 .iter()
2354 .filter(|p| !is_mise_dispatch_dir(p))
2355 .cloned()
2356 .collect();
2357 std::env::join_paths(filtered)
2358 .unwrap_or_else(|_| std::env::var_os(&*env::PATH_KEY).unwrap_or_default())
2359}
2360
2361pub fn strip_shims_from_path(path_val: &str) -> String {
2365 let filtered = env::split_paths(path_val).filter(|p| !is_mise_dispatch_dir(p));
2366 std::env::join_paths(filtered)
2367 .unwrap_or_else(|_| std::ffi::OsString::from(path_val))
2368 .to_string_lossy()
2369 .into_owned()
2370}
2371
2372pub fn strip_dispatch_dirs_from_path(path_val: &str) -> String {
2376 let filtered = env::split_paths(path_val).filter(|p| !is_mise_dispatch_dir(p));
2377 std::env::join_paths(filtered)
2378 .unwrap_or_else(|_| std::ffi::OsString::from(path_val))
2379 .to_string_lossy()
2380 .into_owned()
2381}
2382
2383pub fn strip_shims_dir_from_path(path_val: &str) -> String {
2387 let filtered = env::split_paths(path_val).filter(|p| !is_mise_shims_dir(p));
2388 std::env::join_paths(filtered)
2389 .unwrap_or_else(|_| std::ffi::OsString::from(path_val))
2390 .to_string_lossy()
2391 .into_owned()
2392}
2393
2394pub fn is_command_wrapper_dir(path: &Path) -> bool {
2395 let resolved = replace_path(path);
2396 paths_eq(&resolved, &dirs::COMMAND_WRAPPERS)
2397 || paths_eq(
2398 &canonicalize_path_entry_or_self(&resolved),
2399 &canonicalize_or_self(&dirs::COMMAND_WRAPPERS),
2400 )
2401}
2402
2403pub fn is_mise_dispatch_dir(path: &Path) -> bool {
2404 is_mise_shims_dir(path) || is_command_wrapper_dir(path)
2405}
2406
2407pub fn which_no_shims<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
2411 let paths: Vec<PathBuf> = env::PATH_NON_PRISTINE
2412 .iter()
2413 .filter(|p| !is_mise_dispatch_dir(p))
2414 .cloned()
2415 .collect();
2416 _which(name, &paths)
2417}
2418
2419fn _which<P: AsRef<Path>>(name: P, paths: &[PathBuf]) -> Option<PathBuf> {
2420 let name = name.as_ref();
2421 paths.iter().find_map(|path| {
2422 let bin = path.join(name);
2423 if is_executable(&bin) { Some(bin) } else { None }
2424 })
2425}
2426
2427#[cfg(not(windows))]
2428pub fn executable_names(bin: &str) -> Vec<String> {
2429 vec![bin.to_string()]
2430}
2431
2432#[cfg(windows)]
2433pub fn executable_names(bin: &str) -> Vec<String> {
2434 let mut names = vec![bin.to_string()];
2435 if Path::new(bin).extension().is_none() {
2436 for ext in &Settings::get().windows_executable_extensions {
2437 let name = if ext.is_empty() {
2438 bin.to_string()
2439 } else {
2440 format!("{bin}.{ext}")
2441 };
2442 if !names.contains(&name) {
2443 names.push(name);
2444 }
2445 }
2446 }
2447 names
2448}
2449
2450const EXTRACT_MIN_LIMIT: u64 = if cfg!(test) {
2454 256 * 1024
2455} else {
2456 256 * 1024 * 1024
2457};
2458
2459fn extract_limit(input: &Path) -> Result<u64> {
2464 let ratio = Settings::get().extract_max_ratio;
2465 if ratio <= 0 {
2466 return Ok(u64::MAX);
2467 }
2468 let size = input.metadata()?.len();
2469 Ok(size.saturating_mul(ratio as u64).max(EXTRACT_MIN_LIMIT))
2470}
2471
2472fn extract_limit_error(limit: u64) -> std::io::Error {
2473 std::io::Error::other(format!(
2474 "unpacked size exceeds {limit} bytes, the limit set by the extract_max_ratio setting"
2475 ))
2476}
2477
2478struct LimitedReader<R> {
2480 inner: R,
2481 limit: u64,
2482 remaining: u64,
2483}
2484
2485impl<R: Read> LimitedReader<R> {
2486 fn new(inner: R, limit: u64) -> Self {
2487 Self {
2488 inner,
2489 limit,
2490 remaining: limit,
2491 }
2492 }
2493
2494 fn for_input(input: &Path, decoder: R) -> Result<Self> {
2496 Ok(Self::new(decoder, extract_limit(input)?))
2497 }
2498}
2499
2500impl<R: Read> Read for LimitedReader<R> {
2501 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2502 let n = self.inner.read(buf)?;
2503 self.remaining = self
2504 .remaining
2505 .checked_sub(n as u64)
2506 .ok_or_else(|| extract_limit_error(self.limit))?;
2507 Ok(n)
2508 }
2509}
2510
2511pub fn un_gz(input: &Path, dest: &Path) -> Result<()> {
2512 debug!("gunzip {} > {}", input.display(), dest.display());
2513 let f = File::open(input)?;
2514 let mut dec = LimitedReader::for_input(input, GzDecoder::new(f))?;
2515 let mut output = File::create(dest)?;
2516 std::io::copy(&mut dec, &mut output)
2517 .wrap_err_with(|| format!("failed to un-gzip: {}", display_path(input)))?;
2518 Ok(())
2519}
2520
2521pub fn un_xz(input: &Path, dest: &Path) -> Result<()> {
2522 debug!("xz -d {} -c > {}", input.display(), dest.display());
2523 let f = File::open(input)?;
2524 let mut dec = LimitedReader::for_input(input, xz2::read::XzDecoder::new(f))?;
2525 let mut output = File::create(dest)?;
2526 std::io::copy(&mut dec, &mut output)
2527 .wrap_err_with(|| format!("failed to un-xz: {}", display_path(input)))?;
2528 Ok(())
2529}
2530
2531const ZSTD_WINDOW_LOG_MAX: u32 = 30;
2538
2539fn zstd_decoder<R: Read>(reader: R) -> Result<zstd::Decoder<'static, BufReader<R>>> {
2540 let mut dec = zstd::Decoder::new(reader)?;
2541 dec.window_log_max(ZSTD_WINDOW_LOG_MAX)?;
2542 Ok(dec)
2543}
2544
2545pub fn un_zst(input: &Path, dest: &Path) -> Result<()> {
2546 debug!("zstd -d {} -c > {}", input.display(), dest.display());
2547 let f = File::open(input)?;
2548 let mut dec = LimitedReader::for_input(input, zstd_decoder(f)?)?;
2549 let mut output = File::create(dest)?;
2550 std::io::copy(&mut dec, &mut output)
2551 .wrap_err_with(|| format!("failed to un-zst: {}", display_path(input)))?;
2552 Ok(())
2553}
2554
2555pub fn un_bz2(input: &Path, dest: &Path) -> Result<()> {
2556 debug!("bzip2 -d {} -c > {}", input.display(), dest.display());
2557 let f = File::open(input)?;
2558 let mut dec = LimitedReader::for_input(input, BzDecoder::new(f))?;
2559 let mut output = File::create(dest)?;
2560 std::io::copy(&mut dec, &mut output)
2561 .wrap_err_with(|| format!("failed to un-bz2: {}", display_path(input)))?;
2562 Ok(())
2563}
2564
2565pub fn run_blocking<T>(f: impl FnOnce() -> T) -> T {
2574 match tokio::runtime::Handle::try_current() {
2575 Ok(h) if h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
2576 tokio::task::block_in_place(f)
2577 }
2578 _ => f(),
2579 }
2580}
2581
2582pub fn decompress_file(input: &Path, dest: &Path, format: ExtractionFormat) -> Result<()> {
2583 if let Some(parent) = dest.parent()
2584 && !parent.as_os_str().is_empty()
2585 {
2586 create_dir_all(parent)?;
2587 }
2588
2589 run_blocking(|| match format {
2590 ExtractionFormat::Gz => un_gz(input, dest),
2591 ExtractionFormat::Xz => un_xz(input, dest),
2592 ExtractionFormat::Zst => un_zst(input, dest),
2593 ExtractionFormat::Bz2 => un_bz2(input, dest),
2594 ExtractionFormat::Br | ExtractionFormat::Lz4 | ExtractionFormat::Sz => {
2595 bail!("{format} format not supported")
2596 }
2597 _ => bail!("unsupported compressed file format: {}", format),
2598 })
2599}
2600
2601#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
2602pub enum ExtractionFormat {
2603 #[strum(to_string = "tar.gz", serialize = "tgz")]
2604 TarGz,
2605 #[strum(serialize = "gz")]
2606 Gz,
2607 #[strum(to_string = "tar.xz", serialize = "txz")]
2608 TarXz,
2609 #[strum(serialize = "xz")]
2610 Xz,
2611 #[strum(to_string = "tar.bz2", serialize = "tbz2", serialize = "tbz")]
2612 TarBz2,
2613 #[strum(serialize = "bz2")]
2614 Bz2,
2615 #[strum(to_string = "tar.zst", serialize = "tzst")]
2616 TarZst,
2617 #[strum(serialize = "zst")]
2618 Zst,
2619 #[strum(serialize = "tar")]
2620 Tar,
2621 #[strum(to_string = "zip", serialize = "vsix")]
2622 Zip,
2623 #[strum(serialize = "7z")]
2624 SevenZip,
2625 #[strum(to_string = "tar.br", serialize = "tbr")]
2626 TarBr,
2627 #[strum(serialize = "br")]
2628 Br,
2629 #[strum(to_string = "tar.lz4", serialize = "tlz4")]
2630 TarLz4,
2631 #[strum(serialize = "lz4")]
2632 Lz4,
2633 #[strum(to_string = "tar.sz", serialize = "tsz")]
2634 TarSz,
2635 #[strum(serialize = "sz")]
2636 Sz,
2637 #[strum(serialize = "rar")]
2638 Rar,
2639 #[strum(serialize = "raw")]
2640 Raw,
2641}
2642
2643impl ExtractionFormat {
2644 pub fn from_file_name(filename: &str) -> Self {
2645 let filename = filename.to_lowercase();
2646
2647 if let Some(idx) = filename.rfind(".tar.") {
2648 let ext = &filename[idx + 1..];
2649 if let Some(fmt) = Self::from_ext(ext) {
2650 return fmt;
2651 }
2652 }
2653
2654 if let Some(ext) = Path::new(&filename).extension().and_then(|s| s.to_str()) {
2655 Self::from_ext(ext).unwrap_or(ExtractionFormat::Raw)
2656 } else {
2657 ExtractionFormat::Raw
2658 }
2659 }
2660
2661 pub fn from_ext(ext: &str) -> Option<Self> {
2662 ext.to_lowercase().parse().ok()
2663 }
2664
2665 pub fn detect(path: &Path, filename: &str) -> Result<Self> {
2670 match Self::from_file_name(filename) {
2671 ExtractionFormat::Raw => Ok(Self::from_magic(path)?.unwrap_or(ExtractionFormat::Raw)),
2672 format => Ok(format),
2673 }
2674 }
2675
2676 pub fn from_magic(path: &Path) -> Result<Option<Self>> {
2680 let mut magic = [0; 6];
2681 let len = File::open(path)?.read(&mut magic)?;
2682 let magic = &magic[..len];
2683 if magic.starts_with(b"PK\x03\x04") {
2684 return Ok(Some(ExtractionFormat::Zip));
2685 }
2686 let format = if magic.starts_with(&[0x1f, 0x8b]) {
2687 ExtractionFormat::TarGz
2688 } else if magic.starts_with(b"\xfd7zXZ\0") {
2689 ExtractionFormat::TarXz
2690 } else if magic.starts_with(b"BZh") {
2691 ExtractionFormat::TarBz2
2692 } else if magic.starts_with(&[0x28, 0xb5, 0x2f, 0xfd]) {
2693 ExtractionFormat::TarZst
2694 } else {
2695 ExtractionFormat::Tar
2696 };
2697 let mut header = Vec::with_capacity(512);
2698 let decoded = open_tar(format, path)?.take(512).read_to_end(&mut header);
2700 let is_tar = decoded.is_ok() && header.get(257..262) == Some(&b"ustar"[..]);
2701 Ok(is_tar.then_some(format))
2702 }
2703
2704 pub fn is_archive(&self) -> bool {
2705 self.is_tar_archive()
2706 || matches!(
2707 self,
2708 ExtractionFormat::Zip | ExtractionFormat::SevenZip | ExtractionFormat::Rar
2709 )
2710 }
2711
2712 pub fn is_tar_archive(&self) -> bool {
2713 matches!(
2714 self,
2715 ExtractionFormat::TarGz
2716 | ExtractionFormat::TarXz
2717 | ExtractionFormat::TarBz2
2718 | ExtractionFormat::TarZst
2719 | ExtractionFormat::Tar
2720 | ExtractionFormat::TarBr
2721 | ExtractionFormat::TarLz4
2722 | ExtractionFormat::TarSz
2723 )
2724 }
2725
2726 pub fn is_compressed_file(&self) -> bool {
2727 matches!(
2728 self,
2729 ExtractionFormat::Gz
2730 | ExtractionFormat::Xz
2731 | ExtractionFormat::Bz2
2732 | ExtractionFormat::Zst
2733 | ExtractionFormat::Br
2734 | ExtractionFormat::Lz4
2735 | ExtractionFormat::Sz
2736 )
2737 }
2738
2739 pub fn extension(&self) -> Option<String> {
2740 (*self != ExtractionFormat::Raw).then(|| self.to_string())
2741 }
2742}
2743
2744pub struct ExtractOptions<'a> {
2745 pub strip_components: usize,
2746 pub pr: Option<&'a dyn SingleReport>,
2747 pub preserve_mtime: bool,
2749}
2750
2751impl<'a> Default for ExtractOptions<'a> {
2752 fn default() -> Self {
2753 Self {
2754 strip_components: 0,
2755 pr: None,
2756 preserve_mtime: true,
2757 }
2758 }
2759}
2760
2761pub fn extract_archive(
2762 archive: &Path,
2763 dest: &Path,
2764 format: ExtractionFormat,
2765 opts: &ExtractOptions,
2766) -> Result<()> {
2767 match format {
2768 ExtractionFormat::TarGz
2769 | ExtractionFormat::TarXz
2770 | ExtractionFormat::TarBz2
2771 | ExtractionFormat::TarZst
2772 | ExtractionFormat::Tar
2773 | ExtractionFormat::TarBr
2774 | ExtractionFormat::TarLz4
2775 | ExtractionFormat::TarSz
2776 | ExtractionFormat::Raw => untar(archive, dest, format, opts),
2777 ExtractionFormat::Zip => unzip(archive, dest, opts),
2778 ExtractionFormat::SevenZip => un7z(archive, dest, opts),
2779 ExtractionFormat::Gz
2780 | ExtractionFormat::Xz
2781 | ExtractionFormat::Bz2
2782 | ExtractionFormat::Zst
2783 | ExtractionFormat::Br
2784 | ExtractionFormat::Lz4
2785 | ExtractionFormat::Sz => {
2786 bail!("extract_archive does not support compressed single-file format: {format}")
2787 }
2788 ExtractionFormat::Rar => bail!("rar format not supported"),
2789 }
2790}
2791
2792pub fn untar(
2793 archive: &Path,
2794 dest: &Path,
2795 format: ExtractionFormat,
2796 opts: &ExtractOptions,
2797) -> Result<()> {
2798 if !format.is_tar_archive() && format != ExtractionFormat::Raw {
2799 bail!("untar only supports tar formats, got {}", format);
2800 }
2801
2802 debug!("tar -xf {} -C {}", archive.display(), dest.display());
2803 if let Some(pr) = &opts.pr {
2804 pr.set_message(format!(
2805 "extract {}",
2806 archive.file_name().unwrap().to_string_lossy()
2807 ));
2808 }
2809
2810 let err = || {
2811 let archive = display_path(archive);
2812 let dest = display_path(dest);
2813 format!("failed to extract tar: {archive} to {dest}")
2814 };
2815
2816 run_blocking(|| {
2817 let tar = open_tar(format, archive)?;
2818 create_dir_all(dest).wrap_err_with(err)?;
2819 let mut unpack_opts = UnpackOptions::default();
2820 unpack_opts.preserve_mtime = opts.preserve_mtime;
2821 let saw_appledouble = Rc::new(Cell::new(false));
2822 unpack_opts.on_entry = Some(Box::new({
2823 let saw_appledouble = saw_appledouble.clone();
2824 move |entry| {
2825 trace!("extracting {}", entry.path.display());
2826 if is_appledouble_name(&entry.path) {
2827 saw_appledouble.set(true);
2828 }
2829 }
2830 }));
2831 let summary = Archive::new(tar)
2832 .unpack(dest, &mut unpack_opts)
2833 .wrap_err_with(err)?;
2834 debug!("tar extraction summary: {summary:?}");
2835 #[cfg(target_os = "macos")]
2837 if saw_appledouble.get() {
2838 merge_appledouble_files(dest).wrap_err_with(err)?;
2839 }
2840 strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
2841 format!(
2842 "failed to strip path components from tar archive: {}",
2843 display_path(archive)
2844 )
2845 })
2846 })
2847}
2848
2849fn is_appledouble_name(path: &Path) -> bool {
2852 path.file_name()
2853 .and_then(|name| name.to_str())
2854 .and_then(|name| name.strip_prefix("._"))
2855 .is_some_and(|described| !matches!(described, "" | "." | ".."))
2857}
2858
2859#[cfg(target_os = "macos")]
2864fn merge_appledouble_files(dir: &Path) -> Result<()> {
2865 use std::ffi::CString;
2866
2867 const MAGIC: [u8; 4] = [0x00, 0x05, 0x16, 0x07];
2869 let mut sidecars = vec![];
2870 for entry in WalkDir::new(dir) {
2871 let entry = entry?;
2872 if entry.file_type().is_file() && is_appledouble_name(entry.path()) {
2873 sidecars.push(entry.into_path());
2874 }
2875 }
2876 for sidecar in sidecars {
2877 let name = sidecar.file_name().unwrap().to_string_lossy();
2878 let target = sidecar.with_file_name(&name[2..]);
2879 if target.symlink_metadata().is_err() {
2880 continue;
2881 }
2882 let mut magic = [0u8; 4];
2883 if File::open(&sidecar)
2884 .and_then(|mut f| f.read_exact(&mut magic))
2885 .is_err()
2886 || magic != MAGIC
2887 {
2888 continue;
2889 }
2890 let from = CString::new(sidecar.as_os_str().as_bytes())?;
2891 let to = CString::new(target.as_os_str().as_bytes())?;
2892 let flags = nix::libc::COPYFILE_UNPACK
2893 | nix::libc::COPYFILE_NOFOLLOW
2894 | nix::libc::COPYFILE_ACL
2895 | nix::libc::COPYFILE_XATTR;
2896 let rc =
2898 unsafe { nix::libc::copyfile(from.as_ptr(), to.as_ptr(), std::ptr::null_mut(), flags) };
2899 if rc != 0 {
2900 warn!(
2901 "failed to apply {} to {}: {}",
2902 display_path(&sidecar),
2903 display_path(&target),
2904 std::io::Error::last_os_error()
2905 );
2906 continue;
2907 }
2908 if let Err(e) = remove_file(&sidecar) {
2909 warn!("failed to remove {}: {e:#}", display_path(&sidecar));
2910 }
2911 }
2912 Ok(())
2913}
2914
2915fn open_tar(format: ExtractionFormat, archive: &Path) -> Result<Box<dyn std::io::Read>> {
2919 let f = File::open(archive)?;
2920 let tar: Box<dyn std::io::Read> = match format {
2921 ExtractionFormat::TarGz | ExtractionFormat::Raw => Box::new(GzDecoder::new(f)),
2923 ExtractionFormat::TarXz => Box::new(xz2::read::XzDecoder::new(f)),
2924 ExtractionFormat::TarBz2 => Box::new(BzDecoder::new(f)),
2925 ExtractionFormat::TarZst => Box::new(zstd_decoder(f)?),
2926 ExtractionFormat::Tar => Box::new(f),
2927 ExtractionFormat::TarBr | ExtractionFormat::TarLz4 | ExtractionFormat::TarSz => {
2928 bail!("{format} format not supported")
2929 }
2930 ExtractionFormat::Gz
2931 | ExtractionFormat::Xz
2932 | ExtractionFormat::Bz2
2933 | ExtractionFormat::Zst
2934 | ExtractionFormat::Br
2935 | ExtractionFormat::Lz4
2936 | ExtractionFormat::Sz => {
2937 bail!("{} is not a tar archive", format)
2938 }
2939 ExtractionFormat::Zip => bail!("zip format not supported"),
2940 ExtractionFormat::SevenZip => bail!("7z format not supported"),
2941 ExtractionFormat::Rar => bail!("rar format not supported"),
2942 };
2943 Ok(Box::new(LimitedReader::for_input(archive, tar)?))
2944}
2945
2946fn reset_dir_mtime_to_now(dir: &Path) -> Result<()> {
2947 let now = SystemTime::now();
2948 for entry in WalkDir::new(dir) {
2949 let entry = entry?;
2950 if entry.file_type().is_file() {
2951 set_times(entry.path(), Some(now), Some(now))?;
2952 }
2953 }
2954 Ok(())
2955}
2956
2957fn strip_archive_path_components(dir: &Path, strip_depth: usize) -> Result<()> {
2958 if strip_depth == 0 {
2959 return Ok(());
2960 }
2961 if strip_depth > 1 {
2962 bail!("strip-components > 1 is not supported");
2963 }
2964
2965 let top_level_paths = ls(dir)?;
2966
2967 for path in top_level_paths {
2968 if !path.symlink_metadata()?.is_dir() {
2969 continue;
2970 }
2971
2972 let temp_path = path.with_file_name(format!(
2974 "{}_tmp_strip",
2975 path.file_name().unwrap().to_string_lossy()
2976 ));
2977 do_rename(&path, &temp_path)?;
2978
2979 for entry in ls(&temp_path)? {
2980 if let Some(file_name) = entry.file_name() {
2981 let dest_path = dir.join(file_name);
2982 do_rename(&entry, &dest_path)?;
2983 } else {
2984 continue;
2985 }
2986 }
2987
2988 remove_dir(temp_path)?;
2989 }
2990 Ok(())
2991}
2992
2993pub fn unzip(archive: &Path, dest: &Path, opts: &ExtractOptions<'_>) -> Result<()> {
2994 debug!("unzip {} -d {}", archive.display(), dest.display());
2996 if let Some(pr) = &opts.pr {
2997 pr.set_message(format!(
2998 "extract {}",
2999 archive.file_name().unwrap().to_string_lossy()
3000 ));
3001 }
3002 run_blocking(|| {
3003 let mut zip = ZipArchive::new(File::open(archive)?)
3004 .wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive)))?;
3005 let err = || format!("failed to extract zip archive: {}", display_path(archive));
3006 let limit = extract_limit(archive)?;
3010 let mut declared = 0u64;
3011 for i in 0..zip.len() {
3012 declared = declared.saturating_add(zip.by_index_raw(i).wrap_err_with(err)?.size());
3013 if declared > limit {
3014 return Err(eyre::Report::new(extract_limit_error(limit)).wrap_err(err()));
3015 }
3016 }
3017 zip.extract(dest).wrap_err_with(err)?;
3018
3019 if !opts.preserve_mtime {
3020 reset_dir_mtime_to_now(dest)?;
3021 }
3022
3023 strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
3024 format!(
3025 "failed to strip path components from zip archive: {}",
3026 display_path(archive)
3027 )
3028 })
3029 })
3030}
3031
3032const DMG_VOLUME_METADATA: &[&str] = &[
3036 ".background",
3037 ".com.apple.timemachine.donotpresent",
3038 ".com.apple.timemachine.supported",
3039 ".DocumentRevisions-V100",
3040 ".DS_Store",
3041 ".fseventsd",
3042 ".MobileBackups",
3043 ".Spotlight-V100",
3044 ".TemporaryItems",
3045 ".Trashes",
3046 ".VolumeIcon.icns",
3047 ".HFS+ Private Directory Data\r",
3048 ".HFS+ Private Data\r",
3049];
3050
3051fn copy_dmg_volume(volume: &Path, dest: &Path) -> Result<()> {
3052 copy_dir_all_preserve_symlinks_skipping(volume, dest, DMG_VOLUME_METADATA)
3053}
3054
3055fn dmg_attached_devices(info: &str, archive: &Path) -> Vec<String> {
3061 let archive = canonicalize_or_self(archive);
3062 let mut devices = vec![];
3063 let mut matches = false;
3064 let mut found_device = false;
3065 for line in info.lines() {
3066 if let Some(path) = line.strip_prefix("image-path") {
3067 let path = path.trim_start().trim_start_matches(':').trim();
3068 matches = paths_eq(&canonicalize_or_self(Path::new(path)), &archive);
3069 found_device = false;
3070 } else if matches
3071 && !found_device
3072 && let Some(dev) = line.split_whitespace().next()
3073 && dev.starts_with("/dev/disk")
3074 {
3075 devices.push(dev.to_string());
3076 found_device = true;
3077 }
3078 }
3079 devices
3080}
3081
3082fn detach_stale_dmg(archive: &Path) {
3083 let output = match std::process::Command::new("hdiutil").arg("info").output() {
3084 Ok(output) if output.status.success() => output,
3085 Ok(output) => {
3086 debug!("hdiutil info failed: {}", output.status);
3087 return;
3088 }
3089 Err(err) => {
3090 debug!("failed to run hdiutil info: {err}");
3091 return;
3092 }
3093 };
3094 let info = String::from_utf8_lossy(&output.stdout);
3095 for dev in dmg_attached_devices(&info, archive) {
3096 debug!("hdiutil detach {dev} (left attached by an interrupted run)");
3097 if let Err(err) = cmd!("hdiutil", "detach", "-force", dev.as_str()).run() {
3098 debug!("failed to detach stale DMG {dev}: {err}");
3099 }
3100 }
3101}
3102
3103pub fn un_dmg(archive: &Path, dest: &Path) -> Result<()> {
3104 debug!(
3105 "hdiutil attach -quiet -nobrowse -mountpoint {} {}",
3106 dest.display(),
3107 archive.display()
3108 );
3109 run_blocking(|| {
3110 let mut lock_path = canonicalize_or_self(archive).into_os_string();
3116 lock_path.push(".lock");
3117 let _lock = crate::lock_file::LockFile::at(Path::new(&lock_path)).lock()?;
3118 detach_stale_dmg(archive);
3119 let tmp = tempfile::TempDir::new()?;
3120 cmd!(
3121 "hdiutil",
3122 "attach",
3123 "-quiet",
3124 "-nobrowse",
3125 "-mountpoint",
3126 tmp.path(),
3127 archive.to_path_buf()
3128 )
3129 .env("PAGER", "cat")
3131 .stdin_bytes("Y\n")
3134 .run()?;
3135 let copy_result = copy_dmg_volume(tmp.path(), dest);
3136 let detach_result = cmd!("hdiutil", "detach", tmp.path()).run();
3137 match (copy_result, detach_result) {
3138 (Err(copy_err), Err(detach_err)) => Err(copy_err)
3139 .wrap_err_with(|| format!("additionally failed to detach DMG: {detach_err}")),
3140 (Err(copy_err), _) => Err(copy_err),
3141 (Ok(()), Err(detach_err)) => Err(detach_err.into()),
3142 (Ok(()), Ok(_)) => Ok(()),
3143 }
3144 })
3145}
3146
3147pub fn un_pkg(archive: &Path, dest: &Path) -> Result<()> {
3148 debug!(
3149 "pkgutil --expand-full {} {}",
3150 archive.display(),
3151 dest.display()
3152 );
3153 run_blocking(|| cmd!("pkgutil", "--expand-full", archive, dest).run())?;
3154 Ok(())
3155}
3156
3157pub fn un7z(archive: &Path, dest: &Path, opts: &ExtractOptions<'_>) -> Result<()> {
3158 if let Some(pr) = &opts.pr {
3159 pr.set_message(format!(
3160 "extract {}",
3161 archive.file_name().unwrap().to_string_lossy()
3162 ));
3163 }
3164 let resolved_dest;
3167 let dest = if dest
3168 .components()
3169 .any(|c| c == std::path::Component::ParentDir)
3170 {
3171 create_dir_all(dest)?;
3173 resolved_dest = dest
3174 .canonicalize()
3175 .wrap_err_with(|| format!("failed to resolve {}", display_path(dest)))?;
3176 &resolved_dest
3177 } else {
3178 dest
3179 };
3180 run_blocking(|| {
3181 let limit = extract_limit(archive)?;
3182 let mut remaining = limit;
3183 sevenz_rust2::decompress_file_with_extract_fn(archive, dest, |entry, reader, _| {
3184 let dest_path = dest.join(
3185 sanitize_7z_entry_path(entry.name())
3186 .map_err(|err| sevenz_rust2::Error::Other(format!("{err:#}").into()))?,
3187 );
3188 let mut reader = LimitedReader {
3190 inner: reader,
3191 limit,
3192 remaining,
3193 };
3194 let extracted = sevenz_rust2::default_entry_extract_fn(entry, &mut reader, &dest_path);
3195 remaining = reader.remaining;
3196 extracted
3197 })
3198 .wrap_err_with(|| format!("failed to extract 7z archive: {}", display_path(archive)))?;
3199
3200 if !opts.preserve_mtime {
3201 reset_dir_mtime_to_now(dest)?;
3202 }
3203
3204 strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
3205 format!(
3206 "failed to strip path components from 7z archive: {}",
3207 display_path(archive)
3208 )
3209 })
3210 })
3211}
3212
3213pub fn is_plain_file_name(name: &str) -> bool {
3219 if name.contains('/') || name.contains('\\') {
3222 return false;
3223 }
3224 let mut components = Path::new(name).components();
3225 matches!(
3226 (components.next(), components.next()),
3227 (Some(std::path::Component::Normal(_)), None)
3228 )
3229}
3230
3231pub fn is_safe_relative_path(path: &str) -> bool {
3235 if path.is_empty() {
3236 return false;
3237 }
3238 let normalized = path.replace('\\', "/");
3239 let bytes = normalized.as_bytes();
3240 if normalized.starts_with('/')
3241 || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
3242 {
3243 return false;
3244 }
3245 let mut components = Path::new(&normalized).components();
3246 matches!(components.next(), Some(std::path::Component::Normal(_)))
3247 && components.all(|component| matches!(component, std::path::Component::Normal(_)))
3248}
3249
3250pub fn ensure_symlinks_stay_within(root: &Path) -> Result<()> {
3267 if fs::symlink_metadata(root)?.file_type().is_symlink() {
3268 bail!("{} is a symlink", display_path(root));
3269 }
3270 #[cfg(unix)]
3271 rebase_absolute_symlinks_into_tree(root)?;
3272 let real_root = root.canonicalize()?;
3273 let mut dirs = vec![root.to_path_buf()];
3274 while let Some(dir) = dirs.pop() {
3275 for entry in fs::read_dir(&dir)? {
3276 let path = entry?.path();
3277 let kind = fs::symlink_metadata(&path)?.file_type();
3278 if kind.is_dir() {
3279 dirs.push(path);
3280 } else if kind.is_symlink() {
3281 let target = fs::read_link(&path)?;
3282 let base = path.parent().unwrap_or(root).canonicalize()?;
3283 if !link_target_stays_within(&real_root, root, &base, &target) {
3284 bail!(
3285 "symlink {} points outside of {}: {}",
3286 display_path(&path),
3287 display_path(root),
3288 target.display()
3289 );
3290 }
3291 }
3292 }
3293 }
3294 Ok(())
3295}
3296
3297#[cfg(unix)]
3303fn rebase_absolute_symlinks_into_tree(root: &Path) -> Result<()> {
3304 let real_root = root.canonicalize()?;
3305 loop {
3309 let mut rewrote = false;
3310 let mut dirs = vec![root.to_path_buf()];
3311 while let Some(dir) = dirs.pop() {
3312 for entry in fs::read_dir(&dir)? {
3313 let path = entry?.path();
3314 let kind = fs::symlink_metadata(&path)?.file_type();
3315 if kind.is_dir() {
3316 dirs.push(path);
3317 continue;
3318 }
3319 if !kind.is_symlink() {
3320 continue;
3321 }
3322 let target = fs::read_link(&path)?;
3323 let Ok(inner) = target.strip_prefix("/") else {
3324 continue;
3325 };
3326 let Some(inner) = inner.to_str().filter(|inner| is_safe_relative_path(inner))
3327 else {
3328 continue;
3329 };
3330 let candidate = root.join(inner);
3331 if fs::symlink_metadata(&candidate).is_err() {
3332 continue;
3333 }
3334 let parent = path.parent().unwrap_or(root);
3335 let replacement = relative_path(parent, &candidate);
3336 let base = parent.canonicalize()?;
3337 if link_target_stays_within(&real_root, root, &base, &replacement) {
3338 make_symlink(&replacement, &path)?;
3339 rewrote = true;
3340 }
3341 }
3342 }
3343 if !rewrote {
3344 return Ok(());
3345 }
3346 }
3347}
3348
3349#[cfg(unix)]
3356pub fn rebase_guest_rootfs_absolute_symlinks(root: &Path) -> Result<()> {
3357 if fs::symlink_metadata(root)?.file_type().is_symlink() {
3358 bail!("{} is a symlink", display_path(root));
3359 }
3360 let mut dirs = vec![root.to_path_buf()];
3361 while let Some(dir) = dirs.pop() {
3362 for entry in fs::read_dir(&dir)? {
3363 let path = entry?.path();
3364 let kind = fs::symlink_metadata(&path)?.file_type();
3365 if kind.is_dir() {
3366 dirs.push(path);
3367 } else if kind.is_symlink() {
3368 let target = fs::read_link(&path)?;
3369 if target.is_absolute() {
3370 let replacement = if target == Path::new("/") {
3371 relative_path(path.parent().unwrap(), root)
3372 } else {
3373 let target = target.strip_prefix(Path::new("/")).unwrap();
3374 let target = target.to_str().ok_or_else(|| {
3375 eyre::eyre!(
3376 "absolute symlink target is not valid UTF-8: {}",
3377 path.display()
3378 )
3379 })?;
3380 if !is_safe_relative_path(target) {
3381 bail!(
3382 "absolute symlink target escapes guest rootfs: {} -> /{}",
3383 display_path(&path),
3384 target
3385 );
3386 }
3387 relative_path(path.parent().unwrap(), &root.join(target))
3388 };
3389 make_symlink(&replacement, &path)?;
3390 }
3391 }
3392 }
3393 }
3394 Ok(())
3395}
3396
3397#[cfg(unix)]
3398fn relative_path(from: &Path, to: &Path) -> PathBuf {
3399 use std::path::Component;
3400
3401 let from = from.components().collect::<Vec<_>>();
3402 let to = to.components().collect::<Vec<_>>();
3403 let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
3404 let mut relative = PathBuf::new();
3405 for component in &from[common..] {
3406 if matches!(component, Component::Normal(_)) {
3407 relative.push("..");
3408 }
3409 }
3410 for component in &to[common..] {
3411 relative.push(component.as_os_str());
3412 }
3413 if relative.as_os_str().is_empty() {
3414 PathBuf::from(".")
3415 } else {
3416 relative
3417 }
3418}
3419
3420fn link_target_stays_within(root: &Path, given_root: &Path, base: &Path, target: &Path) -> bool {
3427 use std::collections::VecDeque;
3428 use std::path::Component;
3429 const MAX_LINKS: usize = 40;
3430 let parts = |path: &Path| -> VecDeque<PathBuf> {
3431 path.components()
3432 .map(|part| PathBuf::from(part.as_os_str()))
3433 .collect()
3434 };
3435 let mut current = base.to_path_buf();
3436 let mut pending = parts(target);
3437 let mut followed = 0;
3438 while let Some(part) = pending.pop_front() {
3439 let Some(component) = part.components().next() else {
3440 continue;
3441 };
3442 match component {
3443 Component::Prefix(_) | Component::RootDir => {
3444 let absolute: PathBuf = std::iter::once(part).chain(pending.drain(..)).collect();
3448 let Some(rest) = [root, given_root]
3449 .into_iter()
3450 .find_map(|root| absolute.strip_prefix(root).ok())
3451 else {
3452 return false;
3453 };
3454 pending = parts(rest);
3455 current = root.to_path_buf();
3456 }
3457 Component::CurDir => {}
3458 Component::ParentDir => {
3459 current.pop();
3460 }
3461 Component::Normal(name) => {
3462 let candidate = current.join(name);
3463 match fs::read_link(&candidate) {
3464 Ok(link) => {
3465 followed += 1;
3466 if followed > MAX_LINKS {
3467 return true;
3468 }
3469 for part in link.components().rev() {
3470 pending.push_front(PathBuf::from(part.as_os_str()));
3471 }
3472 }
3473 Err(_) => current = candidate,
3474 }
3475 }
3476 }
3477 if !current.starts_with(root) {
3478 return false;
3479 }
3480 }
3481 true
3482}
3483
3484fn sanitize_7z_entry_path(path: &str) -> Result<PathBuf> {
3485 let normalized = PathBuf::from(path.replace('\\', "/"));
3486 let mut safe_path = PathBuf::new();
3487
3488 for component in normalized.components() {
3489 match component {
3490 std::path::Component::Normal(part) => safe_path.push(part),
3491 std::path::Component::CurDir => {}
3492 std::path::Component::ParentDir
3493 | std::path::Component::RootDir
3494 | std::path::Component::Prefix(_) => {
3495 bail!("7z archive entry path escapes extraction directory: {path}")
3496 }
3497 }
3498 }
3499
3500 Ok(safe_path)
3501}
3502
3503pub fn split_file_name(path: &Path) -> (String, String) {
3504 let file_name = path.file_name().unwrap().to_string_lossy();
3505 let (file_name_base, ext) = file_name
3506 .split_once('.')
3507 .unwrap_or((file_name.as_ref(), ""));
3508 (file_name_base.to_string(), ext.to_string())
3509}
3510
3511pub fn same_file(a: &Path, b: &Path) -> bool {
3512 a == b || desymlink_path(a) == desymlink_path(b)
3513}
3514
3515pub fn path_starts_with_resolved(path: &Path, prefix: &Path) -> bool {
3518 path.starts_with(prefix) || desymlink_path(path).starts_with(desymlink_path(prefix))
3519}
3520
3521fn resolve_path_with_existing_prefix(path: &Path) -> PathBuf {
3522 let mut resolved = if path.is_relative() {
3523 env::current_dir().unwrap_or_default()
3524 } else {
3525 PathBuf::new()
3526 };
3527 let mut components = path.components();
3528 while let Some(component) = components.next() {
3529 if matches!(component, std::path::Component::CurDir) {
3530 continue;
3531 }
3532 #[cfg(windows)]
3533 if matches!(
3534 component,
3535 std::path::Component::Prefix(_) | std::path::Component::RootDir
3536 ) {
3537 resolved.push(component.as_os_str());
3540 continue;
3541 }
3542 let candidate = resolved.join(component.as_os_str());
3543 match candidate.canonicalize() {
3544 Ok(candidate) => resolved = candidate,
3545 Err(_) => {
3546 #[cfg(windows)]
3547 {
3548 let mut raw = resolved.into_os_string();
3552 if Path::new(&raw).file_name().is_some() {
3553 raw.push("\\");
3554 }
3555 raw.push(component.as_os_str());
3556 for component in components {
3557 raw.push("\\");
3558 raw.push(component.as_os_str());
3559 }
3560 resolved = raw.into();
3561 }
3562 #[cfg(not(windows))]
3563 {
3564 resolved.push(component.as_os_str());
3565 resolved.extend(components.map(|component| component.as_os_str()));
3566 }
3567 break;
3568 }
3569 }
3570 }
3571 resolved
3572}
3573
3574pub fn desymlink_path(p: &Path) -> PathBuf {
3575 if p.is_symlink()
3576 && let Ok(target) = fs::read_link(p)
3577 {
3578 let target = if target.is_absolute() {
3579 target
3580 } else {
3581 p.parent().unwrap_or_else(|| Path::new("")).join(target)
3582 };
3583 return target
3584 .canonicalize()
3585 .unwrap_or_else(|_| resolve_path_with_existing_prefix(&target));
3586 }
3587 p.canonicalize()
3588 .unwrap_or_else(|_| resolve_path_with_existing_prefix(p))
3589}
3590
3591static DESYMLINKED: Lazy<Mutex<(u64, HashMap<PathBuf, PathBuf>)>> = Lazy::new(Default::default);
3596
3597pub fn desymlink_path_cached(p: &Path) -> PathBuf {
3601 if !p.is_absolute() {
3602 return desymlink_path(p);
3603 }
3604 let generation = {
3605 let cache = DESYMLINKED.lock().unwrap();
3606 if let Some(resolved) = cache.1.get(p) {
3607 return resolved.clone();
3608 }
3609 cache.0
3610 };
3611 let resolved = desymlink_path(p);
3612 if p.exists() {
3613 let mut cache = DESYMLINKED.lock().unwrap();
3614 if cache.0 == generation {
3615 cache.1.insert(p.to_path_buf(), resolved.clone());
3616 }
3617 }
3618 resolved
3619}
3620
3621pub fn clear_desymlink_cache() {
3625 let mut cache = DESYMLINKED.lock().unwrap();
3626 cache.0 += 1;
3627 cache.1.clear();
3628}
3629
3630pub fn clone_dir(from: &PathBuf, to: &PathBuf) -> Result<()> {
3631 if cfg!(target_os = "macos") {
3632 cmd!("/bin/cp", "-cR", from, to).run()?;
3633 } else if cfg!(windows) {
3634 let output = cmd!("robocopy", from, to, "/MIR").unchecked().run()?;
3637 if !matches!(output.status.code(), Some(0..=7)) {
3639 eyre::bail!("robocopy failed with {}", output.status);
3640 }
3641 } else {
3642 cmd!("cp", "--reflink=auto", "-r", from, to).run()?;
3643 }
3644 Ok(())
3645}
3646
3647fn skip_curdir_components(path: &Path) -> impl Iterator<Item = std::path::Component<'_>> {
3650 path.components()
3651 .skip_while(|c| matches!(c, std::path::Component::CurDir))
3652}
3653
3654pub fn inspect_tar_contents(
3661 archive: &Path,
3662 format: ExtractionFormat,
3663) -> Result<Vec<(String, bool)>> {
3664 let tar = open_tar(format, archive)?;
3665 let mut archive = Archive::new(tar);
3666 let mut top_level_components = std::collections::HashMap::new();
3667
3668 for entry in archive.entries()? {
3669 let entry = entry?;
3670 let path = entry.path()?;
3671 let entry_type = entry.entry_type();
3672
3673 let mut components = skip_curdir_components(&path);
3675
3676 if let Some(first_component) = components.next() {
3677 let name = first_component.as_os_str().to_string_lossy().to_string();
3678
3679 let is_directory = entry_type == EntryType::Directory || components.next().is_some();
3682
3683 let existing = top_level_components.entry(name).or_insert(false);
3686 *existing = *existing || is_directory;
3687 if top_level_components.len() > 1 {
3688 break;
3689 }
3690 }
3691 }
3692
3693 Ok(top_level_components.into_iter().collect())
3694}
3695
3696pub fn inspect_zip_contents(archive: &Path) -> Result<Vec<(String, bool)>> {
3700 let f = File::open(archive)?;
3701 let mut archive = ZipArchive::new(f)
3702 .wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive)))?;
3703 let mut top_level_components = std::collections::HashMap::new();
3704
3705 for i in 0..archive.len() {
3706 let file = archive.by_index(i)?;
3707 if let Some(path) = file.enclosed_name() {
3708 let mut components = skip_curdir_components(&path);
3710
3711 if let Some(first_component) = components.next() {
3712 let name = first_component.as_os_str().to_string_lossy().to_string();
3713
3714 let is_directory = file.is_dir() || components.next().is_some();
3717
3718 let existing = top_level_components.entry(name).or_insert(false);
3719 *existing = *existing || is_directory;
3720 if top_level_components.len() > 1 {
3721 break;
3722 }
3723 }
3724 }
3725 }
3726
3727 Ok(top_level_components.into_iter().collect())
3728}
3729
3730pub fn inspect_7z_contents(archive: &Path) -> Result<Vec<(String, bool)>> {
3733 let sevenz = sevenz_rust2::Archive::open(archive)?;
3734 let mut top_level_components = std::collections::HashMap::new();
3735
3736 for file in &sevenz.files {
3737 let path = sanitize_7z_entry_path(file.name())?;
3738
3739 let mut components = skip_curdir_components(&path);
3741
3742 if let Some(first_component) = components.next() {
3743 let name = first_component.as_os_str().to_string_lossy().to_string();
3744 let is_directory = file.is_directory() || components.next().is_some();
3746
3747 let existing = top_level_components.entry(name).or_insert(false);
3748 *existing = *existing || is_directory;
3749 if top_level_components.len() > 1 {
3750 break;
3751 }
3752 }
3753 }
3754
3755 Ok(top_level_components.into_iter().collect())
3756}
3757
3758pub fn should_strip_components(archive: &Path, format: ExtractionFormat) -> Result<bool> {
3760 let top_level_entries = match format {
3761 ExtractionFormat::Zip => inspect_zip_contents(archive)?,
3762 ExtractionFormat::SevenZip => inspect_7z_contents(archive)?,
3763 _ => inspect_tar_contents(archive, format)?,
3764 };
3765
3766 if top_level_entries.len() == 1 {
3768 let (_, is_directory) = &top_level_entries[0];
3769 Ok(*is_directory)
3770 } else {
3771 Ok(false)
3772 }
3773}
3774
3775#[derive(Debug, Clone)]
3776pub struct ArchiveContent {
3777 pub name: String,
3778 pub sha256: String,
3779}
3780
3781const ARCHIVE_CONTENT_MAX_RATIO: u64 = 100;
3789const ARCHIVE_CONTENT_MIN_BUDGET: u64 = 256 * 1024 * 1024;
3791
3792pub fn archive_content_files(
3799 archive_path: &Path,
3800 format: ExtractionFormat,
3801 strip_components: usize,
3802) -> Result<Vec<ArchiveContent>> {
3803 if strip_components > 1 {
3804 bail!("content-level SLSA verification only supports strip_components values of 0 or 1");
3805 }
3806 let budget = fs::metadata(archive_path)?
3807 .len()
3808 .saturating_mul(ARCHIVE_CONTENT_MAX_RATIO)
3809 .max(ARCHIVE_CONTENT_MIN_BUDGET);
3810
3811 match format {
3812 ExtractionFormat::TarGz
3813 | ExtractionFormat::TarXz
3814 | ExtractionFormat::TarBz2
3815 | ExtractionFormat::TarZst
3816 | ExtractionFormat::Tar
3817 | ExtractionFormat::TarBr
3818 | ExtractionFormat::TarLz4
3819 | ExtractionFormat::TarSz => {
3820 archive_content_files_tar(archive_path, format, strip_components, budget)
3821 }
3822 ExtractionFormat::Zip => archive_content_files_zip(archive_path, strip_components, budget),
3823 ExtractionFormat::SevenZip => {
3824 bail!("content-level SLSA verification does not support 7z archives")
3825 }
3826 ExtractionFormat::Gz
3827 | ExtractionFormat::Xz
3828 | ExtractionFormat::Bz2
3829 | ExtractionFormat::Zst
3830 | ExtractionFormat::Br
3831 | ExtractionFormat::Lz4
3832 | ExtractionFormat::Sz
3833 | ExtractionFormat::Raw => {
3834 bail!("content-level SLSA verification only supports archive formats")
3835 }
3836 ExtractionFormat::Rar => bail!("rar format not supported"),
3837 }
3838}
3839
3840fn archive_content_files_tar(
3841 archive_path: &Path,
3842 format: ExtractionFormat,
3843 strip_components: usize,
3844 mut budget: u64,
3845) -> Result<Vec<ArchiveContent>> {
3846 let tar = open_tar(format, archive_path)?;
3847 let mut archive = Archive::new(tar);
3848 let mut files = Vec::new();
3849
3850 for entry in archive.entries()? {
3851 let mut entry = entry?;
3852 let path = entry.path()?.into_owned();
3853 let entry_type = entry.entry_type();
3854 if entry_type == EntryType::Directory {
3855 continue;
3856 }
3857 if entry_type != EntryType::File {
3858 bail!(
3859 "content-level SLSA verification does not support non-regular archive entry: {}",
3860 path.display()
3861 );
3862 }
3863 let name = normalize_archive_content_path(&path, strip_components)?;
3864 let size = entry.size();
3867 let sha256 = sha256_reader(&mut entry, size, &mut budget)?;
3868 files.push(ArchiveContent { name, sha256 });
3869 }
3870
3871 validate_archive_content_files(files)
3872}
3873
3874fn archive_content_files_zip(
3875 archive_path: &Path,
3876 strip_components: usize,
3877 mut budget: u64,
3878) -> Result<Vec<ArchiveContent>> {
3879 let f = File::open(archive_path)?;
3880 let mut archive = ZipArchive::new(f)
3881 .wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive_path)))?;
3882 let mut files = Vec::new();
3883
3884 for i in 0..archive.len() {
3885 let mut file = archive.by_index(i)?;
3886 if file.is_symlink() {
3890 bail!(
3891 "content-level SLSA verification does not support symlink archive entry: {}",
3892 file.name().as_deref().unwrap_or("<unreadable name>")
3893 );
3894 }
3895 if file.is_dir() {
3896 continue;
3897 }
3898 let enclosed_name = file.enclosed_name().ok_or_else(|| {
3899 eyre::eyre!(
3900 "content-level SLSA verification rejected unsafe zip path: {}",
3901 file.name().as_deref().unwrap_or("<unreadable name>")
3902 )
3903 })?;
3904 let name = normalize_archive_content_path(&enclosed_name, strip_components)?;
3905 let size = file.size();
3906 let sha256 = sha256_reader(&mut file, size, &mut budget)?;
3907 files.push(ArchiveContent { name, sha256 });
3908 }
3909
3910 validate_archive_content_files(files)
3911}
3912
3913fn sha256_reader(reader: &mut impl Read, size: u64, budget: &mut u64) -> Result<String> {
3919 let over_budget = || {
3920 eyre::eyre!(
3921 "content-level SLSA verification rejected an archive that unpacks to more than {ARCHIVE_CONTENT_MAX_RATIO} times its size"
3922 )
3923 };
3924 if size > *budget {
3925 return Err(over_budget());
3926 }
3927 let mut hasher = Sha256::new();
3928 let mut buf = [0; 8192];
3929 loop {
3930 let n = reader.read(&mut buf)?;
3931 if n == 0 {
3932 break;
3933 }
3934 *budget = budget.checked_sub(n as u64).ok_or_else(over_budget)?;
3935 hasher.update(&buf[..n]);
3936 }
3937 Ok(hex::encode(hasher.finalize()))
3938}
3939
3940fn validate_archive_content_files(files: Vec<ArchiveContent>) -> Result<Vec<ArchiveContent>> {
3941 if files.is_empty() {
3942 bail!("content-level SLSA verification found no regular files in archive");
3943 }
3944 let mut names = std::collections::HashSet::new();
3945 for file in &files {
3946 if !names.insert(file.name.clone()) {
3947 bail!(
3948 "content-level SLSA verification found duplicate installed archive path: {}",
3949 file.name
3950 );
3951 }
3952 }
3953 Ok(files)
3954}
3955
3956fn normalize_archive_content_path(path: &Path, strip_components: usize) -> Result<String> {
3957 let mut parts = Vec::new();
3958 for component in skip_curdir_components(path) {
3959 match component {
3960 std::path::Component::Normal(part) => parts.push(part.to_string_lossy().to_string()),
3961 std::path::Component::CurDir => {}
3962 std::path::Component::ParentDir
3963 | std::path::Component::RootDir
3964 | std::path::Component::Prefix(_) => {
3965 bail!(
3966 "content-level SLSA verification rejected unsafe archive path: {}",
3967 path.display()
3968 )
3969 }
3970 }
3971 }
3972 if strip_components > parts.len() {
3973 bail!(
3974 "content-level SLSA verification stripped all components from archive path: {}",
3975 path.display()
3976 );
3977 }
3978 let parts = &parts[strip_components..];
3979 if parts.is_empty() {
3980 bail!(
3981 "content-level SLSA verification stripped all components from archive path: {}",
3982 path.display()
3983 );
3984 }
3985 Ok(parts.join("/"))
3986}
3987
3988#[cfg(test)]
3989mod tests;