fix(cli): never offer a Linux disk that holds boot, home or swap, and test Windows disk names on every host
This commit is contained in:
1 parent
8bffcd6dcf
commit
bf20dda02a
4 files changed
+167
-62
No files matched your search
@@ -10,6 +10,8 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod diskutil;
|
||||
#[cfg(any(windows, test))]
|
||||
mod drive_names;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
//! How setup names Windows disks and partitions: `\\.\PhysicalDriveN` is
|
||||
//! `diskN`, and its partition number M is `diskNpM`. The Windows backend
|
||||
//! opens the devices; this module only reads the names, so it is compiled
|
||||
//! and tested on every host.
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// `diskN` → N.
|
||||
pub(super) fn disk_number(identifier: &str) -> Result<u32> {
|
||||
identifier
|
||||
.strip_prefix("disk")
|
||||
.filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|n| n.parse().ok())
|
||||
.with_context(|| format!("{identifier} is not a whole disk such as disk2"))
|
||||
}
|
||||
|
||||
/// `diskNpM` → (N, M), M from 1.
|
||||
pub(super) fn partition_number(identifier: &str) -> Result<(u32, u32)> {
|
||||
identifier
|
||||
.strip_prefix("disk")
|
||||
.and_then(|rest| rest.split_once('p'))
|
||||
.filter(|(disk, partition)| {
|
||||
[disk, partition]
|
||||
.iter()
|
||||
.all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
})
|
||||
.and_then(|(disk, partition)| Some((disk.parse().ok()?, partition.parse().ok()?)))
|
||||
.filter(|(_, partition)| *partition > 0)
|
||||
.with_context(|| format!("{identifier} is not a partition such as disk2p1"))
|
||||
}
|
||||
|
||||
/// The whole disk `--usb` names, as `diskN`: `PhysicalDriveN`,
|
||||
/// `\\.\PhysicalDriveN` or `diskN`, in any case.
|
||||
pub(super) fn whole_disk(name: &str) -> Option<String> {
|
||||
let name = name.to_ascii_lowercase();
|
||||
let name = name.strip_prefix(r"\\.\").unwrap_or(&name);
|
||||
let number = name
|
||||
.strip_prefix("physicaldrive")
|
||||
.or_else(|| name.strip_prefix("disk"))
|
||||
.filter(|n| !n.is_empty() && n.len() <= 3 && n.bytes().all(|b| b.is_ascii_digit()))?;
|
||||
Some(format!("disk{}", number.parse::<u32>().ok()?))
|
||||
}
|
||||
|
||||
/// The PCI device ID in an NVIDIA device's instance ID, such as
|
||||
/// `PCI\VEN_10DE&DEV_2786&SUBSYS_...`.
|
||||
pub(super) fn nvidia_device(instance: &str) -> Option<u16> {
|
||||
let device = instance.strip_prefix("PCI\\VEN_10DE&DEV_")?.get(..4)?;
|
||||
u16::from_str_radix(device, 16).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn whole_disks_are_named_by_physical_drive_or_disk_number() {
|
||||
for (typed, disk) in [
|
||||
("PhysicalDrive2", "disk2"),
|
||||
(r"\\.\PhysicalDrive2", "disk2"),
|
||||
("physicaldrive10", "disk10"),
|
||||
("disk3", "disk3"),
|
||||
("DISK3", "disk3"),
|
||||
("disk03", "disk3"),
|
||||
] {
|
||||
assert_eq!(whole_disk(typed).as_deref(), Some(disk), "{typed}");
|
||||
}
|
||||
for typed in [
|
||||
"",
|
||||
"disk",
|
||||
"PhysicalDrive",
|
||||
"disk2p1",
|
||||
"E:",
|
||||
r"E:\",
|
||||
r"\\.\E:",
|
||||
"disk-1",
|
||||
"disk1234",
|
||||
"PhysicalDrive2 ",
|
||||
] {
|
||||
assert_eq!(whole_disk(typed), None, "{typed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_and_partition_identifiers_are_checked() {
|
||||
assert_eq!(disk_number("disk0").unwrap(), 0);
|
||||
assert_eq!(disk_number("disk12").unwrap(), 12);
|
||||
for bad in ["", "disk", "disk1p1", "Disk1", "disk+1", "sdb"] {
|
||||
assert!(disk_number(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(partition_number("disk2p1").unwrap(), (2, 1));
|
||||
assert_eq!(partition_number("disk10p12").unwrap(), (10, 12));
|
||||
for bad in [
|
||||
"disk2", "disk2p0", "diskp1", "disk2p", "disk2p+1", "disk+2p1",
|
||||
] {
|
||||
assert!(partition_number(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_ids_name_nvidia_devices() {
|
||||
let id = "PCI\\VEN_10DE&DEV_2786&SUBSYS_00000000&REV_A1\\4&0123ABCD&0&0008";
|
||||
assert_eq!(nvidia_device(id), Some(0x2786));
|
||||
assert_eq!(
|
||||
nvidia_device("PCI\\VEN_1002&DEV_1234&SUBSYS_00000000"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,17 @@ const ESP_TYPES: [&str; 2] = ["c12a7328-f81f-11d2-ba4b-00a0c93ec93b", "0xef"];
|
||||
/// `lsblk`'s columns, for [`Device`].
|
||||
const COLUMNS: &str =
|
||||
"NAME,TYPE,SIZE,MODEL,TRAN,RM,RO,MOUNTPOINT,MOUNTPOINTS,PARTTYPE,PARTUUID,PKNAME";
|
||||
/// The mount points of the running system's volumes, and swap's.
|
||||
const SYSTEM_MOUNTS: [&str; 8] = [
|
||||
"/",
|
||||
"/boot",
|
||||
"/boot/efi",
|
||||
"/efi",
|
||||
"/usr",
|
||||
"/var",
|
||||
"/home",
|
||||
"[SWAP]",
|
||||
];
|
||||
/// The `BLKRRPART` ioctl: reread the partition table.
|
||||
const BLKRRPART: u64 = 0x125f;
|
||||
|
||||
@@ -59,16 +70,27 @@ struct Device {
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// Whether it, or a device on it, is mounted at `/`.
|
||||
fn holds_root(&self) -> bool {
|
||||
self.mountpoint.as_deref() == Some("/")
|
||||
|| self
|
||||
.mountpoints
|
||||
/// Its mount points: `mountpoints`, or `mountpoint` from an older lsblk.
|
||||
fn mounts(&self) -> impl Iterator<Item = &str> {
|
||||
self.mountpoint.as_deref().into_iter().chain(
|
||||
self.mountpoints
|
||||
.iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|mount| mount == "/")
|
||||
|| self.children.iter().any(Device::holds_root)
|
||||
.map(String::as_str),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether it, or a device on it, is mounted at `/`.
|
||||
fn holds_root(&self) -> bool {
|
||||
self.mounts().any(|mount| mount == "/") || self.children.iter().any(Device::holds_root)
|
||||
}
|
||||
|
||||
/// Whether it, or a device on it, holds part of the running system: the
|
||||
/// root, boot, EFI, `/usr`, `/var` or `/home` volume, or active swap.
|
||||
fn holds_system(&self) -> bool {
|
||||
self.mounts().any(|mount| SYSTEM_MOUNTS.contains(&mount))
|
||||
|| self.children.iter().any(Device::holds_system)
|
||||
}
|
||||
|
||||
/// What decides whether setup may erase this whole disk.
|
||||
@@ -281,7 +303,7 @@ impl Host for System {
|
||||
.filter(|d| d.kind == "disk" || d.kind == "loop" && !d.ro && d.size > 0)
|
||||
.map(|d| Disk {
|
||||
removal: d.facts().removal(),
|
||||
system: d.holds_root(),
|
||||
system: d.holds_system(),
|
||||
bytes: d.size,
|
||||
name: match d.model.as_deref().map(str::trim) {
|
||||
Some(model) if !model.is_empty() => model.to_owned(),
|
||||
@@ -547,7 +569,8 @@ mod tests {
|
||||
"parttype": "0x83", "partuuid": null, "pkname": "sda"}]}]}"#;
|
||||
let new: Listing = serde_json::from_str(new).unwrap();
|
||||
let usb = &new.blockdevices[0];
|
||||
assert!(usb.rm && !usb.holds_root());
|
||||
// Its active swap makes it part of the running system.
|
||||
assert!(usb.rm && !usb.holds_root() && usb.holds_system());
|
||||
assert_eq!(usb.children[0].content(), "EFI");
|
||||
assert_eq!(
|
||||
usb.children[0].mount(),
|
||||
@@ -558,7 +581,7 @@ mod tests {
|
||||
let old: Listing = serde_json::from_str(old).unwrap();
|
||||
let ssd = &old.blockdevices[0];
|
||||
assert_eq!(ssd.size, 500_107_862_016);
|
||||
assert!(!ssd.rm && ssd.holds_root());
|
||||
assert!(!ssd.rm && ssd.holds_root() && ssd.holds_system());
|
||||
assert_eq!(ssd.children[0].content(), "0x83");
|
||||
assert_eq!(usb.facts().removal(), Removal::Usb);
|
||||
assert_eq!(ssd.facts().removal(), Removal::Fixed);
|
||||
@@ -580,6 +603,26 @@ mod tests {
|
||||
assert!(require_system_device(&[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disk_holding_boot_home_or_swap_is_never_offered() {
|
||||
let source = r#"{"blockdevices": [
|
||||
{"name":"nvme0n1","type":"disk","tran":"nvme","mountpoint":null,"children":[
|
||||
{"name":"nvme0n1p2","type":"part","mountpoint":"/"}]},
|
||||
{"name":"sdb","type":"disk","tran":"usb","rm":true,"mountpoint":null,"children":[
|
||||
{"name":"sdb1","type":"part","mountpoint":"/boot/efi"}]},
|
||||
{"name":"sdc","type":"disk","tran":"usb","rm":true,"mountpoint":null,"children":[
|
||||
{"name":"sdc1","type":"part","mountpoints":["/home"]}]},
|
||||
{"name":"sdd","type":"disk","tran":"usb","rm":true,"mountpoint":null,"children":[
|
||||
{"name":"sdd1","type":"part","mountpoint":"/media/me/STELA"}]}]}"#;
|
||||
let listing: Listing = serde_json::from_str(source).unwrap();
|
||||
let system: Vec<bool> = listing
|
||||
.blockdevices
|
||||
.iter()
|
||||
.map(Device::holds_system)
|
||||
.collect();
|
||||
assert_eq!(system, [true, true, true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removal_kind_follows_transport_not_hotplug() {
|
||||
let listing = r#"{"blockdevices": [
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
//! are read and written through the physical drive, a sector at a time as
|
||||
//! Windows requires, and a USB is erased by writing setup's own layout to
|
||||
//! its whole disk, with its volumes locked and dismounted.
|
||||
use super::{Bus, Cpu, Disk, DiskFacts, FileSystem, Host, Partition, PartitionInfo, Volume};
|
||||
use super::{
|
||||
Bus, Cpu, Disk, DiskFacts, FileSystem, Host, Partition, PartitionInfo, Volume,
|
||||
drive_names::{self, disk_number, nvidia_device, partition_number},
|
||||
};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
@@ -157,24 +160,6 @@ fn same_guid(a: &GUID, b: &GUID) -> bool {
|
||||
(a.data1, a.data2, a.data3, a.data4) == (b.data1, b.data2, b.data3, b.data4)
|
||||
}
|
||||
|
||||
/// `diskN` → N; `diskNpM` → (N, M).
|
||||
fn disk_number(identifier: &str) -> Result<u32> {
|
||||
identifier
|
||||
.strip_prefix("disk")
|
||||
.filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|n| n.parse().ok())
|
||||
.with_context(|| format!("{identifier} is not a whole disk such as disk2"))
|
||||
}
|
||||
|
||||
fn partition_number(identifier: &str) -> Result<(u32, u32)> {
|
||||
identifier
|
||||
.strip_prefix("disk")
|
||||
.and_then(|rest| rest.split_once('p'))
|
||||
.and_then(|(disk, partition)| Some((disk.parse().ok()?, partition.parse().ok()?)))
|
||||
.filter(|(_, partition)| *partition > 0)
|
||||
.with_context(|| format!("{identifier} is not a partition such as disk2p1"))
|
||||
}
|
||||
|
||||
fn drive_path(disk: u32) -> String {
|
||||
format!(r"\\.\PhysicalDrive{disk}")
|
||||
}
|
||||
@@ -789,19 +774,9 @@ impl Host for System {
|
||||
if usb.is_dir() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(name) = usb.to_str() else {
|
||||
let Some(identifier) = usb.to_str().and_then(drive_names::whole_disk) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = name.to_ascii_lowercase();
|
||||
let name = name.strip_prefix(r"\\.\").unwrap_or(&name);
|
||||
let Some(number) = name
|
||||
.strip_prefix("physicaldrive")
|
||||
.or_else(|| name.strip_prefix("disk"))
|
||||
.filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let identifier = format!("disk{number}");
|
||||
Ok(self
|
||||
.disks()?
|
||||
.into_iter()
|
||||
@@ -863,25 +838,3 @@ impl Host for System {
|
||||
Ok(gpus)
|
||||
}
|
||||
}
|
||||
|
||||
/// The PCI device ID in an NVIDIA device's instance ID, such as
|
||||
/// `PCI\VEN_10DE&DEV_2C02&SUBSYS_...`.
|
||||
fn nvidia_device(instance: &str) -> Option<u16> {
|
||||
let device = instance.strip_prefix("PCI\\VEN_10DE&DEV_")?.get(..4)?;
|
||||
u16::from_str_radix(device, 16).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::nvidia_device;
|
||||
|
||||
#[test]
|
||||
fn instance_ids_name_nvidia_devices() {
|
||||
let id = "PCI\\VEN_10DE&DEV_2C02&SUBSYS_88921043&REV_A1\\4&1A2B3C4D&0&0019";
|
||||
assert_eq!(nvidia_device(id), Some(0x2c02));
|
||||
assert_eq!(
|
||||
nvidia_device("PCI\\VEN_1002&DEV_164E&SUBSYS_88771043"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user