diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/apply.rs | 137 | ||||
| -rw-r--r-- | src/install.rs | 404 | ||||
| -rw-r--r-- | src/rootfs.rs | 199 | ||||
| -rw-r--r-- | src/sync.rs | 116 |
4 files changed, 500 insertions, 356 deletions
diff --git a/src/apply.rs b/src/apply.rs index 4e4ab44..2af85fe 100644 --- a/src/apply.rs +++ b/src/apply.rs @@ -1,4 +1,3 @@ - use std::collections::HashSet; use std::fs; use std::path::Path; @@ -10,6 +9,7 @@ use crate::group; use crate::install::{InstalledDB, load_package}; use crate::parallel; use crate::delete; +use crate::resolver; const DEFAULT_CONFIG_PATH: &str = "/etc/ror/system.yaml"; @@ -24,6 +24,8 @@ pub struct SystemConfig { #[serde(default)] #[allow(dead_code)] pub conflict_resolution: Option<String>, + #[serde(default)] + pub oss: bool, } #[derive(Debug, Deserialize, Default)] @@ -61,39 +63,39 @@ pub fn get_target_packages(sys_config: &SystemConfig, _cfg: &Config) -> Result<V if let Some(ref pkg) = sys_config.roles.init { match resolve_single_role(pkg, "init-system") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err(format!("Package '{}' does not provide init-system", pkg)), - } + }; } if let Some(ref pkg) = sys_config.roles.libc { match resolve_single_role(pkg, "libc") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err(format!("Package '{}' does not provide libc", pkg)), - } + }; } if let Some(ref pkg) = sys_config.roles.core { match resolve_single_role(pkg, "core-utils") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err(format!("Package '{}' does not provide core-utils", pkg)), - } + }; } if let Some(ref pkg) = sys_config.roles.udev { match resolve_single_role(pkg, "udev") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err(format!("Package '{}' does not provide udev", pkg)), - } + }; } if let Some(ref candidates) = sys_config.roles.sh { match resolve_list_role(candidates, "sh") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err("No package from sh list provides 'sh'".to_string()), - } + }; } if let Some(ref candidates) = sys_config.roles.su { match resolve_list_role(candidates, "su") { - Some(name) => { target.insert(name); } + Some(name) => target.insert(name), None => return Err("No package from su list provides 'su'".to_string()), - } + }; } for pkg in &sys_config.packages { @@ -108,11 +110,26 @@ pub fn get_target_packages(sys_config: &SystemConfig, _cfg: &Config) -> Result<V } } - Ok(target.into_iter().collect()) -} + let result: Vec<String> = target.into_iter().collect(); + + if sys_config.oss { + let mut non_oss = Vec::new(); + for pkg_name in &result { + match load_package(pkg_name) { + Some(pkg) if pkg.oss != Some(true) => non_oss.push(pkg_name.clone()), + None => non_oss.push(pkg_name.clone()), + _ => {} + } + } + if !non_oss.is_empty() { + return Err(format!( + "OSS policy is enabled but the following packages are not marked as open-source: {}", + non_oss.join(", ") + )); + } + } -fn resolve_dependencies(packages: &[String]) -> Result<Vec<String>, String> { - crate::rootfs::collect_install_order(packages) + Ok(result) } pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) -> Result<(), String> { @@ -122,23 +139,41 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - let sys_config: SystemConfig = serde_yaml::from_str(&content) .map_err(|e| format!("Invalid YAML: {}", e))?; - let target_packages = get_target_packages(&sys_config, cfg)?; - let ordered = resolve_dependencies(&target_packages)?; - + let target_names = get_target_packages(&sys_config, cfg)?; let db = InstalledDB::load(); - let installed: HashSet<String> = db.packages.keys().cloned().collect(); - let target_set: HashSet<String> = ordered.iter().cloned().collect(); - let to_install: Vec<String> = target_set.difference(&installed).cloned().collect(); - let to_remove: Vec<String> = installed.difference(&target_set).cloned().collect(); + let mut outdated = HashSet::new(); + let required = resolver::collect_required_packages(&target_names, &db, &mut outdated) + .map_err(|e| format!("Dependency 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(); + + if let Err(conflict_err) = resolver::check_conflicts(&required, &db) { + let msg = conflict_err.to_string(); + eprintln!("{} {}", "[ror]".yellow().bold(), msg); + if let Some(pkg_conflict) = msg.split("'").nth(3) { + let pkg = pkg_conflict.to_string(); + if !to_remove.contains(&pkg) { + to_remove.push(pkg); + } + } else { + return Err(conflict_err); + } + } + + to_remove.sort(); + let to_install: Vec<String> = required.iter().cloned().collect(); println!("{} System apply plan:", "[ror]".blue().bold()); + if to_install.is_empty() && to_remove.is_empty() { println!("{} System is already in the desired state.", "[ror]".green()); return Ok(()); } + if !to_install.is_empty() { - println!("{} Install: {}", ">>>".green(), to_install.join(", ")); + println!("{} Install/upgrade: {}", ">>>".green(), to_install.join(", ")); } if !to_remove.is_empty() { println!("{} Remove: {}", ">>>".red(), to_remove.join(", ")); @@ -149,6 +184,23 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - return Ok(()); } + let mut skipped_remove = Vec::new(); + for pkg in &to_remove { + let can_remove = delete::check_critical_removal(pkg, &db).is_ok() + && !delete::has_dependents(pkg, &db, &required); + if can_remove { + println!("{} Removing {}...", ">>>".cyan(), pkg); + delete::remove_package(pkg); + } else { + skipped_remove.push(pkg.clone()); + eprintln!( + "{} Will not remove {} (critical role or still required)", + "[ror]".yellow(), + pkg + ); + } + } + if !to_install.is_empty() { let rt = tokio::runtime::Runtime::new() .map_err(|e| format!("Failed to create async runtime: {}", e))?; @@ -157,24 +209,35 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - std::sync::Arc::new(cfg.clone()), ))?; } - let mut skipped = Vec::new(); - for pkg in &to_remove { - let can_remove = delete::check_critical_removal(pkg, &db).is_ok() - && !delete::has_dependents(pkg, &db, &target_set); - if can_remove { - println!("{} Removing {}...", ">>>".cyan(), pkg); - delete::remove_package(pkg); + + 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) + .map_err(|e| format!("Re-resolution after install failed: {}", e))? + }; + let extra_remove: Vec<String> = final_installed.difference(&final_required).cloned().collect(); + + for pkg in extra_remove { + if delete::check_critical_removal(&pkg, &final_db).is_ok() + && !delete::has_dependents(&pkg, &final_db, &final_required) + { + println!("{} Removing extra {}...", ">>>".cyan(), pkg); + delete::remove_package(&pkg); } else { - skipped.push(pkg.clone()); + if !skipped_remove.contains(&pkg) { + skipped_remove.push(pkg); + } } } - if !skipped.is_empty() { + if !skipped_remove.is_empty() { println!( - "{} Skipped removal of {} (still required by other packages or protected): {}", + "{} Skipped removal of {} (still required or protected): {}", "[ror]".yellow().bold(), - skipped.len(), - skipped.join(", ") + skipped_remove.len(), + skipped_remove.join(", ") ); } diff --git a/src/install.rs b/src/install.rs index 3fe5c5c..e688076 100644 --- a/src/install.rs +++ b/src/install.rs @@ -1,8 +1,9 @@ use serde::{Deserialize, Serialize}; use std::fs; +use std::io::{BufReader, Read, Write}; use std::path::{Path, PathBuf}; +use std::ffi::CStr; use colored::Colorize; -use std::process::Command; use reqwest::blocking::Client; use sha2::{Sha256, Digest}; use walkdir::WalkDir; @@ -12,6 +13,9 @@ use std::os::unix::fs::symlink; use crate::config; use crate::progress::{Spinner, format_bytes}; use crate::debug; +use tar::Archive as TarArchive; +use zstd::stream::read::Decoder as ZstdDecoder; +use pgp::composed::{Deserializable, SignedPublicKey, DetachedSignature}; const REPO_ROOT: &str = "/var/ror/packages"; @@ -93,6 +97,8 @@ pub struct Package { pub depends: Vec<Dependency>, #[serde(default)] pub conflicts: Vec<String>, + #[serde(default)] + pub oss: Option<bool>, } #[derive(Debug, Serialize, Deserialize)] @@ -198,6 +204,95 @@ fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec<String> { timed.into_iter().map(|(_, url)| url).collect() } +pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) -> Result<PathBuf, String> { + debug!("Downloading {} (expected SHA256: {})", url, if expected_sha.is_empty() { "none" } else { expected_sha }); + let client = Client::builder() + .connect_timeout(std::time::Duration::from_secs(30)) + .build() + .map_err(|e| format!("Failed to build HTTP client: {}", e))?; + + let response = client + .get(url) + .send() + .map_err(|e| format!("Download failed: {}", e))?; + + if !response.status().is_success() { + return Err(format!("HTTP error: {}", response.status())); + } + + let total_size = response + .headers() + .get(reqwest::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.parse::<u64>().ok()); + + let tmp_dir = Path::new("/tmp/ror-download"); + fs::create_dir_all(tmp_dir).map_err(|e| format!("Failed to create tmp dir: {}", e))?; + + let file_name = url.split('/').last().unwrap_or("archive.tmp"); + let file_path = tmp_dir.join(file_name); + + { + let mut file = fs::File::create(&file_path) + .map_err(|e| format!("Failed to create temp file: {}", e))?; + let mut hasher = Sha256::new(); + let mut reader = response; + let mut buf = [0u8; 65536]; + let mut downloaded: u64 = 0; + + loop { + let n = reader + .read(&mut buf) + .map_err(|e| format!("Failed to read response body: {}", e))?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]) + .map_err(|e| format!("Failed to write to temp file: {}", e))?; + downloaded += n as u64; + + match total_size { + Some(total) if total > 0 => { + let pct = downloaded * 40 / total; + let bar = format!( + "{}>{}", + "=".repeat(pct.saturating_sub(1) as usize), + " ".repeat((40 - pct) as usize) + ); + eprint!( + "\r\x1b[K\x1b[36m[{}]\x1b[0m {} / {}", + bar, + format_bytes(downloaded), + format_bytes(total) + ); + } + _ => { + eprint!("\r\x1b[K{} downloaded", format_bytes(downloaded)); + } + } + std::io::stderr().flush().ok(); + } + + eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", format_bytes(downloaded)); + + if !expected_sha.is_empty() { + let hash = format!("{:x}", hasher.finalize()); + if hash != expected_sha { + let _ = fs::remove_file(&file_path); + debug!("SHA256 mismatch: expected {}, got {}", expected_sha, hash); + return Err(format!( + "SHA256 mismatch: expected {}, got {}", + expected_sha, hash + )); + } + debug!("SHA256 verified successfully"); + } + } + + Ok(file_path) +} + pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, String> { debug!("Extracting .deb archive {:?} to {:?}", archive_path, dest_root); let file = fs::File::open(archive_path).map_err(|e| e.to_string())?; @@ -209,7 +304,7 @@ pub fn extract_deb(archive_path: &Path, dest_root: &Path) -> Result<Vec<String>, let identifier = std::str::from_utf8(entry.header().identifier()).unwrap_or(""); if identifier.contains("data.tar") { - let reader: Box<dyn std::io::Read> = if identifier.ends_with(".xz") { + let reader: Box<dyn Read> = if identifier.ends_with(".xz") { Box::new(xz2::read::XzDecoder::new(entry)) } else { Box::new(entry) @@ -317,65 +412,32 @@ pub fn find_package_with_repo(pkg_name: &str) -> Option<(PathBuf, String)> { None } -pub fn verify_gpg_signature(archive_path: &Path, asc_path: &Path, pubkey_path: &Path) -> Result<(), String> { - debug!("Verifying GPG signature for {:?}", archive_path); - 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))?; +pub fn verify_gpg_signature( + archive_path: &Path, + asc_path: &Path, + pubkey_path: &Path, +) -> Result<(), String> { + let key_bytes = fs::read(pubkey_path) + .map_err(|e| format!("Cannot read key: {}", e))?; + let public_key = SignedPublicKey::from_bytes(BufReader::new(&key_bytes[..])) + .map_err(|e| format!("Invalid public key: {}", e))?; - if !import.status.success() { - return Err(format!( - "Failed to import GPG key {}: {}", - pubkey_path.display(), - String::from_utf8_lossy(&import.stderr) - )); - } + let sig_bytes = fs::read(asc_path) + .map_err(|e| format!("Cannot read signature: {}", e))?; + let signature = DetachedSignature::from_bytes(BufReader::new(&sig_bytes[..])) + .map_err(|e| format!("Invalid signature format: {}", e))?; - 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 mut data = Vec::new(); + fs::File::open(archive_path) + .map_err(|e| format!("Cannot open archive: {}", e))? + .read_to_end(&mut data) + .map_err(|e| format!("Cannot read archive: {}", e))?; - let _ = fs::remove_file(tmp_keyring); + signature.verify(&public_key, &data) + .map_err(|e| format!("GPG signature verification failed: {}", e))?; - if verify.status.success() { - debug!("GPG signature verification succeeded"); - Ok(()) - } else { - Err(format!( - "GPG signature verification failed for {}: {}", - archive_path.display(), - String::from_utf8_lossy(&verify.stderr).lines().next().unwrap_or("unknown error") - )) - } + Ok(()) } pub fn install_package(pkg_name: &str, cfg: &config::Config) { @@ -428,6 +490,8 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu debug!("Loaded package metadata for {} version {}", pkg.name, pkg.version); + check_oss_policy(&pkg)?; + if pkg.binaries.is_empty() { return Err("No binary packages defined".to_string()); } @@ -607,112 +671,10 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu }) } -pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) -> Result<PathBuf, String> { - debug!("Downloading {} (expected SHA256: {})", url, if expected_sha.is_empty() { "none" } else { expected_sha }); - let client = Client::builder() - .connect_timeout(std::time::Duration::from_secs(30)) - .build() - .map_err(|e| format!("Failed to build HTTP client: {}", e))?; - - let response = client - .get(url) - .send() - .map_err(|e| format!("Download failed: {}", e))?; - - if !response.status().is_success() { - return Err(format!("HTTP error: {}", response.status())); - } - - let total_size = response - .headers() - .get(reqwest::header::CONTENT_LENGTH) - .and_then(|v| v.to_str().ok()) - .and_then(|s| s.parse::<u64>().ok()); - - let tmp_dir = Path::new("/tmp/ror-download"); - fs::create_dir_all(tmp_dir).map_err(|e| format!("Failed to create tmp dir: {}", e))?; - - let file_name = url.split('/').last().unwrap_or("archive.tmp"); - let file_path = tmp_dir.join(file_name); - - { - use std::io::Write; - let mut file = fs::File::create(&file_path) - .map_err(|e| format!("Failed to create temp file: {}", e))?; - let mut hasher = Sha256::new(); - let mut reader = response; - let mut buf = [0u8; 65536]; - let mut downloaded: u64 = 0; - - loop { - use std::io::Read; - let n = reader - .read(&mut buf) - .map_err(|e| format!("Failed to read response body: {}", e))?; - if n == 0 { - break; - } - hasher.update(&buf[..n]); - file.write_all(&buf[..n]) - .map_err(|e| format!("Failed to write to temp file: {}", e))?; - downloaded += n as u64; - - match total_size { - Some(total) if total > 0 => { - let pct = downloaded * 40 / total; - let bar = format!( - "{}>{}", - "=".repeat(pct.saturating_sub(1) as usize), - " ".repeat((40 - pct) as usize) - ); - eprint!( - "\r\x1b[K\x1b[36m[{}]\x1b[0m {} / {}", - bar, - format_bytes(downloaded), - format_bytes(total) - ); - } - _ => { - eprint!("\r\x1b[K{} downloaded", format_bytes(downloaded)); - } - } - use std::io::stderr; - stderr().flush().ok(); - } - - eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", format_bytes(downloaded)); - - if !expected_sha.is_empty() { - let hash = format!("{:x}", hasher.finalize()); - if hash != expected_sha { - let _ = fs::remove_file(&file_path); - debug!("SHA256 mismatch: expected {}, got {}", expected_sha, hash); - return Err(format!( - "SHA256 mismatch: expected {}, got {}", - expected_sha, hash - )); - } - debug!("SHA256 verified successfully"); - } - } - - Ok(file_path) -} - pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - debug!("Extracting native tar archive {:?} to {:?}", archive_path, target_dir); - let status = Command::new("tar") - .arg("-xf") - .arg(archive_path) - .arg("-C") - .arg(target_dir) - .status() - .map_err(|e| format!("Failed to execute tar: {}", e))?; - - if !status.success() { - return Err(format!("tar failed with exit code {:?}", status.code())); - } - + 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() { @@ -720,28 +682,16 @@ pub fn extract_native(archive_path: &Path, target_dir: &Path) -> Result<Vec<Stri files.push(rel_path.to_string_lossy().to_string()); } } - debug!("Extracted {} files/dirs", files.len()); Ok(files) } pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - debug!("Extracting .ror archive {:?} using dictionary {:?}", archive_path, dict_path); - let zstd_arg = format!("zstd -D {}", dict_path.display()); - - let status = Command::new("tar") - .arg("-I") - .arg(&zstd_arg) - .arg("-xf") - .arg(archive_path) - .arg("-C") - .arg(target_dir) - .status() - .map_err(|e| format!("Failed to execute tar for .ror: {}", e))?; - - if !status.success() { - return Err(format!("tar .ror failed with exit code {:?}", status.code())); - } - + 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()) { if entry.file_type().is_file() || entry.file_type().is_symlink() { @@ -749,26 +699,14 @@ pub fn extract_ror(archive_path: &Path, dict_path: &Path, target_dir: &Path) -> files.push(rel_path.to_string_lossy().to_string()); } } - debug!("Extracted {} files from .ror", files.len()); Ok(files) } pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String>, String> { - debug!("Extracting .sror archive {:?} to {:?}", archive_path, target_dir); - 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 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))?; 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() { @@ -776,7 +714,6 @@ pub fn extract_sror(archive_path: &Path, target_dir: &Path) -> Result<Vec<String files.push(rel_path.to_string_lossy().to_string()); } } - debug!("Extracted {} files from .sror", files.len()); Ok(files) } @@ -845,21 +782,50 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) } pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { - debug!("Running commands: {}", steps); if steps.trim().is_empty() { return Ok(()); } - let status = Command::new("sh") - .current_dir(work_dir) - .arg("-c") - .arg(steps) - .status() - .map_err(|e| format!("Failed to execute sh -c: {}", e))?; - if status.success() { - debug!("Commands executed successfully"); - Ok(()) - } else { - Err(format!("Command failed with exit code {:?}", status.code())) + use nix::unistd::{fork, ForkResult, chdir, execve}; + use nix::sys::wait::{waitpid, WaitStatus}; + use std::ffi::CString; + + let script = format!("#!/bin/sh\nset -e\n{}", steps); + let tmp_script = "/tmp/ror-install-step.sh"; + fs::write(tmp_script, &script).map_err(|e| format!("Cannot write script: {}", e))?; + + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chdir(work_dir).is_err() { std::process::exit(1); } + let shell = CString::new("/bin/sh").unwrap(); + let arg0 = CString::new("sh").unwrap(); + let arg1 = CString::new(tmp_script).unwrap(); + let _ = execve::<&CStr, &CStr>(&shell, &[&arg0, &arg1], &[]); + std::process::exit(1); + } + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, code)) => { + let _ = fs::remove_file(tmp_script); + if code == 0 { + Ok(()) + } else { + Err(format!("Install script failed with code {}", code)) + } + } + Ok(_) => { + let _ = fs::remove_file(tmp_script); + Err("Install script terminated by signal".to_string()) + } + Err(e) => { + let _ = fs::remove_file(tmp_script); + Err(format!("waitpid failed: {}", e)) + } + } + } + Err(e) => { + let _ = fs::remove_file(tmp_script); + Err(format!("Fork failed: {}", e)) + } } } @@ -884,6 +850,28 @@ pub fn load_package(pkg_name: &str) -> Option<Package> { serde_yaml::from_str(&content).ok() } +fn check_oss_policy(pkg: &Package) -> Result<(), String> { + const SYSTEM_YAML: &str = "/etc/ror/system.yaml"; + let Ok(content) = fs::read_to_string(SYSTEM_YAML) else { + return Ok(()); + }; + #[derive(serde::Deserialize)] + struct OssCheck { + #[serde(default)] + oss: bool, + } + let Ok(check) = serde_yaml::from_str::<OssCheck>(&content) else { + return Ok(()); + }; + if check.oss && pkg.oss != Some(true) { + return Err(format!( + "Package '{}' is not marked as open-source (oss: true) but system policy requires it", + pkg.name + )); + } + Ok(()) +} + pub fn install_local_package(archive_path: &Path, cfg: &config::Config) { debug!("Starting local install from {:?}", archive_path); match install_local_package_with_result(archive_path, cfg) { diff --git a/src/rootfs.rs b/src/rootfs.rs index b408741..027cce1 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,14 +1,12 @@ use crate::apply::SystemConfig; -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::HashMap; use std::fs; -use std::path::Path; -use std::process::Command; +use std::path::{Path}; use std::os::unix::fs::symlink; use std::sync::{Arc, Mutex}; use std::thread; use colored::Colorize; use serde::Serialize; -use serde_json; use crate::config; use crate::progress::ProgressBar; use chrono::Local; @@ -17,7 +15,14 @@ use crate::install::{ extract_native, extract_ror, install_files_with_root, select_binary_for_arch, InstalledDB, InstalledPackage, }; - +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::ffi::CString; +use std::ffi::CStr; +use std::collections::HashSet; +use std::collections::VecDeque; struct DownloadTask { pkg_name: String, urls: Vec<String>, @@ -167,7 +172,6 @@ fn download_parallel( total, task.pkg_name ); - use std::io::Write; std::io::stderr().flush().ok(); break; } @@ -283,7 +287,7 @@ fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { ("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))?; } @@ -329,27 +333,29 @@ fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { ("proc", "proc", "proc", false), ("sysfs", "sys", "sysfs", false), ]; - for (src, rel, fstype, bind) in mounts { let target = root_dir.join(rel); fs::create_dir_all(&target) .map_err(|e| format!("Failed to create mountpoint {}: {}", rel, e))?; - let status = if *bind { - Command::new("mount") - .args(["--bind", src, target.to_str().unwrap()]) - .status() + if *bind { + mount( + Some(Path::new(src)), + &target, + None::<&str>, + MsFlags::MS_BIND | MsFlags::MS_REC, + None::<&Path>, + ) } else { - Command::new("mount") - .args(["-t", fstype, src, target.to_str().unwrap()]) - .status() - }; - - match status { - Ok(s) if s.success() => {} - Ok(_) => eprintln!("{} Warning: failed to mount {} (non-fatal)", "[ror]".yellow(), rel), - Err(e) => eprintln!("{} Warning: mount {}: {} (non-fatal)", "[ror]".yellow(), rel, e), + mount( + Some(Path::new(src)), + &target, + Some(*fstype), + MsFlags::empty(), + None::<&Path>, + ) } + .map_err(|e| format!("Failed to mount {}: {}", rel, e))?; } Ok(()) } @@ -358,7 +364,7 @@ fn umount_virtual_fs(root_dir: &Path) { for rel in &["dev/pts", "dev/shm", "dev", "proc", "sys"] { let target = root_dir.join(rel); if target.exists() { - let _ = Command::new("umount").args(["-l", target.to_str().unwrap()]).status(); + let _ = umount2(&target, MntFlags::MNT_DETACH); } } } @@ -378,39 +384,56 @@ const SHELL_CANDIDATES: &[(&str, Option<&str>)] = &[ ]; fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { - for &(shell_path, subcmd) in SHELL_CANDIDATES { - if !root_dir.join(shell_path.trim_start_matches('/')).exists() { + for (shell_path, subcmd) in SHELL_CANDIDATES { + let full = root_dir.join(shell_path.trim_start_matches('/')); + if !full.exists() { continue; } - - let mut cmd = Command::new("chroot"); - cmd.arg(root_dir).arg(shell_path); - if let Some(sub) = subcmd { - cmd.arg(sub); + let test_script = "exit 0"; + let script_path = root_dir.join(".ror-shell-test.sh"); + if fs::write(&script_path, format!("#!/bin/sh\n{}", test_script)).is_err() { + continue; } - cmd.arg("-c").arg("exit 0"); - - match cmd.output() { - Ok(out) if out.status.success() => return Some((shell_path, subcmd)), - Ok(out) => { - let stderr = String::from_utf8_lossy(&out.stderr); - eprintln!( - "{} Shell {} failed in chroot ({}), trying next...", - "[ror]".yellow(), - shell_path, - stderr.lines().next().unwrap_or("unknown error").trim() - ); + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let shell_c = CString::new(*shell_path).unwrap(); + let arg0 = CString::new(*shell_path).unwrap(); + let args = if let Some(sub) = subcmd { + let sub_c = CString::new(*sub).unwrap(); + let script_c = CString::new(".ror-shell-test.sh").unwrap(); + vec![arg0, sub_c, script_c] + } else { + let script_c = CString::new(".ror-shell-test.sh").unwrap(); + vec![arg0, script_c] + }; + let args_refs: Vec<&CStr> = args.iter().map(|s| s.as_c_str()).collect(); + let _ = execve::<&CStr, &CStr>(&shell_c, &args_refs, &[]); + std::process::exit(1); } - Err(e) => { - eprintln!("{} Cannot test shell {}: {}, trying next...", "[ror]".yellow(), shell_path, e); + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, 0)) => { + let _ = fs::remove_file(&script_path); + return Some((*shell_path, *subcmd)); + } + Ok(_) => { + let _ = fs::remove_file(&script_path); + } + Err(_) => { + let _ = fs::remove_file(&script_path); + } + } } + Err(_) => { let _ = fs::remove_file(&script_path); } } } None } fn run_install_steps_in_chroot( - pkg_name: &str, + _pkg_name: &str, steps: &str, root_dir: &Path, shell: &str, @@ -418,29 +441,70 @@ fn run_install_steps_in_chroot( ) -> Result<(), String> { let script_rel = "/.ror-install-steps.sh"; let script_host = root_dir.join(script_rel.trim_start_matches('/')); - fs::write(&script_host, format!("#!/bin/sh\nset -e\n{}", steps)) - .map_err(|e| format!("Failed to write install script: {}", e))?; - - let mut cmd = Command::new("chroot"); - cmd.arg(root_dir).arg(shell); - if let Some(sub) = subcmd { - cmd.arg(sub); + .map_err(|e| format!("Failed to write script: {}", e))?; + + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let shell_c = CString::new(shell).unwrap(); + let arg0 = CString::new(shell).unwrap(); + let script_c = CString::new(script_rel).unwrap(); + let args = if let Some(sub) = subcmd { + let sub_c = CString::new(sub).unwrap(); + vec![arg0, sub_c, script_c] + } else { + vec![arg0, script_c] + }; + let _ = execve::<&CStr, &CStr>(&shell_c, &args.iter().map(|s| s.as_ref()).collect::<Vec<_>>(), &[]); + std::process::exit(1); + } + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, code)) => { + let _ = fs::remove_file(&script_host); + if code == 0 { + Ok(()) + } else { + Err(format!("install_steps failed with exit code {}", code)) + } + } + Ok(_) => { + let _ = fs::remove_file(&script_host); + Err("install_steps terminated by signal".to_string()) + } + Err(e) => { + let _ = fs::remove_file(&script_host); + Err(format!("waitpid failed: {}", e)) + } + } + } + Err(e) => { + let _ = fs::remove_file(&script_host); + Err(format!("Fork failed: {}", e)) + } } - cmd.arg(script_rel); - - let status = cmd.status() - .map_err(|e| format!("Failed to execute chroot for {}: {}", pkg_name, e))?; - - let _ = fs::remove_file(&script_host); +} - if status.success() { - Ok(()) - } else { - Err(format!( - "install_steps for '{}' failed with exit code {:?}", - pkg_name, status.code() - )) +fn run_ldconfig_in_root(root_dir: &Path) -> Result<(), String> { + match unsafe { fork() } { + Ok(ForkResult::Child) => { + if chroot(root_dir).is_err() { std::process::exit(1); } + if chdir("/").is_err() { std::process::exit(1); } + let ldconfig = CString::new("/sbin/ldconfig").unwrap(); + let arg0 = CString::new("ldconfig").unwrap(); + let _ = execve::<&CString, &CStr>(&ldconfig, &[&arg0], &[]); + std::process::exit(1); + } + Ok(ForkResult::Parent { child }) => { + match waitpid(child, None) { + Ok(WaitStatus::Exited(_, 0)) => Ok(()), + Ok(_) => Err("ldconfig terminated abnormally".to_string()), + Err(e) => Err(format!("waitpid ldconfig failed: {}", e)), + } + } + Err(e) => Err(format!("Fork for ldconfig failed: {}", e)), } } @@ -649,9 +713,10 @@ pub fn build_rootfs( if !ld_conf.exists() { let _ = fs::write(&ld_conf, "/usr/lib\n/usr/lib64\n"); } - match Command::new("ldconfig").arg("-r").arg(target_dir).status() { - Ok(s) if s.success() => println!("{} ldconfig done.", ">>>".green()), - _ => eprintln!("{} ldconfig failed (non-fatal)", "[ror]".yellow()), + if let Err(e) = run_ldconfig_in_root(target_dir) { + eprintln!("{} ldconfig failed: {} (non-fatal)", "[ror]".yellow(), e); + } else { + println!("{} ldconfig done.", ">>>".green()); } } diff --git a/src/sync.rs b/src/sync.rs index 3734a03..d717694 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -1,69 +1,97 @@ use colored::*; -use std::path::Path; -use std::process::Command; +use std::path::{Path}; +use git2::{Repository, RemoteCallbacks, FetchOptions, build::RepoBuilder}; use crate::config::Config; -const REPOS_DIR: &str = "/var/ror/packages"; +const REPOS_DIR: &str = "/var/ror/packages"; pub fn run_sync(cfg: &Config) { if cfg.repositories.is_empty() { eprintln!("{} No repositories configured.", "[ror]".red().bold()); return; } - for (name, repo) in &cfg.repositories { println!("{} Syncing repository '{}'...", "[ror]".blue().bold(), name); let repo_path = Path::new(REPOS_DIR).join(name); - if repo_path.exists() { println!("{} Updating {}...", ">>>".green(), name); - let status = Command::new("git") - .args(&["-C", repo_path.to_str().unwrap(), "pull"]) - .status() - .expect("Failed to execute git pull"); - - if !status.success() && repo.mirror.is_some() { - eprintln!("{} Pull failed, trying mirror...", "[ror]".red()); - let mirror_url = repo.mirror.as_ref().unwrap(); - let mirror_status = Command::new("git") - .args(&["-C", repo_path.to_str().unwrap(), "pull", mirror_url]) - .status() - .expect("Failed to execute git pull from mirror"); - if mirror_status.success() { - println!("{} Updated from mirror.", ">>>".green()); - } else { - eprintln!("{} Mirror also failed.", "[ror]".red()); - } - } else if !status.success() { - eprintln!("{} Git pull failed, no mirror configured.", "[ror]".red()); + if let Err(e) = pull_or_clone(&repo_path, &repo.url) { + eprintln!("{} {}", "[ror]".red(), e); } else { println!("{} Repository updated.", ">>>".green()); } } else { println!("{} Cloning {}...", ">>>".green(), name); - let primary_url = &repo.url; - let mut status = Command::new("git") - .args(&["clone", primary_url, repo_path.to_str().unwrap()]) - .status() - .expect("Failed to execute git clone"); - - if !status.success() && repo.mirror.is_some() { - eprintln!("{} Clone from primary failed, trying mirror...", "[ror]".red()); - let mirror_url = repo.mirror.as_ref().unwrap(); - status = Command::new("git") - .args(&["clone", mirror_url, repo_path.to_str().unwrap()]) - .status() - .expect("Failed to execute git clone from mirror"); - if status.success() { - println!("{} Cloned from mirror.", ">>>".green()); - } else { - eprintln!("{} Mirror also failed.", "[ror]".red()); - } - } else if !status.success() { - eprintln!("{} Git clone failed.", "[ror]".red()); + if let Err(e) = clone_repo(name, &repo.url, repo.mirror.as_deref()) { + eprintln!("{} {}", "[ror]".red(), e); } else { println!("{} Repository cloned.", ">>>".green()); } } } } + +fn clone_repo(name: &str, primary: &str, mirror: Option<&str>) -> Result<(), String> { + let path = Path::new(REPOS_DIR).join(name); + let cb = RemoteCallbacks::new(); + let mut fo = FetchOptions::new(); + fo.remote_callbacks(cb); + let result = RepoBuilder::new() + .fetch_options(fo) + .clone(primary, &path); + if result.is_err() { + if let Some(mirror_url) = mirror { + let cb2 = RemoteCallbacks::new(); + let mut fo2 = FetchOptions::new(); + fo2.remote_callbacks(cb2); + RepoBuilder::new() + .fetch_options(fo2) + .clone(mirror_url, &path) + .map_err(|e| format!("Failed to clone from primary and mirror: {}", e))?; + } else { + return Err(format!("Clone failed: {}", result.err().unwrap())); + } + } + Ok(()) +} + +fn pull_or_clone(repo_path: &Path, primary: &str) -> Result<(), String> { + let repo = Repository::open(repo_path) + .map_err(|e| format!("Cannot open repository: {}", e))?; + let mut remote = repo.find_remote("origin") + .or_else(|_| { + repo.remote_set_url("origin", primary)?; + repo.find_remote("origin") + }) + .map_err(|e| format!("Remote error: {}", e))?; + let cb = RemoteCallbacks::new(); + let mut fo = FetchOptions::new(); + fo.remote_callbacks(cb); + remote.fetch(&["refs/heads/*:refs/heads/*"], Some(&mut fo), None) + .map_err(|e| format!("Fetch failed: {}", e))?; + let fetch_head = repo.find_reference("FETCH_HEAD") + .map_err(|e| format!("FETCH_HEAD missing: {}", e))?; + let fetch_commit = repo.reference_to_annotated_commit(&fetch_head) + .map_err(|e| format!("Annotated commit error: {}", e))?; + let (analysis, _) = repo.merge_analysis(&[&fetch_commit]) + .map_err(|e| format!("Merge analysis failed: {}", e))?; + if analysis.is_fast_forward() { + let mut refname = "refs/heads/master".to_string(); + if let Ok(head) = repo.head() { + if let Some(name) = head.name() { + refname = name.to_string(); + } + } + let mut reference = repo.find_reference(&refname) + .map_err(|e| format!("Reference not found: {}", e))?; + reference.set_target(fetch_commit.id(), "fast-forward merge") + .map_err(|e| format!("Set target failed: {}", e))?; + repo.set_head(&refname) + .map_err(|e| format!("Set head failed: {}", e))?; + repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force())) + .map_err(|e| format!("Checkout failed: {}", e))?; + } else if analysis.is_normal() { + return Err("Non-fast-forward update requires manual merge".to_string()); + } + Ok(()) +} |