//! Boot Loader Specification (BLS) entry parsing and root-selection planning. //! //! systemd-boot reads `/loader/entries/*.conf` on the ESP. A rollback must edit //! those entries, not just the Btrfs default subvolume: the kernel command line //! carries an explicit `rootflags=subvol=...`, which overrides the default. //! These are pure functions so the exact text written into the ESP is testable //! without a real disk. /// One BLS entry, preserving unknown keys verbatim. #[derive(Debug, Clone, PartialEq, Eq)] pub struct BlsEntry { pub file_name: String, pub title: String, pub linux: String, pub initrds: Vec, pub options: String, pub extra: Vec, } impl BlsEntry { /// Parse a BLS entry. Returns `None` when there is no `linux` line, which /// means it is not a bootable kernel entry. pub fn parse(file_name: &str, text: &str) -> Option { let mut title = String::new(); let mut linux = String::new(); let mut initrds = Vec::new(); let mut options = String::new(); let mut extra = Vec::new(); for line in text.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { continue; } let (key, value) = match trimmed.split_once(char::is_whitespace) { Some((k, v)) => (k, v.trim()), None => (trimmed, ""), }; match key { "title" => title = value.to_string(), "linux" => linux = value.to_string(), "initrd" => initrds.push(value.to_string()), "options" => options = value.to_string(), _ => extra.push(trimmed.to_string()), } } if linux.is_empty() { return None; } Some(Self { file_name: file_name.to_string(), title, linux, initrds, options, extra, }) } /// Render back to BLS text. pub fn render(&self) -> String { let mut out = String::new(); if !self.title.is_empty() { out.push_str(&format!("title {}\n", self.title)); } out.push_str(&format!("linux {}\n", self.linux)); for initrd in &self.initrds { out.push_str(&format!("initrd {initrd}\n")); } if !self.options.trim().is_empty() { out.push_str(&format!("options {}\n", self.options.trim())); } for line in &self.extra { out.push_str(line); out.push('\n'); } out } /// The kernel version implied by the `linux` path /// (`///linux`). pub fn kernel_version(&self) -> Option { let parts: Vec<&str> = self.linux.split('/').filter(|p| !p.is_empty()).collect(); // The segment immediately before the kernel file name is the version. let last = parts.last()?; if *last == "linux" || last.ends_with("vmlinuz") { parts .get(parts.len().checked_sub(2)?) .map(|s| s.to_string()) } else { None } } /// Return a copy whose `options` selects a different root subvolume. pub fn with_root_subvol(&self, subvol: &str) -> Result { let mut entry = self.clone(); entry.options = replace_root_subvol(&self.options, subvol)?; Ok(entry) } /// Return a copy with an extra option appended (e.g. `systemd.unit=`). pub fn with_option(&self, extra: &str) -> Self { let mut entry = self.clone(); entry.options = format!("{} {}", entry.options.trim(), extra) .trim() .to_string(); entry } pub fn with_title(&self, title: &str) -> Self { let mut entry = self.clone(); entry.title = title.to_string(); entry } /// Return a copy whose `sort-key` is `key`. Used to keep the recovery entry /// sorted after the normal kernel entries: the specification's final /// tie-break is by file name in decreasing order, so a recovery entry that /// inherits the kernel's sort-key can otherwise sort first (and, with /// `default *`, boot the installed system into recovery). pub fn with_sort_key(&self, key: &str) -> Self { let mut entry = self.clone(); entry .extra .retain(|line| !line.trim_start().starts_with("sort-key")); entry.extra.push(format!("sort-key {key}")); entry } } /// Replace the `rootflags=subvol=` component of a kernel command line. /// /// The reader must not assume the Btrfs default subvolume changes what is /// mounted: an explicit `subvol=` argument always wins, so rollback edits it. pub fn replace_root_subvol(options: &str, subvol: &str) -> Result { if subvol.is_empty() || subvol.contains(char::is_whitespace) || subvol.contains(',') { return Err(format!("invalid root subvolume name: {subvol}")); } let mut replaced = false; let mut out: Vec = Vec::new(); for token in options.split_whitespace() { if let Some(rest) = token.strip_prefix("rootflags=") { let mut parts: Vec = Vec::new(); for part in rest.split(',') { if part.starts_with("subvol=") { parts.push(format!("subvol={subvol}")); replaced = true; } else if !part.is_empty() { parts.push(part.to_string()); } } if !parts.iter().any(|p| p.starts_with("subvol=")) { parts.push(format!("subvol={subvol}")); replaced = true; } out.push(format!("rootflags={}", parts.join(","))); } else if token == "subvol=" { out.push(format!("subvol={subvol}")); replaced = true; } else { out.push(token.to_string()); } } if !replaced { return Err("command line has no rootflags=subvol= to replace".into()); } Ok(out.join(" ")) } /// Compare kernel versions as numeric components (e.g. `6.12.9` > `6.12.10`? /// no: `6.12.10` > `6.12.9` because components are compared numerically). pub fn version_key(version: &str) -> Vec { version .split(|c: char| !c.is_ascii_digit()) .filter(|s| !s.is_empty()) .filter_map(|s| s.parse::().ok()) .collect() } /// The newest BLS entry whose kernel version is present in `available` /// (the restored root's `/lib/modules`), so a rolled-back root boots a kernel /// that still has matching modules. pub fn choose_entry_for_versions<'a>( entries: &'a [BlsEntry], available: &[String], ) -> Option<&'a BlsEntry> { let mut best: Option<&BlsEntry> = None; for entry in entries { let Some(version) = entry.kernel_version() else { continue; }; if !available.iter().any(|v| v == &version) { continue; } let better = match best { None => true, Some(current) => { let a = version_key(&version); let b = current .kernel_version() .map(|v| version_key(&v)) .unwrap_or_default(); a > b } }; if better { best = Some(entry); } } best } /// The kernel versions present under a restored root's `lib/modules` listing. pub fn kernel_versions_from_module_dirs(names: &[String]) -> Vec { names .iter() .filter(|n| { !n.is_empty() && n.chars() .next() .map(|c| c.is_ascii_digit()) .unwrap_or(false) }) .cloned() .collect() } /// Formats a BLS filename with boot counting attempts according to systemd-boot specification: /// `+.conf` (or `.conf` if no counter). pub fn format_bls_filename(stem: &str, tries: Option) -> String { let clean_stem = stem.strip_suffix(".conf").unwrap_or(stem); let (base, _) = parse_bls_filename(clean_stem); match tries { Some(t) => format!("{base}+{t}.conf"), None => format!("{base}.conf"), } } /// Parses a BLS filename into its base stem and optional remaining tries. /// Follows the Boot Loader Specification: `+[,].conf` /// E.g., `phoebus+3.conf` -> ("phoebus", Some(3)) /// E.g., `phoebus+2,1.conf` -> ("phoebus", Some(2)) /// E.g., `phoebus.conf` -> ("phoebus", None) pub fn parse_bls_filename(filename: &str) -> (String, Option) { let name = filename.strip_suffix(".conf").unwrap_or(filename); if let Some((stem, rest)) = name.split_once('+') { let tries_str = rest.split(',').next().unwrap_or(rest); if let Ok(tries) = tries_str.parse::() { return (stem.to_string(), Some(tries)); } } (name.to_string(), None) } #[cfg(test)] mod tests { use super::*; const ENTRY: &str = "title Gentoo Linux\n\ linux /abcd/6.12.9/linux\n\ initrd /abcd/6.12.9/initrd\n\ options rd.luks.name=u=cryptroot root=/dev/mapper/cryptroot rootfstype=btrfs rootflags=subvol=@ rw quiet\n"; #[test] fn parses_and_renders_roundtrip() { let entry = BlsEntry::parse("abcd-6.12.9.conf", ENTRY).unwrap(); assert_eq!(entry.kernel_version().as_deref(), Some("6.12.9")); let rendered = entry.render(); assert!(rendered.contains("title Gentoo Linux")); assert!(rendered.contains("linux /abcd/6.12.9/linux")); assert!(rendered.contains("initrd /abcd/6.12.9/initrd")); assert!(BlsEntry::parse("x.conf", "# only a comment\n").is_none()); } #[test] fn replaces_the_explicit_root_subvolume() { let entry = BlsEntry::parse("e.conf", ENTRY).unwrap(); let updated = entry.with_root_subvol("@restore-20260101T000000").unwrap(); assert!(updated .options .contains("rootflags=subvol=@restore-20260101T000000")); assert!(!updated.options.contains("subvol=@ ")); // Other rootflags are preserved. assert!(updated.options.contains("rootfstype=btrfs")); } #[test] fn with_sort_key_replaces_an_inherited_key() { let with_key = "title Gentoo Linux\n\ linux /abcd/6.12.9/linux\n\ sort-key gentoo\n\ options root=/dev/x\n"; let entry = BlsEntry::parse("abcd-6.12.9.conf", with_key).unwrap(); let recovery = entry.with_sort_key("zzzz-phoebus-recovery"); let rendered = recovery.render(); assert!(rendered.contains("sort-key zzzz-phoebus-recovery")); assert!(!rendered.contains("sort-key gentoo")); // The kernel sort-key sorts before the recovery one (A-Z increasing). assert!("gentoo" < "zzzz-phoebus-recovery"); } #[test] fn replace_handles_missing_subvol_and_rejects_empty() { assert!(replace_root_subvol("root=/dev/x rootflags=rw", "@new") .unwrap() .contains("subvol=@new")); assert!(replace_root_subvol("root=/dev/x", "@new").is_err()); assert!(replace_root_subvol("rootflags=subvol=@", "").is_err()); assert!(replace_root_subvol("rootflags=subvol=@", "bad name").is_err()); } #[test] fn chooses_the_newest_entry_with_matching_modules() { let a = BlsEntry::parse( "a.conf", "title A\nlinux /id/6.12.9/linux\noptions rootflags=subvol=@\n", ) .unwrap(); let b = BlsEntry::parse( "b.conf", "title B\nlinux /id/6.12.10/linux\noptions rootflags=subvol=@\n", ) .unwrap(); let c = BlsEntry::parse( "c.conf", "title C\nlinux /id/6.13.1/linux\noptions rootflags=subvol=@\n", ) .unwrap(); let entries = vec![a, b, c]; let modules = vec!["6.12.9".to_string(), "6.12.10".to_string()]; let chosen = choose_entry_for_versions(&entries, &modules).unwrap(); assert_eq!(chosen.title, "B"); // No matching modules at all -> refuse to select. assert!(choose_entry_for_versions(&entries, &["5.0.0".to_string()]).is_none()); } #[test] fn module_dir_filter_ignores_non_versions() { let names = vec![ "6.12.9".to_string(), "modules.order".to_string(), "6.12.9-gentoo".to_string(), ]; let versions = kernel_versions_from_module_dirs(&names); assert!(versions.contains(&"6.12.9".to_string())); assert!(versions.contains(&"6.12.9-gentoo".to_string())); assert!(!versions.iter().any(|v| v == "modules.order")); } #[test] fn bls_filename_counter_formatting_and_parsing() { assert_eq!(format_bls_filename("phoebus", Some(3)), "phoebus+3.conf"); assert_eq!( format_bls_filename("phoebus.conf", Some(3)), "phoebus+3.conf" ); assert_eq!( format_bls_filename("phoebus+1.conf", Some(3)), "phoebus+3.conf" ); assert_eq!(format_bls_filename("phoebus", None), "phoebus.conf"); assert_eq!(format_bls_filename("phoebus+3.conf", None), "phoebus.conf"); assert_eq!( parse_bls_filename("phoebus+3.conf"), ("phoebus".to_string(), Some(3)) ); assert_eq!( parse_bls_filename("phoebus+2,1.conf"), ("phoebus".to_string(), Some(2)) ); assert_eq!( parse_bls_filename("phoebus.conf"), ("phoebus".to_string(), None) ); assert_eq!( parse_bls_filename("phoebus-recovery.conf"), ("phoebus-recovery".to_string(), None) ); } }