diff options
Diffstat (limited to 'src')
| -rwxr-xr-x | src/apply.rs | 21 | ||||
| -rwxr-xr-x | src/check.rs | 25 | ||||
| -rwxr-xr-x | src/config.rs | 15 | ||||
| -rw-r--r-- | src/delete.rs | 8 | ||||
| -rwxr-xr-x | src/group.rs | 29 | ||||
| -rw-r--r-- | src/install.rs | 276 | ||||
| -rw-r--r-- | src/main.rs | 153 | ||||
| -rw-r--r-- | src/parallel.rs | 60 | ||||
| -rwxr-xr-x | src/progress.rs | 1 | ||||
| -rwxr-xr-x | src/repo.rs | 83 | ||||
| -rwxr-xr-x | src/resolver.rs | 90 | ||||
| -rwxr-xr-x | src/rootfs.rs | 77 | ||||
| -rwxr-xr-x | src/sync.rs | 161 | ||||
| -rwxr-xr-x | src/update.rs | 33 |
14 files changed, 640 insertions, 392 deletions
diff --git a/src/apply.rs b/src/apply.rs index 423a8bc..dd5268d 100755 --- a/src/apply.rs +++ b/src/apply.rs @@ -163,16 +163,17 @@ pub fn apply_system(cfg: &Config, dry_run: bool, custom_config: Option<&Path>) - let installed_set: HashSet<String> = db.packages.keys().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(); - 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); + let installed_conflicts = resolver::find_installed_conflicts(&required, &db); + for (req_pkg, inst_pkg) in installed_conflicts { + eprintln!( + "{} Package '{}' conflicts with installed '{}'. Scheduling removal of '{}'.", + "[ror]".yellow().bold(), + req_pkg, + inst_pkg, + inst_pkg + ); + if !to_remove.contains(&inst_pkg) { + to_remove.push(inst_pkg); } } diff --git a/src/check.rs b/src/check.rs index 530814f..f7e3126 100755 --- a/src/check.rs +++ b/src/check.rs @@ -2,7 +2,7 @@ use colored::Colorize; use sha2::{Sha256, Digest}; use std::collections::HashMap; use std::fs; -use std::io::Write; +use std::io::{Write, IsTerminal}; use std::path::{Path}; use tempfile::tempdir; @@ -189,15 +189,22 @@ pub fn check_integrity(cfg: &Config) { "[ror]".yellow().bold(), broken_packages.join(", ") ); - print!("{} Reinstall them? [y/N]: ", "[ror]".blue().bold()); - std::io::stdout().flush().ok(); - let mut answer = String::new(); - std::io::stdin().read_line(&mut answer).ok(); - if answer.trim().eq_ignore_ascii_case("y") { - for pkg in broken_packages { - println!("{} Reinstalling {} ...", ">>>".cyan(), pkg); - crate::install::install_package(&pkg, cfg); + if std::io::stdin().is_terminal() { + print!("{} Reinstall them? [y/N]: ", "[ror]".blue().bold()); + std::io::stdout().flush().ok(); + let mut answer = String::new(); + std::io::stdin().read_line(&mut answer).ok(); + if answer.trim().eq_ignore_ascii_case("y") { + for pkg in broken_packages { + println!("{} Reinstalling {} ...", ">>>".cyan(), pkg); + crate::install::install_package(&pkg, cfg); + } } + } else { + eprintln!( + "{} Non-interactive mode: skipping automatic reinstall of broken packages", + "[ror]".yellow() + ); } } } diff --git a/src/config.rs b/src/config.rs index 2ff93d8..9a4a22e 100755 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,11 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs; +use std::io::Write; +use std::os::unix::fs::PermissionsExt; use std::path::Path; use colored::Colorize; +use tempfile::NamedTempFile; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct RepositoryConfig { @@ -155,7 +158,11 @@ impl Config { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } - fs::write(path, ini) + let mut tmp = NamedTempFile::new_in(path.parent().unwrap_or(Path::new(".")))?; + tmp.write_all(ini.as_bytes())?; + fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o644))?; + tmp.persist(path)?; + Ok(()) } pub fn to_ini(&self) -> Result<String, config::ConfigError> { @@ -225,7 +232,11 @@ impl Config { "gpg_key = \"rorka.pub\"\n", ); fs::create_dir_all(path.parent().unwrap())?; - fs::write(path, ini) + let mut tmp = NamedTempFile::new_in(path.parent().unwrap_or(Path::new(".")))?; + tmp.write_all(ini.as_bytes())?; + fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o644))?; + tmp.persist(path)?; + Ok(()) } } diff --git a/src/delete.rs b/src/delete.rs index 6966f82..094e4c4 100644 --- a/src/delete.rs +++ b/src/delete.rs @@ -175,7 +175,13 @@ pub fn remove_package_files_only(_pkg_name: &str, files: &[String]) -> bool { let mut failed = false; for rel_path in files { - let full_path = Path::new("/").join(rel_path); + let clean = rel_path.trim_start_matches('/'); + if clean.contains("..") || clean.is_empty() { + eprintln!("{} Skipping suspicious path: {}", "[ror]".red().bold(), rel_path); + failed = true; + continue; + } + let full_path = Path::new("/").join(clean); if full_path.exists() { debug!("Removing file {}", full_path.display()); if let Err(e) = fs::remove_file(&full_path) { diff --git a/src/group.rs b/src/group.rs index 3f1844b..8ce4a88 100755 --- a/src/group.rs +++ b/src/group.rs @@ -5,6 +5,21 @@ use colored::Colorize; use crate::config; use crate::install; +const GROUPS_DIR: &str = "/var/ror/packages/groups"; + +fn sanitize_group_name(name: &str) -> Result<(), String> { + if name.is_empty() { + return Err("Group name is empty".to_string()); + } + if name.contains('/') || name.contains('\\') || name.contains("..") || name.contains('\0') { + return Err(format!("Invalid group name: '{}' contains path traversal characters", name)); + } + if name.starts_with('-') { + return Err(format!("Invalid group name: '{}' starts with dash", name)); + } + Ok(()) +} + #[derive(Debug, Deserialize)] pub struct Group { #[allow(dead_code)] @@ -34,7 +49,11 @@ pub struct Group { #[allow(dead_code)] pub fn install_group(group_name: &str, cfg: &config::Config) { - let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); + if let Err(e) = sanitize_group_name(group_name) { + eprintln!("{} {}", "[ror]".red().bold(), e); + return; + } + let group_file = format!("{}/{}.yaml", GROUPS_DIR, group_name); if !Path::new(&group_file).exists() { eprintln!("{} Group '{}' not found!", "[ror]".red().bold(), group_name); return; @@ -76,7 +95,8 @@ pub fn install_group(group_name: &str, cfg: &config::Config) { } pub fn load_group(group_name: &str) -> Result<Group, String> { - let group_file = format!("/var/ror/packages/groups/{}.yaml", group_name); + sanitize_group_name(group_name)?; + let group_file = format!("{}/{}.yaml", GROUPS_DIR, group_name); let content = fs::read_to_string(&group_file) .map_err(|e| format!("Failed to read group file: {}", e))?; let group: Group = serde_yaml::from_str(&content) @@ -85,14 +105,13 @@ pub fn load_group(group_name: &str) -> Result<Group, String> { } pub fn list_groups() { - let groups_dir = "/var/ror/packages/groups"; - if !Path::new(groups_dir).exists() { + if !Path::new(GROUPS_DIR).exists() { println!("{} Groups directory not found.", "[ror]".yellow()); return; } println!("{} Available package groups:", "[ror]".blue().bold()); - if let Ok(entries) = std::fs::read_dir(groups_dir) { + if let Ok(entries) = std::fs::read_dir(GROUPS_DIR) { 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")) diff --git a/src/install.rs b/src/install.rs index 48c9c05..8a66118 100644 --- a/src/install.rs +++ b/src/install.rs @@ -2,14 +2,14 @@ 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 reqwest::blocking::Client; use sha2::{Sha256, Digest}; use walkdir::WalkDir; use chrono::Local; use std::collections::HashMap; -use std::os::unix::fs::symlink; +use std::os::unix::fs::{symlink, PermissionsExt}; +use tempfile::{NamedTempFile, tempdir}; use crate::config; use crate::progress::{Spinner, format_bytes}; use crate::debug; @@ -19,6 +19,47 @@ use pgp::composed::{Deserializable, SignedPublicKey, DetachedSignature}; const REPO_ROOT: &str = "/var/ror/packages"; +fn validate_symlink_target(target: &Path, dst: &Path, expected_root: &Path) -> Result<(), String> { + let candidate = if target.is_relative() { + let parent = dst.parent().unwrap_or(expected_root); + parent.join(target) + } else { + target.to_path_buf() + }; + + let mut normalized = PathBuf::new(); + for comp in candidate.components() { + match comp { + std::path::Component::Prefix(p) => normalized.push(p.as_os_str()), + std::path::Component::RootDir => normalized.push("/"), + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + normalized.pop(); + } + std::path::Component::Normal(c) => normalized.push(c), + } + } + + if target.is_relative() && !normalized.starts_with(expected_root) { + return Err(format!( + "Relative symlink escapes target root: {} -> {}", + dst.display(), + target.display() + )); + } + Ok(()) +} + +fn enforce_https(url: &str, context: &str) -> Result<(), String> { + if url.starts_with("http://") { + return Err(format!( + "Insecure HTTP URL rejected for {}: {}. Only HTTPS is allowed.", + context, url + )); + } + Ok(()) +} + #[derive(Debug, Clone, PartialEq)] pub enum VerOp { Ge, Gt, Le, Lt, Eq } @@ -95,10 +136,8 @@ 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, flatten)] + pub libc_depends: HashMap<String, Vec<Dependency>>, #[serde(default)] pub conflicts: Vec<String>, #[serde(default)] @@ -109,17 +148,17 @@ pub struct Package { 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()), + let libc_key = format!("{}.depends", libc); + let specific: Box<dyn Iterator<Item = &Dependency>> = match self.libc_depends.get(&libc_key) { + Some(deps) => Box::new(deps.iter()), + None => Box::new(std::iter::empty()), }; 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()) + .chain(self.libc_depends.values().flatten()) } } @@ -194,7 +233,11 @@ impl InstalledDB { if let Some(parent) = path.parent() { fs::create_dir_all(parent)?; } - fs::write(path, json) + let mut tmp = NamedTempFile::new_in(path.parent().unwrap_or(Path::new("/")))?; + tmp.write_all(json.as_bytes())?; + fs::set_permissions(tmp.path(), std::fs::Permissions::from_mode(0o644))?; + tmp.persist(path)?; + Ok(()) } pub fn add_package(&mut self, pkg: InstalledPackage) { @@ -238,6 +281,8 @@ fn sort_mirrors_by_speed(mirrors: &[String]) -> Vec<String> { 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 }); + enforce_https(url, "package download")?; + let client = Client::builder() .connect_timeout(std::time::Duration::from_secs(30)) .build() @@ -258,70 +303,64 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) .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; + let mut tmp_file = NamedTempFile::new() + .map_err(|e| format!("Failed to create temp file: {}", e))?; + let file_path = tmp_file.path().to_path_buf(); + + 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]); + tmp_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) + ); } - 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)); - } + _ => { + eprint!("\r\x1b[K{} downloaded", format_bytes(downloaded)); } - std::io::stderr().flush().ok(); } + 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"); + 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 { + debug!("SHA256 mismatch: expected {}, got {}", expected_sha, hash); + return Err(format!( + "SHA256 mismatch: expected {}, got {}", + expected_sha, hash + )); } + debug!("SHA256 verified successfully"); } + drop(tmp_file); Ok(file_path) } @@ -877,6 +916,9 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu } }; let key_file = gpg_key.unwrap(); + if key_file.contains("..") || key_file.contains('/') { + return Err(format!("Invalid GPG key path: {}", key_file)); + } 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) { @@ -889,8 +931,8 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu 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); + let shadow = tempdir().map_err(|e| format!("Failed to create temp dir: {}", e))?; + let work_dir = shadow.path().join(&pkg.name); fs::create_dir_all(&work_dir).map_err(|e| format!("Failed to create temp dir: {}", e))?; let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz"); @@ -932,7 +974,6 @@ pub fn install_package_with_result(pkg_name: &str, cfg: &config::Config) -> Resu sp2.finish(&format!("Installed {} files", all_installed_files.len())); debug!("Total installed files: {}", all_installed_files.len()); - let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(&archive_path); downloaded = true; break; @@ -1018,15 +1059,32 @@ fn strip_package_prefix(target_dir: &Path) -> Result<(), String> { if !prefix_dir.is_dir() { return Ok(()); } - let mut todo: Vec<(PathBuf, PathBuf)> = Vec::new(); + + let has_standard_subdir = fs::read_dir(&prefix_dir).ok().map(|rd| { + rd.flatten().any(|e| { + e.file_name().to_str().map(|n| STANDARD_DIRS.contains(&n)).unwrap_or(false) + }) + }).unwrap_or(false); + + if !has_standard_subdir { + return Ok(()); + } + + let mut todo_dirs = Vec::new(); + let mut todo_files = 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 = entry.path().strip_prefix(&prefix_dir).unwrap(); - let dst = target_dir.join(rel); - todo.push((entry.path().to_path_buf(), dst)); + let rel = entry.path().strip_prefix(&prefix_dir).unwrap(); + let dst = target_dir.join(rel); + if entry.file_type().is_dir() { + todo_dirs.push(dst); + } else if entry.file_type().is_file() || entry.file_type().is_symlink() { + todo_files.push((entry.path().to_path_buf(), dst)); } } - for (src, dst) in &todo { + for dir in todo_dirs { + let _ = fs::create_dir_all(&dir); + } + for (src, dst) in &todo_files { if let Some(parent) = dst.parent() { let _ = fs::create_dir_all(parent); } @@ -1119,6 +1177,7 @@ fn install_files(source_dir: &Path, prefix: &str, files: &[String]) -> Result<Ve if meta.is_symlink() { let target = fs::read_link(&src) .map_err(|e| format!("Failed to read link {}: {}", src.display(), e))?; + validate_symlink_target(&target, &dst, prefix_path)?; let _ = fs::remove_file(&dst); symlink(&target, &dst) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; @@ -1150,6 +1209,7 @@ pub fn install_files_to_root(source_dir: &Path, root: &Path, files: &[String]) - if meta.is_symlink() { let target = fs::read_link(&src) .map_err(|e| format!("Failed to read link {}: {}", src.display(), e))?; + validate_symlink_target(&target, &dst, root)?; let _ = fs::remove_file(&dst); symlink(&target, &dst) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; @@ -1167,47 +1227,19 @@ pub fn run_commands(steps: &str, work_dir: &Path) -> Result<(), String> { if steps.trim().is_empty() { return Ok(()); } - 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)) - } + + let status = std::process::Command::new("/bin/sh") + .arg("-e") + .arg("-c") + .arg(steps) + .current_dir(work_dir) + .status() + .map_err(|e| format!("Failed to execute install script: {}", e))?; + + if status.success() { + Ok(()) + } else { + Err(format!("Install script failed with exit status: {}", status)) } } @@ -1288,8 +1320,8 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con let version = "local".to_string(); debug!("Local package: name={}, version={}, extension={}", name, version, ext); - let work_dir = Path::new("/tmp/ror-local").join(&name); - let _ = fs::remove_dir_all(&work_dir); + let shadow = tempdir().map_err(|e| format!("Failed to create temp dir: {}", e))?; + let work_dir = shadow.path().join(&name); 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)); @@ -1316,8 +1348,6 @@ pub fn install_local_package_with_result(archive_path: &Path, _cfg: &config::Con spinner.finish(&format!("Installed {} files", installed_files.len())); debug!("Local installation complete, {} files", installed_files.len()); - let _ = fs::remove_dir_all(&work_dir); - Ok(InstalledPackage { name, version, diff --git a/src/main.rs b/src/main.rs index 4e326f0..c2725ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -230,10 +230,22 @@ async fn main() { let db = install::InstalledDB::load(); - for pkg_name in &packages { - if pkg_name.starts_with('@') { - continue; + let mut all_packages = Vec::new(); + for item in packages { + if let Some(group_name) = item.strip_prefix('@') { + match group::load_group(group_name) { + Ok(grp) => all_packages.extend(grp.packages), + Err(e) => { + eprintln!("{} Failed to load group '{}': {}", "[ror]".red().bold(), group_name, e); + return; + } + } + } else { + all_packages.push(item); } + } + + for pkg_name in &all_packages { let is_local = pkg_name.starts_with('/') || pkg_name.starts_with("./") || pkg_name.ends_with(".ror") @@ -247,62 +259,40 @@ async fn main() { } } - if packages[0].starts_with('@') { - - let group_name = &packages[0][1..]; - match group::load_group(group_name) { - Ok(group) => { - if let Err(e) = parallel::install_packages_parallel( - &group.packages, - Arc::clone(&cfg), - ) - .await - { - eprintln!("{} {}", "[ror]".red().bold(), e); - } - } - Err(e) => eprintln!("{} {}", "[ror]".red().bold(), e), - } - } else { - - let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = packages - .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, - ); - } + let (local_pkgs, remote_pkgs): (Vec<String>, Vec<String>) = all_packages + .into_iter() + .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, + ); + } - 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( - &remote_pkgs, - Arc::clone(&cfg), - ) - .await - { - eprintln!("{} {}", "[ror]".red().bold(), e); + 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( + &remote_pkgs, + Arc::clone(&cfg), + ) + .await + { + eprintln!("{} {}", "[ror]".red().bold(), e); } } } @@ -378,22 +368,29 @@ fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { inst_pkg ); - let del_pkg_c = del_pkg.clone(); - let inst_pkg_c = inst_pkg.clone(); - let cfg_c = Arc::clone(&cfg); - - let del_handle = std::thread::spawn(move || { - delete::remove_package_files_only(&del_pkg_c, &record_files) - }); + let installed_pkg = match install::install_package_with_result(&inst_pkg, &cfg) { + Ok(pkg) => pkg, + Err(e) => { + eprintln!( + "{} Failed to install '{}': {}. Old package remains intact.", + "[ror]".red().bold(), + inst_pkg, + e + ); + return; + } + }; - let inst_handle = std::thread::spawn(move || { - install::install_package_with_result(&inst_pkg_c, &cfg_c) - }); + let new_files: std::collections::HashSet<_> = installed_pkg.files.iter().collect(); + let obsolete_files: Vec<_> = record_files.into_iter() + .filter(|f| !new_files.contains(f)) + .collect(); - let del_ok = del_handle.join().unwrap_or(false); - let inst_result = inst_handle - .join() - .unwrap_or_else(|_| Err("panicked".to_string())); + let del_ok = if obsolete_files.is_empty() { + true + } else { + delete::remove_package_files_only(&del_pkg, &obsolete_files) + }; let mut db = install::InstalledDB::load(); @@ -401,19 +398,7 @@ fn run_di(del_pkg: String, inst_pkg: String, cfg: Arc<config::Config>) { 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 - ); - } - } + db.add_package(installed_pkg); if let Err(e) = db.save() { eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e); diff --git a/src/parallel.rs b/src/parallel.rs index ed4671f..a3a722b 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -1,8 +1,3 @@ -// parallel.rs -#![allow(dead_code)] -#![allow(unused_imports)] -#![allow(unused_variables)] - use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -11,7 +6,6 @@ use std::time::Duration; use std::io::Write; use colored::Colorize; -use futures::StreamExt; use sha2::{Digest, Sha256}; use tokio::sync::oneshot; use tokio::task; @@ -60,12 +54,12 @@ impl InstalledDB { } struct AtomicInstaller { - shadow: tempfile::TempDir, + _shadow: tempfile::TempDir, } impl AtomicInstaller { fn new(shadow: tempfile::TempDir) -> Self { - Self { shadow } + Self { _shadow: shadow } } fn commit( @@ -90,8 +84,21 @@ impl AtomicInstaller { std::fs::create_dir_all(parent) .map_err(|e| format!("Create parent {}: {}", parent.display(), e))?; - let bak_path = dst.with_extension("ror-old"); if dst.exists() && dst.is_file() { + let mut bak_num = 0u32; + let bak_path = loop { + let mut p = dst.as_os_str().to_os_string(); + if bak_num == 0 { + p.push(".ror-old"); + } else { + p.push(format!(".ror-old.{}", bak_num)); + } + let p = PathBuf::from(p); + if !p.exists() { + break p; + } + bak_num += 1; + }; if let Err(e) = std::fs::rename(&dst, &bak_path) { return Err(format!("Cannot backup {}: {}", dst.display(), e)); } @@ -100,19 +107,14 @@ impl AtomicInstaller { 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); - } + Self::rollback(&backup_paths); 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); - } + Self::rollback(&backup_paths); return Err(format!("Failed to install {}: {}", dst.display(), e)); } } @@ -128,9 +130,21 @@ impl AtomicInstaller { Ok(installed) } + + fn rollback(backup_paths: &[(PathBuf, PathBuf)]) { + for (bak, orig) in backup_paths { + if bak.exists() { + let _ = std::fs::rename(bak, orig); + } + } + } } async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<PathBuf, String> { + if url.starts_with("http://") { + return Err(format!("Insecure HTTP URL rejected: {}. Only HTTPS allowed.", url)); + } + let result = timeout(Duration::from_secs(60), async { let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) @@ -147,24 +161,17 @@ async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<Pa return Err(format!("HTTP {} for {}", res.status(), url)); } - 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.rsplit('/').next().unwrap_or("archive.tmp"); - let file_path = tmp_dir.join(file_name); - - let mut file = std::fs::File::create(&file_path).map_err(|e| e.to_string())?; + let mut tmp_file = NamedTempFile::new().map_err(|e| e.to_string())?; + let file_path = tmp_file.path().to_path_buf(); let mut hasher = Sha256::new(); let body = res.bytes().await.map_err(|e| e.to_string())?; hasher.update(&body); - file.write_all(&body).map_err(|e| e.to_string())?; - - drop(file); + tmp_file.write_all(&body).map_err(|e| e.to_string())?; 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 @@ -172,6 +179,7 @@ async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<Pa } } + drop(tmp_file); Ok(file_path) }) .await diff --git a/src/progress.rs b/src/progress.rs index bd9c806..ec97b79 100755 --- a/src/progress.rs +++ b/src/progress.rs @@ -1,4 +1,3 @@ -// src/progress.rs use std::io::{self, Write}; pub struct ProgressBar { diff --git a/src/repo.rs b/src/repo.rs index a6d4b41..34cbbd6 100755 --- a/src/repo.rs +++ b/src/repo.rs @@ -1,45 +1,78 @@ use colored::Colorize; -use std::io::{self, Write}; +use std::io::{self, Write, IsTerminal}; use crate::config::{Config, RepositoryConfig}; +fn is_interactive() -> bool { + io::stdin().is_terminal() && io::stdout().is_terminal() +} + pub fn add_repository(name: &str, url: &str, mirror: Option<&str>) -> Result<(), String> { let mut cfg = Config::load(); 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 url.starts_with("http://") { + return Err(format!( + "Insecure HTTP URL rejected for repository '{}': {}. Only HTTPS is allowed.", + name, url + )); + } + if let Some(m) = mirror { + if m.starts_with("http://") { + return Err(format!( + "Insecure HTTP mirror URL rejected for repository '{}': {}. Only HTTPS is allowed.", + name, m + )); + } + } - if !gpg_support { + let gpg_support = if is_interactive() { print!( - "{} Repository '{}' will have GPG disabled. It may be unsafe. Continue? [y/N]: ", - "[ror]".yellow().bold(), + "{} Enable GPG verification for '{}'? [Y/n]: ", + "[ror]".blue().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 mut answer = String::new(); + io::stdin().read_line(&mut answer).ok(); + let gpg = !answer.trim().eq_ignore_ascii_case("n"); + + if !gpg { + 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(()); + } } - } + gpg + } else { + eprintln!( + "{} Non-interactive mode: GPG enabled by default for '{}'", + "[ror]".yellow(), + name + ); + true + }; 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) } + if is_interactive() { + 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 + } } else { None }; diff --git a/src/resolver.rs b/src/resolver.rs index 1141980..72ddf92 100755 --- a/src/resolver.rs +++ b/src/resolver.rs @@ -21,18 +21,13 @@ impl DependencyGraph { pub fn compute_levels(&self) -> Vec<Vec<String>> { let mut in_degree: HashMap<String, usize> = HashMap::new(); - for (pkg, deps) in &self.edges { + for pkg in self.edges.keys().chain(self.reverse.keys()) { in_degree.entry(pkg.clone()).or_insert(0); - for dep in deps { - *in_degree.entry(dep.clone()).or_insert(0) += 1; - } } - for (pkg, children) in &self.reverse { - in_degree.entry(pkg.clone()).or_insert(0); - for child in children { - in_degree.entry(child.clone()).or_insert(0); - } + for (pkg, deps) in &self.edges { + in_degree.insert(pkg.clone(), deps.len()); } + let mut levels = Vec::new(); let mut queue: VecDeque<String> = in_degree.iter() .filter(|&(_, °)| deg == 0) @@ -43,12 +38,14 @@ impl DependencyGraph { let level_pkgs: Vec<String> = queue.drain(..).collect(); levels.push(level_pkgs.clone()); for pkg in &level_pkgs { - if let Some(children) = self.reverse.get(pkg) { - for child in children { - if let Some(deg) = in_degree.get_mut(child) { - *deg -= 1; - if *deg == 0 { - queue.push_back(child.clone()); + if let Some(dependents) = self.reverse.get(pkg) { + for dep in dependents { + if let Some(deg) = in_degree.get_mut(dep) { + if *deg > 0 { + *deg -= 1; + if *deg == 0 { + queue.push_back(dep.clone()); + } } } } @@ -56,15 +53,17 @@ impl DependencyGraph { } } - let cyclic: Vec<_> = in_degree.iter() + let cyclic: Vec<String> = in_degree.iter() .filter(|&(_, &d)| d > 0) - .map(|(name, _)| name.as_str()) + .map(|(name, _)| name.clone()) .collect(); if !cyclic.is_empty() { eprintln!( - "{} Warning: cycle detected among packages, they will be installed in arbitrary order", - "[ror]".yellow().bold() + "{} Warning: cycle detected among packages, installing them together: {}", + "[ror]".yellow().bold(), + cyclic.join(", ") ); + levels.push(cyclic); } levels } @@ -272,3 +271,56 @@ pub fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) - Ok(()) } +pub fn find_installed_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) -> Vec<(String, String)> { + let mut conflicts = Vec::new(); + for pkg_name in required { + if let Some(pkg) = load_package(pkg_name) { + for conflict in &pkg.conflicts { + if installed_db.is_installed(conflict) { + conflicts.push((pkg_name.clone(), conflict.clone())); + } + } + } + } + conflicts +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_compute_levels_ordering() { + let mut graph = DependencyGraph::new(); + // A depends on B, B depends on C + graph.add_dep("A".into(), "B".into()); + graph.add_dep("B".into(), "C".into()); + // D has no deps + graph.edges.entry("D".into()).or_default(); + + let levels = graph.compute_levels(); + + // C and D must be installed first (level 0) + assert_eq!(levels.len(), 3); + assert!(levels[0].contains(&"C".to_string())); + assert!(levels[0].contains(&"D".to_string())); + // B must be installed second (level 1) + assert_eq!(levels[1], vec!["B".to_string()]); + // A must be installed third (level 2) + assert_eq!(levels[2], vec!["A".to_string()]); + } + + #[test] + fn test_cycle_does_not_drop_packages() { + let mut graph = DependencyGraph::new(); + // A depends on B, B depends on A + graph.add_dep("A".into(), "B".into()); + graph.add_dep("B".into(), "A".into()); + + let levels = graph.compute_levels(); + let flattened: Vec<_> = levels.into_iter().flatten().collect(); + assert!(flattened.contains(&"A".to_string())); + assert!(flattened.contains(&"B".to_string())); + } +} + diff --git a/src/rootfs.rs b/src/rootfs.rs index e31444d..65208a0 100755 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,4 +1,3 @@ -// src/rootfs.rs use std::collections::HashMap; use std::fs; use std::path::Path; @@ -83,8 +82,8 @@ fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &st 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()); + //prefer local package files when available + let workspace = std::env::var("ROR_WORKSPACE").unwrap_or_else(|_| "/var/ror/cache".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())] @@ -128,11 +127,8 @@ fn download_file_quiet( 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); + use std::io::Write; + use tempfile::NamedTempFile; if let Some(local) = url.strip_prefix("file://") { let src = Path::new(local); @@ -141,14 +137,22 @@ fn download_file_quiet( } 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 mut tmp_file = NamedTempFile::new().map_err(|e| e.to_string())?; + let file_path = tmp_file.path().to_path_buf(); + let mut src_file = std::fs::File::open(src).map_err(|e| e.to_string())?; + let mut buf = [0u8; 65536]; + loop { + let n = src_file.read(&mut buf).map_err(|e| e.to_string())?; + if n == 0 { break; } + tmp_file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + } let dict_src = src.with_extension("dict"); if dict_src.exists() { - let dict_dst = file_path.with_extension("dict"); + let dict_dst = tmp_file.path().with_extension("dict"); let _ = std::fs::copy(&dict_src, &dict_dst); } bytes_done_global.fetch_add(size, Ordering::Relaxed); + drop(tmp_file); return Ok((file_path, size)); } @@ -173,7 +177,8 @@ fn download_file_quiet( 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 tmp_file = NamedTempFile::new().map_err(|e| e.to_string())?; + let file_path = tmp_file.path().to_path_buf(); let mut hasher = Sha256::new(); let mut buf = [0u8; 65536]; let mut downloaded: u64 = 0; @@ -183,7 +188,7 @@ fn download_file_quiet( 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())?; + tmp_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); } @@ -191,11 +196,11 @@ fn download_file_quiet( 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)); } } + drop(tmp_file); Ok((file_path, downloaded)) } @@ -341,13 +346,8 @@ fn install_from_archive( root_dir: &Path, pkg_type: &str, ) -> Result<Vec<String>, String> { - let work_dir = std::path::Path::new("/tmp/ror-rootfs").join(pkg_name); - if work_dir.exists() { - fs::remove_dir_all(&work_dir) - .map_err(|e| format!("Failed to clean temp dir for '{}': {}", pkg_name, e))?; - } - fs::create_dir_all(&work_dir) - .map_err(|e| format!("Failed to create temp dir for '{}': {}", pkg_name, e))?; + let shadow = tempfile::tempdir().map_err(|e| format!("Failed to create temp dir: {}", e))?; + let work_dir = shadow.path().join(pkg_name); let extracted = if pkg_type == "ror" { extract_ror(archive_path, &work_dir) @@ -365,7 +365,6 @@ fn install_from_archive( let installed = install_files_to_root(&work_dir, root_dir, &extracted)?; - let _ = fs::remove_dir_all(&work_dir); let _ = fs::remove_file(archive_path); Ok(installed) @@ -586,7 +585,13 @@ fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static 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, &[]); + let env_c = [ + CString::new("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin").unwrap(), + CString::new("HOME=/root").unwrap(), + CString::new("TERM=xterm").unwrap(), + ]; + let env_refs: Vec<&CStr> = env_c.iter().map(|s| s.as_c_str()).collect(); + let _ = execve::<&CStr, &CStr>(&shell_c, &args_refs, &env_refs); std::process::exit(1); } Ok(ForkResult::Parent { child }) => { @@ -634,7 +639,15 @@ fn run_install_steps_in_chroot( } else { vec![arg0, script_c] }; - let _ = execve::<&CStr, &CStr>(&shell_c, &args.iter().map(|s| s.as_ref()).collect::<Vec<_>>(), &[]); + let args_refs: Vec<&CStr> = args.iter().map(|s| s.as_c_str()).collect(); + let env_c = [ + CString::new("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin").unwrap(), + CString::new("HOME=/root").unwrap(), + CString::new("TERM=xterm").unwrap(), + CString::new("USER=root").unwrap(), + ]; + let env_refs: Vec<&CStr> = env_c.iter().map(|s| s.as_c_str()).collect(); + let _ = execve::<&CStr, &CStr>(&shell_c, &args_refs, &env_refs); std::process::exit(1); } Ok(ForkResult::Parent { child }) => { @@ -665,13 +678,25 @@ fn run_install_steps_in_chroot( } fn run_ldconfig_in_root(root_dir: &Path) -> Result<(), String> { + let ldconfig_path = if root_dir.join("sbin/ldconfig").exists() { + "/sbin/ldconfig" + } else if root_dir.join("usr/sbin/ldconfig").exists() { + "/usr/sbin/ldconfig" + } else { + return Ok(()); + }; + 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 ldconfig = CString::new(ldconfig_path).unwrap(); let arg0 = CString::new("ldconfig").unwrap(); - let _ = execve::<&CString, &CStr>(&ldconfig, &[&arg0], &[]); + let env_c = [ + CString::new("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin").unwrap(), + ]; + let env_refs: Vec<&CStr> = env_c.iter().map(|s| s.as_c_str()).collect(); + let _ = execve::<&CStr, &CStr>(&ldconfig, &[&arg0], &env_refs); std::process::exit(1); } Ok(ForkResult::Parent { child }) => { diff --git a/src/sync.rs b/src/sync.rs index ad36aea..2d1b6b7 100755 --- a/src/sync.rs +++ b/src/sync.rs @@ -1,21 +1,75 @@ use colored::*; -use std::path::{Path}; -use git2::{Repository, RemoteCallbacks, FetchOptions, build::RepoBuilder}; +use std::path::Path; +use std::process::Command; use crate::config::Config; const REPOS_DIR: &str = "/var/ror/packages"; +fn enforce_repo_https(url: &str) -> Result<(), String> { + if url.starts_with("http://") { + return Err(format!( + "Insecure HTTP URL rejected: {}. Only HTTPS is allowed for repositories.", + url + )); + } + Ok(()) +} + +fn check_repo_permissions() { + let repo_path = Path::new(REPOS_DIR); + if !repo_path.exists() { + return; + } + match std::fs::metadata(repo_path) { + Ok(meta) => { + use std::os::unix::fs::MetadataExt; + let uid = meta.uid(); + if uid != 0 { + eprintln!( + "{} WARNING: Repository directory '{}' is owned by UID {} (not root). \ + This is a security risk — any user can modify packages.", + "[ror]".yellow().bold(), + REPOS_DIR, + uid + ); + } + let mode = meta.mode() & 0o7777; + if mode & 0o002 != 0 { + eprintln!( + "{} WARNING: Repository directory '{}' is world-writable (mode {:o}). \ + This is a security risk — any user can inject malicious packages.", + "[ror]".yellow().bold(), + REPOS_DIR, + mode + ); + } + } + Err(_) => {} + } +} + pub fn run_sync(cfg: &Config) { if cfg.repositories.is_empty() { eprintln!("{} No repositories configured.", "[ror]".red().bold()); return; } + check_repo_permissions(); for (name, repo) in &cfg.repositories { + if let Err(e) = enforce_repo_https(&repo.url) { + eprintln!("{} {}: {}", "[ror]".red().bold(), name, e); + continue; + } + if let Some(ref mirror) = repo.mirror { + if let Err(e) = enforce_repo_https(mirror) { + eprintln!("{} {}: {}", "[ror]".red().bold(), name, e); + continue; + } + } println!("{} Syncing repository '{}'...", "[ror]".blue().bold(), name); let repo_path = Path::new(REPOS_DIR).join(name); if repo_path.exists() { println!("{} Updating {}...", ">>>".green(), name); - if let Err(e) = pull_or_clone(&repo_path, &repo.url) { + if let Err(e) = pull_repo(&repo_path, repo.mirror.as_deref()) { eprintln!("{} {}", "[ror]".red(), e); } else { println!("{} Repository updated.", ">>>".green()); @@ -33,66 +87,57 @@ pub fn run_sync(cfg: &Config) { 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())); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("Failed to create repos dir: {}", e))?; + } + + let status = Command::new("git") + .args(["clone", primary, path.to_str().unwrap()]) + .status() + .map_err(|e| format!("Failed to run git: {}", e))?; + + if status.success() { + return Ok(()); + } + + if let Some(mirror_url) = mirror { + eprintln!("{} Primary clone failed, trying mirror...", "[ror]".yellow()); + let mirror_status = Command::new("git") + .args(["clone", mirror_url, path.to_str().unwrap()]) + .status() + .map_err(|e| format!("Failed to run git clone for mirror: {}", e))?; + + if mirror_status.success() { + return Ok(()); } } - Ok(()) + + Err(format!("Failed to clone repository '{}'", name)) } -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(); - } +fn pull_repo(repo_path: &Path, mirror: Option<&str>) -> Result<(), String> { + let path_str = repo_path.to_str().ok_or("Invalid repo path")?; + let status = Command::new("git") + .args(["-C", path_str, "pull"]) + .status() + .map_err(|e| format!("Failed to run git pull: {}", e))?; + + if status.success() { + return Ok(()); + } + + if let Some(mirror_url) = mirror { + eprintln!("{} Pull from primary failed, trying mirror...", "[ror]".yellow()); + let mirror_status = Command::new("git") + .args(["-C", path_str, "pull", mirror_url]) + .status() + .map_err(|e| format!("Failed to run git pull from mirror: {}", e))?; + + if mirror_status.success() { + return Ok(()); } - 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(()) + + Err(format!("Failed to pull repository at '{}'", path_str)) } diff --git a/src/update.rs b/src/update.rs index 1cceccc..62be1b5 100755 --- a/src/update.rs +++ b/src/update.rs @@ -83,9 +83,36 @@ pub fn update_package(pkg_name: &str, cfg: &config::Config, dry_run: bool) -> bo return true; } - delete::remove_package(pkg_name); - install::install_package(pkg_name, cfg); - true + let old_files = db.packages.get(pkg_name).map(|r| r.files.clone()).unwrap_or_default(); + + match install::install_package_with_result(pkg_name, cfg) { + Ok(new_pkg) => { + let new_files: std::collections::HashSet<_> = new_pkg.files.iter().collect(); + let obsolete_files: Vec<_> = old_files.into_iter() + .filter(|f| !new_files.contains(f)) + .collect(); + let mut db = InstalledDB::load(); + db.packages.remove(pkg_name); + db.add_package(new_pkg); + if let Err(e) = db.save() { + eprintln!("{} Failed to save DB: {}", "[ror]".red().bold(), e); + } + if !obsolete_files.is_empty() { + delete::remove_package_files_only(pkg_name, &obsolete_files); + } + println!("{} '{}' updated successfully.", "[ror]".green().bold(), pkg_name); + true + } + Err(e) => { + eprintln!( + "{} Failed to install new version of '{}': {}. Old version remains intact.", + "[ror]".red().bold(), + pkg_name, + e + ); + false + } + } } #[allow(dead_code)] |