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 | |
| parent | f726a6920d85f149efeae9ca1624138e9e374938 (diff) | |
| download | ror-3c2bec16cf37437759004bdf240fa6c85bc9e428.tar.gz ror-3c2bec16cf37437759004bdf240fa6c85bc9e428.zip | |
refactor: optimize package extraction and harden path traversal protection
Diffstat (limited to 'src')
| -rwxr-xr-x[-rw-r--r--] | src/apply.rs | 24 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/check.rs | 12 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/config.rs | 1 | ||||
| -rw-r--r-- | src/debug.rs | 1 | ||||
| -rw-r--r-- | src/delete.rs | 18 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/group.rs | 17 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/info.rs | 24 | ||||
| -rw-r--r-- | src/install.rs | 527 | ||||
| -rw-r--r-- | src/listinstalled.rs | 5 | ||||
| -rw-r--r-- | src/main.rs | 26 | ||||
| -rw-r--r-- | src/parallel.rs | 88 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/progress.rs | 4 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/repo.rs | 0 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/resolver.rs | 65 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/rootfs.rs | 622 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/search.rs | 1 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/sync.rs | 1 | ||||
| -rwxr-xr-x[-rw-r--r--] | src/update.rs | 3 |
18 files changed, 1094 insertions, 345 deletions
diff --git a/src/apply.rs b/src/apply.rs index 2af85fe..423a8bc 100644..100755 --- a/src/apply.rs +++ b/src/apply.rs @@ -105,6 +105,14 @@ pub fn get_target_packages(sys_config: &SystemConfig, _cfg: &Config) -> Result<V for group_name in &sys_config.groups { let group = group::load_group(group_name) .map_err(|e| format!("Failed to load group '{}': {}", group_name, e))?; + if let Some(ref libc_pkg) = group.libc { + let libc_name = match libc_pkg.as_str() { + "musl" => "musl", + "glibc" => "glibc", + other => other, + }; + target.insert(libc_name.to_string()); + } for pkg in group.packages { target.insert(pkg); } @@ -143,11 +151,17 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - let db = InstalledDB::load(); let mut outdated = HashSet::new(); - let required = resolver::collect_required_packages(&target_names, &db, &mut outdated) + let libc = &cfg.global.libc; + let required = resolver::collect_required_packages(&target_names, &db, &mut outdated, libc) .map_err(|e| format!("Dependency resolution failed: {}", e))?; + let empty_db = InstalledDB::default(); + let mut _dummy = HashSet::new(); + let target_state = resolver::collect_required_packages(&target_names, &empty_db, &mut _dummy, libc) + .map_err(|e| format!("Target state resolution failed: {}", e))?; + let installed_set: HashSet<String> = db.packages.keys().cloned().collect(); - let mut to_remove: Vec<String> = installed_set.difference(&required).cloned().collect(); + let mut to_remove: Vec<String> = installed_set.difference(&target_state).cloned().collect(); if let Err(conflict_err) = resolver::check_conflicts(&required, &db) { let msg = conflict_err.to_string(); @@ -213,8 +227,9 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - let final_db = InstalledDB::load(); let final_installed: HashSet<String> = final_db.packages.keys().cloned().collect(); let final_required = { - let mut fresh_outdated = HashSet::new(); - resolver::collect_required_packages(&target_names, &final_db, &mut fresh_outdated) + let empty = InstalledDB::default(); + let mut dummy = HashSet::new(); + resolver::collect_required_packages(&target_names, &empty, &mut dummy, libc) .map_err(|e| format!("Re-resolution after install failed: {}", e))? }; let extra_remove: Vec<String> = final_installed.difference(&final_required).cloned().collect(); @@ -244,3 +259,4 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - println!("{} System apply completed.", "[ror]".green().bold()); Ok(()) } + diff --git a/src/check.rs b/src/check.rs index 9e9b775..530814f 100644..100755 --- a/src/check.rs +++ b/src/check.rs @@ -24,13 +24,18 @@ fn load_expected_hashes( binary: &BinaryPackage, cfg: &Config, ) -> Result<HashMap<String, String>, String> { + let effective_filename = crate::install::resolve_filename( + &crate::install::load_package(_pkg_name).unwrap(), + binary, + ); + let urls = if !binary.url.is_empty() { vec![binary.url.clone()] } else { binary .mirrors .iter() - .map(|m| m.replace("{filename}", &binary.filename)) + .map(|m| m.replace("{filename}", &effective_filename)) .collect() }; @@ -50,7 +55,7 @@ fn load_expected_hashes( .as_ref() .ok_or_else(|| "Missing dict URL for .ror".to_string())?; let dict_path = download_and_verify(dict_url, "", cfg)?; - let res = extract_ror(&archive_path, &dict_path, work_dir); + let res = extract_ror(&archive_path, work_dir); let _ = fs::remove_file(&dict_path); res } else if pkg_type == "sror" { @@ -106,7 +111,7 @@ pub fn check_integrity(cfg: &Config) { } }; - let binary = match select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc) { + let binary = match select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc, None) { Ok(b) => b, Err(_) => { println!("{}", "SKIP (no binary)".yellow()); @@ -196,3 +201,4 @@ pub fn check_integrity(cfg: &Config) { } } } + diff --git a/src/config.rs b/src/config.rs index c2d8cdb..2ff93d8 100644..100755 --- a/src/config.rs +++ b/src/config.rs @@ -228,3 +228,4 @@ impl Config { fs::write(path, ini) } } + diff --git a/src/debug.rs b/src/debug.rs index 2f7da4e..317cc58 100644 --- a/src/debug.rs +++ b/src/debug.rs @@ -12,3 +12,4 @@ macro_rules! debug { $crate::debug::debug(&format!($($arg)*)); }; } + diff --git a/src/delete.rs b/src/delete.rs index 83164a3..6966f82 100644 --- a/src/delete.rs +++ b/src/delete.rs @@ -18,7 +18,7 @@ fn check_dependents(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { } if let Some(pkg) = load_package(name) { - for dep in &pkg.depends { + for dep in pkg.all_depends() { match dep { Dependency::Single(raw) => { let (dep_name, _) = parse_dep(raw); @@ -171,6 +171,7 @@ pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), St pub fn remove_package_files_only(_pkg_name: &str, files: &[String]) -> bool { debug!("Removing {} files for package {}", files.len(), _pkg_name); + let mut removed = 0usize; let mut failed = false; for rel_path in files { @@ -181,18 +182,17 @@ pub fn remove_package_files_only(_pkg_name: &str, files: &[String]) -> bool { eprintln!("{} Failed to remove {}: {}", "[ror]".red().bold(), full_path.display(), e); failed = true; } else { - println!("{} Removed {}", ">>>".green(), full_path.display()); + removed += 1; } } else { debug!("File {} does not exist, skipping", full_path.display()); } } - if failed { - debug!("Some files could not be removed"); - } else { - debug!("All files removed successfully"); + if removed > 0 { + println!("{} Removed {} file(s)", ">>>".green(), removed); } + debug!("Removal done: {} ok, failed={}", removed, failed); !failed } @@ -225,6 +225,10 @@ pub fn remove_package(pkg_name: &str) { println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name); + if let Some(pkg_meta) = load_package(pkg_name) { + crate::install::remove_services(&pkg_meta); + } + let success = remove_package_files_only(pkg_name, &files); db.packages.remove(pkg_name); @@ -250,7 +254,7 @@ pub fn has_dependents(pkg_name: &str, db: &InstalledDB, keep_set: &HashSet<Strin continue; } if let Some(pkg) = load_package(name) { - for dep in &pkg.depends { + for dep in pkg.all_depends() { match dep { Dependency::Single(raw) => { let (dep_name, _) = parse_dep(raw); diff --git a/src/group.rs b/src/group.rs index a08bdba..3f1844b 100644..100755 --- a/src/group.rs +++ b/src/group.rs @@ -15,6 +15,21 @@ pub struct Group { pub packages: Vec<String>, #[serde(default)] pub install_steps: String, + + #[serde(rename = "init-system")] + #[allow(dead_code)] + pub init_system: Option<String>, + #[serde(rename = "core-utils")] + #[allow(dead_code)] + pub core_utils: Option<String>, + #[allow(dead_code)] + pub udev: Option<String>, + #[serde(default)] + #[allow(dead_code)] + pub sh: Vec<String>, + #[serde(default)] + #[allow(dead_code)] + pub su: Vec<String>, } #[allow(dead_code)] @@ -68,6 +83,7 @@ pub fn load_group(group_name: &str) -> Result<Group, String> { .map_err(|e| format!("Group YAML error: {}", e))?; Ok(group) } + pub fn list_groups() { let groups_dir = "/var/ror/packages/groups"; if !Path::new(groups_dir).exists() { @@ -92,3 +108,4 @@ pub fn list_groups() { } } } + diff --git a/src/info.rs b/src/info.rs index 0e791fb..d827a53 100644..100755 --- a/src/info.rs +++ b/src/info.rs @@ -5,6 +5,21 @@ use colored::Colorize; const REPO_ROOT: &str = "/var/ror/packages"; +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 +} + fn find_package_file(pkg_name: &str) -> Option<PathBuf> { let repo = Path::new(REPO_ROOT); for entry in fs::read_dir(repo).ok()? { @@ -13,9 +28,12 @@ fn find_package_file(pkg_name: &str) -> Option<PathBuf> { if !cat_path.is_dir() { continue; } - let pkg_path = cat_path.join(pkg_name).join(format!("{}.yaml", pkg_name)); - if pkg_path.exists() && pkg_path.is_file() { - 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(); + let pkg_path = pkg_dir.join(format!("{}.yaml", dir_name)); + if pkg_path.exists() && pkg_path.is_file() { + return Some(pkg_path); + } } } None 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) -} diff --git a/src/listinstalled.rs b/src/listinstalled.rs index 66d4d78..d57a3f5 100644 --- a/src/listinstalled.rs +++ b/src/listinstalled.rs @@ -1,6 +1,11 @@ use colored::Colorize; use crate::install::InstalledDB; +pub fn print_count() { + let db = InstalledDB::load(); + println!("{}", db.packages.len()); +} + pub fn print_installed() { let db = InstalledDB::load(); let packages = db.packages; diff --git a/src/main.rs b/src/main.rs index 609b899..4e326f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,6 +50,9 @@ enum Commands { #[command(alias = "l")] ListInstalled, + + #[command(alias = "c")] + Count, Info { package: String, @@ -82,13 +85,11 @@ enum Commands { BuildRootfs { #[arg(long)] - group: Option<String>, + group: String, #[arg(long)] target: PathBuf, #[arg(long, default_value = "native")] arch: String, - #[arg(long)] - config: Option<PathBuf>, }, Di { @@ -149,6 +150,10 @@ async fn main() { listinstalled::print_installed(); } + Commands::Count => { + listinstalled::print_count(); + } + Commands::Info { package } => { info::print_package_info(&package); } @@ -189,16 +194,15 @@ async fn main() { repo::list_repositories(); } - Commands::BuildRootfs { group, target, arch, config } => { + Commands::BuildRootfs { group, target, arch } => { let cfg = config::Config::load(); let arch = if arch == "native" { "native" } else { &arch }; if let Err(e) = rootfs::build_rootfs( - group.as_deref(), + &group, &target, &cfg, arch, true, - config.as_deref(), ) { eprintln!("{} {}", "[ror]".red().bold(), e); } @@ -279,6 +283,16 @@ async fn main() { ); } + let remote_pkgs: Vec<String> = remote_pkgs.into_iter().map(|p| { + let (name, variant) = install::parse_package_spec(&p); + install::resolve_package_name(&name).map(|canonical| { + match variant { + Some(v) => format!("{}{{{}}}", canonical, v), + None => canonical, + } + }).unwrap_or(p) + }).collect(); + if !remote_pkgs.is_empty() { if let Err(e) = parallel::install_packages_parallel( diff --git a/src/parallel.rs b/src/parallel.rs index fbbbcfe..ed4671f 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -1,6 +1,4 @@ // parallel.rs -// Asynchronous package installation with race conditions, atomic updates. - #![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_variables)] @@ -24,18 +22,18 @@ use crate::config::Config; use crate::install::{ extract_deb, extract_ror, extract_sror, extract_native, select_binary_for_arch, InstalledDB, InstalledPackage, Package, - find_package_with_repo, verify_gpg_signature, + find_package_with_repo, verify_gpg_signature, install_services, }; use crate::resolver; -/*global cache for package metadata to avoid repeated yaml parsing. */ static PACKAGE_CACHE: once_cell::sync::Lazy<Mutex<HashMap<String, Arc<Package>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); -/*flag to detect user interruption. */ static INTERRUPTED: AtomicBool = AtomicBool::new(false); pub fn load_package_cached(name: &str) -> Option<Arc<Package>> { + let (pure_name, _) = crate::install::parse_package_spec(name); + let name = pure_name.as_str(); let mut cache = PACKAGE_CACHE.lock().unwrap(); if let Some(pkg) = cache.get(name) { return Some(Arc::clone(pkg)); @@ -100,11 +98,23 @@ impl AtomicInstaller { backup_paths.push((bak_path, dst.clone())); } - if let Err(e) = std::fs::rename(&src, &dst) { - if let Some((last_bak, orig)) = backup_paths.pop() { - let _ = std::fs::rename(&last_bak, &orig); + let rename_err = std::fs::rename(&src, &dst).err(); + if let Some(e) = rename_err { + use std::io::ErrorKind; + if e.raw_os_error() == Some(18) { + if let Err(ce) = std::fs::copy(&src, &dst) { + if let Some((last_bak, orig)) = backup_paths.pop() { + let _ = std::fs::rename(&last_bak, &orig); + } + return Err(format!("Failed to install (copy) {}: {}", dst.display(), ce)); + } + let _ = std::fs::remove_file(&src); + } else { + if let Some((last_bak, orig)) = backup_paths.pop() { + let _ = std::fs::rename(&last_bak, &orig); + } + return Err(format!("Failed to install {}: {}", dst.display(), e)); } - return Err(format!("Failed to install {}: {}", dst.display(), e)); } installed.push(rel_path.clone()); @@ -170,7 +180,6 @@ async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<Pa result } -/*race-condition download: tries all mirrors and returns the first success. */ async fn race_download( urls: Vec<String>, expected_sha: &str, @@ -216,6 +225,7 @@ async fn race_download( async fn install_single_impl( pkg_name: &str, + variant: Option<&str>, cfg: Arc<Config>, ) -> Result<InstalledPackage, String> { println!("[{}] Resolving {}...", "[ror]".cyan().bold(), pkg_name); @@ -229,29 +239,42 @@ async fn install_single_impl( .ok_or_else(|| format!("Repository info not found for {}", pkg_name))?; let repo_cfg = cfg.repositories.get(&repo_name); - 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)?; + + let effective_filename = crate::install::resolve_filename(&pkg, binary); let mut urls = Vec::new(); if !binary.url.is_empty() { urls.push(binary.url.clone()); } else { for m in &binary.mirrors { - let url = m.replace("{filename}", &binary.filename); - if url.starts_with("http") { - urls.push(url); - } + 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() + }; + + let url = if base_url.contains("{filename}") { + base_url.replace("{filename}", &effective_filename) + } else { + let base = base_url.trim_end_matches('/'); + format!("{}/{}", base, effective_filename) + }; + urls.push(url); } } if urls.is_empty() { - return Err("No download URLs provided".to_string()); + return Err(format!( + "No download URLs for package {}. binary.url={:?}, binary.mirrors={:?}, effective_filename={}", + pkg_name, binary.url, binary.mirrors, effective_filename + )); } println!("[{}] Downloading {}...", "[ror]".blue(), pkg_name); let (archive_path, winning_url) = race_download(urls, &binary.sha256, cfg.clone()).await?; - /*gpg verification */ if repo_cfg.map(|r| r.gpg_support).unwrap_or(false) { if let Some(key_file) = repo_cfg.and_then(|r| r.gpg_key.as_deref()) { let asc_url = format!("{}.asc", winning_url); @@ -297,11 +320,7 @@ async fn install_single_impl( if ptype == "deb" { extract_deb(&archive_path, &work_dir)? } else if ptype == "ror" { - let dict = binary.dict.as_ref().ok_or("Missing dict URL")?; - let dict_path = download_one(dict, "", &cfg).await?; - let f = extract_ror(&archive_path, &dict_path, &work_dir)?; - let _ = std::fs::remove_file(&dict_path); - f + extract_ror(&archive_path, &work_dir)? } else if ptype == "sror" { extract_sror(&archive_path, &work_dir)? } else { @@ -309,7 +328,7 @@ async fn install_single_impl( } }; - println!("[{}] Installing {}...", "[ror]".yellow(), pkg_name); + println!("{} Installing {}...", "[ror]".blue().bold(), pkg_name); let installer = AtomicInstaller::new(shadow); let installed_files = @@ -320,6 +339,8 @@ async fn install_single_impl( let elapsed = start_time.elapsed().as_millis(); println!("[>] Installed {} ({:.2}ms)", pkg_name, elapsed as f64); + install_services(&pkg); + Ok(InstalledPackage { name: pkg.name.clone(), version: pkg.version.clone(), @@ -340,10 +361,23 @@ pub async fn install_packages_parallel( INTERRUPTED.store(true, Ordering::SeqCst); }); + let mut variant_map: HashMap<String, String> = HashMap::new(); + for spec in packages { + let (name, variant) = crate::install::parse_package_spec(spec); + if let Some(v) = variant { + variant_map.insert(name, v); + } + } + + let pure_packages: Vec<String> = packages.iter() + .map(|s| crate::install::parse_package_spec(s).0) + .collect(); + let installed_db = InstalledDB::load(); let mut outdated = HashSet::new(); + let libc = &cfg.global.libc; let required = - resolver::collect_required_packages(packages, &installed_db, &mut outdated)?; + resolver::collect_required_packages(&pure_packages, &installed_db, &mut outdated, libc)?; if required.is_empty() { println!("[>] Nothing to install."); @@ -352,7 +386,7 @@ pub async fn install_packages_parallel( } resolver::check_conflicts(&required, &installed_db)?; - let graph = resolver::build_graph(&required, &installed_db)?; + let graph = resolver::build_graph(&required, &installed_db, libc)?; let levels = graph.compute_levels(); let mut total_installed: Vec<InstalledPackage> = Vec::new(); @@ -374,8 +408,9 @@ pub async fn install_packages_parallel( for pkg in level_pkgs { let c = cfg.clone(); let pkg_name = pkg.clone(); + let variant = variant_map.get(pkg).cloned(); tasks.push(tokio::spawn(async move { - install_single_impl(&pkg_name, c).await + install_single_impl(&pkg_name, variant.as_deref(), c).await })); } @@ -405,7 +440,6 @@ pub async fn install_packages_parallel( return Err(format!("Level {} failed", level_idx)); } - /*save db after every level to prevent inconsistent state */ let mut db = InstalledDB::load(); for pkg in &total_installed { db.add_package(pkg.clone()); diff --git a/src/progress.rs b/src/progress.rs index f6f2227..bd9c806 100644..100755 --- a/src/progress.rs +++ b/src/progress.rs @@ -1,3 +1,4 @@ +// src/progress.rs use std::io::{self, Write}; pub struct ProgressBar { @@ -17,14 +18,13 @@ impl ProgressBar { } } - pub fn inc(&mut self, msg: &str) { self.current += 1; self.message = msg.to_string(); self.render(); } - fn render(&self) { + pub fn render(&self) { let filled = if self.total == 0 { 0 } else { diff --git a/src/repo.rs b/src/repo.rs index a6d4b41..a6d4b41 100644..100755 --- a/src/repo.rs +++ b/src/repo.rs diff --git a/src/resolver.rs b/src/resolver.rs index 240119e..1141980 100644..100755 --- a/src/resolver.rs +++ b/src/resolver.rs @@ -99,11 +99,22 @@ pub fn collect_required_packages( packages: &[String], installed_db: &InstalledDB, outdated: &mut HashSet<String>, + libc: &str, ) -> Result<HashSet<String>> { let mut required = HashSet::new(); let mut stack: Vec<String> = packages.iter().cloned().collect(); - while let Some(pkg_name) = stack.pop() { + let static_set: HashSet<String> = packages.iter() + .filter_map(|s| { + let (name, variant) = crate::install::parse_package_spec(s); + if variant.as_deref() == Some("static") { Some(name) } else { None } + }) + .collect(); + + while let Some(spec) = stack.pop() { + let (pkg_name, variant) = crate::install::parse_package_spec(&spec); + let is_static = variant.as_deref() == Some("static") || static_set.contains(&pkg_name); + if required.contains(&pkg_name) { continue; } @@ -118,27 +129,29 @@ pub fn collect_required_packages( outdated.insert(pkg_name.clone()); required.insert(pkg_name.clone()); } else { - let pkg = match load_package(&pkg_name) { - Some(p) => p, - None => continue, - }; - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - if needs_update(raw, installed_db) { - let (name, _) = parse_dep(raw); - outdated.insert(name.clone()); - if !required.contains(&name) { stack.push(name); } - } - } - Dependency::Any(alts) => { - for alt in alts { - if needs_update(alt, installed_db) { - let (name, _) = parse_dep(alt); + if !is_static { + let pkg = match load_package(&pkg_name) { + Some(p) => p, + None => continue, + }; + for dep in pkg.effective_depends(libc) { + match dep { + Dependency::Single(raw) => { + if needs_update(raw, installed_db) { + let (name, _) = parse_dep(raw); outdated.insert(name.clone()); if !required.contains(&name) { stack.push(name); } } } + Dependency::Any(alts) => { + for alt in alts { + if needs_update(alt, installed_db) { + let (name, _) = parse_dep(alt); + outdated.insert(name.clone()); + if !required.contains(&name) { stack.push(name); } + } + } + } } } } @@ -148,12 +161,16 @@ pub fn collect_required_packages( required.insert(pkg_name.clone()); } + if is_static { + continue; + } + let pkg = match load_package(&pkg_name) { Some(p) => p, None => return Err(format!("Package '{}' not found", pkg_name)), }; - for dep in &pkg.depends { + for dep in pkg.effective_depends(libc) { match dep { Dependency::Single(raw) => { let (name, _) = parse_dep(raw); @@ -178,14 +195,19 @@ pub fn collect_required_packages( Ok(required) } -pub fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB) -> Result<DependencyGraph> { +pub fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB, libc: &str) -> Result<DependencyGraph> { let mut graph = DependencyGraph::new(); for pkg_name in packages { + graph.edges.entry(pkg_name.clone()).or_insert_with(Vec::new); + graph.reverse.entry(pkg_name.clone()).or_insert_with(Vec::new); + } + + for pkg_name in packages { let pkg = load_package(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - for dep in &pkg.depends { + for dep in pkg.effective_depends(libc) { match dep { Dependency::Single(raw) => { let (name, _) = parse_dep(raw); @@ -249,3 +271,4 @@ pub fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) - Ok(()) } + diff --git a/src/rootfs.rs b/src/rootfs.rs index 027cce1..e31444d 100644..100755 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,98 +1,107 @@ -use crate::apply::SystemConfig; +// src/rootfs.rs use std::collections::HashMap; use std::fs; -use std::path::{Path}; +use std::path::Path; use std::os::unix::fs::symlink; use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU64, AtomicBool, Ordering}; use std::thread; use colored::Colorize; -use serde::Serialize; use crate::config; use crate::progress::ProgressBar; use chrono::Local; use crate::install::{ - Dependency, load_package, download_and_verify, - extract_native, extract_ror, install_files_with_root, select_binary_for_arch, - InstalledDB, InstalledPackage, + Dependency, load_package, + extract_native, extract_ror, extract_sror, extract_deb, install_files_to_root, select_binary_for_arch, + InstalledDB, InstalledPackage, resolve_filename, install_services_to_root, }; use nix::mount::{mount, umount2, MntFlags, MsFlags}; use nix::unistd::{chroot, chdir, fork, ForkResult, execve}; use nix::sys::wait::{waitpid, WaitStatus}; -use std::io::Write; +use std::io::{Read, Write}; use std::ffi::CString; use std::ffi::CStr; use std::collections::HashSet; use std::collections::VecDeque; + struct DownloadTask { pkg_name: String, urls: Vec<String>, sha256: String, } -#[derive(Serialize)] -struct InstalledEntry { - name: String, - version: String, -} - -#[derive(Serialize)] -struct ListInstalled { - packages: Vec<InstalledEntry>, -} - -pub fn collect_install_order(start_pkgs: &[String]) -> Result<Vec<String>, String> { +pub fn collect_install_order(start_pkgs: &[String], libc: &str) -> Result<Vec<String>, String> { let mut order: Vec<String> = Vec::new(); let mut visited: HashSet<String> = HashSet::new(); fn visit( - name: &str, + spec: &str, + libc: &str, visited: &mut HashSet<String>, order: &mut Vec<String>, ) -> Result<(), String> { - if visited.contains(name) { + let (name, _) = crate::install::parse_package_spec(spec); + if visited.contains(&name) { return Ok(()); } - visited.insert(name.to_string()); + visited.insert(name.clone()); - let pkg = load_package(name) + let pkg = load_package(&name) .ok_or_else(|| format!("Package '{}' not found in repository", name))?; - for dep in &pkg.depends { + for dep in pkg.effective_depends(libc) { match dep { - Dependency::Single(d) => visit(d, visited, order)?, + Dependency::Single(d) => visit(d, libc, visited, order)?, Dependency::Any(alts) => { if let Some(first) = alts.first() { - visit(first, visited, order)?; + visit(first, libc, visited, order)?; } } } } - order.push(name.to_string()); + order.push(spec.to_string()); Ok(()) } for pkg in start_pkgs { - visit(pkg, &mut visited, &mut order)?; + visit(pkg, libc, &mut visited, &mut order)?; } Ok(order) } -fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &str) -> Result<Vec<DownloadTask>, String> { +fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &str, cfg: &config::Config) -> Result<Vec<DownloadTask>, String> { let mut tasks = Vec::new(); - for pkg_name in packages { - let pkg = load_package(pkg_name) + for pkg_spec in packages { + let (pkg_name, variant) = crate::install::parse_package_spec(pkg_spec); + let pkg = load_package(&pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - let binary = select_binary_for_arch(&pkg, target_arch, target_libc) + let binary = select_binary_for_arch(&pkg, target_arch, target_libc, variant.as_deref()) .map_err(|e| format!("No binary for '{}': {}", pkg_name, e))?; - let urls: Vec<String> = if !binary.url.is_empty() { + let effective_filename = resolve_filename(&pkg, binary); + + // Prefer local package files when available + let workspace = std::env::var("ROR_WORKSPACE").unwrap_or_else(|_| "/home/rorka/rorkos".to_string()); + let local_path = Path::new(&workspace).join(&effective_filename); + let urls: Vec<String> = if local_path.exists() { + vec![format!("file://{}", local_path.display())] + } else if !binary.url.is_empty() { vec![binary.url.clone()] } else { binary.mirrors.iter() - .map(|m| m.replace("{filename}", &binary.filename)) + .filter_map(|m| { + if m.starts_with("http://") || m.starts_with("https://") { + Some(m.replace("{filename}", &effective_filename)) + } else { + let 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('/'); + Some(format!("{}/{}", base, effective_filename)) + } + }) .collect() }; @@ -100,6 +109,8 @@ fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &st return Err(format!("No download URLs for package '{}'", pkg_name)); } + println!("{} {} -> {}", ">>>".cyan(), pkg_name, urls[0]); + tasks.push(DownloadTask { pkg_name: pkg_name.clone(), urls, @@ -110,82 +121,200 @@ fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &st Ok(tasks) } +fn download_file_quiet( + url: &str, + expected_sha: &str, + bytes_done_global: &Arc<AtomicU64>, + bytes_expected_global: &Arc<AtomicU64>, +) -> Result<(std::path::PathBuf, u64), String> { + use sha2::{Sha256, Digest}; + + let tmp_dir = Path::new("/tmp/ror-download"); + std::fs::create_dir_all(tmp_dir).map_err(|e| e.to_string())?; + let file_name = url.split('/').last().unwrap_or("archive.tmp"); + let file_path = tmp_dir.join(file_name); + + if let Some(local) = url.strip_prefix("file://") { + let src = Path::new(local); + if !src.exists() { + return Err(format!("Local file not found: {}", local)); + } + let size = std::fs::metadata(&src).map_err(|e| e.to_string())?.len(); + bytes_expected_global.fetch_add(size, Ordering::Relaxed); + std::fs::copy(&src, &file_path).map_err(|e| e.to_string())?; + // Also copy the accompanying .dict file if it exists (for zstd dictionary decompression) + let dict_src = src.with_extension("dict"); + if dict_src.exists() { + let dict_dst = file_path.with_extension("dict"); + let _ = std::fs::copy(&dict_src, &dict_dst); + } + bytes_done_global.fetch_add(size, Ordering::Relaxed); + return Ok((file_path, size)); + } + + use reqwest::blocking::Client; + let client = Client::builder() + .connect_timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| format!("HTTP client: {}", e))?; + + let resp = client.get(url).send() + .map_err(|e| format!("Download failed: {}", e))?; + if !resp.status().is_success() { + return Err(format!("HTTP {}", resp.status())); + } + + if let Some(len) = resp + .headers() + .get(reqwest::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.parse::<u64>().ok()) + { + bytes_expected_global.fetch_add(len, Ordering::Relaxed); + } + + let mut file = std::fs::File::create(&file_path).map_err(|e| e.to_string())?; + let mut hasher = Sha256::new(); + let mut buf = [0u8; 65536]; + let mut downloaded: u64 = 0; + let mut reader = resp; + + loop { + let n = reader.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { break; } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + downloaded += n as u64; + bytes_done_global.fetch_add(n as u64, Ordering::Relaxed); + } + + if !expected_sha.is_empty() { + let hash = format!("{:x}", hasher.finalize()); + if hash != expected_sha { + let _ = std::fs::remove_file(&file_path); + return Err(format!("SHA256 mismatch: expected {}, got {}", expected_sha, hash)); + } + } + + Ok((file_path, downloaded)) +} + +fn render_overall_bar(bytes_done: u64, bytes_expected: u64) { + use crate::progress::format_bytes; + const W: u64 = 40; + let filled = if bytes_expected > 0 { + (bytes_done * W / bytes_expected).min(W) + } else { + 0 + }; + let arrow = if filled < W { ">" } else { "=" }; + let bar = format!( + "{}{}{}", + "=".repeat(filled.saturating_sub(1) as usize), + arrow, + " ".repeat((W - filled) as usize) + ); + if bytes_expected > 0 { + eprint!( + "\r\x1b[K\x1b[36m[{}]\x1b[0m {} / {}", + bar, + format_bytes(bytes_done), + format_bytes(bytes_expected) + ); + } else { + eprint!("\r\x1b[K\x1b[36m[{}]\x1b[0m {}", bar, format_bytes(bytes_done)); + } + std::io::stderr().flush().ok(); +} + fn download_parallel( tasks: Vec<DownloadTask>, - cfg: Arc<config::Config>, + _cfg: Arc<config::Config>, n_parallel: usize, ) -> Result<HashMap<String, std::path::PathBuf>, String> { let n = n_parallel.max(1).min(tasks.len().max(1)); - let total = tasks.len(); + let total_files = tasks.len(); println!( - "{} Downloading {} packages ({} in parallel)...", + "{} Downloading {} package(s) ({} in parallel)...", ">>>".cyan().bold(), - total, + total_files, n ); let queue: Arc<Mutex<VecDeque<DownloadTask>>> = Arc::new(Mutex::new(tasks.into_iter().collect())); - let results: Arc<Mutex<HashMap<String, std::path::PathBuf>>> = Arc::new(Mutex::new(HashMap::new())); - let first_error: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None)); - let done_count: Arc<Mutex<usize>> = Arc::new(Mutex::new(0)); + + let bytes_done = Arc::new(AtomicU64::new(0)); + let bytes_expected = Arc::new(AtomicU64::new(0)); + let files_done = Arc::new(AtomicU64::new(0)); + + let print_lock: Arc<Mutex<()>> = Arc::new(Mutex::new(())); + + let ticker_running = Arc::new(AtomicBool::new(true)); + { + let bd = Arc::clone(&bytes_done); + let be = Arc::clone(&bytes_expected); + let pl = Arc::clone(&print_lock); + let running = Arc::clone(&ticker_running); + thread::spawn(move || { + while running.load(Ordering::Relaxed) { + thread::sleep(std::time::Duration::from_millis(100)); + let _g = pl.lock().unwrap(); + render_overall_bar(bd.load(Ordering::Relaxed), be.load(Ordering::Relaxed)); + } + }); + } let mut handles = vec![]; for _ in 0..n { - let queue = Arc::clone(&queue); - let results = Arc::clone(&results); - let first_error = Arc::clone(&first_error); - let done_count = Arc::clone(&done_count); - let cfg = Arc::clone(&cfg); + let queue = Arc::clone(&queue); + let results = Arc::clone(&results); + let first_error = Arc::clone(&first_error); + let bytes_done = Arc::clone(&bytes_done); + let bytes_exp = Arc::clone(&bytes_expected); + let files_done = Arc::clone(&files_done); + let print_lock = Arc::clone(&print_lock); handles.push(thread::spawn(move || { loop { - if first_error.lock().unwrap().is_some() { - return; - } + if first_error.lock().unwrap().is_some() { return; } let task = queue.lock().unwrap().pop_front(); - let task = match task { - Some(t) => t, - None => return, - }; + let task = match task { Some(t) => t, None => return }; let mut last_err = String::new(); - let mut downloaded = false; + let mut success = false; for url in &task.urls { - match download_and_verify(url, &task.sha256, &cfg) { - Ok(path) => { + match download_file_quiet(url, &task.sha256, &bytes_done, &bytes_exp) { + Ok((path, file_bytes)) => { results.lock().unwrap().insert(task.pkg_name.clone(), path); - downloaded = true; - - let mut count = done_count.lock().unwrap(); - *count += 1; - eprint!( - "\r\x1b[K{} [{}/{}] {} ", - ">>>".green(), - count, - total, - task.pkg_name + let _done = files_done.fetch_add(1, Ordering::Relaxed) + 1; + + let _g = print_lock.lock().unwrap(); + eprintln!( + "\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", + crate::progress::format_bytes(file_bytes) + ); + render_overall_bar( + bytes_done.load(Ordering::Relaxed), + bytes_exp.load(Ordering::Relaxed), ); - std::io::stderr().flush().ok(); + success = true; break; } Err(e) => last_err = e, } } - if !downloaded { + if !success { let mut err = first_error.lock().unwrap(); if err.is_none() { - *err = Some(format!( - "Failed to download '{}': {}", - task.pkg_name, last_err - )); + *err = Some(format!("Failed to download '{}': {}", task.pkg_name, last_err)); } } } @@ -195,6 +324,8 @@ fn download_parallel( for handle in handles { handle.join().ok(); } + + ticker_running.store(false, Ordering::Relaxed); eprintln!(); if let Some(e) = first_error.lock().unwrap().take() { @@ -209,8 +340,6 @@ fn install_from_archive( archive_path: &std::path::Path, root_dir: &Path, pkg_type: &str, - dict_url: Option<&str>, - cfg: &config::Config, ) -> Result<Vec<String>, String> { let work_dir = std::path::Path::new("/tmp/ror-rootfs").join(pkg_name); if work_dir.exists() { @@ -221,19 +350,20 @@ fn install_from_archive( .map_err(|e| format!("Failed to create temp dir for '{}': {}", pkg_name, e))?; let extracted = if pkg_type == "ror" { - let url = dict_url.ok_or_else(|| format!("Package '{}' has type 'ror' but no dict URL", pkg_name))?; - let dict_path = download_and_verify(url, "", cfg) - .map_err(|e| format!("Failed to download dict for '{}': {}", pkg_name, e))?; - let files = extract_ror(archive_path, &dict_path, &work_dir) - .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))?; - let _ = fs::remove_file(&dict_path); - files + extract_ror(archive_path, &work_dir) + .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? + } else if pkg_type == "sror" { + extract_sror(archive_path, &work_dir) + .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? + } else if pkg_type == "deb" { + extract_deb(archive_path, &work_dir) + .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? } else { extract_native(archive_path, &work_dir) .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? }; - let installed = install_files_with_root(&work_dir, root_dir, &extracted)?; + let installed = install_files_to_root(&work_dir, root_dir, &extracted)?; let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(archive_path); @@ -241,30 +371,16 @@ fn install_from_archive( Ok(installed) } -fn write_listinstalled(target_dir: &Path, packages: &[String]) -> Result<(), String> { - let entries: Vec<InstalledEntry> = packages.iter() - .filter_map(|name| { - let pkg = load_package(name)?; - Some(InstalledEntry { name: pkg.name, version: pkg.version }) - }) - .collect(); - - let list = ListInstalled { packages: entries }; - let yaml = serde_yaml::to_string(&list) - .map_err(|e| format!("Failed to serialize listinstalled: {}", e))?; - - let out_dir = target_dir.join("var/ror"); - fs::create_dir_all(&out_dir) - .map_err(|e| format!("Failed to create var/ror: {}", e))?; - - fs::write(out_dir.join("listinstalled.yaml"), yaml) - .map_err(|e| format!("Failed to write listinstalled.yaml: {}", e))?; +fn setup_usr_merge(target_dir: &Path, target_libc: &str) -> Result<(), String> { + let is_musl = target_libc == "musl"; - Ok(()) -} + let root_dirs: &[&str] = if is_musl { + &["bin", "lib", "sbin"] + } else { + &["bin", "lib", "lib64", "sbin"] + }; -fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { - for dir in &["bin", "lib", "lib64", "sbin"] { + for dir in root_dirs { let path = target_dir.join(dir); if path.symlink_metadata().is_ok() { if path.is_dir() && !path.is_symlink() { @@ -277,19 +393,80 @@ fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { } } - for dir in &["usr/bin", "usr/lib", "usr/lib64", "usr/sbin"] { - fs::create_dir_all(target_dir.join(dir)) - .map_err(|e| format!("Failed to create {}: {}", dir, e))?; + fs::create_dir_all(target_dir.join("usr/bin")) + .map_err(|e| format!("Failed to create usr/bin: {}", e))?; + fs::create_dir_all(target_dir.join("usr/lib")) + .map_err(|e| format!("Failed to create usr/lib: {}", e))?; + if !is_musl { + fs::create_dir_all(target_dir.join("usr/lib64")) + .map_err(|e| format!("Failed to create usr/lib64: {}", e))?; } - for (link, target) in &[ - ("bin", "usr/bin"), - ("lib", "usr/lib"), - ("lib64", "usr/lib64"), - ("sbin", "usr/sbin"), - ] { - symlink(target, target_dir.join(link)) - .map_err(|e| format!("Failed to create symlink {} -> {}: {}", link, target, e))?; + let usr_sbin = target_dir.join("usr/sbin"); + if usr_sbin.exists() || usr_sbin.is_symlink() { + let _ = fs::remove_file(&usr_sbin); + } + symlink("bin", &usr_sbin) + .map_err(|e| format!("Failed to create symlink usr/sbin -> bin: {}", e))?; + + if is_musl { + symlink("usr/bin", target_dir.join("bin")) + .map_err(|e| format!("Failed to create symlink bin -> usr/bin: {}", e))?; + symlink("usr/lib", target_dir.join("lib")) + .map_err(|e| format!("Failed to create symlink lib -> usr/lib: {}", e))?; + symlink("usr/bin", target_dir.join("sbin")) + .map_err(|e| format!("Failed to create symlink sbin -> usr/bin: {}", e))?; + } else { + symlink("usr/bin", target_dir.join("bin")) + .map_err(|e| format!("Failed to create symlink bin -> usr/bin: {}", e))?; + symlink("usr/lib", target_dir.join("lib")) + .map_err(|e| format!("Failed to create symlink lib -> usr/lib: {}", e))?; + symlink("usr/lib64", target_dir.join("lib64")) + .map_err(|e| format!("Failed to create symlink lib64 -> usr/lib64: {}", e))?; + symlink("usr/bin", target_dir.join("sbin")) + .map_err(|e| format!("Failed to create symlink sbin -> usr/bin: {}", e))?; + } + + Ok(()) +} + +fn fix_usr_merge(target_dir: &Path, target_libc: &str) -> Result<(), String> { + let is_musl = target_libc == "musl"; + + let root_links: &[&str] = if is_musl { + &["bin", "lib", "sbin"] + } else { + &["bin", "lib", "lib64", "sbin"] + }; + + for link in root_links { + let path = target_dir.join(link); + if path.exists() || path.is_symlink() { + let _ = fs::remove_file(&path); + } + } + + let usr_sbin = target_dir.join("usr/sbin"); + if usr_sbin.exists() || usr_sbin.is_symlink() { + let _ = fs::remove_file(&usr_sbin); + } + + let usr_bin = target_dir.join("usr/bin"); + if !usr_bin.exists() { + fs::create_dir_all(&usr_bin).map_err(|e| e.to_string())?; + } + + symlink("bin", &usr_sbin).map_err(|e| e.to_string())?; + + if is_musl { + symlink("usr/bin", target_dir.join("bin")).map_err(|e| e.to_string())?; + symlink("usr/lib", target_dir.join("lib")).map_err(|e| e.to_string())?; + symlink("usr/bin", target_dir.join("sbin")).map_err(|e| e.to_string())?; + } else { + symlink("usr/bin", target_dir.join("bin")).map_err(|e| e.to_string())?; + symlink("usr/lib", target_dir.join("lib")).map_err(|e| e.to_string())?; + symlink("usr/lib64", target_dir.join("lib64")).map_err(|e| e.to_string())?; + symlink("usr/bin", target_dir.join("sbin")).map_err(|e| e.to_string())?; } Ok(()) @@ -550,7 +727,9 @@ fn run_all_install_steps( if let Some(pkg) = load_package(pkg_name) { if !pkg.install_steps.trim().is_empty() { pb.inc(&format!("install_steps: {}", pkg_name)); + eprintln!(); run_install_steps_in_chroot(pkg_name, &pkg.install_steps, target_dir, shell, subcmd)?; + pb.render(); } } } @@ -563,16 +742,24 @@ fn write_installed_json( packages: &[String], files_map: &HashMap<String, Vec<String>>, group: &crate::group::Group, + target_libc: &str, ) -> Result<(), String> { let mut db = InstalledDB::default(); let now = Local::now().to_rfc3339(); - for name in packages { - if let Some(pkg) = load_package(name) { - let files = files_map.get(name).cloned().unwrap_or_default(); - db.packages.insert(name.clone(), InstalledPackage { + for spec in packages { + let (pkg_name, _variant) = crate::install::parse_package_spec(spec); + if let Some(pkg) = load_package(&pkg_name) { + let files = files_map.get(&pkg_name).cloned().unwrap_or_default(); + let libc = pkg.libc.clone() + .or_else(|| group.libc.clone()) + .or_else(|| Some(target_libc.to_string())); + if files.is_empty() { + continue; + } + db.packages.insert(pkg_name.clone(), InstalledPackage { name: pkg.name, version: pkg.version, - libc: pkg.libc.clone(), + libc, files, installed_at: now.clone(), }); @@ -595,13 +782,123 @@ fn write_installed_json( Ok(()) } +fn generate_system_yaml(target_dir: &Path, group: &crate::group::Group) -> Result<(), String> { + let mut role_init: Option<String> = None; + let mut role_libc: Option<String> = None; + let mut role_core: Option<String> = None; + let mut role_udev: Option<String> = None; + let mut role_sh: Vec<String> = Vec::new(); + let mut role_su: Vec<String> = Vec::new(); + let mut role_pkgs: std::collections::HashSet<String> = std::collections::HashSet::new(); + + for spec in &group.packages { + let (pkg_name, _) = crate::install::parse_package_spec(spec); + let pkg = match load_package(&pkg_name) { + Some(p) => p, + None => continue, + }; + let mut is_role = false; + for prov in &pkg.provides { + match prov.as_str() { + "init-system" => { role_init = Some(pkg_name.clone()); is_role = true; } + "libc" => { role_libc = Some(pkg_name.clone()); is_role = true; } + "core-utils" => { role_core = Some(pkg_name.clone()); is_role = true; } + "udev" => { role_udev = Some(pkg_name.clone()); is_role = true; } + "sh" => { + if !role_sh.contains(&pkg_name) { role_sh.push(pkg_name.clone()); } + is_role = true; + } + "su" => { + if !role_su.contains(&pkg_name) { role_su.push(pkg_name.clone()); } + is_role = true; + } + _ => {} + } + } + if is_role { + role_pkgs.insert(pkg_name); + } + } + + if role_libc.is_none() { + if let Some(libc_name) = &group.libc { + let libc_pkg = match libc_name.as_str() { + "musl" => "musl", + "glibc" => "glibc", + other => other, + }; + role_libc = Some(libc_pkg.to_string()); + role_pkgs.insert(libc_pkg.to_string()); + } + } + + let extra_pkgs: Vec<&String> = group.packages + .iter() + .filter(|spec| { + let (name, _) = crate::install::parse_package_spec(spec); + !role_pkgs.contains(&name) + }) + .collect(); + + let mut out = String::new(); + + out.push_str("roles:\n"); + + match &role_init { + Some(v) => out.push_str(&format!(" init: {}\n", v)), + None => out.push_str(" init: null\n"), + } + match &role_libc { + Some(v) => out.push_str(&format!(" libc: {}\n", v)), + None => out.push_str(" libc: null\n"), + } + match &role_core { + Some(v) => out.push_str(&format!(" core: {}\n", v)), + None => out.push_str(" core: null\n"), + } + match &role_udev { + Some(v) => out.push_str(&format!(" udev: {}\n", v)), + None => out.push_str(" udev: null\n"), + } + if role_sh.is_empty() { + out.push_str(" sh: []\n"); + } else { + out.push_str(" sh:\n"); + for s in &role_sh { out.push_str(&format!(" - {}\n", s)); } + } + if role_su.is_empty() { + out.push_str(" su: []\n"); + } else { + out.push_str(" su:\n"); + for s in &role_su { out.push_str(&format!(" - {}\n", s)); } + } + + if extra_pkgs.is_empty() { + out.push_str("packages: []\n"); + } else { + out.push_str("packages:\n"); + for p in &extra_pkgs { out.push_str(&format!(" - {}\n", p)); } + } + + out.push_str("groups: []\n"); + out.push_str("oss: false\n"); + + let etc_ror = target_dir.join("etc/ror"); + fs::create_dir_all(&etc_ror) + .map_err(|e| format!("Failed to create etc/ror: {}", e))?; + + fs::write(etc_ror.join("system.yaml"), out) + .map_err(|e| format!("Failed to write system.yaml: {}", e))?; + + Ok(()) +} + pub fn build_rootfs( - group_name: Option<&str>, + group_name: &str, target_dir: &Path, cfg: &config::Config, target_arch: &str, run_ldconfig: bool, - system_config: Option<&Path>, ) -> Result<(), String> { if !target_dir.exists() { fs::create_dir_all(target_dir) @@ -614,31 +911,22 @@ pub fn build_rootfs( } } - let (start_packages, group) = if let Some(config_path) = system_config { - let content = fs::read_to_string(config_path) - .map_err(|e| format!("Failed to read {}: {}", config_path.display(), e))?; - let sys_config: SystemConfig = serde_yaml::from_str(&content) - .map_err(|e| format!("System config YAML error: {}", e))?; - let pkgs = crate::apply::get_target_packages(&sys_config, cfg)?; - let dummy_group = crate::group::Group { - name: "system".into(), - description: Some("from system.yaml".into()), - libc: cfg.global.libc.clone().into(), - version: None, - packages: pkgs.clone(), - install_steps: String::new(), + let group = crate::group::load_group(group_name)?; + let mut start_packages = group.packages.clone(); + + let target_libc: String = group.libc.clone().unwrap_or_else(|| cfg.global.libc.clone()); + + if let Some(libc_name) = &group.libc { + let libc_pkg = match libc_name.as_str() { + "musl" => "musl", + "glibc" => "glibc", + other => other, }; - (pkgs, dummy_group) - } else { - let group_name = group_name.ok_or_else(|| "Either --group or --config is required".to_string())?; - let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); - let content = fs::read_to_string(&group_file) - .map_err(|e| format!("Failed to read group file: {}", e))?; - let group: crate::group::Group = serde_yaml::from_str(&content) - .map_err(|e| format!("Group YAML error: {}", e))?; - let pkgs = group.packages.clone(); - (pkgs, group) - }; + if !start_packages.contains(&libc_pkg.to_string()) { + start_packages.push(libc_pkg.to_string()); + println!("{} Adding libc package: {}", ">>>".cyan(), libc_pkg); + } + } println!( "{} Building rootfs in {}", @@ -650,7 +938,7 @@ pub fn build_rootfs( } println!("\n{} Phase 0: UsrMerge...", ">>>".cyan().bold()); - setup_usr_merge(target_dir)?; + setup_usr_merge(target_dir, &target_libc)?; println!("{} bin/lib/lib64/sbin are now symlinks into usr/", ">>>".green()); println!("{} Creating FHS skeleton...", ">>>".cyan()); @@ -658,11 +946,11 @@ pub fn build_rootfs( println!("{} FHS skeleton created.", ">>>".green()); println!("\n{} Phase 1a: Resolving packages...", ">>>".cyan().bold()); - let all_packages = collect_install_order(&start_packages)?; + let all_packages = collect_install_order(&start_packages, &target_libc)?; println!("{} {} packages to install (including dependencies)", ">>>".green(), all_packages.len()); println!("\n{} Phase 1b: Building download queue...", ">>>".cyan().bold()); - let tasks = build_download_tasks(&all_packages, target_arch, &cfg.global.libc)?; + let tasks = build_download_tasks(&all_packages, target_arch, &target_libc, cfg)?; let n_parallel = cfg.global.parallel_downloads.max(1); let cfg_arc = Arc::new(cfg.clone()); @@ -674,40 +962,50 @@ pub fn build_rootfs( let mut installed_files_map: HashMap<String, Vec<String>> = HashMap::new(); let mut pb = ProgressBar::new(all_packages.len().max(1), "Installing..."); - for pkg_name in &all_packages { - let pkg = load_package(pkg_name) + for pkg_spec in &all_packages { + let (pkg_name, variant) = crate::install::parse_package_spec(pkg_spec); + let pkg = load_package(&pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - let binary = select_binary_for_arch(&pkg, target_arch, &cfg.global.libc) + let binary = select_binary_for_arch(&pkg, target_arch, &target_libc, variant.as_deref()) .map_err(|e| format!("Arch selection failed for '{}': {}", pkg_name, e))?; - let archive_path = downloaded.get(pkg_name) + let archive_path = downloaded.get(pkg_spec) + .or_else(|| downloaded.get(&pkg_name)) .ok_or_else(|| format!("Archive for '{}' was not downloaded", pkg_name))?; pb.inc(&format!("Installing {}", pkg_name)); let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz"); let files = install_from_archive( - pkg_name, + &pkg_name, archive_path, target_dir, pkg_type, - binary.dict.as_deref(), - cfg, )?; installed_files_map.insert(pkg_name.clone(), files); installing.insert(pkg_name.clone()); } pb.finish(&format!("{} packages installed", installing.len())); - println!("\n{} Writing listinstalled.yaml...", ">>>".cyan()); - write_listinstalled(target_dir, &all_packages)?; - println!("{} listinstalled.yaml written to var/ror/", ">>>".green()); + fix_usr_merge(target_dir, &target_libc)?; - println!("{} Writing installed.json...", ">>>".cyan()); - write_installed_json(target_dir, &all_packages, &installed_files_map, &group)?; + println!("\n{} Writing installed.json...", ">>>".cyan()); + write_installed_json(target_dir, &all_packages, &installed_files_map, &group, &target_libc)?; println!("{} installed.json written to etc/ror/", ">>>".green()); - if run_ldconfig { + for pkg_name in &installing { + if let Some(pkg) = load_package(pkg_name) { + if !pkg.services.is_empty() { + install_services_to_root(&pkg, target_dir); + } + } + } + + println!("{} Generating system.yaml...", ">>>".cyan()); + generate_system_yaml(target_dir, &group)?; + println!("{} system.yaml written to etc/ror/", ">>>".green()); + + if run_ldconfig && target_libc != "musl" { println!("{} Running ldconfig...", ">>>".cyan()); let ld_conf = target_dir.join("etc/ld.so.conf"); if !ld_conf.exists() { diff --git a/src/search.rs b/src/search.rs index fabfb47..9fc691b 100644..100755 --- a/src/search.rs +++ b/src/search.rs @@ -90,3 +90,4 @@ pub fn search_packages(query: &str) { println!(" {} {}", name_ver, desc); } } + diff --git a/src/sync.rs b/src/sync.rs index d717694..ad36aea 100644..100755 --- a/src/sync.rs +++ b/src/sync.rs @@ -95,3 +95,4 @@ fn pull_or_clone(repo_path: &Path, primary: &str) -> Result<(), String> { } Ok(()) } + diff --git a/src/update.rs b/src/update.rs index 9703d7a..1cceccc 100644..100755 --- a/src/update.rs +++ b/src/update.rs @@ -130,7 +130,7 @@ pub fn rebuild_from_recipe(recipe_path: &Path, cfg: &config::Config) { group.packages.len() ); - let order = match collect_install_order(&group.packages) { + let order = match collect_install_order(&group.packages, &cfg.global.libc) { Ok(o) => o, Err(e) => { eprintln!("{} {}", "[ror]".red().bold(), e); @@ -176,3 +176,4 @@ pub fn rebuild_from_recipe(recipe_path: &Path, cfg: &config::Config) { ); } } + |