Skip to main content

bootc_internal_blockdev/
blockdev.rs

1use std::collections::{HashMap, HashSet};
2use std::env;
3use std::path::Path;
4use std::process::{Command, Stdio};
5use std::sync::OnceLock;
6
7use anyhow::{Context, Result, anyhow};
8use camino::{Utf8Path, Utf8PathBuf};
9use cap_std_ext::cap_std::fs::Dir;
10use fn_error_context::context;
11use serde::Deserialize;
12
13use bootc_utils::CommandRunExt;
14
15pub mod dps;
16use dps::{BIOS_BOOT, ESP, XBOOTLDR};
17
18/// Check whether the udev database is accessible (cached for the process lifetime).
19///
20/// When running inside a container or sandbox without `/run/udev`
21/// bind-mounted, tools like `lsblk` that depend on the udev database
22/// will return null for fields like `parttype` and `fstype`.
23///
24/// We check for `/run/udev/data` (the actual database directory) rather
25/// than just `/run/udev` because the parent directory can exist as an
26/// empty mount point without the database being populated.
27fn have_udev() -> bool {
28    static HAVE_UDEV: OnceLock<bool> = OnceLock::new();
29    *HAVE_UDEV.get_or_init(|| {
30        let r = Path::new("/run/udev/data").exists();
31        if !r {
32            tracing::debug!(
33                "udev database not available, will use blkid -p for partition metadata"
34            );
35        }
36        r
37    })
38}
39
40/// Probe a device with `blkid -p` and return all discovered properties
41/// as key-value pairs.
42///
43/// This uses the `export` output format (`KEY=value`, one per line) to
44/// retrieve all tags in a single invocation, rather than spawning blkid
45/// once per property.
46///
47/// Returns `Ok(empty map)` if blkid exits with code 2 (no tags found,
48/// e.g. the device is a whole disk). Other non-zero exits are propagated
49/// as errors.
50fn blkid_probe(dev: &str) -> Result<HashMap<String, String>> {
51    let mut cmd = Command::new("blkid");
52    cmd.args(["-p", "-o", "export"]).arg(dev);
53    cmd.log_debug();
54    let output = cmd.output().context("Failed to run blkid")?;
55    if !output.status.success() {
56        // blkid exits with 2 when no tags are found (e.g. whole disk)
57        if output.status.code() == Some(2) {
58            return Ok(HashMap::new());
59        }
60        let stderr = String::from_utf8_lossy(&output.stderr);
61        anyhow::bail!(
62            "blkid -p failed on {dev} (exit status {}): {stderr}",
63            output.status
64        );
65    }
66    let text = String::from_utf8(output.stdout).context("blkid output is not UTF-8")?;
67    let mut props = HashMap::new();
68    for line in text.lines() {
69        if let Some((key, value)) = line.split_once('=') {
70            props.insert(key.to_string(), value.to_string());
71        }
72    }
73    Ok(props)
74}
75
76/// MBR partition type IDs that indicate an EFI System Partition.
77/// 0x06 is FAT16 (used as ESP on some MBR systems), 0xEF is the
78/// explicit EFI System Partition type.
79/// Refer to <https://en.wikipedia.org/wiki/Partition_type>
80pub const ESP_ID_MBR: &[u8] = &[0x06, 0xEF];
81
82#[derive(Debug, Deserialize)]
83struct DevicesOutput {
84    blockdevices: Vec<Device>,
85}
86
87#[allow(dead_code)]
88#[derive(Debug, Clone, serde::Serialize, Deserialize)]
89pub struct Device {
90    pub name: String,
91    pub serial: Option<String>,
92    pub model: Option<String>,
93    pub partlabel: Option<String>,
94    pub parttype: Option<String>,
95    pub partuuid: Option<String>,
96    /// Partition number (1-indexed). None for whole disk devices.
97    pub partn: Option<u32>,
98    pub children: Option<Vec<Device>>,
99    pub size: u64,
100    #[serde(rename = "maj:min")]
101    pub maj_min: Option<String>,
102    // NOTE this one is not available on older util-linux, and
103    // will also not exist for whole blockdevs (as opposed to partitions).
104    pub start: Option<u64>,
105
106    // Filesystem-related properties
107    pub label: Option<String>,
108    pub fstype: Option<String>,
109    pub uuid: Option<String>,
110    pub path: Option<String>,
111    /// Partition table type (e.g., "gpt", "dos"). Only present on whole disk devices.
112    pub pttype: Option<String>,
113    /// Whether the device is read-only (e.g. a loopback over an immutable
114    /// rootfs image on a live ISO). `None` if not reported by `lsblk`.
115    pub ro: Option<bool>,
116}
117
118impl Device {
119    // RHEL8's lsblk doesn't have PATH, so we do it
120    pub fn path(&self) -> String {
121        self.path.clone().unwrap_or(format!("/dev/{}", &self.name))
122    }
123
124    /// Alias for path() for compatibility
125    #[allow(dead_code)]
126    pub fn node(&self) -> String {
127        self.path()
128    }
129
130    #[allow(dead_code)]
131    pub fn has_children(&self) -> bool {
132        self.children.as_ref().is_some_and(|v| !v.is_empty())
133    }
134
135    // Check if the device is mpath
136    pub fn is_mpath(&self) -> Result<bool> {
137        let dm_path = Utf8PathBuf::from_path_buf(std::fs::canonicalize(self.path())?)
138            .map_err(|_| anyhow::anyhow!("Non-UTF8 path"))?;
139        let dm_name = dm_path.file_name().unwrap_or("");
140        let uuid_path = Utf8PathBuf::from(format!("/sys/class/block/{dm_name}/dm/uuid"));
141
142        if uuid_path.exists() {
143            let uuid = std::fs::read_to_string(&uuid_path)
144                .with_context(|| format!("Failed to read {uuid_path}"))?;
145            if uuid.trim_start().starts_with("mpath-") {
146                return Ok(true);
147            }
148        }
149        Ok(false)
150    }
151
152    /// Get the numeric partition index of the ESP (e.g. "1", "2").
153    ///
154    /// We read `/sys/class/block/<name>/partition` rather than parsing device
155    /// names because naming conventions vary across disk types (sd, nvme, dm, etc.).
156    /// On multipath devices the sysfs `partition` attribute doesn't exist, so we
157    /// fall back to the `partn` field reported by lsblk, then to parsing the
158    /// partition suffix from the ESP device path relative to the parent device
159    /// path (e.g. parent `/dev/mapper/mpatha`, ESP `/dev/mapper/mpatha2` → `"2"`).
160    pub fn get_esp_partition_number(&self) -> Result<String> {
161        let esp_device = self.find_partition_of_esp()?;
162        let devname = &esp_device.name;
163
164        let partition_path = Utf8PathBuf::from(format!("/sys/class/block/{devname}/partition"));
165        if partition_path.exists() {
166            return std::fs::read_to_string(&partition_path)
167                .with_context(|| format!("Failed to read {partition_path}"));
168        }
169
170        // On multipath the partition attribute is not existing
171        if self.is_mpath()? {
172            if let Some(partn) = esp_device.partn {
173                return Ok(partn.to_string());
174            }
175            // Last resort: strip the parent device path from the ESP device path,
176            // then skip any non-digit separator (e.g. "p") to get the partition number.
177            // For example: parent "/dev/mapper/mpatha", ESP "/dev/mapper/mpatha2" → "2"
178            //              parent "/dev/mapper/mpatha", ESP "/dev/mapper/mpathap2" → "2"
179            let parent_path = self.path();
180            let esp_path = esp_device.path();
181            if let Some(n) = parse_partition_number_from_suffix(&parent_path, &esp_path) {
182                return Ok(n);
183            }
184        }
185        anyhow::bail!("Not supported for {devname}")
186    }
187
188    /// Find BIOS boot partition among children.
189    pub fn find_partition_of_bios_boot(&self) -> Option<&Device> {
190        self.find_partition_of_type(BIOS_BOOT)
191    }
192
193    /// Find all ESP partitions across all root devices backing this device.
194    /// Calls find_all_roots() to discover physical disks, then searches each for an ESP.
195    /// Returns None if no ESPs are found.
196    pub fn find_colocated_esps(&self) -> Result<Option<Vec<Device>>> {
197        let mut esps = Vec::new();
198        for root in &self.find_all_roots()? {
199            if let Some(esp) = root.find_partition_of_esp_optional()? {
200                esps.push(esp.clone());
201            }
202        }
203        Ok((!esps.is_empty()).then_some(esps))
204    }
205
206    /// Find a single ESP partition among all root devices backing this device.
207    ///
208    /// Walks the parent chain to find all backing disks, then looks for ESP
209    /// partitions on each. Returns the first ESP found. This is the common
210    /// case for composefs/UKI boot paths where exactly one ESP is expected.
211    pub fn find_first_colocated_esp(&self) -> Result<Device> {
212        self.find_colocated_esps()?
213            .and_then(|mut v| Some(v.remove(0)))
214            .ok_or_else(|| anyhow!("No ESP partition found among backing devices"))
215    }
216
217    /// Find all BIOS boot partitions across all root devices backing this device.
218    /// Calls find_all_roots() to discover physical disks, then searches each for a BIOS boot partition.
219    /// Returns None if no BIOS boot partitions are found.
220    pub fn find_colocated_bios_boot(&self) -> Result<Option<Vec<Device>>> {
221        let bios_boots: Vec<_> = self
222            .find_all_roots()?
223            .iter()
224            .filter_map(|root| root.find_partition_of_bios_boot())
225            .cloned()
226            .collect();
227        Ok((!bios_boots.is_empty()).then_some(bios_boots))
228    }
229
230    /// Find a child partition by partition type (case-insensitive).
231    pub fn find_partition_of_type(&self, parttype: &str) -> Option<&Device> {
232        self.children.as_ref()?.iter().find(|child| {
233            child
234                .parttype
235                .as_ref()
236                .is_some_and(|pt| pt.eq_ignore_ascii_case(parttype))
237        })
238    }
239
240    /// Find a VFAT Extended Boot Loader Partition (XBOOTLDR) among children.
241    ///
242    /// Other filesystems are skipped: an XBOOTLDR partition holding UKIs and
243    /// boot entries for systemd-boot must be readable by the firmware.
244    pub fn find_partition_of_xbootldr(&self) -> Option<&Device> {
245        self.find_partition_of_type(XBOOTLDR)
246            .filter(|part| part.fstype.as_deref() == Some("vfat"))
247    }
248
249    /// Find a VFAT Extended Boot Loader Partition (XBOOTLDR) on the same disk
250    /// as this partition, typically the ESP.
251    pub fn find_sibling_xbootldr(&self) -> Result<Option<Device>> {
252        for parent in self.list_parents()?.unwrap_or_default() {
253            let parent = list_dev(Utf8Path::new(&parent.path()))?;
254            if let Some(xbootldr) = parent.find_partition_of_xbootldr() {
255                return Ok(Some(xbootldr.clone()));
256            }
257        }
258        Ok(None)
259    }
260
261    /// Find the EFI System Partition (ESP) among children.
262    ///
263    /// For GPT disks, this matches by the ESP partition type GUID.
264    /// For MBR (dos) disks, this matches by the MBR partition type IDs (0x06 or 0xEF).
265    ///
266    /// If no ESP is found among direct children, this recurses into children
267    /// that have their own partition table (e.g. firmware RAID arrays where the
268    /// hierarchy is disk → md array → partitions).
269    ///
270    /// Returns `Ok(None)` when there are no children or no ESP partition
271    /// is present. Returns `Err` only for genuinely unexpected conditions
272    /// (e.g. an unsupported partition table type).
273    pub fn find_partition_of_esp_optional(&self) -> Result<Option<&Device>> {
274        let Some(children) = self.children.as_ref() else {
275            return Ok(None);
276        };
277        let direct = match self.pttype.as_deref() {
278            Some("dos") => children.iter().find(|child| {
279                child
280                    .parttype
281                    .as_ref()
282                    .and_then(|pt| {
283                        let pt = pt.strip_prefix("0x").unwrap_or(pt);
284                        u8::from_str_radix(pt, 16).ok()
285                    })
286                    .is_some_and(|pt| ESP_ID_MBR.contains(&pt))
287            }),
288            // When pttype is None (e.g. older lsblk or partition devices), default
289            // to GPT UUID matching which will simply not match MBR hex types.
290            Some("gpt") | None => self.find_partition_of_type(ESP),
291            Some(other) => return Err(anyhow!("Unsupported partition table type: {other}")),
292        };
293        if direct.is_some() {
294            return Ok(direct);
295        }
296        // Recurse into children that carry their own partition table, such as
297        // firmware RAID arrays (disk → md array → partitions).
298        for child in children {
299            if child.pttype.is_some() {
300                if let Some(esp) = child.find_partition_of_esp_optional()? {
301                    return Ok(Some(esp));
302                }
303            }
304        }
305        Ok(None)
306    }
307
308    /// Find the EFI System Partition (ESP) among children, or error if absent.
309    ///
310    /// This is a convenience wrapper around [`Self::find_partition_of_esp_optional`]
311    /// for callers that require an ESP to be present.
312    pub fn find_partition_of_esp(&self) -> Result<&Device> {
313        self.find_partition_of_esp_optional()?
314            .ok_or_else(|| anyhow!("ESP partition not found on {}", self.path()))
315    }
316
317    /// Find a child partition by partition number (1-indexed).
318    pub fn find_device_by_partno(&self, partno: u32) -> Result<&Device> {
319        self.children
320            .as_ref()
321            .ok_or_else(|| anyhow!("Device has no children"))?
322            .iter()
323            .find(|child| child.partn == Some(partno))
324            .ok_or_else(|| anyhow!("Missing partition for index {partno}"))
325    }
326
327    /// Re-query this device's information from lsblk, updating all fields.
328    /// This is useful after partitioning when the device's children have changed.
329    pub fn refresh(&mut self) -> Result<()> {
330        let path = self.path();
331        let new_device = list_dev(Utf8Path::new(&path))?;
332        *self = new_device;
333        Ok(())
334    }
335
336    /// Read a sysfs property for this device and parse it as the target type.
337    fn read_sysfs_property<T>(&self, property: &str) -> Result<Option<T>>
338    where
339        T: std::str::FromStr,
340        T::Err: std::error::Error + Send + Sync + 'static,
341    {
342        let Some(majmin) = self.maj_min.as_deref() else {
343            return Ok(None);
344        };
345        let sysfs_path = format!("/sys/dev/block/{majmin}/{property}");
346        if !Utf8Path::new(&sysfs_path).try_exists()? {
347            return Ok(None);
348        }
349        let value = std::fs::read_to_string(&sysfs_path)
350            .with_context(|| format!("Reading {sysfs_path}"))?;
351        let parsed = value
352            .trim()
353            .parse()
354            .with_context(|| format!("Parsing sysfs {property} property"))?;
355        tracing::debug!("backfilled {property} to {value}");
356        Ok(Some(parsed))
357    }
358
359    /// Backfill properties that may be missing from lsblk output.
360    ///
361    /// Older versions of util-linux may lack `start` and `partn`; these are
362    /// backfilled from sysfs. When the udev database is unavailable (e.g.
363    /// inside a container sandbox), `parttype` and `pttype` are backfilled
364    /// via `blkid -p` which reads directly from the disk.
365    pub fn backfill_missing(&mut self) -> Result<()> {
366        // The "start" parameter was only added in a version of util-linux that's only
367        // in Fedora 40 as of this writing.
368        if self.start.is_none() {
369            self.start = self.read_sysfs_property("start")?;
370        }
371        // The "partn" column was added in util-linux 2.39, which is newer than
372        // what CentOS 9 / RHEL 9 ship (2.37). Note: sysfs uses "partition" not "partn".
373        if self.partn.is_none() {
374            self.partn = self.read_sysfs_property("partition")?;
375        }
376        // When udev is unavailable, lsblk can't populate parttype/pttype from
377        // the udev database. Fall back to blkid -p which probes the disk
378        // directly. See https://github.com/osbuild/osbuild/pull/2428
379        if !have_udev() && (self.parttype.is_none() || self.pttype.is_none()) {
380            let props = blkid_probe(&self.path())?;
381            if self.parttype.is_none() {
382                self.parttype = props.get("PART_ENTRY_TYPE").cloned();
383            }
384            if self.pttype.is_none() {
385                self.pttype = props.get("PTTYPE").cloned();
386            }
387        }
388        // Recurse to child devices
389        for child in self.children.iter_mut().flatten() {
390            child.backfill_missing()?;
391        }
392        Ok(())
393    }
394
395    /// Query parent devices via `lsblk --inverse`.
396    ///
397    /// Returns `Ok(None)` if this device is already a root device (no parents).
398    /// In the returned `Vec<Device>`, each device's `children` field contains
399    /// *its own* parents (grandparents, etc.), forming the full chain to the
400    /// root device(s). A device can have multiple parents (e.g. RAID, LVM).
401    pub fn list_parents(&self) -> Result<Option<Vec<Device>>> {
402        let path = self.path();
403        let output: DevicesOutput = Command::new("lsblk")
404            .args(["-J", "-b", "-O", "--inverse"])
405            .arg(&path)
406            .log_debug()
407            .run_and_parse_json()?;
408
409        let device = output
410            .blockdevices
411            .into_iter()
412            .next()
413            .ok_or_else(|| anyhow!("no device output from lsblk --inverse for {path}"))?;
414
415        match device.children {
416            Some(mut children) if !children.is_empty() => {
417                for child in &mut children {
418                    child.backfill_missing()?;
419                }
420                Ok(Some(children))
421            }
422            _ => Ok(None),
423        }
424    }
425
426    /// Walk the parent chain to find all root (whole disk) devices,
427    /// and fail if more than one root is found.
428    ///
429    /// This is a convenience wrapper around `find_all_roots` for callers
430    /// that expect exactly one backing device (e.g. non-RAID setups).
431    pub fn require_single_root(&self) -> Result<Device> {
432        let mut roots = self.find_all_roots()?;
433        match roots.len() {
434            1 => Ok(roots.remove(0)),
435            n => anyhow::bail!(
436                "Expected a single root device for {}, but found {n}",
437                self.path()
438            ),
439        }
440    }
441
442    /// Walk the parent chain to find all root (whole disk) devices.
443    ///
444    /// Returns all root devices with their children (partitions) populated.
445    /// This handles devices backed by multiple parents (e.g. RAID arrays)
446    /// by following all branches of the parent tree.
447    /// If this device is already a root device, returns a single-element list.
448    pub fn find_all_roots(&self) -> Result<Vec<Device>> {
449        let Some(parents) = self.list_parents()? else {
450            // Already a root device; re-query to ensure children are populated
451            return Ok(vec![list_dev(Utf8Path::new(&self.path()))?]);
452        };
453
454        let mut roots = Vec::new();
455        let mut seen = HashSet::new();
456        let mut queue = parents;
457        while let Some(mut device) = queue.pop() {
458            match device.children.take() {
459                Some(grandparents) if !grandparents.is_empty() => {
460                    queue.extend(grandparents);
461                }
462                _ => {
463                    // Deduplicate: in complex topologies (e.g. multipath)
464                    // multiple branches can converge on the same physical disk.
465                    let name = device.name.clone();
466                    if seen.insert(name) {
467                        // Found a new root; re-query to populate its actual children
468                        roots.push(list_dev(Utf8Path::new(&device.path()))?);
469                    }
470                }
471            }
472        }
473        Ok(roots)
474    }
475}
476
477#[context("Listing device {dev}")]
478pub fn list_dev(dev: &Utf8Path) -> Result<Device> {
479    let mut devs: DevicesOutput = Command::new("lsblk")
480        .args(["-J", "-b", "-O"])
481        .arg(dev)
482        .log_debug()
483        .run_and_parse_json()?;
484    for dev in devs.blockdevices.iter_mut() {
485        dev.backfill_missing()?;
486    }
487    devs.blockdevices
488        .into_iter()
489        .next()
490        .ok_or_else(|| anyhow!("no device output from lsblk for {dev}"))
491}
492
493#[context("Finding block device for ZFS dataset {dataset}")]
494fn list_dev_for_zfs_dataset(dataset: &str) -> Result<Device> {
495    let dataset = dataset.strip_prefix("ZFS=").unwrap_or(dataset);
496    let pool = dataset
497        .split('/')
498        .next()
499        .ok_or_else(|| anyhow!("Invalid ZFS dataset: {dataset}"))?;
500
501    let output = Command::new("zpool")
502        .args(["list", "-H", "-v", "-P", pool])
503        .run_get_string()
504        .with_context(|| format!("Querying ZFS pool {pool}"))?;
505
506    for line in output.lines() {
507        if line.starts_with('\t') || line.starts_with(' ') {
508            let dev_path = line.trim_start().split('\t').next().unwrap_or("").trim();
509            if dev_path.starts_with('/') {
510                return list_dev(Utf8Path::new(dev_path));
511            }
512        }
513    }
514
515    anyhow::bail!("Could not find a block device backing ZFS pool {pool}")
516}
517
518/// List the device containing the filesystem mounted at the given directory.
519pub fn list_dev_by_dir(dir: &Dir) -> Result<Device> {
520    let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
521    let source = &fsinfo.source;
522    if fsinfo.fstype == "zfs" || source.starts_with("ZFS=") {
523        return list_dev_for_zfs_dataset(source);
524    }
525    list_dev(&Utf8PathBuf::from(source))
526}
527
528/// The statfs magic of ZFS (`ZFS_SUPER_MAGIC` in OpenZFS), which libc lacks.
529const ZFS_SUPER_MAGIC: u32 = 0x2fc12fc1;
530
531/// Whether a filesystem with the given `st_dev` and statfs magic is backed by
532/// a block device.
533///
534/// The kernel gives filesystems without one (virtiofs, NFS, tmpfs,
535/// overlayfs, ...) an anonymous device number, whose major is 0. btrfs and
536/// ZFS get anonymous device numbers too (btrfs one per subvolume) even though
537/// they sit on block devices, so those are recognized by their magic.
538fn is_block_backed(st_dev: u64, fs_magic: u32) -> bool {
539    rustix::fs::major(st_dev) != 0
540        || fs_magic == libc::BTRFS_SUPER_MAGIC as u32
541        || fs_magic == ZFS_SUPER_MAGIC
542}
543
544/// List the device containing the filesystem mounted at the given directory,
545/// or `None` if that filesystem is not backed by a block device (such as
546/// virtiofs, NFS, tmpfs or overlayfs).
547///
548/// As with [`list_dev_by_dir`], `dir` must be the root of a mount.
549#[context("Finding block device backing directory")]
550pub fn list_dev_by_dir_optional(dir: &Dir) -> Result<Option<Device>> {
551    let st_dev = rustix::fs::fstat(dir)?.st_dev;
552    // Filesystem magic numbers are 32 bits; f_type's width varies by arch.
553    let fs_magic = rustix::fs::fstatfs(dir)?.f_type as u32;
554    if !is_block_backed(st_dev, fs_magic) {
555        tracing::debug!("No block device: st_dev={st_dev:#x} f_type={fs_magic:#x}");
556        return Ok(None);
557    }
558    list_dev_by_dir(dir).map(Some)
559}
560
561/// Determine whether the block device backing the filesystem mounted at the
562/// given directory is physically read-only.
563///
564/// This is the case for e.g. a live ISO, where `/sysroot` is a loopback device
565/// over an immutable rootfs image and the kernel will reject any attempt to
566/// remount it read-write.
567///
568/// Returns `Ok(None)` when the backing device cannot be determined (for example
569/// when the filesystem source is not a real block device, such as an overlay),
570/// leaving the decision to the caller.
571pub fn is_dir_backing_device_ro(dir: &Dir) -> Result<Option<bool>> {
572    let fsinfo = bootc_mount::inspect_filesystem_of_dir(dir)?;
573    let source = &fsinfo.source;
574    // Only real block device nodes can be queried via lsblk; sources like
575    // "overlay" or a ZFS dataset are not physical devices we can interrogate
576    // for a read-only flag here.
577    if !source.starts_with("/dev/") {
578        tracing::debug!("Filesystem source {source} is not a block device node");
579        return Ok(None);
580    }
581    let dev = list_dev(&Utf8PathBuf::from(source))?;
582    Ok(dev.ro)
583}
584
585pub struct LoopbackDevice {
586    pub dev: Option<Utf8PathBuf>,
587    // Handle to the cleanup helper process
588    cleanup_handle: Option<LoopbackCleanupHandle>,
589}
590
591/// Handle to manage the cleanup helper process for loopback devices
592struct LoopbackCleanupHandle {
593    /// Child process handle
594    child: std::process::Child,
595}
596
597impl LoopbackDevice {
598    // Create a new loopback block device targeting the provided file path.
599    pub fn new(path: &Path) -> Result<Self> {
600        let direct_io = match env::var("BOOTC_DIRECT_IO") {
601            Ok(val) => {
602                if val == "on" {
603                    "on"
604                } else {
605                    "off"
606                }
607            }
608            Err(_e) => "off",
609        };
610
611        let dev = Command::new("losetup")
612            .args([
613                "--show",
614                format!("--direct-io={direct_io}").as_str(),
615                "-P",
616                "--find",
617            ])
618            .arg(path)
619            .run_get_string()?;
620        let dev = Utf8PathBuf::from(dev.trim());
621        tracing::debug!("Allocated loopback {dev}");
622
623        // Try to spawn cleanup helper, but don't fail if it doesn't work
624        let cleanup_handle = match Self::spawn_cleanup_helper(dev.as_str()) {
625            Ok(handle) => Some(handle),
626            Err(e) => {
627                tracing::warn!(
628                    "Failed to spawn loopback cleanup helper for {}: {}. \
629                     Loopback device may not be cleaned up if process is interrupted.",
630                    dev,
631                    e
632                );
633                None
634            }
635        };
636
637        Ok(Self {
638            dev: Some(dev),
639            cleanup_handle,
640        })
641    }
642
643    // Access the path to the loopback block device.
644    pub fn path(&self) -> &Utf8Path {
645        // SAFETY: The option cannot be destructured until we are dropped
646        self.dev.as_deref().unwrap()
647    }
648
649    /// Spawn a cleanup helper process that will clean up the loopback device
650    /// if the parent process dies unexpectedly
651    fn spawn_cleanup_helper(device_path: &str) -> Result<LoopbackCleanupHandle> {
652        // Try multiple strategies to find the bootc binary
653        let bootc_path = bootc_utils::reexec::executable_path()
654            .context("Failed to locate bootc binary for cleanup helper")?;
655
656        // Create the helper process
657        let mut cmd = Command::new(bootc_path);
658        cmd.args([
659            "internals",
660            "loopback-cleanup-helper",
661            "--device",
662            device_path,
663        ]);
664
665        // Set environment variable to indicate this is a cleanup helper
666        cmd.env("BOOTC_LOOPBACK_CLEANUP_HELPER", "1");
667
668        // Set up stdio to redirect to /dev/null
669        cmd.stdin(Stdio::null());
670        cmd.stdout(Stdio::null());
671        // Don't redirect stderr so we can see error messages
672
673        // Spawn the process
674        let child = cmd
675            .spawn()
676            .context("Failed to spawn loopback cleanup helper")?;
677
678        Ok(LoopbackCleanupHandle { child })
679    }
680
681    // Shared backend for our `close` and `drop` implementations.
682    fn impl_close(&mut self) -> Result<()> {
683        // SAFETY: This is the only place we take the option
684        let Some(dev) = self.dev.take() else {
685            tracing::trace!("loopback device already deallocated");
686            return Ok(());
687        };
688
689        // Kill the cleanup helper since we're cleaning up normally
690        if let Some(mut cleanup_handle) = self.cleanup_handle.take() {
691            // Send SIGTERM to the child process and let it do the cleanup
692            let _ = cleanup_handle.child.kill();
693        }
694
695        Command::new("losetup")
696            .args(["-d", dev.as_str()])
697            .run_capture_stderr()
698    }
699
700    /// Consume this device, unmounting it.
701    pub fn close(mut self) -> Result<()> {
702        self.impl_close()
703    }
704}
705
706impl Drop for LoopbackDevice {
707    fn drop(&mut self) {
708        // Best effort to unmount if we're dropped without invoking `close`
709        let _ = self.impl_close();
710    }
711}
712
713/// Main function for the loopback cleanup helper process
714/// This function does not return - it either exits normally or via signal
715pub async fn run_loopback_cleanup_helper(device_path: &str) -> Result<()> {
716    // Check if we're running as a cleanup helper
717    if std::env::var("BOOTC_LOOPBACK_CLEANUP_HELPER").is_err() {
718        anyhow::bail!("This function should only be called as a cleanup helper");
719    }
720
721    // Set up death signal notification - we want to be notified when parent dies
722    rustix::process::set_parent_process_death_signal(Some(rustix::process::Signal::TERM))
723        .context("Failed to set parent death signal")?;
724
725    // Wait for SIGTERM (either from parent death or normal cleanup)
726    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
727        .expect("Failed to create signal stream")
728        .recv()
729        .await;
730
731    // Clean up the loopback device
732    let output = std::process::Command::new("losetup")
733        .args(["-d", device_path])
734        .output();
735
736    match output {
737        Ok(output) if output.status.success() => {
738            // Log to systemd journal instead of stderr
739            tracing::info!("Cleaned up leaked loopback device {}", device_path);
740            std::process::exit(0);
741        }
742        Ok(output) => {
743            let stderr = String::from_utf8_lossy(&output.stderr);
744            tracing::error!(
745                "Failed to clean up loopback device {}: {}. Stderr: {}",
746                device_path,
747                output.status,
748                stderr.trim()
749            );
750            std::process::exit(1);
751        }
752        Err(e) => {
753            tracing::error!(
754                "Error executing losetup to clean up loopback device {}: {}",
755                device_path,
756                e
757            );
758            std::process::exit(1);
759        }
760    }
761}
762
763/// Parse a string into mibibytes
764pub fn parse_size_mib(mut s: &str) -> Result<u64> {
765    let suffixes = [
766        ("MiB", 1u64),
767        ("M", 1u64),
768        ("GiB", 1024),
769        ("G", 1024),
770        ("TiB", 1024 * 1024),
771        ("T", 1024 * 1024),
772    ];
773    let mut mul = 1u64;
774    for (suffix, imul) in suffixes {
775        if let Some((sv, rest)) = s.rsplit_once(suffix) {
776            if !rest.is_empty() {
777                anyhow::bail!("Trailing text after size: {rest}");
778            }
779            s = sv;
780            mul = imul;
781        }
782    }
783    let v = s.parse::<u64>()?;
784    Ok(v * mul)
785}
786
787/// Extract a partition number by stripping the parent device path from the
788/// ESP partition device path, then skipping any non-digit separator characters.
789///
790/// Multipath partition devices are named by appending a partition suffix to
791/// the parent device path. The suffix may include a separator like "p" before
792/// the digits:
793///   - `/dev/mapper/mpatha`  + `2`  → `/dev/mapper/mpatha2`
794///   - `/dev/mapper/mpatha`  + `p2` → `/dev/mapper/mpathap2`
795///
796/// This function returns `None` if the ESP path doesn't start with the parent
797/// path or if no trailing digits are found in the suffix.
798fn parse_partition_number_from_suffix(parent_path: &str, esp_path: &str) -> Option<String> {
799    let suffix = esp_path.strip_prefix(parent_path)?;
800    let digits = suffix.trim_start_matches(|c: char| !c.is_ascii_digit());
801    if digits.is_empty() {
802        return None;
803    }
804    Some(digits.to_string())
805}
806
807#[cfg(test)]
808mod test {
809    use super::*;
810
811    #[test]
812    fn test_is_block_backed() {
813        use rustix::fs::makedev;
814        // Filesystem magic numbers are 32 bits; see list_dev_by_dir_optional.
815        let cases = [
816            (makedev(252, 3), libc::XFS_SUPER_MAGIC as u32, true),
817            (makedev(253, 0), libc::EXT4_SUPER_MAGIC as u32, true),
818            (makedev(0, 38), libc::BTRFS_SUPER_MAGIC as u32, true),
819            (makedev(0, 51), ZFS_SUPER_MAGIC, true),
820            (makedev(0, 29), libc::FUSE_SUPER_MAGIC as u32, false),
821            (makedev(0, 52), libc::NFS_SUPER_MAGIC as u32, false),
822            (makedev(0, 40), libc::OVERLAYFS_SUPER_MAGIC as u32, false),
823            (makedev(0, 23), libc::TMPFS_MAGIC as u32, false),
824        ];
825        for (st_dev, fs_magic, expected) in cases {
826            assert_eq!(
827                is_block_backed(st_dev, fs_magic),
828                expected,
829                "st_dev={st_dev:#x} f_type={fs_magic:#x}"
830            );
831        }
832    }
833
834    #[test]
835    fn test_list_dev_by_dir_optional_procfs() -> Result<()> {
836        let proc = Dir::open_ambient_dir("/proc", cap_std_ext::cap_std::ambient_authority())?;
837        assert!(list_dev_by_dir_optional(&proc)?.is_none());
838        Ok(())
839    }
840
841    #[test]
842    fn test_parse_size_mib() {
843        let ident_cases = [0, 10, 9, 1024].into_iter().map(|k| (k.to_string(), k));
844        let cases = [
845            ("0M", 0),
846            ("10M", 10),
847            ("10MiB", 10),
848            ("1G", 1024),
849            ("9G", 9216),
850            ("11T", 11 * 1024 * 1024),
851        ]
852        .into_iter()
853        .map(|(k, v)| (k.to_string(), v));
854        for (s, v) in ident_cases.chain(cases) {
855            assert_eq!(parse_size_mib(&s).unwrap(), v as u64, "Parsing {s}");
856        }
857    }
858
859    #[test]
860    fn test_parse_lsblk() {
861        let fixture = include_str!("../tests/fixtures/lsblk.json");
862        let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
863        let dev = devs.blockdevices.into_iter().next().unwrap();
864        // The parent device has no partition number
865        assert_eq!(dev.partn, None);
866        let children = dev.children.as_deref().unwrap();
867        assert_eq!(children.len(), 3);
868        let first_child = &children[0];
869        assert_eq!(first_child.partn, Some(1));
870        assert_eq!(
871            first_child.parttype.as_deref().unwrap(),
872            "21686148-6449-6e6f-744e-656564454649"
873        );
874        assert_eq!(
875            first_child.partuuid.as_deref().unwrap(),
876            "3979e399-262f-4666-aabc-7ab5d3add2f0"
877        );
878        // Verify find_device_by_partno works
879        let part2 = dev.find_device_by_partno(2).unwrap();
880        assert_eq!(part2.partn, Some(2));
881        assert_eq!(part2.parttype.as_deref().unwrap(), ESP);
882        // Verify find_partition_of_esp works
883        let esp = dev.find_partition_of_esp().unwrap();
884        assert_eq!(esp.partn, Some(2));
885        // Verify find_partition_of_bios_boot works (vda1 is BIOS-BOOT)
886        let bios = dev.find_partition_of_bios_boot().unwrap();
887        assert_eq!(bios.partn, Some(1));
888        assert_eq!(bios.parttype.as_deref().unwrap(), BIOS_BOOT);
889    }
890
891    /// Verify that without the udev database, partition type fields are null
892    /// and partition discovery fails. This simulates what happens when bootc
893    /// runs inside a sandbox (like osbuild's bwrap) without /run/udev.
894    #[test]
895    fn test_parse_lsblk_no_udev() {
896        let fixture = include_str!("../tests/fixtures/lsblk-no-udev.json");
897        let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
898        let dev = devs.blockdevices.into_iter().next().unwrap();
899        // Without udev, parttype and pttype are null
900        assert!(dev.pttype.is_none());
901        let children = dev.children.as_deref().unwrap();
902        assert_eq!(children.len(), 3);
903        assert!(children[0].parttype.is_none());
904        assert!(children[1].parttype.is_none());
905        assert!(children[2].parttype.is_none());
906        // ESP and BIOS boot discovery should fail (no parttype to match)
907        assert!(dev.find_partition_of_esp_optional().unwrap().is_none());
908        assert!(dev.find_partition_of_bios_boot().is_none());
909    }
910
911    #[test]
912    fn test_parse_lsblk_mbr() {
913        let fixture = include_str!("../tests/fixtures/lsblk-mbr.json");
914        let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
915        let dev = devs.blockdevices.into_iter().next().unwrap();
916        // The parent device has no partition number and is MBR
917        assert_eq!(dev.partn, None);
918        assert_eq!(dev.pttype.as_deref().unwrap(), "dos");
919        let children = dev.children.as_deref().unwrap();
920        assert_eq!(children.len(), 3);
921        // First partition: FAT16 boot partition (MBR type 0x06, an ESP type)
922        let first_child = &children[0];
923        assert_eq!(first_child.partn, Some(1));
924        assert_eq!(first_child.parttype.as_deref().unwrap(), "0x06");
925        assert_eq!(first_child.partuuid.as_deref().unwrap(), "a1b2c3d4-01");
926        assert_eq!(first_child.fstype.as_deref().unwrap(), "vfat");
927        // MBR partitions have no partlabel
928        assert!(first_child.partlabel.is_none());
929        // Second partition: Linux root (MBR type 0x83)
930        let second_child = &children[1];
931        assert_eq!(second_child.partn, Some(2));
932        assert_eq!(second_child.parttype.as_deref().unwrap(), "0x83");
933        assert_eq!(second_child.partuuid.as_deref().unwrap(), "a1b2c3d4-02");
934        // Third partition: EFI System Partition (MBR type 0xef)
935        let third_child = &children[2];
936        assert_eq!(third_child.partn, Some(3));
937        assert_eq!(third_child.parttype.as_deref().unwrap(), "0xef");
938        assert_eq!(third_child.partuuid.as_deref().unwrap(), "a1b2c3d4-03");
939        // Verify find_device_by_partno works on MBR
940        let part1 = dev.find_device_by_partno(1).unwrap();
941        assert_eq!(part1.partn, Some(1));
942        // find_partition_of_esp returns the first matching ESP type (0x06 on partition 1)
943        let esp = dev.find_partition_of_esp().unwrap();
944        assert_eq!(esp.partn, Some(1));
945    }
946
947    /// Helper to construct a minimal MBR disk Device with given child partition types.
948    fn make_mbr_disk(parttypes: &[&str]) -> Device {
949        Device {
950            name: "vda".into(),
951            serial: None,
952            model: None,
953            partlabel: None,
954            parttype: None,
955            partuuid: None,
956            partn: None,
957            size: 10737418240,
958            maj_min: None,
959            start: None,
960            label: None,
961            fstype: None,
962            uuid: None,
963            path: Some("/dev/vda".into()),
964            pttype: Some("dos".into()),
965            ro: None,
966            children: Some(
967                parttypes
968                    .iter()
969                    .enumerate()
970                    .map(|(i, pt)| Device {
971                        name: format!("vda{}", i + 1),
972                        serial: None,
973                        model: None,
974                        partlabel: None,
975                        parttype: Some(pt.to_string()),
976                        partuuid: None,
977                        partn: Some(i as u32 + 1),
978                        size: 1048576,
979                        maj_min: None,
980                        start: Some(2048),
981                        label: None,
982                        fstype: None,
983                        uuid: None,
984                        path: None,
985                        pttype: Some("dos".into()),
986                        ro: None,
987                        children: None,
988                    })
989                    .collect(),
990            ),
991        }
992    }
993
994    #[test]
995    fn test_parse_lsblk_vroc() {
996        let fixture = include_str!("../tests/fixtures/lsblk-vroc.json");
997        let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
998        assert_eq!(devs.blockdevices.len(), 2);
999
1000        // find_partition_of_esp recurses through the md126 RAID array to
1001        // locate the ESP (md126p1) even though it is not a direct child of
1002        // the NVMe disk.
1003        for nvme in &devs.blockdevices {
1004            let esp = nvme.find_partition_of_esp().unwrap();
1005            assert_eq!(esp.name, "md126p1");
1006            assert_eq!(esp.partn, Some(1));
1007            assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1008            assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1009        }
1010    }
1011
1012    #[test]
1013    fn test_parse_lsblk_swraid() {
1014        let fixture = include_str!("../tests/fixtures/lsblk-swraid.json");
1015        let devs: DevicesOutput = serde_json::from_str(fixture).unwrap();
1016        assert_eq!(devs.blockdevices.len(), 2);
1017
1018        // In a software RAID (mdadm) setup each disk is individually
1019        // partitioned with its own GPT table and ESP.  The root partition
1020        // (sda3/sdb3) is a linux_raid_member assembled into md0.
1021        // find_partition_of_esp should locate the ESP as a direct child of
1022        // each disk — no recursion through an md array is needed here.
1023        let sda = &devs.blockdevices[0];
1024        let esp = sda.find_partition_of_esp().unwrap();
1025        assert_eq!(esp.name, "sda1");
1026        assert_eq!(esp.partn, Some(1));
1027        assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1028        assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1029
1030        let sdb = &devs.blockdevices[1];
1031        let esp = sdb.find_partition_of_esp().unwrap();
1032        assert_eq!(esp.name, "sdb1");
1033        assert_eq!(esp.partn, Some(1));
1034        assert_eq!(esp.parttype.as_deref().unwrap(), ESP);
1035        assert_eq!(esp.fstype.as_deref().unwrap(), "vfat");
1036
1037        // Verify the md0 RAID array is visible as a child of the root
1038        // partition on each disk.
1039        let sda3 = sda
1040            .children
1041            .as_ref()
1042            .unwrap()
1043            .iter()
1044            .find(|c| c.name == "sda3")
1045            .unwrap();
1046        assert_eq!(sda3.fstype.as_deref().unwrap(), "linux_raid_member");
1047        let md0 = sda3
1048            .children
1049            .as_ref()
1050            .unwrap()
1051            .iter()
1052            .find(|c| c.name == "md0")
1053            .unwrap();
1054        assert_eq!(md0.fstype.as_deref().unwrap(), "ext4");
1055    }
1056
1057    #[test]
1058    fn test_mbr_esp_detection() {
1059        // 0x06 (FAT16) is recognized as ESP
1060        let dev = make_mbr_disk(&["0x06"]);
1061        assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(1));
1062
1063        // 0xef (EFI System Partition) is recognized as ESP
1064        let dev = make_mbr_disk(&["0x83", "0xef"]);
1065        assert_eq!(dev.find_partition_of_esp().unwrap().partn, Some(2));
1066
1067        // No ESP types present: 0x83 (Linux) and 0x82 (swap)
1068        let dev = make_mbr_disk(&["0x83", "0x82"]);
1069        assert!(dev.find_partition_of_esp().is_err());
1070    }
1071
1072    #[test]
1073    fn test_find_partition_of_xbootldr() {
1074        let cases = [
1075            (XBOOTLDR, Some("vfat"), Some(2)),
1076            (XBOOTLDR, Some("ext4"), None),
1077            (XBOOTLDR, None, None),
1078            (ESP, Some("vfat"), None),
1079        ];
1080        for (parttype, fstype, expected) in cases {
1081            let disk: Device = serde_json::from_value(serde_json::json!({
1082                "name": "vda",
1083                "size": 10737418240_u64,
1084                "pttype": "gpt",
1085                "children": [
1086                    {"name": "vda1", "size": 104857600, "partn": 1, "parttype": ESP, "fstype": "vfat"},
1087                    {"name": "vda2", "size": 2147483648_u64, "partn": 2, "parttype": parttype, "fstype": fstype},
1088                ]
1089            }))
1090            .unwrap();
1091            assert_eq!(
1092                disk.find_partition_of_xbootldr().and_then(|p| p.partn),
1093                expected,
1094                "{parttype} {fstype:?}"
1095            );
1096        }
1097    }
1098
1099    #[test]
1100    fn test_parse_partition_number_from_suffix() {
1101        // Short alias like /dev/mapper/mpatha → /dev/mapper/mpatha2
1102        assert_eq!(
1103            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha2"),
1104            Some("2".into())
1105        );
1106        // With a "p" separator: /dev/mapper/mpatha → /dev/mapper/mpathap2
1107        assert_eq!(
1108            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap2"),
1109            Some("2".into())
1110        );
1111        // WWID-style name with "part" separator
1112        assert_eq!(
1113            parse_partition_number_from_suffix(
1114                "/dev/mapper/3600508b4001",
1115                "/dev/mapper/3600508b4001-part1"
1116            ),
1117            Some("1".into())
1118        );
1119        // Multi-digit partition number
1120        assert_eq!(
1121            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha12"),
1122            Some("12".into())
1123        );
1124        // ESP path doesn't share the parent prefix → None
1125        assert_eq!(
1126            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/sda1"),
1127            None
1128        );
1129        // No digits in suffix → None
1130        assert_eq!(
1131            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpathap"),
1132            None
1133        );
1134        // Identical paths (no suffix at all) → None
1135        assert_eq!(
1136            parse_partition_number_from_suffix("/dev/mapper/mpatha", "/dev/mapper/mpatha"),
1137            None
1138        );
1139    }
1140}