use std::fs;
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use super::sha256::{is_valid_sha256_hex, parse_sha256sums_for_file, sha256_file_hex};
static SDK_STAGE_SEQ: AtomicU64 = AtomicU64::new(1);
pub(crate) fn ends_with_ignore_ascii_case(haystack: &str, suffix: &str) -> bool {
haystack.len() >= suffix.len()
&& haystack.as_bytes()[haystack.len() - suffix.len()..].eq_ignore_ascii_case(suffix.as_bytes())
}
pub(crate) fn extract_archive_filename(url_or_path: &str) -> String {
let no_frag = url_or_path.split('#').next().unwrap_or(url_or_path);
let no_query = no_frag.split('?').next().unwrap_or(no_frag);
let candidate = no_query
.rsplit(['/', '\\'])
.next()
.map(str::trim)
.unwrap_or_default();
if candidate.is_empty()
|| candidate == "."
|| candidate == ".."
|| candidate.contains('\0')
|| candidate.contains(':')
{
"artifact.tar.gz".to_owned()
} else {
candidate.to_owned()
}
}
pub fn validate_relative_sdk_path(raw: &str) -> Result<PathBuf, String> {
if raw.is_empty() {
return Err("path must not be empty".to_owned());
}
if raw.contains('\0') {
return Err(format!("path '{raw}' contains NUL byte"));
}
if raw.starts_with('/') || raw.starts_with('\\') {
return Err(format!("absolute path '{raw}' is not allowed"));
}
let bytes = raw.as_bytes();
if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
return Err(format!("drive-prefixed path '{raw}' is not allowed"));
}
let mut normalized = PathBuf::new();
for segment in raw.split(['/', '\\']) {
if segment.is_empty() || segment == "." {
continue;
}
if segment == ".." {
return Err(format!("path traversal '..' in '{raw}' is not allowed"));
}
normalized.push(segment);
}
for comp in normalized.components() {
if !matches!(comp, Component::Normal(_)) {
return Err(format!("non-relative path component in '{raw}' is not allowed"));
}
}
Ok(normalized)
}
pub(crate) fn validate_relative_symlink_target(link_rel: &Path, target: &str) -> Result<(), String> {
if target.is_empty() || target.contains('\0') {
return Err(format!(
"invalid symlink target '{target}' for '{}'",
link_rel.display()
));
}
if target.starts_with('/') || target.starts_with('\\') {
return Err(format!(
"escaping absolute symlink '{}' -> '{target}' is not allowed",
link_rel.display()
));
}
let bytes = target.as_bytes();
if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
return Err(format!(
"escaping drive-prefixed symlink '{}' -> '{target}' is not allowed",
link_rel.display()
));
}
let mut depth: isize = link_rel
.parent()
.map(|p| {
p.components()
.filter(|c| matches!(c, Component::Normal(_)))
.count() as isize
})
.unwrap_or(0);
for seg in target.split(['/', '\\']) {
if seg.is_empty() || seg == "." {
continue;
}
if seg == ".." {
depth -= 1;
if depth < 0 {
return Err(format!(
"escaping symlink '{}' -> '{target}' traverses outside archive root",
link_rel.display()
));
}
} else {
depth += 1;
}
}
Ok(())
}
pub(crate) struct TempPathGuard {
path: Option<PathBuf>,
is_dir: bool,
}
impl TempPathGuard {
pub(crate) fn file(path: PathBuf) -> Self {
Self { path: Some(path), is_dir: false }
}
pub(crate) fn dir(path: PathBuf) -> Self {
Self { path: Some(path), is_dir: true }
}
pub(crate) fn path(&self) -> &Path {
self.path.as_deref().unwrap_or_else(|| Path::new(""))
}
pub(crate) fn disarm(&mut self) {
self.path = None;
}
}
impl Drop for TempPathGuard {
fn drop(&mut self) {
if let Some(p) = self.path.take() {
if self.is_dir {
let _ = fs::remove_dir_all(p);
} else {
let _ = fs::remove_file(p);
}
}
}
}
pub(crate) fn swap_dir_atomic(stage: &Path, dest: &Path) -> Result<(), String> {
let parent = dest
.parent()
.ok_or_else(|| format!("invalid destination '{}'", dest.display()))?;
let seq = SDK_STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
let backup = parent.join(format!(
".{}.prev-{}-{seq}",
dest.file_name().and_then(|n| n.to_str()).unwrap_or("sdk"),
std::process::id()
));
let had_dest = dest.exists();
if had_dest {
fs::rename(dest, &backup).map_err(|e| {
format!(
"failed to rotate '{}' -> '{}': {e}",
dest.display(),
backup.display()
)
})?;
}
if let Err(err) = fs::rename(stage, dest) {
if had_dest {
let _ = fs::rename(&backup, dest);
}
return Err(format!(
"failed to move '{}' -> '{}': {err}",
stage.display(),
dest.display()
));
}
if had_dest {
let _ = fs::remove_dir_all(&backup);
}
Ok(())
}
pub(crate) fn validate_archive_before_extract(archive: &Path) -> Result<(), String> {
let name = archive
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
if ends_with_ignore_ascii_case(name, ".zip") {
if cfg!(windows) {
return validate_tar_entries(archive, &["-tf"], &["-tvf"]);
}
let out = Command::new("unzip")
.args(["-Z", "-1"])
.arg(archive)
.output()
.map_err(|e| format!("failed to inspect zip '{}': {e}", archive.display()))?;
if !out.status.success() {
return Err(format!(
"inspecting zip archive '{}' failed ({})",
archive.display(),
out.status
));
}
for line in String::from_utf8_lossy(&out.stdout).lines() {
let entry = line.trim_end_matches('\r');
if !entry.is_empty() {
validate_relative_sdk_path(entry)?;
}
}
return Ok(());
}
if ends_with_ignore_ascii_case(name, ".tar.zst") {
validate_tar_entries(archive, &["--zstd", "-tf"], &["--zstd", "-tvf"])
} else {
validate_tar_entries(archive, &["-tf"], &["-tvf"])
}
}
fn validate_tar_entries(archive: &Path, list_args: &[&str], verbose_args: &[&str]) -> Result<(), String> {
let list_out = Command::new("tar")
.args(list_args)
.arg(archive)
.output()
.map_err(|e| format!("failed to inspect archive '{}': {e}", archive.display()))?;
if !list_out.status.success() {
return Err(format!(
"inspecting archive '{}' failed ({})",
archive.display(),
list_out.status
));
}
for line in String::from_utf8_lossy(&list_out.stdout).lines() {
let entry = line.trim_end_matches('\r');
if !entry.is_empty() {
validate_relative_sdk_path(entry)?;
}
}
let verbose_out = Command::new("tar")
.args(verbose_args)
.arg(archive)
.output()
.map_err(|e| format!("failed to inspect archive metadata '{}': {e}", archive.display()))?;
if verbose_out.status.success() {
for line in String::from_utf8_lossy(&verbose_out.stdout).lines() {
let trimmed = line.trim_end_matches('\r');
if trimmed.starts_with('l') {
if let Some((before, target)) = trimmed.rsplit_once(" -> ") {
let link_path = before.split_whitespace().last().unwrap_or_default();
let rel = validate_relative_sdk_path(link_path)?;
validate_relative_symlink_target(&rel, target)?;
} else {
return Err(format!(
"unparseable symlink entry in archive '{}': '{trimmed}'",
archive.display()
));
}
} else if trimmed.starts_with('h')
&& let Some((_, target)) = trimmed.rsplit_once(" link to ")
{
validate_relative_sdk_path(target)?;
}
}
}
Ok(())
}
fn validate_extracted_symlinks(root: &Path, dir: &Path) -> Result<(), String> {
let entries = fs::read_dir(dir)
.map_err(|e| format!("failed to scan extracted dir '{}': {e}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("failed to read extracted entry: {e}"))?;
let path = entry.path();
let meta = fs::symlink_metadata(&path)
.map_err(|e| format!("failed to stat '{}': {e}", path.display()))?;
let rel = path.strip_prefix(root).unwrap_or(&path);
if meta.file_type().is_symlink() {
let target = fs::read_link(&path)
.map_err(|e| format!("failed to read symlink '{}': {e}", path.display()))?;
let target_str = target.to_str().ok_or_else(|| {
format!("non-UTF-8 symlink target at '{}' is not allowed", rel.display())
})?;
validate_relative_symlink_target(rel, target_str)?;
} else if meta.is_dir() {
validate_extracted_symlinks(root, &path)?;
}
}
Ok(())
}
pub fn extract_archive(archive: &Path, dest_dir: &Path) -> Result<(), String> {
validate_archive_before_extract(archive)?;
fs::create_dir_all(dest_dir)
.map_err(|e| format!("failed to create '{}': {e}", dest_dir.display()))?;
let name = archive
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
let status = if ends_with_ignore_ascii_case(name, ".zip") {
if cfg!(windows) {
Command::new("tar")
.args(["-xf"])
.arg(archive)
.arg("-C")
.arg(dest_dir)
.status()
} else {
Command::new("unzip")
.args(["-q", "-o"])
.arg(archive)
.arg("-d")
.arg(dest_dir)
.status()
}
} else if ends_with_ignore_ascii_case(name, ".tar.zst") {
Command::new("tar")
.args(["--zstd", "-xf"])
.arg(archive)
.arg("-C")
.arg(dest_dir)
.status()
} else {
Command::new("tar")
.args(["-xf"])
.arg(archive)
.arg("-C")
.arg(dest_dir)
.status()
}
.map_err(|e| format!("failed to extract '{}': {e}", archive.display()))?;
if !status.success() {
return Err(format!(
"extracting '{}' into '{}' failed with {status}",
archive.display(),
dest_dir.display()
));
}
validate_extracted_symlinks(dest_dir, dest_dir)?;
Ok(())
}
fn try_fetch_url_text(url: &str) -> Option<String> {
let out = Command::new("curl")
.args(["-fsSL", "--retry", "2", url])
.output()
.ok()?;
if !out.status.success() {
return None;
}
String::from_utf8(out.stdout).ok()
}
pub(crate) fn resolve_auto_sha256(url_or_path: &str, archive_filename: &str) -> Option<String> {
let local_path = url_or_path
.strip_prefix("file://")
.map(PathBuf::from)
.or_else(|| {
let p = Path::new(url_or_path);
p.is_file().then(|| p.to_path_buf())
});
if let Some(path) = local_path {
let sidecar = PathBuf::from(format!("{}.sha256", path.display()));
if let Ok(text) = fs::read_to_string(&sidecar)
&& let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, true)
{
return Some(hex);
}
if let Some(dir) = path.parent() {
for sums_name in ["SHA256SUMS.txt", "SHA256SUMS"] {
if let Ok(text) = fs::read_to_string(dir.join(sums_name))
&& let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, false)
{
return Some(hex);
}
}
}
return None;
}
let no_frag = url_or_path.split('#').next().unwrap_or(url_or_path);
let no_query = no_frag.split('?').next().unwrap_or(no_frag);
if let Some(slash) = no_query.rfind('/') {
let base_dir = &no_query[..=slash];
if let Some(text) = try_fetch_url_text(&format!("{base_dir}SHA256SUMS.txt"))
&& let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, false)
{
return Some(hex);
}
}
if let Some(text) = try_fetch_url_text(&format!("{no_query}.sha256"))
&& let Some(hex) = parse_sha256sums_for_file(&text, archive_filename, true)
{
return Some(hex);
}
None
}
pub fn fetch_and_extract_verified(
url_or_path: &str,
expected_sha256: Option<&str>,
dest_dir: &Path,
) -> Result<(), String> {
fetch_and_extract_verified_with_policy(url_or_path, expected_sha256, false, dest_dir)
}
pub fn fetch_and_extract_verified_with_policy(
url_or_path: &str,
expected_sha256: Option<&str>,
allow_unverified: bool,
dest_dir: &Path,
) -> Result<(), String> {
let parent = dest_dir
.parent()
.ok_or_else(|| format!("invalid cache destination '{}'", dest_dir.display()))?;
fs::create_dir_all(parent)
.map_err(|e| format!("failed to create '{}': {e}", parent.display()))?;
let filename = extract_archive_filename(url_or_path);
let seq = SDK_STAGE_SEQ.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let tmp_archive_guard = TempPathGuard::file(parent.join(format!(".nv-dl-{pid}-{seq}-{filename}")));
let mut tmp_stage_guard = TempPathGuard::dir(parent.join(format!(".nv-stage-{pid}-{seq}-{filename}")));
if let Some(local) = url_or_path.strip_prefix("file://") {
fs::copy(local, tmp_archive_guard.path())
.map_err(|e| format!("failed to copy '{local}': {e}"))?;
} else if Path::new(url_or_path).is_file() {
fs::copy(url_or_path, tmp_archive_guard.path())
.map_err(|e| format!("failed to copy '{url_or_path}': {e}"))?;
} else {
let status = Command::new("curl")
.args(["-fsSL", "--retry", "3", "-o"])
.arg(tmp_archive_guard.path())
.arg(url_or_path)
.status()
.map_err(|e| format!("failed to spawn `curl` for '{url_or_path}': {e}"))?;
if !status.success() {
return Err(format!("`curl` failed fetching '{url_or_path}' ({status})"));
}
}
let explicit = expected_sha256.map(str::trim).filter(|s| !s.is_empty());
let resolved_sha = match explicit {
Some(hex) => {
if !is_valid_sha256_hex(hex) {
return Err(format!(
"invalid --sha256 digest '{hex}' for '{url_or_path}' (expected 64 hex chars)"
));
}
#[expect(
clippy::disallowed_methods,
reason = "cold CLI SDK install path normalizing an explicit 64-char SHA-256 hex digest"
)]
Some(hex.to_ascii_lowercase())
}
None => resolve_auto_sha256(url_or_path, &filename),
};
match resolved_sha {
Some(expected) => {
let actual = sha256_file_hex(tmp_archive_guard.path())?;
if !actual.eq_ignore_ascii_case(&expected) {
return Err(format!(
"SHA-256 mismatch for '{url_or_path}': expected {expected}, got {actual}"
));
}
}
None if allow_unverified => {
eprintln!("warning: skipping SHA-256 verification for '{url_or_path}' (--allow-unverified)");
}
None => {
return Err(format!(
"SHA-256 verification is required for '{url_or_path}' (no --sha256 given and no SHA256SUMS.txt or .sha256 found; pass --sha256 <HEX> or --allow-unverified)"
));
}
}
extract_archive(tmp_archive_guard.path(), tmp_stage_guard.path())?;
drop(tmp_archive_guard);
let content_root = unwrap_single_dir(tmp_stage_guard.path());
let moving_stage_itself = content_root == tmp_stage_guard.path();
swap_dir_atomic(&content_root, dest_dir)?;
if moving_stage_itself {
tmp_stage_guard.disarm();
}
Ok(())
}
fn unwrap_single_dir(dir: &Path) -> PathBuf {
let Ok(rd) = fs::read_dir(dir) else {
return dir.to_path_buf();
};
let entries: Vec<PathBuf> = rd.filter_map(|e| e.ok().map(|x| x.path())).collect();
if entries.len() == 1
&& entries[0].is_dir()
&& !fs::symlink_metadata(&entries[0]).is_ok_and(|m| m.file_type().is_symlink())
&& entries[0]
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| !n.ends_with(".xcframework"))
{
entries[0].clone()
} else {
dir.to_path_buf()
}
}