diff options
| author | rorka900 <rorka900@gmail.com> | 2026-04-06 21:05:06 +0300 |
|---|---|---|
| committer | rorka900 <rorka900@gmail.com> | 2026-04-06 21:05:06 +0300 |
| commit | 62d9463b3f24516158e9e73cd20ccebfc9eec329 (patch) | |
| tree | 664ee2433618df788e9a3db3118a609329ca6e8d | |
| parent | 044d414f07b13bfdee5a04bc2484510ecfe0a0f8 (diff) | |
| download | ror-62d9463b3f24516158e9e73cd20ccebfc9eec329.tar.gz ror-62d9463b3f24516158e9e73cd20ccebfc9eec329.zip | |
feat: add sror package type, gpg repo verification, and group command
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/config.rs | 112 | ||||
| -rw-r--r-- | src/delete.rs | 39 | ||||
| -rw-r--r-- | src/group.rs | 19 | ||||
| -rw-r--r-- | src/install.rs | 277 | ||||
| -rw-r--r-- | src/main.rs | 267 | ||||
| -rw-r--r-- | src/repo.rs | 60 | ||||
| -rw-r--r-- | src/rootfs.rs | 10 |
9 files changed, 638 insertions, 150 deletions
@@ -1354,7 +1354,7 @@ dependencies = [ [[package]] name = "ror" -version = "0.5.0" +version = "0.6.0" dependencies = [ "ar", "bzip2", @@ -1,6 +1,6 @@ [package] name = "ror" -version = "0.5.0" +version = "0.6.0" edition = "2024" authors = ["rorka900"] description = "RorkOS package manager" diff --git a/src/config.rs b/src/config.rs index 0c6fc1b..ff83f01 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,9 +8,17 @@ use colored::Colorize; pub struct RepositoryConfig { pub url: String, #[serde(default)] + pub urlrepo: Option<String>, + #[serde(default)] pub mirror: Option<String>, + #[serde(default = "default_gpg_support")] + pub gpg_support: bool, + #[serde(default)] + pub gpg_key: Option<String>, } +fn default_gpg_support() -> bool { true } + #[derive(Debug, Deserialize, Serialize, Clone)] pub struct GlobalConfig { #[serde(default = "default_ignore_speed")] @@ -46,12 +54,79 @@ fn default_parallel_downloads() -> usize { 4 } fn default_arch() -> String { std::env::consts::ARCH.to_string() } fn default_libc() -> String { "glibc".to_string() } +#[derive(Debug, Deserialize, Serialize, Clone, Default)] +pub struct SystemProfile { + #[serde(rename = "init-system", default)] + pub init_system: Option<String>, + #[serde(default)] + pub libc: Option<String>, + #[serde(rename = "core-utils", default)] + pub core_utils: Option<String>, + #[serde(default)] + pub sh: Vec<String>, + #[serde(default)] + pub su: Vec<String>, + #[serde(default)] + pub udev: Option<String>, + #[serde(rename = "active-group", default)] + pub active_group: Option<String>, +} + +impl SystemProfile { + pub fn group_name(&self) -> Option<String> { + if let Some(g) = &self.active_group { + return Some(g.clone()); + } + let init = self.init_system.as_deref()?; + let libc = self.libc.as_deref()?; + let utils = self.core_utils.as_deref()?; + let sh = self.sh.first().map(|s| s.as_str())?; + let su = self.su.first().map(|s| s.as_str())?; + let udev = self.udev.as_deref()?; + Some(format!("{}-{}-{}-{}-{}-{}-min", init, libc, utils, sh, su, udev)) + } + + pub fn set_single_role(&mut self, role: &str, pkg: &str) { + match role { + "init-system" => self.init_system = Some(pkg.to_string()), + "libc" => self.libc = Some(pkg.to_string()), + "core-utils" => self.core_utils = Some(pkg.to_string()), + "udev" => self.udev = Some(pkg.to_string()), + _ => {} + } + } + + pub fn replace_in_list_role(&mut self, role: &str, old_pkg: &str, new_pkg: &str) { + let list = match role { + "sh" => &mut self.sh, + "su" => &mut self.su, + _ => return, + }; + if let Some(pos) = list.iter().position(|p| p == old_pkg) { + list[pos] = new_pkg.to_string(); + } else { + list.push(new_pkg.to_string()); + } + } + #[allow(dead_code)] + pub fn remove_from_list_role(&mut self, role: &str, pkg: &str) { + let list = match role { + "sh" => &mut self.sh, + "su" => &mut self.su, + _ => return, + }; + list.retain(|p| p != pkg); + } +} + #[derive(Debug, Deserialize, Serialize, Default, Clone)] pub struct Config { #[serde(default)] pub global: GlobalConfig, #[serde(default)] pub repositories: HashMap<String, RepositoryConfig>, + #[serde(default)] + pub profile: SystemProfile, } impl Config { @@ -72,6 +147,15 @@ impl Config { } } + pub fn save(&self) -> std::io::Result<()> { + let path = Path::new("/etc/ror/ror.conf"); + let ini = self.to_ini().map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(path, ini) + } + pub fn to_ini(&self) -> Result<String, config::ConfigError> { let mut lines = vec!["[global]".to_string()]; lines.push(format!("ignore_speed = {}", self.global.ignore_speed)); @@ -80,12 +164,37 @@ impl Config { lines.push(format!("arch = {}", self.global.arch)); lines.push(format!("libc = {}", self.global.libc)); lines.push(String::new()); + + let p = &self.profile; + let has_profile = p.init_system.is_some() || p.libc.is_some() + || p.core_utils.is_some() || !p.sh.is_empty() + || !p.su.is_empty() || p.udev.is_some() || p.active_group.is_some(); + + if has_profile { + lines.push("[profile]".to_string()); + if let Some(v) = &p.active_group { lines.push(format!("active-group = {}", v)); } + if let Some(v) = &p.init_system { lines.push(format!("init-system = {}", v)); } + if let Some(v) = &p.libc { lines.push(format!("libc = {}", v)); } + if let Some(v) = &p.core_utils { lines.push(format!("core-utils = {}", v)); } + if !p.sh.is_empty() { lines.push(format!("sh = {}", p.sh.join(","))); } + if !p.su.is_empty() { lines.push(format!("su = {}", p.su.join(","))); } + if let Some(v) = &p.udev { lines.push(format!("udev = {}", v)); } + lines.push(String::new()); + } + for (name, repo) in &self.repositories { lines.push(format!("[repositories.{}]", name)); lines.push(format!("url = \"{}\"", repo.url)); + if let Some(v) = &repo.urlrepo { + lines.push(format!("urlrepo = \"{}\"", v)); + } if let Some(m) = &repo.mirror { lines.push(format!("mirror = \"{}\"", m)); } + lines.push(format!("gpg_support = {}", repo.gpg_support)); + if let Some(k) = &repo.gpg_key { + lines.push(format!("gpg_key = \"{}\"", k)); + } lines.push(String::new()); } Ok(lines.join("\n")) @@ -109,7 +218,10 @@ impl Config { "\n", "[repositories.rorkos]\n", "url = \"https://github.com/RorkOS/RorkOS_package\"\n", + "urlrepo = \"https://github.com/RorkOS/RorkOS_packages_bin/releases/download/latest/\"\n", "mirror = \"https://github.com/rork-os/RorkOS_package\"\n", + "gpg_support = true\n", + "gpg_key = \"rorka.pub\"\n", ); fs::create_dir_all(path.parent().unwrap())?; fs::write(path, ini) diff --git a/src/delete.rs b/src/delete.rs index 365867e..93d6a6c 100644 --- a/src/delete.rs +++ b/src/delete.rs @@ -3,7 +3,8 @@ use std::path::Path; use colored::Colorize; use crate::install::{load_package, InstalledDB}; -const CRITICAL_ROLES: &[&str] = &["init-system", "sh"]; +const STRICT_ROLES: &[&str] = &["init-system", "libc", "core-utils", "udev"]; +const MULTI_ROLES: &[&str] = &["sh", "su"]; fn has_role(pkg_name: &str, role: &str) -> bool { load_package(pkg_name) @@ -11,10 +12,40 @@ fn has_role(pkg_name: &str, role: &str) -> bool { .unwrap_or(false) } +pub fn critical_role_of(pkg_name: &str) -> Option<&'static str> { + let pkg = load_package(pkg_name)?; + for &role in STRICT_ROLES.iter().chain(MULTI_ROLES.iter()) { + if pkg.provides.contains(&role.to_string()) { + return Some(role); + } + } + None +} + +pub fn critical_role_of_from_recipe(pkg_name: &str) -> Option<&'static str> { + critical_role_of(pkg_name) +} + +pub fn is_strict_role(role: &str) -> bool { + STRICT_ROLES.contains(&role) +} + pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; - for &role in CRITICAL_ROLES { + for &role in STRICT_ROLES { + if pkg.provides.contains(&role.to_string()) { + return Err(format!( + "{} CRITICAL: '{}' provides '{}' which is a protected system role. Direct removal is forbidden. Use --di {} <replacement> to replace it.", + "[ror]".red().bold(), + pkg_name, + role, + pkg_name + )); + } + } + + for &role in MULTI_ROLES { if !pkg.provides.contains(&role.to_string()) { continue; } @@ -38,7 +69,7 @@ pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; let replacement_pkg = load_package(replacement).ok_or("Replacement package not found in repository")?; - for &role in CRITICAL_ROLES { + for &role in STRICT_ROLES.iter().chain(MULTI_ROLES.iter()) { if !pkg.provides.contains(&role.to_string()) { continue; } @@ -63,7 +94,7 @@ pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; - for &role in CRITICAL_ROLES { + for &role in STRICT_ROLES { if !pkg.provides.contains(&role.to_string()) { continue; } diff --git a/src/group.rs b/src/group.rs index edabcc6..a349d62 100644 --- a/src/group.rs +++ b/src/group.rs @@ -75,13 +75,18 @@ pub fn list_groups() { println!("{} Available package groups:", "[ror]".blue().bold()); if let Ok(entries) = std::fs::read_dir(groups_dir) { - for entry in entries.flatten() { - if let Some(name) = entry.file_name().to_str() { - if name.ends_with(".yaml") { - let group_name = name.trim_end_matches(".yaml"); - println!(" {}", group_name.green()); - } - } + let mut groups: Vec<String> = entries.flatten() + .filter_map(|e| e.file_name().to_str().map(|s| s.to_string())) + .filter(|n| n.ends_with(".yaml")) + .map(|n| n.trim_end_matches(".yaml").to_string()) + .collect(); + groups.sort(); + for (i, group_name) in groups.iter().enumerate() { + println!( + " {} {}", + format!("[{}]", i + 1).cyan().bold(), + group_name.green() + ); } } } diff --git a/src/install.rs b/src/install.rs index 1801cc0..66ad894 100644 --- a/src/install.rs +++ b/src/install.rs @@ -65,8 +65,6 @@ pub struct BinaryPackage { #[serde(default = "default_install_prefix")] pub install_prefix: String, #[serde(default)] - pub files: Vec<String>, - #[serde(default)] pub libc: Option<String>, #[serde(default)] pub dict: Option<String>, @@ -242,6 +240,84 @@ pub fn find_package_file(pkg_name: &str) -> Option<PathBuf> { None } +pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { + let repo = Path::new(REPO_ROOT); + let read_dir = fs::read_dir(repo).ok()?; + + for entry in read_dir.flatten() { + let cat_path = entry.path(); + 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() { + let repo_name = cat_path.file_name()?.to_string_lossy().to_string(); + return Some((pkg_path, repo_name)); + } + } + None +} + +fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { + if !pubkey_path.exists() { + return Err(format!( + "GPG public key not found: {}", + pubkey_path.display() + )); + } + + if !asc_path.exists() { + return Err(format!( + "GPG signature not found: {} — cannot verify package", + asc_path.display() + )); + } + + let tmp_keyring = Path::new("/tmp/ror-gpg-keyring.gpg"); + + let import = Command::new("gpg") + .args([ + "--batch", + "--no-default-keyring", + "--keyring", tmp_keyring.to_str().unwrap(), + "--import", pubkey_path.to_str().unwrap(), + ]) + .output() + .map_err(|e| format!("Failed to run gpg --import: {}", e))?; + + if !import.status.success() { + return Err(format!( + "Failed to import GPG key {}: {}", + pubkey_path.display(), + String::from_utf8_lossy(&import.stderr) + )); + } + + let verify = Command::new("gpg") + .args([ + "--batch", + "--no-default-keyring", + "--keyring", tmp_keyring.to_str().unwrap(), + "--verify", asc_path.to_str().unwrap(), + archive_path.to_str().unwrap(), + ]) + .output() + .map_err(|e| format!("Failed to run gpg --verify: {}", e))?; + + let _ = fs::remove_file(tmp_keyring); + + if verify.status.success() { + Ok(()) + } else { + Err(format!( + "GPG signature verification failed for {}: {}", + archive_path.display(), + String::from_utf8_lossy(&verify.stderr).lines().next().unwrap_or("unknown error") + )) + } +} + pub fn install_package(pkg_name: &str, cfg: &config::Config) { match install_package_with_result(pkg_name, cfg) { Ok(installed_pkg) => { @@ -264,9 +340,22 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let mut spinner = Spinner::new(&format!("Resolving {}", pkg_name)); spinner.tick(&format!("Resolving {}", pkg_name)); - let pkg_path = find_package_file(pkg_name) + let (pkg_path, repo_name) = find_package_with_repo(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; + let repo_cfg = cfg.repositories.get(&repo_name); + let gpg_enabled = repo_cfg.map(|r| r.gpg_support).unwrap_or(false); + let gpg_key = repo_cfg.and_then(|r| r.gpg_key.as_deref()); + + if gpg_enabled { + if gpg_key.is_none() { + return Err(format!( + "Repository '{}' has gpg_support = true but no gpg_key configured", + repo_name + )); + } + } + let content = fs::read_to_string(&pkg_path) .map_err(|e| format!("Failed to read package file: {}", e))?; @@ -295,12 +384,25 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu 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}", &binary.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)) + } + }) .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)); + } + if !cfg.global.ignore_speed && urls_to_try.len() > 1 { spinner.tick("Testing mirror speeds..."); urls_to_try = sort_mirrors_by_speed(&urls_to_try); @@ -324,6 +426,31 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu spinner.finish(&format!("Downloaded {}", pkg_name)); + if gpg_enabled { + let asc_url = format!("{}.asc", url); + spinner.tick(&format!("Downloading GPG signature...")); + let asc_path = match download_and_verify(&asc_url, "", cfg) { + Ok(p) => p, + Err(_) => { + let _ = fs::remove_file(&archive_path); + return Err(format!( + "GPG signature not found for '{}' at {} — installation aborted", + pkg_name, asc_url + )); + } + }; + let key_file = gpg_key.unwrap(); + let pubkey_path = Path::new(REPO_ROOT).join(key_file); + spinner.tick(&format!("Verifying GPG signature for {}...", pkg_name)); + if let Err(e) = verify_gpg_signature(&archive_path, &asc_path, &pubkey_path) { + let _ = fs::remove_file(&archive_path); + let _ = fs::remove_file(&asc_path); + return Err(e); + } + let _ = fs::remove_file(&asc_path); + spinner.finish(&format!("GPG signature OK for {}", pkg_name)); + } + let work_dir = Path::new("/tmp/ror-install").join(&pkg.name); let _ = fs::remove_dir_all(&work_dir); fs::create_dir_all(&work_dir).map_err(|e| format!("Failed to create temp dir: {}", e))?; @@ -344,17 +471,22 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu let files = extract_ror(&archive_path, &dict_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; let _ = fs::remove_file(&dict_path); - let file_list = if binary.files.is_empty() { files } else { binary.files.clone() }; sp2.tick(&format!("Installing files for {}...", pkg_name)); - let mut installed = install_files(&work_dir, &binary.install_prefix, &file_list) + let mut installed = install_files(&work_dir, &binary.install_prefix, &files) + .map_err(|e| format!("Failed to install files: {}", e))?; + all_installed_files.append(&mut installed); + } else if pkg_type == "sror" { + let files = extract_sror(&archive_path, &work_dir) + .map_err(|e| format!("Extraction failed: {}", e))?; + 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))?; all_installed_files.append(&mut installed); } else { let files = extract_native(&archive_path, &work_dir) .map_err(|e| format!("Extraction failed: {}", e))?; - let file_list = if binary.files.is_empty() { files } else { binary.files.clone() }; sp2.tick(&format!("Installing files for {}...", pkg_name)); - let mut installed = install_files(&work_dir, &binary.install_prefix, &file_list) + let mut installed = install_files(&work_dir, &binary.install_prefix, &files) .map_err(|e| format!("Failed to install files: {}", e))?; all_installed_files.append(&mut installed); } @@ -514,7 +646,32 @@ pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> .map_err(|e| format!("Failed to execute tar for .ror: {}", e))?; if !status.success() { - return Err(format!("tar .ror extraction failed with exit code {:?}", status.code())); + return Err(format!("tar .ror failed with exit code {:?}", status.code())); + } + + 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()); + } + } + Ok(files) +} + +pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { + let status = Command::new("tar") + .arg("-I") + .arg("zstd") + .arg("-xf") + .arg(archive_path) + .arg("-C") + .arg(target_dir) + .status() + .map_err(|e| format!("Failed to execute tar for .sror: {}", e))?; + + if !status.success() { + return Err(format!("tar .sror failed with exit code {:?}", status.code())); } let mut files = Vec::new(); @@ -624,3 +781,105 @@ pub fn load_package(pkg_name: &str) -> Option<Package> { let content = fs::read_to_string(pkg_path).ok()?; serde_yaml::from_str(&content).ok() } + +pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { + match install_local_package_with_result(archive_path, cfg) { + Ok(installed_pkg) => { + let mut db = InstalledDB::load(); + db.add_package(installed_pkg); + if let Err(e) = db.save() { + eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); + } else { + println!("{} Package registered in database", "[ror]".green()); + } + println!("{} {} Package installed successfully.", "[ror]".blue().bold(), ">>>".green()); + } + Err(e) => { + eprintln!("{} {}", "[ror]".red().bold(), e); + } + } +} + +pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Config) -> Result<InstalledPackage, String> { + if !archive_path.exists() { + return Err(format!("File not found: {}", archive_path.display())); + } + + let ext = archive_path.extension().and_then(|e| e.to_str()).unwrap_or(""); + let stem = archive_path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown"); + + let name = stem.to_string(); + let version = "local".to_string(); + + let work_dir = Path::new("/tmp/ror-local").join(&name); + let _ = fs::remove_dir_all(&work_dir); + fs::create_dir_all(&work_dir).map_err(|e| format!("Failed to create temp dir: {}", e))?; + + let mut spinner = Spinner::new(&format!("Installing local package {}", name)); + spinner.tick(&format!("Extracting {}...", name)); + + let installed_files = if ext == "sror" { + let files = extract_sror(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))?; + 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() + )); + } + let files = extract_ror(archive_path, &dict_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))?; + installed + } else { + return Err(format!("Unsupported local package format: .{}", ext)); + }; + + spinner.finish(&format!("Installed {} files", installed_files.len())); + + let _ = fs::remove_dir_all(&work_dir); + + Ok(InstalledPackage { + name, + version, + libc: None, + files: installed_files, + installed_at: Local::now().to_rfc3339(), + }) +} + +fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) -> Result<Vec<String>, String> { + 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/main.rs b/src/main.rs index fc1df89..5b93b66 100644 --- a/src/main.rs +++ b/src/main.rs @@ -52,8 +52,11 @@ struct Args { #[arg(long = "dry-run")] dry_run: bool, - #[arg(short = 'u', long = "upgrade", value_name = "RECIPE")] - upgrade: Option<std::path::PathBuf>, + #[arg(short = 'u', long = "upgrade")] + upgrade: bool, + + #[arg(long = "up", value_name = "GROUP")] + upgrade_to: Option<String>, #[arg(long = "repo-add", value_names = ["NAME", "URL"])] repo_add: Option<Vec<String>>, @@ -78,128 +81,138 @@ struct Args { #[arg(long = "di", value_names = ["DELETE", "INSTALL"], num_args = 2)] delete_install: Option<Vec<String>>, - + #[arg(long = "lg", alias = "listgroups")] listgroups: bool, } -fn main() { - let args = Args::parse(); +fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { + let db = install::InstalledDB::load(); - if args.version { - println!("ror {}", env!("CARGO_PKG_VERSION")); + if !db.is_installed(&del_pkg) { + eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), del_pkg); return; } - if args.gen_config { - let config_path = Path::new("/etc/ror/ror.conf"); - match config::Config::create_default_config(config_path) { - Ok(()) => println!( - "{} Default config created at {:?}", - "[ror]".blue().bold(), - config_path - ), - Err(e) => eprintln!( - "{} Failed to create config: {}", - "[ror]".red().bold(), - e - ), + let del_role = delete::critical_role_of(&del_pkg); + let inst_role = delete::critical_role_of_from_recipe(&inst_pkg); + + if let Some(dr) = del_role { + match inst_role { + None => { + eprintln!( + "{} '{}' provides critical role '{}' but '{}' does not. Replacement rejected.", + "[ror]".red().bold(), del_pkg, dr, inst_pkg + ); + return; + } + Some(ir) if ir != dr => { + eprintln!( + "{} Role mismatch: '{}' is '{}' but '{}' is '{}'. Roles must match.", + "[ror]".red().bold(), del_pkg, dr, inst_pkg, ir + ); + return; + } + _ => {} } - return; } - let cfg = Arc::new(config::Config::load()); - - if let Some(di_args) = args.delete_install { - let del_pkg = di_args[0].clone(); - let inst_pkg = di_args[1].clone(); - - let db = install::InstalledDB::load(); - - if !db.is_installed(&del_pkg) { - eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), del_pkg); - return; - } + if let Err(e) = delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db) { + eprintln!("{}", e); + return; + } - if let Err(e) = delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db) { + if let Err(e) = delete::check_critical_install(&inst_pkg, &db) { + if !db.packages.contains_key(&inst_pkg) && !e.contains(&del_pkg) { eprintln!("{}", e); return; } + } - if let Err(e) = delete::check_critical_install(&inst_pkg, &db) { - let already_installed_by_same = db.packages.get(&inst_pkg).is_some(); - if !already_installed_by_same { - let conflict_is_the_deleted = e.contains(&del_pkg); - if !conflict_is_the_deleted { - eprintln!("{}", e); - return; - } - } - } + let record_files = db.packages.get(&del_pkg).map(|r| r.files.clone()).unwrap_or_default(); - let record_files = db.packages - .get(&del_pkg) - .map(|r| r.files.clone()) - .unwrap_or_default(); - - println!( - "{} Replacing '{}' with '{}'...", - "[ror]".blue().bold(), - del_pkg, - inst_pkg - ); - - let del_pkg_for_thread = del_pkg.clone(); - let inst_pkg_for_thread = inst_pkg.clone(); - let cfg_for_thread = Arc::clone(&cfg); - - let del_handle = thread::spawn(move || { - println!("{} [remove] Starting removal of '{}'", ">>>".yellow(), del_pkg_for_thread); - let ok = delete::remove_package_files_only(&del_pkg_for_thread, &record_files); - if ok { - println!("{} [remove] Files removed for '{}'", ">>>".green(), del_pkg_for_thread); - } else { - eprintln!("{} [remove] Errors during removal of '{}'", "[ror]".red().bold(), del_pkg_for_thread); - } - ok - }); + let full_rebuild = del_role.map(|r| matches!(r, "libc" | "core-utils" | "udev")).unwrap_or(false); - let inst_handle = thread::spawn(move || { - println!("{} [install] Starting install of '{}'", ">>>".cyan(), inst_pkg_for_thread); - install::install_package_with_result(&inst_pkg_for_thread, &cfg_for_thread) - }); + println!("{} Replacing '{}' with '{}'...", "[ror]".blue().bold(), del_pkg, inst_pkg); - let del_ok = del_handle.join().unwrap_or(false); - let inst_result = inst_handle.join().unwrap_or_else(|_| Err("install thread panicked".to_string())); + if full_rebuild { + println!("{} Critical role '{}' — running parallel replace + full system rebuild", ">>>".yellow(), del_role.unwrap()); + } - let mut db = install::InstalledDB::load(); + let del_pkg_c = del_pkg.clone(); + let inst_pkg_c = inst_pkg.clone(); + let cfg_c = Arc::clone(&cfg); - if del_ok { - db.packages.remove(&del_pkg); - println!("{} '{}' removed from database", "[ror]".green(), del_pkg); - } + let del_handle = thread::spawn(move || { + delete::remove_package_files_only(&del_pkg_c, &record_files) + }); + + let inst_handle = thread::spawn(move || { + install::install_package_with_result(&inst_pkg_c, &cfg_c) + }); + + let del_ok = del_handle.join().unwrap_or(false); + let inst_result = inst_handle.join().unwrap_or_else(|_| Err("panicked".to_string())); + + let mut db = install::InstalledDB::load(); + if del_ok { db.packages.remove(&del_pkg); } + match inst_result { + Ok(p) => { db.add_package(p); } + Err(e) => { eprintln!("{} Failed to install '{}': {}", "[ror]".red().bold(), inst_pkg, e); } + } + if let Err(e) = db.save() { + eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e); + return; + } - match inst_result { - Ok(installed_pkg) => { - db.add_package(installed_pkg); - println!("{} '{}' added to database", "[ror]".green(), inst_pkg); + if del_ok { + if let Some(role) = del_role { + let mut sys_cfg = config::Config::load(); + if delete::is_strict_role(role) { + sys_cfg.profile.set_single_role(role, &inst_pkg); + } else { + sys_cfg.profile.replace_in_list_role(role, &del_pkg, &inst_pkg); } - Err(e) => { - eprintln!("{} Failed to install '{}': {}", "[ror]".red().bold(), inst_pkg, e); + if let Err(e) = sys_cfg.save() { + eprintln!("{} Failed to update profile: {}", "[ror]".yellow().bold(), e); + } else { + println!("{} Profile updated: {} = {}", "[ror]".cyan().bold(), role, inst_pkg); + if let Some(name) = sys_cfg.profile.group_name() { + println!("{} Active group: {}", "[ror]".cyan(), name.cyan()); + if full_rebuild { + println!("{} Running full system rebuild...", ">>>".yellow()); + let recipe = PathBuf::from(format!("/var/ror/packages/groups/{}.yaml", name)); + update::rebuild_from_recipe(&recipe, &sys_cfg); + } + } } } + } - if let Err(e) = db.save() { - eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); - } else { - println!( - "{} Replace operation finished: '{}' -> '{}'", - "[ror]".green().bold(), - del_pkg, - inst_pkg - ); + println!("{} Replace finished: '{}' -> '{}'", "[ror]".green().bold(), del_pkg, inst_pkg); +} + +fn main() { + let args = Args::parse(); + + if args.version { + println!("ror {}", env!("CARGO_PKG_VERSION")); + return; + } + + if args.gen_config { + let config_path = Path::new("/etc/ror/ror.conf"); + match config::Config::create_default_config(config_path) { + Ok(()) => println!("{} Default config created at {:?}", "[ror]".blue().bold(), config_path), + Err(e) => eprintln!("{} Failed to create config: {}", "[ror]".red().bold(), e), } + return; + } + + let cfg = Arc::new(config::Config::load()); + if let Some(di_args) = args.delete_install { + run_di(di_args[0].clone(), di_args[1].clone(), cfg); return; } @@ -219,11 +232,7 @@ fn main() { } if args.build_rootfs { - let arch = if args.rootfs_arch == "native" { - "native" - } else { - &args.rootfs_arch - }; + let arch = if args.rootfs_arch == "native" { "native" } else { &args.rootfs_arch }; if let (Some(group), Some(target)) = (args.rootfs_group, args.rootfs_target) { if let Err(e) = rootfs::build_rootfs(&group, &target, &cfg, arch, true) { eprintln!("{} {}", "[ror]".red().bold(), e); @@ -247,9 +256,10 @@ fn main() { if !args.install.is_empty() { let db = install::InstalledDB::load(); for pkg_name in &args.install { - if pkg_name.starts_with('@') { - continue; - } + if pkg_name.starts_with('@') { continue; } + let is_local = pkg_name.starts_with('/') || pkg_name.starts_with("./") + || pkg_name.ends_with(".ror") || pkg_name.ends_with(".sror"); + if is_local { continue; } if let Err(e) = delete::check_critical_install(pkg_name, &db) { eprintln!("{}", e); return; @@ -267,15 +277,56 @@ fn main() { Err(e) => eprintln!("{} {}", "[ror]".red().bold(), e), } } else { - if let Err(e) = parallel::install_packages_parallel(&args.install, Arc::clone(&cfg)) { - eprintln!("{} {}", "[ror]".red().bold(), e); + let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = args.install.iter() + .cloned() + .partition(|p| { + p.starts_with('/') || p.starts_with("./") + || p.ends_with(".ror") || p.ends_with(".sror") + }); + for path_str in &local_pkgs { + install::install_local_package(std::path::Path::new(path_str), &cfg); + } + if !remote_pkgs.is_empty() { + if let Err(e) = parallel::install_packages_parallel(&remote_pkgs, Arc::clone(&cfg)) { + eprintln!("{} {}", "[ror]".red().bold(), e); + } } } return; } - if let Some(recipe_path) = args.upgrade { - update::rebuild_from_recipe(&recipe_path, &cfg); + if args.upgrade { + match cfg.profile.group_name() { + Some(name) => { + let recipe = PathBuf::from(format!("/var/ror/packages/groups/{}.yaml", name)); + println!("{} Upgrading via profile group: {}", "[ror]".blue().bold(), name.cyan()); + update::rebuild_from_recipe(&recipe, &cfg); + } + None => { + eprintln!( + "{} No system profile in ror.conf. Use --up <group> to set a profile first.", + "[ror]".red().bold() + ); + } + } + return; + } + + if let Some(group_name) = args.upgrade_to { + let recipe = PathBuf::from(format!("/var/ror/packages/groups/{}.yaml", group_name)); + if !recipe.exists() { + eprintln!("{} Group '{}' not found at {}", "[ror]".red().bold(), group_name, recipe.display()); + return; + } + let mut sys_cfg = config::Config::load(); + sys_cfg.profile.active_group = Some(group_name.clone()); + if let Err(e) = sys_cfg.save() { + eprintln!("{} Failed to save profile: {}", "[ror]".red().bold(), e); + return; + } + println!("{} Profile set to group: {}", "[ror]".cyan().bold(), group_name.cyan()); + println!("{} Upgrading system...", ">>>".yellow()); + update::rebuild_from_recipe(&recipe, &sys_cfg); return; } diff --git a/src/repo.rs b/src/repo.rs index 0de55c5..a6d4b41 100644 --- a/src/repo.rs +++ b/src/repo.rs @@ -1,6 +1,5 @@ use colored::Colorize; -use std::fs; -use std::path::Path; +use std::io::{self, Write}; use crate::config::{Config, RepositoryConfig}; pub fn add_repository(name: &str, url: &str, mirror: Option<&str>) -> Result<(), String> { @@ -8,12 +7,52 @@ pub fn add_repository(name: &str, url: &str, mirror: Option<&str>) -> Result<(), if cfg.repositories.contains_key(name) { return Err(format!("Repository '{}' already exists", name)); } + + print!( + "{} Enable GPG verification for '{}'? [Y/n]: ", + "[ror]".blue().bold(), + name + ); + io::stdout().flush().ok(); + let mut answer = String::new(); + io::stdin().read_line(&mut answer).ok(); + let gpg_support = !answer.trim().eq_ignore_ascii_case("n"); + + if !gpg_support { + print!( + "{} Repository '{}' will have GPG disabled. It may be unsafe. Continue? [y/N]: ", + "[ror]".yellow().bold(), + name + ); + io::stdout().flush().ok(); + let mut confirm = String::new(); + io::stdin().read_line(&mut confirm).ok(); + if !confirm.trim().eq_ignore_ascii_case("y") { + println!("{} Aborted.", "[ror]".yellow()); + return Ok(()); + } + } + + let gpg_key = if gpg_support { + print!("{} GPG key filename (e.g. rorka.pub): ", "[ror]".blue().bold()); + io::stdout().flush().ok(); + let mut key = String::new(); + io::stdin().read_line(&mut key).ok(); + let key = key.trim().to_string(); + if key.is_empty() { None } else { Some(key) } + } else { + None + }; + let repo = RepositoryConfig { url: url.to_string(), + urlrepo: None, mirror: mirror.map(String::from), + gpg_support, + gpg_key, }; cfg.repositories.insert(name.to_string(), repo); - save_config(&cfg)?; + cfg.save().map_err(|e| format!("Failed to save config: {}", e))?; println!("{} Repository '{}' added.", "[ror]".green().bold(), name); Ok(()) } @@ -24,7 +63,7 @@ pub fn remove_repository(name: &str) -> Result<(), String> { return Err(format!("Repository '{}' not found", name)); } cfg.repositories.remove(name); - save_config(&cfg)?; + cfg.save().map_err(|e| format!("Failed to save config: {}", e))?; println!("{} Repository '{}' removed.", "[ror]".green().bold(), name); Ok(()) } @@ -41,12 +80,11 @@ pub fn list_repositories() { if let Some(m) = &repo.mirror { println!(" mirror: {}", m); } + if repo.gpg_support { + let key = repo.gpg_key.as_deref().unwrap_or("none"); + println!(" gpg: {} (key: {})", "enabled".green(), key.cyan()); + } else { + println!(" gpg: {}", "disabled".red().bold()); + } } } - -fn save_config(cfg: &Config) -> Result<(), String> { - let path = Path::new("/etc/ror/ror.conf"); - let ini = cfg.to_ini().map_err(|e| format!("Failed to serialize config: {}", e))?; - fs::write(path, ini).map_err(|e| format!("Failed to write config: {}", e))?; - Ok(()) -} diff --git a/src/rootfs.rs b/src/rootfs.rs index bd139de..3f06045 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -204,7 +204,6 @@ fn install_from_archive( pkg_name: &str, archive_path: &std::path::Path, root_dir: &Path, - binary_files: &[String], pkg_type: &str, dict_url: Option<&str>, cfg: &config::Config, @@ -230,13 +229,7 @@ fn install_from_archive( .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? }; - let file_list = if binary_files.is_empty() { - extracted - } else { - binary_files.to_vec() - }; - - let installed = install_files_with_root(&work_dir, root_dir, &file_list)?; + let installed = install_files_with_root(&work_dir, root_dir, &extracted)?; let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(archive_path); @@ -613,7 +606,6 @@ pub fn build_rootfs( pkg_name, archive_path, target_dir, - &binary.files, pkg_type, binary.dict.as_deref(), cfg, |