Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions crates/lib/src/bootc_composefs/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{
grub_menuconfig::{parse_grub_menuentry_file, MenuEntry},
},
spec::{BootEntry, BootOrder, Host, HostSpec, ImageReference, ImageStatus},
utils::{read_uefi_var, EfiError},
};

use std::str::FromStr;
Expand All @@ -32,7 +33,6 @@ use crate::composefs_consts::{
COMPOSEFS_STAGED_DEPLOYMENT_FNAME, COMPOSEFS_TRANSIENT_STATE_DIR, ORIGIN_KEY_BOOT,
ORIGIN_KEY_BOOT_TYPE, STATE_DIR_RELATIVE,
};
use crate::install::EFIVARFS;
use crate::spec::Bootloader;

/// A parsed composefs command line
Expand Down Expand Up @@ -153,16 +153,9 @@ async fn get_container_manifest_and_config(

#[context("Getting bootloader")]
fn get_bootloader() -> Result<Bootloader> {
let efivarfs = match Dir::open_ambient_dir(EFIVARFS, ambient_authority()) {
Ok(dir) => dir,
// Most likely using BIOS
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Bootloader::Grub),
Err(e) => Err(e).context(format!("Opening {EFIVARFS}"))?,
};

const EFI_LOADER_INFO: &str = "LoaderInfo-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f";

match efivarfs.read_to_string(EFI_LOADER_INFO) {
match read_uefi_var(EFI_LOADER_INFO) {
Ok(loader) => {
if loader.to_lowercase().contains("systemd-boot") {
return Ok(Bootloader::Systemd);
Expand All @@ -171,9 +164,12 @@ fn get_bootloader() -> Result<Bootloader> {
return Ok(Bootloader::Grub);
}

Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Bootloader::Grub),
Err(efi_error) => match efi_error {
EfiError::SystemNotUEFI => return Ok(Bootloader::Grub),
EfiError::MissingVar => return Ok(Bootloader::Grub),
Comment on lines +168 to +169
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The match arms for EfiError::SystemNotUEFI and EfiError::MissingVar have the same logic. They can be combined into a single arm using the | operator for conciseness and better readability.

Suggested change
EfiError::SystemNotUEFI => return Ok(Bootloader::Grub),
EfiError::MissingVar => return Ok(Bootloader::Grub),
EfiError::SystemNotUEFI | EfiError::MissingVar => return Ok(Bootloader::Grub),


Err(e) => Err(e).context(format!("Opening {EFI_LOADER_INFO}"))?,
e => return Err(anyhow::anyhow!("Failed to read EfiLoaderInfo: {e:?}")),
},
}
}

Expand Down
57 changes: 57 additions & 0 deletions crates/lib/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,63 @@ pub(crate) fn digested_pullspec(image: &str, digest: &str) -> String {
format!("{image}@{digest}")
}

#[cfg(feature = "composefs-backend")]
#[derive(Debug)]
pub enum EfiError {
SystemNotUEFI,
MissingVar,
#[allow(dead_code)]
InvalidData(&'static str),
#[allow(dead_code)]
Io(std::io::Error),
Comment on lines +196 to +199
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The #[allow(dead_code)] attributes on the InvalidData and Io variants of EfiError are unnecessary. The InvalidData variant is used in read_uefi_var, and the Io variant is used via the From<std::io::Error> implementation and the ? operator. Removing these attributes will make the code cleaner and avoid suppressing potential future warnings about genuinely unused code.

Suggested change
#[allow(dead_code)]
InvalidData(&'static str),
#[allow(dead_code)]
Io(std::io::Error),
InvalidData(&'static str),
Io(std::io::Error),

}

#[cfg(feature = "composefs-backend")]
impl From<std::io::Error> for EfiError {
fn from(e: std::io::Error) -> Self {
EfiError::Io(e)
}
}

#[cfg(feature = "composefs-backend")]
pub fn read_uefi_var(var_name: &str) -> Result<String, EfiError> {
use crate::install::EFIVARFS;
use cap_std_ext::cap_std::ambient_authority;

let efivarfs = match Dir::open_ambient_dir(EFIVARFS, ambient_authority()) {
Ok(dir) => dir,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(EfiError::SystemNotUEFI),
Err(e) => Err(e)?,
};

match efivarfs.read(var_name) {
Ok(loader_bytes) => {
if loader_bytes.len() % 2 != 0 {
return Err(EfiError::InvalidData(
"EFI var length is not valid UTF-16 LE",
));
}

// EFI vars are UTF-16 LE
let loader_u16_bytes: Vec<u16> = loader_bytes
.chunks_exact(2)
.map(|x| u16::from_le_bytes([x[0], x[1]]))
.collect();

let loader = String::from_utf16(&loader_u16_bytes)
.map_err(|_| EfiError::InvalidData("EFI var is not UTF-16"))?;

return Ok(loader);
}

Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did coreos/cap-std-ext#78 motivated by this btw

return Err(EfiError::MissingVar);
}

Err(e) => Err(e)?,
}
}
Comment on lines +210 to +246
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The read_uefi_var function can be refactored to be more idiomatic and readable by using the ? operator for error handling and avoiding multiple match statements with early returns. This improves maintainability.

pub fn read_uefi_var(var_name: &str) -> Result<String, EfiError> {
    use crate::install::EFIVARFS;
    use cap_std_ext::cap_std::ambient_authority;

    let efivarfs = Dir::open_ambient_dir(EFIVARFS, ambient_authority()).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            EfiError::SystemNotUEFI
        } else {
            e.into()
        }
    })?;

    let loader_bytes = efivarfs.read(var_name).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            EfiError::MissingVar
        } else {
            e.into()
        }
    })?;

    if loader_bytes.len() % 2 != 0 {
        return Err(EfiError::InvalidData(
            "EFI var length is not valid UTF-16 LE",
        ));
    }

    // EFI vars are UTF-16 LE
    let loader_u16_bytes: Vec<u16> = loader_bytes
        .chunks_exact(2)
        .map(|x| u16::from_le_bytes([x[0], x[1]]))
        .collect();

    String::from_utf16(&loader_u16_bytes)
        .map_err(|_| EfiError::InvalidData("EFI var is not UTF-16"))
}


/// Computes a relative path from `from` to `to`.
///
/// Both `from` and `to` must be absolute paths.
Expand Down