-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathboot.rs
More file actions
1474 lines (1226 loc) · 49.7 KB
/
boot.rs
File metadata and controls
1474 lines (1226 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Composefs boot setup and configuration.
//!
//! This module handles setting up boot entries for composefs-based deployments,
//! including generating BLS (Boot Loader Specification) entries, copying kernel/initrd
//! files, managing UKI (Unified Kernel Images), and configuring the ESP (EFI System
//! Partition).
//!
//! ## Boot Ordering
//!
//! A critical aspect of this module is boot entry ordering, which must work correctly
//! across both Grub and systemd-boot bootloaders despite their fundamentally different
//! sorting behaviors.
//!
//! ## Critical Context: Grub's Filename Parsing
//!
//! **Grub does NOT read BLS fields** - it parses the filename as an RPM package name!
//! See: <https://github.com/ostreedev/ostree/issues/2961>
//!
//! Grub's `split_package_string()` parsing algorithm:
//! 1. Strip `.conf` suffix
//! 2. Find LAST `-` → extract **release** field
//! 3. Find SECOND-TO-LAST `-` → extract **version** field
//! 4. Remainder → **name** field
//!
//! Example: `kernel-5.14.0-362.fc38.conf`
//! - name: `kernel`
//! - version: `5.14.0`
//! - release: `362.fc38`
//!
//! **Critical:** Grub sorts by (name, version, release) in DESCENDING order.
//!
//! ## Bootloader Differences
//!
//! ### Grub
//! - Ignores BLS sort-key field completely
//! - Parses filename to extract name-version-release
//! - Sorts by (name, version, release) DESCENDING
//! - Any `-` in name/version gets incorrectly split
//!
//! ### Systemd-boot
//! - Reads BLS sort-key field
//! - Sorts by sort-key ASCENDING (A→Z, 0→9)
//! - Filename is mostly irrelevant
//!
//! ## Implementation Strategy
//!
//! **Filenames** (for Grub's RPM-style parsing and descending sort):
//! - Format: `bootc_{os_id}-{version}-{priority}.conf`
//! - Replace `-` with `_` in os_id to prevent mis-parsing
//! - Primary: `bootc_fedora-41.20251125.0-1.conf` → (name=bootc_fedora, version=41.20251125.0, release=1)
//! - Secondary: `bootc_fedora-41.20251124.0-0.conf` → (name=bootc_fedora, version=41.20251124.0, release=0)
//! - Grub sorts: Primary (release=1) > Secondary (release=0) when versions equal
//!
//! **Sort-keys** (for systemd-boot's ascending sort):
//! - Primary: `bootc-{os_id}-0` (lower value, sorts first)
//! - Secondary: `bootc-{os_id}-1` (higher value, sorts second)
//!
//! ## Boot Entry Ordering
//!
//! After an upgrade, both bootloaders show:
//! 1. **Primary**: New/upgraded deployment (default boot target)
//! 2. **Secondary**: Currently booted deployment (rollback option)
use std::ffi::OsStr;
use std::fs::create_dir_all;
use std::io::Write;
use std::path::Path;
use anyhow::{Context, Result, anyhow, bail};
use bootc_kernel_cmdline::utf8::{Cmdline, Parameter, ParameterKey};
use bootc_mount::tempmount::TempMount;
use camino::{Utf8Path, Utf8PathBuf};
use cap_std_ext::{
cap_std::{ambient_authority, fs::Dir},
dirext::CapStdExtDirExt,
};
use cfsctl::composefs;
use cfsctl::composefs_boot;
use cfsctl::composefs_oci;
use clap::ValueEnum;
use composefs::fs::read_file;
use composefs::fsverity::{FsVerityHashValue, Sha512HashValue};
use composefs::tree::RegularFile;
use composefs_boot::BootOps;
use composefs_boot::bootloader::{
BootEntry as ComposefsBootEntry, EFI_ADDON_DIR_EXT, EFI_ADDON_FILE_EXT, EFI_EXT, PEType,
UsrLibModulesVmlinuz,
};
use composefs_boot::{cmdline::get_cmdline_composefs, os_release::OsReleaseInfo, uki};
use composefs_oci::OciDigest;
use composefs_oci::image::create_filesystem as create_composefs_filesystem;
use fn_error_context::context;
use rustix::{mount::MountFlags, path::Arg};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::{
bootc_composefs::repo::get_imgref,
composefs_consts::{TYPE1_ENT_PATH, TYPE1_ENT_PATH_STAGED},
};
use crate::{
bootc_composefs::repo::open_composefs_repo,
store::{ComposefsFilesystem, Storage},
};
use crate::{
bootc_composefs::state::{get_booted_bls, write_composefs_state},
composefs_consts::TYPE1_BOOT_DIR_PREFIX,
};
use crate::{bootc_composefs::status::ComposefsCmdline, task::Task};
use crate::{
bootc_composefs::status::get_container_manifest_and_config, bootc_kargs::compute_new_kargs,
};
use crate::{bootc_composefs::status::get_sorted_grub_uki_boot_entries, install::PostFetchState};
use crate::{
composefs_consts::UKI_NAME_PREFIX,
parsers::bls_config::{BLSConfig, BLSConfigType},
};
use crate::{
composefs_consts::{
BOOT_LOADER_ENTRIES, ORIGIN_KEY_BOOT, ORIGIN_KEY_BOOT_DIGEST, STAGED_BOOT_LOADER_ENTRIES,
STATE_DIR_ABS, USER_CFG, USER_CFG_STAGED,
},
spec::{Bootloader, Host},
};
use crate::{parsers::grub_menuconfig::MenuEntry, store::BootedComposefs};
use crate::install::{RootSetup, State};
/// Contains the EFP's filesystem UUID. Used by grub
pub(crate) const EFI_UUID_FILE: &str = "efiuuid.cfg";
/// The EFI Linux directory
pub(crate) const EFI_LINUX: &str = "EFI/Linux";
/// Timeout for systemd-boot bootloader menu
const SYSTEMD_TIMEOUT: &str = "timeout 5";
const SYSTEMD_LOADER_CONF_PATH: &str = "loader/loader.conf";
pub(crate) const INITRD: &str = "initrd";
pub(crate) const VMLINUZ: &str = "vmlinuz";
const BOOTC_AUTOENROLL_PATH: &str = "usr/lib/bootc/install/secureboot-keys";
const AUTH_EXT: &str = "auth";
/// We want to be able to control the ordering of UKIs so we put them in a directory that's not the
/// directory specified by the BLS spec. We do this because we want systemd-boot to only look at
/// our config files and not show the actual UKIs in the bootloader menu
/// This is relative to the ESP
pub(crate) const BOOTC_UKI_DIR: &str = "EFI/Linux/bootc";
pub(crate) enum BootSetupType<'a> {
/// For initial setup, i.e. install to-disk
Setup(
(
&'a RootSetup,
&'a State,
&'a PostFetchState,
&'a ComposefsFilesystem,
),
),
/// For `bootc upgrade`
Upgrade(
(
&'a Storage,
&'a BootedComposefs,
&'a ComposefsFilesystem,
&'a Host,
),
),
}
#[derive(
ValueEnum, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema,
)]
pub enum BootType {
#[default]
Bls,
Uki,
}
impl ::std::fmt::Display for BootType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
BootType::Bls => "bls",
BootType::Uki => "uki",
};
write!(f, "{}", s)
}
}
impl TryFrom<&str> for BootType {
type Error = anyhow::Error;
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
match value {
"bls" => Ok(Self::Bls),
"uki" => Ok(Self::Uki),
unrecognized => Err(anyhow::anyhow!(
"Unrecognized boot option: '{unrecognized}'"
)),
}
}
}
impl From<&ComposefsBootEntry<Sha512HashValue>> for BootType {
fn from(entry: &ComposefsBootEntry<Sha512HashValue>) -> Self {
match entry {
ComposefsBootEntry::Type1(..) => Self::Bls,
ComposefsBootEntry::Type2(..) => Self::Uki,
ComposefsBootEntry::UsrLibModulesVmLinuz(..) => Self::Bls,
}
}
}
/// Returns the beginning of the grub2/user.cfg file
/// where we source a file containing the ESPs filesystem UUID
pub(crate) fn get_efi_uuid_source() -> String {
format!(
r#"
if [ -f ${{config_directory}}/{EFI_UUID_FILE} ]; then
source ${{config_directory}}/{EFI_UUID_FILE}
fi
"#
)
}
/// Mount the ESP from the provided device
pub fn mount_esp(device: &str) -> Result<TempMount> {
let flags = MountFlags::NOEXEC | MountFlags::NOSUID;
TempMount::mount_dev(device, "vfat", flags, Some(c"fmask=0177,dmask=0077"))
}
/// Filename release field for primary (new/upgraded) entry.
/// Grub parses this as the "release" field and sorts descending, so "1" > "0".
pub(crate) const FILENAME_PRIORITY_PRIMARY: &str = "1";
/// Filename release field for secondary (currently booted) entry.
pub(crate) const FILENAME_PRIORITY_SECONDARY: &str = "0";
/// Sort-key priority for primary (new/upgraded) entry.
/// Systemd-boot sorts by sort-key in ascending order, so "0" appears before "1".
pub(crate) const SORTKEY_PRIORITY_PRIMARY: &str = "0";
/// Sort-key priority for secondary (currently booted) entry.
pub(crate) const SORTKEY_PRIORITY_SECONDARY: &str = "1";
/// Generate BLS Type 1 entry filename compatible with Grub's RPM-style parsing.
///
/// Format: `bootc_{os_id}-{version}-{priority}.conf`
///
/// Grub parses this as:
/// - name: `bootc_{os_id}` (hyphens in os_id replaced with underscores)
/// - version: `{version}`
/// - release: `{priority}`
///
/// The underscore replacement prevents Grub from mis-parsing os_id values
/// containing hyphens (e.g., "fedora-coreos" → "fedora_coreos").
pub fn type1_entry_conf_file_name(
os_id: &str,
version: impl std::fmt::Display,
priority: &str,
) -> String {
let os_id_safe = os_id.replace('-', "_");
format!("bootc_{os_id_safe}-{version}-{priority}.conf")
}
/// Generate sort key for the primary (new/upgraded) boot entry.
/// Format: bootc-{id}-0
/// Systemd-boot sorts ascending by sort-key, so "0" comes first.
/// Grub ignores sort-key and uses filename/version ordering.
pub(crate) fn primary_sort_key(os_id: &str) -> String {
format!("bootc-{os_id}-{SORTKEY_PRIORITY_PRIMARY}")
}
/// Generate sort key for the secondary (currently booted) boot entry.
/// Format: bootc-{id}-1
pub(crate) fn secondary_sort_key(os_id: &str) -> String {
format!("bootc-{os_id}-{SORTKEY_PRIORITY_SECONDARY}")
}
/// Returns the name of the directory where we store Type1 boot entries
pub(crate) fn get_type1_dir_name(depl_verity: &str) -> String {
format!("{TYPE1_BOOT_DIR_PREFIX}{depl_verity}")
}
/// Returns the name of a UKI given verity digest
pub(crate) fn get_uki_name(depl_verity: &str) -> String {
format!("{UKI_NAME_PREFIX}{depl_verity}{EFI_EXT}")
}
/// Returns the name of a UKI Addon directory given verity digest
pub(crate) fn get_uki_addon_dir_name(depl_verity: &str) -> String {
format!("{UKI_NAME_PREFIX}{depl_verity}{EFI_ADDON_DIR_EXT}")
}
#[allow(dead_code)]
/// Returns the name of a UKI Addon given verity digest
pub(crate) fn get_uki_addon_file_name(depl_verity: &str) -> String {
format!("{UKI_NAME_PREFIX}{depl_verity}{EFI_ADDON_FILE_EXT}")
}
/// Compute SHA256Sum of VMlinuz + Initrd
///
/// # Arguments
/// * entry - BootEntry containing VMlinuz and Initrd
/// * repo - The composefs repository
#[context("Computing boot digest")]
fn compute_boot_digest(
entry: &UsrLibModulesVmlinuz<Sha512HashValue>,
repo: &crate::store::ComposefsRepository,
) -> Result<String> {
let vmlinuz = read_file(&entry.vmlinuz, &repo).context("Reading vmlinuz")?;
let Some(initramfs) = &entry.initramfs else {
anyhow::bail!("initramfs not found");
};
let initramfs = read_file(initramfs, &repo).context("Reading intird")?;
let mut hasher = openssl::hash::Hasher::new(openssl::hash::MessageDigest::sha256())
.context("Creating hasher")?;
hasher.update(&vmlinuz).context("hashing vmlinuz")?;
hasher.update(&initramfs).context("hashing initrd")?;
let digest: &[u8] = &hasher.finish().context("Finishing digest")?;
Ok(hex::encode(digest))
}
/// Compute SHA256Sum of .linux + .initrd section of the UKI
///
/// # Arguments
/// * entry - BootEntry containing VMlinuz and Initrd
/// * repo - The composefs repository
#[context("Computing boot digest")]
pub(crate) fn compute_boot_digest_uki(uki: &[u8]) -> Result<String> {
let vmlinuz =
uki::get_section(uki, ".linux").ok_or_else(|| anyhow::anyhow!(".linux not present"))??;
let initramfs = uki::get_section(uki, ".initrd")
.ok_or_else(|| anyhow::anyhow!(".initrd not present"))??;
let mut hasher = openssl::hash::Hasher::new(openssl::hash::MessageDigest::sha256())
.context("Creating hasher")?;
hasher.update(&vmlinuz).context("hashing vmlinuz")?;
hasher.update(&initramfs).context("hashing initrd")?;
let digest: &[u8] = &hasher.finish().context("Finishing digest")?;
Ok(hex::encode(digest))
}
/// Given the SHA256 sum of current VMlinuz + Initrd combo, find boot entry with the same SHA256Sum
///
/// # Returns
/// Returns the verity of all deployments that have a boot digest same as the one passed in
#[context("Checking boot entry duplicates")]
pub(crate) fn find_vmlinuz_initrd_duplicates(digest: &str) -> Result<Option<Vec<String>>> {
let deployments = Dir::open_ambient_dir(STATE_DIR_ABS, ambient_authority());
let deployments = match deployments {
Ok(d) => d,
// The first ever deployment
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => anyhow::bail!(e),
};
let mut symlink_to: Option<Vec<String>> = None;
for depl in deployments.entries()? {
let depl = depl?;
let depl_file_name = depl.file_name();
let depl_file_name = depl_file_name.as_str()?;
let config = depl
.open_dir()
.with_context(|| format!("Opening {depl_file_name}"))?
.read_to_string(format!("{depl_file_name}.origin"))
.context("Reading origin file")?;
let ini = tini::Ini::from_string(&config)
.with_context(|| format!("Failed to parse file {depl_file_name}.origin as ini"))?;
match ini.get::<String>(ORIGIN_KEY_BOOT, ORIGIN_KEY_BOOT_DIGEST) {
Some(hash) => {
if hash == digest {
match symlink_to {
Some(ref mut prev) => prev.push(depl_file_name.to_string()),
None => symlink_to = Some(vec![depl_file_name.to_string()]),
}
}
}
// No SHASum recorded in origin file
// `symlink_to` is already none, but being explicit here
None => symlink_to = None,
};
}
Ok(symlink_to)
}
#[context("Writing BLS entries to disk")]
fn write_bls_boot_entries_to_disk(
boot_dir: &Utf8PathBuf,
deployment_id: &Sha512HashValue,
entry: &UsrLibModulesVmlinuz<Sha512HashValue>,
repo: &crate::store::ComposefsRepository,
) -> Result<()> {
let dir_name = get_type1_dir_name(&deployment_id.to_hex());
// Write the initrd and vmlinuz at /boot/composefs-<id>/
let path = boot_dir.join(&dir_name);
create_dir_all(&path)?;
let entries_dir = Dir::open_ambient_dir(&path, ambient_authority())
.with_context(|| format!("Opening {path}"))?;
entries_dir
.atomic_write(
VMLINUZ,
read_file(&entry.vmlinuz, &repo).context("Reading vmlinuz")?,
)
.context("Writing vmlinuz to path")?;
let Some(initramfs) = &entry.initramfs else {
anyhow::bail!("initramfs not found");
};
entries_dir
.atomic_write(
INITRD,
read_file(initramfs, &repo).context("Reading initrd")?,
)
.context("Writing initrd to path")?;
// Can't call fsync on O_PATH fds, so re-open it as a non O_PATH fd
let owned_fd = entries_dir
.reopen_as_ownedfd()
.context("Reopen as owned fd")?;
rustix::fs::fsync(owned_fd).context("fsync")?;
Ok(())
}
/// Parses /usr/lib/os-release and returns (id, title, version)
fn parse_os_release(
fs: &crate::store::ComposefsFilesystem,
repo: &crate::store::ComposefsRepository,
) -> Result<Option<(String, Option<String>, Option<String>)>> {
// Every update should have its own /usr/lib/os-release
let (dir, fname) = fs
.root
.split(OsStr::new("/usr/lib/os-release"))
.context("Getting /usr/lib/os-release")?;
let os_release = dir
.get_file_opt(fname)
.context("Getting /usr/lib/os-release")?;
let Some(os_rel_file) = os_release else {
return Ok(None);
};
let file_contents = match read_file(os_rel_file, repo) {
Ok(c) => c,
Err(e) => {
tracing::warn!("Could not read /usr/lib/os-release: {e:?}");
return Ok(None);
}
};
let file_contents = match std::str::from_utf8(&file_contents) {
Ok(c) => c,
Err(e) => {
tracing::warn!("/usr/lib/os-release did not have valid UTF-8: {e}");
return Ok(None);
}
};
let parsed = OsReleaseInfo::parse(file_contents);
let os_id = parsed
.get_value(&["ID"])
.unwrap_or_else(|| "bootc".to_string());
Ok(Some((
os_id,
parsed.get_pretty_name(),
parsed.get_version(),
)))
}
struct BLSEntryPath {
/// Where to write vmlinuz/initrd
entries_path: Utf8PathBuf,
/// The absolute path, with reference to the partition's root, where the vmlinuz/initrd are written to
abs_entries_path: Utf8PathBuf,
/// Where to write the .conf files
config_path: Utf8PathBuf,
}
/// Sets up and writes BLS entries and binaries (VMLinuz + Initrd) to disk
///
/// # Returns
/// Returns the SHA256Sum of VMLinuz + Initrd combo. Error if any
#[context("Setting up BLS boot")]
pub(crate) fn setup_composefs_bls_boot(
setup_type: BootSetupType,
repo: crate::store::ComposefsRepository,
id: &Sha512HashValue,
entry: &ComposefsBootEntry<Sha512HashValue>,
mounted_erofs: &Dir,
) -> Result<String> {
let id_hex = id.to_hex();
let (root_path, esp_device, mut cmdline_refs, fs, bootloader) = match setup_type {
BootSetupType::Setup((root_setup, state, postfetch, fs)) => {
// root_setup.kargs has [root=UUID=<UUID>, "rw"]
let mut cmdline_options = Cmdline::new();
cmdline_options.extend(&root_setup.kargs);
let composefs_cmdline =
ComposefsCmdline::build(&id_hex, state.composefs_options.allow_missing_verity);
cmdline_options.extend(&Cmdline::from(&composefs_cmdline.to_string()));
// Locate ESP partition device
let esp_part = root_setup.device_info.find_partition_of_esp()?;
(
root_setup.physical_root_path.clone(),
esp_part.path(),
cmdline_options,
fs,
postfetch.detected_bootloader.clone(),
)
}
BootSetupType::Upgrade((storage, booted_cfs, fs, host)) => {
let bootloader = host.require_composefs_booted()?.bootloader.clone();
let boot_dir = storage.require_boot_dir()?;
let current_cfg = get_booted_bls(&boot_dir, booted_cfs)?;
let mut cmdline = match current_cfg.cfg_type {
BLSConfigType::NonEFI { options, .. } => {
let options = options
.ok_or_else(|| anyhow::anyhow!("No 'options' found in BLS Config"))?;
Cmdline::from(options)
}
_ => anyhow::bail!("Found NonEFI config"),
};
// Copy all cmdline args, replacing only `composefs=`
let cfs_cmdline =
ComposefsCmdline::build(&id_hex, booted_cfs.cmdline.allow_missing_fsverity)
.to_string();
let param = Parameter::parse(&cfs_cmdline)
.context("Failed to create 'composefs=' parameter")?;
cmdline.add_or_modify(¶m);
// Locate ESP partition device
let root_dev =
bootc_blockdev::list_dev_by_dir(&storage.physical_root)?.require_single_root()?;
let esp_dev = root_dev.find_partition_of_esp()?;
(
Utf8PathBuf::from("/sysroot"),
esp_dev.path(),
cmdline,
fs,
bootloader,
)
}
};
// Remove "root=" from kernel cmdline as systemd-auto-gpt-generator should use DPS
// UUID
if bootloader == Bootloader::Systemd {
cmdline_refs.remove(&ParameterKey::from("root"));
}
let is_upgrade = matches!(setup_type, BootSetupType::Upgrade(..));
let current_root = if is_upgrade {
Some(&Dir::open_ambient_dir("/", ambient_authority()).context("Opening root")?)
} else {
None
};
compute_new_kargs(mounted_erofs, current_root, &mut cmdline_refs)?;
let (entry_paths, _tmpdir_guard) = match bootloader {
Bootloader::Grub => {
let root = Dir::open_ambient_dir(&root_path, ambient_authority())
.context("Opening root path")?;
// Grub wants the paths to be absolute against the mounted drive that the kernel +
// initrd live in
//
// If "boot" is a partition, we want the paths to be absolute to "/"
let entries_path = match root.is_mountpoint("boot")? {
Some(true) => "/",
// We can be fairly sure that the kernels we target support `statx`
Some(false) | None => "/boot",
};
(
BLSEntryPath {
entries_path: root_path.join("boot"),
config_path: root_path.join("boot"),
abs_entries_path: entries_path.into(),
},
None,
)
}
Bootloader::Systemd => {
let efi_mount = mount_esp(&esp_device).context("Mounting ESP")?;
let mounted_efi = Utf8PathBuf::from(efi_mount.dir.path().as_str()?);
let efi_linux_dir = mounted_efi.join(EFI_LINUX);
(
BLSEntryPath {
entries_path: efi_linux_dir,
config_path: mounted_efi.clone(),
abs_entries_path: Utf8PathBuf::from("/").join(EFI_LINUX),
},
Some(efi_mount),
)
}
Bootloader::None => unreachable!("Checked at install time"),
};
let (bls_config, boot_digest, os_id) = match &entry {
ComposefsBootEntry::Type1(..) => anyhow::bail!("Found Type1 entries in /boot"),
ComposefsBootEntry::Type2(..) => anyhow::bail!("Found UKI"),
ComposefsBootEntry::UsrLibModulesVmLinuz(usr_lib_modules_vmlinuz) => {
let boot_digest = compute_boot_digest(usr_lib_modules_vmlinuz, &repo)
.context("Computing boot digest")?;
let osrel = parse_os_release(fs, &repo)?;
let (os_id, title, version, sort_key) = match osrel {
Some((id_str, title_opt, version_opt)) => (
id_str.clone(),
title_opt.unwrap_or_else(|| id.to_hex()),
version_opt.unwrap_or_else(|| id.to_hex()),
primary_sort_key(&id_str),
),
None => {
let default_id = "bootc".to_string();
(
default_id.clone(),
id.to_hex(),
id.to_hex(),
primary_sort_key(&default_id),
)
}
};
let mut bls_config = BLSConfig::default();
let entries_dir = get_type1_dir_name(&id_hex);
bls_config
.with_title(title)
.with_version(version)
.with_sort_key(sort_key)
.with_cfg(BLSConfigType::NonEFI {
linux: entry_paths
.abs_entries_path
.join(&entries_dir)
.join(VMLINUZ),
initrd: vec![entry_paths.abs_entries_path.join(&entries_dir).join(INITRD)],
options: Some(cmdline_refs),
});
match find_vmlinuz_initrd_duplicates(&boot_digest)? {
Some(shared_entries) => {
// Multiple deployments could be using the same kernel + initrd, but there
// would be only one available
//
// Symlinking directories themselves would be better, but vfat does not support
// symlinks
let mut shared_entry: Option<String> = None;
let entries =
Dir::open_ambient_dir(entry_paths.entries_path, ambient_authority())
.context("Opening entries path")?
.entries_utf8()
.context("Getting dir entries")?;
for ent in entries {
let ent = ent?;
// We shouldn't error here as all our file names are UTF-8 compatible
let ent_name = ent.file_name()?;
let Some(entry_verity_part) = ent_name.strip_prefix(TYPE1_BOOT_DIR_PREFIX)
else {
// Not our directory
continue;
};
if shared_entries
.iter()
.any(|shared_ent| shared_ent == entry_verity_part)
{
shared_entry = Some(ent_name);
break;
}
}
let shared_entry = shared_entry
.ok_or_else(|| anyhow::anyhow!("Shared boot binaries not found"))?;
match bls_config.cfg_type {
BLSConfigType::NonEFI {
ref mut linux,
ref mut initrd,
..
} => {
*linux = entry_paths
.abs_entries_path
.join(&shared_entry)
.join(VMLINUZ);
*initrd = vec![
entry_paths
.abs_entries_path
.join(&shared_entry)
.join(INITRD),
];
}
_ => unreachable!(),
};
}
None => {
write_bls_boot_entries_to_disk(
&entry_paths.entries_path,
id,
usr_lib_modules_vmlinuz,
&repo,
)?;
}
};
(bls_config, boot_digest, os_id)
}
};
let loader_path = entry_paths.config_path.join("loader");
let (config_path, booted_bls) = if is_upgrade {
let boot_dir = Dir::open_ambient_dir(&entry_paths.config_path, ambient_authority())?;
let BootSetupType::Upgrade((_, booted_cfs, ..)) = setup_type else {
// This is just for sanity
unreachable!("enum mismatch");
};
let mut booted_bls = get_booted_bls(&boot_dir, booted_cfs)?;
booted_bls.sort_key = Some(secondary_sort_key(&os_id));
let staged_path = loader_path.join(STAGED_BOOT_LOADER_ENTRIES);
// Delete the staged entries directory if it exists as we want to overwrite the entries
// anyway
if boot_dir
.remove_all_optional(TYPE1_ENT_PATH_STAGED)
.context("Failed to remove staged directory")?
{
tracing::debug!("Removed existing staged entries directory");
}
// This will be atomically renamed to 'loader/entries' on shutdown/reboot
(staged_path, Some(booted_bls))
} else {
(loader_path.join(BOOT_LOADER_ENTRIES), None)
};
create_dir_all(&config_path).with_context(|| format!("Creating {:?}", config_path))?;
let loader_entries_dir = Dir::open_ambient_dir(&config_path, ambient_authority())
.with_context(|| format!("Opening {config_path:?}"))?;
loader_entries_dir.atomic_write(
type1_entry_conf_file_name(&os_id, &bls_config.version(), FILENAME_PRIORITY_PRIMARY),
bls_config.to_string().as_bytes(),
)?;
if let Some(booted_bls) = booted_bls {
loader_entries_dir.atomic_write(
type1_entry_conf_file_name(&os_id, &booted_bls.version(), FILENAME_PRIORITY_SECONDARY),
booted_bls.to_string().as_bytes(),
)?;
}
let owned_loader_entries_fd = loader_entries_dir
.reopen_as_ownedfd()
.context("Reopening as owned fd")?;
rustix::fs::fsync(owned_loader_entries_fd).context("fsync")?;
Ok(boot_digest)
}
struct UKIInfo {
boot_label: String,
version: Option<String>,
os_id: Option<String>,
boot_digest: String,
}
/// Writes a PortableExecutable to ESP along with any PE specific or Global addons
#[context("Writing {file_path} to ESP")]
fn write_pe_to_esp(
repo: &crate::store::ComposefsRepository,
file: &RegularFile<Sha512HashValue>,
file_path: &Utf8Path,
pe_type: PEType,
uki_id: &Sha512HashValue,
missing_fsverity_allowed: bool,
mounted_efi: impl AsRef<Path>,
) -> Result<Option<UKIInfo>> {
let efi_bin = read_file(file, &repo).context("Reading .efi binary")?;
let mut boot_label: Option<UKIInfo> = None;
// UKI Extension might not even have a cmdline
// TODO: UKI Addon might also have a composefs= cmdline?
if matches!(pe_type, PEType::Uki) {
let cmdline = uki::get_cmdline(&efi_bin).context("Getting UKI cmdline")?;
let (composefs_cmdline, missing_verity_allowed_cmdline) =
get_cmdline_composefs::<Sha512HashValue>(cmdline).context("Parsing composefs=")?;
// If the UKI cmdline does not match what the user has passed as cmdline option
// NOTE: This will only be checked for new installs and now upgrades/switches
match missing_fsverity_allowed {
true if !missing_verity_allowed_cmdline => {
tracing::warn!(
"--allow-missing-fsverity passed as option but UKI cmdline does not support it"
);
}
false if missing_verity_allowed_cmdline => {
tracing::warn!("UKI cmdline has composefs set as insecure");
}
_ => { /* no-op */ }
}
if composefs_cmdline != *uki_id {
anyhow::bail!(
"The UKI has the wrong composefs= parameter (is '{composefs_cmdline:?}', should be {uki_id:?})"
);
}
let osrel = uki::get_text_section(&efi_bin, ".osrel")?;
let parsed_osrel = OsReleaseInfo::parse(osrel);
let boot_digest = compute_boot_digest_uki(&efi_bin)?;
boot_label = Some(UKIInfo {
boot_label: uki::get_boot_label(&efi_bin).context("Getting UKI boot label")?,
version: parsed_osrel.get_version(),
os_id: parsed_osrel.get_value(&["ID"]),
boot_digest,
});
}
let efi_linux_path = mounted_efi.as_ref().join(BOOTC_UKI_DIR);
create_dir_all(&efi_linux_path).context("Creating bootc UKI directory")?;
let final_pe_path = match file_path.parent() {
Some(parent) => {
let renamed_path = match parent.as_str().ends_with(EFI_ADDON_DIR_EXT) {
true => {
let dir_name = get_uki_addon_dir_name(&uki_id.to_hex());
parent
.parent()
.map(|p| p.join(&dir_name))
.unwrap_or(dir_name.into())
}
false => parent.to_path_buf(),
};
let full_path = efi_linux_path.join(renamed_path);
create_dir_all(&full_path)?;
full_path
}
None => efi_linux_path,
};
let pe_dir = Dir::open_ambient_dir(&final_pe_path, ambient_authority())
.with_context(|| format!("Opening {final_pe_path:?}"))?;
let pe_name = match pe_type {
PEType::Uki => &get_uki_name(&uki_id.to_hex()),
PEType::UkiAddon => file_path
.components()
.last()
.ok_or_else(|| anyhow::anyhow!("Failed to get UKI Addon file name"))?
.as_str(),
};
pe_dir
.atomic_write(pe_name, efi_bin)
.context("Writing UKI")?;
rustix::fs::fsync(
pe_dir
.reopen_as_ownedfd()
.context("Reopening as owned fd")?,
)
.context("fsync")?;
Ok(boot_label)
}
#[context("Writing Grub menuentry")]
fn write_grub_uki_menuentry(
root_path: Utf8PathBuf,
setup_type: &BootSetupType,
boot_label: String,
id: &Sha512HashValue,
esp_device: &String,
) -> Result<()> {
let boot_dir = root_path.join("boot");
create_dir_all(&boot_dir).context("Failed to create boot dir")?;
let is_upgrade = matches!(setup_type, BootSetupType::Upgrade(..));
let efi_uuid_source = get_efi_uuid_source();
let user_cfg_name = if is_upgrade {
USER_CFG_STAGED
} else {
USER_CFG
};
let grub_dir = Dir::open_ambient_dir(boot_dir.join("grub2"), ambient_authority())
.context("opening boot/grub2")?;
// Iterate over all available deployments, and generate a menuentry for each
if is_upgrade {
let mut str_buf = String::new();
let boot_dir =
Dir::open_ambient_dir(boot_dir, ambient_authority()).context("Opening boot dir")?;
let entries = get_sorted_grub_uki_boot_entries(&boot_dir, &mut str_buf)?;
grub_dir
.atomic_replace_with(user_cfg_name, |f| -> std::io::Result<_> {
f.write_all(efi_uuid_source.as_bytes())?;
f.write_all(
MenuEntry::new(&boot_label, &id.to_hex())
.to_string()
.as_bytes(),
)?;
// Write out only the currently booted entry, which should be the very first one
// Even if we have booted into the second menuentry "boot entry", the default will be the
// first one
f.write_all(entries[0].to_string().as_bytes())?;
Ok(())
})
.with_context(|| format!("Writing to {user_cfg_name}"))?;
rustix::fs::fsync(grub_dir.reopen_as_ownedfd()?).context("fsync")?;
return Ok(());
}
// Open grub2/efiuuid.cfg and write the EFI partition fs-UUID in there
// This will be sourced by grub2/user.cfg to be used for `--fs-uuid`
let esp_uuid = Task::new("blkid for ESP UUID", "blkid")
.args(["-s", "UUID", "-o", "value", &esp_device])
.read()?;