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/rootfs.rs | |
| parent | 78828df65dfc90d30e82490b290db04ebf2c6f30 (diff) | |
| download | ror-283afa1922f87e5e97c4bec2c019b3add71e375a.tar.gz ror-283afa1922f87e5e97c4bec2c019b3add71e375a.zip | |
Diffstat (limited to 'src/rootfs.rs')
| -rw-r--r-- | src/rootfs.rs | 531 |
1 files changed, 11 insertions, 520 deletions
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(), |