Skip to main content

mise_util/
file.rs

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/// Windows' `MAX_PATH`. Not a limit mise imposes — the point below is that some paths hit it long
65/// before others do. It counts UTF-16 code units and includes the terminating NUL, so a path of
66/// exactly `MAX_PATH` is already one too many.
67///
68/// Shared with mise's `cli::self_update`, which needs the same number for the opposite reason:
69/// the file APIs can be escaped past this with a `\\?\` prefix, which is why `std::fs` copes with
70/// long paths, but `CreateProcess` has no such escape hatch and simply will not start an
71/// executable whose path reaches it.
72#[cfg(windows)]
73pub const MAX_PATH: usize = 260;
74
75/// Why a Windows file operation on `path` probably failed, when the error says something a reader
76/// cannot act on.
77///
78/// `None` on unix, always: deleting a running binary succeeds there, and `MAX_PATH` does not
79/// exist. Splitting the remedy by platform rather than the wording follows
80/// [`make_executable_hint`], where `chmod +x` was not merely unavailable on Windows but the wrong
81/// instruction.
82///
83/// The error codes are the ones already spoken elsewhere in this file — see [`do_rename`] and
84/// `should_retry_atomic_persist`, which retry on the same pair. This answers a different question
85/// about them: not whether to try again, but what to tell the user when trying again will not help.
86#[cfg(windows)]
87fn windows_io_hint(path: &Path, err: &std::io::Error) -> Option<String> {
88    use std::os::windows::ffi::OsStrExt;
89
90    // ERROR_ACCESS_DENIED (5) / ERROR_SHARING_VIOLATION (32). Unlike the transient locks that
91    // `do_rename` retries through, a file held open by a running process stays held, so this is a
92    // message rather than a retry.
93    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    // Only the errors Windows actually reports for an over-long path. Without this the branch
103    // fires on anything that happens to occur deep in a tree -- a genuinely missing directory
104    // would be answered with advice about path length.
105    //
106    // ERROR_PATH_NOT_FOUND (3) is what was measured; ERROR_INVALID_NAME (123) and
107    // ERROR_FILENAME_EXCED_RANGE (206) are the other two Windows uses for the same cause. `3` is
108    // ambiguous by nature -- a path can be both long and absent -- so the wording below suggests
109    // rather than asserts.
110    if !matches!(err.raw_os_error(), Some(3) | Some(123) | Some(206)) {
111        return None;
112    }
113    // UTF-16 code units, which is what the limit counts. `OsStr::len()` is WTF-8 bytes on Windows,
114    // so a path with any non-ASCII in it would measure long before Windows thought so.
115    let units = path.as_os_str().encode_wide().count();
116    if units < MAX_PATH - 16 {
117        return None;
118    }
119    // Measured: `std::fs` itself copes well past `MAX_PATH` -- create_dir_all, write and rename all
120    // succeeded at 490 units with long paths disabled -- so a "path not found" this close to the
121    // limit is more likely the length than the missing directory it appears to be.
122    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
135/// Attach [`windows_io_hint`] to `err`, if it has anything to say about this path.
136/// `msg`, plus whatever [`windows_io_hint`] can say about `err` at `path`.
137///
138/// `pub(crate)` because the operations that need it are not all in this module: `tempfile`'s
139/// persist is used directly by the downloader too, and that is the call that fails first as a
140/// path approaches `MAX_PATH`.
141pub 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    // `symlink_metadata`, not `metadata`: the latter resolves the entry before deciding what to do
151    // with it, so a link that no longer points anywhere reports `NotFound` and falls through to
152    // the no-op arm below — the entry stays on disk and the caller is told nothing. `mise link`
153    // creates exactly such an entry whenever its target is moved or deleted. Resolving also made
154    // the `is_symlink` test unreachable, since a followed link never reports as one.
155    match fs::symlink_metadata(path).map(|m| m.file_type()) {
156        // Removing the link, never what it points at. On Windows `make_symlink` writes a junction,
157        // which is a directory carrying a reparse point: `remove_file` refuses it outright
158        // (measured: `PermissionDenied`, live or dangling), so this goes through the helper that
159        // deletes by handle after checking the reparse tag.
160        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            // `map_err` rather than `wrap_err_with`: the hint depends on the error, and
169            // `wrap_err_with`'s closure is not given it.
170            remove_dir_all_restoring_owner_access(path).map_err(|e| {
171                let msg = with_io_hint(
172                    // Not "rm -rf": mise calls `remove_dir_all`, and on Windows it is naming a
173                    // command the reader does not have.
174                    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
186/// [`fs::remove_dir_all`], retried once after the owner regains full access to every
187/// directory in the tree. An archive can install directories without the owner's write bit (a
188/// sealed `0555` runtime, or Go's read-only module cache), and nothing can be unlinked from such
189/// a directory, so `mise uninstall` failed with "Permission denied" on what mise had installed.
190fn 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/// Give the owner read, write and search access to the directory `name` under `parent` and to
215/// every directory below it. Each directory is opened relative to the descriptor of the one
216/// holding it with `O_NOFOLLOW` and changed through its own descriptor, as [`remove_all_at`]
217/// walks a tree, so neither a link in the tree nor one swapped in mid-walk can redirect the
218/// change to a directory outside it. A directory the owner cannot open stops the walk.
219#[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/// Remove `name` under `parent` and, for a directory, everything below it,
258/// without following a symlink anywhere in the tree. Every entry is resolved
259/// relative to a descriptor for the directory holding it: a symlink is
260/// unlinked, never descended into, and a directory is opened with
261/// `O_NOFOLLOW`, so an entry swapped for a symlink mid-walk fails the open
262/// instead of redirecting the removal. Directories are removed bottom-up. A
263/// missing `name` is not an error.
264#[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    // Compare the whole type field: sockets and block devices share the
273    // directory bit.
274    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
302/// Removes a path, retrying when a concurrent writer recreates directory entries while
303/// [`fs::remove_dir_all`] is running.
304///
305/// This remains a strict removal operation: if the directory is still non-empty after the
306/// retries are exhausted, the final error is returned to the caller.
307pub 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/// Removes a path whose kind the caller does not know, resolving it first.
332///
333/// Resolving is why this is not what a cache or install walk wants: a link is
334/// judged by what it points at. The remaining caller knows it is handling a
335/// staged Homebrew payload, which has no links pointing out of it.
336#[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
397/// Whether a directory entry is there at all, without resolving it.
398///
399/// [`Path::exists`] answers about a link's *target*, so it is false for one whose target is gone —
400/// and that entry is exactly the thing a caller asking "is there something here to remove, or to
401/// tell the user about?" needs to find.
402pub 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    // Not `exists()`: a link whose target is gone is still an entry to remove, and reporting
409    // nothing to do would leave it behind exactly where a user went looking for it.
410    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
417/// Renames `from` to `to`.
418///
419/// Warning: this is the raw `rename(2)`/`fs::rename` behavior. It is atomic on a
420/// single filesystem, but it will fail if `from` and `to` are on different
421/// mounts. If you need a cross-device-safe move, use [`move_file`] instead.
422///
423/// On Windows, retries transient failures (`ERROR_ACCESS_DENIED` / `ERROR_SHARING_VIOLATION`)
424/// that commonly occur when antivirus or the OS still holds handles to files in the source
425/// directory (e.g. after extracting an archive).
426pub 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    // Renaming a freshly extracted directory fails while antivirus is still scanning the files
448    // inside it, which takes tens of seconds for a multi-gigabyte archive such as flutter's.
449    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                // ERROR_ACCESS_DENIED (5) or ERROR_SHARING_VIOLATION (32):
457                // likely a transient lock from antivirus or the OS.
458                // Exponential backoff from 50ms, capped at 5s (about a minute in total).
459                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
476/// Moves a path, falling back to copy+remove when source and destination are on different filesystems.
477///
478/// This preserves the normal `rename` behavior when possible, but avoids cross-device failures
479/// (`ErrorKind::CrossesDevices`) when `from` and `to` live on separate mounts (for example, when
480/// downloads are cached on one volume and installs are written to another). Directory fallbacks
481/// preserve symlinks and file/directory permissions.
482pub 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
524/// Give `from`'s content a second name at `to` without duplicating it, falling back to a
525/// copy.
526///
527/// A hard link needs both paths on one volume and a filesystem that supports them, so
528/// failing is an ordinary outcome rather than an error worth surfacing.
529pub 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
552/// Copies `from` into `to` like [`copy_dir_all_preserve_symlinks`], without
553/// descending into top-level entries of `from` named in `skip_top_level`.
554fn 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    // Apply directory permissions after copying children so read-only source
590    // directories do not prevent populating their destination.
591    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    /// Atomically renames this already-written replacement into place.
611    pub fn commit(self) -> Result<()> {
612        // The hint matters most here. `tempfile`'s persist does not get the extended-length path
613        // handling `std::fs` applies, so this is the operation that fails first as a path
614        // approaches `MAX_PATH` -- measured breaking at a 253-character target while `fs::rename`
615        // on the same tree succeeded at 415.
616        persist_atomic(self.temporary, &self.target).map_err(|e| {
617            let msg = format!("failed atomic write: {}", display_path(&self.target));
618            // Resolve the hint before `wrap_err` takes `e` by value: `downcast_ref` borrows it,
619            // and doing both in one expression leaves the borrow alive across the move.
620            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
631/// Writes and syncs a complete replacement beside `path` without changing `path` yet.
632///
633/// New files use ordinary write permissions subject to the process umask. Replacements preserve
634/// the destination's existing Unix permissions.
635pub 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
646/// Writes a complete replacement beside `path`, then renames it into place without syncing
647/// either. A crash of this process never leaves a partial file, but a power loss can lose the
648/// write. For derived files written in bulk, which `sync_filesystem` then makes durable at
649/// once on Linux: syncing each one costs a journal commit per file.
650pub 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/// Makes every write on the filesystem holding `path` durable, for a batch written with
659/// [`write_atomic_unsynced`]. Only Linux can flush one filesystem and wait for it: elsewhere
660/// `sync()` may return before the writes reach the disk, so a batch syncs each file instead.
661#[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
713/// Writes a complete replacement beside `path`, then atomically renames it into place.
714pub 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
789/// Largest config file mise reads: `mise.toml`, `.tool-versions`, idiomatic
790/// version files, `mise.lock`, `.miserc.toml` and task TOML. These are found in
791/// whatever directory mise runs in, before anything is trusted, and are read
792/// whole, so without a limit a checkout could make every prompt allocate as much
793/// as the file holds. Real files are kilobytes: mise's own lockfile, covering
794/// dozens of tools on every platform, is about 70 KiB, and a config file a
795/// person writes is a few KiB. 16 MiB leaves more than two hundred times that
796/// while keeping the cost of a hostile file small.
797pub 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
807/// Opens `path` only if it is a regular file, judged from the opened handle so
808/// that nothing swapped in after an earlier check is read instead. On unix the
809/// open does not block, so a pipe put in the file's place cannot hang it.
810pub 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
822/// [`read_to_string`] for a config file, refusing one that is not a regular
823/// file or is larger than [`CONFIG_FILE_LIMIT`].
824pub 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
831/// [`read_config_to_string`] for a file that may not exist: `None` when it
832/// does not. mise looks for several such files on every run, and builds no
833/// error for the missing ones: with `RUST_BACKTRACE` set, every error resolves
834/// a backtrace from the binary's symbols, which costs milliseconds.
835pub 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
860/// Fails when `path` is a config file larger than [`CONFIG_FILE_LIMIT`], for
861/// readers that open the file themselves. A file that cannot be inspected is
862/// left to the reader to report.
863pub 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
871/// [`read_config_to_string`] on the blocking pool, for async callers: the same
872/// regular-file check and size limit, judged on the opened handle.
873pub 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/// The bytes of a UTF-8 byte-order mark, as [`decode_text`] matches them below.
881#[cfg(windows)]
882pub const UTF8_BOM_BYTES: [u8; 3] = [0xef, 0xbb, 0xbf];
883
884/// `s` without a leading UTF-8 byte-order mark.
885///
886/// Needed wherever mise matches on the *start* of a line it read from disk. `str::trim` does not
887/// help: U+FEFF does not carry the Unicode `White_Space` property, so a mark left in front of a
888/// `#!` or a `#MISE` defeats every prefix test silently. The writers that leave one there are
889/// ordinary on Windows -- see [`decode_text`], which names them.
890pub fn strip_utf8_bom(s: &str) -> &str {
891    s.strip_prefix('\u{feff}').unwrap_or(s)
892}
893
894/// Decode text that may begin with a byte-order mark.
895///
896/// `std`'s UTF-8-only readers reject UTF-16 outright, which is how a checksum file sank an install
897/// in #5399: PowerShell shipped `hashes.sha256` as UTF-16LE and mise stopped at "stream did not
898/// contain valid UTF-8". Windows PowerShell 5.1's `Out-File` writes UTF-16LE by default, so any
899/// project generating checksums that way produces the same thing.
900///
901/// Only a BOM switches the encoding. Detecting UTF-16 without one means guessing from the density
902/// of NUL bytes, which can misfire on binary input; `Out-File` always writes a BOM, so the guess
903/// buys nothing here. Input with no BOM is decoded as UTF-8, exactly as before.
904pub 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/// The UTF-16 encoding `path` announces with a byte-order mark, if it announces one.
933///
934/// The marks are the ones [`decode_text`] matches, kept here rather than spelled out again at the
935/// call site so there is one description of what a mark looks like.
936///
937/// A UTF-8 mark is deliberately not reported. `has_shebang` already looks past that one, so a
938/// file carrying it is executable and never reaches a caller that needs to explain why it is not.
939/// (Named without a link: that function is `#[cfg(windows)]` and this doc is built on unix too.)
940///
941/// Compiled for tests on every platform so the byte matching is checked everywhere, but only used
942/// on Windows: on unix the execute bit decides what is executable, and a UTF-16 script with that
943/// bit set fails at exec rather than being skipped.
944#[cfg(any(windows, test))]
945pub fn utf16_bom(path: &Path) -> Option<&'static str> {
946    // `read_to_end` on a `take`, not `read_exact`: a one-byte file is a legitimate answer of
947    // "no mark", and `read_exact` would fail on it. Same shape as `has_shebang` below.
948    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
963/// [`read_to_string`], but tolerant of a byte-order mark. See [`decode_text`].
964///
965/// Only reads *from disk* need this. Bodies fetched over HTTP already arrive decoded: reqwest's
966/// `text()` goes through `text_with_charset` -> `encoding_rs::Encoding::decode`, which sniffs a BOM
967/// and lets it override the declared charset. `std::fs::read_to_string` has no such step, and that
968/// asymmetry is the only reason this function exists — reaching for it on an `HTTP.get_text` result
969/// would be redundant.
970pub 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 not exists error
1002            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
1011/// A path formatted for a person to read: `$HOME` becomes `~`, a Windows extended-length prefix
1012/// is dropped, and separators settle on the host's.
1013///
1014/// The separator step lives here rather than in [`PathExt::display_user`] because that one also
1015/// feeds strings mise *matches* rather than shows — see [`crate::path::settle_display_separators`].
1016pub 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        // Both halves take the host's separator. Hardcoding `./` and printing the remainder raw
1032        // produced `./mise-tasks\build` on Windows. Byte-identical off Windows, where
1033        // `MAIN_SEPARATOR` is `/` and nothing is rewritten.
1034        Ok(rel) => format!(".{}{}", std::path::MAIN_SEPARATOR, display_path(rel)),
1035        Err(_) => display_path(path),
1036    }
1037}
1038
1039/// replaces $HOME in a string with "~" and $PATH with "$PATH", generally used to clean up output
1040/// after it is rendered
1041pub 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
1046/// replaces "~" with $HOME
1047///
1048/// The remainder is re-joined one component at a time rather than pushed as a
1049/// single slice. `Path::strip_prefix` returns a raw subslice of the input — it
1050/// trims the remainder's leading/trailing separators but leaves interior ones
1051/// untouched — so `HOME.join(rest)` only prepends a separator. On Windows that
1052/// made `~/.local/share/mise` expand to `C:\Users\me\.local/share/mise`, and
1053/// since `MISE_DATA_DIR` flows into `dirs::DATA`/`INSTALLS`, that mixed-separator
1054/// path surfaced verbatim in `mise where`, `mise which`, `mise ls --json`,
1055/// `mise bin-paths`, shims, and error messages.
1056///
1057/// Rebuilding from `components()` also folds redundant separators and `.`
1058/// segments; `..` is preserved. On unix the result is byte-identical to the old
1059/// behavior for any ordinary input.
1060///
1061/// Paths without a `~/` prefix are returned unchanged: a user-supplied
1062/// `C:/mise/data` stays exactly as typed. This is a tilde expander, not a path
1063/// normalizer — one caller passes glob patterns through it
1064/// (`config::expand_task_include`).
1065pub 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
1079/// Compare two paths for filesystem equivalence, taking platform conventions
1080/// into account. macOS volumes (HFS+/APFS) and Windows volumes are
1081/// case-insensitive by default, so a byte-equal comparison can fail when
1082/// inputs differ only by case (e.g. `/Users/Foo/...` vs `/Users/foo/...`
1083/// when `$HOME` is mixed-case in the user's environment but the resolved
1084/// path uses a different case).
1085///
1086/// On case-insensitive platforms, comparison is done over `Path::components()`
1087/// with each component lowercased — this also folds trailing slashes,
1088/// redundant separators, and (on Windows) `/` vs `\` since `Path::components`
1089/// treats both as separators.
1090///
1091/// This is the right comparator for "is this PATH entry the shims
1092/// directory?" checks, where a false negative leads to mise's shim being
1093/// inherited by a child process and recursing infinitely.
1094pub 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
1109/// Compare configured storage paths by both platform-aware spelling and
1110/// resolved filesystem identity. The latter matters when distributions
1111/// deliberately point user and system storage at the same directory through
1112/// different symlinks.
1113pub 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
1135/// Sets `path`'s access and modification times, following symlinks. A `None` time is left as
1136/// it is. Only the right to write attributes is needed, so on Windows this works on a directory
1137/// and on a read-only file (git's `.git/objects` files in a zipped checkout, for one), which a
1138/// write handle would refuse with "Access is denied".
1139pub 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
1147/// Like [`set_times`], but sets a symlink's own times and leaves its target alone.
1148pub 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/// Synchronizes a directory to disk, ensuring that filesystem metadata changes
1219/// (such as file creations or deletions) are persisted.
1220///
1221/// This is important after operations like removing files to ensure the changes
1222/// are immediately visible to other processes, e.g. to avoid race conditions.
1223///
1224/// # Platform-specific behavior
1225///
1226/// - **Unix/Linux**: Performs an fsync on the directory file descriptor, which
1227///   ensures directory metadata (like file listings) is written to disk.
1228/// - **Windows**: Not implemented (no-op).
1229///
1230/// # Errors
1231///
1232/// On Unix systems, returns an error if the directory cannot be opened or synced.
1233/// On Windows, always succeeds.
1234#[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    // Not implemented on Windows
1247    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
1272/// Names of the directories in `dir`, including links that lead to one. A link whose target is
1273/// gone is dropped: it is not a directory a caller can read a plugin, a cached download or another
1274/// version manager's install out of. (Version listing keeps those; it has its own scan.)
1275pub 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        // `entry.file_type()` describes the entry itself; `entry.path().is_dir()` resolves it.
1285        let ft = entry.file_type()?;
1286        if ft.is_dir() || (ft.is_symlink() && entry.path().is_dir()) {
1287            // A name that is not UTF-8 cannot name a plugin, tool or version, so skip it.
1288            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    // Create the symlink at a unique temporary name in the same directory, then
1316    // atomically rename it over `link`. rename(2) replaces an existing path in a
1317    // single step, so concurrent mise processes racing to create the same link all
1318    // succeed (last writer wins) instead of one failing with EEXIST — which showed
1319    // up as spurious "failed to ln -sf ...: File exists (os error 17)" warnings
1320    // when several mise invocations start at once (e.g. spawning a git worktree,
1321    // #10292). Approach based on the closed PR #9701.
1322    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    // `junction::create` makes the directory before it sets the reparse point,
1391    // so a later failure (a target too long for the reparse buffer) leaves a
1392    // plain directory that would pass for an installed version. Remove only what
1393    // this call created, and only if it is still an empty plain directory.
1394    // `AlreadyExists` means `create_dir` itself failed because something else holds the
1395    // name (another process won the race), so there is nothing of ours to remove.
1396    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        // remove existing file if exists
1427        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    // Windows aliases created before runtime links became junctions are plain
1435    // files holding the target path, so both forms are read here.
1436    // One look at the path answers both questions: what is not a link is
1437    // what following it would find.
1438    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/// Links `link` to the directory `target` (a relative target is taken from
1461/// `link`'s parent) for a runtime alias such as `installs/node/latest`.
1462///
1463/// On Windows this is a real junction, which tools that enumerate the path
1464/// (IDE SDK selectors) can follow; it never falls back to a text file. A failure
1465/// is returned so the caller can warn and carry on without the link.
1466#[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            // Something else made the slot in the meantime: replace it below.
1481            Err(_) if fs::symlink_metadata(link).is_ok() => {}
1482            Err(err) => return Err(err),
1483        }
1484    }
1485    // Replacing a link: build the new one beside it first, so a failure to
1486    // create it leaves the working link in place instead of an empty slot.
1487    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    // What the link pointed at, to put it back if the swap cannot be completed.
1495    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` retries the transient locks antivirus and the OS put on a fresh entry.
1501        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/// Removes a link made by [`make_dir_link`], or an older text-file alias.
1515#[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/// Whether `a` and `b` are spelled the same. Paths that differ only in case are different
1569/// paths on Unix.
1570#[cfg(unix)]
1571pub fn same_path_ignoring_case(a: &Path, b: &Path) -> bool {
1572    a == b
1573}
1574
1575/// Whether `a` and `b` are spelled the same apart from letter case, compared the way Windows
1576/// compares file names: ordinal, so code points it keeps distinct (the Kelvin sign and `K`)
1577/// stay distinct.
1578#[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/// Whether `a` and `b` name the same location. Paths that differ only in case are different
1621/// paths on Unix.
1622#[cfg(unix)]
1623pub fn same_location_ignoring_case(a: &Path, b: &Path) -> bool {
1624    a == b
1625}
1626
1627/// Whether `a` and `b`, spelled the same apart from letter case, name the same location: the
1628/// same file in a directory that ignores case when they exist, and otherwise the same place in
1629/// such a directory. A directory marked case-sensitive can hold `foo` and `Foo` as two files,
1630/// or as two hard links to one.
1631#[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        // two hard links can be one file under names a case-sensitive directory tells apart
1641        Ok(same) => same && !respelled_in_case_sensitive_dir(a, b),
1642        Err(_) => dangling_paths_share_case_insensitive_parent(a, b),
1643    }
1644}
1645
1646/// Whether a component that `a` and `b` spell differently sits in a directory marked
1647/// case-sensitive, where the two spellings are two names. Only the directories holding a
1648/// respelled component matter: `C:\Work\sensitive\x` and `C:\WORK\sensitive\x` are one file
1649/// when `C:\` ignores case, whatever `sensitive` is marked.
1650#[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    // POSIX has no standard unlink-by-handle operation, so a concurrent replacement can still
1790    // occur between this check and remove_file. The latter cannot remove directories; callers
1791    // must keep the parent directory protected from untrusted writers.
1792    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/// How to make `path` count as executable, phrased for the platform the user is on.
1888///
1889/// Lives beside [`is_executable`] because it has to track it: the two platforms answer that
1890/// question by different rules, so the remedy differs too. `chmod +x` is not merely unavailable on
1891/// Windows — it is the wrong instruction, since the Windows branch never looks at a permission bit.
1892#[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    // A shebang the file already carries, in an encoding `has_shebang` reads as bytes and so
1900    // cannot see. Windows PowerShell 5.1's `>` and `Out-File` write UTF-16LE by default, which
1901    // makes this the shell that ships with the OS producing a file mise then tells the user to
1902    // add a shebang to. Naming the encoding is the fix; telling them to add what is already
1903    // there is not. Said whether or not a shebang is in there, because either way the encoding
1904    // is what has to change first.
1905    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        // Read from the setting rather than hardcoded: a user who has changed
1915        // `windows_executable_extensions` would otherwise be told to use extensions mise will not
1916        // accept from them.
1917        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/// Check if a file starts with a shebang (#!), allowing for a leading UTF-8 byte-order mark.
1939///
1940/// Reads only the first 5 bytes to minimize I/O during task discovery: two for the `#!`, plus
1941/// three for a mark in front of it. Reading just the two saw `EF BB` and answered "no shebang",
1942/// which on Windows is the whole of [`is_executable`] for an extensionless file -- so a task
1943/// written by `Out-File -Encoding utf8` disappeared from `mise tasks` with no diagnostic, while
1944/// the same file on unix was a task because there the execute bit decides.
1945///
1946/// A `read_exact` here would fail outright on a file shorter than the buffer, so read what is
1947/// available instead. A UTF-16 mark is deliberately not accepted: no interpreter mise dispatches
1948/// to can run a UTF-16 script, so treating one as a task would only trade silence for a
1949/// confusing failure at exec time.
1950#[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/// Extensions `std::process::Command` can start from a path alone on Windows: `exe` and `com`
1965/// natively, `bat` and `cmd` because std routes those through cmd.exe with escaped arguments.
1966/// Anything else needs an interpreter named for it — `pwsh -File` for a `.ps1`,
1967/// `cscript` for a `.vbs`, whatever a shebang asks for.
1968///
1969/// A fixed list on purpose. It describes what the OS can start, which
1970/// `windows_executable_extensions` has no say over: that setting decides what mise *treats* as
1971/// executable. Deriving it the other way round — subtracting known interpreter-only extensions
1972/// from the setting — happened to be right for the default list and wrong for any other, since a
1973/// user who added `sh` or `py` was then answered "yes, `CreateProcess` can start this" and the
1974/// task died with "not a valid Win32 application" instead of using its shebang.
1975///
1976/// `pub(crate)` so `task::task_executor` can assert that `shell_from_extension` names an
1977/// interpreter for every default extension this list excludes.
1978#[cfg(windows)]
1979pub const OS_LAUNCHABLE_EXTENSIONS: [&str; 4] = ["exe", "com", "bat", "cmd"];
1980
1981/// Whether the OS can start a file with this extension without an interpreter.
1982///
1983/// Compared case-insensitively, the way [`has_known_executable_extension`] does: Windows
1984/// extensions are not case-sensitive, so `PIPX.PS1` is the same file as `pipx.ps1`.
1985#[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
1992/// Check if a file can be executed directly by the OS without a shell wrapper.
1993/// On Unix, this checks the executable permission bit.
1994/// On Windows, it takes both questions in turn: does mise treat this extension as executable
1995/// (`windows_executable_extensions`, which a user may narrow), and can the OS actually start it
1996/// ([`OS_LAUNCHABLE_EXTENSIONS`], which a user may not widen)?
1997///
1998/// Distinct from [`is_executable`], which on Windows deliberately also accepts a
1999/// shebang-only file. Callers that hand the path to `Command::new` need this one:
2000/// `CreateProcess` can run `.exe`/`.com`/`.cmd`/`.bat`, but not a `.ps1`, a `.vbs`,
2001/// or a script that only carries a shebang.
2002///
2003/// Note that on Windows this never touches the filesystem — it is pure extension
2004/// inspection, so it answers true for a `foo.exe` that does not exist. `is_executable`
2005/// checks `is_file()` inline; this one does not. A lookup that walks candidate paths must
2006/// compose the two, which is what [`is_spawnable`] does.
2007pub 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
2022/// True when the OS will accept `path` as the program argument of a spawn.
2023pub 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/// Add execute bits along with the matching read bits.
2042///
2043/// A file that only receives the execute bits (`mode | 0o111`) can end up executable but not
2044/// readable (e.g. a `0o600` tempfile becomes `0o711`). For interpreted executables like PHP PHARs
2045/// the interpreter must be able to *read* the file, so any class that gains execute must also gain
2046/// read. See https://github.com/jdx/mise/discussions/11108.
2047#[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
2073/// A ceiling path as given, with `~` expanded, and its target when it goes
2074/// through a symlink. The directories `all_dirs` walks come from the current
2075/// directory, which the kernel reports with symlinks resolved, so a ceiling
2076/// written through a symlink would never match one of them.
2077pub fn ceiling_path_forms(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
2078    let path = replace_path(path);
2079    // dunce leaves out the `\\?\` prefix std adds on Windows, which the ancestors
2080    // of the current directory never have.
2081    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            // A start directory std canonicalized on Windows begins with `\\?\`, which
2099            // `ceiling_path_forms` leaves out.
2100            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; // in tests, do not recurse further than ./test
2169        }
2170        if !self.current_dir.pop() {
2171            return None;
2172        }
2173        self.next()
2174    }
2175}
2176
2177/// returns the first executable in PATH
2178/// will not include mise bin paths or other paths added by mise
2179pub 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
2194/// Returns the first directly spawnable executable in PATH, expanding configured
2195/// executable extensions on Windows when `name` has no extension.
2196pub fn which_spawnable(name: &str) -> Option<PathBuf> {
2197    _which_spawnable(name, &env::PATH)
2198}
2199
2200/// Like [`which_spawnable`], but searching `paths` rather than PATH.
2201/// For directories that PATH may not list yet, such as one a package manager
2202/// has just installed into.
2203pub 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
2217/// returns the first executable in PATH
2218/// will include mise bin paths or other paths added by mise
2219pub fn which_non_pristine<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
2220    _which(name, &env::PATH_NON_PRISTINE)
2221}
2222
2223/// Canonicalize a path and cache successful resolutions for the current process.
2224///
2225/// Use this for repeated comparisons against stable roots or PATH entries. Failed
2226/// canonicalizations are not cached because many callers handle paths that may be
2227/// created later in the same process.
2228pub 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
2245/// Canonicalize a PATH entry for comparison against mise-managed directories.
2246///
2247/// Under WSL the default Windows PATH interop appends folders on `/mnt/<drive>`
2248/// (a 9p mount where every path component costs a round trip to Windows), and
2249/// resolving each of them added roughly half a second to every `mise activate`
2250/// and `hook-env`. Those folders are never symlinks to a mise-managed directory,
2251/// so their literal path is returned as the comparison key instead of resolving
2252/// them. The literal path still matches a mise directory that itself lives on a
2253/// drive mount (e.g. an install root symlinked to `/mnt/c`).
2254pub 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
2261/// Like [`canonicalize_path_entry`], falling back to the original path.
2262pub 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
2273/// True for `/mnt/<drive letter>/...` without `..` components, which could
2274/// lead out of the mount and so still need resolving.
2275fn 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
2291/// Canonicalize a path using the process cache, falling back to the original
2292/// path when canonicalization fails.
2293pub fn canonicalize_or_self(path: &Path) -> PathBuf {
2294    canonicalize_cached(path).unwrap_or_else(|| path.to_path_buf())
2295}
2296
2297/// Returns true if `path` is one of mise's shim directories.
2298///
2299/// The configured user and system shim directories qualify. An active shim outside these
2300/// configured directories is rejected per candidate instead of treating its
2301/// entire parent directory as shims, since that directory may also contain
2302/// legitimate executables.
2303///
2304/// Uses `paths_eq` + `replace_path` for the fast path (expands `~`,
2305/// case-insensitive on macOS/Windows), then falls back to `canonicalize_or_self`
2306/// so symlinked roots (e.g. `/usr/local/share` → `/private/usr/local/share` on
2307/// macOS) still match — the cached helper keeps this off the filesystem hot path.
2308pub 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    // A shims directory that does not exist has no other spelling, and the
2316    // comparison above already covered its own. Asking for its canonical form
2317    // would walk every parent only to fail, once for each `PATH` entry.
2318    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
2332/// Returns true if `path` resolves to the shim that delegated to this mise
2333/// process. Candidate-level filtering avoids excluding legitimate sibling
2334/// executables that happen to share a directory with the active shim.
2335pub 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
2343/// Build a PATH value with mise shims filtered out, suitable for passing to
2344/// subprocesses via `.env("PATH", ...)`. Prevents infinite recursion when a
2345/// subprocess (e.g. `gh auth token`, `git credential fill`) resolves to a
2346/// mise shim that re-enters mise.
2347///
2348/// Uses the current process's PATH (`PATH_NON_PRISTINE`). For stripping
2349/// shims from an arbitrary PATH string (e.g. from `PRISTINE_ENV`), use
2350/// `strip_shims_from_path` instead.
2351pub 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
2361/// Strip mise shims from an arbitrary PATH string. Use this when the
2362/// subprocess receives a custom env map (e.g. `PRISTINE_ENV`) rather
2363/// than inheriting the current process's PATH.
2364pub 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
2372/// Strip every mise dispatch directory (shims and command wrappers) from PATH.
2373/// This lets the command resolve a tool managed by mise or fall through to
2374/// rustup/the system without going through a shim or a wrapper.
2375pub 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
2383/// Strip only the shims directory from PATH, keeping the command wrapper directory. A command
2384/// wrapper's children use this so a wrapper they run still applies; the wrapper that started
2385/// them is skipped by name instead (`__MISE_ACTIVE_WRAPPERS`).
2386pub 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
2407/// returns the first executable in PATH, excluding the mise shim directories
2408/// use this for internal tool lookups to avoid recursive shim invocations
2409/// (shims call `mise exec`, which would re-enter the same code path)
2410pub 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
2450/// Unpacking may always produce this much, whatever `extract_max_ratio` allows:
2451/// a small download that compresses well is no threat to the disk. Lower in
2452/// tests, which have to unpack more than this to reach the limit.
2453const EXTRACT_MIN_LIMIT: u64 = if cfg!(test) {
2454    256 * 1024
2455} else {
2456    256 * 1024 * 1024
2457};
2458
2459/// The most bytes unpacking `input` may produce: `extract_max_ratio` times its
2460/// size, and at least [`EXTRACT_MIN_LIMIT`]. Release archives rarely unpack to
2461/// more than 10 times their size, while 1 GiB of zeroes is under 1 KiB of
2462/// bzip2, so without a bound a small download could fill the disk.
2463fn 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
2478/// Fails once more than `remaining` bytes have been read from `inner`.
2479struct 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    /// Bounds what `decoder` may produce from the compressed file `input`.
2495    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
2531/// The largest zstd window mise decodes: 2^30 (1 GiB). libzstd refuses frames
2532/// with a window above 2^27 (128 MiB) unless the caller raises the limit, the
2533/// same limit the `zstd` CLI lifts with `--long`. Large release archives such
2534/// as LLVM's are compressed with a 1 GiB window. Going no higher bounds the
2535/// memory an archive can make the decoder allocate, and 2^30 is also the most
2536/// libzstd supports on 32-bit platforms.
2537const 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
2565/// Run long blocking work (archive extraction, subprocess waits) without tying up a tokio worker.
2566///
2567/// Extraction can take seconds and is called directly from async install paths, where it would
2568/// otherwise block a runtime worker thread for the duration. On mise's multi-threaded runtime
2569/// (see `main.rs`), `tokio::task::block_in_place` hands the worker's core off to another thread so
2570/// concurrent tasks (progress bars, downloads, other installs) keep running. Outside a runtime, or
2571/// on a current-thread runtime (e.g. `#[tokio::test]`), `block_in_place` would panic, so fall back
2572/// to running the closure inline.
2573pub 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    /// The format a download's name implies, falling back to its leading
2666    /// bytes when the name carries no known extension — as brew does, since
2667    /// URLs such as `codeload.github.com/<owner>/<repo>/tar.gz/refs/tags/<tag>`
2668    /// end without one.
2669    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    /// Identify an archive by its content. A compressed stream only counts as
2677    /// a tarball when its payload opens with a ustar header, so a bare
2678    /// compressed file or a binary is never mistaken for an archive.
2679    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        // a stream that fails to decode is not an archive we can unpack
2699        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    /// When false, files will be extracted with current timestamp instead of archive's mtime
2748    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        // Before stripping, which unwraps a top-level directory away from its `._<dir>` sidecar.
2836        #[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
2849/// Whether `path` names an AppleDouble sidecar (`._<name>`), which bsdtar on macOS writes to
2850/// carry a file's xattrs, such as the code signatures of a signed `.app` bundle.
2851fn 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        // `._.` and `._..` would name the directory itself or its parent.
2856        .is_some_and(|described| !matches!(described, "" | "." | ".."))
2857}
2858
2859/// Folds each AppleDouble sidecar under `dir` into the file it describes and removes it, as
2860/// macOS `tar` does. Left as plain files, the sidecars are extra files inside a signed bundle,
2861/// which invalidates its seal so that macOS kills the binary on launch. A sidecar that is not
2862/// valid AppleDouble, or that has no file to describe, is left alone.
2863#[cfg(target_os = "macos")]
2864fn merge_appledouble_files(dir: &Path) -> Result<()> {
2865    use std::ffi::CString;
2866
2867    // AppleDouble magic number, big endian.
2868    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        // SAFETY: both paths are NUL-terminated and outlive the call, and a null state is allowed.
2897        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
2915/// The decoded tar stream of `archive`, bounded by [`extract_limit`]. Sparse
2916/// members are the exception: jdx-tar makes up their holes itself, and writes
2917/// them as holes, so they never pass through this reader.
2918fn 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        // TODO: we probably shouldn't assume raw is tar.gz, but this was to retain existing behavior
2922        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        // rename the directory to a temp name to avoid conflicts when moving files
2973        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    // TODO: show progress
2995    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        // The zip crate fails an entry that unpacks to more than the size its
3007        // central directory record declares, so those sizes bound what
3008        // `extract` writes, even when several records share one member.
3009        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
3032/// Volume metadata that macOS and disk-image tools leave at a DMG's root. It is
3033/// never part of an artifact, and some of it cannot be read: `.Trashes` ships
3034/// with mode 0333 in some images. This is Homebrew's `DMG_METADATA` list.
3035const 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
3055/// Whole-disk devices that `hdiutil info` reports as still attached from `archive`.
3056///
3057/// An interrupted extraction leaves its image attached, and attaching the same image again
3058/// fails with "Resource busy". In the text output each image block starts with an
3059/// `image-path` line, followed by one line per entity; the first `/dev/diskN` is the disk.
3060fn 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        // Hold a lock on the archive so another live extraction of the same image is never
3111        // mistaken for an interrupted one by `detach_stale_dmg`.
3112        // The lock sits next to the archive, not in the cache dir, so processes with different
3113        // MISE_CACHE_DIRs still coordinate on the same image.
3114        // Canonicalized so a symlink to the archive shares its lock.
3115        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        // Display licenses without an interactive pager before accepting them.
3130        .env("PAGER", "cat")
3131        // DMGs can require license acceptance even with -quiet. Supply one
3132        // answer directly so unattended installs do not wait for terminal input.
3133        .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    // sevenz-rust2 rejects any `..` in an entry's destination path, but `dest`
3165    // can legitimately contain one (e.g. a localized mise under `tools/../.mise`).
3166    let resolved_dest;
3167    let dest = if dest
3168        .components()
3169        .any(|c| c == std::path::Component::ParentDir)
3170    {
3171        // canonicalize follows symlinks, so `..` means what the caller's path means
3172        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            // One budget across entries, not one per entry.
3189            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
3213/// Whether `name` is a plain file name: exactly one normal path component, with
3214/// no separators, parent/root components, or drive prefixes on any platform.
3215/// Use to validate user-supplied names (e.g. `bin`, `rename_exe`, `filter_bins`
3216/// tool options) before joining them onto a directory, so a value like
3217/// `../evil` or `/abs/path` cannot escape it.
3218pub fn is_plain_file_name(name: &str) -> bool {
3219    // Reject both separators explicitly: `\` is a legal file-name character on
3220    // Unix, but these names come from cross-platform config.
3221    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
3231/// Whether `path` is a non-empty relative path containing only normal
3232/// components. Both slash styles are treated as separators so config values are
3233/// validated consistently across platforms.
3234pub 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
3250/// Fails if a symlink under `root` points outside of it.
3251///
3252/// Archive extraction keeps symlink entries whatever their target, and the steps
3253/// that run after it (renaming or chmodding the binary, creating `.mise-bins`,
3254/// writing state files) open paths below the install directory by name, which
3255/// follows those links. Call this on an extracted tree before any such step.
3256///
3257/// Each target is resolved component by component, following every link on the
3258/// way, so chains and links through linked directories are checked; components
3259/// that do not exist are taken as written.
3260///
3261/// On Unix, an absolute link whose target (read as a path below `root`) exists
3262/// inside the tree is first rewritten to a relative link, because packages that
3263/// ship an `/opt/<name>` tree link into it with absolute paths. The rewritten
3264/// link is checked like any other, and an absolute link to a path that is not in
3265/// the tree is left as it is and refused.
3266pub 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/// Rewrites absolute symlinks whose target exists inside `root` (as `root` plus
3298/// the target) to relative links, so an archive that links `usr/bin/tool` to
3299/// `/opt/pkg/bin/tool` installs with a link into its own tree. Links to paths
3300/// that are not in the tree, contain `..`, or would still leave `root` once
3301/// rewritten are left untouched for [`ensure_symlinks_stay_within`] to refuse.
3302#[cfg(unix)]
3303fn rebase_absolute_symlinks_into_tree(root: &Path) -> Result<()> {
3304    let real_root = root.canonicalize()?;
3305    // A link can depend on another absolute link that is rewritten later in the
3306    // walk, so repeat until a pass rewrites nothing. Each rewrite turns an
3307    // absolute link relative, so this ends.
3308    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/// Rewrites absolute symlinks in a guest root filesystem to relative links.
3350///
3351/// A guest root filesystem is later mounted as `/`, so `/bin/tool` in it
3352/// means `<root>/bin/tool`, not the host's `/bin/tool`. Rebase those links
3353/// before checking the enclosing archive with [`ensure_symlinks_stay_within`]
3354/// so the installed tree never contains a link that resolves outside it.
3355#[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
3420/// Resolves `target` as seen from the directory `base` (already real), following
3421/// every link on the way, and reports whether each step stays under `root` (the
3422/// real path of the tree, which is `given_root` as the caller spelled it).
3423/// Components that do not exist are taken as written. A chain of links that loops
3424/// without leaving `root` is harmless, so the walk stops after `MAX_LINKS` links
3425/// and accepts it.
3426fn 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                // An absolute path stays inside only if it names the tree's
3445                // root, by either spelling; walk the rest from the root rather
3446                // than through the root's ancestors.
3447                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
3515/// Returns whether `path` starts with `prefix` either lexically or after
3516/// resolving symlinks and the existing path prefix.
3517pub 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            // A drive prefix such as `C:` is drive-relative until its root is
3538            // present, so do not canonicalize the two components separately.
3539            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                    // PathBuf::push lexically resolves `..` after a verbatim
3549                    // (`\\?\`) prefix, but the unresolved suffix must remain
3550                    // opaque so two potentially different files stay distinct.
3551                    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
3591/// Resolutions made by [`desymlink_path_cached`], and how many times
3592/// [`clear_desymlink_cache`] has run. A lookup caches its result only if no
3593/// clear happened while it was resolving, so a resolution made before a clear
3594/// cannot be stored after it.
3595static DESYMLINKED: Lazy<Mutex<(u64, HashMap<PathBuf, PathBuf>)>> = Lazy::new(Default::default);
3596
3597/// [`desymlink_path`] with resolutions of existing absolute paths cached until
3598/// [`clear_desymlink_cache`]. A path that does not exist yet is resolved on
3599/// every call, since it may be created later in the process.
3600pub 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
3621/// Forget every resolution [`desymlink_path_cached`] has made, so the next call
3622/// follows symlinks as they are now. Config reloads call this: a symlink
3623/// retargeted since the last load must not keep its old destination.
3624pub 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        // robocopy exits 0-7 when the copy succeeded (1 means files were copied) and 8 or
3635        // more on failure, so a nonzero exit is not an error by itself. Only 0-7 is success.
3636        let output = cmd!("robocopy", from, to, "/MIR").unchecked().run()?;
3637        // A negative code is a crash such as an access violation, not a copy result.
3638        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
3647/// Skips leading CurDir (".") components from a path's components iterator.
3648/// Archives often have paths like "./foo/bar" where the leading "." should be ignored.
3649fn 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
3654/// Inspects the top-level contents of a tar archive without extracting it.
3655///
3656/// Stops at the second distinct top-level entry, which already settles
3657/// [`should_strip_components`]. A tar entry name can be up to 1 MiB and
3658/// compresses to a few bytes, so collecting every name would let a tiny
3659/// archive hold gigabytes of memory.
3660pub 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        // Get the first non-CurDir component of the path (top-level directory/file)
3674        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            // Check if this entry indicates the component is a directory
3680            // It's a directory if the entry type is dir OR if there are more components after the first
3681            let is_directory = entry_type == EntryType::Directory || components.next().is_some();
3682
3683            // Update the component's directory status
3684            // A component is a directory if ANY entry indicates it's a directory
3685            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
3696/// Inspects the top-level contents of a zip archive without extracting it.
3697///
3698/// Like [`inspect_tar_contents`], stops at the second distinct top-level entry.
3699pub 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            // Get the first non-CurDir component of the path (top-level directory/file)
3709            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                // Check if this entry indicates the component is a directory
3715                // It's a directory if the entry type is dir OR if there are more components after the first
3716                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
3730/// Adapted from inspect_tar_contents for 7z archives, and like it stops at the
3731/// second distinct top-level entry.
3732pub 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        // Get the first non-CurDir component of the path (top-level directory/file)
3740        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            // It's a directory if the entry type is dir OR if there are more components after the first
3745            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
3758/// Determines if strip_components=1 should be applied based on archive structure
3759pub 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 there's exactly one top-level entry and it's a directory, we should strip it
3767    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
3781/// How many bytes [`archive_content_files`] hashes per byte of archive before it
3782/// gives up.
3783///
3784/// Nothing has vouched for the archive yet, and hashing writes nothing, so no
3785/// full disk ends it. Zip entries that share one member, sparse tar members and
3786/// plain decompression bombs would otherwise turn a few kilobytes of download
3787/// into hours of hashing, or no end at all.
3788const ARCHIVE_CONTENT_MAX_RATIO: u64 = 100;
3789/// An archive may always unpack to this much, whatever its ratio.
3790const ARCHIVE_CONTENT_MIN_BUDGET: u64 = 256 * 1024 * 1024;
3791
3792/// Return the regular files in an archive after applying strip-components.
3793///
3794/// This is intentionally stricter than extraction: content-level provenance is
3795/// only safe when every installed regular file is covered, so ambiguous archive
3796/// entries (links, unsafe paths, stripped-away file names, unsupported formats)
3797/// fail closed instead of being ignored.
3798pub 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        // For a sparse member this is the size including its holes, which
3865        // jdx-tar reads back as zeroes.
3866        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        // `is_dir` only looks at the name and `is_symlink` only at the mode, so one
3887        // entry can be both. `ZipArchive::extract` creates such an entry as a symlink,
3888        // so ask in the same order.
3889        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
3913/// Hash an archive entry and deduct what was read from `budget`.
3914///
3915/// The declared `size` refuses an oversized entry before any work is done. What
3916/// is deducted is what was read, because a zip entry can inflate to more than it
3917/// declares.
3918fn 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;