use anyhow::{bail, Context, Result};
use camino::Utf8PathBuf;
use cap_std::ambient_authority;
use cap_std::fs::Dir;
use cap_std_ext::dirext::CapStdExtDirExt;
use fn_error_context::context;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;
use bootc_internal_blockdev::Device;
use crate::bootloader::Bootloader;
use crate::bootupd::{RootContext, Sysroot};
use crate::component::*;
use crate::filetree::FileMetadata;
use crate::filetree::FileTree;
use crate::freezethaw::fsfreeze_thaw_cycle;
use crate::grubconfigs;
use crate::model::*;
use crate::packagesystem;
pub(crate) const GRUB_BIN: &str = "usr/sbin/grub2-install";
#[cfg(target_arch = "x86_64")]
const GRUB_MODULES: &str = "usr/lib/grub/i386-pc";
#[cfg(target_arch = "powerpc64")]
const GRUB_MODULES: &str = "usr/lib/grub/powerpc-ieee1275";
#[cfg(target_arch = "powerpc64")]
fn target_device(device: &Device) -> Result<String> {
const PREPBOOT_GUID: &str = "9E1A2D38-C612-4316-AA26-8B49521E5A8B";
const PREPBOOT_MBR_TYPE: &str = "41";
if !device.has_children() {
return Ok(device.path());
}
let prepdev = device
.find_partition_of_type(PREPBOOT_GUID)
.or_else(|| device.find_partition_of_type(PREPBOOT_MBR_TYPE))
.ok_or_else(|| {
anyhow::anyhow!("Failed to find PReP partition with GUID {PREPBOOT_GUID}")
})?;
Ok(prepdev.path())
}
#[context("Hashing GRUB files in directory at {path}")]
fn hash_grub_dir(
dir: &Dir,
path: &str,
children: &mut BTreeMap<String, FileMetadata>,
) -> Result<()> {
for entry in dir.entries_utf8()? {
let entry = entry?;
let name = entry.file_name().context("getting file name")?;
let rel_path = format!("{path}/{name}");
let file_type = entry.file_type()?;
if file_type.is_file() {
let meta = FileMetadata::new_from_path(dir, &name)
.with_context(|| format!("hashing {rel_path}"))?;
children.insert(rel_path, meta);
} else if file_type.is_dir() {
let child = dir.open_dir(&name)?;
hash_grub_dir(&child, &rel_path, children)?;
} else {
bail!("Unsupported file type in the GRUB modules directory: {rel_path}");
}
}
Ok(())
}
#[context("Generating GRUB FileTree from root {}", root.as_ref().display())]
fn grub_filetree(root: impl AsRef<Path>) -> Result<FileTree> {
let root = root.as_ref();
let dir = Dir::open_ambient_dir(root, ambient_authority())
.with_context(|| format!("opening {}", root.display()))?;
let mut children = BTreeMap::new();
let meta = FileMetadata::new_from_path(&dir, GRUB_BIN)
.with_context(|| format!("hashing {GRUB_BIN}"))?;
children.insert(GRUB_BIN.into(), meta);
if let Some(grubdir) = dir.open_dir_optional(GRUB_MODULES)? {
hash_grub_dir(&grubdir, GRUB_MODULES, &mut children)?;
}
Ok(FileTree { children })
}
fn ensure_file(path: &Path) -> Result<()> {
match path.metadata() {
Ok(meta) if meta.is_file() => Ok(()),
Ok(_) => bail!("{} is not a file", path.display()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
bail!("Failed to find {:?}", path)
}
Err(e) => Err(e).with_context(|| format!("checking for {}", path.display())),
}
}
fn grub_install_bin(process_root: &Path) -> Result<PathBuf> {
let modules = process_root.join(GRUB_MODULES);
match modules.metadata() {
Ok(meta) if meta.is_dir() => {}
Ok(_) => bail!("{} is not a directory", modules.display()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
bail!("Failed to find GRUB modules at {}", modules.display())
}
Err(e) => {
return Err(e)
.with_context(|| format!("checking for GRUB modules at {}", modules.display()))
}
}
ensure_file(&modules.join("modinfo.sh"))?;
let grub_install = process_root.join(GRUB_BIN);
ensure_file(&grub_install)?;
rustix::fs::access(&grub_install, rustix::fs::Access::EXEC_OK)
.with_context(|| format!("{} cannot be run", grub_install.display()))?;
Ok(grub_install)
}
fn check_grub_install(process_root: &Path) -> Result<()> {
let grub_install = grub_install_bin(process_root)?;
let mut cmd = Command::new(&grub_install);
cmd.arg("--version").stdin(std::process::Stdio::null());
let cmdout = cmd
.output()
.with_context(|| format!("{} cannot be run", grub_install.display()))?;
if !cmdout.status.success() {
std::io::stderr().write_all(&cmdout.stderr)?;
bail!("Failed to run {:?}", cmd);
}
Ok(())
}
#[derive(Default)]
pub(crate) struct Bios {}
impl Bios {
fn run_grub_install(&self, dest_root: &str, device: &Device) -> Result<PathBuf> {
let process_root = PathBuf::from("/");
let grub_install = grub_install_bin(&process_root)?;
let mut cmd = Command::new(grub_install);
let boot_dir = Path::new(dest_root).join("boot");
#[cfg(target_arch = "x86_64")]
cmd.args(["--target", "i386-pc"])
.args(["--boot-directory", boot_dir.to_str().unwrap()])
.args(["--modules", "mdraid1x part_gpt"])
.arg(&device.path());
#[cfg(target_arch = "powerpc64")]
{
let device = target_device(device)?;
cmd.args(&["--target", "powerpc-ieee1275"])
.args(&["--boot-directory", boot_dir.to_str().unwrap()])
.arg("--no-nvram")
.arg(&device);
}
let cmdout = cmd.output()?;
if !cmdout.status.success() {
std::io::stderr().write_all(&cmdout.stderr)?;
bail!("Failed to run {:?}", cmd);
}
Ok(process_root)
}
}
impl Component for Bios {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn name(&self) -> &'static str {
self.component_type().into()
}
fn component_type(&self) -> ComponentType {
ComponentType::Bios
}
fn is_bootloader_supported(&self, bootloader: Bootloader) -> bool {
matches!(bootloader, Bootloader::Grub)
}
fn check_payload(&self, _src_root: &str, _bootloader: Bootloader) -> Result<()> {
check_grub_install(Path::new("/"))
}
fn install(
&self,
src_root: &str,
dest_root: &str,
device: Option<&Device>,
_update_firmware: bool,
bootloader: Bootloader,
) -> Result<InstalledContent> {
if !self.is_bootloader_supported(bootloader) {
anyhow::bail!("{bootloader} cannot be installed for {}", self.name());
}
let device =
device.ok_or_else(|| anyhow::anyhow!("BIOS component requires a target device"))?;
let src_dir = Dir::open_ambient_dir(src_root, ambient_authority())
.with_context(|| format!("opening source directory {src_root}"))?;
let Some(meta) = self.get_component_update(&src_dir, Some(bootloader))? else {
anyhow::bail!("No update metadata for component {} found", self.name());
};
let root = self
.run_grub_install(dest_root, device)
.with_context(|| format!("installing GRUB on {}", device.path()))?;
Ok(InstalledContent {
meta,
filetree: Some(grub_filetree(&root)?),
adopted_from: None,
})
}
fn generate_update_metadata(&self, sysroot_path: &str) -> Result<Option<ContentMetadata>> {
let grub_install = Path::new(sysroot_path).join(GRUB_BIN);
if !grub_install.exists() {
println!("Failed to find {:?}", grub_install);
return Ok(None);
}
let meta = packagesystem::query_files(sysroot_path, [&grub_install])?;
write_update_metadata(sysroot_path, self.component_update_data_name(), &meta)?;
Ok(Some(meta))
}
fn query_adopt(&self, devices: &Option<Vec<Device>>) -> Result<Option<Adoptable>> {
#[cfg(target_arch = "x86_64")]
if crate::efi::is_efi_booted()? && devices.is_none() {
log::debug!("Skip BIOS adopt");
return Ok(None);
}
crate::component::query_adopt_state()
}
fn migrate_static_grub_config(&self, sysroot_path: &str, destdir: &Dir) -> Result<()> {
let grub = "boot/grub2";
let grub_config_path = Utf8PathBuf::from(sysroot_path).join(grub);
let grub_config_dir = destdir.open_dir(grub).context("Opening boot/grub2")?;
let grub_config = grub_config_path.join(grubconfigs::GRUBCONFIG);
if !grub_config.exists() {
anyhow::bail!("Could not find '{}'", grub_config);
}
let mut current_config;
if !grub_config.is_symlink() {
println!("'{}' is not a symlink", grub_config);
current_config = grub_config.clone();
} else {
let real_config = grub_config_dir.read_link(grubconfigs::GRUBCONFIG)?;
let real_config =
Utf8PathBuf::from_path_buf(real_config).expect("Path should be valid UTF-8");
current_config = grub_config_path.clone();
current_config.push(real_config);
}
let backup_config = grub_config_path.join(grubconfigs::GRUBCONFIG_BACKUP);
if !backup_config.exists() {
println!(
"Creating a backup of the current GRUB config '{}' in '{}'...",
current_config, backup_config
);
std::fs::copy(¤t_config, &backup_config)
.context("Failed to backup GRUB config")?;
}
crate::grubconfigs::install(&destdir, None, None, true, None)?;
if current_config != grub_config {
println!("Removing {}", current_config);
match std::fs::remove_file(current_config.as_std_path()) {
Ok(..) => { }
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
println!("{} not found for removal", current_config);
}
Err(e) => Err(e).with_context(|| format!("Removing {current_config}"))?,
};
}
fsfreeze_thaw_cycle(grub_config_dir.reopen_as_ownedfd()?)?;
Ok(())
}
fn adopt_update(
&self,
rootcxt: &RootContext,
update: &ContentMetadata,
with_static_config: bool,
bootloader: Bootloader,
) -> Result<Option<InstalledContent>> {
if !self.is_bootloader_supported(bootloader) {
log::debug!(
"Skip BIOS adopt: bootloader {} is not supported",
bootloader.efi_component_name()
);
return Ok(None);
}
let bios_devices = rootcxt.device.find_colocated_bios_boot()?;
let Some(meta) = self.query_adopt(&bios_devices)? else {
return Ok(None);
};
for parent in rootcxt.device.find_all_roots()? {
self.run_grub_install(rootcxt.path.as_str(), &parent)?;
log::debug!("Installed grub modules on {}", parent.path());
}
if with_static_config {
if let Some(bootloader) = crate::ostreeutil::get_ostree_bootloader()? {
println!(
"ostree repo 'sysroot.bootloader' config option is currently set to: '{bootloader}'",
);
} else {
println!("ostree repo 'sysroot.bootloader' config option is not set yet");
self.migrate_static_grub_config(rootcxt.path.as_str(), &rootcxt.sysroot)?;
};
}
Ok(Some(InstalledContent {
meta: update.clone(),
filetree: Some(grub_filetree(&rootcxt.path)?),
adopted_from: Some(meta.version),
}))
}
fn query_update(
&self,
sysroot: &Dir,
bootloader: Bootloader,
) -> Result<Option<ContentMetadata>> {
if !self.is_bootloader_supported(bootloader) {
return Ok(None);
}
self.get_component_update(sysroot, Some(bootloader))
}
fn query_requires_update(&self, sysroot: &Dir) -> Result<()> {
if !sysroot.exists("sys/firmware/efi") {
anyhow::bail!("Failed to find BIOS update metadata");
}
Ok(())
}
fn run_update(&self, rootcxt: &RootContext, _: &InstalledContent) -> Result<InstalledContent> {
let updatemeta = self
.query_update(&rootcxt.sysroot, Bootloader::Grub)?
.expect("update available");
for parent in rootcxt.device.find_all_roots()? {
self.run_grub_install(rootcxt.path.as_str(), &parent)?;
log::debug!("Installed grub modules on {}", parent.path());
}
let adopted_from = None;
Ok(InstalledContent {
meta: updatemeta,
filetree: Some(grub_filetree(&rootcxt.path)?),
adopted_from,
})
}
fn validate(&self, _: &InstalledContent, _device: &Device) -> Result<ValidationResult> {
Ok(ValidationResult::Skip)
}
fn get_efi_vendor(&self, _: &Path) -> Result<Option<String>> {
Ok(None)
}
fn has_changed_content(
&self,
sysroot: Sysroot<'_>,
current: &InstalledContent,
_bootloader: Bootloader,
) -> Result<bool> {
let updated = grub_filetree(sysroot.path)?;
if let Some(t) = current.filetree.as_ref() {
Ok(!t.is_content_eq(&updated))
} else {
log::warn!("no filetree available for the current install, assuming updatable");
Ok(true)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::packagesystem::Module;
use camino::Utf8Path;
use chrono::Utc;
use std::path::PathBuf;
fn link_grub_install(root: &Path, program: &str) -> Result<PathBuf> {
let path = std::env::var_os("PATH").context("PATH is unset")?;
let program = std::env::split_paths(&path)
.map(|dir| dir.join(program))
.find(|candidate| candidate.is_file())
.with_context(|| format!("no {program} in PATH"))?;
let bin = root.join(GRUB_BIN);
std::fs::create_dir_all(bin.parent().unwrap())?;
std::os::unix::fs::symlink(program, &bin)?;
Ok(bin)
}
#[test]
fn test_grub_install_bin() -> Result<()> {
use std::os::unix::fs::PermissionsExt;
let td = tempfile::tempdir()?;
let root = td.path();
let modules = root.join(GRUB_MODULES);
let err = grub_install_bin(root).unwrap_err();
assert_eq!(
err.to_string(),
format!("Failed to find GRUB modules at {}", modules.display())
);
std::fs::create_dir_all(modules.parent().unwrap())?;
std::fs::write(&modules, "")?;
let err = grub_install_bin(root).unwrap_err();
assert!(err.to_string().ends_with("is not a directory"), "{err}");
std::fs::remove_file(&modules)?;
std::fs::create_dir_all(&modules)?;
let err = grub_install_bin(root).unwrap_err();
assert!(err.to_string().contains("modinfo.sh"), "{err}");
std::fs::write(modules.join("modinfo.sh"), "")?;
let err = grub_install_bin(root).unwrap_err();
assert!(err.to_string().contains(GRUB_BIN), "{err}");
let bin = root.join(GRUB_BIN);
std::fs::create_dir_all(&bin)?;
let err = grub_install_bin(root).unwrap_err();
assert!(err.to_string().ends_with("is not a file"), "{err}");
std::fs::remove_dir(&bin)?;
std::fs::write(&bin, "")?;
let err = grub_install_bin(root).unwrap_err();
assert!(err.to_string().ends_with("cannot be run"), "{err}");
std::fs::write(&bin, "#!/nonexistent\n")?;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))?;
let err = check_grub_install(root).unwrap_err();
assert!(err.to_string().ends_with("cannot be run"), "{err}");
std::fs::remove_file(&bin)?;
assert_eq!(link_grub_install(root, "false")?, bin);
assert_eq!(grub_install_bin(root)?, bin);
let err = check_grub_install(root).unwrap_err();
assert!(err.to_string().starts_with("Failed to run"), "{err}");
std::fs::remove_file(&bin)?;
link_grub_install(root, "true")?;
assert_eq!(grub_install_bin(root)?, bin);
check_grub_install(root)?;
Ok(())
}
#[test]
fn test_query_updatable_content_differs() -> Result<()> {
let sysroot = tempfile::tempdir()?;
let sysroot_path = Utf8Path::from_path(sysroot.path()).expect("valid UTF-8");
std::fs::create_dir_all(sysroot_path.join("usr/sbin"))?;
std::fs::write(sysroot_path.join(GRUB_BIN), "grub2-install new")?;
std::fs::create_dir_all(sysroot_path.join(BOOTUPD_UPDATES_DIR))?;
let meta = ContentMetadata {
timestamp: Utc::now(),
version: "grub2 2.12-7.el9".into(),
versions: Some(vec![Module {
name: "grub2".into(),
evr: "2.12-7.el9".into(),
}]),
#[cfg(efi_arch)]
default_bootloader: None,
};
write_update_metadata(sysroot_path.as_str(), PathBuf::from("BIOS.json"), &meta)?;
let old_payload = tempfile::tempdir()?;
std::fs::create_dir_all(old_payload.path().join("usr/sbin"))?;
std::fs::write(old_payload.path().join(GRUB_BIN), "grub2-install old")?;
let sysroot_dir = Dir::open_ambient_dir(sysroot_path, ambient_authority())?;
let sysroot = Sysroot {
dir: &sysroot_dir,
path: sysroot_path,
};
let bios = Bios::default();
let inst = InstalledContent {
meta: meta.clone(),
filetree: Some(grub_filetree(old_payload.path())?),
adopted_from: None,
};
let (update, updatable) = bios.query_updatable(sysroot, &inst, Bootloader::Grub)?;
assert!(update.is_some());
assert!(matches!(updatable, ComponentUpdatable::Upgradable));
let inst = InstalledContent {
meta: meta.clone(),
filetree: None,
adopted_from: None,
};
let (_, updatable) = bios.query_updatable(sysroot, &inst, Bootloader::Grub)?;
assert!(matches!(updatable, ComponentUpdatable::Upgradable));
let inst = InstalledContent {
meta: meta.clone(),
filetree: Some(grub_filetree(sysroot.path)?),
adopted_from: None,
};
let (_, updatable) = bios.query_updatable(sysroot, &inst, Bootloader::Grub)?;
assert!(matches!(updatable, ComponentUpdatable::AtLatestVersion));
Ok(())
}
#[test]
fn test_grub_filetree_includes_modules() -> Result<()> {
let payload = tempfile::tempdir()?;
std::fs::create_dir_all(payload.path().join("usr/sbin"))?;
std::fs::write(payload.path().join(GRUB_BIN), "grub2-install")?;
let modules = payload.path().join(GRUB_MODULES);
std::fs::create_dir_all(&modules)?;
std::fs::write(modules.join("kernel.img"), "kernel")?;
let fonts = modules.join("fonts");
std::fs::create_dir_all(&fonts)?;
std::fs::write(fonts.join("unicode.pf2"), "font")?;
let tree = grub_filetree(payload.path())?;
assert!(tree.children.contains_key(GRUB_BIN));
assert!(tree
.children
.contains_key(&format!("{GRUB_MODULES}/kernel.img")));
std::fs::write(
payload.path().join(GRUB_MODULES).join("kernel.img"),
"kernel new",
)?;
let changed = grub_filetree(payload.path())?;
assert!(!tree.is_content_eq(&changed));
let tree = grub_filetree(payload.path())?;
assert!(tree
.children
.contains_key(&format!("{GRUB_MODULES}/fonts/unicode.pf2")));
std::fs::write(fonts.join("unicode.pf2"), "font new")?;
let changed = grub_filetree(payload.path())?;
assert!(!tree.is_content_eq(&changed));
Ok(())
}
#[test]
fn test_grub_filetree_refuses_symlinks_in_modules() -> Result<()> {
let payload = tempfile::tempdir()?;
std::fs::create_dir_all(payload.path().join("usr/sbin"))?;
std::fs::write(payload.path().join(GRUB_BIN), "grub2-install")?;
let modules = payload.path().join(GRUB_MODULES);
std::fs::create_dir_all(&modules)?;
std::os::unix::fs::symlink("target", modules.join("link"))?;
let err = grub_filetree(payload.path())
.expect_err("a symlink in the modules directory should be refused");
assert!(format!("{err:#}").contains("Unsupported file type"));
Ok(())
}
}