use crate::path::{Path, PathBuf, PathExt};
use std::cell::Cell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Display;
use std::fs;
use std::fs::File;
use std::io::{BufReader, Read, Write};
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(unix)]
use std::os::unix::prelude::*;
use std::rc::Rc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime};
use bzip2::read::BzDecoder;
use eyre::bail;
use eyre::{Context, Result};
use flate2::read::GzDecoder;
use itertools::Itertools;
use jdx_tar::{Archive, EntryType, UnpackOptions};
use path_absolutize::Absolutize;
use sha2::{Digest, Sha256};
use std::sync::LazyLock as Lazy;
use walkdir::WalkDir;
use zip::ZipArchive;
use crate::progress::SingleReport;
use crate::{dirs, env};
use mise_settings::Settings;
pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
let path = path.as_ref();
trace!("open {}", display_path(path));
File::open(path).wrap_err_with(|| format!("failed open: {}", display_path(path)))
}
pub fn read<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
let path = path.as_ref();
trace!("cat {}", display_path(path));
fs::read(path).wrap_err_with(|| format!("failed read: {}", display_path(path)))
}
pub fn size<P: AsRef<Path>>(path: P) -> Result<u64> {
let path = path.as_ref();
trace!("du -b {}", display_path(path));
path.metadata()
.map(|m| m.len())
.wrap_err_with(|| format!("failed size: {}", display_path(path)))
}
pub fn append<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
trace!("append {}", display_path(path));
fs::OpenOptions::new()
.append(true)
.create(true)
.open(path)
.and_then(|mut f| f.write_all(contents.as_ref()))
.wrap_err_with(|| format!("failed append: {}", display_path(path)))
}
#[cfg(windows)]
pub const MAX_PATH: usize = 260;
#[cfg(windows)]
fn windows_io_hint(path: &Path, err: &std::io::Error) -> Option<String> {
use std::os::windows::ffi::OsStrExt;
let in_use = err.kind() == std::io::ErrorKind::PermissionDenied
|| matches!(err.raw_os_error(), Some(5) | Some(32));
if in_use {
return Some(
"A file under it is in use. A program started from this directory — the tool itself, \
an editor, or a shell sitting in it — is probably still running."
.to_string(),
);
}
if !matches!(err.raw_os_error(), Some(3) | Some(123) | Some(206)) {
return None;
}
let units = path.as_os_str().encode_wide().count();
if units < MAX_PATH - 16 {
return None;
}
Some(format!(
"The path is {units} characters, at or near Windows' {MAX_PATH}-character limit, which \
may be the real cause rather than a missing directory. mise writes through a temporary \
file whose name is longer than the final one, so it crosses the limit first. Try a \
shorter directory."
))
}
#[cfg(not(windows))]
fn windows_io_hint(_path: &Path, _err: &std::io::Error) -> Option<String> {
None
}
pub fn with_io_hint(msg: String, path: &Path, err: &std::io::Error) -> String {
match windows_io_hint(path, err) {
Some(hint) => format!("{msg}\n{hint}"),
None => msg,
}
}
pub fn remove_all<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
match fs::symlink_metadata(path).map(|m| m.file_type()) {
Ok(x) if x.is_symlink() => {
remove_symlink_or_junction(path)?;
}
Ok(x) if x.is_file() => {
remove_file(path)?;
}
Ok(x) if x.is_dir() => {
trace!("rm -rf {}", display_path(path));
remove_dir_all_restoring_owner_access(path).map_err(|e| {
let msg = with_io_hint(
format!("failed to remove: {}", display_path(path)),
path,
&e,
);
eyre::eyre!(e).wrap_err(msg)
})?;
}
_ => {}
};
Ok(())
}
fn remove_dir_all_restoring_owner_access(path: &Path) -> std::io::Result<()> {
let result = fs::remove_dir_all(path);
#[cfg(unix)]
if let Err(err) = &result
&& err.kind() == std::io::ErrorKind::PermissionDenied
&& restore_owner_access(path).is_ok()
{
return fs::remove_dir_all(path);
}
result
}
#[cfg(unix)]
fn restore_owner_access(path: &Path) -> Result<()> {
let parent = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
let Some(name) = path.file_name() else {
bail!("no directory name in {}", display_path(path));
};
restore_owner_access_at(File::open(parent)?, name)
}
#[cfg(unix)]
fn restore_owner_access_at<Fd: std::os::fd::AsFd>(
parent: Fd,
name: &std::ffi::OsStr,
) -> Result<()> {
let fd = nix::fcntl::openat(
&parent,
name,
nix::fcntl::OFlag::O_RDONLY
| nix::fcntl::OFlag::O_DIRECTORY
| nix::fcntl::OFlag::O_NOFOLLOW
| nix::fcntl::OFlag::O_CLOEXEC,
nix::sys::stat::Mode::empty(),
)?;
let mode = nix::sys::stat::fstat(&fd)?.st_mode;
if mode & 0o700 != 0o700 {
nix::sys::stat::fchmod(&fd, nix::sys::stat::Mode::from_bits_truncate(mode | 0o700))?;
}
let mut directory = nix::dir::Dir::from_fd(fd)?;
let entries = directory
.iter()
.map(|entry| entry.map(|entry| entry.file_name().to_owned()))
.collect::<std::result::Result<Vec<_>, _>>()?;
for entry in entries {
let entry = std::ffi::OsStr::from_bytes(entry.to_bytes());
if entry == "." || entry == ".." {
continue;
}
let stat =
nix::sys::stat::fstatat(&directory, entry, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW)?;
let kind = nix::sys::stat::SFlag::from_bits_truncate(stat.st_mode & nix::libc::S_IFMT);
if kind == nix::sys::stat::SFlag::S_IFDIR {
restore_owner_access_at(&directory, entry)?;
}
}
Ok(())
}
#[cfg(unix)]
pub fn remove_all_at<Fd: std::os::fd::AsFd>(parent: Fd, name: &std::ffi::OsStr) -> Result<()> {
let stat =
match nix::sys::stat::fstatat(&parent, name, nix::fcntl::AtFlags::AT_SYMLINK_NOFOLLOW) {
Ok(stat) => stat,
Err(nix::errno::Errno::ENOENT) => return Ok(()),
Err(err) => return Err(err.into()),
};
let kind = nix::sys::stat::SFlag::from_bits_truncate(stat.st_mode & nix::libc::S_IFMT);
if kind == nix::sys::stat::SFlag::S_IFDIR {
let fd = nix::fcntl::openat(
&parent,
name,
nix::fcntl::OFlag::O_RDONLY
| nix::fcntl::OFlag::O_DIRECTORY
| nix::fcntl::OFlag::O_NOFOLLOW
| nix::fcntl::OFlag::O_CLOEXEC,
nix::sys::stat::Mode::empty(),
)?;
let mut directory = nix::dir::Dir::from_fd(fd)?;
let entries = directory
.iter()
.map(|entry| entry.map(|entry| entry.file_name().to_owned()))
.collect::<std::result::Result<Vec<_>, _>>()?;
for entry in entries {
if entry.as_bytes() != b"." && entry.as_bytes() != b".." {
remove_all_at(&directory, std::ffi::OsStr::from_bytes(entry.to_bytes()))?;
}
}
nix::unistd::unlinkat(parent, name, nix::unistd::UnlinkatFlags::RemoveDir)?;
} else {
nix::unistd::unlinkat(parent, name, nix::unistd::UnlinkatFlags::NoRemoveDir)?;
}
Ok(())
}
pub fn remove_all_with_retry<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
retry_remove_all(|| remove_all(path))
}
fn retry_remove_all(mut remove: impl FnMut() -> Result<()>) -> Result<()> {
const MAX_RETRIES: u32 = 4;
for retry in 0..MAX_RETRIES {
match remove() {
Ok(()) => return Ok(()),
Err(err)
if err
.downcast_ref::<std::io::Error>()
.is_some_and(|err| err.kind() == std::io::ErrorKind::DirectoryNotEmpty) =>
{
std::thread::sleep(Duration::from_millis(10 * (1 << retry)));
}
Err(err) => return Err(err),
}
}
remove()
}
#[cfg(unix)]
pub fn remove_file_or_dir<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
match path.metadata().map(|m| m.file_type()) {
Ok(x) if x.is_dir() => {
remove_dir(path)?;
}
_ => {
remove_file(path)?;
}
};
Ok(())
}
pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
trace!("rm {}", display_path(path));
fs::remove_file(path).wrap_err_with(|| format!("failed rm: {}", display_path(path)))
}
pub async fn remove_file_async_if_exists<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
trace!("rm {}", display_path(path));
match tokio::fs::remove_file(path).await {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e).wrap_err_with(|| format!("failed rm: {}", display_path(path))),
}
}
pub fn remove_dir<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
(|| -> Result<()> {
if path.exists() && is_empty_dir(path)? {
trace!("rmdir {}", display_path(path));
fs::remove_dir(path)?;
}
Ok(())
})()
.wrap_err_with(|| format!("failed to remove_dir: {}", display_path(path)))
}
pub fn remove_dir_ignore<P: AsRef<Path>>(path: P, is_empty_ignore_files: Vec<&str>) -> Result<()> {
let path = path.as_ref();
(|| -> Result<()> {
if path.exists() && is_empty_dir_ignore(path, is_empty_ignore_files)? {
trace!("rm -rf {}", display_path(path));
remove_all_with_warning(path)?;
}
Ok(())
})()
.wrap_err_with(|| format!("failed to remove_dir: {}", display_path(path)))
}
pub fn remove_all_with_warning<P: AsRef<Path>>(path: P) -> Result<()> {
remove_all(&path).map_err(|e| {
warn!("failed to remove {}: {}", path.as_ref().display(), e);
e
})
}
pub fn entry_exists<P: AsRef<Path>>(path: P) -> bool {
fs::symlink_metadata(path.as_ref()).is_ok()
}
pub fn remove_all_with_progress<P: AsRef<Path>>(path: P, pr: &dyn SingleReport) -> Result<()> {
let path = path.as_ref();
if !entry_exists(path) {
return Ok(());
}
pr.set_message(format!("remove {}", display_path(path)));
remove_all_with_warning(path)
}
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
try_rename(from, to).wrap_err_with(|| {
format!(
"failed rename: {} -> {}",
display_path(from),
display_path(to)
)
})
}
pub fn try_rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> std::io::Result<()> {
let from = from.as_ref();
let to = to.as_ref();
trace!("mv {} {}", from.display(), to.display());
do_rename(from, to)
}
#[cfg(windows)]
fn do_rename(from: &Path, to: &Path) -> std::io::Result<()> {
const MAX_ATTEMPTS: u32 = 20;
const MAX_DELAY_MS: u64 = 5000;
let mut last_err = None;
for attempt in 0..MAX_ATTEMPTS {
match fs::rename(from, to) {
Ok(()) => return Ok(()),
Err(e) if matches!(e.raw_os_error(), Some(5) | Some(32)) => {
last_err = Some(e);
if attempt + 1 < MAX_ATTEMPTS {
let delay = (50u64 << attempt).min(MAX_DELAY_MS);
std::thread::sleep(std::time::Duration::from_millis(delay));
}
}
Err(e) => return Err(e),
}
}
Err(last_err.unwrap())
}
#[cfg(not(windows))]
fn do_rename(from: &Path, to: &Path) -> std::io::Result<()> {
fs::rename(from, to)
}
pub fn move_file<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
match try_rename(from, to) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::CrossesDevices => {
if from.is_dir() {
create_dir_all(to)?;
copy_dir_all_preserve_symlinks(from, to)?;
remove_all(from)?;
} else {
copy(from, to)?;
remove_file(from)?;
}
Ok(())
}
Err(err) => Err(err).wrap_err_with(|| {
format!(
"failed move: {} -> {}",
display_path(from),
display_path(to)
)
}),
}
}
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
trace!("cp {} {}", from.display(), to.display());
fs::copy(from, to)
.wrap_err_with(|| {
format!(
"failed copy: {} -> {}",
display_path(from),
display_path(to)
)
})
.map(|_| ())
}
pub fn hard_link_or_copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()> {
let from = from.as_ref();
let to = to.as_ref();
match fs::hard_link(from, to) {
Ok(()) => {
trace!("ln {} {}", from.display(), to.display());
Ok(())
}
Err(err) => {
trace!(
"ln {} {} failed ({err}), copying instead",
from.display(),
to.display()
);
copy(from, to)
}
}
}
pub fn copy_dir_all_preserve_symlinks(from: &Path, to: &Path) -> Result<()> {
copy_dir_all_preserve_symlinks_skipping(from, to, &[])
}
fn copy_dir_all_preserve_symlinks_skipping(
from: &Path,
to: &Path,
skip_top_level: &[&str],
) -> Result<()> {
trace!("cp -a {} {}", from.display(), to.display());
let permissions = fs::metadata(from)?.permissions();
create_dir_all(to)?;
let mut directory_permissions = vec![(to.to_path_buf(), permissions)];
let entries = WalkDir::new(from)
.follow_links(false)
.min_depth(1)
.into_iter()
.filter_entry(|entry| {
entry.depth() != 1
|| !entry
.file_name()
.to_str()
.is_some_and(|name| skip_top_level.contains(&name))
});
for entry in entries {
let entry = entry?;
let relative = entry.path().strip_prefix(from)?;
let dest = to.join(relative);
if entry.file_type().is_dir() {
create_dir_all(&dest)?;
directory_permissions.push((dest, entry.metadata()?.permissions()));
} else if entry.file_type().is_symlink() {
create_dir_all(dest.parent().unwrap())?;
make_symlink(&fs::read_link(entry.path())?, &dest)?;
} else if entry.file_type().is_file() {
create_dir_all(dest.parent().unwrap())?;
copy(entry.path(), &dest)?;
}
}
for (path, permissions) in directory_permissions.into_iter().rev() {
fs::set_permissions(path, permissions)?;
}
Ok(())
}
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
trace!("write {}", display_path(path));
fs::write(path, contents).wrap_err_with(|| format!("failed write: {}", display_path(path)))
}
pub struct PreparedAtomicWrite {
temporary: tempfile::NamedTempFile,
target: PathBuf,
parent: PathBuf,
}
impl PreparedAtomicWrite {
pub fn commit(self) -> Result<()> {
persist_atomic(self.temporary, &self.target).map_err(|e| {
let msg = format!("failed atomic write: {}", display_path(&self.target));
let msg = match e.downcast_ref::<std::io::Error>() {
Some(io) => with_io_hint(msg, &self.target, io),
None => msg,
};
e.wrap_err(msg)
})?;
sync_dir(&self.parent)?;
Ok(())
}
}
pub fn prepare_atomic_write<P: AsRef<Path>, C: AsRef<[u8]>>(
path: P,
contents: C,
) -> Result<PreparedAtomicWrite> {
let path = path.as_ref();
trace!("prepare_atomic_write {}", display_path(path));
let mut prepared = prepare_replacement(path, contents)?;
prepared.temporary.as_file_mut().sync_all()?;
Ok(prepared)
}
pub fn write_atomic_unsynced<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
trace!("write_atomic_unsynced {}", display_path(path));
let prepared = prepare_replacement(path, contents)?;
persist_atomic(prepared.temporary, &prepared.target)
.wrap_err_with(|| format!("failed atomic write: {}", display_path(&prepared.target)))
}
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn sync_filesystem<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
trace!("sync filesystem of {}", display_path(path));
let dir = File::open(path)
.wrap_err_with(|| format!("failed to open dir for sync: {}", display_path(path)))?;
nix::unistd::syncfs(&dir)
.wrap_err_with(|| format!("failed to sync filesystem of {}", display_path(path)))
}
fn prepare_replacement<C: AsRef<[u8]>>(path: &Path, contents: C) -> Result<PreparedAtomicWrite> {
let target = atomic_write_target(path)?;
let path = target.as_path();
let parent = path
.parent()
.ok_or_else(|| eyre::eyre!("path has no parent: {}", display_path(path)))?;
let prefix = format!(
".{}.",
path.file_name().unwrap_or_default().to_string_lossy()
);
let mut builder = tempfile::Builder::new();
builder.prefix(&prefix);
#[cfg(unix)]
let existing_permissions = match fs::metadata(path) {
Ok(metadata) => Some(metadata.permissions()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => return Err(err.into()),
};
#[cfg(unix)]
if existing_permissions.is_none() {
builder.permissions(fs::Permissions::from_mode(0o666));
}
let mut temporary = builder.tempfile_in(parent)?;
#[cfg(unix)]
if let Some(permissions) = existing_permissions {
temporary.as_file().set_permissions(permissions)?;
}
temporary.write_all(contents.as_ref())?;
let parent = parent.to_path_buf();
Ok(PreparedAtomicWrite {
temporary,
target,
parent,
})
}
pub fn write_atomic<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
trace!("write_atomic {}", display_path(path));
prepare_atomic_write(path, contents)?.commit()
}
pub fn atomic_write_target(path: &Path) -> Result<PathBuf> {
const MAX_SYMLINKS: usize = 40;
let mut target = path.to_path_buf();
for followed in 0..=MAX_SYMLINKS {
if !target.is_symlink() {
return Ok(desymlink_path(&target));
}
if followed == MAX_SYMLINKS {
break;
}
let link = fs::read_link(&target)
.wrap_err_with(|| format!("failed to read symlink: {}", display_path(&target)))?;
target = if link.is_absolute() {
link
} else {
target.parent().unwrap_or_else(|| Path::new("")).join(link)
};
}
bail!(
"too many symlinks while resolving atomic write target: {}",
display_path(path)
)
}
pub fn persist_atomic(mut temporary: tempfile::NamedTempFile, path: &Path) -> Result<()> {
const RETRIES: u32 = 20;
for attempt in 0..=RETRIES {
match temporary.persist(path) {
Ok(_) => return Ok(()),
Err(err) if should_retry_atomic_persist(&err.error) && attempt < RETRIES => {
temporary = err.file;
std::thread::sleep(Duration::from_millis(5 * u64::from(attempt + 1)));
}
Err(err) => return Err(err.error.into()),
}
}
unreachable!("atomic persist retry loop should always return");
}
#[cfg(windows)]
fn should_retry_atomic_persist(err: &std::io::Error) -> bool {
err.kind() == std::io::ErrorKind::PermissionDenied
|| matches!(err.raw_os_error(), Some(5) | Some(32))
}
#[cfg(not(windows))]
fn should_retry_atomic_persist(_err: &std::io::Error) -> bool {
false
}
pub async fn write_async<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
trace!("write {}", display_path(path));
tokio::fs::write(path, contents)
.await
.wrap_err_with(|| format!("failed write: {}", display_path(path)))
}
pub fn read_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
trace!("cat {}", path.display_user());
fs::read_to_string(path)
.wrap_err_with(|| format!("failed read_to_string: {}", path.display_user()))
}
pub const CONFIG_FILE_LIMIT: u64 = 16 * 1024 * 1024;
fn config_file_too_large(path: &Path) -> eyre::Report {
eyre::eyre!(
"not reading {}: it is larger than {} MiB, the most mise reads from a config file",
path.display_user(),
CONFIG_FILE_LIMIT / 1024 / 1024
)
}
pub fn open_regular_file<P: AsRef<Path>>(path: P) -> std::io::Result<File> {
let mut options = fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, nix::libc::O_NONBLOCK);
let file = options.open(path.as_ref())?;
if !file.metadata()?.is_file() {
return Err(std::io::Error::other("not a regular file"));
}
Ok(file)
}
pub fn read_config_to_string<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
trace!("cat {}", path.display_user());
let file = open_regular_file(path).wrap_err_with(|| read_failed(path))?;
read_config_body(path, file)
}
pub fn read_config_to_string_if_exists<P: AsRef<Path>>(path: P) -> Result<Option<String>> {
let path = path.as_ref();
trace!("cat {}", path.display_user());
match open_regular_file(path) {
Ok(file) => read_config_body(path, file).map(Some),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err).wrap_err_with(|| read_failed(path)),
}
}
fn read_failed(path: &Path) -> String {
format!("failed read_to_string: {}", path.display_user())
}
fn read_config_body(path: &Path, file: File) -> Result<String> {
let mut body = String::new();
file.take(CONFIG_FILE_LIMIT + 1)
.read_to_string(&mut body)
.wrap_err_with(|| read_failed(path))?;
if body.len() as u64 > CONFIG_FILE_LIMIT {
return Err(config_file_too_large(path));
}
Ok(body)
}
pub fn ensure_config_file_size<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
match fs::metadata(path) {
Ok(metadata) if metadata.len() > CONFIG_FILE_LIMIT => Err(config_file_too_large(path)),
_ => Ok(()),
}
}
pub async fn read_config_to_string_async<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref().to_path_buf();
tokio::task::spawn_blocking(move || read_config_to_string(&path))
.await
.wrap_err("config file read was cancelled")?
}
#[cfg(windows)]
pub const UTF8_BOM_BYTES: [u8; 3] = [0xef, 0xbb, 0xbf];
pub fn strip_utf8_bom(s: &str) -> &str {
s.strip_prefix('\u{feff}').unwrap_or(s)
}
pub fn decode_text(bytes: &[u8]) -> Result<String> {
fn from_utf16(bytes: &[u8], to_u16: fn([u8; 2]) -> u16, label: &str) -> Result<String> {
if !bytes.len().is_multiple_of(2) {
bail!(
"truncated {label} text: {} bytes is not a whole number of code units",
bytes.len()
);
}
let units = bytes
.as_chunks::<2>()
.0
.iter()
.map(|c| to_u16(*c))
.collect_vec();
String::from_utf16(&units).wrap_err_with(|| format!("invalid {label} text"))
}
match bytes {
[0xef, 0xbb, 0xbf, rest @ ..] => {
String::from_utf8(rest.to_vec()).wrap_err("invalid UTF-8 text after a UTF-8 BOM")
}
[0xff, 0xfe, rest @ ..] => from_utf16(rest, u16::from_le_bytes, "UTF-16LE"),
[0xfe, 0xff, rest @ ..] => from_utf16(rest, u16::from_be_bytes, "UTF-16BE"),
_ => String::from_utf8(bytes.to_vec())
.wrap_err("invalid UTF-8 text, and no byte-order mark identifying another encoding"),
}
}
#[cfg(any(windows, test))]
pub fn utf16_bom(path: &Path) -> Option<&'static str> {
let bytes = std::fs::File::open(path)
.and_then(|f| {
use std::io::Read;
let mut buf = Vec::with_capacity(2);
f.take(2).read_to_end(&mut buf)?;
Ok(buf)
})
.ok()?;
match bytes[..] {
[0xff, 0xfe] => Some("UTF-16LE"),
[0xfe, 0xff] => Some("UTF-16BE"),
_ => None,
}
}
pub fn read_to_string_bom<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
trace!("cat {}", path.display_user());
let bytes = fs::read(path).wrap_err_with(|| format!("failed read: {}", path.display_user()))?;
decode_text(&bytes).wrap_err_with(|| format!("failed to decode {}", path.display_user()))
}
pub async fn read_to_string_async<P: AsRef<Path>>(path: P) -> Result<String> {
let path = path.as_ref();
trace!("cat {}", path.display_user());
tokio::fs::read_to_string(path)
.await
.wrap_err_with(|| format!("failed read_to_string: {}", path.display_user()))
}
pub fn create(path: &Path) -> Result<File> {
if let Some(parent) = path.parent() {
create_dir_all(parent)?;
}
trace!("touch {}", display_path(path));
File::create(path).wrap_err_with(|| format!("failed create: {}", display_path(path)))
}
pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
static LOCK: Lazy<Mutex<u8>> = Lazy::new(Default::default);
let _lock = LOCK.lock().unwrap();
let path = path.as_ref();
if !path.exists() {
trace!("mkdir -p {}", display_path(path));
if let Err(err) = fs::create_dir_all(path) {
if err.kind() != std::io::ErrorKind::AlreadyExists {
return Err(err)
.wrap_err_with(|| format!("failed create_dir_all: {}", display_path(path)));
}
}
}
Ok(())
}
pub fn display_path<P: AsRef<Path>>(path: P) -> String {
crate::path::settle_display_separators(path.as_ref().display_user())
}
pub fn display_filename<P: AsRef<Path>>(path: P) -> String {
let path = path.as_ref();
path.file_name()
.unwrap_or(path.as_os_str())
.to_string_lossy()
.into_owned()
}
pub fn display_rel_path<P: AsRef<Path>>(path: P) -> String {
let path = path.as_ref();
match path.strip_prefix(dirs::CWD.as_ref().unwrap()) {
Ok(rel) => format!(".{}{}", std::path::MAIN_SEPARATOR, display_path(rel)),
Err(_) => display_path(path),
}
}
pub fn replace_paths_in_string<S: Display>(input: S) -> String {
let home = env::HOME.to_string_lossy().to_string();
input.to_string().replace(&home, "~")
}
pub fn replace_path<P: AsRef<Path>>(path: P) -> PathBuf {
let path = path.as_ref();
match path.strip_prefix("~/") {
Ok(rest) => {
let mut expanded = dirs::HOME.to_path_buf();
for component in rest.components() {
expanded.push(component.as_os_str());
}
expanded
}
Err(_) => path.to_path_buf(),
}
}
pub fn paths_eq(a: &Path, b: &Path) -> bool {
#[cfg(any(windows, target_os = "macos"))]
{
let normalize =
|c: std::path::Component<'_>| c.as_os_str().to_string_lossy().to_lowercase();
a.components()
.map(normalize)
.eq(b.components().map(normalize))
}
#[cfg(all(not(windows), not(target_os = "macos")))]
{
a == b
}
}
pub fn storage_paths_eq(a: &Path, b: &Path) -> bool {
paths_eq(a, b) || same_file(a, b)
}
pub fn touch_file(file: &Path) -> Result<()> {
if !file.exists() {
create(file)?;
return Ok(());
}
trace!("touch_file {}", file.display());
let now = SystemTime::now();
set_times(file, Some(now), Some(now))
.wrap_err_with(|| format!("failed to touch file: {}", display_path(file)))
}
pub fn touch_dir(dir: &Path) -> Result<()> {
trace!("touch {}", dir.display());
let now = SystemTime::now();
set_times(dir, Some(now), Some(now))
.wrap_err_with(|| format!("failed to touch dir: {}", display_path(dir)))
}
pub fn set_times(
path: &Path,
accessed: Option<SystemTime>,
modified: Option<SystemTime>,
) -> std::io::Result<()> {
set_path_times(path, accessed, modified, true)
}
pub fn set_symlink_times(
path: &Path,
accessed: Option<SystemTime>,
modified: Option<SystemTime>,
) -> std::io::Result<()> {
set_path_times(path, accessed, modified, false)
}
#[cfg(unix)]
fn set_path_times(
path: &Path,
accessed: Option<SystemTime>,
modified: Option<SystemTime>,
follow: bool,
) -> std::io::Result<()> {
use nix::sys::stat::{UtimensatFlags, utimensat};
use nix::sys::time::TimeSpec;
fn spec(time: Option<SystemTime>) -> TimeSpec {
match time.map(|time| time.duration_since(SystemTime::UNIX_EPOCH)) {
None => TimeSpec::UTIME_OMIT,
Some(Ok(after)) => TimeSpec::from_duration(after),
Some(Err(before)) => -TimeSpec::from_duration(before.duration()),
}
}
let flag = if follow {
UtimensatFlags::FollowSymlink
} else {
UtimensatFlags::NoFollowSymlink
};
utimensat(
nix::fcntl::AT_FDCWD,
path,
&spec(accessed),
&spec(modified),
flag,
)?;
Ok(())
}
#[cfg(windows)]
fn set_path_times(
path: &Path,
accessed: Option<SystemTime>,
modified: Option<SystemTime>,
follow: bool,
) -> std::io::Result<()> {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::{
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_WRITE_ATTRIBUTES,
};
let mut flags = FILE_FLAG_BACKUP_SEMANTICS;
if !follow {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
let file = fs::OpenOptions::new()
.access_mode(FILE_WRITE_ATTRIBUTES)
.custom_flags(flags)
.open(path)?;
let mut times = fs::FileTimes::new();
if let Some(accessed) = accessed {
times = times.set_accessed(accessed);
}
if let Some(modified) = modified {
times = times.set_modified(modified);
}
file.set_times(times)
}
#[cfg(unix)]
pub fn sync_dir<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
trace!("sync {}", display_path(path));
let dir = File::open(path)
.wrap_err_with(|| format!("failed to open dir for sync: {}", display_path(path)))?;
dir.sync_all()
.wrap_err_with(|| format!("failed to sync dir: {}", display_path(path)))
}
#[cfg(windows)]
pub fn sync_dir<P: AsRef<Path>>(_path: P) -> Result<()> {
Ok(())
}
pub fn modified_duration(path: &Path) -> Result<Duration> {
let metadata = path.metadata()?;
let modified = metadata.modified()?;
let duration = modified.elapsed().unwrap_or_default();
Ok(duration)
}
pub fn find_up<FN: AsRef<str>>(from: &Path, filenames: &[FN]) -> Option<PathBuf> {
let mut current = from.to_path_buf();
loop {
for filename in filenames {
let path = current.join(filename.as_ref());
if path.exists() {
return Some(path);
}
}
if !current.pop() {
return None;
}
}
}
pub fn dir_subdirs(dir: &Path) -> Result<BTreeSet<String>> {
let mut output = Default::default();
if !dir.exists() {
return Ok(output);
}
for entry in dir.read_dir()? {
let entry = entry?;
let ft = entry.file_type()?;
if ft.is_dir() || (ft.is_symlink() && entry.path().is_dir()) {
if let Ok(name) = entry.file_name().into_string() {
output.insert(name);
}
}
}
Ok(output)
}
pub fn ls(dir: &Path) -> Result<BTreeSet<PathBuf>> {
let mut output = Default::default();
if !dir.is_dir() {
return Ok(output);
}
for entry in dir.read_dir()? {
let entry = entry?;
output.insert(entry.path());
}
Ok(output)
}
#[cfg(unix)]
pub fn make_symlink(target: &Path, link: &Path) -> Result<(PathBuf, PathBuf)> {
trace!("ln -sf {} {}", target.display(), link.display());
static COUNTER: AtomicU64 = AtomicU64::new(0);
let file_name = link
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("symlink");
let tmp = link.with_file_name(format!(
".{file_name}.tmp.{}.{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
let _ = fs::remove_file(&tmp);
symlink(target, &tmp)
.wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()))?;
if let Err(err) = fs::rename(&tmp, link) {
let _ = fs::remove_file(&tmp);
return Err(err)
.wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()));
}
Ok((target.to_path_buf(), link.to_path_buf()))
}
#[cfg(unix)]
pub fn make_symlink_or_copy(target: &Path, link: &Path) -> Result<()> {
make_symlink(target, link)?;
Ok(())
}
#[cfg(windows)]
pub fn make_symlink_or_copy(target: &Path, link: &Path) -> Result<()> {
copy(target, link)?;
Ok(())
}
#[cfg(windows)]
pub fn is_unc_path(path: &Path) -> bool {
matches!(
path.components().next(),
Some(std::path::Component::Prefix(prefix))
if matches!(
prefix.kind(),
std::path::Prefix::UNC(..) | std::path::Prefix::VerbatimUNC(..)
)
)
}
#[cfg(windows)]
fn create_windows_unc_symlink(target: &Path, link: &Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_dir(target, link).map_err(|err| {
if err.kind() == std::io::ErrorKind::PermissionDenied {
std::io::Error::new(
err.kind(),
format!(
"{err}. Creating directory symlinks on Windows may require administrator privileges or Developer Mode"
),
)
} else {
err
}
})
}
#[cfg(windows)]
fn create_windows_dir_link(target: &Path, link: &Path) -> std::io::Result<()> {
if is_unc_path(target) {
return create_windows_unc_symlink(target, link);
}
let existed = fs::symlink_metadata(link).is_ok();
let result = junction::create(target, link);
if let Err(err) = &result
&& err.kind() != std::io::ErrorKind::AlreadyExists
&& !existed
&& junction::get_target(link).is_err()
{
let _ = fs::remove_dir(link);
}
result
}
#[cfg(windows)]
pub fn make_symlink(target: &Path, link: &Path) -> Result<(PathBuf, PathBuf)> {
if let Err(err) = create_windows_dir_link(target, link) {
if err.kind() == std::io::ErrorKind::AlreadyExists {
remove_symlink_or_junction(link)?;
create_windows_dir_link(target, link)
} else {
Err(err)
}
} else {
Ok(())
}
.wrap_err_with(|| format!("failed to ln -sf {} {}", target.display(), link.display()))?;
Ok((target.to_path_buf(), link.to_path_buf()))
}
#[cfg(windows)]
pub fn make_symlink_or_file(target: &Path, link: &Path) -> Result<()> {
trace!("ln -sf {} {}", target.display(), link.display());
if link.is_file() || link.is_symlink() {
fs::remove_file(link)?;
}
xx::file::write(link, target.to_string_lossy().to_string())?;
Ok(())
}
pub fn resolve_symlink(link: &Path) -> Result<Option<PathBuf>> {
let file_type = link.symlink_metadata().ok().map(|m| m.file_type());
if file_type.is_some_and(|t| t.is_symlink()) {
Ok(Some(fs::read_link(link)?))
} else if let Some(target) = junction_target(link) {
Ok(Some(target))
} else if file_type.is_some_and(|t| t.is_file()) {
Ok(Some(fs::read_to_string(link)?.into()))
} else {
Ok(None)
}
}
#[cfg(windows)]
fn junction_target(link: &Path) -> Option<PathBuf> {
junction::get_target(link).ok()
}
#[cfg(not(windows))]
fn junction_target(_link: &Path) -> Option<PathBuf> {
None
}
#[cfg(unix)]
pub fn make_dir_link(target: &Path, link: &Path) -> Result<()> {
make_symlink(target, link)?;
Ok(())
}
#[cfg(windows)]
pub fn make_dir_link(target: &Path, link: &Path) -> Result<()> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let target = resolve_relative_link_target(link, target.to_path_buf());
let target = target.absolutize()?.into_owned();
if fs::symlink_metadata(link).is_err() {
match make_symlink(&target, link) {
Ok(_) => return Ok(()),
Err(_) if fs::symlink_metadata(link).is_ok() => {}
Err(err) => return Err(err),
}
}
let name = link.file_name().and_then(|n| n.to_str()).unwrap_or("link");
let tmp = link.with_file_name(format!(
".{name}.tmp.{}.{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
make_symlink(&target, &tmp)?;
let previous = resolve_symlink(link)
.ok()
.flatten()
.map(|old| resolve_relative_link_target(link, old));
let swapped = remove_dir_link(link).and_then(|()| {
rename(&tmp, link)
});
if swapped.is_err() {
let _ = remove_symlink_or_junction(&tmp);
if let Some(previous) = previous
&& fs::symlink_metadata(link).is_err()
{
let _ = make_symlink(&previous, link);
}
}
swapped
}
#[cfg(unix)]
pub fn remove_dir_link(link: &Path) -> Result<()> {
if link.is_symlink() || link.is_file() {
remove_file(link)?;
}
Ok(())
}
#[cfg(windows)]
pub fn remove_dir_link(link: &Path) -> Result<()> {
if is_symlink_or_junction(link) {
remove_symlink_or_junction(link)
} else if link.is_file() {
remove_file(link)
} else {
Ok(())
}
}
pub fn is_symlink_to(link: &Path, target: &Path) -> bool {
is_symlink_or_junction(link) && same_file::is_same_file(link, target).unwrap_or(false)
}
#[cfg(unix)]
pub fn is_symlink_or_junction(path: &Path) -> bool {
path.is_symlink()
}
#[cfg(windows)]
pub fn is_symlink_or_junction(path: &Path) -> bool {
path.is_symlink() || junction::get_target(path).is_ok()
}
#[cfg(unix)]
pub fn make_symlink_or_file(target: &Path, link: &Path) -> Result<()> {
make_symlink(target, link)?;
Ok(())
}
pub fn is_symlink_target_within(link: &Path, root: &Path) -> Result<bool> {
let Some(target) = dir_link_target(link)? else {
return Ok(false);
};
let target = target.absolutize()?;
let root = root.absolutize()?;
Ok(path_starts_with(&target, &root))
}
#[cfg(unix)]
fn path_starts_with(path: &Path, root: &Path) -> bool {
path.starts_with(root)
}
#[cfg(unix)]
pub fn same_path_ignoring_case(a: &Path, b: &Path) -> bool {
a == b
}
#[cfg(windows)]
pub fn same_path_ignoring_case(a: &Path, b: &Path) -> bool {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Globalization::{CSTR_EQUAL, CompareStringOrdinal};
if a == b {
return true;
}
let a = a.as_os_str().encode_wide().collect::<Vec<_>>();
let b = b.as_os_str().encode_wide().collect::<Vec<_>>();
let (Ok(a_len), Ok(b_len)) = (i32::try_from(a.len()), i32::try_from(b.len())) else {
return false;
};
unsafe { CompareStringOrdinal(a.as_ptr(), a_len, b.as_ptr(), b_len, 1) == CSTR_EQUAL }
}
#[cfg(windows)]
fn path_starts_with(path: &Path, root: &Path) -> bool {
if path.starts_with(root) {
return true;
}
let root_component_count = root.components().count();
let root = root.components().collect::<PathBuf>();
let candidate = path
.components()
.take(root_component_count)
.collect::<PathBuf>();
if candidate.components().count() != root_component_count {
return false;
}
if !same_path_ignoring_case(&candidate, &root) {
return false;
}
match same_file::is_same_file(&candidate, &root) {
Ok(same) => same,
Err(_) => dangling_paths_share_case_insensitive_parent(&candidate, &root),
}
}
#[cfg(unix)]
pub fn same_location_ignoring_case(a: &Path, b: &Path) -> bool {
a == b
}
#[cfg(windows)]
pub fn same_location_ignoring_case(a: &Path, b: &Path) -> bool {
if a == b {
return true;
}
if !same_path_ignoring_case(a, b) {
return false;
}
match same_file::is_same_file(a, b) {
Ok(same) => same && !respelled_in_case_sensitive_dir(a, b),
Err(_) => dangling_paths_share_case_insensitive_parent(a, b),
}
}
#[cfg(windows)]
fn respelled_in_case_sensitive_dir(a: &Path, b: &Path) -> bool {
let mut dir = PathBuf::new();
for (in_a, in_b) in a.components().zip(b.components()) {
if in_a != in_b
&& !dir.as_os_str().is_empty()
&& directory_is_case_sensitive(&dir) == Some(true)
{
return true;
}
dir.push(in_a);
}
false
}
#[cfg(windows)]
fn dangling_paths_share_case_insensitive_parent(path: &Path, root: &Path) -> bool {
let Some((path_parent, path_missing_components)) = nearest_existing_directory(path) else {
return false;
};
let Some((root_parent, root_missing_components)) = nearest_existing_directory(root) else {
return false;
};
path_missing_components == root_missing_components
&& same_file::is_same_file(&path_parent, &root_parent).unwrap_or(false)
&& directory_is_case_sensitive(&path_parent) == Some(false)
}
#[cfg(windows)]
fn nearest_existing_directory(path: &Path) -> Option<(PathBuf, usize)> {
let mut path = path;
let mut missing_components = 0;
loop {
match fs::metadata(path) {
Ok(metadata) if metadata.is_dir() => {
return Some((path.to_path_buf(), missing_components));
}
Ok(_) => return None,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
path = path.parent()?;
missing_components += 1;
}
Err(_) => return None,
}
}
}
#[cfg(windows)]
fn directory_is_case_sensitive(path: &Path) -> Option<bool> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
FILE_CASE_SENSITIVE_INFO, FILE_FLAG_BACKUP_SEMANTICS, FileCaseSensitiveInfo,
GetFileInformationByHandleEx,
};
use windows_sys::Win32::System::SystemServices::FILE_CS_FLAG_CASE_SENSITIVE_DIR;
let directory = fs::OpenOptions::new()
.read(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)
.ok()?;
let mut case_info = FILE_CASE_SENSITIVE_INFO::default();
let inspected = unsafe {
GetFileInformationByHandleEx(
directory.as_raw_handle(),
FileCaseSensitiveInfo,
std::ptr::from_mut(&mut case_info).cast(),
std::mem::size_of::<FILE_CASE_SENSITIVE_INFO>() as u32,
)
};
(inspected != 0).then_some(case_info.Flags & FILE_CS_FLAG_CASE_SENSITIVE_DIR != 0)
}
#[cfg(unix)]
fn dir_link_target(link: &Path) -> Result<Option<PathBuf>> {
let metadata = match fs::symlink_metadata(link) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => {
return Err(err)
.wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
}
};
if !metadata.file_type().is_symlink() {
return Ok(None);
}
let target = fs::read_link(link)
.wrap_err_with(|| format!("failed to read link: {}", display_path(link)))?;
Ok(Some(resolve_relative_link_target(link, target)))
}
#[cfg(windows)]
fn dir_link_target(link: &Path) -> Result<Option<PathBuf>> {
const ERROR_NOT_A_REPARSE_POINT: i32 = 4390;
let metadata = match fs::symlink_metadata(link) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => {
return Err(err)
.wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
}
};
let target = if metadata.file_type().is_symlink() {
fs::read_link(link)
.wrap_err_with(|| format!("failed to read link: {}", display_path(link)))?
} else {
match junction::get_target(link) {
Ok(target) => target,
Err(err)
if err.kind() == std::io::ErrorKind::NotFound
|| err.raw_os_error() == Some(ERROR_NOT_A_REPARSE_POINT)
|| (err.kind() == std::io::ErrorKind::Other
&& err.raw_os_error().is_none()) =>
{
return Ok(None);
}
Err(err) => {
return Err(err).wrap_err_with(|| {
format!("failed to inspect junction: {}", display_path(link))
});
}
}
};
Ok(Some(resolve_relative_link_target(link, target)))
}
fn resolve_relative_link_target(link: &Path, target: PathBuf) -> PathBuf {
if target.is_absolute() {
target
} else {
link.parent().unwrap_or(link).join(target)
}
}
#[cfg(unix)]
pub fn remove_symlink_or_junction(link: &Path) -> Result<()> {
if dir_link_target(link)?.is_none() {
bail!("refusing to remove non-link: {}", display_path(link));
}
fs::remove_file(link)
.wrap_err_with(|| format!("failed to remove symlink: {}", display_path(link)))
}
#[cfg(windows)]
pub fn remove_symlink_or_junction(link: &Path) -> Result<()> {
let link_handle = open_link_for_removal(link)?;
remove_open_link(link_handle)
.wrap_err_with(|| format!("failed to remove link or junction: {}", display_path(link)))
}
#[cfg(windows)]
fn open_link_for_removal(link: &Path) -> Result<File> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
DELETE, FILE_ATTRIBUTE_TAG_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
FileAttributeTagInfo, GetFileInformationByHandleEx,
};
use windows_sys::Win32::System::SystemServices::{
IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK,
};
let file = fs::OpenOptions::new()
.access_mode(DELETE)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
.open(link)
.wrap_err_with(|| format!("failed to open link: {}", display_path(link)))?;
let mut tag_info = FILE_ATTRIBUTE_TAG_INFO::default();
let inspected = unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileAttributeTagInfo,
std::ptr::from_mut(&mut tag_info).cast(),
std::mem::size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
)
};
if inspected == 0 {
return Err(std::io::Error::last_os_error())
.wrap_err_with(|| format!("failed to inspect link: {}", display_path(link)));
}
if !matches!(
tag_info.ReparseTag,
IO_REPARSE_TAG_SYMLINK | IO_REPARSE_TAG_MOUNT_POINT
) {
bail!("refusing to remove non-link: {}", display_path(link));
}
Ok(file)
}
#[cfg(windows)]
fn remove_open_link(file: File) -> std::io::Result<()> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let removed = unsafe {
SetFileInformationByHandle(
file.as_raw_handle(),
FileDispositionInfo,
std::ptr::from_ref(&disposition).cast(),
std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
)
};
if removed == 0 {
return Err(std::io::Error::last_os_error());
}
drop(file);
Ok(())
}
#[cfg(unix)]
pub fn is_executable(path: &Path) -> bool {
if let Ok(metadata) = path.metadata() {
return metadata.permissions().mode() & 0o111 != 0;
}
false
}
#[cfg(windows)]
pub fn is_executable(path: &Path) -> bool {
if !path.is_file() {
return false;
}
if has_known_executable_extension(path) {
return true;
}
has_shebang(path)
}
#[cfg(unix)]
pub fn make_executable_hint(path: &Path) -> String {
format!("Run: chmod +x {}", display_path(path))
}
#[cfg(windows)]
pub fn make_executable_hint(path: &Path) -> String {
if let Some(encoding) = utf16_bom(path) {
return format!(
"{} is {encoding}. mise reads a shebang as bytes, so save it as UTF-8.",
display_path(path),
);
}
format!(
"Add a shebang line to {}, or give it one of these extensions: {}",
display_path(path),
Settings::get().windows_executable_extensions.join(", ")
)
}
#[cfg(windows)]
pub fn has_known_executable_extension(path: &Path) -> bool {
path.extension().map_or(
Settings::get()
.windows_executable_extensions
.contains(&String::new()),
|ext| {
if let Some(str_val) = ext.to_str() {
return Settings::get()
.windows_executable_extensions
.contains(&str_val.to_lowercase().to_string());
}
false
},
)
}
#[cfg(windows)]
pub fn has_shebang(path: &Path) -> bool {
std::fs::File::open(path)
.and_then(|f| {
use std::io::Read;
let mut buf = Vec::with_capacity(UTF8_BOM_BYTES.len() + 2);
f.take((UTF8_BOM_BYTES.len() + 2) as u64)
.read_to_end(&mut buf)?;
let bytes = buf.strip_prefix(UTF8_BOM_BYTES.as_slice()).unwrap_or(&buf);
Ok(bytes.starts_with(b"#!"))
})
.unwrap_or(false)
}
#[cfg(windows)]
pub const OS_LAUNCHABLE_EXTENSIONS: [&str; 4] = ["exe", "com", "bat", "cmd"];
#[cfg(windows)]
pub fn os_can_launch_extension(ext: &str) -> bool {
OS_LAUNCHABLE_EXTENSIONS
.iter()
.any(|known| ext.eq_ignore_ascii_case(known))
}
pub fn can_execute_directly(path: &Path) -> bool {
#[cfg(windows)]
{
has_known_executable_extension(path)
&& path
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(os_can_launch_extension)
}
#[cfg(not(windows))]
{
is_executable(path)
}
}
pub fn is_spawnable(path: &Path) -> bool {
if cfg!(windows) && !path.is_file() {
return false;
}
can_execute_directly(path)
}
#[cfg(unix)]
pub fn make_executable<P: AsRef<Path>>(path: P) -> Result<()> {
trace!("chmod +x {}", display_path(&path));
let path = path.as_ref();
let mut perms = path.metadata()?.permissions();
perms.set_mode(executable_mode(perms.mode()));
fs::set_permissions(path, perms)
.wrap_err_with(|| format!("failed to chmod +x: {}", display_path(path)))?;
Ok(())
}
#[cfg(unix)]
fn executable_mode(mode: u32) -> u32 {
mode | 0o111 | 0o444
}
#[cfg(windows)]
pub fn make_executable<P: AsRef<Path>>(_path: P) -> Result<()> {
Ok(())
}
#[cfg(unix)]
pub async fn make_executable_async<P: AsRef<Path>>(path: P) -> Result<()> {
trace!("chmod +x {}", display_path(&path));
let path = path.as_ref();
let mut perms = path.metadata()?.permissions();
perms.set_mode(executable_mode(perms.mode()));
tokio::fs::set_permissions(path, perms)
.await
.wrap_err_with(|| format!("failed to chmod +x: {}", display_path(path)))
}
#[cfg(windows)]
pub async fn make_executable_async<P: AsRef<Path>>(_path: P) -> Result<()> {
Ok(())
}
pub fn ceiling_path_forms(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
let path = replace_path(path);
let resolved = dunce::canonicalize(&path).ok().filter(|p| *p != path);
std::iter::once(path).chain(resolved)
}
pub fn all_dirs<P: AsRef<Path>>(
start_dir: P,
ceiling_dirs: &HashSet<PathBuf>,
) -> Result<Vec<PathBuf>> {
trace!(
"file::all_dirs Collecting all ancestors of {} until ceiling {:?}",
display_path(&start_dir),
ceiling_dirs
);
Ok(start_dir
.as_ref()
.ancestors()
.map_while(|p| {
if ceiling_dirs.contains(p) || ceiling_dirs.contains(dunce::simplified(p)) {
debug!(
"file::all_dirs Reached ceiling directory: {}",
display_path(p)
);
None
} else {
trace!(
"file::all_dirs Adding ancestor directory: {}",
display_path(p)
);
Some(p.to_path_buf())
}
})
.collect())
}
fn is_empty_dir(path: &Path) -> Result<bool> {
path.read_dir()
.map(|mut i| i.next().is_none())
.wrap_err_with(|| format!("failed to read_dir: {}", display_path(path)))
}
fn is_empty_dir_ignore(path: &Path, ignore_files: Vec<&str>) -> Result<bool> {
path.read_dir()
.map(|mut i| {
i.all(|entry| match entry {
Ok(entry) => ignore_files.iter().any(|ignore_file| {
entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case(ignore_file)
}),
Err(_) => false,
})
})
.wrap_err_with(|| format!("failed to read_dir: {}", display_path(path)))
}
pub struct FindUp {
current_dir: PathBuf,
current_dir_filenames: Vec<String>,
filenames: Vec<String>,
}
impl FindUp {
pub fn new(from: &Path, filenames: &[String]) -> Self {
let filenames: Vec<String> = filenames.iter().map(|s| s.to_string()).collect();
Self {
current_dir: from.to_path_buf(),
filenames: filenames.clone(),
current_dir_filenames: filenames,
}
}
}
impl Iterator for FindUp {
type Item = PathBuf;
fn next(&mut self) -> Option<Self::Item> {
while let Some(filename) = self.current_dir_filenames.pop() {
let path = self.current_dir.join(filename);
if path.is_file() {
return Some(path);
}
}
self.current_dir_filenames.clone_from(&self.filenames);
if crate::testing::active() && self.current_dir == *dirs::HOME {
return None; }
if !self.current_dir.pop() {
return None;
}
self.next()
}
}
pub fn which<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
static CACHE: Lazy<Mutex<HashMap<PathBuf, Option<PathBuf>>>> = Lazy::new(Default::default);
let name = name.as_ref();
if let Some(path) = CACHE.lock().unwrap().get(name) {
return path.clone();
}
let path = _which(name, &env::PATH);
CACHE
.lock()
.unwrap()
.insert(name.to_path_buf(), path.clone());
path
}
pub fn which_spawnable(name: &str) -> Option<PathBuf> {
_which_spawnable(name, &env::PATH)
}
pub fn which_spawnable_in(name: &str, paths: &[PathBuf]) -> Option<PathBuf> {
_which_spawnable(name, paths)
}
fn _which_spawnable(name: &str, paths: &[PathBuf]) -> Option<PathBuf> {
let names = executable_names(name);
paths.iter().find_map(|dir| {
names
.iter()
.map(|name| dir.join(name))
.find(|candidate| is_spawnable(candidate))
})
}
pub fn which_non_pristine<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
_which(name, &env::PATH_NON_PRISTINE)
}
pub fn canonicalize_cached(path: &Path) -> Option<PathBuf> {
static CACHE: Lazy<Mutex<HashMap<PathBuf, PathBuf>>> = Lazy::new(Default::default);
if !path.is_absolute() {
return path.canonicalize().ok();
}
if let Some(path) = CACHE.lock().unwrap().get(path).cloned() {
return Some(path);
}
let canonicalized = path.canonicalize().ok()?;
CACHE
.lock()
.unwrap()
.insert(path.to_path_buf(), canonicalized.clone());
Some(canonicalized)
}
pub fn canonicalize_path_entry(path: &Path) -> Option<PathBuf> {
if in_wsl() && is_windows_drive_mount(path) {
return Some(path.to_path_buf());
}
canonicalize_cached(path)
}
pub fn canonicalize_path_entry_or_self(path: &Path) -> PathBuf {
canonicalize_path_entry(path).unwrap_or_else(|| path.to_path_buf())
}
fn in_wsl() -> bool {
static WSL: Lazy<bool> = Lazy::new(|| {
std::env::var_os("WSL_DISTRO_NAME").is_some() || std::env::var_os("WSL_INTEROP").is_some()
});
*WSL
}
fn is_windows_drive_mount(path: &Path) -> bool {
use std::path::Component;
let mut components = path.components();
if components.next() != Some(Component::RootDir) {
return false;
}
if components.next() != Some(Component::Normal("mnt".as_ref())) {
return false;
}
matches!(
components.next(),
Some(Component::Normal(drive))
if drive.len() == 1 && drive.as_encoded_bytes()[0].is_ascii_alphabetic()
) && components.all(|c| c != Component::ParentDir)
}
pub fn canonicalize_or_self(path: &Path) -> PathBuf {
canonicalize_cached(path).unwrap_or_else(|| path.to_path_buf())
}
pub fn is_mise_shims_dir(path: &Path) -> bool {
let resolved = replace_path(path);
let user_shims = dirs::shims();
let sys_shims = dirs::system_shims();
if paths_eq(&resolved, &user_shims) || paths_eq(&resolved, &sys_shims) {
return true;
}
let canon_shims = [user_shims, sys_shims]
.into_iter()
.filter(|shims| shims.symlink_metadata().is_ok())
.map(|shims| canonicalize_or_self(&shims))
.collect::<Vec<_>>();
if canon_shims.is_empty() {
return false;
}
let canon_input = canonicalize_path_entry_or_self(&resolved);
canon_shims
.iter()
.any(|shims| paths_eq(&canon_input, shims))
}
pub fn is_active_mise_shim(path: &Path) -> bool {
env::MISE_SHIM_PATH
.read()
.unwrap()
.as_ref()
.is_some_and(|active| paths_eq(&canonicalize_or_self(path), &canonicalize_or_self(active)))
}
pub fn path_env_without_shims() -> std::ffi::OsString {
let filtered: Vec<_> = env::PATH_NON_PRISTINE
.iter()
.filter(|p| !is_mise_dispatch_dir(p))
.cloned()
.collect();
std::env::join_paths(filtered)
.unwrap_or_else(|_| std::env::var_os(&*env::PATH_KEY).unwrap_or_default())
}
pub fn strip_shims_from_path(path_val: &str) -> String {
let filtered = env::split_paths(path_val).filter(|p| !is_mise_dispatch_dir(p));
std::env::join_paths(filtered)
.unwrap_or_else(|_| std::ffi::OsString::from(path_val))
.to_string_lossy()
.into_owned()
}
pub fn strip_dispatch_dirs_from_path(path_val: &str) -> String {
let filtered = env::split_paths(path_val).filter(|p| !is_mise_dispatch_dir(p));
std::env::join_paths(filtered)
.unwrap_or_else(|_| std::ffi::OsString::from(path_val))
.to_string_lossy()
.into_owned()
}
pub fn strip_shims_dir_from_path(path_val: &str) -> String {
let filtered = env::split_paths(path_val).filter(|p| !is_mise_shims_dir(p));
std::env::join_paths(filtered)
.unwrap_or_else(|_| std::ffi::OsString::from(path_val))
.to_string_lossy()
.into_owned()
}
pub fn is_command_wrapper_dir(path: &Path) -> bool {
let resolved = replace_path(path);
paths_eq(&resolved, &dirs::COMMAND_WRAPPERS)
|| paths_eq(
&canonicalize_path_entry_or_self(&resolved),
&canonicalize_or_self(&dirs::COMMAND_WRAPPERS),
)
}
pub fn is_mise_dispatch_dir(path: &Path) -> bool {
is_mise_shims_dir(path) || is_command_wrapper_dir(path)
}
pub fn which_no_shims<P: AsRef<Path>>(name: P) -> Option<PathBuf> {
let paths: Vec<PathBuf> = env::PATH_NON_PRISTINE
.iter()
.filter(|p| !is_mise_dispatch_dir(p))
.cloned()
.collect();
_which(name, &paths)
}
fn _which<P: AsRef<Path>>(name: P, paths: &[PathBuf]) -> Option<PathBuf> {
let name = name.as_ref();
paths.iter().find_map(|path| {
let bin = path.join(name);
if is_executable(&bin) { Some(bin) } else { None }
})
}
#[cfg(not(windows))]
pub fn executable_names(bin: &str) -> Vec<String> {
vec![bin.to_string()]
}
#[cfg(windows)]
pub fn executable_names(bin: &str) -> Vec<String> {
let mut names = vec![bin.to_string()];
if Path::new(bin).extension().is_none() {
for ext in &Settings::get().windows_executable_extensions {
let name = if ext.is_empty() {
bin.to_string()
} else {
format!("{bin}.{ext}")
};
if !names.contains(&name) {
names.push(name);
}
}
}
names
}
const EXTRACT_MIN_LIMIT: u64 = if cfg!(test) {
256 * 1024
} else {
256 * 1024 * 1024
};
fn extract_limit(input: &Path) -> Result<u64> {
let ratio = Settings::get().extract_max_ratio;
if ratio <= 0 {
return Ok(u64::MAX);
}
let size = input.metadata()?.len();
Ok(size.saturating_mul(ratio as u64).max(EXTRACT_MIN_LIMIT))
}
fn extract_limit_error(limit: u64) -> std::io::Error {
std::io::Error::other(format!(
"unpacked size exceeds {limit} bytes, the limit set by the extract_max_ratio setting"
))
}
struct LimitedReader<R> {
inner: R,
limit: u64,
remaining: u64,
}
impl<R: Read> LimitedReader<R> {
fn new(inner: R, limit: u64) -> Self {
Self {
inner,
limit,
remaining: limit,
}
}
fn for_input(input: &Path, decoder: R) -> Result<Self> {
Ok(Self::new(decoder, extract_limit(input)?))
}
}
impl<R: Read> Read for LimitedReader<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
self.remaining = self
.remaining
.checked_sub(n as u64)
.ok_or_else(|| extract_limit_error(self.limit))?;
Ok(n)
}
}
pub fn un_gz(input: &Path, dest: &Path) -> Result<()> {
debug!("gunzip {} > {}", input.display(), dest.display());
let f = File::open(input)?;
let mut dec = LimitedReader::for_input(input, GzDecoder::new(f))?;
let mut output = File::create(dest)?;
std::io::copy(&mut dec, &mut output)
.wrap_err_with(|| format!("failed to un-gzip: {}", display_path(input)))?;
Ok(())
}
pub fn un_xz(input: &Path, dest: &Path) -> Result<()> {
debug!("xz -d {} -c > {}", input.display(), dest.display());
let f = File::open(input)?;
let mut dec = LimitedReader::for_input(input, xz2::read::XzDecoder::new(f))?;
let mut output = File::create(dest)?;
std::io::copy(&mut dec, &mut output)
.wrap_err_with(|| format!("failed to un-xz: {}", display_path(input)))?;
Ok(())
}
const ZSTD_WINDOW_LOG_MAX: u32 = 30;
fn zstd_decoder<R: Read>(reader: R) -> Result<zstd::Decoder<'static, BufReader<R>>> {
let mut dec = zstd::Decoder::new(reader)?;
dec.window_log_max(ZSTD_WINDOW_LOG_MAX)?;
Ok(dec)
}
pub fn un_zst(input: &Path, dest: &Path) -> Result<()> {
debug!("zstd -d {} -c > {}", input.display(), dest.display());
let f = File::open(input)?;
let mut dec = LimitedReader::for_input(input, zstd_decoder(f)?)?;
let mut output = File::create(dest)?;
std::io::copy(&mut dec, &mut output)
.wrap_err_with(|| format!("failed to un-zst: {}", display_path(input)))?;
Ok(())
}
pub fn un_bz2(input: &Path, dest: &Path) -> Result<()> {
debug!("bzip2 -d {} -c > {}", input.display(), dest.display());
let f = File::open(input)?;
let mut dec = LimitedReader::for_input(input, BzDecoder::new(f))?;
let mut output = File::create(dest)?;
std::io::copy(&mut dec, &mut output)
.wrap_err_with(|| format!("failed to un-bz2: {}", display_path(input)))?;
Ok(())
}
pub fn run_blocking<T>(f: impl FnOnce() -> T) -> T {
match tokio::runtime::Handle::try_current() {
Ok(h) if h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(f)
}
_ => f(),
}
}
pub fn decompress_file(input: &Path, dest: &Path, format: ExtractionFormat) -> Result<()> {
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
{
create_dir_all(parent)?;
}
run_blocking(|| match format {
ExtractionFormat::Gz => un_gz(input, dest),
ExtractionFormat::Xz => un_xz(input, dest),
ExtractionFormat::Zst => un_zst(input, dest),
ExtractionFormat::Bz2 => un_bz2(input, dest),
ExtractionFormat::Br | ExtractionFormat::Lz4 | ExtractionFormat::Sz => {
bail!("{format} format not supported")
}
_ => bail!("unsupported compressed file format: {}", format),
})
}
#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display)]
pub enum ExtractionFormat {
#[strum(to_string = "tar.gz", serialize = "tgz")]
TarGz,
#[strum(serialize = "gz")]
Gz,
#[strum(to_string = "tar.xz", serialize = "txz")]
TarXz,
#[strum(serialize = "xz")]
Xz,
#[strum(to_string = "tar.bz2", serialize = "tbz2", serialize = "tbz")]
TarBz2,
#[strum(serialize = "bz2")]
Bz2,
#[strum(to_string = "tar.zst", serialize = "tzst")]
TarZst,
#[strum(serialize = "zst")]
Zst,
#[strum(serialize = "tar")]
Tar,
#[strum(to_string = "zip", serialize = "vsix")]
Zip,
#[strum(serialize = "7z")]
SevenZip,
#[strum(to_string = "tar.br", serialize = "tbr")]
TarBr,
#[strum(serialize = "br")]
Br,
#[strum(to_string = "tar.lz4", serialize = "tlz4")]
TarLz4,
#[strum(serialize = "lz4")]
Lz4,
#[strum(to_string = "tar.sz", serialize = "tsz")]
TarSz,
#[strum(serialize = "sz")]
Sz,
#[strum(serialize = "rar")]
Rar,
#[strum(serialize = "raw")]
Raw,
}
impl ExtractionFormat {
pub fn from_file_name(filename: &str) -> Self {
let filename = filename.to_lowercase();
if let Some(idx) = filename.rfind(".tar.") {
let ext = &filename[idx + 1..];
if let Some(fmt) = Self::from_ext(ext) {
return fmt;
}
}
if let Some(ext) = Path::new(&filename).extension().and_then(|s| s.to_str()) {
Self::from_ext(ext).unwrap_or(ExtractionFormat::Raw)
} else {
ExtractionFormat::Raw
}
}
pub fn from_ext(ext: &str) -> Option<Self> {
ext.to_lowercase().parse().ok()
}
pub fn detect(path: &Path, filename: &str) -> Result<Self> {
match Self::from_file_name(filename) {
ExtractionFormat::Raw => Ok(Self::from_magic(path)?.unwrap_or(ExtractionFormat::Raw)),
format => Ok(format),
}
}
pub fn from_magic(path: &Path) -> Result<Option<Self>> {
let mut magic = [0; 6];
let len = File::open(path)?.read(&mut magic)?;
let magic = &magic[..len];
if magic.starts_with(b"PK\x03\x04") {
return Ok(Some(ExtractionFormat::Zip));
}
let format = if magic.starts_with(&[0x1f, 0x8b]) {
ExtractionFormat::TarGz
} else if magic.starts_with(b"\xfd7zXZ\0") {
ExtractionFormat::TarXz
} else if magic.starts_with(b"BZh") {
ExtractionFormat::TarBz2
} else if magic.starts_with(&[0x28, 0xb5, 0x2f, 0xfd]) {
ExtractionFormat::TarZst
} else {
ExtractionFormat::Tar
};
let mut header = Vec::with_capacity(512);
let decoded = open_tar(format, path)?.take(512).read_to_end(&mut header);
let is_tar = decoded.is_ok() && header.get(257..262) == Some(&b"ustar"[..]);
Ok(is_tar.then_some(format))
}
pub fn is_archive(&self) -> bool {
self.is_tar_archive()
|| matches!(
self,
ExtractionFormat::Zip | ExtractionFormat::SevenZip | ExtractionFormat::Rar
)
}
pub fn is_tar_archive(&self) -> bool {
matches!(
self,
ExtractionFormat::TarGz
| ExtractionFormat::TarXz
| ExtractionFormat::TarBz2
| ExtractionFormat::TarZst
| ExtractionFormat::Tar
| ExtractionFormat::TarBr
| ExtractionFormat::TarLz4
| ExtractionFormat::TarSz
)
}
pub fn is_compressed_file(&self) -> bool {
matches!(
self,
ExtractionFormat::Gz
| ExtractionFormat::Xz
| ExtractionFormat::Bz2
| ExtractionFormat::Zst
| ExtractionFormat::Br
| ExtractionFormat::Lz4
| ExtractionFormat::Sz
)
}
pub fn extension(&self) -> Option<String> {
(*self != ExtractionFormat::Raw).then(|| self.to_string())
}
}
pub struct ExtractOptions<'a> {
pub strip_components: usize,
pub pr: Option<&'a dyn SingleReport>,
pub preserve_mtime: bool,
}
impl<'a> Default for ExtractOptions<'a> {
fn default() -> Self {
Self {
strip_components: 0,
pr: None,
preserve_mtime: true,
}
}
}
pub fn extract_archive(
archive: &Path,
dest: &Path,
format: ExtractionFormat,
opts: &ExtractOptions,
) -> Result<()> {
match format {
ExtractionFormat::TarGz
| ExtractionFormat::TarXz
| ExtractionFormat::TarBz2
| ExtractionFormat::TarZst
| ExtractionFormat::Tar
| ExtractionFormat::TarBr
| ExtractionFormat::TarLz4
| ExtractionFormat::TarSz
| ExtractionFormat::Raw => untar(archive, dest, format, opts),
ExtractionFormat::Zip => unzip(archive, dest, opts),
ExtractionFormat::SevenZip => un7z(archive, dest, opts),
ExtractionFormat::Gz
| ExtractionFormat::Xz
| ExtractionFormat::Bz2
| ExtractionFormat::Zst
| ExtractionFormat::Br
| ExtractionFormat::Lz4
| ExtractionFormat::Sz => {
bail!("extract_archive does not support compressed single-file format: {format}")
}
ExtractionFormat::Rar => bail!("rar format not supported"),
}
}
pub fn untar(
archive: &Path,
dest: &Path,
format: ExtractionFormat,
opts: &ExtractOptions,
) -> Result<()> {
if !format.is_tar_archive() && format != ExtractionFormat::Raw {
bail!("untar only supports tar formats, got {}", format);
}
debug!("tar -xf {} -C {}", archive.display(), dest.display());
if let Some(pr) = &opts.pr {
pr.set_message(format!(
"extract {}",
archive.file_name().unwrap().to_string_lossy()
));
}
let err = || {
let archive = display_path(archive);
let dest = display_path(dest);
format!("failed to extract tar: {archive} to {dest}")
};
run_blocking(|| {
let tar = open_tar(format, archive)?;
create_dir_all(dest).wrap_err_with(err)?;
let mut unpack_opts = UnpackOptions::default();
unpack_opts.preserve_mtime = opts.preserve_mtime;
let saw_appledouble = Rc::new(Cell::new(false));
unpack_opts.on_entry = Some(Box::new({
let saw_appledouble = saw_appledouble.clone();
move |entry| {
trace!("extracting {}", entry.path.display());
if is_appledouble_name(&entry.path) {
saw_appledouble.set(true);
}
}
}));
let summary = Archive::new(tar)
.unpack(dest, &mut unpack_opts)
.wrap_err_with(err)?;
debug!("tar extraction summary: {summary:?}");
#[cfg(target_os = "macos")]
if saw_appledouble.get() {
merge_appledouble_files(dest).wrap_err_with(err)?;
}
strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
format!(
"failed to strip path components from tar archive: {}",
display_path(archive)
)
})
})
}
fn is_appledouble_name(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.strip_prefix("._"))
.is_some_and(|described| !matches!(described, "" | "." | ".."))
}
#[cfg(target_os = "macos")]
fn merge_appledouble_files(dir: &Path) -> Result<()> {
use std::ffi::CString;
const MAGIC: [u8; 4] = [0x00, 0x05, 0x16, 0x07];
let mut sidecars = vec![];
for entry in WalkDir::new(dir) {
let entry = entry?;
if entry.file_type().is_file() && is_appledouble_name(entry.path()) {
sidecars.push(entry.into_path());
}
}
for sidecar in sidecars {
let name = sidecar.file_name().unwrap().to_string_lossy();
let target = sidecar.with_file_name(&name[2..]);
if target.symlink_metadata().is_err() {
continue;
}
let mut magic = [0u8; 4];
if File::open(&sidecar)
.and_then(|mut f| f.read_exact(&mut magic))
.is_err()
|| magic != MAGIC
{
continue;
}
let from = CString::new(sidecar.as_os_str().as_bytes())?;
let to = CString::new(target.as_os_str().as_bytes())?;
let flags = nix::libc::COPYFILE_UNPACK
| nix::libc::COPYFILE_NOFOLLOW
| nix::libc::COPYFILE_ACL
| nix::libc::COPYFILE_XATTR;
let rc =
unsafe { nix::libc::copyfile(from.as_ptr(), to.as_ptr(), std::ptr::null_mut(), flags) };
if rc != 0 {
warn!(
"failed to apply {} to {}: {}",
display_path(&sidecar),
display_path(&target),
std::io::Error::last_os_error()
);
continue;
}
if let Err(e) = remove_file(&sidecar) {
warn!("failed to remove {}: {e:#}", display_path(&sidecar));
}
}
Ok(())
}
fn open_tar(format: ExtractionFormat, archive: &Path) -> Result<Box<dyn std::io::Read>> {
let f = File::open(archive)?;
let tar: Box<dyn std::io::Read> = match format {
ExtractionFormat::TarGz | ExtractionFormat::Raw => Box::new(GzDecoder::new(f)),
ExtractionFormat::TarXz => Box::new(xz2::read::XzDecoder::new(f)),
ExtractionFormat::TarBz2 => Box::new(BzDecoder::new(f)),
ExtractionFormat::TarZst => Box::new(zstd_decoder(f)?),
ExtractionFormat::Tar => Box::new(f),
ExtractionFormat::TarBr | ExtractionFormat::TarLz4 | ExtractionFormat::TarSz => {
bail!("{format} format not supported")
}
ExtractionFormat::Gz
| ExtractionFormat::Xz
| ExtractionFormat::Bz2
| ExtractionFormat::Zst
| ExtractionFormat::Br
| ExtractionFormat::Lz4
| ExtractionFormat::Sz => {
bail!("{} is not a tar archive", format)
}
ExtractionFormat::Zip => bail!("zip format not supported"),
ExtractionFormat::SevenZip => bail!("7z format not supported"),
ExtractionFormat::Rar => bail!("rar format not supported"),
};
Ok(Box::new(LimitedReader::for_input(archive, tar)?))
}
fn reset_dir_mtime_to_now(dir: &Path) -> Result<()> {
let now = SystemTime::now();
for entry in WalkDir::new(dir) {
let entry = entry?;
if entry.file_type().is_file() {
set_times(entry.path(), Some(now), Some(now))?;
}
}
Ok(())
}
fn strip_archive_path_components(dir: &Path, strip_depth: usize) -> Result<()> {
if strip_depth == 0 {
return Ok(());
}
if strip_depth > 1 {
bail!("strip-components > 1 is not supported");
}
let top_level_paths = ls(dir)?;
for path in top_level_paths {
if !path.symlink_metadata()?.is_dir() {
continue;
}
let temp_path = path.with_file_name(format!(
"{}_tmp_strip",
path.file_name().unwrap().to_string_lossy()
));
do_rename(&path, &temp_path)?;
for entry in ls(&temp_path)? {
if let Some(file_name) = entry.file_name() {
let dest_path = dir.join(file_name);
do_rename(&entry, &dest_path)?;
} else {
continue;
}
}
remove_dir(temp_path)?;
}
Ok(())
}
pub fn unzip(archive: &Path, dest: &Path, opts: &ExtractOptions<'_>) -> Result<()> {
debug!("unzip {} -d {}", archive.display(), dest.display());
if let Some(pr) = &opts.pr {
pr.set_message(format!(
"extract {}",
archive.file_name().unwrap().to_string_lossy()
));
}
run_blocking(|| {
let mut zip = ZipArchive::new(File::open(archive)?)
.wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive)))?;
let err = || format!("failed to extract zip archive: {}", display_path(archive));
let limit = extract_limit(archive)?;
let mut declared = 0u64;
for i in 0..zip.len() {
declared = declared.saturating_add(zip.by_index_raw(i).wrap_err_with(err)?.size());
if declared > limit {
return Err(eyre::Report::new(extract_limit_error(limit)).wrap_err(err()));
}
}
zip.extract(dest).wrap_err_with(err)?;
if !opts.preserve_mtime {
reset_dir_mtime_to_now(dest)?;
}
strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
format!(
"failed to strip path components from zip archive: {}",
display_path(archive)
)
})
})
}
const DMG_VOLUME_METADATA: &[&str] = &[
".background",
".com.apple.timemachine.donotpresent",
".com.apple.timemachine.supported",
".DocumentRevisions-V100",
".DS_Store",
".fseventsd",
".MobileBackups",
".Spotlight-V100",
".TemporaryItems",
".Trashes",
".VolumeIcon.icns",
".HFS+ Private Directory Data\r",
".HFS+ Private Data\r",
];
fn copy_dmg_volume(volume: &Path, dest: &Path) -> Result<()> {
copy_dir_all_preserve_symlinks_skipping(volume, dest, DMG_VOLUME_METADATA)
}
fn dmg_attached_devices(info: &str, archive: &Path) -> Vec<String> {
let archive = canonicalize_or_self(archive);
let mut devices = vec![];
let mut matches = false;
let mut found_device = false;
for line in info.lines() {
if let Some(path) = line.strip_prefix("image-path") {
let path = path.trim_start().trim_start_matches(':').trim();
matches = paths_eq(&canonicalize_or_self(Path::new(path)), &archive);
found_device = false;
} else if matches
&& !found_device
&& let Some(dev) = line.split_whitespace().next()
&& dev.starts_with("/dev/disk")
{
devices.push(dev.to_string());
found_device = true;
}
}
devices
}
fn detach_stale_dmg(archive: &Path) {
let output = match std::process::Command::new("hdiutil").arg("info").output() {
Ok(output) if output.status.success() => output,
Ok(output) => {
debug!("hdiutil info failed: {}", output.status);
return;
}
Err(err) => {
debug!("failed to run hdiutil info: {err}");
return;
}
};
let info = String::from_utf8_lossy(&output.stdout);
for dev in dmg_attached_devices(&info, archive) {
debug!("hdiutil detach {dev} (left attached by an interrupted run)");
if let Err(err) = cmd!("hdiutil", "detach", "-force", dev.as_str()).run() {
debug!("failed to detach stale DMG {dev}: {err}");
}
}
}
pub fn un_dmg(archive: &Path, dest: &Path) -> Result<()> {
debug!(
"hdiutil attach -quiet -nobrowse -mountpoint {} {}",
dest.display(),
archive.display()
);
run_blocking(|| {
let mut lock_path = canonicalize_or_self(archive).into_os_string();
lock_path.push(".lock");
let _lock = crate::lock_file::LockFile::at(Path::new(&lock_path)).lock()?;
detach_stale_dmg(archive);
let tmp = tempfile::TempDir::new()?;
cmd!(
"hdiutil",
"attach",
"-quiet",
"-nobrowse",
"-mountpoint",
tmp.path(),
archive.to_path_buf()
)
.env("PAGER", "cat")
.stdin_bytes("Y\n")
.run()?;
let copy_result = copy_dmg_volume(tmp.path(), dest);
let detach_result = cmd!("hdiutil", "detach", tmp.path()).run();
match (copy_result, detach_result) {
(Err(copy_err), Err(detach_err)) => Err(copy_err)
.wrap_err_with(|| format!("additionally failed to detach DMG: {detach_err}")),
(Err(copy_err), _) => Err(copy_err),
(Ok(()), Err(detach_err)) => Err(detach_err.into()),
(Ok(()), Ok(_)) => Ok(()),
}
})
}
pub fn un_pkg(archive: &Path, dest: &Path) -> Result<()> {
debug!(
"pkgutil --expand-full {} {}",
archive.display(),
dest.display()
);
run_blocking(|| cmd!("pkgutil", "--expand-full", archive, dest).run())?;
Ok(())
}
pub fn un7z(archive: &Path, dest: &Path, opts: &ExtractOptions<'_>) -> Result<()> {
if let Some(pr) = &opts.pr {
pr.set_message(format!(
"extract {}",
archive.file_name().unwrap().to_string_lossy()
));
}
let resolved_dest;
let dest = if dest
.components()
.any(|c| c == std::path::Component::ParentDir)
{
create_dir_all(dest)?;
resolved_dest = dest
.canonicalize()
.wrap_err_with(|| format!("failed to resolve {}", display_path(dest)))?;
&resolved_dest
} else {
dest
};
run_blocking(|| {
let limit = extract_limit(archive)?;
let mut remaining = limit;
sevenz_rust2::decompress_file_with_extract_fn(archive, dest, |entry, reader, _| {
let dest_path = dest.join(
sanitize_7z_entry_path(entry.name())
.map_err(|err| sevenz_rust2::Error::Other(format!("{err:#}").into()))?,
);
let mut reader = LimitedReader {
inner: reader,
limit,
remaining,
};
let extracted = sevenz_rust2::default_entry_extract_fn(entry, &mut reader, &dest_path);
remaining = reader.remaining;
extracted
})
.wrap_err_with(|| format!("failed to extract 7z archive: {}", display_path(archive)))?;
if !opts.preserve_mtime {
reset_dir_mtime_to_now(dest)?;
}
strip_archive_path_components(dest, opts.strip_components).wrap_err_with(|| {
format!(
"failed to strip path components from 7z archive: {}",
display_path(archive)
)
})
})
}
pub fn is_plain_file_name(name: &str) -> bool {
if name.contains('/') || name.contains('\\') {
return false;
}
let mut components = Path::new(name).components();
matches!(
(components.next(), components.next()),
(Some(std::path::Component::Normal(_)), None)
)
}
pub fn is_safe_relative_path(path: &str) -> bool {
if path.is_empty() {
return false;
}
let normalized = path.replace('\\', "/");
let bytes = normalized.as_bytes();
if normalized.starts_with('/')
|| (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
{
return false;
}
let mut components = Path::new(&normalized).components();
matches!(components.next(), Some(std::path::Component::Normal(_)))
&& components.all(|component| matches!(component, std::path::Component::Normal(_)))
}
pub fn ensure_symlinks_stay_within(root: &Path) -> Result<()> {
if fs::symlink_metadata(root)?.file_type().is_symlink() {
bail!("{} is a symlink", display_path(root));
}
#[cfg(unix)]
rebase_absolute_symlinks_into_tree(root)?;
let real_root = root.canonicalize()?;
let mut dirs = vec![root.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
let kind = fs::symlink_metadata(&path)?.file_type();
if kind.is_dir() {
dirs.push(path);
} else if kind.is_symlink() {
let target = fs::read_link(&path)?;
let base = path.parent().unwrap_or(root).canonicalize()?;
if !link_target_stays_within(&real_root, root, &base, &target) {
bail!(
"symlink {} points outside of {}: {}",
display_path(&path),
display_path(root),
target.display()
);
}
}
}
}
Ok(())
}
#[cfg(unix)]
fn rebase_absolute_symlinks_into_tree(root: &Path) -> Result<()> {
let real_root = root.canonicalize()?;
loop {
let mut rewrote = false;
let mut dirs = vec![root.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
let kind = fs::symlink_metadata(&path)?.file_type();
if kind.is_dir() {
dirs.push(path);
continue;
}
if !kind.is_symlink() {
continue;
}
let target = fs::read_link(&path)?;
let Ok(inner) = target.strip_prefix("/") else {
continue;
};
let Some(inner) = inner.to_str().filter(|inner| is_safe_relative_path(inner))
else {
continue;
};
let candidate = root.join(inner);
if fs::symlink_metadata(&candidate).is_err() {
continue;
}
let parent = path.parent().unwrap_or(root);
let replacement = relative_path(parent, &candidate);
let base = parent.canonicalize()?;
if link_target_stays_within(&real_root, root, &base, &replacement) {
make_symlink(&replacement, &path)?;
rewrote = true;
}
}
}
if !rewrote {
return Ok(());
}
}
}
#[cfg(unix)]
pub fn rebase_guest_rootfs_absolute_symlinks(root: &Path) -> Result<()> {
if fs::symlink_metadata(root)?.file_type().is_symlink() {
bail!("{} is a symlink", display_path(root));
}
let mut dirs = vec![root.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
let kind = fs::symlink_metadata(&path)?.file_type();
if kind.is_dir() {
dirs.push(path);
} else if kind.is_symlink() {
let target = fs::read_link(&path)?;
if target.is_absolute() {
let replacement = if target == Path::new("/") {
relative_path(path.parent().unwrap(), root)
} else {
let target = target.strip_prefix(Path::new("/")).unwrap();
let target = target.to_str().ok_or_else(|| {
eyre::eyre!(
"absolute symlink target is not valid UTF-8: {}",
path.display()
)
})?;
if !is_safe_relative_path(target) {
bail!(
"absolute symlink target escapes guest rootfs: {} -> /{}",
display_path(&path),
target
);
}
relative_path(path.parent().unwrap(), &root.join(target))
};
make_symlink(&replacement, &path)?;
}
}
}
}
Ok(())
}
#[cfg(unix)]
fn relative_path(from: &Path, to: &Path) -> PathBuf {
use std::path::Component;
let from = from.components().collect::<Vec<_>>();
let to = to.components().collect::<Vec<_>>();
let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
let mut relative = PathBuf::new();
for component in &from[common..] {
if matches!(component, Component::Normal(_)) {
relative.push("..");
}
}
for component in &to[common..] {
relative.push(component.as_os_str());
}
if relative.as_os_str().is_empty() {
PathBuf::from(".")
} else {
relative
}
}
fn link_target_stays_within(root: &Path, given_root: &Path, base: &Path, target: &Path) -> bool {
use std::collections::VecDeque;
use std::path::Component;
const MAX_LINKS: usize = 40;
let parts = |path: &Path| -> VecDeque<PathBuf> {
path.components()
.map(|part| PathBuf::from(part.as_os_str()))
.collect()
};
let mut current = base.to_path_buf();
let mut pending = parts(target);
let mut followed = 0;
while let Some(part) = pending.pop_front() {
let Some(component) = part.components().next() else {
continue;
};
match component {
Component::Prefix(_) | Component::RootDir => {
let absolute: PathBuf = std::iter::once(part).chain(pending.drain(..)).collect();
let Some(rest) = [root, given_root]
.into_iter()
.find_map(|root| absolute.strip_prefix(root).ok())
else {
return false;
};
pending = parts(rest);
current = root.to_path_buf();
}
Component::CurDir => {}
Component::ParentDir => {
current.pop();
}
Component::Normal(name) => {
let candidate = current.join(name);
match fs::read_link(&candidate) {
Ok(link) => {
followed += 1;
if followed > MAX_LINKS {
return true;
}
for part in link.components().rev() {
pending.push_front(PathBuf::from(part.as_os_str()));
}
}
Err(_) => current = candidate,
}
}
}
if !current.starts_with(root) {
return false;
}
}
true
}
fn sanitize_7z_entry_path(path: &str) -> Result<PathBuf> {
let normalized = PathBuf::from(path.replace('\\', "/"));
let mut safe_path = PathBuf::new();
for component in normalized.components() {
match component {
std::path::Component::Normal(part) => safe_path.push(part),
std::path::Component::CurDir => {}
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_) => {
bail!("7z archive entry path escapes extraction directory: {path}")
}
}
}
Ok(safe_path)
}
pub fn split_file_name(path: &Path) -> (String, String) {
let file_name = path.file_name().unwrap().to_string_lossy();
let (file_name_base, ext) = file_name
.split_once('.')
.unwrap_or((file_name.as_ref(), ""));
(file_name_base.to_string(), ext.to_string())
}
pub fn same_file(a: &Path, b: &Path) -> bool {
a == b || desymlink_path(a) == desymlink_path(b)
}
pub fn path_starts_with_resolved(path: &Path, prefix: &Path) -> bool {
path.starts_with(prefix) || desymlink_path(path).starts_with(desymlink_path(prefix))
}
fn resolve_path_with_existing_prefix(path: &Path) -> PathBuf {
let mut resolved = if path.is_relative() {
env::current_dir().unwrap_or_default()
} else {
PathBuf::new()
};
let mut components = path.components();
while let Some(component) = components.next() {
if matches!(component, std::path::Component::CurDir) {
continue;
}
#[cfg(windows)]
if matches!(
component,
std::path::Component::Prefix(_) | std::path::Component::RootDir
) {
resolved.push(component.as_os_str());
continue;
}
let candidate = resolved.join(component.as_os_str());
match candidate.canonicalize() {
Ok(candidate) => resolved = candidate,
Err(_) => {
#[cfg(windows)]
{
let mut raw = resolved.into_os_string();
if Path::new(&raw).file_name().is_some() {
raw.push("\\");
}
raw.push(component.as_os_str());
for component in components {
raw.push("\\");
raw.push(component.as_os_str());
}
resolved = raw.into();
}
#[cfg(not(windows))]
{
resolved.push(component.as_os_str());
resolved.extend(components.map(|component| component.as_os_str()));
}
break;
}
}
}
resolved
}
pub fn desymlink_path(p: &Path) -> PathBuf {
if p.is_symlink()
&& let Ok(target) = fs::read_link(p)
{
let target = if target.is_absolute() {
target
} else {
p.parent().unwrap_or_else(|| Path::new("")).join(target)
};
return target
.canonicalize()
.unwrap_or_else(|_| resolve_path_with_existing_prefix(&target));
}
p.canonicalize()
.unwrap_or_else(|_| resolve_path_with_existing_prefix(p))
}
static DESYMLINKED: Lazy<Mutex<(u64, HashMap<PathBuf, PathBuf>)>> = Lazy::new(Default::default);
pub fn desymlink_path_cached(p: &Path) -> PathBuf {
if !p.is_absolute() {
return desymlink_path(p);
}
let generation = {
let cache = DESYMLINKED.lock().unwrap();
if let Some(resolved) = cache.1.get(p) {
return resolved.clone();
}
cache.0
};
let resolved = desymlink_path(p);
if p.exists() {
let mut cache = DESYMLINKED.lock().unwrap();
if cache.0 == generation {
cache.1.insert(p.to_path_buf(), resolved.clone());
}
}
resolved
}
pub fn clear_desymlink_cache() {
let mut cache = DESYMLINKED.lock().unwrap();
cache.0 += 1;
cache.1.clear();
}
pub fn clone_dir(from: &PathBuf, to: &PathBuf) -> Result<()> {
if cfg!(target_os = "macos") {
cmd!("/bin/cp", "-cR", from, to).run()?;
} else if cfg!(windows) {
let output = cmd!("robocopy", from, to, "/MIR").unchecked().run()?;
if !matches!(output.status.code(), Some(0..=7)) {
eyre::bail!("robocopy failed with {}", output.status);
}
} else {
cmd!("cp", "--reflink=auto", "-r", from, to).run()?;
}
Ok(())
}
fn skip_curdir_components(path: &Path) -> impl Iterator<Item = std::path::Component<'_>> {
path.components()
.skip_while(|c| matches!(c, std::path::Component::CurDir))
}
pub fn inspect_tar_contents(
archive: &Path,
format: ExtractionFormat,
) -> Result<Vec<(String, bool)>> {
let tar = open_tar(format, archive)?;
let mut archive = Archive::new(tar);
let mut top_level_components = std::collections::HashMap::new();
for entry in archive.entries()? {
let entry = entry?;
let path = entry.path()?;
let entry_type = entry.entry_type();
let mut components = skip_curdir_components(&path);
if let Some(first_component) = components.next() {
let name = first_component.as_os_str().to_string_lossy().to_string();
let is_directory = entry_type == EntryType::Directory || components.next().is_some();
let existing = top_level_components.entry(name).or_insert(false);
*existing = *existing || is_directory;
if top_level_components.len() > 1 {
break;
}
}
}
Ok(top_level_components.into_iter().collect())
}
pub fn inspect_zip_contents(archive: &Path) -> Result<Vec<(String, bool)>> {
let f = File::open(archive)?;
let mut archive = ZipArchive::new(f)
.wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive)))?;
let mut top_level_components = std::collections::HashMap::new();
for i in 0..archive.len() {
let file = archive.by_index(i)?;
if let Some(path) = file.enclosed_name() {
let mut components = skip_curdir_components(&path);
if let Some(first_component) = components.next() {
let name = first_component.as_os_str().to_string_lossy().to_string();
let is_directory = file.is_dir() || components.next().is_some();
let existing = top_level_components.entry(name).or_insert(false);
*existing = *existing || is_directory;
if top_level_components.len() > 1 {
break;
}
}
}
}
Ok(top_level_components.into_iter().collect())
}
pub fn inspect_7z_contents(archive: &Path) -> Result<Vec<(String, bool)>> {
let sevenz = sevenz_rust2::Archive::open(archive)?;
let mut top_level_components = std::collections::HashMap::new();
for file in &sevenz.files {
let path = sanitize_7z_entry_path(file.name())?;
let mut components = skip_curdir_components(&path);
if let Some(first_component) = components.next() {
let name = first_component.as_os_str().to_string_lossy().to_string();
let is_directory = file.is_directory() || components.next().is_some();
let existing = top_level_components.entry(name).or_insert(false);
*existing = *existing || is_directory;
if top_level_components.len() > 1 {
break;
}
}
}
Ok(top_level_components.into_iter().collect())
}
pub fn should_strip_components(archive: &Path, format: ExtractionFormat) -> Result<bool> {
let top_level_entries = match format {
ExtractionFormat::Zip => inspect_zip_contents(archive)?,
ExtractionFormat::SevenZip => inspect_7z_contents(archive)?,
_ => inspect_tar_contents(archive, format)?,
};
if top_level_entries.len() == 1 {
let (_, is_directory) = &top_level_entries[0];
Ok(*is_directory)
} else {
Ok(false)
}
}
#[derive(Debug, Clone)]
pub struct ArchiveContent {
pub name: String,
pub sha256: String,
}
const ARCHIVE_CONTENT_MAX_RATIO: u64 = 100;
const ARCHIVE_CONTENT_MIN_BUDGET: u64 = 256 * 1024 * 1024;
pub fn archive_content_files(
archive_path: &Path,
format: ExtractionFormat,
strip_components: usize,
) -> Result<Vec<ArchiveContent>> {
if strip_components > 1 {
bail!("content-level SLSA verification only supports strip_components values of 0 or 1");
}
let budget = fs::metadata(archive_path)?
.len()
.saturating_mul(ARCHIVE_CONTENT_MAX_RATIO)
.max(ARCHIVE_CONTENT_MIN_BUDGET);
match format {
ExtractionFormat::TarGz
| ExtractionFormat::TarXz
| ExtractionFormat::TarBz2
| ExtractionFormat::TarZst
| ExtractionFormat::Tar
| ExtractionFormat::TarBr
| ExtractionFormat::TarLz4
| ExtractionFormat::TarSz => {
archive_content_files_tar(archive_path, format, strip_components, budget)
}
ExtractionFormat::Zip => archive_content_files_zip(archive_path, strip_components, budget),
ExtractionFormat::SevenZip => {
bail!("content-level SLSA verification does not support 7z archives")
}
ExtractionFormat::Gz
| ExtractionFormat::Xz
| ExtractionFormat::Bz2
| ExtractionFormat::Zst
| ExtractionFormat::Br
| ExtractionFormat::Lz4
| ExtractionFormat::Sz
| ExtractionFormat::Raw => {
bail!("content-level SLSA verification only supports archive formats")
}
ExtractionFormat::Rar => bail!("rar format not supported"),
}
}
fn archive_content_files_tar(
archive_path: &Path,
format: ExtractionFormat,
strip_components: usize,
mut budget: u64,
) -> Result<Vec<ArchiveContent>> {
let tar = open_tar(format, archive_path)?;
let mut archive = Archive::new(tar);
let mut files = Vec::new();
for entry in archive.entries()? {
let mut entry = entry?;
let path = entry.path()?.into_owned();
let entry_type = entry.entry_type();
if entry_type == EntryType::Directory {
continue;
}
if entry_type != EntryType::File {
bail!(
"content-level SLSA verification does not support non-regular archive entry: {}",
path.display()
);
}
let name = normalize_archive_content_path(&path, strip_components)?;
let size = entry.size();
let sha256 = sha256_reader(&mut entry, size, &mut budget)?;
files.push(ArchiveContent { name, sha256 });
}
validate_archive_content_files(files)
}
fn archive_content_files_zip(
archive_path: &Path,
strip_components: usize,
mut budget: u64,
) -> Result<Vec<ArchiveContent>> {
let f = File::open(archive_path)?;
let mut archive = ZipArchive::new(f)
.wrap_err_with(|| format!("failed to open zip archive: {}", display_path(archive_path)))?;
let mut files = Vec::new();
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
if file.is_symlink() {
bail!(
"content-level SLSA verification does not support symlink archive entry: {}",
file.name().as_deref().unwrap_or("<unreadable name>")
);
}
if file.is_dir() {
continue;
}
let enclosed_name = file.enclosed_name().ok_or_else(|| {
eyre::eyre!(
"content-level SLSA verification rejected unsafe zip path: {}",
file.name().as_deref().unwrap_or("<unreadable name>")
)
})?;
let name = normalize_archive_content_path(&enclosed_name, strip_components)?;
let size = file.size();
let sha256 = sha256_reader(&mut file, size, &mut budget)?;
files.push(ArchiveContent { name, sha256 });
}
validate_archive_content_files(files)
}
fn sha256_reader(reader: &mut impl Read, size: u64, budget: &mut u64) -> Result<String> {
let over_budget = || {
eyre::eyre!(
"content-level SLSA verification rejected an archive that unpacks to more than {ARCHIVE_CONTENT_MAX_RATIO} times its size"
)
};
if size > *budget {
return Err(over_budget());
}
let mut hasher = Sha256::new();
let mut buf = [0; 8192];
loop {
let n = reader.read(&mut buf)?;
if n == 0 {
break;
}
*budget = budget.checked_sub(n as u64).ok_or_else(over_budget)?;
hasher.update(&buf[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
fn validate_archive_content_files(files: Vec<ArchiveContent>) -> Result<Vec<ArchiveContent>> {
if files.is_empty() {
bail!("content-level SLSA verification found no regular files in archive");
}
let mut names = std::collections::HashSet::new();
for file in &files {
if !names.insert(file.name.clone()) {
bail!(
"content-level SLSA verification found duplicate installed archive path: {}",
file.name
);
}
}
Ok(files)
}
fn normalize_archive_content_path(path: &Path, strip_components: usize) -> Result<String> {
let mut parts = Vec::new();
for component in skip_curdir_components(path) {
match component {
std::path::Component::Normal(part) => parts.push(part.to_string_lossy().to_string()),
std::path::Component::CurDir => {}
std::path::Component::ParentDir
| std::path::Component::RootDir
| std::path::Component::Prefix(_) => {
bail!(
"content-level SLSA verification rejected unsafe archive path: {}",
path.display()
)
}
}
}
if strip_components > parts.len() {
bail!(
"content-level SLSA verification stripped all components from archive path: {}",
path.display()
);
}
let parts = &parts[strip_components..];
if parts.is_empty() {
bail!(
"content-level SLSA verification stripped all components from archive path: {}",
path.display()
);
}
Ok(parts.join("/"))
}
#[cfg(test)]
mod tests;