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