1use std::borrow::Cow;
9use std::fmt::Display;
10use std::fmt::Write as _;
11use std::io::Write;
12use std::process::Command;
13use std::process::Stdio;
14
15use anyhow::Ok;
16use anyhow::{Context, Result};
17use bootc_utils::CommandRunExt;
18use camino::Utf8Path;
19use camino::Utf8PathBuf;
20use cap_std::fs::Dir;
21use cap_std_ext::cap_std;
22use clap::ValueEnum;
23use fn_error_context::context;
24use serde::{Deserialize, Serialize};
25
26use super::MountSpec;
27use super::RUN_BOOTC;
28use super::RW_KARG;
29use super::RootSetup;
30use super::State;
31use super::config::Filesystem;
32use crate::task::Task;
33use bootc_kernel_cmdline::utf8::Cmdline;
34#[cfg(feature = "install-to-disk")]
35use bootc_mount::is_mounted_in_pid1_mountns;
36
37pub(crate) const BOOTPN_SIZE_MB: u32 = 510;
39pub(crate) const EFIPN_SIZE_MB: u32 = 512;
40pub(crate) const CFS_EFIPN_SIZE_MB: u32 = 1024;
44#[cfg(feature = "install-to-disk")]
45pub(crate) const PREPBOOT_GUID: &str = "9E1A2D38-C612-4316-AA26-8B49521E5A8B";
46#[cfg(feature = "install-to-disk")]
47pub(crate) const PREPBOOT_LABEL: &str = "PowerPC-PReP-boot";
48
49#[derive(clap::ValueEnum, Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "kebab-case")]
51pub(crate) enum BlockSetup {
52 #[default]
53 Direct,
54 Tpm2Luks,
55}
56
57impl Display for BlockSetup {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 self.to_possible_value().unwrap().get_name().fmt(f)
60 }
61}
62
63#[derive(Debug, Clone, clap::Args, Serialize, Deserialize, PartialEq, Eq)]
65#[serde(rename_all = "kebab-case")]
66pub(crate) struct InstallBlockDeviceOpts {
67 pub(crate) device: Utf8PathBuf,
69
70 #[clap(long)]
72 #[serde(default)]
73 pub(crate) wipe: bool,
74
75 #[clap(long, value_enum)]
80 pub(crate) block_setup: Option<BlockSetup>,
81
82 #[clap(long, value_enum)]
84 pub(crate) filesystem: Option<Filesystem>,
85
86 #[clap(long)]
90 pub(crate) root_size: Option<String>,
91}
92
93impl BlockSetup {
94 pub(crate) fn requires_bootpart(&self) -> bool {
96 match self {
97 BlockSetup::Direct => false,
98 BlockSetup::Tpm2Luks => true,
99 }
100 }
101}
102
103#[cfg(feature = "install-to-disk")]
104fn mkfs<'a>(
105 dev: &str,
106 fs: Filesystem,
107 label: &str,
108 wipe: bool,
109 opts: impl IntoIterator<Item = &'a str>,
110) -> Result<uuid::Uuid> {
111 let devinfo = bootc_blockdev::list_dev(dev.into())?;
112 let size = ostree_ext::glib::format_size(devinfo.size);
113
114 let u = uuid::Uuid::new_v4();
116
117 let mut t = Task::new(
118 &format!("Creating {label} filesystem ({fs}) on device {dev} (size={size})"),
119 format!("mkfs.{fs}"),
120 );
121 match fs {
122 Filesystem::Xfs => {
123 if wipe {
124 t.cmd.arg("-f");
125 }
126 t.cmd.arg("-m");
127 t.cmd.arg(format!("uuid={u}"));
128 }
129 Filesystem::Btrfs | Filesystem::Ext4 => {
130 t.cmd.arg("-U");
131 t.cmd.arg(u.to_string());
132 }
133 };
134 t.cmd.args(["-L", label]);
136 t.cmd.args(opts);
137 t.cmd.arg(dev);
138 t.cmd.stdout(Stdio::null());
140 t.verbose().run()?;
142 Ok(u)
143}
144
145pub(crate) fn wipefs(dev: &Utf8Path) -> Result<()> {
146 println!("Wiping device {dev}");
147 Command::new("wipefs")
148 .args(["-a", dev.as_str()])
149 .run_inherited_with_cmd_context()
150}
151
152pub(crate) fn udev_settle() -> Result<()> {
153 std::thread::sleep(std::time::Duration::from_millis(200));
158
159 let st = super::run_in_host_mountns("udevadm")?
160 .arg("settle")
161 .status()?;
162 if !st.success() {
163 anyhow::bail!("Failed to run udevadm settle: {st:?}");
164 }
165 Ok(())
166}
167
168#[context("Creating rootfs")]
169#[cfg(feature = "install-to-disk")]
170pub(crate) fn install_create_rootfs(
171 state: &State,
172 opts: InstallBlockDeviceOpts,
173) -> Result<RootSetup> {
174 let install_config = state.install_config.as_ref();
175 let luks_name = "root";
176 let root_filesystem = opts
178 .filesystem
179 .or(install_config
180 .and_then(|c| c.filesystem_root())
181 .and_then(|r| r.fstype))
182 .ok_or_else(|| anyhow::anyhow!("No root filesystem specified"))?;
183 let mut device = bootc_blockdev::list_dev(&opts.device)?;
186
187 if is_mounted_in_pid1_mountns(&device.path())? {
189 anyhow::bail!("Device {} is mounted", device.path())
190 }
191
192 if opts.wipe {
194 let dev = &opts.device;
195 for child in device.children.iter().flatten() {
196 let child = child.path();
197 println!("Wiping {child}");
198 wipefs(Utf8Path::new(&child))?;
199 }
200 println!("Wiping {dev}");
201 wipefs(dev)?;
202 } else if device.has_children() {
203 anyhow::bail!(
204 "Detected existing partitions on {}; use e.g. `wipefs` or --wipe if you intend to overwrite",
205 opts.device
206 );
207 }
208
209 let run_bootc = Utf8Path::new(RUN_BOOTC);
210 let mntdir = run_bootc.join("mounts");
211 if mntdir.exists() {
212 std::fs::remove_dir_all(&mntdir)?;
213 }
214
215 let block_setup = if let Some(config) = install_config {
217 config.get_block_setup(opts.block_setup.as_ref().copied())?
218 } else if opts.filesystem.is_some() {
219 opts.block_setup.unwrap_or_default()
222 } else {
223 anyhow::bail!("No install configuration found, and no filesystem specified")
226 };
227 let serial = device.serial.as_deref().unwrap_or("<unknown>");
228 let model = device.model.as_deref().unwrap_or("<unknown>");
229 println!("Block setup: {block_setup}");
230 println!(" Size: {}", device.size);
231 println!(" Serial: {serial}");
232 println!(" Model: {model}");
233
234 let root_size = opts
235 .root_size
236 .as_deref()
237 .map(bootc_blockdev::parse_size_mib)
238 .transpose()
239 .context("Parsing root size")?;
240
241 let sepolicy = state.load_policy()?;
243 let sepolicy = sepolicy.as_ref();
244
245 let physical_root_path = mntdir.join("rootfs");
248 std::fs::create_dir_all(&physical_root_path)?;
249 let bootfs = mntdir.join("boot");
250 std::fs::create_dir_all(bootfs)?;
251
252 let mut partno = 0;
254 let mut partitioning_buf = String::new();
255 writeln!(partitioning_buf, "label: gpt")?;
256 let random_label = uuid::Uuid::new_v4();
257 writeln!(&mut partitioning_buf, "label-id: {random_label}")?;
258 if cfg!(target_arch = "x86_64") {
259 partno += 1;
260 writeln!(
261 &mut partitioning_buf,
262 r#"size=1MiB, bootable, type=21686148-6449-6E6F-744E-656564454649, name="BIOS-BOOT""#
263 )?;
264 } else if cfg!(target_arch = "powerpc64") {
265 partno += 1;
267 let label = PREPBOOT_LABEL;
268 let uuid = PREPBOOT_GUID;
269 writeln!(
270 &mut partitioning_buf,
271 r#"size=4MiB, bootable, type={uuid}, name="{label}""#
272 )?;
273 } else if cfg!(any(target_arch = "aarch64", target_arch = "s390x")) {
274 } else {
276 anyhow::bail!("Unsupported architecture: {}", std::env::consts::ARCH);
277 }
278
279 let esp_partno = if super::ARCH_USES_EFI {
280 let esp_guid = crate::discoverable_partition_specification::ESP;
281 partno += 1;
282
283 let esp_size = if state.composefs_options.composefs_backend {
284 CFS_EFIPN_SIZE_MB
285 } else {
286 EFIPN_SIZE_MB
287 };
288
289 writeln!(
290 &mut partitioning_buf,
291 r#"size={esp_size}MiB, type={esp_guid}, name="EFI-SYSTEM""#
292 )?;
293 Some(partno)
294 } else {
295 None
296 };
297
298 let boot_partno = if block_setup.requires_bootpart() {
302 partno += 1;
303 writeln!(
304 &mut partitioning_buf,
305 r#"size={BOOTPN_SIZE_MB}MiB, name="boot""#
306 )?;
307 Some(partno)
308 } else {
309 None
310 };
311 let rootpn = partno + 1;
312 let root_size = root_size
313 .map(|v| Cow::Owned(format!("size={v}MiB, ")))
314 .unwrap_or_else(|| Cow::Borrowed(""));
315 let rootpart_uuid =
316 uuid::Uuid::parse_str(crate::discoverable_partition_specification::this_arch_root())?;
317 writeln!(
318 &mut partitioning_buf,
319 r#"{root_size}type={rootpart_uuid}, name="root""#
320 )?;
321 tracing::debug!("Partitioning: {partitioning_buf}");
322 Task::new("Initializing partitions", "sfdisk")
323 .arg("--wipe=always")
324 .arg(device.path())
325 .quiet()
326 .run_with_stdin_buf(Some(partitioning_buf.as_bytes()))
327 .context("Failed to run sfdisk")?;
328 tracing::debug!("Created partition table");
329
330 udev_settle()?;
333
334 device.refresh()?;
336
337 let root_device = device.find_device_by_partno(rootpn)?;
338 let expected_parttype = crate::discoverable_partition_specification::this_arch_root();
340 if !root_device
341 .parttype
342 .as_ref()
343 .is_some_and(|pt| pt.eq_ignore_ascii_case(expected_parttype))
344 {
345 anyhow::bail!(
346 "root partition {rootpn} has type {}; expected {expected_parttype}",
347 root_device.parttype.as_deref().unwrap_or("<none>")
348 );
349 }
350 let (rootdev_path, root_blockdev_kargs) = match block_setup {
351 BlockSetup::Direct => (root_device.path(), None),
352 BlockSetup::Tpm2Luks => {
353 let uuid = uuid::Uuid::new_v4().to_string();
354 let dummy_passphrase = uuid::Uuid::new_v4().to_string();
356 let mut tmp_keyfile = tempfile::NamedTempFile::new()?;
357 tmp_keyfile.write_all(dummy_passphrase.as_bytes())?;
358 tmp_keyfile.flush()?;
359 let tmp_keyfile = tmp_keyfile.path();
360 let dummy_passphrase_input = Some(dummy_passphrase.as_bytes());
361
362 let root_devpath = root_device.path();
363
364 Task::new("Initializing LUKS for root", "cryptsetup")
365 .args(["luksFormat", "--uuid", uuid.as_str(), "--key-file"])
366 .args([tmp_keyfile])
367 .arg(&root_devpath)
368 .run()?;
369 Task::new("Enrolling root device with TPM", "systemd-cryptenroll")
372 .args(["--wipe-slot=all", "--tpm2-device=auto", "--unlock-key-file"])
373 .args([tmp_keyfile])
374 .arg(&root_devpath)
375 .verbose()
376 .run_with_stdin_buf(dummy_passphrase_input)?;
377 Task::new("Opening root LUKS device", "cryptsetup")
378 .args(["luksOpen", &root_devpath, luks_name])
379 .run()?;
380 let rootdev = format!("/dev/mapper/{luks_name}");
381 let kargs = vec![
382 format!("luks.uuid={uuid}"),
383 format!("luks.options=tpm2-device=auto,headless=true"),
384 ];
385 (rootdev, Some(kargs))
386 }
387 };
388
389 let bootdev = if let Some(bootpn) = boot_partno {
391 Some(device.find_device_by_partno(bootpn)?)
392 } else {
393 None
394 };
395 let boot_uuid = if let Some(bootdev) = bootdev {
396 Some(
397 mkfs(&bootdev.path(), root_filesystem, "boot", opts.wipe, [])
398 .context("Initializing /boot")?,
399 )
400 } else {
401 None
402 };
403
404 let mkfs_options = match root_filesystem {
406 Filesystem::Ext4 => ["-O", "verity"].as_slice(),
407 _ => [].as_slice(),
408 };
409
410 let root_uuid = mkfs(
412 &rootdev_path,
413 root_filesystem,
414 "root",
415 opts.wipe,
416 mkfs_options.iter().copied(),
417 )?;
418 let rootarg = format!("root=UUID={root_uuid}");
419 let bootsrc = boot_uuid.as_ref().map(|uuid| format!("UUID={uuid}"));
420 let bootarg = bootsrc.as_deref().map(|bootsrc| format!("boot={bootsrc}"));
421 let boot = bootsrc.map(|bootsrc| MountSpec {
422 source: bootsrc,
423 target: "/boot".into(),
424 fstype: MountSpec::AUTO.into(),
425 options: Some("ro".into()),
426 });
427
428 let mut kargs = Cmdline::new();
429
430 if let Some(root_blockdev_kargs) = root_blockdev_kargs {
432 for karg in root_blockdev_kargs {
433 kargs.extend(&Cmdline::from(karg.as_str()));
434 }
435 }
436
437 kargs.extend(&Cmdline::from(format!("{rootarg} {RW_KARG}")));
439
440 if let Some(bootarg) = bootarg {
442 kargs.extend(&Cmdline::from(bootarg.as_str()));
443 }
444
445 if let Some(cli_kargs) = state.config_opts.karg.as_ref() {
447 for karg in cli_kargs {
448 kargs.extend(karg);
449 }
450 }
451
452 bootc_mount::mount(&rootdev_path, &physical_root_path)?;
453 let target_rootfs = Dir::open_ambient_dir(&physical_root_path, cap_std::ambient_authority())?;
454 crate::lsm::ensure_dir_labeled(&target_rootfs, "", Some("/".into()), 0o755.into(), sepolicy)?;
455 let physical_root = Dir::open_ambient_dir(&physical_root_path, cap_std::ambient_authority())?;
456 let bootfs = physical_root_path.join("boot");
457 crate::lsm::ensure_dir_labeled(&target_rootfs, "boot", None, 0o755.into(), sepolicy)?;
459 if let Some(bootdev) = bootdev {
460 bootc_mount::mount(&bootdev.path(), &bootfs)?;
461 }
462 crate::lsm::ensure_dir_labeled(&target_rootfs, "boot", None, 0o755.into(), sepolicy)?;
464
465 if let Some(esp_partno) = esp_partno {
467 let espdev = device.find_device_by_partno(esp_partno)?;
468 Task::new("Creating ESP filesystem", "mkfs.fat")
469 .args([&espdev.path(), "-n", "EFI-SYSTEM"])
470 .verbose()
471 .quiet_output()
472 .run()?;
473 let efifs_path = bootfs.join(crate::bootloader::EFI_DIR);
474 std::fs::create_dir(&efifs_path).context("Creating efi dir")?;
475 }
476
477 let luks_device = match block_setup {
478 BlockSetup::Direct => None,
479 BlockSetup::Tpm2Luks => Some(luks_name.to_string()),
480 };
481 Ok(RootSetup {
482 luks_device,
483 device_info: device,
484 physical_root_path,
485 physical_root,
486 target_root_path: None,
487 rootfs_uuid: Some(root_uuid.to_string()),
488 boot,
489 kargs,
490 skip_finalize: false,
491 })
492}