// src/rootfs.rs use std::collections::HashMap; use std::fs; use std::path::Path; use std::os::unix::fs::symlink; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicU64, AtomicBool, Ordering}; use std::thread; use colored::Colorize; 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, urls: Vec, sha256: String, } pub fn collect_install_order(start_pkgs: &[String], libc: &str) -> Result, String> { let mut order: Vec = Vec::new(); let mut visited: HashSet = HashSet::new(); fn visit( spec: &str, libc: &str, visited: &mut HashSet, order: &mut Vec, ) -> Result<(), String> { let (name, _) = crate::install::parse_package_spec(spec); if visited.contains(&name) { return Ok(()); } visited.insert(name.clone()); let pkg = load_package(&name) .ok_or_else(|| format!("Package '{}' not found in repository", name))?; for dep in pkg.effective_depends(libc) { match dep { Dependency::Single(d) => visit(d, libc, visited, order)?, Dependency::Any(alts) => { if let Some(first) = alts.first() { visit(first, libc, visited, order)?; } } } } order.push(spec.to_string()); Ok(()) } for pkg in start_pkgs { visit(pkg, libc, &mut visited, &mut order)?; } Ok(order) } fn build_download_tasks(packages: &[String], target_arch: &str, target_libc: &str, cfg: &config::Config) -> Result, String> { let mut tasks = Vec::new(); for pkg_spec in packages { let (pkg_name, variant) = crate::install::parse_package_spec(pkg_spec); let pkg = load_package(&pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; let binary = select_binary_for_arch(&pkg, target_arch, target_libc, variant.as_deref()) .map_err(|e| format!("No binary for '{}': {}", pkg_name, e))?; 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()); let local_path = Path::new(&workspace).join(&effective_filename); let urls: Vec = if local_path.exists() { vec![format!("file://{}", local_path.display())] } else if !binary.url.is_empty() { vec![binary.url.clone()] } else { binary.mirrors.iter() .filter_map(|m| { if m.starts_with("http://") || m.starts_with("https://") { Some(m.replace("{filename}", &effective_filename)) } else { let repo = cfg.repositories.get(m.as_str())?; let base = repo.urlrepo.as_deref().unwrap_or(repo.url.as_str()); let base = base.trim_end_matches('/'); Some(format!("{}/{}", base, effective_filename)) } }) .collect() }; if urls.is_empty() { return Err(format!("No download URLs for package '{}'", pkg_name)); } println!("{} {} -> {}", ">>>".cyan(), pkg_name, urls[0]); tasks.push(DownloadTask { pkg_name: pkg_name.clone(), urls, sha256: binary.sha256.clone(), }); } Ok(tasks) } fn download_file_quiet( url: &str, expected_sha: &str, bytes_done_global: &Arc, bytes_expected_global: &Arc, ) -> 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); if let Some(local) = url.strip_prefix("file://") { let src = Path::new(local); if !src.exists() { return Err(format!("Local file not found: {}", local)); } 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 dict_src = src.with_extension("dict"); if dict_src.exists() { let dict_dst = file_path.with_extension("dict"); let _ = std::fs::copy(&dict_src, &dict_dst); } bytes_done_global.fetch_add(size, Ordering::Relaxed); return Ok((file_path, size)); } use reqwest::blocking::Client; let client = Client::builder() .connect_timeout(std::time::Duration::from_secs(30)) .build() .map_err(|e| format!("HTTP client: {}", e))?; let resp = client.get(url).send() .map_err(|e| format!("Download failed: {}", e))?; if !resp.status().is_success() { return Err(format!("HTTP {}", resp.status())); } if let Some(len) = resp .headers() .get(reqwest::header::CONTENT_LENGTH) .and_then(|v| v.to_str().ok()) .and_then(|s| s.parse::().ok()) { 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 hasher = Sha256::new(); let mut buf = [0u8; 65536]; let mut downloaded: u64 = 0; let mut reader = resp; loop { 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())?; downloaded += n as u64; bytes_done_global.fetch_add(n as u64, Ordering::Relaxed); } 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)); } } Ok((file_path, downloaded)) } fn render_overall_bar(bytes_done: u64, bytes_expected: u64) { use crate::progress::format_bytes; const W: u64 = 40; let filled = if bytes_expected > 0 { (bytes_done * W / bytes_expected).min(W) } else { 0 }; let arrow = if filled < W { ">" } else { "=" }; let bar = format!( "{}{}{}", "=".repeat(filled.saturating_sub(1) as usize), arrow, " ".repeat((W - filled) as usize) ); if bytes_expected > 0 { eprint!( "\r\x1b[K\x1b[36m[{}]\x1b[0m {} / {}", bar, format_bytes(bytes_done), format_bytes(bytes_expected) ); } else { eprint!("\r\x1b[K\x1b[36m[{}]\x1b[0m {}", bar, format_bytes(bytes_done)); } std::io::stderr().flush().ok(); } fn download_parallel( tasks: Vec, _cfg: Arc, n_parallel: usize, ) -> Result, String> { let n = n_parallel.max(1).min(tasks.len().max(1)); let total_files = tasks.len(); println!( "{} Downloading {} package(s) ({} in parallel)...", ">>>".cyan().bold(), total_files, n ); let queue: Arc>> = Arc::new(Mutex::new(tasks.into_iter().collect())); let results: Arc>> = Arc::new(Mutex::new(HashMap::new())); let first_error: Arc>> = Arc::new(Mutex::new(None)); let bytes_done = Arc::new(AtomicU64::new(0)); let bytes_expected = Arc::new(AtomicU64::new(0)); let files_done = Arc::new(AtomicU64::new(0)); let print_lock: Arc> = Arc::new(Mutex::new(())); let ticker_running = Arc::new(AtomicBool::new(true)); { let bd = Arc::clone(&bytes_done); let be = Arc::clone(&bytes_expected); let pl = Arc::clone(&print_lock); let running = Arc::clone(&ticker_running); thread::spawn(move || { while running.load(Ordering::Relaxed) { thread::sleep(std::time::Duration::from_millis(100)); let _g = pl.lock().unwrap(); render_overall_bar(bd.load(Ordering::Relaxed), be.load(Ordering::Relaxed)); } }); } let mut handles = vec![]; for _ in 0..n { let queue = Arc::clone(&queue); let results = Arc::clone(&results); let first_error = Arc::clone(&first_error); let bytes_done = Arc::clone(&bytes_done); let bytes_exp = Arc::clone(&bytes_expected); let files_done = Arc::clone(&files_done); let print_lock = Arc::clone(&print_lock); handles.push(thread::spawn(move || { loop { if first_error.lock().unwrap().is_some() { return; } let task = queue.lock().unwrap().pop_front(); let task = match task { Some(t) => t, None => return }; let mut last_err = String::new(); let mut success = false; for url in &task.urls { match download_file_quiet(url, &task.sha256, &bytes_done, &bytes_exp) { Ok((path, file_bytes)) => { results.lock().unwrap().insert(task.pkg_name.clone(), path); let _done = files_done.fetch_add(1, Ordering::Relaxed) + 1; let _g = print_lock.lock().unwrap(); eprintln!( "\r\x1b[K\x1b[32m✓\x1b[0m Downloaded {}", crate::progress::format_bytes(file_bytes) ); render_overall_bar( bytes_done.load(Ordering::Relaxed), bytes_exp.load(Ordering::Relaxed), ); success = true; break; } Err(e) => last_err = e, } } if !success { let mut err = first_error.lock().unwrap(); if err.is_none() { *err = Some(format!("Failed to download '{}': {}", task.pkg_name, last_err)); } } } })); } for handle in handles { handle.join().ok(); } ticker_running.store(false, Ordering::Relaxed); eprintln!(); if let Some(e) = first_error.lock().unwrap().take() { return Err(e); } Ok(Arc::try_unwrap(results).unwrap().into_inner().unwrap()) } fn install_from_archive( pkg_name: &str, archive_path: &std::path::Path, root_dir: &Path, pkg_type: &str, ) -> Result, 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 extracted = if pkg_type == "ror" { extract_ror(archive_path, &work_dir) .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? } else if pkg_type == "sror" { extract_sror(archive_path, &work_dir) .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? } else if pkg_type == "deb" { extract_deb(archive_path, &work_dir) .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? } else { extract_native(archive_path, &work_dir) .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))? }; 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) } 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>, ) } 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 _ = execve::<&CStr, &CStr>(&shell_c, &args_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 _ = execve::<&CStr, &CStr>(&shell_c, &args.iter().map(|s| s.as_ref()).collect::>(), &[]); 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> { match unsafe { fork() } { Ok(ForkResult::Child) => { if chroot(root_dir).is_err() { std::process::exit(1); } if chdir("/").is_err() { std::process::exit(1); } let ldconfig = CString::new("/sbin/ldconfig").unwrap(); let arg0 = CString::new("ldconfig").unwrap(); let _ = execve::<&CString, &CStr>(&ldconfig, &[&arg0], &[]); std::process::exit(1); } Ok(ForkResult::Parent { child }) => { match waitpid(child, None) { Ok(WaitStatus::Exited(_, 0)) => Ok(()), Ok(_) => Err("ldconfig terminated abnormally".to_string()), Err(e) => Err(format!("waitpid ldconfig failed: {}", e)), } } Err(e) => Err(format!("Fork for ldconfig failed: {}", e)), } } fn run_all_install_steps( group_order: &[String], all_installed: &HashSet, target_dir: &Path, ) -> Result<(), String> { let mut done: HashSet = HashSet::new(); let mut queue: Vec<&str> = group_order.iter().map(|s| s.as_str()).collect(); let mut extras: Vec = 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 = 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(); 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], files_map: &HashMap>, group: &crate::group::Group, target_libc: &str, ) -> Result<(), String> { let mut db = InstalledDB::default(); let now = Local::now().to_rfc3339(); for spec in packages { let (pkg_name, _variant) = crate::install::parse_package_spec(spec); if let Some(pkg) = load_package(&pkg_name) { let files = files_map.get(&pkg_name).cloned().unwrap_or_default(); let libc = pkg.libc.clone() .or_else(|| group.libc.clone()) .or_else(|| Some(target_libc.to_string())); if files.is_empty() { continue; } db.packages.insert(pkg_name.clone(), InstalledPackage { name: pkg.name, version: pkg.version, libc, files, installed_at: now.clone(), }); } } db.packages.insert(group.name.clone(), InstalledPackage { name: group.name.clone(), version: group.version.clone().unwrap_or_else(|| "0".to_string()), libc: group.libc.clone(), files: vec![], installed_at: now.clone(), }); let json = serde_json::to_string_pretty(&db) .map_err(|e| format!("Failed to serialize installed.json: {}", e))?; let out_dir = target_dir.join("etc/ror"); fs::create_dir_all(&out_dir) .map_err(|e| format!("Failed to create etc/ror: {}", e))?; fs::write(out_dir.join("installed.json"), json) .map_err(|e| format!("Failed to write installed.json: {}", e))?; Ok(()) } fn generate_system_yaml(target_dir: &Path, group: &crate::group::Group) -> Result<(), String> { let mut role_init: Option = None; let mut role_libc: Option = None; let mut role_core: Option = None; let mut role_udev: Option = None; let mut role_sh: Vec = Vec::new(); let mut role_su: Vec = Vec::new(); let mut role_pkgs: std::collections::HashSet = std::collections::HashSet::new(); for spec in &group.packages { let (pkg_name, _) = crate::install::parse_package_spec(spec); let pkg = match load_package(&pkg_name) { Some(p) => p, None => continue, }; let mut is_role = false; for prov in &pkg.provides { match prov.as_str() { "init-system" => { role_init = Some(pkg_name.clone()); is_role = true; } "libc" => { role_libc = Some(pkg_name.clone()); is_role = true; } "core-utils" => { role_core = Some(pkg_name.clone()); is_role = true; } "udev" => { role_udev = Some(pkg_name.clone()); is_role = true; } "sh" => { if !role_sh.contains(&pkg_name) { role_sh.push(pkg_name.clone()); } is_role = true; } "su" => { if !role_su.contains(&pkg_name) { role_su.push(pkg_name.clone()); } is_role = true; } _ => {} } } if is_role { role_pkgs.insert(pkg_name); } } 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()); } } let extra_pkgs: Vec<&String> = group.packages .iter() .filter(|spec| { let (name, _) = crate::install::parse_package_spec(spec); !role_pkgs.contains(&name) }) .collect(); let mut out = String::new(); out.push_str("roles:\n"); match &role_init { Some(v) => out.push_str(&format!(" init: {}\n", v)), None => out.push_str(" init: null\n"), } match &role_libc { Some(v) => out.push_str(&format!(" libc: {}\n", v)), None => out.push_str(" libc: null\n"), } match &role_core { Some(v) => out.push_str(&format!(" core: {}\n", v)), None => out.push_str(" core: null\n"), } match &role_udev { Some(v) => out.push_str(&format!(" udev: {}\n", v)), None => out.push_str(" udev: null\n"), } if role_sh.is_empty() { out.push_str(" sh: []\n"); } else { out.push_str(" sh:\n"); for s in &role_sh { out.push_str(&format!(" - {}\n", s)); } } if role_su.is_empty() { out.push_str(" su: []\n"); } else { out.push_str(" su:\n"); for s in &role_su { out.push_str(&format!(" - {}\n", s)); } } if extra_pkgs.is_empty() { out.push_str("packages: []\n"); } else { out.push_str("packages:\n"); for p in &extra_pkgs { out.push_str(&format!(" - {}\n", p)); } } out.push_str("groups: []\n"); out.push_str("oss: false\n"); let etc_ror = target_dir.join("etc/ror"); fs::create_dir_all(&etc_ror) .map_err(|e| format!("Failed to create etc/ror: {}", e))?; fs::write(etc_ror.join("system.yaml"), out) .map_err(|e| format!("Failed to write system.yaml: {}", e))?; Ok(()) } pub fn build_rootfs( group_name: &str, target_dir: &Path, cfg: &config::Config, target_arch: &str, run_ldconfig: bool, ) -> Result<(), String> { if !target_dir.exists() { fs::create_dir_all(target_dir) .map_err(|e| format!("Failed to create target directory: {}", e))?; } else { let mut entries = target_dir.read_dir() .map_err(|e| format!("Failed to read target directory: {}", e))?; if entries.next().is_some() { return Err(format!("Target directory {} is not empty", target_dir.display())); } } let group = crate::group::load_group(group_name)?; let mut 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(), target_dir.display() ); if let Some(desc) = &group.description { 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()); 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()); let tasks = build_download_tasks(&all_packages, target_arch, &target_libc, cfg)?; let n_parallel = cfg.global.parallel_downloads.max(1); let cfg_arc = Arc::new(cfg.clone()); let downloaded = download_parallel(tasks, cfg_arc, n_parallel)?; println!("{} All downloads complete.", ">>>".green().bold()); println!("\n{} Phase 1c: Installing files...", ">>>".cyan().bold()); let mut installing: HashSet = HashSet::new(); let mut installed_files_map: HashMap> = HashMap::new(); let mut pb = ProgressBar::new(all_packages.len().max(1), "Installing..."); for pkg_spec in &all_packages { let (pkg_name, variant) = crate::install::parse_package_spec(pkg_spec); let pkg = load_package(&pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; let binary = select_binary_for_arch(&pkg, target_arch, &target_libc, variant.as_deref()) .map_err(|e| format!("Arch selection failed for '{}': {}", pkg_name, e))?; let archive_path = downloaded.get(pkg_spec) .or_else(|| downloaded.get(&pkg_name)) .ok_or_else(|| format!("Archive for '{}' was not downloaded", pkg_name))?; pb.inc(&format!("Installing {}", pkg_name)); let pkg_type = binary.pkg_type.as_deref().unwrap_or("tar.xz"); let files = install_from_archive( &pkg_name, archive_path, target_dir, pkg_type, )?; installed_files_map.insert(pkg_name.clone(), files); installing.insert(pkg_name.clone()); } 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()); for pkg_name in &installing { if let Some(pkg) = load_package(pkg_name) { if !pkg.services.is_empty() { install_services_to_root(&pkg, target_dir); } } } println!("{} Generating system.yaml...", ">>>".cyan()); 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()); mount_virtual_fs(target_dir)?; 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(), target_dir.display() ); Ok(()) }