diff options
| author | Ivan Vasilchenko <qvkapp@gmail.com> | 2026-11-19 22:14:55 +0300 |
|---|---|---|
| committer | Ivan Vasilchenko <qvkapp@gmail.com> | 2026-11-19 22:14:55 +0300 |
| commit | 283afa1922f87e5e97c4bec2c019b3add71e375a (patch) | |
| tree | d6d8a9defcf3450f0200ff13f83ad99aea246287 /src | |
| parent | 78828df65dfc90d30e82490b290db04ebf2c6f30 (diff) | |
| download | ror-283afa1922f87e5e97c4bec2c019b3add71e375a.tar.gz ror-283afa1922f87e5e97c4bec2c019b3add71e375a.zip | |
Diffstat (limited to 'src')
| -rw-r--r-- | src/apply.rs | 7 | ||||
| -rw-r--r-- | src/config.rs | 69 | ||||
| -rw-r--r-- | src/group.rs | 1 | ||||
| -rw-r--r-- | src/install.rs | 31 | ||||
| -rw-r--r-- | src/main.rs | 103 | ||||
| -rw-r--r-- | src/parallel.rs | 81 | ||||
| -rw-r--r-- | src/progress.rs | 116 | ||||
| -rw-r--r-- | src/rootfs.rs | 531 |
8 files changed, 303 insertions, 636 deletions
diff --git a/src/apply.rs b/src/apply.rs index dd5268d..5494773 100644 --- a/src/apply.rs +++ b/src/apply.rs @@ -106,12 +106,7 @@ pub fn get_target_packages(sys_config: &SystemConfig, _cfg: &Config) -> Result<V let group = group::load_group(group_name) .map_err(|e| format!("Failed to load group '{}': {}", group_name, e))?; if let Some(ref libc_pkg) = group.libc { - let libc_name = match libc_pkg.as_str() { - "musl" => "musl", - "glibc" => "glibc", - other => other, - }; - target.insert(libc_name.to_string()); + target.insert(libc_pkg.clone()); } for pkg in group.packages { target.insert(pkg); diff --git a/src/config.rs b/src/config.rs index e4ffdaf..e9d1c95 100644 --- a/src/config.rs +++ b/src/config.rs @@ -54,8 +54,26 @@ impl Default for GlobalConfig { fn default_ignore_speed() -> bool { false } fn default_strict_gpg() -> bool { false } fn default_parallel_downloads() -> usize { 4 } -fn default_arch() -> String { std::env::consts::ARCH.to_string() } -fn default_libc() -> String { "glibc".to_string() } + +pub fn detect_arch() -> String { + std::env::consts::ARCH.to_string() +} + +pub fn detect_libc() -> String { + if cfg!(target_env = "musl") { + "musl".to_string() + } else { + "glibc".to_string() + } +} + +fn default_arch() -> String { + detect_arch() +} + +fn default_libc() -> String { + detect_libc() +} #[derive(Debug, Deserialize, Serialize, Clone, Default)] pub struct SystemProfile { @@ -167,29 +185,17 @@ impl Config { pub fn to_ini(&self) -> Result<String, config::ConfigError> { let mut lines = vec!["[global]".to_string()]; - lines.push(format!("ignore_speed = {}", self.global.ignore_speed)); - lines.push(format!("strict_gpg = {}", self.global.strict_gpg)); lines.push(format!("parallel_downloads = {}", self.global.parallel_downloads)); - lines.push(format!("arch = {}", self.global.arch)); - lines.push(format!("libc = {}", self.global.libc)); - lines.push(String::new()); - - let p = &self.profile; - let has_profile = p.init_system.is_some() || p.libc.is_some() - || p.core_utils.is_some() || !p.sh.is_empty() - || !p.su.is_empty() || p.udev.is_some() || p.active_group.is_some(); - - if has_profile { - lines.push("[profile]".to_string()); - if let Some(v) = &p.active_group { lines.push(format!("active-group = {}", v)); } - if let Some(v) = &p.init_system { lines.push(format!("init-system = {}", v)); } - if let Some(v) = &p.libc { lines.push(format!("libc = {}", v)); } - if let Some(v) = &p.core_utils { lines.push(format!("core-utils = {}", v)); } - if !p.sh.is_empty() { lines.push(format!("sh = {}", p.sh.join(","))); } - if !p.su.is_empty() { lines.push(format!("su = {}", p.su.join(","))); } - if let Some(v) = &p.udev { lines.push(format!("udev = {}", v)); } - lines.push(String::new()); + if self.global.strict_gpg { + lines.push(format!("strict_gpg = {}", self.global.strict_gpg)); + } + if self.global.allow_external_binaries { + lines.push(format!("allow_external_binaries = {}", self.global.allow_external_binaries)); } + if self.global.ignore_speed { + lines.push(format!("ignore_speed = {}", self.global.ignore_speed)); + } + lines.push(String::new()); for (name, repo) in &self.repositories { lines.push(format!("[repositories.{}]", name)); @@ -200,7 +206,9 @@ impl Config { if let Some(m) = &repo.mirror { lines.push(format!("mirror = \"{}\"", m)); } - lines.push(format!("gpg_support = {}", repo.gpg_support)); + if repo.gpg_support { + lines.push(format!("gpg_support = {}", repo.gpg_support)); + } if let Some(k) = &repo.gpg_key { lines.push(format!("gpg_key = \"{}\"", k)); } @@ -219,20 +227,17 @@ impl Config { pub fn create_default_config(path: &Path) -> std::io::Result<()> { let ini = concat!( "[global]\n", - "ignore_speed = true\n", - "strict_gpg = false\n", - "allow_external_binaries = true\n", "parallel_downloads = 4\n", - "arch = x86_64\n", - "libc = glibc\n\n", + "strict_gpg = false\n\n", "[repositories.rorkos]\n", - "url = \"https://rorkos.duckdns.org/pkg/\"\n", + "url = \"https://codeberg.org/RorkOS/packages.git\"\n", "urlrepo = \"https://rorkos.duckdns.org/pkg/\"\n", - "mirror = \"https://rorkos.duckdns.org/pkg/\"\n", "gpg_support = false\n", ); - fs::create_dir_all(path.parent().unwrap())?; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } 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))?; diff --git a/src/group.rs b/src/group.rs index bc34a68..6623b40 100644 --- a/src/group.rs +++ b/src/group.rs @@ -16,6 +16,7 @@ pub struct Group { pub version: Option<String>, pub packages: Vec<String>, #[serde(default)] + #[allow(dead_code)] pub install_steps: String, #[serde(rename = "init-system")] diff --git a/src/install.rs b/src/install.rs index e58735e..fae66fc 100644 --- a/src/install.rs +++ b/src/install.rs @@ -11,7 +11,7 @@ use std::collections::HashMap; use std::os::unix::fs::{symlink, PermissionsExt}; use tempfile::{NamedTempFile, tempdir}; use crate::config; -use crate::progress::{Spinner, format_bytes}; +use crate::progress::{Spinner, DownloadBar}; use crate::debug; use tar::Archive as TarArchive; use zstd::stream::read::Decoder as ZstdDecoder; @@ -301,6 +301,9 @@ 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 filename = url.rsplit('/').next().unwrap_or(url); + let mut bar = DownloadBar::new(filename, total_size); + 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(); @@ -308,7 +311,6 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) let mut hasher = Sha256::new(); let mut reader = response; let mut buf = [0u8; 65536]; - let mut downloaded: u64 = 0; loop { let n = reader @@ -320,31 +322,10 @@ pub fn download_and_verify(url: &str, expected_sha: &str, _cfg: &config::Config) 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) - ); - } - _ => { - eprint!("\r\x1b[K{} downloaded", format_bytes(downloaded)); - } - } - std::io::stderr().flush().ok(); + bar.update(n as u64); } - eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", format_bytes(downloaded)); + bar.finish(); if !expected_sha.is_empty() { let hash = format!("{:x}", hasher.finalize()); diff --git a/src/main.rs b/src/main.rs index c2725ee..447c93a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,4 @@ -use clap::{Parser, Subcommand}; +use clap::{CommandFactory, Parser, Subcommand}; use std::sync::Arc; use colored::Colorize; use std::path::{Path, PathBuf}; @@ -22,7 +22,12 @@ mod apply; mod resolver; #[derive(Parser)] -#[command(name = "ror", about = "Ror package manager")] +#[command( + name = "ror", + about = "ror package manager", + version = concat!(env!("CARGO_PKG_VERSION"), " MPL 2"), + disable_help_subcommand = true +)] struct Cli { #[command(subcommand)] command: Commands, @@ -30,86 +35,127 @@ struct Cli { #[derive(Subcommand)] enum Commands { - + /// install one or more packages or groups #[command(alias = "i")] Install { + /// package names or @group specifications to install #[arg(required = true)] packages: Vec<String>, }, - + + /// list available package groups #[command(alias = "lg")] ListGroups, - + + /// synchronize repository package recipes from remote #[command(alias = "s")] Sync, - + + /// remove an installed package #[command(alias = "d")] Delete { + /// name of the package to remove package: String, }, - + + /// list all installed packages #[command(alias = "l")] ListInstalled, + /// print the total count of installed packages #[command(alias = "c")] Count, - + + /// display detailed information about a package Info { + /// name of the package package: String, }, - + + /// update a specific package to the latest available version Update { + /// name of the package to update package: String, + /// check for update without making modifications #[arg(long)] dry_run: bool, }, - + + /// upgrade all installed packages to their latest versions #[command(alias = "u")] Upgrade, - + + /// search for packages by query in repositories Search { + /// search query string query: String, }, - + + /// add a new package repository RepoAdd { + /// repository name name: String, + /// repository recipe git url url: String, + /// optional binary package mirror url mirror: Option<String>, }, - + + /// remove a configured package repository RepoRemove { + /// name of the repository to remove name: String, }, - + + /// list all configured package repositories RepoList, - + + /// build a rootfs environment from a package group BuildRootfs { + /// package group name to build #[arg(long)] group: String, + /// target directory path for rootfs #[arg(long)] target: PathBuf, + /// target architecture (default: native) #[arg(long, default_value = "native")] arch: String, }, - + + /// atomically replace one package with another Di { + /// package to delete delete: String, + /// package to install install: String, }, - + + /// apply declarative system configuration state #[command(alias = "a")] Apply { + /// show changes without applying them #[arg(long)] dry_run: bool, + /// custom system.yaml configuration file path #[arg(long)] config: Option<PathBuf>, }, - + + /// check integrity of installed packages Check, - + + /// generate default configuration file at /etc/ror/ror.conf GenConfig, - + + /// display ror version information Version, + + /// print this message or the help of the given subcommand + Help { + /// name of the subcommand + subcommand: Option<String>, + }, } #[tokio::main] @@ -117,8 +163,22 @@ async fn main() { let cli = Cli::parse(); match cli.command { + Commands::Help { subcommand } => { + let mut cmd = Cli::command(); + if let Some(sub) = subcommand { + if let Some(subcmd) = cmd.find_subcommand_mut(&sub) { + let _ = subcmd.print_help(); + } else { + let _ = cmd.print_help(); + } + } else { + let _ = cmd.print_help(); + } + println!(); + } + Commands::Version => { - println!("ror {}", env!("CARGO_PKG_VERSION")); + println!("ror {} MPL 2", env!("CARGO_PKG_VERSION")); } Commands::GenConfig => { @@ -202,7 +262,6 @@ async fn main() { &target, &cfg, arch, - true, ) { eprintln!("{} {}", "[ror]".red().bold(), e); } diff --git a/src/parallel.rs b/src/parallel.rs index aacd9c3..93958e6 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -140,18 +140,23 @@ impl AtomicInstaller { } } -async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<PathBuf, String> { +async fn download_one( + url: &str, + expected_sha: &str, + pkg_name: Option<&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 result = timeout(Duration::from_secs(120), async { let client = reqwest::Client::builder() - .timeout(Duration::from_secs(30)) + .timeout(Duration::from_secs(60)) .build() .map_err(|e| format!("HTTP client builder: {}", e))?; - let res = client + let mut res = client .get(url) .send() .await @@ -161,13 +166,23 @@ async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<Pa return Err(format!("HTTP {} for {}", res.status(), url)); } + let total_size = res.content_length(); + let mut bar = pkg_name.map(|name| crate::progress::DownloadBar::new(name, total_size)); + 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); - tmp_file.write_all(&body).map_err(|e| e.to_string())?; + while let Some(chunk) = res.chunk().await.map_err(|e| e.to_string())? { + hasher.update(&chunk); + tmp_file.write_all(&chunk).map_err(|e| e.to_string())?; + if let Some(b) = &mut bar { + b.update(chunk.len() as u64); + } + } + + if let Some(b) = &bar { + b.finish(); + } if !expected_sha.is_empty() { let hash = format!("{:x}", hasher.finalize()); @@ -191,10 +206,11 @@ async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<Pa async fn race_download( urls: Vec<String>, expected_sha: &str, + pkg_name: &str, cfg: Arc<Config>, ) -> Result<(PathBuf, String), String> { if urls.len() == 1 { - let p = download_one(&urls[0], expected_sha, &cfg).await?; + let p = download_one(&urls[0], expected_sha, Some(pkg_name), &cfg).await?; return Ok((p, urls[0].clone())); } @@ -206,9 +222,10 @@ async fn race_download( let tx_clone = Arc::clone(&tx); let cfg_clone = cfg.clone(); let sha = expected_sha.to_string(); + let name = pkg_name.to_string(); handles.push(task::spawn(async move { - match download_one(&url, &sha, &cfg_clone).await { + match download_one(&url, &sha, Some(&name), &cfg_clone).await { Ok(path) => { let mut guard = tx_clone.lock().unwrap(); if let Some(sender) = guard.take() { @@ -236,7 +253,7 @@ async fn install_single_impl( variant: Option<&str>, cfg: Arc<Config>, ) -> Result<InstalledPackage, String> { - println!("[{}] Resolving {}...", "[ror]".cyan().bold(), pkg_name); + println!("{} Resolving {}...", "[ror]".cyan().bold(), pkg_name); let start_time = std::time::Instant::now(); @@ -279,18 +296,17 @@ async fn install_single_impl( )); } - println!("[{}] Downloading {}...", "[ror]".blue(), pkg_name); let (archive_path, winning_url) = - race_download(urls, &binary.sha256, cfg.clone()).await?; + race_download(urls, &binary.sha256, pkg_name, cfg.clone()).await?; if repo_cfg.map(|r| r.gpg_support).unwrap_or(false) { if let Some(key_file) = repo_cfg.and_then(|r| r.gpg_key.as_deref()) { let asc_url = format!("{}.asc", winning_url); - println!("[{}] Verifying GPG...", "[ror]".cyan()); + println!("{} Verifying GPG...", "[ror]".cyan().bold()); let asc_path = match timeout( Duration::from_secs(30), - download_one(&asc_url, "", &cfg), + download_one(&asc_url, "", None, &cfg), ) .await { @@ -318,7 +334,7 @@ async fn install_single_impl( } } - println!("[{}] Extracting {}...", "[ror]".green(), pkg_name); + println!("{} Extracting {}...", "[ror]".green().bold(), pkg_name); let shadow = tempfile::tempdir().map_err(|e| e.to_string())?; let work_dir = shadow.path().join("root"); std::fs::create_dir_all(&work_dir).map_err(|e| e.to_string())?; @@ -336,7 +352,7 @@ async fn install_single_impl( } }; - println!("{} Installing {}...", "[ror]".blue().bold(), pkg_name); + println!("{} Installing {}...", "[ror]".blue().bold(), pkg_name); let installer = AtomicInstaller::new(shadow); let installed_files = @@ -345,7 +361,7 @@ async fn install_single_impl( let _ = std::fs::remove_file(&archive_path); let elapsed = start_time.elapsed().as_millis(); - println!("[>] Installed {} ({:.2}ms)", pkg_name, elapsed as f64); + println!("{} Installed {} ({:.2}ms)", "[ror]".green().bold(), pkg_name, elapsed as f64); install_services(&pkg); @@ -362,7 +378,7 @@ pub async fn install_packages_parallel( packages: &[String], cfg: Arc<Config>, ) -> Result<(), String> { - println!("[>] Starting package synchronization..."); + println!("{} Starting package installation...", "[ror]".blue().bold()); let ctrl_c_handle = tokio::spawn(async { tokio::signal::ctrl_c().await.ok(); @@ -388,7 +404,7 @@ pub async fn install_packages_parallel( resolver::collect_required_packages(&pure_packages, &installed_db, &mut outdated, libc)?; if required.is_empty() { - println!("[>] Nothing to install."); + println!("{} Nothing to install.", "[ror]".green().bold()); ctrl_c_handle.abort(); return Ok(()); } @@ -401,16 +417,19 @@ pub async fn install_packages_parallel( for (level_idx, level_pkgs) in levels.iter().enumerate() { if INTERRUPTED.load(Ordering::SeqCst) { - println!("[!] Interrupted by user."); + println!("{} Interrupted by user.", "[ror]".yellow().bold()); ctrl_c_handle.abort(); return Err("Installation aborted".to_string()); } - println!( - "[>] Level {} installing {} packages...", - level_idx, - level_pkgs.len() - ); + if levels.len() > 1 { + println!( + "{} Level {} installing {} package(s)...", + "[ror]".blue().bold(), + level_idx + 1, + level_pkgs.len() + ); + } let mut tasks = Vec::new(); for pkg in level_pkgs { @@ -440,12 +459,12 @@ pub async fn install_packages_parallel( } if !level_errors.is_empty() { - println!("[X] Errors at level {}:", level_idx); + println!("{} Errors at level {}:", "[ror]".red().bold(), level_idx + 1); for (name, err) in &level_errors { - println!(" [!] {}: {}", name.red(), err); + println!(" {} {}: {}", "[ror]".red().bold(), name, err); } ctrl_c_handle.abort(); - return Err(format!("Level {} failed", level_idx)); + return Err(format!("Level {} failed", level_idx + 1)); } let mut db = InstalledDB::load(); @@ -455,13 +474,13 @@ pub async fn install_packages_parallel( let path = Path::new(InstalledDB::PATH); if let Err(e) = db.save_atomic(path) { - eprintln!("[X] Failed to save database: {}", e); + eprintln!("{} Failed to save database: {}", "[ror]".red().bold(), e); ctrl_c_handle.abort(); return Err(format!("Failed to save DB: {}", e)); } } ctrl_c_handle.abort(); - println!("[>] Synchronization completed successfully."); + println!("{} All packages installed successfully.", "[ror]".green().bold()); Ok(()) } diff --git a/src/progress.rs b/src/progress.rs index ec97b79..eb5ea00 100644 --- a/src/progress.rs +++ b/src/progress.rs @@ -91,3 +91,119 @@ pub fn format_bytes(bytes: u64) -> String { format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)) } } + +pub struct DownloadBar { + name: String, + total: Option<u64>, + downloaded: u64, + start_time: std::time::Instant, + last_render: std::time::Instant, + width: usize, +} + +impl DownloadBar { + pub fn new(name: &str, total: Option<u64>) -> Self { + let bar = Self { + name: name.to_string(), + total, + downloaded: 0, + start_time: std::time::Instant::now(), + last_render: std::time::Instant::now(), + width: 25, + }; + bar.render(); + bar + } + + pub fn update(&mut self, delta: u64) { + self.downloaded += delta; + if self.last_render.elapsed().as_millis() >= 80 { + self.render(); + self.last_render = std::time::Instant::now(); + } + } + + pub fn render(&self) { + let elapsed = self.start_time.elapsed().as_secs_f64(); + let speed = if elapsed > 0.05 { + format!("{}/s", format_bytes((self.downloaded as f64 / elapsed) as u64)) + } else { + "-- B/s".to_string() + }; + + if let Some(total) = self.total { + if total > 0 { + let pct = ((self.downloaded as f64 / total as f64) * 100.0).min(100.0); + let pos = ((self.downloaded as usize * self.width) / total as usize).min(self.width); + let runner = if (self.downloaded / 65536) % 2 == 0 { "R" } else { "r" }; + let mut bar = String::new(); + for i in 0..self.width { + if i < pos { + bar.push('═'); + } else if i == pos { + bar.push_str("\x1b[1;36m"); + bar.push_str(runner); + bar.push_str("\x1b[0m"); + } else if i % 3 == 0 { + bar.push_str("\x1b[1;37mo\x1b[0m"); + } else { + bar.push(' '); + } + } + + eprint!( + "\r\x1b[K\x1b[1;34m[ror]\x1b[0m {} \x1b[36m[{}]\x1b[0m \x1b[32m{:>3.0}%\x1b[0m {:>8} / {:<8} \x1b[90m({})\x1b[0m", + self.name, + bar, + pct, + format_bytes(self.downloaded), + format_bytes(total), + speed + ); + io::stderr().flush().ok(); + return; + } + } + + let pos = ((self.start_time.elapsed().as_millis() / 150) as usize) % self.width; + let runner = if (pos % 2) == 0 { "R" } else { "r" }; + let mut bar = String::new(); + for i in 0..self.width { + if i < pos { + bar.push('═'); + } else if i == pos { + bar.push_str("\x1b[1;36m"); + bar.push_str(runner); + bar.push_str("\x1b[0m"); + } else if i % 3 == 0 { + bar.push_str("\x1b[1;37mo\x1b[0m"); + } else { + bar.push(' '); + } + } + + eprint!( + "\r\x1b[K\x1b[1;34m[ror]\x1b[0m {} \x1b[36m[{}]\x1b[0m {:>8} downloaded \x1b[90m({})\x1b[0m", + self.name, + bar, + format_bytes(self.downloaded), + speed + ); + io::stderr().flush().ok(); + } + + pub fn finish(&self) { + let elapsed = self.start_time.elapsed().as_secs_f64(); + let speed = if elapsed > 0.05 { + format!("{}/s", format_bytes((self.downloaded as f64 / elapsed) as u64)) + } else { + String::new() + }; + eprintln!( + "\r\x1b[K\x1b[1;32m[ror] ✓\x1b[0m Downloaded {} ({}{})", + self.name, + format_bytes(self.downloaded), + if speed.is_empty() { String::new() } else { format!(", {}", speed) } + ); + } +} diff --git a/src/rootfs.rs b/src/rootfs.rs index 46025d0..8da1b90 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,28 +1,19 @@ -use std::collections::HashMap; -use crate::debug; +use std::collections::{HashMap, HashSet, VecDeque}; use std::fs; +use std::io::{Read, Write}; use std::path::Path; -use std::os::unix::fs::symlink; use std::sync::{Arc, Mutex}; -use std::sync::atomic::{AtomicU64, AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::thread; use colored::Colorize; +use chrono::Local; use crate::config; use crate::progress::ProgressBar; -use chrono::Local; use crate::install::{ Dependency, load_package, extract_native, extract_ror, extract_sror, extract_deb, install_files_to_root, select_binary_for_arch, InstalledDB, InstalledPackage, resolve_filename, install_services_to_root, }; -use nix::mount::{mount, umount2, MntFlags, MsFlags}; -use nix::unistd::{chroot, chdir, fork, ForkResult, execve}; -use nix::sys::wait::{waitpid, WaitStatus}; -use std::io::{Read, Write}; -use std::ffi::CString; -use std::ffi::CStr; -use std::collections::HashSet; -use std::collections::VecDeque; struct DownloadTask { pkg_name: String, @@ -371,424 +362,6 @@ fn install_from_archive( Ok(installed) } -fn setup_usr_merge(target_dir: &Path, target_libc: &str) -> Result<(), String> { - let is_musl = target_libc == "musl"; - - let root_dirs: &[&str] = if is_musl { - &["bin", "lib", "sbin"] - } else { - &["bin", "lib", "lib64", "sbin"] - }; - - for dir in root_dirs { - let path = target_dir.join(dir); - if path.symlink_metadata().is_ok() { - if path.is_dir() && !path.is_symlink() { - fs::remove_dir_all(&path) - .map_err(|e| format!("Failed to remove directory {}: {}", dir, e))?; - } else { - fs::remove_file(&path) - .map_err(|e| format!("Failed to remove {}: {}", dir, e))?; - } - } - } - - fs::create_dir_all(target_dir.join("usr/bin")) - .map_err(|e| format!("Failed to create usr/bin: {}", e))?; - fs::create_dir_all(target_dir.join("usr/lib")) - .map_err(|e| format!("Failed to create usr/lib: {}", e))?; - if !is_musl { - fs::create_dir_all(target_dir.join("usr/lib64")) - .map_err(|e| format!("Failed to create usr/lib64: {}", e))?; - } - - let usr_sbin = target_dir.join("usr/sbin"); - if usr_sbin.exists() || usr_sbin.is_symlink() { - let _ = fs::remove_file(&usr_sbin); - } - symlink("bin", &usr_sbin) - .map_err(|e| format!("Failed to create symlink usr/sbin -> bin: {}", e))?; - - if is_musl { - symlink("usr/bin", target_dir.join("bin")) - .map_err(|e| format!("Failed to create symlink bin -> usr/bin: {}", e))?; - symlink("usr/lib", target_dir.join("lib")) - .map_err(|e| format!("Failed to create symlink lib -> usr/lib: {}", e))?; - symlink("usr/bin", target_dir.join("sbin")) - .map_err(|e| format!("Failed to create symlink sbin -> usr/bin: {}", e))?; - } else { - symlink("usr/bin", target_dir.join("bin")) - .map_err(|e| format!("Failed to create symlink bin -> usr/bin: {}", e))?; - symlink("usr/lib", target_dir.join("lib")) - .map_err(|e| format!("Failed to create symlink lib -> usr/lib: {}", e))?; - symlink("usr/lib64", target_dir.join("lib64")) - .map_err(|e| format!("Failed to create symlink lib64 -> usr/lib64: {}", e))?; - symlink("usr/bin", target_dir.join("sbin")) - .map_err(|e| format!("Failed to create symlink sbin -> usr/bin: {}", e))?; - } - - Ok(()) -} - -fn fix_usr_merge(target_dir: &Path, target_libc: &str) -> Result<(), String> { - let is_musl = target_libc == "musl"; - - let root_links: &[&str] = if is_musl { - &["bin", "lib", "sbin"] - } else { - &["bin", "lib", "lib64", "sbin"] - }; - - for link in root_links { - let path = target_dir.join(link); - if path.exists() || path.is_symlink() { - let _ = fs::remove_file(&path); - } - } - - let usr_sbin = target_dir.join("usr/sbin"); - if usr_sbin.exists() || usr_sbin.is_symlink() { - let _ = fs::remove_file(&usr_sbin); - } - - let usr_bin = target_dir.join("usr/bin"); - if !usr_bin.exists() { - fs::create_dir_all(&usr_bin).map_err(|e| e.to_string())?; - } - - symlink("bin", &usr_sbin).map_err(|e| e.to_string())?; - - if is_musl { - symlink("usr/bin", target_dir.join("bin")).map_err(|e| e.to_string())?; - symlink("usr/lib", target_dir.join("lib")).map_err(|e| e.to_string())?; - symlink("usr/bin", target_dir.join("sbin")).map_err(|e| e.to_string())?; - } else { - symlink("usr/bin", target_dir.join("bin")).map_err(|e| e.to_string())?; - symlink("usr/lib", target_dir.join("lib")).map_err(|e| e.to_string())?; - symlink("usr/lib64", target_dir.join("lib64")).map_err(|e| e.to_string())?; - symlink("usr/bin", target_dir.join("sbin")).map_err(|e| e.to_string())?; - } - - Ok(()) -} - -fn create_fhs_skeleton(target_dir: &Path) -> Result<(), String> { - use std::os::unix::fs::PermissionsExt; - - let dirs = &[ - "boot", "dev", "dev/pts", "dev/shm", "etc", "etc/ror", - "home", "mnt", "opt", "proc", "root", "run", "srv", "sys", - "tmp", "usr/include", "usr/local/bin", "usr/local/lib", - "usr/local/share", "usr/share", "usr/share/doc", - "var", "var/cache", "var/empty", "var/lib", "var/lock", - "var/log", "var/run", "var/spool", "var/tmp", - ]; - - for dir in dirs { - fs::create_dir_all(target_dir.join(dir)) - .map_err(|e| format!("Failed to create FHS dir {}: {}", dir, e))?; - } - - for dir in &["tmp", "var/tmp"] { - fs::set_permissions(target_dir.join(dir), fs::Permissions::from_mode(0o1777)) - .map_err(|e| format!("Failed to set sticky bit on {}: {}", dir, e))?; - } - - for dir in &["root", "var/empty"] { - fs::set_permissions(target_dir.join(dir), fs::Permissions::from_mode(0o700)) - .map_err(|e| format!("Failed to set permissions on {}: {}", dir, e))?; - } - - Ok(()) -} - -fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { - let mounts: &[(&str, &str, &str, bool)] = &[ - ("/dev", "dev", "devtmpfs", true), - ("/dev/pts", "dev/pts", "devpts", true), - ("/dev/shm", "dev/shm", "tmpfs", true), - ("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))?; - - if *bind { - mount( - Some(Path::new(src)), - &target, - None::<&str>, - MsFlags::MS_BIND | MsFlags::MS_REC, - None::<&Path>, - ) - .map_err(|e| format!("Failed to bind mount {}: {}", rel, e))?; - - let _ = mount( - None::<&Path>, - &target, - None::<&str>, - MsFlags::MS_PRIVATE | MsFlags::MS_REC, - None::<&Path>, - ); - } else { - mount( - Some(Path::new(src)), - &target, - Some(*fstype), - MsFlags::empty(), - None::<&Path>, - ) - .map_err(|e| format!("Failed to mount {}: {}", rel, e))?; - } - } - Ok(()) -} - -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 _ = umount2(&target, MntFlags::MNT_DETACH); - } - } -} - -const SHELL_CANDIDATES: &[(&str, Option<&str>)] = &[ - ("/bin/sh", None), - ("/usr/bin/sh", None), - ("/bin/dash", None), - ("/usr/bin/dash", None), - ("/bin/bash", None), - ("/usr/bin/bash", None), - ("/bin/busybox", Some("sh")), - ("/usr/bin/busybox", Some("sh")), - ("/bin/toybox", Some("sh")), - ("/bin/ash", None), - ("/usr/bin/ash", None), -]; - -fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { - for (shell_path, subcmd) in SHELL_CANDIDATES { - let full = root_dir.join(shell_path.trim_start_matches('/')); - if !full.exists() { - continue; - } - 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; - } - 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 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 }) => { - 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, - steps: &str, - root_dir: &Path, - shell: &str, - subcmd: Option<&str>, -) -> 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 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 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 }) => { - 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)) - } - } -} - -fn run_ldconfig_in_root(root_dir: &Path) -> Result<(), String> { - let status = std::process::Command::new("ldconfig") - .arg("-r") - .arg(root_dir) - .arg("-C") - .arg("/etc/ld.so.cache") - .status(); - if let Ok(s) = status { - if s.success() { - debug!("Host ldconfig -r generated /etc/ld.so.cache successfully"); - return Ok(()); - } - } - - 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 Err("No ldconfig available".to_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(ldconfig_path).unwrap(); - let arg0 = CString::new("ldconfig").unwrap(); - 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 }) => { - 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)), - } -} - -fn run_all_install_steps( - group_order: &[String], - all_installed: &HashSet<String>, - target_dir: &Path, -) -> Result<(), String> { - let mut done: HashSet<String> = HashSet::new(); - let mut queue: Vec<&str> = group_order.iter().map(|s| s.as_str()).collect(); - - let mut extras: Vec<String> = all_installed.iter() - .filter(|p| !group_order.contains(p)) - .cloned() - .collect(); - extras.sort(); - for e in &extras { - queue.push(e.as_str()); - } - - let steps_pkgs: Vec<String> = queue.iter() - .filter(|&&pkg_name| { - all_installed.contains(pkg_name) && - load_package(pkg_name).map(|p| !p.install_steps.trim().is_empty()).unwrap_or(false) - }) - .map(|s| s.to_string()) - .collect(); - - if steps_pkgs.is_empty() { - return Ok(()); - } - - let mut pb = ProgressBar::new(steps_pkgs.len().max(1), "Running install steps..."); - - let (shell, subcmd) = find_working_shell(target_dir) - .ok_or_else(|| "No working shell found in rootfs. Tried: sh, dash, bash, busybox, ash".to_string())?; - - println!("{} Using shell: {}{}", ">>>".cyan(), shell, - subcmd.map(|s| format!(" {}", s)).unwrap_or_default()); - - for pkg_name in queue { - if done.contains(pkg_name) || !all_installed.contains(pkg_name) { - continue; - } - done.insert(pkg_name.to_string()); - - if let Some(pkg) = load_package(pkg_name) { - if !pkg.install_steps.trim().is_empty() { - pb.inc(&format!("install_steps: {}", pkg_name)); - eprintln!(); - run_install_steps_in_chroot(pkg_name, &pkg.install_steps, target_dir, shell, subcmd)?; - pb.render(); - } - } - } - pb.finish("All install steps done"); - Ok(()) -} - fn write_installed_json( target_dir: &Path, packages: &[String], @@ -841,7 +414,7 @@ fn generate_system_yaml(target_dir: &Path, group: &crate::group::Group) -> Resul let mut role_udev: Option<String> = None; let mut role_sh: Vec<String> = Vec::new(); let mut role_su: Vec<String> = Vec::new(); - let mut role_pkgs: std::collections::HashSet<String> = std::collections::HashSet::new(); + let mut role_pkgs: HashSet<String> = HashSet::new(); for spec in &group.packages { let (pkg_name, _) = crate::install::parse_package_spec(spec); @@ -874,13 +447,8 @@ fn generate_system_yaml(target_dir: &Path, group: &crate::group::Group) -> Resul if role_libc.is_none() { if let Some(libc_name) = &group.libc { - let libc_pkg = match libc_name.as_str() { - "musl" => "musl", - "glibc" => "glibc", - other => other, - }; - role_libc = Some(libc_pkg.to_string()); - role_pkgs.insert(libc_pkg.to_string()); + role_libc = Some(libc_name.clone()); + role_pkgs.insert(libc_name.clone()); } } @@ -950,7 +518,6 @@ pub fn build_rootfs( target_dir: &Path, cfg: &config::Config, target_arch: &str, - run_ldconfig: bool, ) -> Result<(), String> { if !target_dir.exists() { fs::create_dir_all(target_dir) @@ -964,22 +531,9 @@ pub fn build_rootfs( } let group = crate::group::load_group(group_name)?; - let mut start_packages = group.packages.clone(); - + let start_packages = group.packages.clone(); let target_libc: String = group.libc.clone().unwrap_or_else(|| cfg.global.libc.clone()); - if let Some(libc_name) = &group.libc { - let libc_pkg = match libc_name.as_str() { - "musl" => "musl", - "glibc" => "glibc", - other => other, - }; - if !start_packages.contains(&libc_pkg.to_string()) { - start_packages.push(libc_pkg.to_string()); - println!("{} Adding libc package: {}", ">>>".cyan(), libc_pkg); - } - } - println!( "{} Building rootfs in {}", "[ror]".blue().bold(), @@ -989,19 +543,11 @@ pub fn build_rootfs( println!("{} {}", "Description:".yellow(), desc); } - println!("\n{} Phase 0: UsrMerge...", ">>>".cyan().bold()); - setup_usr_merge(target_dir, &target_libc)?; - println!("{} bin/lib/lib64/sbin are now symlinks into usr/", ">>>".green()); - - println!("{} Creating FHS skeleton...", ">>>".cyan()); - create_fhs_skeleton(target_dir)?; - println!("{} FHS skeleton created.", ">>>".green()); - - println!("\n{} Phase 1a: Resolving packages...", ">>>".cyan().bold()); + println!("\n{} Phase 1: Resolving packages...", ">>>".cyan().bold()); let all_packages = collect_install_order(&start_packages, &target_libc)?; println!("{} {} packages to install (including dependencies)", ">>>".green(), all_packages.len()); - println!("\n{} Phase 1b: Building download queue...", ">>>".cyan().bold()); + println!("\n{} Phase 2: Building download queue...", ">>>".cyan().bold()); let tasks = build_download_tasks(&all_packages, target_arch, &target_libc, cfg)?; let n_parallel = cfg.global.parallel_downloads.max(1); @@ -1009,7 +555,7 @@ pub fn build_rootfs( let downloaded = download_parallel(tasks, cfg_arc, n_parallel)?; println!("{} All downloads complete.", ">>>".green().bold()); - println!("\n{} Phase 1c: Installing files...", ">>>".cyan().bold()); + println!("\n{} Phase 3: Installing files...", ">>>".cyan().bold()); let mut installing: HashSet<String> = HashSet::new(); let mut installed_files_map: HashMap<String, Vec<String>> = HashMap::new(); let mut pb = ProgressBar::new(all_packages.len().max(1), "Installing..."); @@ -1039,8 +585,6 @@ pub fn build_rootfs( } pb.finish(&format!("{} packages installed", installing.len())); - fix_usr_merge(target_dir, &target_libc)?; - println!("\n{} Writing installed.json...", ">>>".cyan()); write_installed_json(target_dir, &all_packages, &installed_files_map, &group, &target_libc)?; println!("{} installed.json written to etc/ror/", ">>>".green()); @@ -1057,59 +601,6 @@ pub fn build_rootfs( generate_system_yaml(target_dir, &group)?; println!("{} system.yaml written to etc/ror/", ">>>".green()); - if run_ldconfig && target_libc != "musl" { - println!("{} Running ldconfig...", ">>>".cyan()); - let ld_conf = target_dir.join("etc/ld.so.conf"); - if !ld_conf.exists() { - let _ = fs::write(&ld_conf, "/usr/lib\n/usr/lib64\n"); - } - if let Err(e) = run_ldconfig_in_root(target_dir) { - eprintln!("{} ldconfig failed: {} (non-fatal)", "[ror]".yellow(), e); - } else { - println!("{} ldconfig done.", ">>>".green()); - } - } - - println!("\n{} Phase 2: Running install_steps in chroot...", ">>>".cyan().bold()); - println!("{} Mounting /dev /proc /sys...", ">>>".cyan()); - if let Err(e) = mount_virtual_fs(target_dir) { - eprintln!("{} Warning: Failed to mount virtual fs: {} (continuing anyway)", "[ror]".yellow(), e); - } - - let result = run_all_install_steps(&group.packages, &installing, target_dir); - - if result.is_ok() && !group.install_steps.trim().is_empty() { - println!("{} Running group install_steps in chroot...", ">>>".cyan()); - let shell_result = find_working_shell(target_dir) - .ok_or_else(|| "No working shell found for group install_steps".to_string()); - match shell_result { - Ok((shell, subcmd)) => { - if let Err(e) = run_install_steps_in_chroot( - &group.name, - &group.install_steps, - target_dir, - shell, - subcmd, - ) { - println!("{} Unmounting virtual filesystems...", ">>>".cyan()); - umount_virtual_fs(target_dir); - return Err(e); - } - println!("{} Group install_steps done.", ">>>".green()); - } - Err(e) => { - println!("{} Unmounting virtual filesystems...", ">>>".cyan()); - umount_virtual_fs(target_dir); - return Err(e); - } - } - } - - println!("{} Unmounting virtual filesystems...", ">>>".cyan()); - umount_virtual_fs(target_dir); - - result?; - println!( "\n{} Rootfs built successfully at {} ", "[ror]".green().bold(), |