//! High-level VM creation and lifecycle management.
use std::collections::BTreeSet;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, Read, Write};
use std::os::fd::{AsRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use fs2::FileExt;
use rustix::fs::{AtFlags, FileType, Mode, OFlags, RenameFlags};
use uuid::Uuid;
use crate::backup::{
BackupManifest, CONFIG_FILE as BACKUP_CONFIG_FILE, DISK_FILE as BACKUP_DISK_FILE,
TPM_STATE_DIR as BACKUP_TPM_STATE_DIR, UEFI_VARS_FILE as BACKUP_UEFI_VARS_FILE,
validate_tpm_state_name,
};
use crate::config::{
Acceleration, AudioMode, DirectoryShare, DiskFormat, Firmware, NetworkMode, NetworkProtocol,
PointerDevice, PortForward, UsbHostDevice, VmConfig,
};
use crate::paths::{AppPaths, ensure_private_dir};
use crate::qemu::{
CommandSpec, HostCapabilities, RuntimeFiles, build_command, build_swtpm_command,
prepare_uefi_vars,
};
use crate::qga::{GuestAgentClient, ShutdownMode};
use crate::qmp::QmpClient;
use crate::state::{VmState, process_exists};
const MAX_SCREENSHOT_BYTES: u64 = 256 * 1024 * 1024;
const MAX_PPM_HEADER_BYTES: usize = 4096;
const MAX_PPM_TOKEN_BYTES: usize = 32;
const SNAPSHOT_REVERT_MARKER: &str = ".snapshot-revert-in-progress";
/// Input for creating a new VM definition and system disk.
#[derive(Debug, Clone)]
pub struct CreateOptions {
/// VM name.
pub name: String,
/// QEMU image size such as `64G`.
pub disk_size: String,
/// Optional installation ISO.
pub install_media: Option<PathBuf>,
/// Guest memory in MiB.
pub memory_mib: u64,
/// Virtual CPU count.
pub vcpus: u16,
/// Guest boot firmware.
pub firmware: Firmware,
/// Attach a per-VM software TPM 2.0 device.
pub software_tpm2: bool,
}
/// Files removed or intentionally preserved by a VM deletion.
#[derive(Debug, Clone)]
pub struct DeleteReport {
/// Removed TOML definition.
pub definition: PathBuf,
/// Whether the managed system disk was removed.
pub removed_managed_disk: bool,
/// A disk path preserved because it was outside `KnottVM`'s managed location.
pub preserved_disk: Option<PathBuf>,
}
/// Optional offline changes to a VM's compute and host integration settings.
#[derive(Debug, Clone, Default)]
pub struct ConfigureOptions {
/// Replacement memory size in MiB.
pub memory_mib: Option<u64>,
/// Replacement virtual CPU count.
pub vcpus: Option<u16>,
/// Replacement accelerator preference.
pub acceleration: Option<Acceleration>,
/// Replacement network attachment mode.
pub network_mode: Option<NetworkMode>,
/// Replacement host audio backend.
pub audio: Option<AudioMode>,
/// Replacement guest pointer device.
pub pointer_device: Option<PointerDevice>,
/// Replacement guest boot firmware.
pub firmware: Option<Firmware>,
}
/// Current runtime memory reported by QEMU and its configured ceiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BalloonStatus {
/// Guest-reported current memory in bytes.
pub actual_bytes: u64,
/// Boot-time configured memory in MiB.
pub configured_mib: u64,
}
/// Observable VM state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VmStatus {
/// No process is associated with the definition.
Stopped,
/// QEMU answered a QMP status query.
Running { pid: u32, qemu_status: String },
/// State exists but QEMU cannot be reached.
Stale { pid: u32 },
}
/// Coordinates definitions, runtime state, QEMU, and QMP.
pub struct VmManager {
paths: AppPaths,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SnapshotOperation {
List,
Create,
Revert,
Delete,
}
fn ensure_snapshot_tpm_compatible(config: &VmConfig, operation: SnapshotOperation) -> Result<()> {
if config.software_tpm2
&& matches!(
operation,
SnapshotOperation::Create | SnapshotOperation::Revert
)
{
bail!(
"internal snapshot creation and reversion are unavailable for software TPM 2 VMs until disk and TPM state can be paired"
);
}
Ok(())
}
fn require_stopped_status(name: &str, status: &VmStatus) -> Result<()> {
match status {
VmStatus::Stopped => Ok(()),
VmStatus::Running { .. } => bail!("VM {name} must be stopped for this operation"),
VmStatus::Stale { pid } => {
bail!("VM {name} has stale runtime state for PID {pid}; resolve it first")
}
}
}
#[derive(Clone, Copy)]
struct SnapshotRevertRecovery<'a> {
host: &'a HostCapabilities,
disk: &'a Path,
rollback_snapshot: &'a str,
marker: &'a Path,
data: &'a Path,
}
impl VmManager {
/// Construct a manager and secure all root directories.
pub fn new(paths: AppPaths) -> Result<Self> {
paths.ensure()?;
Ok(Self { paths })
}
/// Discover roots from the XDG environment.
pub fn discover() -> Result<Self> {
Self::new(AppPaths::discover()?)
}
/// Access resolved application roots.
#[must_use]
pub const fn paths(&self) -> &AppPaths {
&self.paths
}
/// Create a VM definition and an empty qcow2 system disk.
pub fn create(&self, options: &CreateOptions) -> Result<PathBuf> {
let _lock = self.lock(&options.name)?;
let disk_ownership = self.lock_disk_ownership()?;
let config_path = self.paths.config(&options.name)?;
match fs::symlink_metadata(&config_path) {
Ok(_) => bail!("VM {} already exists", options.name),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
if options.disk_size.is_empty()
|| !options
.disk_size
.chars()
.all(|character| character.is_ascii_digit() || "KMGTPE".contains(character))
{
bail!("disk size must look like 64G, 1024M, or 1T");
}
let data = self.paths.data(&options.name)?;
ensure_private_dir(&data)?;
let disk = data.join("system.qcow2");
match fs::symlink_metadata(&disk) {
Ok(_) => bail!(
"refusing to replace existing VM disk {}; resolve the orphan manually",
disk.display()
),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let install_media = options
.install_media
.as_ref()
.map(|media| {
fs::canonicalize(media).with_context(|| {
format!("installation media {} does not exist", media.display())
})
})
.transpose()?;
let mut config = VmConfig::new(options.name.clone(), disk, install_media);
config.memory_mib = options.memory_mib;
config.vcpus = options.vcpus;
config.firmware = options.firmware;
config.software_tpm2 = options.software_tpm2;
self.ensure_unique_disk_owner(&options.name, &config)?;
drop(disk_ownership);
let source = config.to_toml()?;
let host = HostCapabilities::probe()?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let temporary_disk = data.join(format!("system.qcow2.tmp-{}-{nonce}", std::process::id()));
let temporary_config =
config_path.with_extension(format!("toml.tmp-{}-{nonce}", std::process::id()));
let output = Command::new(&host.qemu_img)
.args(["create", "-f", "qcow2"])
.arg(&temporary_disk)
.arg(&options.disk_size)
.output()
.context("failed to execute qemu-img")?;
if !output.status.success() {
let _ = fs::remove_file(&temporary_disk);
bail!(
"qemu-img failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
let mut config_file = match OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary_config)
{
Ok(file) => file,
Err(error) => {
let _ = fs::remove_file(&temporary_disk);
return Err(error).with_context(|| {
format!("failed to stage VM definition {}", config_path.display())
});
}
};
let staged_result = config_file
.write_all(source.as_bytes())
.and_then(|()| config_file.sync_all())
.and_then(|()| File::open(&temporary_disk)?.sync_all());
drop(config_file);
if let Err(error) = staged_result {
let _ = fs::remove_file(&temporary_disk);
let _ = fs::remove_file(&temporary_config);
return Err(error).with_context(|| {
format!(
"failed to prepare VM disk and definition for {}",
options.name
)
});
}
if let Err(error) = publish_file_noreplace(&temporary_disk, &config.disk.path) {
let _ = fs::remove_file(&temporary_disk);
let _ = fs::remove_file(&temporary_config);
return Err(error).with_context(|| {
format!(
"failed to publish VM disk {} without replacing an existing path",
config.disk.path.display()
)
});
}
if let Err(error) = publish_file_noreplace(&temporary_config, &config_path) {
let _ = fs::remove_file(&temporary_config);
return Err(error).with_context(|| {
format!(
"VM definition {} could not be published; the disk is preserved as an orphan at {}",
config_path.display(),
config.disk.path.display()
)
});
}
sync_directory(&data).context("VM was created but syncing its disk directory failed")?;
sync_directory(&self.paths.config_root)
.context("VM was created but syncing its definition directory failed")?;
Ok(config_path)
}
/// Create an independent full-copy clone of a stopped VM.
pub fn clone_vm(&self, source_name: &str, destination_name: &str) -> Result<PathBuf> {
if source_name == destination_name {
bail!("source and destination VM names must differ");
}
let host = HostCapabilities::probe()?;
self.clone_vm_with_host(source_name, destination_name, &host)
}
fn clone_vm_with_host(
&self,
source_name: &str,
destination_name: &str,
host: &HostCapabilities,
) -> Result<PathBuf> {
if source_name == destination_name {
bail!("source and destination VM names must differ");
}
let destination_config_path = self.paths.config(destination_name)?;
self.paths.config(source_name)?;
let (_first_lock, _second_lock) = if source_name < destination_name {
(self.lock(source_name)?, self.lock(destination_name)?)
} else {
(self.lock(destination_name)?, self.lock(source_name)?)
};
let disk_ownership = self.lock_disk_ownership()?;
match self.status_unlocked(source_name)? {
VmStatus::Stopped => {}
VmStatus::Running { .. } => {
bail!("source VM {source_name} must be stopped before cloning");
}
VmStatus::Stale { pid } => {
bail!("source VM {source_name} has stale runtime state for PID {pid}");
}
}
match self.status_unlocked(destination_name)? {
VmStatus::Stopped => {}
VmStatus::Running { pid, .. } => {
bail!("destination VM {destination_name} is already running as PID {pid}");
}
VmStatus::Stale { pid } => {
bail!("destination VM {destination_name} has stale runtime state for PID {pid}");
}
}
self.clean_runtime(source_name)?;
self.clean_runtime(destination_name)?;
ensure_path_absent(&destination_config_path, "destination VM definition")?;
let source = self.config(source_name)?;
self.ensure_unique_disk_owner(source_name, &source)?;
let source_data = self.paths.data(source_name)?;
let destination_data = self.paths.data(destination_name)?;
ensure_private_dir(&destination_data)?;
let destination_disk = destination_data.join("system.qcow2");
let destination_vars = destination_data.join("uefi-vars.fd");
let destination_tpm_state = destination_data.join(BACKUP_TPM_STATE_DIR);
ensure_path_absent(&destination_disk, "destination VM disk")?;
ensure_path_absent(&destination_vars, "destination UEFI variables")?;
ensure_path_absent(&destination_tpm_state, "destination software TPM state")?;
let mut destination = source.clone();
destination_name.clone_into(&mut destination.name);
destination.disk.path.clone_from(&destination_disk);
destination.disk.format = DiskFormat::Qcow2;
destination.generation_id = Some(Uuid::new_v4());
destination.network.mac = None;
destination.network.forwards.clear();
destination.usb_devices.clear();
destination.shares.clear();
self.ensure_unique_disk_owner(destination_name, &destination)?;
drop(disk_ownership);
let definition = destination.to_toml()?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let temporary_disk =
destination_data.join(format!("system.qcow2.clone-{}-{nonce}", std::process::id()));
let mut disk_published = false;
let mut vars_published = false;
let mut definition_published = false;
let result = (|| -> Result<()> {
let output = Command::new(&host.qemu_img)
.arg("convert")
.args(["-f", source.disk.format.qemu_driver(), "-O", "qcow2"])
.arg(&source.disk.path)
.arg(&temporary_disk)
.output()
.context("failed to execute qemu-img convert")?;
if !output.status.success() {
bail!(
"qemu-img convert failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
fs::hard_link(&temporary_disk, &destination_disk).with_context(|| {
format!(
"failed to publish cloned disk {}",
destination_disk.display()
)
})?;
disk_published = true;
fs::remove_file(&temporary_disk)?;
let source_vars = source_data.join("uefi-vars.fd");
match fs::symlink_metadata(&source_vars) {
Ok(_) => {
copy_regular_file_new(&source_vars, &destination_vars)?;
vars_published = true;
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&destination_config_path)?;
definition_published = true;
file.write_all(definition.as_bytes())?;
file.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary_disk);
if definition_published {
let _ = fs::remove_file(&destination_config_path);
}
if vars_published {
let _ = fs::remove_file(&destination_vars);
}
if disk_published {
let _ = fs::remove_file(&destination_disk);
}
}
result?;
Ok(destination_config_path)
}
/// Attach read-only installation media to a stopped VM.
pub fn media_attach(&self, name: &str, media: &Path) -> Result<PathBuf> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let media = fs::canonicalize(media)
.with_context(|| format!("installation media {} does not exist", media.display()))?;
if !media.is_file() {
bail!(
"installation media {} is not a regular file",
media.display()
);
}
let mut config = self.config(name)?;
config.install_media = Some(media.clone());
self.save_config_unlocked(name, &config)?;
Ok(media)
}
/// Detach installation media from a stopped VM.
pub fn media_detach(&self, name: &str) -> Result<Option<PathBuf>> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
let detached = config.install_media.take();
self.save_config_unlocked(name, &config)?;
Ok(detached)
}
/// Grow a stopped VM's system disk by a positive amount such as `20G`.
pub fn disk_grow(&self, name: &str, amount: &str) -> Result<()> {
let amount = validate_growth_amount(amount)?;
let _lock = self.lock(name)?;
let disk_ownership = self.lock_disk_ownership()?;
self.require_stopped_unlocked(name)?;
let config = self.config(name)?;
self.ensure_unique_disk_owner(name, &config)?;
drop(disk_ownership);
let host = HostCapabilities::probe()?;
let output = Command::new(&host.qemu_img)
.arg("resize")
.args(["-f", config.disk.format.qemu_driver()])
.arg(&config.disk.path)
.arg(format!("+{amount}"))
.output()
.context("failed to execute qemu-img resize")?;
if !output.status.success() {
bail!(
"qemu-img resize failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(())
}
/// Return `qemu-img` JSON information for a stopped VM's system disk.
pub fn disk_info(&self, name: &str) -> Result<serde_json::Value> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let config = self.config(name)?;
let host = HostCapabilities::probe()?;
let output = Command::new(&host.qemu_img)
.arg("info")
.arg("--output=json")
.arg(&config.disk.path)
.output()
.context("failed to execute qemu-img info")?;
if !output.status.success() {
bail!(
"qemu-img info failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
serde_json::from_slice(&output.stdout).context("qemu-img returned invalid JSON")
}
/// Add a validated user-network port forward to a stopped VM.
pub fn port_add(&self, name: &str, forward: PortForward) -> Result<()> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
config.network.forwards.push(forward);
self.save_config_unlocked(name, &config)
}
/// Remove a user-network port forward from a stopped VM.
pub fn port_remove(
&self,
name: &str,
protocol: NetworkProtocol,
host_address: std::net::Ipv4Addr,
host_port: u16,
) -> Result<PortForward> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
let index = config
.network
.forwards
.iter()
.position(|forward| {
forward.protocol == protocol
&& forward.host_address == host_address
&& forward.host_port == host_port
})
.with_context(|| {
format!(
"no {} port forward listens on {host_address}:{host_port}",
protocol.qemu_name()
)
})?;
let removed = config.network.forwards.remove(index);
self.save_config_unlocked(name, &config)?;
Ok(removed)
}
/// Assign an exact host USB bus and address to a stopped VM.
pub fn usb_add(&self, name: &str, device: UsbHostDevice) -> Result<()> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
config.usb_devices.push(device);
config
.usb_devices
.sort_unstable_by_key(|device| (device.bus, device.address));
self.save_config_unlocked(name, &config)
}
/// Remove an exact host USB bus and address from a stopped VM.
pub fn usb_remove(&self, name: &str, device: UsbHostDevice) -> Result<UsbHostDevice> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
let index = config
.usb_devices
.iter()
.position(|configured| configured == &device)
.with_context(|| {
format!(
"no USB host device is configured at bus {} address {}",
device.bus, device.address
)
})?;
let removed = config.usb_devices.remove(index);
self.save_config_unlocked(name, &config)?;
Ok(removed)
}
/// Add a canonical host directory share to a stopped VM.
pub fn share_add(
&self,
name: &str,
tag: String,
path: &Path,
read_only: bool,
) -> Result<DirectoryShare> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let path = fs::canonicalize(path)
.with_context(|| format!("shared host directory {} does not exist", path.display()))?;
let metadata = fs::symlink_metadata(&path)?;
if !metadata.is_dir() {
bail!("shared host path {} is not a directory", path.display());
}
let share = DirectoryShare {
tag,
path,
read_only,
};
let mut config = self.config(name)?;
config.shares.push(share.clone());
config
.shares
.sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
self.save_config_unlocked(name, &config)?;
Ok(share)
}
/// Remove a host directory share from a stopped VM by mount tag.
pub fn share_remove(&self, name: &str, tag: &str) -> Result<DirectoryShare> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
let index = config
.shares
.iter()
.position(|share| share.tag == tag)
.with_context(|| format!("no host directory share has tag {tag}"))?;
let removed = config.shares.remove(index);
self.save_config_unlocked(name, &config)?;
Ok(removed)
}
/// Atomically update compute, guest, and host integration settings for a stopped VM.
pub fn configure(&self, name: &str, options: &ConfigureOptions) -> Result<VmConfig> {
if options.memory_mib.is_none()
&& options.vcpus.is_none()
&& options.acceleration.is_none()
&& options.network_mode.is_none()
&& options.audio.is_none()
&& options.pointer_device.is_none()
&& options.firmware.is_none()
{
bail!("configure requires at least one setting");
}
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
if let Some(memory_mib) = options.memory_mib {
config.memory_mib = memory_mib;
}
if let Some(vcpus) = options.vcpus {
config.vcpus = vcpus;
}
if let Some(acceleration) = options.acceleration {
config.acceleration = acceleration;
}
if let Some(network_mode) = options.network_mode {
config.network.mode = network_mode;
}
if let Some(audio) = options.audio {
config.audio = audio;
}
if let Some(pointer_device) = options.pointer_device {
config.pointer_device = pointer_device;
}
if let Some(firmware) = options.firmware {
config.firmware = firmware;
}
self.save_config_unlocked(name, &config)?;
Ok(config)
}
/// Create a portable, integrity-checked backup directory for a stopped VM.
pub fn backup_create(&self, name: &str, destination: &Path) -> Result<BackupManifest> {
let host = HostCapabilities::probe()?;
self.backup_create_with_host(name, destination, &host)
}
fn backup_create_with_host(
&self,
name: &str,
destination: &Path,
host: &HostCapabilities,
) -> Result<BackupManifest> {
let _lock = self.lock(name)?;
let disk_ownership = self.lock_disk_ownership()?;
self.require_stopped_unlocked(name)?;
self.clean_runtime(name)?;
let source = self.config(name)?;
self.ensure_unique_disk_owner(name, &source)?;
drop(disk_ownership);
ensure_path_absent(destination, "backup destination")?;
let source_data = self.paths.data(name)?;
ensure_private_dir(&source_data)?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let staging = source_data.join(format!(".backup-stage-{}-{nonce}", std::process::id()));
fs::create_dir(&staging)?;
ensure_private_dir(&staging)?;
let destination_parent_path = destination.parent().unwrap_or_else(|| Path::new("."));
let destination_name = destination
.file_name()
.context("backup destination must have a directory name")?;
let destination_parent = PinnedDir::open(destination_parent_path)?;
let publication_name = format!(".knottvm-backup-{}-{nonce}", std::process::id());
let mut publication_directory = None;
let mut published = false;
let result = (|| -> Result<BackupManifest> {
let backup_disk = staging.join(BACKUP_DISK_FILE);
let output = Command::new(&host.qemu_img)
.arg("convert")
.args(["-f", source.disk.format.qemu_driver(), "-O", "qcow2"])
.arg(&source.disk.path)
.arg(&backup_disk)
.output()
.context("failed to execute qemu-img convert for backup")?;
if !output.status.success() {
bail!(
"qemu-img backup conversion failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
secure_regular_file(&backup_disk)?;
let mut portable = source.clone();
portable.disk.path = PathBuf::from(BACKUP_DISK_FILE);
portable.disk.format = DiskFormat::Qcow2;
portable.install_media = None;
portable.usb_devices.clear();
portable.shares.clear();
let config_path = staging.join(BACKUP_CONFIG_FILE);
write_new_file(&config_path, portable.to_toml()?.as_bytes())?;
let source_vars = source_data.join("uefi-vars.fd");
match fs::symlink_metadata(&source_vars) {
Ok(_) => {
copy_regular_file_new(&source_vars, &staging.join(BACKUP_UEFI_VARS_FILE))?;
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let source_tpm_state = source_data.join(BACKUP_TPM_STATE_DIR);
let has_tpm_state = match fs::symlink_metadata(&source_tpm_state) {
Ok(_) => true,
Err(error) if error.kind() == io::ErrorKind::NotFound => false,
Err(error) => return Err(error.into()),
};
if portable.software_tpm2 || has_tpm_state {
if has_tpm_state {
ensure_private_dir(&source_tpm_state)?;
validate_tpm_state_directory(&source_tpm_state)?;
}
copy_tpm_state_directory(
&source_tpm_state,
&staging.join(BACKUP_TPM_STATE_DIR),
!has_tpm_state,
)?;
}
let manifest = BackupManifest::build(&staging, name.to_owned())?;
manifest.save(&staging)?;
let verified = Self::backup_verify_with_host(&staging, host)?;
if verified != manifest {
bail!("staged backup manifest changed unexpectedly");
}
rustix::fs::mkdirat(&destination_parent.fd, &publication_name, Mode::RWXU)
.with_context(|| {
format!(
"failed to create private backup publication directory under {}",
destination_parent_path.display()
)
})?;
publication_directory = destination_parent.open_child(&publication_name)?;
let publication_directory = publication_directory
.as_ref()
.context("new backup publication directory disappeared")?;
publication_directory
.copy_regular_from(&staging.join(BACKUP_CONFIG_FILE), BACKUP_CONFIG_FILE)?;
publication_directory
.copy_regular_from(&staging.join(BACKUP_DISK_FILE), BACKUP_DISK_FILE)?;
if manifest.uefi_vars.is_some() {
publication_directory.copy_regular_from(
&staging.join(BACKUP_UEFI_VARS_FILE),
BACKUP_UEFI_VARS_FILE,
)?;
}
if let Some(tpm_state) = &manifest.tpm_state {
copy_tpm_state_to_pinned(
publication_directory,
&staging.join(BACKUP_TPM_STATE_DIR),
tpm_state,
)?;
}
publication_directory.copy_regular_from(
&staging.join(crate::backup::MANIFEST_FILE),
crate::backup::MANIFEST_FILE,
)?;
publication_directory.sync()?;
rustix::fs::renameat_with(
&destination_parent.fd,
&publication_name,
&destination_parent.fd,
destination_name,
RenameFlags::NOREPLACE,
)?;
published = true;
destination_parent.sync()?;
Ok(manifest)
})();
cleanup_backup_directory(&staging);
if result.is_err()
&& !published
&& let Some(directory) = publication_directory.take()
{
cleanup_pinned_backup_directory(&directory);
destination_parent.remove_child_dir_if_matches(&publication_name, &directory);
}
result
}
/// Verify hashes, schema, and qcow2 structure for a portable backup.
pub fn backup_verify(&self, root: &Path) -> Result<BackupManifest> {
let host = HostCapabilities::probe()?;
Self::backup_verify_with_host(root, &host)
}
fn backup_verify_with_host(root: &Path, host: &HostCapabilities) -> Result<BackupManifest> {
let metadata = fs::symlink_metadata(root)
.with_context(|| format!("failed to inspect backup root {}", root.display()))?;
if !metadata.is_dir() {
bail!("backup root {} is not a directory", root.display());
}
let manifest = BackupManifest::load(root)?;
manifest.verify(root)?;
let config = VmConfig::load(&root.join(BACKUP_CONFIG_FILE))?;
if config.name != manifest.source_name {
bail!("backup manifest and portable definition names do not match");
}
if config.software_tpm2 && manifest.tpm_state.is_none() {
bail!("backup configuration and TPM state manifest do not match");
}
validate_standalone_qcow2(host, &root.join(BACKUP_DISK_FILE))?;
Ok(manifest)
}
/// Restore a verified backup under a new VM name and independent identity.
pub fn backup_restore(&self, root: &Path, destination_name: &str) -> Result<PathBuf> {
let host = HostCapabilities::probe()?;
self.backup_restore_with_host(root, destination_name, &host)
}
fn backup_restore_with_host(
&self,
root: &Path,
destination_name: &str,
host: &HostCapabilities,
) -> Result<PathBuf> {
let original_manifest = Self::backup_verify_with_host(root, host)?;
let _lock = self.lock(destination_name)?;
let disk_ownership = self.lock_disk_ownership()?;
self.require_stopped_unlocked(destination_name)?;
self.clean_runtime(destination_name)?;
let destination_config_path = self.paths.config(destination_name)?;
ensure_path_absent(&destination_config_path, "destination VM definition")?;
let destination_data = self.paths.data(destination_name)?;
ensure_private_dir(&destination_data)?;
let destination_directory = PinnedDir::open(&destination_data)?;
let destination_disk = destination_data.join("system.qcow2");
let destination_vars = destination_data.join("uefi-vars.fd");
let destination_tpm_state = destination_data.join(BACKUP_TPM_STATE_DIR);
let marker = destination_data.join(".restore-in-progress");
let temporary_disk = destination_data.join(".restore-disk.tmp");
let staging = destination_data.join(".restore-stage");
require_restore_marker_clear(&destination_directory, &marker)?;
ensure_path_absent(&destination_disk, "destination VM disk")?;
ensure_path_absent(&destination_vars, "destination UEFI variables")?;
ensure_path_absent(&destination_tpm_state, "destination software TPM state")?;
ensure_path_absent(&temporary_disk, "destination restore staging disk")?;
ensure_path_absent(&staging, "destination restore staging directory")?;
write_new_file(&marker, original_manifest.source_name.as_bytes())?;
let result = (|| -> Result<()> {
fs::create_dir(&staging)?;
ensure_private_dir(&staging)?;
copy_regular_file_new(
&root.join(crate::backup::MANIFEST_FILE),
&staging.join(crate::backup::MANIFEST_FILE),
)?;
copy_regular_file_new(
&root.join(BACKUP_CONFIG_FILE),
&staging.join(BACKUP_CONFIG_FILE),
)?;
copy_regular_file_new(
&root.join(BACKUP_DISK_FILE),
&staging.join(BACKUP_DISK_FILE),
)?;
if original_manifest.uefi_vars.is_some() {
copy_regular_file_new(
&root.join(BACKUP_UEFI_VARS_FILE),
&staging.join(BACKUP_UEFI_VARS_FILE),
)?;
}
if let Some(tpm_state) = &original_manifest.tpm_state {
copy_tpm_state_directory(
&root.join(BACKUP_TPM_STATE_DIR),
&staging.join(BACKUP_TPM_STATE_DIR),
false,
)?;
if tpm_state.is_empty() && !staging.join(BACKUP_TPM_STATE_DIR).is_dir() {
bail!("backup TPM state staging directory was not created");
}
}
let staged_manifest = Self::backup_verify_with_host(&staging, host)?;
if staged_manifest != original_manifest {
bail!("backup changed while it was being staged for restore");
}
let mut source = VmConfig::load(&staging.join(BACKUP_CONFIG_FILE))?;
if source.name != staged_manifest.source_name {
bail!("backup manifest and portable definition names do not match");
}
if source.software_tpm2 && staged_manifest.tpm_state.is_none() {
bail!("backup configuration and TPM state manifest do not match");
}
let staged_disk = staging.join(BACKUP_DISK_FILE);
if fs::canonicalize(&source.disk.path)? != fs::canonicalize(&staged_disk)? {
bail!("portable backup definition references an unexpected disk path");
}
destination_name.clone_into(&mut source.name);
source.disk.path.clone_from(&destination_disk);
source.disk.format = DiskFormat::Qcow2;
source.generation_id = Some(Uuid::new_v4());
source.install_media = None;
source.network.mac = None;
source.network.forwards.clear();
source.usb_devices.clear();
source.shares.clear();
self.ensure_unique_disk_owner(destination_name, &source)?;
drop(disk_ownership);
let definition = source.to_toml()?;
let output = Command::new(&host.qemu_img)
.arg("convert")
.args(["-f", "qcow2", "-O", "qcow2"])
.arg(&staged_disk)
.arg(&temporary_disk)
.output()
.context("failed to execute qemu-img convert for restore")?;
if !output.status.success() {
bail!(
"qemu-img restore conversion failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
fs::hard_link(&temporary_disk, &destination_disk)?;
fs::remove_file(&temporary_disk)?;
if staged_manifest.uefi_vars.is_some() {
copy_regular_file_new(&staging.join(BACKUP_UEFI_VARS_FILE), &destination_vars)?;
}
if staged_manifest.tpm_state.is_some() {
copy_tpm_state_directory(
&staging.join(BACKUP_TPM_STATE_DIR),
&destination_tpm_state,
false,
)?;
}
write_new_file(&destination_config_path, definition.as_bytes())?;
cleanup_backup_directory(&staging);
destination_directory.remove_regular(".restore-in-progress")?;
destination_directory.sync()?;
sync_directory(&self.paths.config_root)?;
Ok(())
})();
// Keep the marker and every artifact after an error. A future invocation
// will stop for manual inspection instead of guessing which paths this
// process still owns after a crash or concurrent filesystem change.
result?;
Ok(destination_config_path)
}
/// Delete a stopped VM definition and only its known managed artifacts.
pub fn delete_vm(&self, name: &str) -> Result<DeleteReport> {
let _lock = self.lock(name)?;
let _disk_ownership = self.lock_disk_ownership()?;
self.require_stopped_unlocked(name)?;
let definition = self.paths.config(name)?;
let tombstone = definition.with_extension("toml.deleting");
let (config, needs_tombstone) = match fs::symlink_metadata(&definition) {
Ok(metadata) if metadata.is_file() => {
let config = self.config(name)?;
self.ensure_unique_disk_owner(name, &config)?;
ensure_path_absent(&tombstone, "VM deletion tombstone")?;
(config, true)
}
Ok(_) => bail!(
"VM definition {} is not a regular file",
definition.display()
),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let metadata = fs::symlink_metadata(&tombstone).with_context(|| {
format!("VM {name} does not exist and has no deletion to resume")
})?;
if !metadata.is_file() {
bail!(
"VM deletion tombstone {} is not a regular file",
tombstone.display()
);
}
let config = VmConfig::load(&tombstone)?;
if config.name != name {
bail!("VM deletion tombstone name does not match {name}");
}
self.ensure_unique_disk_owner(name, &config)?;
(config, false)
}
Err(error) => return Err(error.into()),
};
let data = self.paths.data(name)?;
let data_root = PinnedDir::open(&self.paths.data_root)?;
let data_directory = data_root.open_child(name)?;
let managed_disk = data.join("system.qcow2");
let owns_managed_disk = config.disk.path == managed_disk;
let preserved_disk = (!owns_managed_disk).then(|| config.disk.path.clone());
if needs_tombstone {
fs::rename(&definition, &tombstone)
.with_context(|| format!("failed to begin durable deletion of VM {name}"))?;
sync_directory(&self.paths.config_root)?;
}
self.clean_runtime(name)?;
if let Some(data_directory) = &data_directory {
if owns_managed_disk {
// Recheck after runtime cleanup immediately before unlinking.
// The durable tombstone keeps this disk visible to concurrent
// owner checks while deletion is in progress.
self.ensure_unique_disk_owner(name, &config)
.context("disk ownership changed while deleting the VM")?;
data_directory.remove_regular("system.qcow2")?;
}
data_directory.remove_regular("uefi-vars.fd")?;
data_directory.remove_child_regular_tree(BACKUP_TPM_STATE_DIR)?;
data_directory.sync()?;
}
drop(data_directory);
let _ = fs::remove_dir(&data);
fs::remove_file(&tombstone)?;
sync_directory(&self.paths.config_root)?;
Ok(DeleteReport {
definition,
removed_managed_disk: owns_managed_disk,
preserved_disk,
})
}
/*
* Keep backup validation and destructive lifecycle operations above the
* ordinary configuration accessors so their ordering invariants remain
* visible together.
*/
/// Load a named definition.
pub fn config(&self, name: &str) -> Result<VmConfig> {
let config = VmConfig::load(&self.paths.config(name)?)?;
if config.name != name {
bail!(
"VM definition filename {name}.toml does not match internal name {}",
config.name
);
}
Ok(config)
}
/// Build the exact QEMU command without launching it.
pub fn command(&self, name: &str) -> Result<CommandSpec> {
let _lock = self.lock(name)?;
self.ensure_no_unresolved_snapshot_revert(name)?;
let config = self.config(name)?;
let host = HostCapabilities::probe()?;
let data = self.paths.data(name)?;
ensure_private_dir(&data)?;
let runtime = self.runtime_files(name, &data)?;
if config.firmware.uses_uefi() {
prepare_uefi_vars(&host, config.firmware, &runtime.uefi_vars)?;
}
build_command(&config, &host, &runtime)
}
/// Launch QEMU as a daemon and record its private control endpoints.
pub fn start(&self, name: &str) -> Result<VmState> {
let host = HostCapabilities::probe()?;
self.start_with_host(name, &host)
}
fn start_with_host(&self, name: &str, host: &HostCapabilities) -> Result<VmState> {
let _lock = self.lock(name)?;
let disk_ownership = self.lock_disk_ownership()?;
match self.status_unlocked(name)? {
VmStatus::Running { pid, .. } => bail!("VM {name} is already running as PID {pid}"),
VmStatus::Stale { pid } if process_exists(pid) => {
bail!(
"VM {name} has a live PID {pid} but QMP is unavailable; use `knottvm kill {name}` after checking the process"
);
}
VmStatus::Stale { .. } | VmStatus::Stopped => {}
}
self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())?;
let mut config = self.config(name)?;
if config.generation_id.is_none() {
config.generation_id = Some(Uuid::new_v4());
self.save_config_unlocked(name, &config)?;
}
self.ensure_unique_disk_owner(name, &config)?;
drop(disk_ownership);
let data = self.paths.data(name)?;
let runtime_dir = self.paths.runtime(name)?;
ensure_private_dir(&data)?;
ensure_private_dir(&runtime_dir)?;
let files = self.runtime_files(name, &data)?;
if config.firmware.uses_uefi() {
prepare_uefi_vars(host, config.firmware, &files.uefi_vars)?;
}
for path in [
&files.qmp_socket,
&files.display_socket,
&files.agent_socket,
&files.pid_file,
] {
remove_if_exists(path)?;
}
let mut command = build_command(&config, host, &files)?;
let launch_marker = runtime_dir.join("launching");
create_launch_marker(&launch_marker, std::process::id())?;
if config.software_tpm2 {
let result = (|| -> Result<()> {
ensure_private_dir(&files.tpm_state_dir)?;
validate_tpm_state_directory(&files.tpm_state_dir)?;
let swtpm = build_swtpm_command(&config, host, &files)?
.context("software TPM command was unexpectedly omitted")?;
launch_swtpm(&swtpm)?;
wait_for_swtpm(&files, Duration::from_secs(5))?;
Ok(())
})();
if let Err(error) = result {
if let Err(cleanup_error) =
self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
{
bail!(
"{error:#}; software TPM cleanup failed and runtime state was preserved: {cleanup_error:#}"
);
}
return Err(error);
}
}
let launch = (|| -> Result<Output> {
let mut output = launch_qemu(&command, &launch_marker)?;
if !output.status.success()
&& config.acceleration == crate::config::Acceleration::Auto
&& host.kvm_available
&& is_kvm_initialization_failure(&output.stderr)
// Retry only if QEMU failed before publishing a PID file.
&& fs::symlink_metadata(&files.pid_file)
.is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
{
let mut fallback_host = host.clone();
fallback_host.kvm_available = false;
command = build_command(&config, &fallback_host, &files)?;
output = launch_qemu(&command, &launch_marker)?;
}
Ok(output)
})();
let output = match launch {
Ok(output) => output,
Err(error) => {
if let Err(cleanup_error) =
self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
{
bail!(
"{error:#}; software TPM cleanup failed and runtime state was preserved: {cleanup_error:#}"
);
}
return Err(error);
}
};
if !output.status.success() {
if let Ok(pid) = read_pid(&files.pid_file)
&& process_exists(pid)
{
bail!(
"QEMU reported startup failure but PID {pid} is live; runtime files were preserved"
);
}
if let Err(cleanup_error) =
self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
{
bail!(
"QEMU failed to start: {}; runtime cleanup failed and runtime state was preserved: {cleanup_error:#}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
bail!(
"QEMU failed to start: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
let startup = (|| {
let pid = read_pid(&files.pid_file)?;
wait_for_socket(&files.qmp_socket, pid, Duration::from_secs(5))?;
wait_for_socket(&files.display_socket, pid, Duration::from_secs(5))?;
wait_for_socket(&files.agent_socket, pid, Duration::from_secs(5))?;
let state = VmState::new(
name.to_owned(),
pid,
files.qmp_socket.clone(),
files.display_socket.clone(),
Some(files.agent_socket.clone()),
);
state.save(&runtime_dir.join("state.json"))?;
remove_if_exists(&launch_marker)?;
Ok(state)
})();
match startup {
Ok(state) => Ok(state),
Err(error) => {
let pid = read_pid(&files.pid_file).ok();
let live = pid.is_some_and(process_exists);
let stopped = if live {
QmpClient::connect(&files.qmp_socket)
.and_then(|mut qmp| qmp.quit())
.and_then(|()| {
wait_for_exit(pid.unwrap_or_default(), Duration::from_secs(3))
})
.is_ok()
} else {
true
};
if !stopped {
bail!(
"{error:#}; QEMU may still be running and runtime files were preserved for recovery"
);
}
if let Err(cleanup_error) =
self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
{
bail!(
"{error:#}; runtime cleanup failed and runtime state was preserved: {cleanup_error:#}"
);
}
Err(error)
}
}
}
/// Query QMP when possible and distinguish stopped from stale state.
pub fn status(&self, name: &str) -> Result<VmStatus> {
let _lock = self.lock(name)?;
self.status_unlocked(name)
}
/// Request ACPI power-off and escalate to QMP quit after the timeout.
pub fn stop(&self, name: &str, timeout: Duration) -> Result<()> {
let _lock = self.lock(name)?;
let Some(state) = self.load_state(name)? else {
let runtime = self.paths.runtime(name)?;
if ["swtpm.pid", "tpm.sock", "tpm-ctrl.sock"]
.iter()
.any(|file| fs::symlink_metadata(runtime.join(file)).is_ok())
{
return self.clean_runtime(name);
}
bail!("VM is not running");
};
if !process_exists(state.pid) {
self.clean_runtime(name)?;
return Ok(());
}
// Reject an unrepresentable timeout before requesting guest shutdown.
let preflight_deadline = Instant::now()
.checked_add(timeout)
.context("VM shutdown timeout is too large")?;
if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| {
qmp.resume_if_paused()?;
qmp.system_powerdown()
}) {
return self.stop_after_control_error(name, state.pid, error);
}
let deadline = deadline_after_shutdown_request(Instant::now(), timeout, preflight_deadline);
while Instant::now() < deadline {
if !process_exists(state.pid) {
self.clean_runtime(name)?;
return Ok(());
}
thread::sleep(Duration::from_millis(100));
}
if !process_exists(state.pid) {
self.clean_runtime(name)?;
return Ok(());
}
if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| qmp.quit()) {
return self.stop_after_control_error(name, state.pid, error);
}
wait_for_exit(state.pid, Duration::from_secs(3))?;
self.clean_runtime(name)
}
fn stop_after_control_error(&self, name: &str, pid: u32, error: anyhow::Error) -> Result<()> {
// An endpoint may disappear during either handshake or a command.
// Preserve runtime state whenever the captured process is still live.
if process_exists(pid) {
Err(error)
} else {
self.clean_runtime(name)
}
}
/// Stop QEMU immediately through QMP.
pub fn kill(&self, name: &str) -> Result<()> {
let _lock = self.lock(name)?;
let Some(state) = self.load_state(name)? else {
return self.clean_runtime(name);
};
if process_exists(state.pid) {
if !state.qmp_socket.exists() {
bail!(
"refusing to discard live state for PID {} without its QMP socket",
state.pid
);
}
if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| qmp.quit()) {
return self.stop_after_control_error(name, state.pid, error);
}
wait_for_exit(state.pid, Duration::from_secs(3))?;
}
self.clean_runtime(name)
}
/// Pause all virtual CPUs through QMP.
pub fn pause(&self, name: &str) -> Result<()> {
let _lock = self.lock(name)?;
self.qmp_unlocked(name)?.pause()
}
/// Resume all virtual CPUs through QMP.
pub fn resume(&self, name: &str) -> Result<()> {
let _lock = self.lock(name)?;
self.qmp_unlocked(name)?.resume()
}
/// Reset the virtual machine through QMP.
pub fn reset(&self, name: &str) -> Result<()> {
let _lock = self.lock(name)?;
self.qmp_unlocked(name)?.reset()
}
/// Return the running VM's guest-reported balloon state.
pub fn balloon_status(&self, name: &str) -> Result<BalloonStatus> {
let _lock = self.lock(name)?;
let configured_mib = self.config(name)?.memory_mib;
let actual_bytes = self.qmp_unlocked(name)?.query_balloon()?;
Ok(BalloonStatus {
actual_bytes,
configured_mib,
})
}
/// Request a bounded runtime memory target for a running VM.
pub fn balloon_set(&self, name: &str, memory_mib: u64) -> Result<()> {
let _lock = self.lock(name)?;
let configured_mib = self.config(name)?.memory_mib;
let bytes = validate_balloon_target(memory_mib, configured_mib)?;
self.qmp_unlocked(name)?.set_balloon(bytes)
}
/// Restore a running VM's balloon target to its configured boot memory.
pub fn balloon_restore(&self, name: &str) -> Result<u64> {
let _lock = self.lock(name)?;
let configured_mib = self.config(name)?.memory_mib;
let bytes = validate_balloon_target(configured_mib, configured_mib)?;
self.qmp_unlocked(name)?.set_balloon(bytes)?;
Ok(configured_mib)
}
/// Capture a running VM's current framebuffer as a new bounded PPM file.
pub fn screenshot(&self, name: &str, destination: &Path) -> Result<u64> {
let _lock = self.lock(name)?;
ensure_path_absent(destination, "screenshot destination")?;
let runtime = self.paths.runtime(name)?;
let staging = runtime.join("screenshot.ppm");
remove_if_exists(&staging)?;
let result = (|| -> Result<u64> {
self.qmp_unlocked(name)?.screendump(&staging)?;
publish_screenshot(&staging, destination)
})();
let cleanup = remove_if_exists(&staging);
match (result, cleanup) {
(Ok(bytes), Ok(())) => Ok(bytes),
(Err(error), _) | (Ok(_), Err(error)) => Err(error),
}
}
/// Verify that the QEMU Guest Agent inside a running VM responds.
pub fn agent_ping(&self, name: &str) -> Result<()> {
let _lock = self.lock(name)?;
self.agent_unlocked(name)?.ping()
}
/// Return the running guest agent's version and supported command list.
pub fn agent_info(&self, name: &str) -> Result<serde_json::Value> {
let _lock = self.lock(name)?;
self.agent_unlocked(name)?.info()
}
/// Ask the guest operating system to shut down through its guest agent.
pub fn agent_shutdown(&self, name: &str, mode: ShutdownMode) -> Result<()> {
let _lock = self.lock(name)?;
self.agent_unlocked(name)?.shutdown(mode)
}
/// List internal qcow2 snapshots for a stopped VM.
pub fn snapshot_list(&self, name: &str) -> Result<String> {
self.snapshot_command(name, &["-l"], SnapshotOperation::List)
}
/// Create an internal qcow2 snapshot for a stopped VM.
pub fn snapshot_create(&self, name: &str, snapshot: &str) -> Result<()> {
validate_snapshot_name(snapshot)?;
self.snapshot_command(name, &["-c", snapshot], SnapshotOperation::Create)
.map(|_| ())
}
/// Revert a stopped VM to an internal qcow2 snapshot.
pub fn snapshot_revert(&self, name: &str, snapshot: &str) -> Result<()> {
self.snapshot_revert_with_probe(name, snapshot, HostCapabilities::probe)
}
fn snapshot_revert_with_probe(
&self,
name: &str,
snapshot: &str,
probe_host: impl FnOnce() -> Result<HostCapabilities>,
) -> Result<()> {
self.snapshot_revert_with_probes(name, snapshot, || self.status_unlocked(name), probe_host)
}
fn snapshot_revert_with_probes(
&self,
name: &str,
snapshot: &str,
probe_status: impl FnOnce() -> Result<VmStatus>,
probe_host: impl FnOnce() -> Result<HostCapabilities>,
) -> Result<()> {
validate_snapshot_name(snapshot)?;
let _lock = self.lock(name)?;
let disk_ownership = self.lock_disk_ownership()?;
let status = probe_status()?;
require_stopped_status(name, &status)?;
let mut config = self.config(name)?;
let original_config = config.clone();
ensure_snapshot_tpm_compatible(&config, SnapshotOperation::Revert)?;
self.ensure_unique_disk_owner(name, &config)?;
drop(disk_ownership);
if config.disk.format != DiskFormat::Qcow2 {
bail!("internal snapshots require a qcow2 system disk");
}
let host = probe_host()?;
let disk = config.disk.path.clone();
let data = self.paths.data(name)?;
ensure_private_dir(&data)?;
let marker = data.join(SNAPSHOT_REVERT_MARKER);
ensure_path_absent(&marker, "snapshot revert transaction marker")?;
let rollback_snapshot = format!("knottvm-revert-{}", Uuid::new_v4().simple());
let marker_contents =
format!("rollback_snapshot={rollback_snapshot}\nrequested_snapshot={snapshot}\n");
write_new_file(&marker, marker_contents.as_bytes())
.context("failed to create snapshot revert recovery marker")?;
if let Err(error) = sync_directory(&data) {
let cleanup = remove_if_exists(&marker);
return Err(match cleanup {
Ok(()) => error.context("failed to persist snapshot revert recovery marker"),
Err(cleanup_error) => error.context(format!(
"failed to persist snapshot revert recovery marker; marker cleanup also failed: {cleanup_error:#}"
)),
});
}
if let Err(error) = run_qemu_img_snapshot(&host, &["-c", &rollback_snapshot], &disk) {
return Err(error.context(format!(
"failed to create the snapshot revert safety checkpoint; VM use is blocked by {}",
marker.display()
)));
}
if let Err(error) = run_qemu_img_snapshot(&host, &["-a", snapshot], &disk) {
return Err(Self::finish_failed_snapshot_revert(
SnapshotRevertRecovery {
host: &host,
disk: &disk,
rollback_snapshot: &rollback_snapshot,
marker: &marker,
data: &data,
},
error.context(format!("failed to revert VM {name} to snapshot {snapshot}")),
true,
));
}
config.generation_id = Some(Uuid::new_v4());
if let Err(error) = self.save_config_unlocked(name, &config) {
return Err(self.finish_failed_snapshot_revert_with_original_config(
name,
&original_config,
SnapshotRevertRecovery {
host: &host,
disk: &disk,
rollback_snapshot: &rollback_snapshot,
marker: &marker,
data: &data,
},
error.context("disk snapshot reverted but VMGenID publication failed"),
));
}
if let Err(error) = sync_directory(&self.paths.config_root) {
return Err(self.finish_failed_snapshot_revert_with_original_config(
name,
&original_config,
SnapshotRevertRecovery {
host: &host,
disk: &disk,
rollback_snapshot: &rollback_snapshot,
marker: &marker,
data: &data,
},
error.context("VMGenID directory sync failed after publication"),
));
}
if let Err(error) = run_qemu_img_snapshot(&host, &["-d", &rollback_snapshot], &disk) {
return Err(error.context(format!(
"snapshot revert and VMGenID publication succeeded, but safety checkpoint {rollback_snapshot} could not be removed; VM use is blocked by {}",
marker.display()
)));
}
remove_if_exists(&marker).context(format!(
"snapshot revert succeeded but recovery marker {} could not be removed",
marker.display()
))?;
sync_directory(&data)
.context("snapshot revert succeeded but syncing its data directory failed")?;
Ok(())
}
fn finish_failed_snapshot_revert(
recovery: SnapshotRevertRecovery<'_>,
cause: anyhow::Error,
restore_disk: bool,
) -> anyhow::Error {
if restore_disk
&& let Err(rollback_error) = run_qemu_img_snapshot(
recovery.host,
&["-a", recovery.rollback_snapshot],
recovery.disk,
)
{
return cause.context(format!(
"failed to restore the original disk from safety checkpoint {}: {rollback_error:#}; VM use is blocked by {}",
recovery.rollback_snapshot,
recovery.marker.display()
));
}
if let Err(checkpoint_error) = run_qemu_img_snapshot(
recovery.host,
&["-d", recovery.rollback_snapshot],
recovery.disk,
) {
return cause.context(format!(
"original disk and VMGenID were restored, but safety checkpoint {} could not be removed: {checkpoint_error:#}; VM use is blocked by {}",
recovery.rollback_snapshot,
recovery.marker.display()
));
}
if let Err(marker_error) = remove_if_exists(recovery.marker) {
return cause.context(format!(
"original disk and VMGenID were restored, but recovery marker {} remains: {marker_error:#}",
recovery.marker.display()
));
}
if let Err(sync_error) = sync_directory(recovery.data) {
return cause.context(format!(
"original disk and VMGenID were restored, but syncing recovery cleanup failed: {sync_error:#}"
));
}
cause
}
fn finish_failed_snapshot_revert_with_original_config(
&self,
name: &str,
original_config: &VmConfig,
recovery: SnapshotRevertRecovery<'_>,
cause: anyhow::Error,
) -> anyhow::Error {
if let Err(rollback_error) = run_qemu_img_snapshot(
recovery.host,
&["-a", recovery.rollback_snapshot],
recovery.disk,
) {
return cause.context(format!(
"failed to restore the original disk from safety checkpoint {}: {rollback_error:#}; VM use is blocked by {}",
recovery.rollback_snapshot,
recovery.marker.display()
));
}
let config_restore = match self.config(name) {
Ok(current) if current.generation_id == original_config.generation_id => Ok(()),
Ok(_) => self
.save_config_unlocked(name, original_config)
.and_then(|()| sync_directory(&self.paths.config_root)),
Err(error) => Err(error),
};
if let Err(config_error) = config_restore {
return cause.context(format!(
"original disk was restored but the original VM definition could not be confirmed or restored: {config_error:#}; VM use is blocked by {}",
recovery.marker.display()
));
}
Self::finish_failed_snapshot_revert(recovery, cause, false)
}
/// Delete an internal qcow2 snapshot from a stopped VM.
pub fn snapshot_delete(&self, name: &str, snapshot: &str) -> Result<()> {
validate_snapshot_name(snapshot)?;
self.snapshot_command(name, &["-d", snapshot], SnapshotOperation::Delete)
.map(|_| ())
}
/// Return the stable VM Generation ID exposed to the guest.
pub fn generation_id(&self, name: &str) -> Result<Option<Uuid>> {
Ok(self.config(name)?.generation_id)
}
/// Replace a stopped VM's generation ID after an external duplication event.
pub fn regenerate_generation_id(&self, name: &str) -> Result<Uuid> {
let _lock = self.lock(name)?;
self.require_stopped_unlocked(name)?;
let mut config = self.config(name)?;
let generation_id = Uuid::new_v4();
config.generation_id = Some(generation_id);
self.save_config_unlocked(name, &config)?;
Ok(generation_id)
}
/// Load current runtime state for the console.
pub fn running_state(&self, name: &str) -> Result<VmState> {
match self.status(name)? {
VmStatus::Running { .. } => self
.load_state(name)?
.context("running VM did not have state metadata"),
VmStatus::Stopped => bail!("VM {name} is stopped"),
VmStatus::Stale { pid } => bail!("VM {name} has stale state for PID {pid}"),
}
}
/// Return definition names in deterministic order.
pub fn list(&self) -> Result<Vec<String>> {
let mut names = fs::read_dir(&self.paths.config_root)?
.filter_map(Result::ok)
.filter_map(|entry| {
let path = entry.path();
(path.extension().and_then(|value| value.to_str()) == Some("toml"))
.then(|| path.file_stem()?.to_str().map(ToOwned::to_owned))
.flatten()
})
.collect::<Vec<_>>();
names.sort();
Ok(names)
}
fn status_unlocked(&self, name: &str) -> Result<VmStatus> {
self.paths.config(name)?;
self.ensure_no_unresolved_snapshot_revert(name)?;
let Some(state) = self.load_state(name)? else {
let runtime = self.paths.runtime(name)?;
let swtpm_pid_file = runtime.join("swtpm.pid");
match fs::symlink_metadata(&swtpm_pid_file) {
Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
let pid = read_process_pid(&swtpm_pid_file, "swtpm")?;
if process_exists(pid) {
return Ok(VmStatus::Stale { pid });
}
}
Ok(_) => bail!("software TPM PID file is not a regular file"),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
if probe_unix_socket(&runtime.join("tpm-ctrl.sock"))?
|| probe_unix_socket(&runtime.join("tpm.sock"))?
{
bail!(
"software TPM is live without recoverable PID state; use `knottvm kill {name}` after checking the process"
);
}
return Ok(VmStatus::Stopped);
};
if !process_exists(state.pid) {
return Ok(VmStatus::Stale { pid: state.pid });
}
match QmpClient::connect(&state.qmp_socket).and_then(|mut qmp| {
if qmp.query_name()? != name {
bail!("QMP endpoint belongs to a different VM");
}
qmp.query_status()
}) {
Ok(qemu_status) => {
if self.config(name)?.software_tpm2 {
let swtpm_pid_file = self.paths.runtime(name)?.join("swtpm.pid");
if !fs::symlink_metadata(&swtpm_pid_file).is_ok_and(|metadata| {
metadata.is_file() && !metadata.file_type().is_symlink()
}) || !read_process_pid(&swtpm_pid_file, "swtpm").is_ok_and(process_exists)
{
return Ok(VmStatus::Stale { pid: state.pid });
}
}
Ok(VmStatus::Running {
pid: state.pid,
qemu_status,
})
}
Err(_) => Ok(VmStatus::Stale { pid: state.pid }),
}
}
fn require_stopped_unlocked(&self, name: &str) -> Result<()> {
let status = self.status_unlocked(name)?;
require_stopped_status(name, &status)
}
fn ensure_no_unresolved_snapshot_revert(&self, name: &str) -> Result<()> {
let data = self.paths.data(name)?;
match fs::symlink_metadata(&data) {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
Ok(metadata) if !metadata.is_dir() || metadata.file_type().is_symlink() => {
bail!(
"VM data directory {} is not a real directory",
data.display()
);
}
Ok(_) => {}
}
let marker = data.join(SNAPSHOT_REVERT_MARKER);
match fs::symlink_metadata(&marker) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
bail!(
"VM {name} has an unresolved snapshot revert transaction at {}; inspect its rollback checkpoint before use",
marker.display()
);
}
Ok(_) => bail!(
"snapshot revert transaction marker {} is not a regular file",
marker.display()
),
}
}
fn save_config_unlocked(&self, name: &str, config: &VmConfig) -> Result<()> {
if config.name != name {
bail!("refusing to save a VM definition under a different name");
}
let path = self.paths.config(name)?;
let metadata = fs::symlink_metadata(&path)
.with_context(|| format!("failed to inspect VM definition {}", path.display()))?;
if !metadata.is_file() {
bail!("VM definition {} is not a regular file", path.display());
}
let source = config.to_toml()?;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let temporary = path.with_extension(format!("toml.tmp-{}-{nonce}", std::process::id()));
let result = (|| -> Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
file.write_all(source.as_bytes())?;
file.sync_all()?;
fs::rename(&temporary, &path)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result.with_context(|| format!("failed to update VM definition {}", path.display()))
}
fn qmp_unlocked(&self, name: &str) -> Result<QmpClient> {
let state = self.load_state(name)?.context("VM is not running")?;
if !process_exists(state.pid) {
bail!("VM {name} has stale state for PID {}", state.pid);
}
let mut qmp = QmpClient::connect(&state.qmp_socket)?;
if qmp.query_name()? != name {
bail!("QMP endpoint does not belong to VM {name}");
}
Ok(qmp)
}
fn agent_unlocked(&self, name: &str) -> Result<GuestAgentClient> {
let state = self.load_state(name)?.context("VM is not running")?;
if !process_exists(state.pid) {
bail!("VM {name} has stale state for PID {}", state.pid);
}
let socket = match state.agent_socket {
Some(socket) => socket,
None => self.paths.runtime(name)?.join("agent.sock"),
};
GuestAgentClient::connect(&socket)
}
fn snapshot_command(
&self,
name: &str,
arguments: &[&str],
operation: SnapshotOperation,
) -> Result<String> {
let _lock = self.lock(name)?;
let _disk_ownership = self.lock_disk_ownership()?;
self.snapshot_command_unlocked(name, arguments, operation)
}
fn snapshot_command_unlocked(
&self,
name: &str,
arguments: &[&str],
operation: SnapshotOperation,
) -> Result<String> {
match self.status_unlocked(name)? {
VmStatus::Stopped => {}
VmStatus::Running { .. } => {
bail!("VM {name} must be stopped before changing internal snapshots");
}
VmStatus::Stale { pid } => {
bail!("VM {name} has stale runtime state for PID {pid}; resolve it first");
}
}
let config = self.config(name)?;
ensure_snapshot_tpm_compatible(&config, operation)?;
self.ensure_unique_disk_owner(name, &config)?;
if config.disk.format != DiskFormat::Qcow2 {
bail!("internal snapshots require a qcow2 system disk");
}
let host = HostCapabilities::probe()?;
run_qemu_img_snapshot(&host, arguments, &config.disk.path)
}
fn ensure_unique_disk_owner(&self, name: &str, config: &VmConfig) -> Result<()> {
let disk = disk_reference(&config.disk.path).with_context(|| {
format!(
"failed to resolve guest disk {}",
config.disk.path.display()
)
})?;
for (other_name, definition) in self.disk_owner_definitions()? {
if other_name == name {
continue;
}
let other = VmConfig::load(&definition).with_context(|| {
format!(
"cannot verify disk ownership because VM definition {other_name} is invalid"
)
})?;
let other_disk = disk_reference(&other.disk.path).with_context(|| {
format!(
"cannot verify disk ownership because VM {other_name} references {}",
other.disk.path.display()
)
})?;
let same_path = other_disk.path == disk.path;
let same_file = matches!((disk.identity, other_disk.identity),
(Some(first), Some(second)) if first == second);
if same_path || same_file {
bail!(
"VM definitions {name} and {other_name} reference the same system disk {}",
disk.path.display()
);
}
}
Ok(())
}
/// Return every current or pending VM definition that can own a disk.
/// Deletion tombstones remain owners until their managed artifacts are
/// removed and the tombstone itself is durably cleared.
fn disk_owner_definitions(&self) -> Result<Vec<(String, PathBuf)>> {
let mut definitions = Vec::new();
let mut names = BTreeSet::new();
for entry in fs::read_dir(&self.paths.config_root)? {
let entry = entry?;
let path = entry.path();
let filename = entry.file_name();
let bytes = filename.as_bytes();
let name_bytes = if let Some(name) = bytes.strip_suffix(b".toml.deleting") {
name
} else if let Some(name) = bytes.strip_suffix(b".toml") {
name
} else {
continue;
};
let name = std::str::from_utf8(name_bytes)
.context("cannot verify disk ownership for a non-UTF-8 VM definition name")?;
crate::config::validate_name(name).with_context(|| {
format!("cannot verify disk ownership for invalid name {name:?}")
})?;
let metadata = fs::symlink_metadata(&path)
.with_context(|| format!("cannot inspect VM definition {}", path.display()))?;
if !metadata.is_file() {
bail!(
"cannot verify disk ownership because VM definition {} is not a regular file",
path.display()
);
}
if !names.insert(name.to_owned()) {
bail!(
"cannot verify disk ownership because VM {name} has both a definition and a pending deletion"
);
}
definitions.push((name.to_owned(), path));
}
definitions.sort_by(|left, right| left.0.cmp(&right.0));
Ok(definitions)
}
fn runtime_files(&self, name: &str, data: &Path) -> Result<RuntimeFiles> {
let runtime = self.paths.runtime(name)?;
Ok(RuntimeFiles {
qmp_socket: runtime.join("qmp.sock"),
display_socket: runtime.join("display.sock"),
agent_socket: runtime.join("agent.sock"),
pid_file: runtime.join("qemu.pid"),
uefi_vars: data.join("uefi-vars.fd"),
tpm_socket: runtime.join("tpm.sock"),
tpm_control_socket: runtime.join("tpm-ctrl.sock"),
swtpm_pid_file: runtime.join("swtpm.pid"),
tpm_state_dir: data.join("tpm-state"),
})
}
fn stop_swtpm(&self, name: &str, ioctl_override: Option<&Path>) -> Result<()> {
let data = self.paths.data(name)?;
let files = self.runtime_files(name, &data)?;
stop_swtpm_files(&files, ioctl_override)
.with_context(|| format!("failed to stop software TPM for VM {name}"))?;
Ok(())
}
fn load_state(&self, name: &str) -> Result<Option<VmState>> {
let path = self.paths.runtime(name)?.join("state.json");
if path.exists() {
return VmState::load(&path).map(Some);
}
let runtime = self.paths.runtime(name)?;
let pid_file = runtime.join("qemu.pid");
if pid_file.exists() {
let pid = read_pid(&pid_file)?;
let state = VmState::new(
name.to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
Some(runtime.join("agent.sock")),
);
if process_exists(pid)
&& let Ok(mut qmp) = QmpClient::connect(&state.qmp_socket)
&& matches!(qmp.query_name(), Ok(ref qemu_name) if qemu_name == name)
{
state.save(&path)?;
}
return Ok(Some(state));
}
let launch_marker = runtime.join("launching");
if launch_marker.exists() {
let qmp_socket = runtime.join("qmp.sock");
if let Ok(mut qmp) = QmpClient::connect(&qmp_socket)
&& matches!(qmp.query_name(), Ok(ref qemu_name) if qemu_name == name)
{
bail!("VM {name} is running without a recoverable QEMU PID file");
}
if runtime.join("swtpm.pid").exists() {
return Ok(None);
}
let marker_age = fs::metadata(&launch_marker)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| modified.elapsed().ok())
.unwrap_or_default();
if marker_age < Duration::from_secs(10) {
bail!("VM {name} has an incomplete launch in progress; retry shortly");
}
let display_socket = runtime.join("display.sock");
if UnixStream::connect(&display_socket).is_ok() {
bail!("VM {name} has a live display endpoint without recoverable PID state");
}
for stale in [qmp_socket, display_socket, launch_marker] {
remove_if_exists(&stale)?;
}
}
for endpoint in [runtime.join("qmp.sock"), runtime.join("display.sock")] {
if endpoint.exists() {
bail!(
"orphan runtime endpoint {} exists without recoverable PID state",
endpoint.display()
);
}
}
Ok(None)
}
fn clean_runtime(&self, name: &str) -> Result<()> {
self.clean_runtime_with_ioctl(name, None)
}
fn clean_runtime_with_ioctl(&self, name: &str, ioctl_override: Option<&Path>) -> Result<()> {
self.stop_swtpm(name, ioctl_override)?;
let runtime = self.paths.runtime(name)?;
for file in [
"state.json",
"qemu.pid",
"qmp.sock",
"display.sock",
"agent.sock",
"screenshot.ppm",
"launching",
"swtpm.pid",
"tpm.sock",
"tpm-ctrl.sock",
] {
remove_if_exists(&runtime.join(file))?;
}
Ok(())
}
fn lock(&self, name: &str) -> Result<VmLock> {
let runtime = self.paths.runtime(name)?;
ensure_private_dir(&runtime)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(runtime.join("operation.lock"))?;
file.lock_exclusive()?;
Ok(VmLock(file))
}
/// Serialize ownership scans and deletion's tombstone/unlink window across
/// manager processes. Callers acquire per-VM locks first.
fn lock_disk_ownership(&self) -> Result<VmLock> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(self.paths.runtime_root.join("disk-ownership.lock"))?;
file.lock_exclusive()
.context("failed to acquire VM disk ownership lock")?;
Ok(VmLock(file))
}
}
struct VmLock(File);
struct DiskReference {
path: PathBuf,
identity: Option<(u64, u64)>,
}
/// Resolve existing aliases and prospective paths whose final file is absent.
/// Missing peer parents and dangling symlinks fail closed in ownership checks.
fn disk_reference(path: &Path) -> Result<DiskReference> {
let resolved = match fs::symlink_metadata(path) {
Ok(_) => fs::canonicalize(path)
.with_context(|| format!("failed to canonicalize disk path {}", path.display()))?,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
let filename = path
.file_name()
.context("disk path has no final filename")?;
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
fs::canonicalize(parent)
.with_context(|| format!("failed to resolve disk parent {}", parent.display()))?
.join(filename)
}
Err(error) => {
return Err(error)
.with_context(|| format!("failed to inspect disk path {}", path.display()));
}
};
let identity = match fs::metadata(&resolved) {
Ok(metadata) => Some((metadata.dev(), metadata.ino())),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => {
return Err(error).with_context(|| {
format!("failed to inspect resolved disk {}", resolved.display())
});
}
};
Ok(DiskReference {
path: resolved,
identity,
})
}
impl Drop for VmLock {
fn drop(&mut self) {
let _ = FileExt::unlock(&self.0);
}
}
fn read_pid(path: &Path) -> Result<u32> {
let mut source = String::new();
File::open(path)
.with_context(|| format!("QEMU did not create PID file {}", path.display()))?
.read_to_string(&mut source)?;
source
.trim()
.parse::<u32>()
.with_context(|| format!("invalid QEMU PID in {}", path.display()))
}
fn wait_for_socket(path: &Path, pid: u32, timeout: Duration) -> Result<()> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if path.exists() {
return Ok(());
}
if !process_exists(pid) {
bail!("QEMU exited before creating {}", path.display());
}
thread::sleep(Duration::from_millis(25));
}
bail!("timed out waiting for QEMU socket {}", path.display())
}
fn wait_for_exit(pid: u32, timeout: Duration) -> Result<()> {
let deadline = Instant::now()
.checked_add(timeout)
.context("VM exit timeout is too large")?;
while Instant::now() < deadline {
if !process_exists(pid) {
return Ok(());
}
thread::sleep(
deadline
.saturating_duration_since(Instant::now())
.min(Duration::from_millis(50)),
);
}
if !process_exists(pid) {
return Ok(());
}
bail!("QEMU process {pid} did not exit")
}
fn deadline_after_shutdown_request(
now: Instant,
timeout: Duration,
preflight_deadline: Instant,
) -> Instant {
now.checked_add(timeout).unwrap_or(preflight_deadline)
}
fn remove_if_exists(path: &Path) -> Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error).with_context(|| format!("failed to remove {}", path.display())),
}
}
fn ensure_path_absent(path: &Path, label: &str) -> Result<()> {
match fs::symlink_metadata(path) {
Ok(_) => bail!("{label} {} already exists", path.display()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
fn validate_tpm_state_directory(path: &Path) -> Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
bail!(
"software TPM state {} is not a real directory",
path.display()
);
}
let uid = unsafe { libc::geteuid() };
if metadata.uid() != uid {
bail!(
"software TPM state {} is owned by another user",
path.display()
);
}
let mut total_bytes = 0_u64;
let mut count = 0_usize;
for entry in fs::read_dir(path)? {
let entry = entry?;
let name = entry.file_name();
let name = name
.to_str()
.context("software TPM state contains a non-UTF-8 filename")?;
validate_tpm_state_name(name)?;
let entry_metadata = fs::symlink_metadata(entry.path())?;
if !entry_metadata.is_file() || entry_metadata.file_type().is_symlink() {
bail!(
"software TPM state entry {} is not a regular file",
entry.path().display()
);
}
if entry_metadata.uid() != uid {
bail!(
"software TPM state entry {} is owned by another user",
entry.path().display()
);
}
total_bytes = total_bytes
.checked_add(entry_metadata.len())
.context("software TPM state size overflow")?;
count += 1;
if count > crate::backup::MAX_TPM_STATE_FILES
|| total_bytes > crate::backup::MAX_TPM_STATE_BYTES
{
bail!("software TPM state exceeds the managed file or size limit");
}
secure_regular_file(&entry.path())?;
}
Ok(())
}
fn copy_tpm_state_directory(source: &Path, destination: &Path, allow_missing: bool) -> Result<()> {
match fs::symlink_metadata(source) {
Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}
Ok(_) => bail!(
"software TPM state {} is not a real directory",
source.display()
),
Err(error) if error.kind() == io::ErrorKind::NotFound && allow_missing => {
fs::create_dir(destination)?;
ensure_private_dir(destination)?;
return Ok(());
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
bail!("software TPM state {} is missing", source.display());
}
Err(error) => return Err(error.into()),
}
fs::create_dir(destination)?;
ensure_private_dir(destination)?;
let mut total_bytes = 0_u64;
let mut count = 0_usize;
for entry in fs::read_dir(source)? {
let entry = entry?;
let name = entry
.file_name()
.into_string()
.map_err(|_| anyhow::anyhow!("software TPM state contains a non-UTF-8 filename"))?;
validate_tpm_state_name(&name)?;
let metadata = fs::symlink_metadata(entry.path())?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
bail!(
"software TPM state entry {} is not a regular file",
entry.path().display()
);
}
count += 1;
if count > crate::backup::MAX_TPM_STATE_FILES {
bail!("software TPM state exceeds the managed file or size limit");
}
let copied = copy_tpm_state_file_new(
&entry.path(),
&destination.join(name),
crate::backup::MAX_TPM_STATE_BYTES,
)?;
total_bytes = total_bytes
.checked_add(copied)
.context("software TPM state size overflow")?;
if total_bytes > crate::backup::MAX_TPM_STATE_BYTES {
bail!("software TPM state exceeds the managed file or size limit");
}
}
sync_directory(destination)
}
fn copy_tpm_state_file_new(source: &Path, destination: &Path, limit: u64) -> Result<u64> {
let mut source_file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(source)
.with_context(|| format!("failed to open TPM state source {}", source.display()))?;
let source_metadata = source_file.metadata()?;
if !source_metadata.is_file() || source_metadata.len() > limit {
bail!(
"TPM state source {} exceeds the managed size limit",
source.display()
);
}
let mut destination_file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(destination)
.with_context(|| format!("failed to create TPM state file {}", destination.display()))?;
let result = (|| -> Result<u64> {
let mut copied = 0_u64;
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = source_file.read(&mut buffer)?;
if read == 0 {
break;
}
copied = copied
.checked_add(u64::try_from(read)?)
.context("TPM state copy size overflow")?;
if copied > limit {
bail!(
"TPM state source {} exceeds the managed size limit",
source.display()
);
}
destination_file.write_all(&buffer[..read])?;
}
if copied != source_metadata.len() || source_file.metadata()?.len() != copied {
bail!(
"TPM state source {} changed while being copied",
source.display()
);
}
destination_file.sync_all()?;
secure_regular_file(destination)?;
Ok(copied)
})();
if result.is_err() {
let _ = fs::remove_file(destination);
}
result
}
fn launch_swtpm(command: &CommandSpec) -> Result<()> {
let mut child = Command::new(&command.program)
.args(&command.args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("failed to launch {}", command.program.display()))?;
let deadline = Instant::now() + Duration::from_secs(3);
loop {
if let Some(status) = child.try_wait()? {
if !status.success() {
bail!("swtpm failed to start with {status}");
}
return Ok(());
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
bail!("swtpm daemonization command timed out");
}
thread::sleep(Duration::from_millis(25));
}
}
fn wait_for_swtpm(files: &RuntimeFiles, timeout: Duration) -> Result<u32> {
let deadline = Instant::now()
.checked_add(timeout)
.context("software TPM startup timeout is too large")?;
loop {
let pid = match fs::symlink_metadata(&files.swtpm_pid_file) {
Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
Some(read_process_pid(&files.swtpm_pid_file, "swtpm")?)
}
Ok(_) => bail!("swtpm PID path is not a regular file"),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
if let Some(pid) = pid {
if !process_exists(pid) {
bail!("swtpm exited before creating its sockets");
}
let server_ready = is_unix_socket(&files.tpm_socket)?;
let control_ready = is_unix_socket(&files.tpm_control_socket)?;
if server_ready && control_ready {
return Ok(pid);
}
}
if Instant::now() >= deadline {
bail!("timed out waiting for swtpm PID and Unix sockets");
}
thread::sleep(Duration::from_millis(25));
}
}
fn is_unix_socket(path: &Path) -> Result<bool> {
match fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_socket() => Ok(true),
Ok(_) => bail!("{} is not a Unix socket", path.display()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
fn stop_swtpm_files(files: &RuntimeFiles, ioctl_override: Option<&Path>) -> Result<()> {
let pid_metadata = match fs::symlink_metadata(&files.swtpm_pid_file) {
Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => Some(metadata),
Ok(_) => bail!("swtpm PID file is not a regular file"),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
let pid = pid_metadata
.as_ref()
.map(|_| read_process_pid(&files.swtpm_pid_file, "swtpm"))
.transpose()?;
let pid_live = pid.is_some_and(process_exists);
let control_exists = fs::symlink_metadata(&files.tpm_control_socket).is_ok();
let command_exists = fs::symlink_metadata(&files.tpm_socket).is_ok();
if pid_live {
if !is_unix_socket(&files.tpm_control_socket)? {
bail!("live swtpm PID has no usable control socket; preserving runtime files");
}
let ioctl = ioctl_override
.map(Path::to_path_buf)
.or_else(find_swtpm_ioctl)
.context("swtpm_ioctl is required to stop a live software TPM")?;
run_swtpm_ioctl_stop(&ioctl, &files.tpm_control_socket)?;
wait_for_process_exit(pid.unwrap_or_default(), Duration::from_secs(3), "swtpm")?;
} else {
let control_live = probe_unix_socket(&files.tpm_control_socket)?;
let command_live = probe_unix_socket(&files.tpm_socket)?;
if control_live {
let ioctl = ioctl_override
.map(Path::to_path_buf)
.or_else(find_swtpm_ioctl)
.context("swtpm_ioctl is required to stop an untracked software TPM")?;
run_swtpm_ioctl_stop(&ioctl, &files.tpm_control_socket)?;
wait_for_unix_socket_closed(&files.tpm_control_socket, Duration::from_secs(3))?;
} else if command_live {
bail!("software TPM command socket is live without recoverable control state");
}
}
if pid.is_some_and(process_exists)
|| probe_unix_socket(&files.tpm_control_socket)?
|| probe_unix_socket(&files.tpm_socket)?
{
bail!("software TPM is still live; preserving its runtime files");
}
if control_exists || command_exists || pid_metadata.is_some() {
remove_swtpm_runtime_file(&files.swtpm_pid_file, false)?;
remove_swtpm_runtime_file(&files.tpm_control_socket, true)?;
remove_swtpm_runtime_file(&files.tpm_socket, true)?;
}
Ok(())
}
fn remove_swtpm_runtime_file(path: &Path, socket: bool) -> Result<()> {
match fs::symlink_metadata(path) {
Ok(metadata)
if if socket {
metadata.file_type().is_socket()
} else {
metadata.is_file() && !metadata.file_type().is_symlink()
} =>
{
fs::remove_file(path)?;
Ok(())
}
Ok(_) => bail!(
"refusing to remove unexpected swtpm runtime entry {}",
path.display()
),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
fn probe_unix_socket(path: &Path) -> Result<bool> {
if !is_unix_socket(path)? {
return Ok(false);
}
match UnixStream::connect(path) {
Ok(_) => Ok(true),
Err(error)
if matches!(
error.kind(),
io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound
) =>
{
Ok(false)
}
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Ok(true),
Err(error) => Err(error.into()),
}
}
fn wait_for_unix_socket_closed(path: &Path, timeout: Duration) -> Result<()> {
let deadline = Instant::now()
.checked_add(timeout)
.context("software TPM shutdown timeout is too large")?;
while probe_unix_socket(path)? {
if Instant::now() >= deadline {
bail!("software TPM control socket remained live after stop request");
}
thread::sleep(Duration::from_millis(25));
}
Ok(())
}
fn run_swtpm_ioctl_stop(ioctl: &Path, control_socket: &Path) -> Result<()> {
let mut child = Command::new(ioctl)
.arg("--unix")
.arg(control_socket)
.arg("--stop")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("failed to execute swtpm_ioctl {}", ioctl.display()))?;
let deadline = Instant::now() + Duration::from_secs(3);
loop {
if let Some(status) = child.try_wait()? {
if !status.success() {
bail!("swtpm_ioctl failed to stop the software TPM");
}
return Ok(());
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
bail!("swtpm_ioctl timed out while stopping the software TPM");
}
thread::sleep(Duration::from_millis(25));
}
}
fn wait_for_process_exit(pid: u32, timeout: Duration, label: &str) -> Result<()> {
let deadline = Instant::now()
.checked_add(timeout)
.with_context(|| format!("{label} exit timeout is too large"))?;
while process_exists(pid) {
if Instant::now() >= deadline {
bail!("{label} process {pid} did not exit");
}
thread::sleep(Duration::from_millis(25));
}
Ok(())
}
fn read_process_pid(path: &Path, label: &str) -> Result<u32> {
let mut source = String::new();
File::open(path)
.with_context(|| format!("{label} did not create PID file {}", path.display()))?
.read_to_string(&mut source)?;
source
.trim()
.parse::<u32>()
.with_context(|| format!("invalid {label} PID in {}", path.display()))
}
fn find_swtpm_ioctl() -> Option<PathBuf> {
std::env::var_os("PATH")
.map(|path| std::env::split_paths(&path).collect::<Vec<_>>())?
.into_iter()
.map(|directory| directory.join("swtpm_ioctl"))
.find(|candidate| candidate.is_file())
}
fn require_restore_marker_clear(directory: &PinnedDir, marker: &Path) -> Result<()> {
match directory.entry_type(".restore-in-progress")? {
Some(FileType::RegularFile) => bail!(
"an earlier restore left {}; all destination files are preserved for manual inspection",
marker.display()
),
Some(_) => bail!("restore marker {} is not a regular file", marker.display()),
None => Ok(()),
}
}
fn copy_regular_file_new(source: &Path, destination: &Path) -> Result<()> {
let mut source_file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(source)
.with_context(|| format!("failed to open clone source {}", source.display()))?;
let metadata = source_file.metadata()?;
if !metadata.is_file() {
bail!("clone source {} is not a regular file", source.display());
}
let mut destination_file = OpenOptions::new()
.write(true)
.create_new(true)
.open(destination)
.with_context(|| format!("failed to create clone target {}", destination.display()))?;
let result = (|| -> Result<()> {
io::copy(&mut source_file, &mut destination_file)?;
destination_file.sync_all()?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(destination);
}
result.with_context(|| {
format!(
"failed to copy {} to {}",
source.display(),
destination.display()
)
})?;
secure_regular_file(destination)
}
fn publish_screenshot(source: &Path, destination: &Path) -> Result<u64> {
let mut source_file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(source)
.with_context(|| {
format!(
"failed to open screenshot staging file {}",
source.display()
)
})?;
let metadata = source_file.metadata()?;
if !metadata.is_file() {
bail!(
"screenshot staging path {} is not a regular file",
source.display()
);
}
if !(3..=MAX_SCREENSHOT_BYTES).contains(&metadata.len()) {
bail!("screenshot exceeded the {MAX_SCREENSHOT_BYTES}-byte limit");
}
let mut source_reader = BufReader::new(&mut source_file);
let header = read_binary_ppm_header(&mut source_reader)?;
let expected_len = u64::try_from(header.bytes.len())?
.checked_add(header.raster_bytes)
.context("PPM screenshot size overflow")?;
if expected_len != metadata.len() {
bail!("PPM dimensions do not match the screenshot raster length");
}
let mut destination_file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(destination)
.with_context(|| format!("failed to create screenshot {}", destination.display()))?;
let result = (|| -> Result<()> {
destination_file.write_all(&header.bytes)?;
let copied = copy_validated_ppm_raster(
&mut source_reader,
&mut destination_file,
header.raster_bytes,
header.max_value,
)?;
if copied
.checked_add(u64::try_from(header.bytes.len())?)
.context("screenshot size overflow")?
!= metadata.len()
{
bail!("screenshot staging file changed while it was being published");
}
let mut trailing = [0_u8; 1];
if source_reader.read(&mut trailing)? != 0 {
bail!("screenshot staging file changed while it was being published");
}
destination_file.sync_all()?;
secure_regular_file(destination)
})();
if result.is_err() {
let _ = fs::remove_file(destination);
}
result?;
Ok(metadata.len())
}
struct BinaryPpmHeader {
bytes: Vec<u8>,
raster_bytes: u64,
max_value: u64,
}
fn read_binary_ppm_header(reader: &mut impl BufRead) -> Result<BinaryPpmHeader> {
if peek_ppm_byte(reader)? != b'P' {
bail!("QEMU screenshot did not contain binary PPM data");
}
let mut bytes = Vec::with_capacity(32);
let magic = read_ppm_token(reader, &mut bytes)?;
if magic != b"P6" {
bail!("QEMU screenshot did not contain binary PPM data");
}
let width = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "width")?;
let height = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "height")?;
let max_value = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "maxval")?;
if width == 0 || height == 0 {
bail!("PPM dimensions must be positive");
}
if !(1..=65_535).contains(&max_value) {
bail!("PPM maxval must be between 1 and 65535");
}
let raster_bytes = width
.checked_mul(height)
.and_then(|pixels| pixels.checked_mul(3))
.and_then(|samples| samples.checked_mul(if max_value < 256 { 1 } else { 2 }))
.context("PPM raster size overflow")?;
Ok(BinaryPpmHeader {
bytes,
raster_bytes,
max_value,
})
}
fn read_ppm_token(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<Vec<u8>> {
loop {
match peek_ppm_byte(reader)? {
byte if byte.is_ascii_whitespace() => {
consume_ppm_byte(reader, header)?;
}
b'#' => consume_ppm_comment(reader, header)?,
_ => break,
}
}
let mut token = Vec::with_capacity(8);
loop {
match peek_ppm_byte(reader)? {
byte if byte.is_ascii_whitespace() => {
let separator = consume_ppm_byte(reader, header)?;
if separator == b'\r' && peek_ppm_byte(reader).ok() == Some(b'\n') {
consume_ppm_byte(reader, header)?;
}
break;
}
b'#' => {
consume_ppm_comment(reader, header)?;
break;
}
_ => {
if token.len() == MAX_PPM_TOKEN_BYTES {
bail!("PPM header token exceeds {MAX_PPM_TOKEN_BYTES} bytes");
}
token.push(consume_ppm_byte(reader, header)?);
}
}
}
if token.is_empty() {
bail!("PPM header contains an empty token");
}
Ok(token)
}
fn peek_ppm_byte(reader: &mut impl BufRead) -> Result<u8> {
reader
.fill_buf()
.context("failed to read PPM header")?
.first()
.copied()
.context("truncated PPM header")
}
fn consume_ppm_byte(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<u8> {
if header.len() == MAX_PPM_HEADER_BYTES {
bail!("PPM header exceeds {MAX_PPM_HEADER_BYTES} bytes");
}
let byte = peek_ppm_byte(reader)?;
reader.consume(1);
header.push(byte);
Ok(byte)
}
fn consume_ppm_comment(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<()> {
if consume_ppm_byte(reader, header)? != b'#' {
bail!("invalid PPM comment");
}
loop {
match consume_ppm_byte(reader, header)? {
b'\n' => return Ok(()),
b'\r' => {
if peek_ppm_byte(reader).ok() == Some(b'\n') {
consume_ppm_byte(reader, header)?;
}
return Ok(());
}
_ => {}
}
}
}
fn parse_ppm_number(token: &[u8], label: &str) -> Result<u64> {
if token.is_empty() || !token.iter().all(u8::is_ascii_digit) {
bail!("PPM {label} is not a decimal integer");
}
token.iter().try_fold(0_u64, |value, byte| {
value
.checked_mul(10)
.and_then(|value| value.checked_add(u64::from(*byte - b'0')))
.context("PPM integer overflow")
})
}
fn copy_validated_ppm_raster(
reader: &mut impl Read,
writer: &mut impl Write,
raster_bytes: u64,
max_value: u64,
) -> Result<u64> {
let bytes_per_sample = if max_value < 256 { 1 } else { 2 };
let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
let mut remaining = raster_bytes;
while remaining > 0 {
let mut chunk_len = usize::try_from(remaining.min(buffer.len() as u64))?;
chunk_len -= chunk_len % bytes_per_sample;
reader
.read_exact(&mut buffer[..chunk_len])
.context("PPM raster is truncated")?;
for sample in buffer[..chunk_len].chunks_exact(bytes_per_sample) {
let value = if bytes_per_sample == 1 {
u64::from(sample[0])
} else {
u64::from(u16::from_be_bytes([sample[0], sample[1]]))
};
if value > max_value {
bail!("PPM raster sample exceeds maxval");
}
}
writer.write_all(&buffer[..chunk_len])?;
remaining -= chunk_len as u64;
}
Ok(raster_bytes)
}
fn write_new_file(path: &Path, contents: &[u8]) -> Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| format!("failed to create {}", path.display()))?;
let result = file
.write_all(contents)
.and_then(|()| file.sync_all())
.map_err(anyhow::Error::from)
.and_then(|()| secure_regular_file(path));
if result.is_err() {
let _ = fs::remove_file(path);
}
result
}
fn secure_regular_file(path: &Path) -> Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() {
bail!("{} is not a regular file", path.display());
}
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
Ok(())
}
struct PinnedDir {
fd: OwnedFd,
}
impl PinnedDir {
fn open(path: &Path) -> Result<Self> {
let fd = rustix::fs::open(
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.with_context(|| format!("failed to pin directory {}", path.display()))?;
Ok(Self { fd })
}
fn open_child(&self, name: &str) -> Result<Option<Self>> {
match rustix::fs::openat(
&self.fd,
name,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => Ok(Some(Self { fd })),
Err(rustix::io::Errno::NOENT) => Ok(None),
Err(error) => Err(error.into()),
}
}
fn remove_regular(&self, name: &str) -> Result<bool> {
if self.entry_type(name)? != Some(FileType::RegularFile) {
return Ok(false);
}
rustix::fs::unlinkat(&self.fd, name, AtFlags::empty())?;
Ok(true)
}
fn remove_child_regular_tree(&self, name: &str) -> Result<bool> {
let Some(child) = self.open_child(name)? else {
return Ok(false);
};
let fd_path = PathBuf::from(format!("/proc/self/fd/{}", child.fd.as_raw_fd()));
for entry in fs::read_dir(fd_path)? {
let entry = entry?;
let name = entry
.file_name()
.into_string()
.map_err(|_| anyhow::anyhow!("managed state contains a non-UTF-8 filename"))?;
validate_tpm_state_name(&name)?;
if child.entry_type(&name)? != Some(FileType::RegularFile) {
bail!("managed TPM state entry {name} is not a regular file");
}
child.remove_regular(&name)?;
}
child.sync()?;
self.remove_child_dir_if_matches(name, &child);
if self.entry_type(name)?.is_some() {
bail!("managed TPM state directory {name} could not be removed");
}
Ok(true)
}
fn entry_type(&self, name: &str) -> Result<Option<FileType>> {
match rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => Ok(Some(FileType::from_raw_mode(stat.st_mode))),
Err(rustix::io::Errno::NOENT) => Ok(None),
Err(error) => Err(error.into()),
}
}
fn copy_regular_from(&self, source: &Path, name: &str) -> Result<()> {
let mut source_file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(source)
.with_context(|| format!("failed to open backup source {}", source.display()))?;
if !source_file.metadata()?.is_file() {
bail!("backup source {} is not a regular file", source.display());
}
let fd = rustix::fs::openat(
&self.fd,
name,
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::RUSR | Mode::WUSR,
)?;
let mut destination = File::from(fd);
let result =
io::copy(&mut source_file, &mut destination).and_then(|_| destination.sync_all());
if result.is_err() {
let _ = rustix::fs::unlinkat(&self.fd, name, AtFlags::empty());
}
result.map_err(Into::into)
}
fn sync(&self) -> Result<()> {
rustix::fs::fsync(&self.fd)?;
Ok(())
}
fn remove_child_dir_if_matches(&self, name: &str, child: &Self) {
let Ok(pinned) = rustix::fs::fstat(&child.fd) else {
return;
};
let Ok(current) = rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW) else {
return;
};
if FileType::from_raw_mode(current.st_mode) == FileType::Directory
&& current.st_dev == pinned.st_dev
&& current.st_ino == pinned.st_ino
{
let _ = rustix::fs::unlinkat(&self.fd, name, AtFlags::REMOVEDIR);
let _ = self.sync();
}
}
}
fn cleanup_backup_directory(path: &Path) {
let Ok(directory) = PinnedDir::open(path) else {
return;
};
cleanup_pinned_backup_directory(&directory);
drop(directory);
let _ = fs::remove_dir(path);
}
fn cleanup_pinned_backup_directory(directory: &PinnedDir) {
for name in [
crate::backup::MANIFEST_FILE,
BACKUP_CONFIG_FILE,
BACKUP_DISK_FILE,
BACKUP_UEFI_VARS_FILE,
] {
let _ = directory.remove_regular(name);
}
let _ = directory.remove_child_regular_tree(BACKUP_TPM_STATE_DIR);
let _ = directory.sync();
}
fn copy_tpm_state_to_pinned(
parent: &PinnedDir,
source: &Path,
files: &std::collections::BTreeMap<String, crate::backup::FileDigest>,
) -> Result<()> {
rustix::fs::mkdirat(&parent.fd, BACKUP_TPM_STATE_DIR, Mode::RWXU)?;
let child = parent
.open_child(BACKUP_TPM_STATE_DIR)?
.context("new backup TPM state directory disappeared")?;
for name in files.keys() {
validate_tpm_state_name(name)?;
child.copy_regular_from(&source.join(name), name)?;
}
child.sync()
}
fn validate_standalone_qcow2(host: &HostCapabilities, path: &Path) -> Result<()> {
let info = Command::new(&host.qemu_img)
.arg("info")
.arg("--output=json")
.arg(path)
.output()
.context("failed to execute qemu-img info for backup")?;
if !info.status.success() {
bail!(
"backup image inspection failed: {}",
String::from_utf8_lossy(&info.stderr).trim()
);
}
let info: serde_json::Value =
serde_json::from_slice(&info.stdout).context("qemu-img info returned invalid JSON")?;
if info.get("format").and_then(serde_json::Value::as_str) != Some("qcow2") {
bail!("backup system disk is not qcow2");
}
for field in ["backing-filename", "full-backing-filename", "data-file"] {
if info.get(field).is_some_and(|value| !value.is_null()) {
bail!("backup system disk uses unsupported external {field}");
}
}
let check = Command::new(&host.qemu_img)
.arg("check")
.args(["-f", "qcow2"])
.arg(path)
.output()
.context("failed to execute qemu-img check for backup")?;
if !check.status.success() {
bail!(
"backup qcow2 validation failed: {}",
String::from_utf8_lossy(&check.stderr).trim()
);
}
Ok(())
}
fn publish_file_noreplace(source: &Path, destination: &Path) -> Result<()> {
rustix::fs::renameat_with(
rustix::fs::CWD,
source,
rustix::fs::CWD,
destination,
RenameFlags::NOREPLACE,
)
.with_context(|| {
format!(
"failed to publish {} without replacing a destination",
source.display()
)
})?;
Ok(())
}
fn run_qemu_img_snapshot(
host: &HostCapabilities,
arguments: &[&str],
disk: &Path,
) -> Result<String> {
let output = Command::new(&host.qemu_img)
.arg("snapshot")
.args(arguments)
.arg(disk)
.output()
.context("failed to execute qemu-img snapshot")?;
if !output.status.success() {
bail!(
"qemu-img snapshot failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
fn sync_directory(path: &Path) -> Result<()> {
File::open(path)?.sync_all()?;
Ok(())
}
fn validate_snapshot_name(name: &str) -> Result<()> {
if name.is_empty()
|| name.len() > 64
|| !name.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_')
})
{
bail!("snapshot name must contain 1-64 ASCII letters, digits, '.', '-', or '_' characters");
}
Ok(())
}
fn validate_growth_amount(amount: &str) -> Result<String> {
let amount = amount.trim().to_ascii_uppercase();
let Some((digits, suffix)) = amount.split_at_checked(amount.len().saturating_sub(1)) else {
bail!("disk growth must look like 20G, 1024M, or 1T");
};
if digits.is_empty()
|| digits.starts_with('0')
|| !digits.bytes().all(|byte| byte.is_ascii_digit())
|| !matches!(suffix, "K" | "M" | "G" | "T" | "P")
{
bail!("disk growth must be a positive size like 20G, 1024M, or 1T");
}
Ok(amount)
}
fn is_kvm_initialization_failure(stderr: &[u8]) -> bool {
let stderr = String::from_utf8_lossy(stderr).to_ascii_lowercase();
[
"failed to initialize kvm",
"could not access kvm kernel module",
"kvm acceleration not available",
"kvm is not supported",
]
.iter()
.any(|message| stderr.contains(message))
}
fn launch_qemu(command: &CommandSpec, launch_marker: &Path) -> Result<Output> {
let mut process = Command::new(&command.program);
process
.args(&command.args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
match process.spawn() {
Ok(child) => child.wait_with_output().with_context(|| {
format!(
"failed to collect output from {}",
command.program.display()
)
}),
Err(error) => {
remove_if_exists(launch_marker).with_context(|| {
format!(
"failed to clean launch marker after failing to launch {}",
command.program.display()
)
})?;
Err(error).with_context(|| format!("failed to launch {}", command.program.display()))
}
}
}
fn create_launch_marker(path: &Path, pid: u32) -> Result<()> {
create_launch_marker_with(path, |marker| {
writeln!(marker, "{pid}")?;
marker.sync_all()
})
}
fn create_launch_marker_with(
path: &Path,
write_marker: impl FnOnce(&mut File) -> io::Result<()>,
) -> Result<()> {
let mut marker = OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| format!("failed to create launch marker {}", path.display()))?;
if let Err(error) = write_marker(&mut marker) {
drop(marker);
remove_if_exists(path).with_context(|| {
format!(
"failed to remove incomplete launch marker {}",
path.display()
)
})?;
return Err(error)
.with_context(|| format!("failed to write launch marker {}", path.display()));
}
Ok(())
}
fn validate_balloon_target(memory_mib: u64, configured_mib: u64) -> Result<u64> {
if !(256..=configured_mib).contains(&memory_mib) {
bail!("balloon target must be between 256 and {configured_mib} MiB");
}
memory_mib
.checked_mul(1024 * 1024)
.context("balloon target byte count overflowed")
}
#[cfg(test)]
mod tests {
use super::{
BACKUP_CONFIG_FILE, BACKUP_DISK_FILE, BACKUP_UEFI_VARS_FILE, CreateOptions,
SNAPSHOT_REVERT_MARKER, SnapshotOperation, VmManager, VmStatus, cleanup_backup_directory,
copy_tpm_state_directory, create_launch_marker_with, deadline_after_shutdown_request,
ensure_snapshot_tpm_compatible, is_kvm_initialization_failure, launch_qemu, launch_swtpm,
publish_file_noreplace, publish_screenshot, read_process_pid, require_restore_marker_clear,
run_swtpm_ioctl_stop, stop_swtpm_files, validate_balloon_target, validate_growth_amount,
validate_snapshot_name, validate_tpm_state_directory, wait_for_exit, wait_for_process_exit,
wait_for_swtpm,
};
use crate::backup::BackupManifest;
use crate::config::{Firmware, PointerDevice, UsbHostDevice, VmConfig};
use crate::paths::AppPaths;
use crate::qemu::{CommandSpec, HostCapabilities};
use crate::state::VmState;
use serde_json::{Value, json};
use std::fs;
use std::io::{self, BufRead, BufReader, Write};
use std::os::unix::fs::{PermissionsExt, symlink};
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::{Duration, Instant};
use tempfile::tempdir;
fn snapshot_fixture(software_tpm2: bool) -> (tempfile::TempDir, VmManager, VmConfig, PathBuf) {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let data = manager.paths().data("test").unwrap();
fs::create_dir_all(&data).unwrap();
let disk = data.join("system.qcow2");
fs::write(&disk, b"snapshot fixture disk").unwrap();
let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
config.software_tpm2 = software_tpm2;
fs::write(
manager.paths().config("test").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
(root, manager, config, disk)
}
fn snapshot_qemu_fixture(
root: &Path,
manager: &VmManager,
disk: &Path,
mode: &str,
) -> (HostCapabilities, PathBuf, PathBuf) {
let qemu_img = root.join("qemu-img-fixture");
let checkpoint = root.join("snapshot-checkpoint");
let checkpoint_name = root.join("snapshot-checkpoint-name");
let log = root.join("snapshot-log");
let observed_config = root.join("config-observed-at-revert");
let config = manager.paths().config("test").unwrap();
let config_root = &manager.paths().config_root;
let script = format!(
"#!/bin/sh\nset -eu\ncase \"$2\" in\n -c)\n cp {disk} {checkpoint}\n printf '%s' \"$3\" > {checkpoint_name}\n printf 'create\\n' >> {log}\n ;;\n -a)\n if [ \"$3\" = target ]; then\n printf 'target-attempt\\n' >> {log}\n cp {config} {observed_config}\n if [ '{mode}' = missing-target ]; then\n printf \"Snapshot '%s' does not exist\\n\" \"$3\" >&2\n exit 1\n fi\n if [ '{mode}' = fail-revert ] || [ '{mode}' = rollback-fails ]; then\n printf 'partial target\\n' > {disk}\n printf 'target failed\\n' >&2\n exit 1\n fi\n printf 'target snapshot\\n' > {disk}\n if [ '{mode}' = config-publish-fails ]; then chmod 0500 {config_root}; fi\n else\n if [ \"$3\" != \"$(cat {checkpoint_name})\" ]; then exit 2; fi\n if [ '{mode}' = rollback-fails ]; then\n printf 'rollback failed\\n' >&2\n exit 1\n fi\n cp {checkpoint} {disk}\n printf 'restore\\n' >> {log}\n fi\n ;;\n -d)\n if [ \"$3\" != \"$(cat {checkpoint_name})\" ]; then exit 2; fi\n printf 'delete-attempt\\n' >> {log}\n if [ '{mode}' = checkpoint-delete-fails ]; then\n printf 'checkpoint deletion failed\\n' >&2\n exit 1\n fi\n rm -f {checkpoint} {checkpoint_name}\n printf 'delete\\n' >> {log}\n ;;\n *) exit 2 ;;\nesac\n",
disk = shell_quote(disk),
checkpoint = shell_quote(&checkpoint),
checkpoint_name = shell_quote(&checkpoint_name),
log = shell_quote(&log),
observed_config = shell_quote(&observed_config),
config = shell_quote(&config),
config_root = shell_quote(config_root),
);
fs::write(&qemu_img, script).unwrap();
fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
let host = HostCapabilities {
qemu: PathBuf::from("/bin/false"),
qemu_img,
swtpm: None,
swtpm_ioctl: None,
kvm_available: false,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
(host, log, observed_config)
}
#[test]
fn lists_only_toml_definitions() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
fs::write(manager.paths().config_root.join("beta.toml"), "").unwrap();
fs::write(manager.paths().config_root.join("alpha.toml"), "").unwrap();
fs::write(manager.paths().config_root.join("ignore.txt"), "").unwrap();
assert_eq!(manager.list().unwrap(), ["alpha", "beta"]);
}
#[test]
fn operation_lock_rejects_a_symlink_without_touching_its_target() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir(&runtime).unwrap();
let target = root.path().join("unrelated-lock-target");
fs::write(&target, b"preserve this file").unwrap();
let lock_path = runtime.join("operation.lock");
symlink(&target, &lock_path).unwrap();
assert!(manager.lock("test").is_err());
assert_eq!(fs::read(&target).unwrap(), b"preserve this file");
assert!(
fs::symlink_metadata(&lock_path)
.unwrap()
.file_type()
.is_symlink()
);
}
#[test]
fn operation_lock_is_created_owner_only() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let _lock = manager.lock("test").unwrap();
let path = manager
.paths()
.runtime("test")
.unwrap()
.join("operation.lock");
assert_eq!(
fs::metadata(path).unwrap().permissions().mode() & 0o777,
0o600
);
}
#[test]
fn disk_ownership_rejects_hard_link_aliases() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let first_disk = root.path().join("first.qcow2");
let second_disk = root.path().join("second.qcow2");
fs::write(&first_disk, b"one shared disk inode").unwrap();
fs::hard_link(&first_disk, &second_disk).unwrap();
for (name, disk) in [("first", first_disk), ("second", second_disk)] {
let config = VmConfig::new(name.to_owned(), disk, None);
fs::write(
manager.paths().config(name).unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
}
let config = manager.config("first").unwrap();
let error = manager
.ensure_unique_disk_owner("first", &config)
.unwrap_err();
assert!(error.to_string().contains("same system disk"));
}
#[test]
fn disk_ownership_rejects_a_future_path_referenced_by_another_vm() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let target_data = manager.paths().data("target").unwrap();
fs::create_dir_all(&target_data).unwrap();
let future_disk = target_data.join("system.qcow2");
let other = VmConfig::new("other".to_owned(), future_disk.clone(), None);
fs::write(
manager.paths().config("other").unwrap(),
other.to_toml().unwrap(),
)
.unwrap();
let target = VmConfig::new("target".to_owned(), future_disk.clone(), None);
let error = manager
.ensure_unique_disk_owner("target", &target)
.unwrap_err();
assert!(error.to_string().contains("same system disk"));
assert!(!future_disk.exists());
}
#[test]
fn disk_ownership_lock_is_private_and_exclusive_across_open_files() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let held = manager.lock_disk_ownership().unwrap();
let lock_path = manager.paths().runtime_root.join("disk-ownership.lock");
assert_eq!(
fs::metadata(&lock_path).unwrap().permissions().mode() & 0o777,
0o600
);
let contender = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(lock_path)
.unwrap();
assert!(fs2::FileExt::try_lock_exclusive(&contender).is_err());
drop(held);
fs2::FileExt::try_lock_exclusive(&contender).unwrap();
fs2::FileExt::unlock(&contender).unwrap();
}
#[test]
fn deletion_preserves_disk_when_invalid_definition_references_it() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let target_data = manager.paths().data("target").unwrap();
fs::create_dir_all(&target_data).unwrap();
let shared_disk = target_data.join("system.qcow2");
fs::write(&shared_disk, b"guest data that must survive").unwrap();
let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
fs::write(
manager.paths().config("target").unwrap(),
target.to_toml().unwrap(),
)
.unwrap();
// This definition still names the same disk, but its filename and
// internal name disagree, so manager.config("other") rejects it.
let mismatched = VmConfig::new("not-other".to_owned(), shared_disk.clone(), None);
let other_definition = manager.paths().config("other").unwrap();
fs::write(&other_definition, mismatched.to_toml().unwrap()).unwrap();
let result = manager.delete_vm("target");
let error = result.unwrap_err();
assert!(error.to_string().contains("same system disk"));
assert_eq!(
fs::read(&shared_disk).unwrap(),
b"guest data that must survive"
);
assert!(manager.paths().config("target").unwrap().is_file());
assert!(other_definition.is_file());
}
#[test]
fn qemu_spawn_failure_removes_launch_marker() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let program = root.path().join("not-executable");
fs::write(&program, b"not an executable").unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o600)).unwrap();
let launch_marker = runtime.join("launching");
fs::write(&launch_marker, "launching\n").unwrap();
let command = CommandSpec {
program,
args: Vec::new(),
};
let error = launch_qemu(&command, &launch_marker).unwrap_err();
assert!(format!("{error:#}").contains("failed to launch"));
assert!(!launch_marker.exists());
assert_eq!(manager.status("test").unwrap(), VmStatus::Stopped);
}
#[test]
fn launch_marker_writer_failure_removes_created_marker() {
let root = tempdir().unwrap();
let launch_marker = root.path().join("launching");
let error = create_launch_marker_with(&launch_marker, |marker| {
marker.write_all(b"partial marker\n")?;
Err(io::Error::other("injected marker sync failure"))
})
.unwrap_err();
assert!(format!("{error:#}").contains("failed to write launch marker"));
assert!(!launch_marker.exists());
}
#[test]
fn launch_marker_create_new_preserves_preexisting_marker() {
let root = tempdir().unwrap();
let launch_marker = root.path().join("launching");
let original = b"pre-existing launch marker\n";
fs::write(&launch_marker, original).unwrap();
let writer_called = std::cell::Cell::new(false);
let error = create_launch_marker_with(&launch_marker, |_| {
writer_called.set(true);
Ok(())
})
.unwrap_err();
assert!(error.to_string().contains("failed to create launch marker"));
assert!(!writer_called.get());
assert_eq!(fs::read(&launch_marker).unwrap(), original);
}
#[test]
fn stop_cleans_runtime_for_an_exited_unreaped_qemu_pid() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sh")
.args(["-c", "exit 0"])
.spawn()
.unwrap();
let pid = child.id();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let deadline = Instant::now() + Duration::from_secs(2);
while crate::state::process_exists(pid) {
assert!(Instant::now() < deadline, "child did not exit");
thread::sleep(Duration::from_millis(5));
}
manager.stop("test", Duration::ZERO).unwrap();
assert!(!state_path.exists());
assert!(child.wait().unwrap().success());
}
#[test]
fn stop_cleans_runtime_if_process_exits_during_qmp_reopen() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
let pid = child.id();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream
.write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
for (expected, response) in [
("qmp_capabilities", json!({})),
("query-name", json!({"name": "test"})),
("query-status", json!({"status": "running"})),
("system_powerdown", json!({})),
] {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let request: Value = serde_json::from_str(&line).unwrap();
assert_eq!(request["execute"], expected);
serde_json::to_writer(
&mut stream,
&json!({"return": response, "id": request["id"]}),
)
.unwrap();
stream.write_all(b"\r\n").unwrap();
}
// Keep the child alive through the timeout check, then exit while
// the manager is opening its second QMP connection.
listener.set_nonblocking(true).unwrap();
let deadline = Instant::now() + Duration::from_secs(2);
let second = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
assert!(Instant::now() < deadline, "missing second QMP connection");
thread::sleep(Duration::from_millis(5));
}
Err(error) => panic!("second QMP accept failed: {error}"),
}
};
// SAFETY: `pid` is the unreaped child created for this test.
let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
let deadline = Instant::now() + Duration::from_secs(2);
while crate::state::process_exists(pid) {
assert!(Instant::now() < deadline, "child did not exit");
thread::sleep(Duration::from_millis(5));
}
drop(second);
});
let result = manager.stop("test", Duration::ZERO);
let server_result = server.join();
let _ = child.kill();
let status = child.wait().unwrap();
server_result.unwrap();
result.unwrap();
assert!(!state_path.exists());
assert!(!runtime.join("qmp.sock").exists());
assert!(!status.success());
}
#[test]
fn stop_cleans_runtime_when_process_exits_at_timeout_boundary() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
let pid = child.id();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream
.write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
for (expected, response) in [
("qmp_capabilities", json!({})),
("query-name", json!({"name": "test"})),
("query-status", json!({"status": "running"})),
("system_powerdown", json!({})),
] {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let request: Value = serde_json::from_str(&line).unwrap();
assert_eq!(request["execute"], expected);
if expected == "system_powerdown" {
let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
// SAFETY: this test owns the unreaped child identified by child_pid.
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
let deadline = Instant::now() + Duration::from_millis(500);
while crate::state::process_exists(pid) {
assert!(
Instant::now() < deadline,
"child did not exit after SIGTERM"
);
thread::sleep(Duration::from_millis(1));
}
}
serde_json::to_writer(
&mut stream,
&json!({"return": response, "id": request["id"]}),
)
.unwrap();
stream.write_all(b"\r\n").unwrap();
}
});
manager.stop("test", Duration::ZERO).unwrap();
server.join().unwrap();
assert!(!state_path.exists());
assert!(!runtime.join("qmp.sock").exists());
assert!(!child.wait().unwrap().success());
}
#[test]
fn wait_for_exit_observes_a_process_absent_at_the_deadline() {
assert!(wait_for_exit(u32::MAX, Duration::ZERO).is_ok());
assert!(wait_for_exit(u32::MAX, Duration::MAX).is_err());
}
#[test]
fn stop_uses_preflight_deadline_if_post_request_deadline_overflows() {
let preflight_deadline = Instant::now();
assert_eq!(
deadline_after_shutdown_request(Instant::now(), Duration::MAX, preflight_deadline),
preflight_deadline
);
}
#[test]
fn stop_cleans_runtime_if_process_exits_during_initial_qmp_handshake() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
let pid = child.id();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let server = thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
// SAFETY: the test owns the unreaped child identified by child_pid.
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
let deadline = Instant::now() + Duration::from_secs(2);
while crate::state::process_exists(pid) {
assert!(Instant::now() < deadline, "child did not exit");
thread::sleep(Duration::from_millis(5));
}
drop(stream);
});
let result = manager.stop("test", Duration::ZERO);
let server_result = server.join();
let _ = child.kill();
let status = child.wait().unwrap();
server_result.unwrap();
result.unwrap();
assert!(!status.success());
assert!(!state_path.exists());
assert!(!runtime.join("qmp.sock").exists());
}
#[test]
fn kill_cleans_runtime_if_process_exits_during_quit_response() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
let pid = child.id();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
pid,
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream
.write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
for (expected, response) in [
("qmp_capabilities", json!({})),
("query-name", json!({"name": "test"})),
] {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let request: Value = serde_json::from_str(&line).unwrap();
assert_eq!(request["execute"], expected);
serde_json::to_writer(
&mut stream,
&json!({"return": response, "id": request["id"]}),
)
.unwrap();
stream.write_all(b"\r\n").unwrap();
}
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let request: Value = serde_json::from_str(&line).unwrap();
assert_eq!(request["execute"], "quit");
let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
// SAFETY: this test owns the unreaped child identified by child_pid.
assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
let deadline = Instant::now() + Duration::from_secs(2);
while crate::state::process_exists(pid) {
assert!(Instant::now() < deadline, "child did not exit");
thread::sleep(Duration::from_millis(5));
}
drop(stream);
});
let result = manager.kill("test");
let server_result = server.join();
let _ = child.kill();
let status = child.wait().unwrap();
server_result.unwrap();
result.unwrap();
assert!(!status.success());
assert!(!state_path.exists());
assert!(!runtime.join("qmp.sock").exists());
}
#[test]
fn stop_preserves_runtime_if_qmp_fails_while_process_is_live() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
let state_path = runtime.join("state.json");
VmState::new(
"test".to_owned(),
child.id(),
runtime.join("qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&state_path)
.unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let server = thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
drop(stream);
});
let result = manager.stop("test", Duration::ZERO);
let server_result = server.join();
let alive = child.try_wait().unwrap().is_none();
let state_retained = state_path.exists();
let _ = child.kill();
let _ = child.wait();
server_result.unwrap();
assert!(result.is_err());
assert!(alive && state_retained);
}
#[test]
fn stop_rejects_an_unrepresentable_timeout_before_contacting_qmp() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir_all(&runtime).unwrap();
let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
VmState::new(
"test".to_owned(),
child.id(),
runtime.join("missing-qmp.sock"),
runtime.join("display.sock"),
None,
)
.save(&runtime.join("state.json"))
.unwrap();
let result = manager.stop("test", Duration::MAX);
let alive = child.try_wait().unwrap().is_none();
let _ = child.kill();
let _ = child.wait();
assert!(alive, "timeout validation must not stop the process");
assert!(
result
.unwrap_err()
.to_string()
.contains("timeout is too large")
);
}
#[test]
fn validates_snapshot_names_before_qemu_img() {
assert!(validate_snapshot_name("before-upgrade_1").is_ok());
assert!(validate_snapshot_name("").is_err());
assert!(validate_snapshot_name("../escape").is_err());
assert!(validate_snapshot_name("has spaces").is_err());
}
#[test]
fn snapshot_tpm_guard_blocks_only_unpaired_disk_rewrites() {
let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
let operations = [
SnapshotOperation::List,
SnapshotOperation::Create,
SnapshotOperation::Revert,
SnapshotOperation::Delete,
];
for operation in operations {
assert!(ensure_snapshot_tpm_compatible(&config, operation).is_ok());
}
config.software_tpm2 = true;
assert!(ensure_snapshot_tpm_compatible(&config, SnapshotOperation::List).is_ok());
assert!(ensure_snapshot_tpm_compatible(&config, SnapshotOperation::Delete).is_ok());
for operation in [SnapshotOperation::Create, SnapshotOperation::Revert] {
let error = ensure_snapshot_tpm_compatible(&config, operation).unwrap_err();
assert!(
error
.to_string()
.contains("disk and TPM state can be paired")
);
}
}
#[test]
fn software_tpm_snapshot_create_rejects_before_host_probe_or_disk_change() {
let (_root, manager, _config, disk) = snapshot_fixture(true);
let error = manager
.snapshot_create("test", "before-upgrade")
.unwrap_err();
assert!(error.to_string().contains("software TPM 2"));
assert_eq!(fs::read(disk).unwrap(), b"snapshot fixture disk");
}
#[test]
fn software_tpm_snapshot_revert_rejects_before_rotating_generation_id() {
let (_root, manager, config, _disk) = snapshot_fixture(true);
let original_generation_id = config.generation_id;
let error = manager
.snapshot_revert("test", "before-upgrade")
.unwrap_err();
assert!(error.to_string().contains("software TPM 2"));
assert_eq!(
manager.config("test").unwrap().generation_id,
original_generation_id
);
}
#[test]
fn snapshot_revert_rejects_running_vm_before_host_probe_or_mutation() {
let (_root, manager, config, disk) = snapshot_fixture(false);
let status_probe_called = std::cell::Cell::new(false);
let probe_called = std::cell::Cell::new(false);
let error = manager
.snapshot_revert_with_probes(
"test",
"target",
|| {
status_probe_called.set(true);
Ok(VmStatus::Running {
pid: 1234,
qemu_status: "running".to_owned(),
})
},
|| {
probe_called.set(true);
panic!("host capability probe must not run for a running VM")
},
)
.unwrap_err();
assert!(error.to_string().contains("must be stopped"));
assert!(status_probe_called.get());
assert!(!probe_called.get());
assert_eq!(
manager.config("test").unwrap().generation_id,
config.generation_id
);
assert_eq!(fs::read(disk).unwrap(), b"snapshot fixture disk");
assert!(
!manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.exists()
);
}
#[test]
fn snapshot_revert_missing_snapshot_restores_disk_without_publishing_generation_id() {
let (root, manager, config, disk) = snapshot_fixture(false);
let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
let original_disk = fs::read(&disk).unwrap();
let (host, log, observed_config) =
snapshot_qemu_fixture(root.path(), &manager, &disk, "missing-target");
let error = manager
.snapshot_revert_with_probe("test", "target", || Ok(host))
.unwrap_err();
assert!(format!("{error:#}").contains("does not exist"));
assert_eq!(
manager.config("test").unwrap().generation_id,
config.generation_id
);
assert_eq!(
fs::read(manager.paths().config("test").unwrap()).unwrap(),
original_config
);
assert_eq!(fs::read(observed_config).unwrap(), original_config);
assert_eq!(fs::read(disk).unwrap(), original_disk);
assert_eq!(
fs::read_to_string(log).unwrap(),
"create\ntarget-attempt\nrestore\ndelete-attempt\ndelete\n"
);
assert!(
!manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.exists()
);
}
#[test]
fn successful_snapshot_revert_publishes_generation_id_after_disk_revert() {
let (root, manager, config, disk) = snapshot_fixture(false);
let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
let (host, log, observed_config) =
snapshot_qemu_fixture(root.path(), &manager, &disk, "success");
manager
.snapshot_revert_with_probe("test", "target", || Ok(host))
.unwrap();
assert_eq!(fs::read(observed_config).unwrap(), original_config);
assert_ne!(
manager.config("test").unwrap().generation_id,
config.generation_id
);
assert_eq!(fs::read(disk).unwrap(), b"target snapshot\n");
assert_eq!(
fs::read_to_string(log).unwrap(),
"create\ntarget-attempt\ndelete-attempt\ndelete\n"
);
assert!(
!manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.exists()
);
}
#[test]
fn snapshot_revert_checkpoint_cleanup_failure_leaves_marker_and_blocks_vm_use() {
let (root, manager, config, disk) = snapshot_fixture(false);
let (host, log, _observed_config) =
snapshot_qemu_fixture(root.path(), &manager, &disk, "checkpoint-delete-fails");
let error = manager
.snapshot_revert_with_probe("test", "target", || Ok(host))
.unwrap_err();
assert!(format!("{error:#}").contains("safety checkpoint knottvm-revert-"));
assert!(format!("{error:#}").contains("VM use is blocked"));
assert_ne!(
manager.config("test").unwrap().generation_id,
config.generation_id
);
assert_eq!(fs::read(disk).unwrap(), b"target snapshot\n");
assert_eq!(
fs::read_to_string(log).unwrap(),
"create\ntarget-attempt\ndelete-attempt\n"
);
assert!(
manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.is_file()
);
assert!(
manager
.status("test")
.unwrap_err()
.to_string()
.contains("unresolved snapshot revert")
);
}
#[test]
fn snapshot_revert_vmgenid_publication_failure_restores_disk_and_definition() {
let (root, manager, config, disk) = snapshot_fixture(false);
let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
let original_disk = fs::read(&disk).unwrap();
let (host, log, _observed_config) =
snapshot_qemu_fixture(root.path(), &manager, &disk, "config-publish-fails");
let config_root = manager.paths().config_root.clone();
let result = manager.snapshot_revert_with_probe("test", "target", || Ok(host));
fs::set_permissions(&config_root, fs::Permissions::from_mode(0o700)).unwrap();
let error = result.unwrap_err();
assert!(format!("{error:#}").contains("VMGenID publication failed"));
assert_eq!(
manager.config("test").unwrap().generation_id,
config.generation_id
);
assert_eq!(
fs::read(manager.paths().config("test").unwrap()).unwrap(),
original_config
);
assert_eq!(fs::read(disk).unwrap(), original_disk);
assert_eq!(
fs::read_to_string(log).unwrap(),
"create\ntarget-attempt\nrestore\ndelete-attempt\ndelete\n"
);
assert!(
!manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.exists()
);
}
#[test]
fn snapshot_revert_rollback_failure_leaves_marker_and_blocks_vm_use() {
let (root, manager, config, disk) = snapshot_fixture(false);
let original_generation_id = config.generation_id;
let (host, _log, _observed_config) =
snapshot_qemu_fixture(root.path(), &manager, &disk, "rollback-fails");
let error = manager
.snapshot_revert_with_probe("test", "target", || Ok(host))
.unwrap_err();
assert!(format!("{error:#}").contains("VM use is blocked"));
assert_eq!(
manager.config("test").unwrap().generation_id,
original_generation_id
);
assert_eq!(fs::read(disk).unwrap(), b"partial target\n");
assert!(
manager
.paths()
.data("test")
.unwrap()
.join(SNAPSHOT_REVERT_MARKER)
.is_file()
);
assert!(
manager
.status("test")
.unwrap_err()
.to_string()
.contains("unresolved snapshot revert")
);
}
#[test]
fn no_replace_disk_publication_preserves_a_destination_created_after_preflight() {
let root = tempdir().unwrap();
let staged = root.path().join("system.qcow2.staged");
let destination = root.path().join("system.qcow2");
fs::write(&staged, b"new disk").unwrap();
// Simulate another creator winning after our earlier absent-path check.
fs::write(&destination, b"another creator's disk").unwrap();
let result = publish_file_noreplace(&staged, &destination);
assert!(result.is_err());
assert_eq!(fs::read(&destination).unwrap(), b"another creator's disk");
assert_eq!(fs::read(&staged).unwrap(), b"new disk");
}
#[test]
fn refuses_to_replace_an_orphaned_system_disk() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let data = manager.paths().data("test").unwrap();
fs::create_dir(&data).unwrap();
let disk = data.join("system.qcow2");
fs::write(&disk, b"keep me").unwrap();
let result = manager.create(&CreateOptions {
name: "test".to_owned(),
disk_size: "64M".to_owned(),
install_media: None,
memory_mib: 512,
vcpus: 1,
firmware: Firmware::Uefi,
software_tpm2: false,
});
assert!(result.is_err());
assert_eq!(fs::read(&disk).unwrap(), b"keep me");
}
#[test]
fn recovers_missing_state_from_pid_and_qmp_identity() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir(&runtime).unwrap();
fs::write(runtime.join("qemu.pid"), std::process::id().to_string()).unwrap();
let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
let server = thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
stream
.write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
.unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
for response in [json!({}), json!({"name": "test"})] {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
let request: Value = serde_json::from_str(&line).unwrap();
serde_json::to_writer(
&mut stream,
&json!({"return": response, "id": request["id"]}),
)
.unwrap();
stream.write_all(b"\r\n").unwrap();
}
});
let state = manager.load_state("test").unwrap().unwrap();
assert_eq!(state.pid, std::process::id());
assert!(runtime.join("state.json").is_file());
server.join().unwrap();
}
#[test]
fn rejects_definition_name_mismatches() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let config = VmConfig::new("other".to_owned(), root.path().join("disk.qcow2"), None);
fs::write(
manager.paths().config("expected").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
assert!(manager.config("expected").is_err());
}
#[test]
fn clone_rejects_identical_names_before_disk_work() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
assert!(manager.clone_vm("same", "same").is_err());
}
#[test]
fn persists_unique_offline_usb_assignments() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
fs::write(
manager.paths().config("test").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let device = UsbHostDevice { bus: 1, address: 4 };
manager.usb_add("test", device).unwrap();
assert_eq!(manager.config("test").unwrap().usb_devices, [device]);
assert!(manager.usb_add("test", device).is_err());
assert_eq!(manager.config("test").unwrap().usb_devices, [device]);
assert_eq!(manager.usb_remove("test", device).unwrap(), device);
assert!(manager.config("test").unwrap().usb_devices.is_empty());
}
#[test]
fn configures_guest_pointer_device_while_stopped() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
fs::write(
manager.paths().config("test").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let configured = manager
.configure(
"test",
&super::ConfigureOptions {
pointer_device: Some(PointerDevice::Mouse),
..super::ConfigureOptions::default()
},
)
.unwrap();
assert_eq!(configured.pointer_device, PointerDevice::Mouse);
assert_eq!(
manager.config("test").unwrap().pointer_device,
PointerDevice::Mouse
);
assert!(
manager
.configure("test", &super::ConfigureOptions::default())
.is_err()
);
}
#[test]
fn persists_canonical_offline_directory_shares() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
fs::write(
manager.paths().config("test").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let shared = root.path().join("shared");
fs::create_dir(&shared).unwrap();
let share = manager
.share_add("test", "host-data".to_owned(), &shared, true)
.unwrap();
assert_eq!(share.path, fs::canonicalize(&shared).unwrap());
assert!(share.read_only);
let configured = manager.config("test").unwrap();
assert_eq!(configured.shares.as_slice(), std::slice::from_ref(&share));
assert!(
manager
.share_add("test", "host-data".to_owned(), &shared, false)
.is_err()
);
assert_eq!(manager.share_remove("test", "host-data").unwrap(), share);
assert!(manager.config("test").unwrap().shares.is_empty());
}
#[test]
fn publishes_only_new_binary_ppm_screenshots() {
let root = tempdir().unwrap();
let staging = root.path().join("staging.ppm");
let destination = root.path().join("screen.ppm");
fs::write(&staging, b"P6\n1 1\n255\n\0\0\0").unwrap();
assert_eq!(publish_screenshot(&staging, &destination).unwrap(), 14);
assert_eq!(fs::read(&destination).unwrap(), b"P6\n1 1\n255\n\0\0\0");
assert!(publish_screenshot(&staging, &destination).is_err());
assert_eq!(fs::read(&destination).unwrap(), b"P6\n1 1\n255\n\0\0\0");
fs::write(&staging, b"not a screenshot").unwrap();
assert!(publish_screenshot(&staging, &root.path().join("invalid.ppm")).is_err());
}
#[test]
fn validates_ppm_dimensions_raster_length_and_samples_before_publication() {
let root = tempdir().unwrap();
let staging = root.path().join("staging.ppm");
let cases: &[(&str, &[u8])] = &[
("zero-width", b"P6\n0 1\n255\n\0\0\0"),
("truncated", b"P6\n2 1\n255\n\0\0\0"),
("trailing", b"P6\n1 1\n255\n\0\0\0x"),
("invalid-maxval", b"P6\n1 1\n65536\n\0\0\0"),
("sample-out-of-range", b"P6\n1 1\n15\n\x10\0\0"),
("raster-overflow", b"P6\n18446744073709551615 2\n255\n"),
];
for (name, bytes) in cases {
fs::write(&staging, bytes).unwrap();
let destination = root.path().join(format!("{name}.ppm"));
assert!(
publish_screenshot(&staging, &destination).is_err(),
"{name}"
);
assert!(!destination.exists(), "{name} left a partial screenshot");
}
}
#[test]
fn publishes_valid_commented_crlf_sixteen_bit_ppm() {
let root = tempdir().unwrap();
let staging = root.path().join("staging.ppm");
let destination = root.path().join("screen.ppm");
let ppm = b"P6\r\n# valid comment\n1 1\n1023\r\n\0\0\x01\xff\x03\xff";
fs::write(&staging, ppm).unwrap();
assert_eq!(
publish_screenshot(&staging, &destination).unwrap(),
ppm.len() as u64
);
assert_eq!(fs::read(destination).unwrap(), ppm);
}
#[test]
fn validates_positive_disk_growth() {
assert_eq!(validate_growth_amount("20g").unwrap(), "20G");
assert!(validate_growth_amount("0G").is_err());
assert!(validate_growth_amount("-1G").is_err());
assert!(validate_growth_amount("20").is_err());
}
#[test]
fn retries_only_kvm_initialization_failures() {
assert!(is_kvm_initialization_failure(
b"qemu-system-x86_64: failed to initialize kvm: Device or resource busy"
));
assert!(is_kvm_initialization_failure(
b"Could not access KVM kernel module: Permission denied"
));
assert!(!is_kvm_initialization_failure(
b"usb-host: failed to open host usb device 1:4"
));
}
#[test]
fn kvm_failure_with_a_live_pid_does_not_start_a_second_qemu() {
let (root, manager, mut config, _) = snapshot_fixture(false);
config.firmware = Firmware::Bios;
fs::write(
manager.paths().config("test").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let runtime = manager.paths().runtime("test").unwrap();
let pid_file = runtime.join("qemu.pid");
let attempts = root.path().join("qemu-attempts");
let program = root.path().join("qemu-fixture");
let script = format!(
"#!/bin/sh\nprintf 'launch\\n' >> {}\nprintf '%s\\n' '{}' > {}\n\
printf 'failed to initialize kvm: Device or resource busy\\n' >&2\nexit 1\n",
shell_quote(&attempts),
std::process::id(),
shell_quote(&pid_file),
);
fs::write(&program, script).unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o700)).unwrap();
let host = HostCapabilities {
qemu: program,
qemu_img: PathBuf::from("/bin/false"),
swtpm: None,
swtpm_ioctl: None,
kvm_available: true,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
let error = manager.start_with_host("test", &host).unwrap_err();
assert!(error.to_string().contains("runtime files were preserved"));
assert_eq!(fs::read_to_string(attempts).unwrap(), "launch\n");
assert!(pid_file.is_file());
}
#[test]
fn bounds_balloon_targets_to_configured_memory() {
assert_eq!(validate_balloon_target(256, 512).unwrap(), 268_435_456);
assert_eq!(validate_balloon_target(512, 512).unwrap(), 536_870_912);
assert!(validate_balloon_target(255, 512).is_err());
assert!(validate_balloon_target(513, 512).is_err());
}
#[test]
fn deletion_rejects_a_symlinked_vm_data_directory() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let outside = root.path().join("outside");
fs::create_dir(&outside).unwrap();
fs::write(outside.join("system.qcow2"), b"must survive").unwrap();
let data = manager.paths().data("test").unwrap();
symlink(&outside, &data).unwrap();
let config = VmConfig::new("test".to_owned(), data.join("system.qcow2"), None);
let definition = manager.paths().config("test").unwrap();
fs::write(&definition, config.to_toml().unwrap()).unwrap();
assert!(manager.delete_vm("test").is_err());
assert!(definition.is_file());
assert_eq!(
fs::read(outside.join("system.qcow2")).unwrap(),
b"must survive"
);
}
#[test]
fn deletion_resumes_from_a_durable_tombstone() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let data = manager.paths().data("test").unwrap();
fs::create_dir(&data).unwrap();
let disk = data.join("system.qcow2");
fs::write(&disk, b"disk").unwrap();
fs::write(data.join("uefi-vars.fd"), b"vars").unwrap();
let tpm_state = data.join("tpm-state");
fs::create_dir(&tpm_state).unwrap();
fs::write(tpm_state.join("tpm2-00.permall"), b"TPM identity").unwrap();
let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
config.software_tpm2 = true;
let definition = manager.paths().config("test").unwrap();
fs::write(&definition, config.to_toml().unwrap()).unwrap();
let tombstone = definition.with_extension("toml.deleting");
fs::rename(&definition, &tombstone).unwrap();
let report = manager.delete_vm("test").unwrap();
assert!(report.removed_managed_disk);
assert!(!disk.exists());
assert!(!tpm_state.exists());
assert!(!tombstone.exists());
assert!(
manager
.paths()
.runtime("test")
.unwrap()
.join("operation.lock")
.is_file()
);
}
#[test]
fn pending_deletion_tombstone_remains_in_disk_owner_checks() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let target_data = manager.paths().data("target").unwrap();
fs::create_dir_all(&target_data).unwrap();
let shared_disk = target_data.join("system.qcow2");
fs::write(&shared_disk, b"guest data owned by pending deletion").unwrap();
let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
let tombstone = manager
.paths()
.config("target")
.unwrap()
.with_extension("toml.deleting");
fs::write(&tombstone, target.to_toml().unwrap()).unwrap();
let other = VmConfig::new("other".to_owned(), shared_disk.clone(), None);
fs::write(
manager.paths().config("other").unwrap(),
other.to_toml().unwrap(),
)
.unwrap();
let error = manager
.ensure_unique_disk_owner("other", &manager.config("other").unwrap())
.unwrap_err();
assert!(error.to_string().contains("same system disk"));
assert_eq!(
fs::read(&shared_disk).unwrap(),
b"guest data owned by pending deletion"
);
}
#[test]
fn resumed_deletion_preserves_disk_referenced_by_another_vm() {
let root = tempdir().unwrap();
let manager = VmManager::new(AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
))
.unwrap();
let target_data = manager.paths().data("target").unwrap();
fs::create_dir_all(&target_data).unwrap();
let shared_disk = target_data.join("system.qcow2");
fs::write(&shared_disk, b"guest data owned by other").unwrap();
let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
let target_tombstone = manager
.paths()
.config("target")
.unwrap()
.with_extension("toml.deleting");
fs::write(&target_tombstone, target.to_toml().unwrap()).unwrap();
let other = VmConfig::new("other".to_owned(), shared_disk.clone(), None);
let other_definition = manager.paths().config("other").unwrap();
fs::write(&other_definition, other.to_toml().unwrap()).unwrap();
let error = manager.delete_vm("target").unwrap_err();
assert!(error.to_string().contains("same system disk"));
assert_eq!(
fs::read(&shared_disk).unwrap(),
b"guest data owned by other"
);
assert!(target_tombstone.is_file());
assert!(other_definition.is_file());
}
#[test]
fn interrupted_restore_preserves_all_destination_artifacts() {
let root = tempdir().unwrap();
let data = root.path().join("vm-data");
fs::create_dir(&data).unwrap();
fs::write(data.join(".restore-in-progress"), b"source-vm").unwrap();
fs::write(data.join("system.qcow2"), b"existing disk").unwrap();
fs::write(data.join("uefi-vars.fd"), b"existing vars").unwrap();
fs::write(data.join(".restore-disk.tmp"), b"staged disk").unwrap();
let staging = data.join(".restore-stage");
fs::create_dir(&staging).unwrap();
fs::write(staging.join("sentinel"), b"staged backup").unwrap();
let directory = super::PinnedDir::open(&data).unwrap();
let error = require_restore_marker_clear(&directory, &data.join(".restore-in-progress"))
.unwrap_err();
assert!(
error
.to_string()
.contains("preserved for manual inspection")
);
assert_eq!(
fs::read(data.join("system.qcow2")).unwrap(),
b"existing disk"
);
assert_eq!(
fs::read(data.join("uefi-vars.fd")).unwrap(),
b"existing vars"
);
assert_eq!(
fs::read(data.join(".restore-disk.tmp")).unwrap(),
b"staged disk"
);
assert_eq!(
fs::read(staging.join("sentinel")).unwrap(),
b"staged backup"
);
assert!(data.join(".restore-in-progress").is_file());
}
#[test]
fn restore_failure_after_publication_preserves_every_artifact() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let backup = root.path().join("backup");
fs::create_dir(&backup).unwrap();
let config = VmConfig::new("source".to_owned(), PathBuf::from(BACKUP_DISK_FILE), None);
fs::write(backup.join(BACKUP_CONFIG_FILE), config.to_toml().unwrap()).unwrap();
fs::write(backup.join(BACKUP_DISK_FILE), b"source qcow2 bytes").unwrap();
fs::write(backup.join(BACKUP_UEFI_VARS_FILE), b"source vars").unwrap();
BackupManifest::build(&backup, "source".to_owned())
.unwrap()
.save(&backup)
.unwrap();
let definition = manager.paths().config("destination").unwrap();
let qemu_img = root.path().join("qemu-img");
let script = format!(
"#!/bin/sh\ncase \"$1\" in\n info) printf '%s\\n' '{{\"format\":\"qcow2\"}}'; exit 0 ;;\n check) exit 0 ;;\n convert) output=; for arg do output=\"$arg\"; done; printf 'restored disk' > \"$output\"; printf 'concurrent definition' > {}; exit 0 ;;\nesac\nexit 1\n",
shell_quote(&definition)
);
fs::write(&qemu_img, script).unwrap();
fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
let host = HostCapabilities {
qemu: PathBuf::from("/bin/false"),
qemu_img,
swtpm: None,
swtpm_ioctl: None,
kvm_available: false,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
let error = manager
.backup_restore_with_host(&backup, "destination", &host)
.unwrap_err();
assert!(error.to_string().contains("failed to create"));
let data = manager.paths().data("destination").unwrap();
assert!(data.join(".restore-in-progress").is_file());
assert!(data.join(".restore-stage/manifest.json").is_file());
assert_eq!(
fs::read(data.join("system.qcow2")).unwrap(),
b"restored disk"
);
assert_eq!(fs::read(data.join("uefi-vars.fd")).unwrap(), b"source vars");
assert_eq!(fs::read(&definition).unwrap(), b"concurrent definition");
}
fn shell_quote(path: &Path) -> String {
format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
}
#[test]
fn backup_cleanup_never_follows_a_directory_symlink() {
let root = tempdir().unwrap();
let outside = root.path().join("outside");
fs::create_dir(&outside).unwrap();
for name in ["manifest.json", "vm.toml", "disk.qcow2", "uefi-vars.fd"] {
fs::write(outside.join(name), b"must survive").unwrap();
}
let staging_link = root.path().join(".restore-stage");
symlink(&outside, &staging_link).unwrap();
cleanup_backup_directory(&staging_link);
for name in ["manifest.json", "vm.toml", "disk.qcow2", "uefi-vars.fd"] {
assert_eq!(fs::read(outside.join(name)).unwrap(), b"must survive");
}
}
#[test]
fn swtpm_cleanup_preserves_live_helper_when_control_socket_is_missing() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let data = manager.paths().data("test").unwrap();
let runtime = manager.paths().runtime("test").unwrap();
fs::create_dir(&data).unwrap();
fs::create_dir(&runtime).unwrap();
let tpm_state = data.join("tpm-state");
fs::create_dir(&tpm_state).unwrap();
fs::write(tpm_state.join("tpm2-00.permall"), b"persistent identity").unwrap();
validate_tpm_state_directory(&tpm_state).unwrap();
assert_eq!(
fs::metadata(tpm_state.join("tpm2-00.permall"))
.unwrap()
.permissions()
.mode()
& 0o777,
0o600
);
let files = manager.runtime_files("test", &data).unwrap();
fs::write(&files.tpm_control_socket, b"not a socket").unwrap();
let fake_swtpm = format!(
"/bin/sleep 60 &\nprintf '%s\\n' \"$!\" > {}\nexit 0\n",
shell_quote(&files.swtpm_pid_file)
);
launch_swtpm(&CommandSpec {
program: PathBuf::from("/bin/sh"),
args: vec!["-c".into(), fake_swtpm.into()],
})
.unwrap();
let pid = read_process_pid(&files.swtpm_pid_file, "swtpm").unwrap();
assert!(crate::state::process_exists(pid));
assert!(wait_for_swtpm(&files, Duration::ZERO).is_err());
assert!(stop_swtpm_files(&files, None).is_err());
assert!(crate::state::process_exists(pid));
assert!(files.swtpm_pid_file.exists());
assert!(files.tpm_control_socket.exists());
assert_eq!(
fs::read(tpm_state.join("tpm2-00.permall")).unwrap(),
b"persistent identity"
);
let pid_i32 = i32::try_from(pid).unwrap();
assert_eq!(unsafe { libc::kill(pid_i32, libc::SIGTERM) }, 0);
wait_for_process_exit(pid, Duration::from_secs(2), "fake swtpm").unwrap();
}
#[test]
fn swtpm_ioctl_stop_invokes_bounded_control_command() {
let root = tempdir().unwrap();
let log = root.path().join("args");
let fake_ioctl = root.path().join("swtpm_ioctl");
let control = root.path().join("control.sock");
fs::write(
&fake_ioctl,
format!("#!/bin/sh\nprintf '%s\\n' \"$*\" > {}\n", shell_quote(&log)),
)
.unwrap();
fs::set_permissions(&fake_ioctl, fs::Permissions::from_mode(0o700)).unwrap();
run_swtpm_ioctl_stop(&fake_ioctl, &control).unwrap();
let args = fs::read_to_string(log).unwrap();
assert!(args.contains("--unix"));
assert!(args.contains("--stop"));
assert!(args.contains(&control.display().to_string()));
}
#[test]
fn tpm_state_copy_is_private_and_does_not_copy_unsafe_entries() {
let root = tempdir().unwrap();
let source = root.path().join("source");
let destination = root.path().join("destination");
fs::create_dir(&source).unwrap();
fs::set_permissions(&source, fs::Permissions::from_mode(0o700)).unwrap();
fs::write(source.join("tpm2-00.permall"), b"state").unwrap();
fs::write(source.join(".lock"), []).unwrap();
copy_tpm_state_directory(&source, &destination, false).unwrap();
assert_eq!(
fs::read(destination.join("tpm2-00.permall")).unwrap(),
b"state"
);
assert!(destination.join(".lock").is_file());
assert_eq!(
fs::metadata(&destination).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(
fs::metadata(destination.join("tpm2-00.permall"))
.unwrap()
.permissions()
.mode()
& 0o777,
0o600
);
let unsafe_source = root.path().join("unsafe");
fs::create_dir(&unsafe_source).unwrap();
fs::write(unsafe_source.join("unexpected"), b"must not copy").unwrap();
let unsafe_destination = root.path().join("unsafe-copy");
assert!(copy_tpm_state_directory(&unsafe_source, &unsafe_destination, false).is_err());
assert!(!unsafe_destination.join("unexpected").exists());
}
#[test]
fn cloning_an_enabled_tpm_vm_does_not_copy_source_tpm_identity() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let source_data = manager.paths().data("source").unwrap();
fs::create_dir(&source_data).unwrap();
let disk = source_data.join("system.qcow2");
fs::write(&disk, b"qcow2 source").unwrap();
let tpm_state = source_data.join("tpm-state");
fs::create_dir(&tpm_state).unwrap();
fs::write(tpm_state.join("tpm2-00.permall"), b"source TPM identity").unwrap();
let mut config = VmConfig::new("source".to_owned(), disk, None);
config.firmware = Firmware::Bios;
config.software_tpm2 = true;
fs::write(
manager.paths().config("source").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let qemu_img = root.path().join("qemu-img");
fs::write(
&qemu_img,
"#!/bin/sh\noutput=\nfor arg do output=\"$arg\"; done\nprintf 'independent disk' > \"$output\"\n",
)
.unwrap();
fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
let host = HostCapabilities {
qemu: PathBuf::from("/bin/false"),
qemu_img,
swtpm: None,
swtpm_ioctl: None,
kvm_available: false,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
manager
.clone_vm_with_host("source", "clone", &host)
.unwrap();
let clone = manager.config("clone").unwrap();
assert!(clone.software_tpm2);
assert!(
!manager
.paths()
.data("clone")
.unwrap()
.join("tpm-state")
.exists()
);
assert_eq!(
fs::read(tpm_state.join("tpm2-00.permall")).unwrap(),
b"source TPM identity"
);
}
#[test]
fn tpm_backup_restore_preserves_guest_identity_and_secure_modes() {
let root = tempdir().unwrap();
let paths = AppPaths::new(
root.path().join("config"),
root.path().join("data"),
root.path().join("runtime"),
);
let manager = VmManager::new(paths).unwrap();
let source_data = manager.paths().data("source").unwrap();
fs::create_dir(&source_data).unwrap();
let disk = source_data.join("system.qcow2");
fs::write(&disk, b"qcow2 source bytes").unwrap();
let state_dir = source_data.join("tpm-state");
fs::create_dir(&state_dir).unwrap();
fs::write(state_dir.join("tpm2-00.permall"), b"guest TPM identity").unwrap();
fs::write(state_dir.join(".lock"), []).unwrap();
let mut config = VmConfig::new("source".to_owned(), disk, None);
config.software_tpm2 = true;
fs::write(
manager.paths().config("source").unwrap(),
config.to_toml().unwrap(),
)
.unwrap();
let qemu_img = root.path().join("qemu-img");
fs::write(
&qemu_img,
"#!/bin/sh\ncase \"$1\" in\n info) printf '%s\\n' '{\"format\":\"qcow2\"}'; exit 0;;\n check) exit 0;;\n convert) source=; output=; for arg do source=\"$output\"; output=\"$arg\"; done; cp \"$source\" \"$output\"; exit 0;;\nesac\nexit 1\n",
)
.unwrap();
fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
let host = HostCapabilities {
qemu: PathBuf::from("/bin/false"),
qemu_img,
swtpm: None,
swtpm_ioctl: None,
kvm_available: false,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
let backup = root.path().join("backup");
let manifest = manager
.backup_create_with_host("source", &backup, &host)
.unwrap();
assert!(manifest.tpm_state.is_some());
assert_eq!(
fs::read(backup.join("tpm-state/tpm2-00.permall")).unwrap(),
b"guest TPM identity"
);
assert!(backup.join("tpm-state/.lock").is_file());
assert_eq!(
fs::metadata(backup.join("tpm-state"))
.unwrap()
.permissions()
.mode()
& 0o777,
0o700
);
assert_eq!(
fs::metadata(backup.join("tpm-state/tpm2-00.permall"))
.unwrap()
.permissions()
.mode()
& 0o777,
0o600
);
assert_eq!(
VmManager::backup_verify_with_host(&backup, &host)
.unwrap()
.tpm_state,
manifest.tpm_state
);
manager
.backup_restore_with_host(&backup, "restored", &host)
.unwrap();
assert!(manager.config("restored").unwrap().software_tpm2);
assert_eq!(
fs::read(
manager
.paths()
.data("restored")
.unwrap()
.join("tpm-state/tpm2-00.permall")
)
.unwrap(),
b"guest TPM identity"
);
assert!(
manager
.paths()
.data("restored")
.unwrap()
.join("tpm-state/.lock")
.is_file()
);
}
}