summaryrefslogtreecommitdiff
path: root/src/install.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/install.rs')
-rw-r--r--src/install.rs276
1 files changed, 153 insertions, 123 deletions
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,