diff options
| author | rorka <rorka@rorka.my.domain> | 2026-06-23 20:38:02 +0300 |
|---|---|---|
| committer | rorka <rorka@rorka.my.domain> | 2026-06-23 20:38:02 +0300 |
| commit | 3c2bec16cf37437759004bdf240fa6c85bc9e428 (patch) | |
| tree | 42c760a8dcd878cfee91c41958874c23b8bc7889 /src/install.rs | |
| parent | f726a6920d85f149efeae9ca1624138e9e374938 (diff) | |
| download | ror-3c2bec16cf37437759004bdf240fa6c85bc9e428.tar.gz ror-3c2bec16cf37437759004bdf240fa6c85bc9e428.zip | |
refactor: optimize package extraction and harden path traversal protection
Diffstat (limited to 'src/install.rs')
| -rw-r--r-- | src/install.rs | 527 |
1 files changed, 418 insertions, 109 deletions
diff --git a/src/install.rs b/src/install.rs index e688076..9f7d80d 100644 --- a/src/install.rs +++ b/src/install.rs @@ -1,3 +1,4 @@ +// install.rs use serde::{Deserialize, Serialize}; use std::fs; use std::io::{BufReader, Read, Write}; @@ -95,10 +96,40 @@ pub struct Package { pub libc: Option<String>, #[serde(default)] pub depends: Vec<Dependency>, + #[serde(default, rename = "musl.depends")] + pub musl_depends: Vec<Dependency>, + #[serde(default, rename = "glibc.depends")] + pub glibc_depends: Vec<Dependency>, #[serde(default)] pub conflicts: Vec<String>, #[serde(default)] pub oss: Option<bool>, + #[serde(default)] + pub services: Vec<ServiceEntry>, +} + +impl Package { + pub fn effective_depends(&self, libc: &str) -> impl Iterator<Item = &Dependency> { + let specific: Box<dyn Iterator<Item = &Dependency>> = match libc { + "musl" => Box::new(self.musl_depends.iter()), + _ => Box::new(self.glibc_depends.iter()), + }; + self.depends.iter().chain(specific) + } + + pub fn all_depends(&self) -> impl Iterator<Item = &Dependency> { + self.depends.iter() + .chain(self.musl_depends.iter()) + .chain(self.glibc_depends.iter()) + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +pub struct ServiceEntry { + pub init: String, + pub filepath: String, + #[serde(default)] + pub file: String, } #[derive(Debug, Serialize, Deserialize)] @@ -108,7 +139,7 @@ pub struct BinaryPackage { pub filename: String, #[serde(default)] pub mirrors: Vec<String>, - #[serde(rename = "type", default)] + #[serde(rename = "type", alias = "pkg_type", default)] pub pkg_type: Option<String>, #[serde(default)] pub url: String, @@ -317,6 +348,12 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, let mut f = file_result.map_err(|e: std::io::Error| e.to_string())?; let path = f.path().map_err(|e: std::io::Error| e.to_string())?.to_path_buf(); + for component in path.components() { + if matches!(component, std::path::Component::ParentDir) { + return Err(format!("Path traversal detected in archive entry: {}", path.display())); + } + } + f.unpack_in(dest_root).map_err(|e: std::io::Error| e.to_string())?; installed_files.push(path.to_string_lossy().to_string()); } @@ -348,30 +385,61 @@ fn normalize_libc(libc: &str) -> &str { } } -pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str) -> Result<&'a BinaryPackage, String> { +pub fn select_binary_for_arch<'a>(pkg: &'a Package, arch: &str, libc: &str, variant: Option<&str>) -> Result<&'a BinaryPackage, String> { let target_arch = normalize_arch(arch); - let target_libc = normalize_libc(libc); - debug!("Selecting binary for arch={}, libc={}", target_arch, target_libc); + debug!("Selecting binary for arch={}, libc={}, variant={:?}", target_arch, libc, variant); pkg.binaries .iter() .find(|b| { let arch_ok = b.arch == target_arch || b.arch == "all" || b.arch == "x86_64"; - let libc_ok = match b.libc.as_deref() { - None => true, - Some("gm") => true, - Some("static") => true, - Some(l) => normalize_libc(l) == target_libc, + let libc_ok = match variant { + Some("static") => b.libc.as_deref() == Some("static"), + Some("musl") => matches!(b.libc.as_deref(), Some("m") | Some("musl") | Some("gm")), + Some("glibc") => matches!(b.libc.as_deref(), Some("g") | Some("glibc") | Some("gm")), + _ => match b.libc.as_deref() { + None => true, + Some("gm") => true, + Some("static") => true, + Some(l) => normalize_libc(l) == normalize_libc(libc), + }, }; arch_ok && libc_ok }) .ok_or_else(|| format!( - "No binary for arch='{}' libc='{}' in package '{}'", - arch, libc, pkg.name + "No binary for arch='{}' libc='{}' variant={:?} in package '{}'", + arch, libc, variant, pkg.name )) } +pub fn parse_package_spec(s: &str) -> (String, Option<String>) { + if let Some(start) = s.find('{') { + if s.ends_with('}') { + let name = s[..start].trim().to_string(); + let variant = s[start + 1..s.len() - 1].trim().to_string(); + return (name, if variant.is_empty() { None } else { Some(variant) }); + } + } + (s.to_string(), None) +} + +fn find_case_insensitive_dir(parent: &Path, target: &str) -> Option<PathBuf> { + let exact = parent.join(target); + if exact.exists() && exact.is_dir() { + return Some(exact); + } + let target_lower = target.to_lowercase(); + for entry in fs::read_dir(parent).ok()? { + let entry = entry.ok()?; + if entry.file_type().ok()?.is_dir() && entry.file_name().to_string_lossy().to_lowercase() == target_lower { + return Some(entry.path()); + } + } + None +} + pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { + let (pkg_name, _) = parse_package_spec(pkg_name); debug!("Looking for package {} in repository root", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -382,16 +450,20 @@ pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { continue; } - let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); - if pkg_path.exists() && pkg_path.is_file() { - debug!("Found package at {:?}", pkg_path); - return Some(pkg_path); + if let Some(pkg_dir) = find_case_insensitive_dir(&cat_path, &pkg_name) { + let dir_name = pkg_dir.file_name()?.to_string_lossy().to_string(); + let pkg_path = pkg_dir.join(format!("{}.yaml", dir_name)); + if pkg_path.exists() && pkg_path.is_file() { + debug!("Found package at {:?}", pkg_path); + return Some(pkg_path); + } } } None } pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { + let (pkg_name, _) = parse_package_spec(pkg_name); debug!("Searching for package {} with repository info", pkg_name); let repo = Path::new(REPO_ROOT); let read_dir = fs::read_dir(repo).ok()?; @@ -402,17 +474,27 @@ pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { continue; } - let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); - if pkg_path.exists() && pkg_path.is_file() { - let repo_name = cat_path.file_name()?.to_string_lossy().to_string(); - debug!("Found package in repo {}: {:?}", repo_name, pkg_path); - return Some((pkg_path, repo_name)); + if let Some(pkg_dir) = find_case_insensitive_dir(&cat_path, &pkg_name) { + let dir_name = pkg_dir.file_name()?.to_string_lossy().to_string(); + let pkg_path = pkg_dir.join(format!("{}.yaml", dir_name)); + if pkg_path.exists() && pkg_path.is_file() { + let repo_name = cat_path.file_name()?.to_string_lossy().to_string(); + debug!("Found package in repo {}: {:?}", repo_name, pkg_path); + return Some((pkg_path, repo_name)); + } } } None } +pub fn resolve_package_name(pkg_name: &str) -> Option<String> { + let path = find_package_file(pkg_name)?; + let content = fs::read_to_string(path).ok()?; + let pkg: Package = serde_yaml::from_str(&content).ok()?; + Some(pkg.name) +} + pub fn verify_gpg_signature( archive_path: &Path, asc_path: &Path, @@ -440,6 +522,171 @@ pub fn verify_gpg_signature( Ok(()) } +fn expand_libc(libc: &str) -> &str { + match libc { + "g" | "glibc" => "glibc", + "m" | "musl" => "musl", + other => other, + } +} + +pub fn resolve_filename(pkg: &Package, binary: &BinaryPackage) -> String { + if !binary.filename.is_empty() { + return binary.filename.clone(); + } + let libc = expand_libc(binary.libc.as_deref().unwrap_or("glibc")); + let ext = match binary.pkg_type.as_deref() { + Some("ror") => "ror", + Some("sror") => "sror", + Some("deb") => "deb", + _ => "tar.xz", + }; + format!("{}-{}-pkg-{}-{}-rorkos.{}", pkg.name, pkg.version, binary.arch, libc, ext) +} + +#[allow(dead_code)] +pub fn generate_dict_url(filename: &str, mirrors: &[String], cfg: &config::Config) -> Result<String, String> { + let dict_filename = { + let stem = if let Some(s) = filename.strip_suffix(".ror") { + s + } else if let Some(pos) = filename.rfind('.') { + &filename[..pos] + } else { + filename + }; + format!("{}.dict", stem) + }; + for m in mirrors { + if m.starts_with("http://") || m.starts_with("https://") { + return Ok(m.replace("{filename}", &dict_filename)); + } else if let Some(repo) = cfg.repositories.get(m.as_str()) { + let base = repo.urlrepo.as_deref().unwrap_or(repo.url.as_str()); + let base = base.trim_end_matches('/'); + return Ok(format!("{}/{}", base, dict_filename)); + } + } + Err(format!("Cannot derive dict URL: no usable mirrors for {}", filename)) +} + +pub fn get_current_init_in_root(root_dir: &Path) -> Option<String> { + let db_path = root_dir.join("etc/ror/installed.json"); + if !db_path.exists() { + return None; + } + let content = fs::read_to_string(db_path).ok()?; + let db: InstalledDB = serde_json::from_str(&content).ok()?; + for (name, _) in db.packages { + if let Some(pkg) = load_package(&name) { + if pkg.provides.contains(&"init-system".to_string()) { + return Some(name); + } + } + } + None +} + +pub fn remove_services(pkg: &Package) { + for service in &pkg.services { + let path = std::path::Path::new(&service.filepath); + if path.exists() { + match std::fs::remove_file(path) { + Ok(_) => println!( + "{} Removed service for '{}': {}", + "[ror]".green().bold(), pkg.name, service.filepath + ), + Err(e) => eprintln!( + "{} Failed to remove service file '{}': {}", + "[ror]".red().bold(), service.filepath, e + ), + } + } + } +} + +pub fn install_services(pkg: &Package) { + let current_init = get_current_init_in_root(Path::new("/")); + for service in &pkg.services { + match ¤t_init { + None => { + eprintln!( + "{} No init system detected, skipping service for '{}'", + "[ror]".yellow().bold(), pkg.name + ); + } + Some(init) if init != &service.init => { + eprintln!( + "{} Package '{}' has a service for '{}', but your init is '{}' — not supported", + "[ror]".yellow().bold(), pkg.name, service.init, init + ); + } + Some(_) => { + let path = std::path::Path::new(&service.filepath); + if let Some(parent) = path.parent() { + if let Err(e) = std::fs::create_dir_all(parent) { + eprintln!( + "{} Failed to create service directory '{}': {}", + "[ror]".red().bold(), parent.display(), e + ); + continue; + } + } + match std::fs::write(path, &service.file) { + Ok(_) => println!( + "{} Created service for '{}': {}", + "[ror]".green().bold(), pkg.name, service.filepath + ), + Err(e) => eprintln!( + "{} Failed to write service file '{}': {}", + "[ror]".red().bold(), service.filepath, e + ), + } + } + } + } +} + +pub fn install_services_to_root(pkg: &Package, root_dir: &Path) { + let current_init = get_current_init_in_root(root_dir); + for service in &pkg.services { + match ¤t_init { + None => { + eprintln!( + "{} No init system detected in rootfs, skipping service for '{}'", + "[ror]".yellow().bold(), pkg.name + ); + } + Some(init) if init != &service.init => { + eprintln!( + "{} Package '{}' has a service for '{}', but rootfs init is '{}' — not supported", + "[ror]".yellow().bold(), pkg.name, service.init, init + ); + } + Some(_) => { + let full_path = root_dir.join(service.filepath.trim_start_matches('/')); + if let Some(parent) = full_path.parent() { + if let Err(e) = std::fs::create_dir_all(parent) { + eprintln!( + "{} Failed to create service directory '{}': {}", + "[ror]".red().bold(), parent.display(), e + ); + continue; + } + } + match std::fs::write(&full_path, &service.file) { + Ok(_) => println!( + "{} Created service for '{}': {}", + "[ror]".green().bold(), pkg.name, service.filepath + ), + Err(e) => eprintln!( + "{} Failed to write service file '{}': {}", + "[ror]".red().bold(), service.filepath, e + ), + } + } + } + } +} + pub fn install_package(pkg_name: &str, cfg: &config::Config) { debug!("Starting install of package: {}", pkg_name); match install_package_with_result(pkg_name, cfg) { @@ -460,7 +707,9 @@ pub fn install_package(pkg_name: &str, cfg: &config::Config) { } pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Result<InstalledPackage, String> { - debug!("Resolving package {}", pkg_name); + let (pure_name, variant) = parse_package_spec(pkg_name); + let pkg_name = pure_name.as_str(); + debug!("Resolving package {} variant={:?}", pkg_name, variant); let mut spinner = Spinner::new(&format!("Resolving {}", pkg_name)); spinner.tick(&format!("Resolving {}", pkg_name)); @@ -496,7 +745,7 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu return Err("No binary packages defined".to_string()); } - let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc)?; + let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc, variant.as_deref())?; debug!("Selected binary: arch={}, libc={:?}", binary.arch, binary.libc); let db = InstalledDB::load(); @@ -510,6 +759,9 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } } + let effective_filename = resolve_filename(&pkg, binary); + debug!("Effective filename: {}", effective_filename); + let mut urls_to_try = Vec::new(); if !binary.url.is_empty() { urls_to_try.push(binary.url.clone()); @@ -517,22 +769,28 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu urls_to_try = binary .mirrors .iter() - .filter_map(|m| { - if m.starts_with("http://") || m.starts_with("https://") { - Some(m.replace("{filename}", &binary.filename)) + .map(|m| { + let base_url = if let Some(repo) = cfg.repositories.get(m.as_str()) { + repo.urlrepo.as_deref().unwrap_or(&repo.url) + } else { + m.as_str() + }; + + if base_url.contains("{filename}") { + base_url.replace("{filename}", &effective_filename) } else { - let repo = cfg.repositories.get(m.as_str())?; - let base = repo.urlrepo.as_deref().or(Some(repo.url.as_str()))?; - let base = base.trim_end_matches('/'); - Some(format!("{}/{}", base, binary.filename)) + let base = base_url.trim_end_matches('/'); + format!("{}/{}", base, effective_filename) } }) .collect(); - } else { - return Err(format!("No URL or mirrors provided for package {}", pkg_name)); } + if urls_to_try.is_empty() { - return Err(format!("Could not resolve any download URL for package {}", pkg_name)); + return Err(format!( + "No download URLs for package {}. binary.url={:?}, binary.mirrors={:?}", + pkg_name, binary.url, binary.mirrors + )); } debug!("Resolved {} download URLs", urls_to_try.len()); @@ -609,14 +867,9 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut files = extract_deb(&archive_path, Path::new("/"))?; all_installed_files.append(&mut files); } else if pkg_type == "ror" { - let dict_url = binary.dict.as_ref() - .ok_or_else(|| format!("Package {} has type ror but no dict URL", pkg_name))?; - sp2.tick(&format!("Downloading dictionary for {}...", pkg_name)); - debug!("Downloading dictionary: {}", dict_url); - let dict_path = download_and_verify(dict_url, "", cfg)?; - let files = extract_ror(&archive_path, &dict_path, &work_dir) + sp2.tick(&format!("Extracting {}...", pkg_name)); + let files = extract_ror(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; - let _ = fs::remove_file(&dict_path); sp2.tick(&format!("Installing files for {}...", pkg_name)); let mut installed = install_files(&work_dir, &binary.install_prefix, &files) .map_err(|e| format!("Failed to install files: {}", e))?; @@ -660,6 +913,8 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu sp3.finish("Install steps done"); } + install_services(&pkg); + debug!("Installation complete for {}", pkg_name); Ok(InstalledPackage { @@ -671,42 +926,84 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu }) } -pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; - let mut tar = TarArchive::new(file); - tar.unpack(target_dir).map_err(|e| format!("Tar unpack failed: {}", e))?; - let mut files = Vec::new(); - for entry in WalkDir::new(target_dir).into_iter().filter_map(|e| e.ok()) { - if entry.file_type().is_file() || entry.file_type().is_symlink() { - let rel_path = entry.path().strip_prefix(target_dir).unwrap(); - files.push(rel_path.to_string_lossy().to_string()); +fn safe_unpack<R: Read>(mut archive: TarArchive<R>, target_dir: &Path) -> Result<(), String> { + for entry in archive.entries().map_err(|e| e.to_string())? { + let mut entry = entry.map_err(|e| e.to_string())?; + let path = entry.path().map_err(|e| e.to_string())?.to_path_buf(); + for component in path.components() { + if matches!(component, std::path::Component::ParentDir) { + return Err(format!("Path traversal detected in archive entry: {}", path.display())); + } } + entry.unpack_in(target_dir).map_err(|e| e.to_string())?; } - Ok(files) + Ok(()) } -pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { +pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; - let dict_data = fs::read(dict_path).map_err(|e| e.to_string())?; - let decoder = ZstdDecoder::with_dictionary(BufReader::new(file), &dict_data) - .map_err(|e| format!("Zstd decoder with dictionary failed: {}", e))?; - let mut tar = TarArchive::new(decoder); - tar.unpack(target_dir).map_err(|e| format!("Tar unpack failed: {}", e))?; - let mut files = Vec::new(); - for entry in WalkDir::new(target_dir).into_iter().filter_map(|e| e.ok()) { + let path_str = archive_path.to_str().unwrap_or(""); + let reader: Box<dyn Read> = if path_str.ends_with(".tar.xz") || path_str.ends_with(".txz") { + Box::new(xz2::read::XzDecoder::new(file)) + } else if path_str.ends_with(".tar.zst") || path_str.ends_with(".tar.zstd") { + Box::new(ZstdDecoder::new(file).map_err(|e| format!("Zstd init failed: {}", e))?) + } else { + Box::new(file) + }; + let tar = TarArchive::new(reader); + safe_unpack(tar, target_dir)?; + strip_package_prefix(target_dir)?; + collect_files(target_dir) +} + +fn strip_package_prefix(target_dir: &Path) -> Result<(), String> { + const STANDARD_DIRS: &[&str] = &[ + "bin", "boot", "dev", "etc", "home", "lib", "lib64", "mnt", "opt", + "proc", "root", "run", "sbin", "srv", "sys", "tmp", "usr", "var", + ]; + let mut non_standard: Vec<String> = Vec::new(); + if let Ok(reader) = fs::read_dir(target_dir) { + for entry in reader.flatten() { + if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) { + if let Ok(name) = entry.file_name().into_string() { + if !STANDARD_DIRS.contains(&name.as_str()) { + non_standard.push(name); + } + } + } + } + } + if non_standard.len() != 1 { + return Ok(()); + } + let prefix = &non_standard[0]; + let prefix_dir = target_dir.join(prefix); + if !prefix_dir.is_dir() { + return Ok(()); + } + let mut todo: Vec<(PathBuf, PathBuf)> = Vec::new(); + for entry in WalkDir::new(&prefix_dir).into_iter().filter_map(|e| e.ok()) { if entry.file_type().is_file() || entry.file_type().is_symlink() { - let rel_path = entry.path().strip_prefix(target_dir).unwrap(); - files.push(rel_path.to_string_lossy().to_string()); + let rel = entry.path().strip_prefix(&prefix_dir).unwrap(); + let dst = target_dir.join(rel); + todo.push((entry.path().to_path_buf(), dst)); } } - Ok(files) + for (src, dst) in &todo { + if let Some(parent) = dst.parent() { + let _ = fs::create_dir_all(parent); + } + let _ = fs::remove_file(dst); + if fs::rename(src, dst).is_err() { + let _ = fs::copy(src, dst); + let _ = fs::remove_file(src); + } + } + let _ = fs::remove_dir_all(&prefix_dir); + Ok(()) } -pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; - let decoder = ZstdDecoder::new(BufReader::new(file)).map_err(|e| format!("Zstd decoder failed: {}", e))?; - let mut tar = TarArchive::new(decoder); - tar.unpack(target_dir).map_err(|e| format!("Tar unpack failed: {}", e))?; +fn collect_files(target_dir: &Path) -> Result<Vec<String>, String> { let mut files = Vec::new(); for entry in WalkDir::new(target_dir).into_iter().filter_map(|e| e.ok()) { if entry.file_type().is_file() || entry.file_type().is_symlink() { @@ -717,6 +1014,54 @@ pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String Ok(files) } +pub fn extract_ror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + let data = fs::read(archive_path).map_err(|e| e.to_string())?; + let decompressed = if data.len() > 1 && data[0] == 1 && (data[1] & 1) != 0 { + let dict_len = u32::from_le_bytes([data[2], data[3], data[4], data[5]]) as usize; + if data.len() < 6 + dict_len { + return Err("Invalid .ror header: truncated dictionary".into()); + } + let dict_data = &data[6..6 + dict_len]; + let compressed = &data[6 + dict_len..]; + let mut decoder = ZstdDecoder::with_dictionary(std::io::Cursor::new(compressed), dict_data) + .map_err(|e| format!("Zstd decoder with dictionary failed: {}", e))?; + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut decoder, &mut out) + .map_err(|e| format!("Zstd decompression failed: {}", e))?; + out + } else { + let zstd_magic: &[u8; 4] = &[0x28, 0xB5, 0x2F, 0xFD]; + let is_zstd_frame = data.len() >= 4 && &data[0..4] == zstd_magic; + let extern_dict_path = archive_path.with_extension("dict"); + if is_zstd_frame && extern_dict_path.exists() { + let dict_data = fs::read(&extern_dict_path).map_err(|e| e.to_string())?; + let mut decoder = ZstdDecoder::with_dictionary(std::io::Cursor::new(&data), &dict_data) + .map_err(|e| format!("Zstd decoder with external dictionary failed: {}", e))?; + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut decoder, &mut out) + .map_err(|e| format!("Zstd decompression with external dict failed: {}", e))?; + out + } else { + zstd::decode_all(std::io::Cursor::new(&data)) + .map_err(|e| format!("Zstd decompression failed: {}", e))? + } + }; + let tar = TarArchive::new(std::io::Cursor::new(decompressed)); + safe_unpack(tar, target_dir)?; + strip_package_prefix(target_dir)?; + collect_files(target_dir) +} + +pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + let compressed = fs::read(archive_path).map_err(|e| e.to_string())?; + let decompressed = zstd::decode_all(std::io::Cursor::new(&compressed)) + .map_err(|e| format!("Zstd decompression failed: {}", e))?; + let tar = TarArchive::new(std::io::Cursor::new(decompressed)); + safe_unpack(tar, target_dir)?; + strip_package_prefix(target_dir)?; + collect_files(target_dir) +} + fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Vec<String>, String> { debug!("Installing {} files from {:?} to prefix {}", files.len(), source_dir, prefix); let prefix_path = Path::new(prefix); @@ -741,6 +1086,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve symlink(&target, &dst) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; } else { + let _ = fs::remove_file(&dst); fs::copy(&src, &dst) .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; } @@ -749,7 +1095,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve Ok(installed) } -pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { +pub fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { debug!("Installing {} files to root {:?}", files.len(), root); let mut installed = Vec::new(); for rel_path in files { @@ -772,7 +1118,6 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; } else { let _ = fs::remove_file(&dst); - fs::copy(&src, &dst) .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; } @@ -830,8 +1175,9 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { } pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { + let (pkg_name, _) = parse_package_spec(pkg_name); debug!("Getting info for package {}", pkg_name); - let pkg_path = find_package_file(pkg_name)?; + let pkg_path = find_package_file(&pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; let name = pkg_name.to_string(); let version = content @@ -844,8 +1190,9 @@ pub fn get_package_info(pkg_name: &str) -> Option<(String, String)> { } pub fn load_package(pkg_name: &str) -> Option<Package> { + let (pkg_name, _) = parse_package_spec(pkg_name); debug!("Loading full package metadata for {}", pkg_name); - let pkg_path = find_package_file(pkg_name)?; + let pkg_path = find_package_file(&pkg_name)?; let content = fs::read_to_string(pkg_path).ok()?; serde_yaml::from_str(&content).ok() } @@ -919,15 +1266,8 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con .map_err(|e| format!("Failed to install files: {}", e))?; installed } else if ext == "ror" { - let dict_path = archive_path.with_extension("dict"); - if !dict_path.exists() { - return Err(format!( - "Dictionary file not found: {} (expected alongside .ror)", - dict_path.display() - )); - } - debug!("Extracting local ror package with dictionary"); - let files = extract_ror(archive_path, &dict_path, &work_dir) + debug!("Extracting local ror package"); + let files = extract_ror(archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let installed = install_files_to_root(&work_dir, Path::new("/"), &files) .map_err(|e| format!("Failed to install files: {}", e))?; @@ -949,34 +1289,3 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con installed_at: Local::now().to_rfc3339(), }) } - -fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { - debug!("Copying files from {:?} to root {:?}", source_dir, root); - let mut installed = Vec::new(); - for rel_path in files { - let src = source_dir.join(rel_path); - let dst = root.join(rel_path); - - let meta = fs::symlink_metadata(&src) - .map_err(|_| format!("File {} not found in package", rel_path))?; - - if let Some(parent) = dst.parent() { - fs::create_dir_all(parent) - .map_err(|e| format!("Failed to create dir {}: {}", parent.display(), e))?; - } - - if meta.is_symlink() { - let target = fs::read_link(&src) - .map_err(|e| format!("Failed to read link {}: {}", src.display(), e))?; - let _ = fs::remove_file(&dst); - symlink(&target, &dst) - .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; - } else { - let _ = fs::remove_file(&dst); - fs::copy(&src, &dst) - .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; - } - installed.push(rel_path.clone()); - } - Ok(installed) -} |