Skip to main content

aev_vm/
manager.rs

1//! High-level VM creation and lifecycle management.
2
3use std::collections::BTreeSet;
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, BufRead, BufReader, Read, Write};
6use std::os::fd::{AsRawFd, OwnedFd};
7use std::os::unix::ffi::OsStrExt;
8use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt};
9use std::os::unix::net::UnixStream;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Output, Stdio};
12use std::thread;
13use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
14
15use anyhow::{Context, Result, bail};
16use fs2::FileExt;
17use rustix::fs::{AtFlags, FileType, Mode, OFlags, RenameFlags};
18use uuid::Uuid;
19
20use crate::backup::{
21    BackupManifest, CONFIG_FILE as BACKUP_CONFIG_FILE, DISK_FILE as BACKUP_DISK_FILE,
22    TPM_STATE_DIR as BACKUP_TPM_STATE_DIR, UEFI_VARS_FILE as BACKUP_UEFI_VARS_FILE,
23    validate_tpm_state_name,
24};
25use crate::config::{
26    Acceleration, AudioMode, DirectoryShare, DiskFormat, Firmware, NetworkMode, NetworkProtocol,
27    PointerDevice, PortForward, UsbHostDevice, VmConfig,
28};
29use crate::paths::{AppPaths, ensure_private_dir};
30use crate::qemu::{
31    CommandSpec, HostCapabilities, RuntimeFiles, build_command, build_swtpm_command,
32    prepare_uefi_vars,
33};
34use crate::qga::{GuestAgentClient, ShutdownMode};
35use crate::qmp::QmpClient;
36use crate::state::{VmState, process_exists};
37
38const MAX_SCREENSHOT_BYTES: u64 = 256 * 1024 * 1024;
39const MAX_PPM_HEADER_BYTES: usize = 4096;
40const MAX_PPM_TOKEN_BYTES: usize = 32;
41const SNAPSHOT_REVERT_MARKER: &str = ".snapshot-revert-in-progress";
42
43/// Input for creating a new VM definition and system disk.
44#[derive(Debug, Clone)]
45pub struct CreateOptions {
46    /// VM name.
47    pub name: String,
48    /// QEMU image size such as `64G`.
49    pub disk_size: String,
50    /// Optional installation ISO.
51    pub install_media: Option<PathBuf>,
52    /// Guest memory in MiB.
53    pub memory_mib: u64,
54    /// Virtual CPU count.
55    pub vcpus: u16,
56    /// Guest boot firmware.
57    pub firmware: Firmware,
58    /// Attach a per-VM software TPM 2.0 device.
59    pub software_tpm2: bool,
60}
61
62/// Files removed or intentionally preserved by a VM deletion.
63#[derive(Debug, Clone)]
64pub struct DeleteReport {
65    /// Removed TOML definition.
66    pub definition: PathBuf,
67    /// Whether the managed system disk was removed.
68    pub removed_managed_disk: bool,
69    /// A disk path preserved because it was outside `KnottVM`'s managed location.
70    pub preserved_disk: Option<PathBuf>,
71}
72
73/// Optional offline changes to a VM's compute and host integration settings.
74#[derive(Debug, Clone, Default)]
75pub struct ConfigureOptions {
76    /// Replacement memory size in MiB.
77    pub memory_mib: Option<u64>,
78    /// Replacement virtual CPU count.
79    pub vcpus: Option<u16>,
80    /// Replacement accelerator preference.
81    pub acceleration: Option<Acceleration>,
82    /// Replacement network attachment mode.
83    pub network_mode: Option<NetworkMode>,
84    /// Replacement host audio backend.
85    pub audio: Option<AudioMode>,
86    /// Replacement guest pointer device.
87    pub pointer_device: Option<PointerDevice>,
88    /// Replacement guest boot firmware.
89    pub firmware: Option<Firmware>,
90}
91
92/// Current runtime memory reported by QEMU and its configured ceiling.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct BalloonStatus {
95    /// Guest-reported current memory in bytes.
96    pub actual_bytes: u64,
97    /// Boot-time configured memory in MiB.
98    pub configured_mib: u64,
99}
100
101/// Observable VM state.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum VmStatus {
104    /// No process is associated with the definition.
105    Stopped,
106    /// QEMU answered a QMP status query.
107    Running { pid: u32, qemu_status: String },
108    /// State exists but QEMU cannot be reached.
109    Stale { pid: u32 },
110}
111
112/// Coordinates definitions, runtime state, QEMU, and QMP.
113pub struct VmManager {
114    paths: AppPaths,
115}
116
117#[derive(Clone, Copy, Debug, Eq, PartialEq)]
118enum SnapshotOperation {
119    List,
120    Create,
121    Revert,
122    Delete,
123}
124
125fn ensure_snapshot_tpm_compatible(config: &VmConfig, operation: SnapshotOperation) -> Result<()> {
126    if config.software_tpm2
127        && matches!(
128            operation,
129            SnapshotOperation::Create | SnapshotOperation::Revert
130        )
131    {
132        bail!(
133            "internal snapshot creation and reversion are unavailable for software TPM 2 VMs until disk and TPM state can be paired"
134        );
135    }
136    Ok(())
137}
138
139fn require_stopped_status(name: &str, status: &VmStatus) -> Result<()> {
140    match status {
141        VmStatus::Stopped => Ok(()),
142        VmStatus::Running { .. } => bail!("VM {name} must be stopped for this operation"),
143        VmStatus::Stale { pid } => {
144            bail!("VM {name} has stale runtime state for PID {pid}; resolve it first")
145        }
146    }
147}
148
149#[derive(Clone, Copy)]
150struct SnapshotRevertRecovery<'a> {
151    host: &'a HostCapabilities,
152    disk: &'a Path,
153    rollback_snapshot: &'a str,
154    marker: &'a Path,
155    data: &'a Path,
156}
157
158impl VmManager {
159    /// Construct a manager and secure all root directories.
160    pub fn new(paths: AppPaths) -> Result<Self> {
161        paths.ensure()?;
162        Ok(Self { paths })
163    }
164
165    /// Discover roots from the XDG environment.
166    pub fn discover() -> Result<Self> {
167        Self::new(AppPaths::discover()?)
168    }
169
170    /// Access resolved application roots.
171    #[must_use]
172    pub const fn paths(&self) -> &AppPaths {
173        &self.paths
174    }
175
176    /// Create a VM definition and an empty qcow2 system disk.
177    pub fn create(&self, options: &CreateOptions) -> Result<PathBuf> {
178        let _lock = self.lock(&options.name)?;
179        let disk_ownership = self.lock_disk_ownership()?;
180        let config_path = self.paths.config(&options.name)?;
181        match fs::symlink_metadata(&config_path) {
182            Ok(_) => bail!("VM {} already exists", options.name),
183            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
184            Err(error) => return Err(error.into()),
185        }
186        if options.disk_size.is_empty()
187            || !options
188                .disk_size
189                .chars()
190                .all(|character| character.is_ascii_digit() || "KMGTPE".contains(character))
191        {
192            bail!("disk size must look like 64G, 1024M, or 1T");
193        }
194        let data = self.paths.data(&options.name)?;
195        ensure_private_dir(&data)?;
196        let disk = data.join("system.qcow2");
197        match fs::symlink_metadata(&disk) {
198            Ok(_) => bail!(
199                "refusing to replace existing VM disk {}; resolve the orphan manually",
200                disk.display()
201            ),
202            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
203            Err(error) => return Err(error.into()),
204        }
205        let install_media = options
206            .install_media
207            .as_ref()
208            .map(|media| {
209                fs::canonicalize(media).with_context(|| {
210                    format!("installation media {} does not exist", media.display())
211                })
212            })
213            .transpose()?;
214        let mut config = VmConfig::new(options.name.clone(), disk, install_media);
215        config.memory_mib = options.memory_mib;
216        config.vcpus = options.vcpus;
217        config.firmware = options.firmware;
218        config.software_tpm2 = options.software_tpm2;
219        self.ensure_unique_disk_owner(&options.name, &config)?;
220        drop(disk_ownership);
221        let source = config.to_toml()?;
222        let host = HostCapabilities::probe()?;
223        let nonce = SystemTime::now()
224            .duration_since(UNIX_EPOCH)
225            .unwrap_or_default()
226            .as_nanos();
227        let temporary_disk = data.join(format!("system.qcow2.tmp-{}-{nonce}", std::process::id()));
228        let temporary_config =
229            config_path.with_extension(format!("toml.tmp-{}-{nonce}", std::process::id()));
230        let output = Command::new(&host.qemu_img)
231            .args(["create", "-f", "qcow2"])
232            .arg(&temporary_disk)
233            .arg(&options.disk_size)
234            .output()
235            .context("failed to execute qemu-img")?;
236        if !output.status.success() {
237            let _ = fs::remove_file(&temporary_disk);
238            bail!(
239                "qemu-img failed: {}",
240                String::from_utf8_lossy(&output.stderr).trim()
241            );
242        }
243        let mut config_file = match OpenOptions::new()
244            .write(true)
245            .create_new(true)
246            .open(&temporary_config)
247        {
248            Ok(file) => file,
249            Err(error) => {
250                let _ = fs::remove_file(&temporary_disk);
251                return Err(error).with_context(|| {
252                    format!("failed to stage VM definition {}", config_path.display())
253                });
254            }
255        };
256        let staged_result = config_file
257            .write_all(source.as_bytes())
258            .and_then(|()| config_file.sync_all())
259            .and_then(|()| File::open(&temporary_disk)?.sync_all());
260        drop(config_file);
261        if let Err(error) = staged_result {
262            let _ = fs::remove_file(&temporary_disk);
263            let _ = fs::remove_file(&temporary_config);
264            return Err(error).with_context(|| {
265                format!(
266                    "failed to prepare VM disk and definition for {}",
267                    options.name
268                )
269            });
270        }
271        if let Err(error) = publish_file_noreplace(&temporary_disk, &config.disk.path) {
272            let _ = fs::remove_file(&temporary_disk);
273            let _ = fs::remove_file(&temporary_config);
274            return Err(error).with_context(|| {
275                format!(
276                    "failed to publish VM disk {} without replacing an existing path",
277                    config.disk.path.display()
278                )
279            });
280        }
281        if let Err(error) = publish_file_noreplace(&temporary_config, &config_path) {
282            let _ = fs::remove_file(&temporary_config);
283            return Err(error).with_context(|| {
284                format!(
285                    "VM definition {} could not be published; the disk is preserved as an orphan at {}",
286                    config_path.display(),
287                    config.disk.path.display()
288                )
289            });
290        }
291        sync_directory(&data).context("VM was created but syncing its disk directory failed")?;
292        sync_directory(&self.paths.config_root)
293            .context("VM was created but syncing its definition directory failed")?;
294        Ok(config_path)
295    }
296
297    /// Create an independent full-copy clone of a stopped VM.
298    pub fn clone_vm(&self, source_name: &str, destination_name: &str) -> Result<PathBuf> {
299        if source_name == destination_name {
300            bail!("source and destination VM names must differ");
301        }
302        let host = HostCapabilities::probe()?;
303        self.clone_vm_with_host(source_name, destination_name, &host)
304    }
305
306    fn clone_vm_with_host(
307        &self,
308        source_name: &str,
309        destination_name: &str,
310        host: &HostCapabilities,
311    ) -> Result<PathBuf> {
312        if source_name == destination_name {
313            bail!("source and destination VM names must differ");
314        }
315        let destination_config_path = self.paths.config(destination_name)?;
316        self.paths.config(source_name)?;
317        let (_first_lock, _second_lock) = if source_name < destination_name {
318            (self.lock(source_name)?, self.lock(destination_name)?)
319        } else {
320            (self.lock(destination_name)?, self.lock(source_name)?)
321        };
322        let disk_ownership = self.lock_disk_ownership()?;
323        match self.status_unlocked(source_name)? {
324            VmStatus::Stopped => {}
325            VmStatus::Running { .. } => {
326                bail!("source VM {source_name} must be stopped before cloning");
327            }
328            VmStatus::Stale { pid } => {
329                bail!("source VM {source_name} has stale runtime state for PID {pid}");
330            }
331        }
332        match self.status_unlocked(destination_name)? {
333            VmStatus::Stopped => {}
334            VmStatus::Running { pid, .. } => {
335                bail!("destination VM {destination_name} is already running as PID {pid}");
336            }
337            VmStatus::Stale { pid } => {
338                bail!("destination VM {destination_name} has stale runtime state for PID {pid}");
339            }
340        }
341        self.clean_runtime(source_name)?;
342        self.clean_runtime(destination_name)?;
343        ensure_path_absent(&destination_config_path, "destination VM definition")?;
344
345        let source = self.config(source_name)?;
346        self.ensure_unique_disk_owner(source_name, &source)?;
347        let source_data = self.paths.data(source_name)?;
348        let destination_data = self.paths.data(destination_name)?;
349        ensure_private_dir(&destination_data)?;
350        let destination_disk = destination_data.join("system.qcow2");
351        let destination_vars = destination_data.join("uefi-vars.fd");
352        let destination_tpm_state = destination_data.join(BACKUP_TPM_STATE_DIR);
353        ensure_path_absent(&destination_disk, "destination VM disk")?;
354        ensure_path_absent(&destination_vars, "destination UEFI variables")?;
355        ensure_path_absent(&destination_tpm_state, "destination software TPM state")?;
356
357        let mut destination = source.clone();
358        destination_name.clone_into(&mut destination.name);
359        destination.disk.path.clone_from(&destination_disk);
360        destination.disk.format = DiskFormat::Qcow2;
361        destination.generation_id = Some(Uuid::new_v4());
362        destination.network.mac = None;
363        destination.network.forwards.clear();
364        destination.usb_devices.clear();
365        destination.shares.clear();
366        self.ensure_unique_disk_owner(destination_name, &destination)?;
367        drop(disk_ownership);
368        let definition = destination.to_toml()?;
369        let nonce = SystemTime::now()
370            .duration_since(UNIX_EPOCH)
371            .unwrap_or_default()
372            .as_nanos();
373        let temporary_disk =
374            destination_data.join(format!("system.qcow2.clone-{}-{nonce}", std::process::id()));
375
376        let mut disk_published = false;
377        let mut vars_published = false;
378        let mut definition_published = false;
379        let result = (|| -> Result<()> {
380            let output = Command::new(&host.qemu_img)
381                .arg("convert")
382                .args(["-f", source.disk.format.qemu_driver(), "-O", "qcow2"])
383                .arg(&source.disk.path)
384                .arg(&temporary_disk)
385                .output()
386                .context("failed to execute qemu-img convert")?;
387            if !output.status.success() {
388                bail!(
389                    "qemu-img convert failed: {}",
390                    String::from_utf8_lossy(&output.stderr).trim()
391                );
392            }
393            fs::hard_link(&temporary_disk, &destination_disk).with_context(|| {
394                format!(
395                    "failed to publish cloned disk {}",
396                    destination_disk.display()
397                )
398            })?;
399            disk_published = true;
400            fs::remove_file(&temporary_disk)?;
401
402            let source_vars = source_data.join("uefi-vars.fd");
403            match fs::symlink_metadata(&source_vars) {
404                Ok(_) => {
405                    copy_regular_file_new(&source_vars, &destination_vars)?;
406                    vars_published = true;
407                }
408                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
409                Err(error) => return Err(error.into()),
410            }
411
412            let mut file = OpenOptions::new()
413                .write(true)
414                .create_new(true)
415                .open(&destination_config_path)?;
416            definition_published = true;
417            file.write_all(definition.as_bytes())?;
418            file.sync_all()?;
419            Ok(())
420        })();
421        if result.is_err() {
422            let _ = fs::remove_file(&temporary_disk);
423            if definition_published {
424                let _ = fs::remove_file(&destination_config_path);
425            }
426            if vars_published {
427                let _ = fs::remove_file(&destination_vars);
428            }
429            if disk_published {
430                let _ = fs::remove_file(&destination_disk);
431            }
432        }
433        result?;
434        Ok(destination_config_path)
435    }
436
437    /// Attach read-only installation media to a stopped VM.
438    pub fn media_attach(&self, name: &str, media: &Path) -> Result<PathBuf> {
439        let _lock = self.lock(name)?;
440        self.require_stopped_unlocked(name)?;
441        let media = fs::canonicalize(media)
442            .with_context(|| format!("installation media {} does not exist", media.display()))?;
443        if !media.is_file() {
444            bail!(
445                "installation media {} is not a regular file",
446                media.display()
447            );
448        }
449        let mut config = self.config(name)?;
450        config.install_media = Some(media.clone());
451        self.save_config_unlocked(name, &config)?;
452        Ok(media)
453    }
454
455    /// Detach installation media from a stopped VM.
456    pub fn media_detach(&self, name: &str) -> Result<Option<PathBuf>> {
457        let _lock = self.lock(name)?;
458        self.require_stopped_unlocked(name)?;
459        let mut config = self.config(name)?;
460        let detached = config.install_media.take();
461        self.save_config_unlocked(name, &config)?;
462        Ok(detached)
463    }
464
465    /// Grow a stopped VM's system disk by a positive amount such as `20G`.
466    pub fn disk_grow(&self, name: &str, amount: &str) -> Result<()> {
467        let amount = validate_growth_amount(amount)?;
468        let _lock = self.lock(name)?;
469        let disk_ownership = self.lock_disk_ownership()?;
470        self.require_stopped_unlocked(name)?;
471        let config = self.config(name)?;
472        self.ensure_unique_disk_owner(name, &config)?;
473        drop(disk_ownership);
474        let host = HostCapabilities::probe()?;
475        let output = Command::new(&host.qemu_img)
476            .arg("resize")
477            .args(["-f", config.disk.format.qemu_driver()])
478            .arg(&config.disk.path)
479            .arg(format!("+{amount}"))
480            .output()
481            .context("failed to execute qemu-img resize")?;
482        if !output.status.success() {
483            bail!(
484                "qemu-img resize failed: {}",
485                String::from_utf8_lossy(&output.stderr).trim()
486            );
487        }
488        Ok(())
489    }
490
491    /// Return `qemu-img` JSON information for a stopped VM's system disk.
492    pub fn disk_info(&self, name: &str) -> Result<serde_json::Value> {
493        let _lock = self.lock(name)?;
494        self.require_stopped_unlocked(name)?;
495        let config = self.config(name)?;
496        let host = HostCapabilities::probe()?;
497        let output = Command::new(&host.qemu_img)
498            .arg("info")
499            .arg("--output=json")
500            .arg(&config.disk.path)
501            .output()
502            .context("failed to execute qemu-img info")?;
503        if !output.status.success() {
504            bail!(
505                "qemu-img info failed: {}",
506                String::from_utf8_lossy(&output.stderr).trim()
507            );
508        }
509        serde_json::from_slice(&output.stdout).context("qemu-img returned invalid JSON")
510    }
511
512    /// Add a validated user-network port forward to a stopped VM.
513    pub fn port_add(&self, name: &str, forward: PortForward) -> Result<()> {
514        let _lock = self.lock(name)?;
515        self.require_stopped_unlocked(name)?;
516        let mut config = self.config(name)?;
517        config.network.forwards.push(forward);
518        self.save_config_unlocked(name, &config)
519    }
520
521    /// Remove a user-network port forward from a stopped VM.
522    pub fn port_remove(
523        &self,
524        name: &str,
525        protocol: NetworkProtocol,
526        host_address: std::net::Ipv4Addr,
527        host_port: u16,
528    ) -> Result<PortForward> {
529        let _lock = self.lock(name)?;
530        self.require_stopped_unlocked(name)?;
531        let mut config = self.config(name)?;
532        let index = config
533            .network
534            .forwards
535            .iter()
536            .position(|forward| {
537                forward.protocol == protocol
538                    && forward.host_address == host_address
539                    && forward.host_port == host_port
540            })
541            .with_context(|| {
542                format!(
543                    "no {} port forward listens on {host_address}:{host_port}",
544                    protocol.qemu_name()
545                )
546            })?;
547        let removed = config.network.forwards.remove(index);
548        self.save_config_unlocked(name, &config)?;
549        Ok(removed)
550    }
551
552    /// Assign an exact host USB bus and address to a stopped VM.
553    pub fn usb_add(&self, name: &str, device: UsbHostDevice) -> Result<()> {
554        let _lock = self.lock(name)?;
555        self.require_stopped_unlocked(name)?;
556        let mut config = self.config(name)?;
557        config.usb_devices.push(device);
558        config
559            .usb_devices
560            .sort_unstable_by_key(|device| (device.bus, device.address));
561        self.save_config_unlocked(name, &config)
562    }
563
564    /// Remove an exact host USB bus and address from a stopped VM.
565    pub fn usb_remove(&self, name: &str, device: UsbHostDevice) -> Result<UsbHostDevice> {
566        let _lock = self.lock(name)?;
567        self.require_stopped_unlocked(name)?;
568        let mut config = self.config(name)?;
569        let index = config
570            .usb_devices
571            .iter()
572            .position(|configured| configured == &device)
573            .with_context(|| {
574                format!(
575                    "no USB host device is configured at bus {} address {}",
576                    device.bus, device.address
577                )
578            })?;
579        let removed = config.usb_devices.remove(index);
580        self.save_config_unlocked(name, &config)?;
581        Ok(removed)
582    }
583
584    /// Add a canonical host directory share to a stopped VM.
585    pub fn share_add(
586        &self,
587        name: &str,
588        tag: String,
589        path: &Path,
590        read_only: bool,
591    ) -> Result<DirectoryShare> {
592        let _lock = self.lock(name)?;
593        self.require_stopped_unlocked(name)?;
594        let path = fs::canonicalize(path)
595            .with_context(|| format!("shared host directory {} does not exist", path.display()))?;
596        let metadata = fs::symlink_metadata(&path)?;
597        if !metadata.is_dir() {
598            bail!("shared host path {} is not a directory", path.display());
599        }
600        let share = DirectoryShare {
601            tag,
602            path,
603            read_only,
604        };
605        let mut config = self.config(name)?;
606        config.shares.push(share.clone());
607        config
608            .shares
609            .sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
610        self.save_config_unlocked(name, &config)?;
611        Ok(share)
612    }
613
614    /// Remove a host directory share from a stopped VM by mount tag.
615    pub fn share_remove(&self, name: &str, tag: &str) -> Result<DirectoryShare> {
616        let _lock = self.lock(name)?;
617        self.require_stopped_unlocked(name)?;
618        let mut config = self.config(name)?;
619        let index = config
620            .shares
621            .iter()
622            .position(|share| share.tag == tag)
623            .with_context(|| format!("no host directory share has tag {tag}"))?;
624        let removed = config.shares.remove(index);
625        self.save_config_unlocked(name, &config)?;
626        Ok(removed)
627    }
628
629    /// Atomically update compute, guest, and host integration settings for a stopped VM.
630    pub fn configure(&self, name: &str, options: &ConfigureOptions) -> Result<VmConfig> {
631        if options.memory_mib.is_none()
632            && options.vcpus.is_none()
633            && options.acceleration.is_none()
634            && options.network_mode.is_none()
635            && options.audio.is_none()
636            && options.pointer_device.is_none()
637            && options.firmware.is_none()
638        {
639            bail!("configure requires at least one setting");
640        }
641        let _lock = self.lock(name)?;
642        self.require_stopped_unlocked(name)?;
643        let mut config = self.config(name)?;
644        if let Some(memory_mib) = options.memory_mib {
645            config.memory_mib = memory_mib;
646        }
647        if let Some(vcpus) = options.vcpus {
648            config.vcpus = vcpus;
649        }
650        if let Some(acceleration) = options.acceleration {
651            config.acceleration = acceleration;
652        }
653        if let Some(network_mode) = options.network_mode {
654            config.network.mode = network_mode;
655        }
656        if let Some(audio) = options.audio {
657            config.audio = audio;
658        }
659        if let Some(pointer_device) = options.pointer_device {
660            config.pointer_device = pointer_device;
661        }
662        if let Some(firmware) = options.firmware {
663            config.firmware = firmware;
664        }
665        self.save_config_unlocked(name, &config)?;
666        Ok(config)
667    }
668
669    /// Create a portable, integrity-checked backup directory for a stopped VM.
670    pub fn backup_create(&self, name: &str, destination: &Path) -> Result<BackupManifest> {
671        let host = HostCapabilities::probe()?;
672        self.backup_create_with_host(name, destination, &host)
673    }
674
675    fn backup_create_with_host(
676        &self,
677        name: &str,
678        destination: &Path,
679        host: &HostCapabilities,
680    ) -> Result<BackupManifest> {
681        let _lock = self.lock(name)?;
682        let disk_ownership = self.lock_disk_ownership()?;
683        self.require_stopped_unlocked(name)?;
684        self.clean_runtime(name)?;
685        let source = self.config(name)?;
686        self.ensure_unique_disk_owner(name, &source)?;
687        drop(disk_ownership);
688        ensure_path_absent(destination, "backup destination")?;
689        let source_data = self.paths.data(name)?;
690        ensure_private_dir(&source_data)?;
691        let nonce = SystemTime::now()
692            .duration_since(UNIX_EPOCH)
693            .unwrap_or_default()
694            .as_nanos();
695        let staging = source_data.join(format!(".backup-stage-{}-{nonce}", std::process::id()));
696        fs::create_dir(&staging)?;
697        ensure_private_dir(&staging)?;
698        let destination_parent_path = destination.parent().unwrap_or_else(|| Path::new("."));
699        let destination_name = destination
700            .file_name()
701            .context("backup destination must have a directory name")?;
702        let destination_parent = PinnedDir::open(destination_parent_path)?;
703        let publication_name = format!(".knottvm-backup-{}-{nonce}", std::process::id());
704        let mut publication_directory = None;
705        let mut published = false;
706        let result = (|| -> Result<BackupManifest> {
707            let backup_disk = staging.join(BACKUP_DISK_FILE);
708            let output = Command::new(&host.qemu_img)
709                .arg("convert")
710                .args(["-f", source.disk.format.qemu_driver(), "-O", "qcow2"])
711                .arg(&source.disk.path)
712                .arg(&backup_disk)
713                .output()
714                .context("failed to execute qemu-img convert for backup")?;
715            if !output.status.success() {
716                bail!(
717                    "qemu-img backup conversion failed: {}",
718                    String::from_utf8_lossy(&output.stderr).trim()
719                );
720            }
721            secure_regular_file(&backup_disk)?;
722
723            let mut portable = source.clone();
724            portable.disk.path = PathBuf::from(BACKUP_DISK_FILE);
725            portable.disk.format = DiskFormat::Qcow2;
726            portable.install_media = None;
727            portable.usb_devices.clear();
728            portable.shares.clear();
729            let config_path = staging.join(BACKUP_CONFIG_FILE);
730            write_new_file(&config_path, portable.to_toml()?.as_bytes())?;
731
732            let source_vars = source_data.join("uefi-vars.fd");
733            match fs::symlink_metadata(&source_vars) {
734                Ok(_) => {
735                    copy_regular_file_new(&source_vars, &staging.join(BACKUP_UEFI_VARS_FILE))?;
736                }
737                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
738                Err(error) => return Err(error.into()),
739            }
740            let source_tpm_state = source_data.join(BACKUP_TPM_STATE_DIR);
741            let has_tpm_state = match fs::symlink_metadata(&source_tpm_state) {
742                Ok(_) => true,
743                Err(error) if error.kind() == io::ErrorKind::NotFound => false,
744                Err(error) => return Err(error.into()),
745            };
746            if portable.software_tpm2 || has_tpm_state {
747                if has_tpm_state {
748                    ensure_private_dir(&source_tpm_state)?;
749                    validate_tpm_state_directory(&source_tpm_state)?;
750                }
751                copy_tpm_state_directory(
752                    &source_tpm_state,
753                    &staging.join(BACKUP_TPM_STATE_DIR),
754                    !has_tpm_state,
755                )?;
756            }
757
758            let manifest = BackupManifest::build(&staging, name.to_owned())?;
759            manifest.save(&staging)?;
760            let verified = Self::backup_verify_with_host(&staging, host)?;
761            if verified != manifest {
762                bail!("staged backup manifest changed unexpectedly");
763            }
764
765            rustix::fs::mkdirat(&destination_parent.fd, &publication_name, Mode::RWXU)
766                .with_context(|| {
767                    format!(
768                        "failed to create private backup publication directory under {}",
769                        destination_parent_path.display()
770                    )
771                })?;
772            publication_directory = destination_parent.open_child(&publication_name)?;
773            let publication_directory = publication_directory
774                .as_ref()
775                .context("new backup publication directory disappeared")?;
776            publication_directory
777                .copy_regular_from(&staging.join(BACKUP_CONFIG_FILE), BACKUP_CONFIG_FILE)?;
778            publication_directory
779                .copy_regular_from(&staging.join(BACKUP_DISK_FILE), BACKUP_DISK_FILE)?;
780            if manifest.uefi_vars.is_some() {
781                publication_directory.copy_regular_from(
782                    &staging.join(BACKUP_UEFI_VARS_FILE),
783                    BACKUP_UEFI_VARS_FILE,
784                )?;
785            }
786            if let Some(tpm_state) = &manifest.tpm_state {
787                copy_tpm_state_to_pinned(
788                    publication_directory,
789                    &staging.join(BACKUP_TPM_STATE_DIR),
790                    tpm_state,
791                )?;
792            }
793            publication_directory.copy_regular_from(
794                &staging.join(crate::backup::MANIFEST_FILE),
795                crate::backup::MANIFEST_FILE,
796            )?;
797            publication_directory.sync()?;
798            rustix::fs::renameat_with(
799                &destination_parent.fd,
800                &publication_name,
801                &destination_parent.fd,
802                destination_name,
803                RenameFlags::NOREPLACE,
804            )?;
805            published = true;
806            destination_parent.sync()?;
807            Ok(manifest)
808        })();
809        cleanup_backup_directory(&staging);
810        if result.is_err()
811            && !published
812            && let Some(directory) = publication_directory.take()
813        {
814            cleanup_pinned_backup_directory(&directory);
815            destination_parent.remove_child_dir_if_matches(&publication_name, &directory);
816        }
817        result
818    }
819
820    /// Verify hashes, schema, and qcow2 structure for a portable backup.
821    pub fn backup_verify(&self, root: &Path) -> Result<BackupManifest> {
822        let host = HostCapabilities::probe()?;
823        Self::backup_verify_with_host(root, &host)
824    }
825
826    fn backup_verify_with_host(root: &Path, host: &HostCapabilities) -> Result<BackupManifest> {
827        let metadata = fs::symlink_metadata(root)
828            .with_context(|| format!("failed to inspect backup root {}", root.display()))?;
829        if !metadata.is_dir() {
830            bail!("backup root {} is not a directory", root.display());
831        }
832        let manifest = BackupManifest::load(root)?;
833        manifest.verify(root)?;
834        let config = VmConfig::load(&root.join(BACKUP_CONFIG_FILE))?;
835        if config.name != manifest.source_name {
836            bail!("backup manifest and portable definition names do not match");
837        }
838        if config.software_tpm2 && manifest.tpm_state.is_none() {
839            bail!("backup configuration and TPM state manifest do not match");
840        }
841        validate_standalone_qcow2(host, &root.join(BACKUP_DISK_FILE))?;
842        Ok(manifest)
843    }
844
845    /// Restore a verified backup under a new VM name and independent identity.
846    pub fn backup_restore(&self, root: &Path, destination_name: &str) -> Result<PathBuf> {
847        let host = HostCapabilities::probe()?;
848        self.backup_restore_with_host(root, destination_name, &host)
849    }
850
851    fn backup_restore_with_host(
852        &self,
853        root: &Path,
854        destination_name: &str,
855        host: &HostCapabilities,
856    ) -> Result<PathBuf> {
857        let original_manifest = Self::backup_verify_with_host(root, host)?;
858        let _lock = self.lock(destination_name)?;
859        let disk_ownership = self.lock_disk_ownership()?;
860        self.require_stopped_unlocked(destination_name)?;
861        self.clean_runtime(destination_name)?;
862        let destination_config_path = self.paths.config(destination_name)?;
863        ensure_path_absent(&destination_config_path, "destination VM definition")?;
864        let destination_data = self.paths.data(destination_name)?;
865        ensure_private_dir(&destination_data)?;
866        let destination_directory = PinnedDir::open(&destination_data)?;
867        let destination_disk = destination_data.join("system.qcow2");
868        let destination_vars = destination_data.join("uefi-vars.fd");
869        let destination_tpm_state = destination_data.join(BACKUP_TPM_STATE_DIR);
870        let marker = destination_data.join(".restore-in-progress");
871        let temporary_disk = destination_data.join(".restore-disk.tmp");
872        let staging = destination_data.join(".restore-stage");
873
874        require_restore_marker_clear(&destination_directory, &marker)?;
875        ensure_path_absent(&destination_disk, "destination VM disk")?;
876        ensure_path_absent(&destination_vars, "destination UEFI variables")?;
877        ensure_path_absent(&destination_tpm_state, "destination software TPM state")?;
878        ensure_path_absent(&temporary_disk, "destination restore staging disk")?;
879        ensure_path_absent(&staging, "destination restore staging directory")?;
880        write_new_file(&marker, original_manifest.source_name.as_bytes())?;
881
882        let result = (|| -> Result<()> {
883            fs::create_dir(&staging)?;
884            ensure_private_dir(&staging)?;
885            copy_regular_file_new(
886                &root.join(crate::backup::MANIFEST_FILE),
887                &staging.join(crate::backup::MANIFEST_FILE),
888            )?;
889            copy_regular_file_new(
890                &root.join(BACKUP_CONFIG_FILE),
891                &staging.join(BACKUP_CONFIG_FILE),
892            )?;
893            copy_regular_file_new(
894                &root.join(BACKUP_DISK_FILE),
895                &staging.join(BACKUP_DISK_FILE),
896            )?;
897            if original_manifest.uefi_vars.is_some() {
898                copy_regular_file_new(
899                    &root.join(BACKUP_UEFI_VARS_FILE),
900                    &staging.join(BACKUP_UEFI_VARS_FILE),
901                )?;
902            }
903            if let Some(tpm_state) = &original_manifest.tpm_state {
904                copy_tpm_state_directory(
905                    &root.join(BACKUP_TPM_STATE_DIR),
906                    &staging.join(BACKUP_TPM_STATE_DIR),
907                    false,
908                )?;
909                if tpm_state.is_empty() && !staging.join(BACKUP_TPM_STATE_DIR).is_dir() {
910                    bail!("backup TPM state staging directory was not created");
911                }
912            }
913            let staged_manifest = Self::backup_verify_with_host(&staging, host)?;
914            if staged_manifest != original_manifest {
915                bail!("backup changed while it was being staged for restore");
916            }
917
918            let mut source = VmConfig::load(&staging.join(BACKUP_CONFIG_FILE))?;
919            if source.name != staged_manifest.source_name {
920                bail!("backup manifest and portable definition names do not match");
921            }
922            if source.software_tpm2 && staged_manifest.tpm_state.is_none() {
923                bail!("backup configuration and TPM state manifest do not match");
924            }
925            let staged_disk = staging.join(BACKUP_DISK_FILE);
926            if fs::canonicalize(&source.disk.path)? != fs::canonicalize(&staged_disk)? {
927                bail!("portable backup definition references an unexpected disk path");
928            }
929            destination_name.clone_into(&mut source.name);
930            source.disk.path.clone_from(&destination_disk);
931            source.disk.format = DiskFormat::Qcow2;
932            source.generation_id = Some(Uuid::new_v4());
933            source.install_media = None;
934            source.network.mac = None;
935            source.network.forwards.clear();
936            source.usb_devices.clear();
937            source.shares.clear();
938            self.ensure_unique_disk_owner(destination_name, &source)?;
939            drop(disk_ownership);
940            let definition = source.to_toml()?;
941            let output = Command::new(&host.qemu_img)
942                .arg("convert")
943                .args(["-f", "qcow2", "-O", "qcow2"])
944                .arg(&staged_disk)
945                .arg(&temporary_disk)
946                .output()
947                .context("failed to execute qemu-img convert for restore")?;
948            if !output.status.success() {
949                bail!(
950                    "qemu-img restore conversion failed: {}",
951                    String::from_utf8_lossy(&output.stderr).trim()
952                );
953            }
954            fs::hard_link(&temporary_disk, &destination_disk)?;
955            fs::remove_file(&temporary_disk)?;
956            if staged_manifest.uefi_vars.is_some() {
957                copy_regular_file_new(&staging.join(BACKUP_UEFI_VARS_FILE), &destination_vars)?;
958            }
959            if staged_manifest.tpm_state.is_some() {
960                copy_tpm_state_directory(
961                    &staging.join(BACKUP_TPM_STATE_DIR),
962                    &destination_tpm_state,
963                    false,
964                )?;
965            }
966            write_new_file(&destination_config_path, definition.as_bytes())?;
967            cleanup_backup_directory(&staging);
968            destination_directory.remove_regular(".restore-in-progress")?;
969            destination_directory.sync()?;
970            sync_directory(&self.paths.config_root)?;
971            Ok(())
972        })();
973        // Keep the marker and every artifact after an error. A future invocation
974        // will stop for manual inspection instead of guessing which paths this
975        // process still owns after a crash or concurrent filesystem change.
976        result?;
977        Ok(destination_config_path)
978    }
979
980    /// Delete a stopped VM definition and only its known managed artifacts.
981    pub fn delete_vm(&self, name: &str) -> Result<DeleteReport> {
982        let _lock = self.lock(name)?;
983        let _disk_ownership = self.lock_disk_ownership()?;
984        self.require_stopped_unlocked(name)?;
985        let definition = self.paths.config(name)?;
986        let tombstone = definition.with_extension("toml.deleting");
987        let (config, needs_tombstone) = match fs::symlink_metadata(&definition) {
988            Ok(metadata) if metadata.is_file() => {
989                let config = self.config(name)?;
990                self.ensure_unique_disk_owner(name, &config)?;
991                ensure_path_absent(&tombstone, "VM deletion tombstone")?;
992                (config, true)
993            }
994            Ok(_) => bail!(
995                "VM definition {} is not a regular file",
996                definition.display()
997            ),
998            Err(error) if error.kind() == io::ErrorKind::NotFound => {
999                let metadata = fs::symlink_metadata(&tombstone).with_context(|| {
1000                    format!("VM {name} does not exist and has no deletion to resume")
1001                })?;
1002                if !metadata.is_file() {
1003                    bail!(
1004                        "VM deletion tombstone {} is not a regular file",
1005                        tombstone.display()
1006                    );
1007                }
1008                let config = VmConfig::load(&tombstone)?;
1009                if config.name != name {
1010                    bail!("VM deletion tombstone name does not match {name}");
1011                }
1012                self.ensure_unique_disk_owner(name, &config)?;
1013                (config, false)
1014            }
1015            Err(error) => return Err(error.into()),
1016        };
1017
1018        let data = self.paths.data(name)?;
1019        let data_root = PinnedDir::open(&self.paths.data_root)?;
1020        let data_directory = data_root.open_child(name)?;
1021        let managed_disk = data.join("system.qcow2");
1022        let owns_managed_disk = config.disk.path == managed_disk;
1023        let preserved_disk = (!owns_managed_disk).then(|| config.disk.path.clone());
1024        if needs_tombstone {
1025            fs::rename(&definition, &tombstone)
1026                .with_context(|| format!("failed to begin durable deletion of VM {name}"))?;
1027            sync_directory(&self.paths.config_root)?;
1028        }
1029        self.clean_runtime(name)?;
1030        if let Some(data_directory) = &data_directory {
1031            if owns_managed_disk {
1032                // Recheck after runtime cleanup immediately before unlinking.
1033                // The durable tombstone keeps this disk visible to concurrent
1034                // owner checks while deletion is in progress.
1035                self.ensure_unique_disk_owner(name, &config)
1036                    .context("disk ownership changed while deleting the VM")?;
1037                data_directory.remove_regular("system.qcow2")?;
1038            }
1039            data_directory.remove_regular("uefi-vars.fd")?;
1040            data_directory.remove_child_regular_tree(BACKUP_TPM_STATE_DIR)?;
1041            data_directory.sync()?;
1042        }
1043        drop(data_directory);
1044        let _ = fs::remove_dir(&data);
1045        fs::remove_file(&tombstone)?;
1046        sync_directory(&self.paths.config_root)?;
1047        Ok(DeleteReport {
1048            definition,
1049            removed_managed_disk: owns_managed_disk,
1050            preserved_disk,
1051        })
1052    }
1053
1054    /*
1055     * Keep backup validation and destructive lifecycle operations above the
1056     * ordinary configuration accessors so their ordering invariants remain
1057     * visible together.
1058     */
1059
1060    /// Load a named definition.
1061    pub fn config(&self, name: &str) -> Result<VmConfig> {
1062        let config = VmConfig::load(&self.paths.config(name)?)?;
1063        if config.name != name {
1064            bail!(
1065                "VM definition filename {name}.toml does not match internal name {}",
1066                config.name
1067            );
1068        }
1069        Ok(config)
1070    }
1071
1072    /// Build the exact QEMU command without launching it.
1073    pub fn command(&self, name: &str) -> Result<CommandSpec> {
1074        let _lock = self.lock(name)?;
1075        self.ensure_no_unresolved_snapshot_revert(name)?;
1076        let config = self.config(name)?;
1077        let host = HostCapabilities::probe()?;
1078        let data = self.paths.data(name)?;
1079        ensure_private_dir(&data)?;
1080        let runtime = self.runtime_files(name, &data)?;
1081        if config.firmware.uses_uefi() {
1082            prepare_uefi_vars(&host, config.firmware, &runtime.uefi_vars)?;
1083        }
1084        build_command(&config, &host, &runtime)
1085    }
1086
1087    /// Launch QEMU as a daemon and record its private control endpoints.
1088    pub fn start(&self, name: &str) -> Result<VmState> {
1089        let host = HostCapabilities::probe()?;
1090        self.start_with_host(name, &host)
1091    }
1092
1093    fn start_with_host(&self, name: &str, host: &HostCapabilities) -> Result<VmState> {
1094        let _lock = self.lock(name)?;
1095        let disk_ownership = self.lock_disk_ownership()?;
1096        match self.status_unlocked(name)? {
1097            VmStatus::Running { pid, .. } => bail!("VM {name} is already running as PID {pid}"),
1098            VmStatus::Stale { pid } if process_exists(pid) => {
1099                bail!(
1100                    "VM {name} has a live PID {pid} but QMP is unavailable; use `knottvm kill {name}` after checking the process"
1101                );
1102            }
1103            VmStatus::Stale { .. } | VmStatus::Stopped => {}
1104        }
1105        self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())?;
1106        let mut config = self.config(name)?;
1107        if config.generation_id.is_none() {
1108            config.generation_id = Some(Uuid::new_v4());
1109            self.save_config_unlocked(name, &config)?;
1110        }
1111        self.ensure_unique_disk_owner(name, &config)?;
1112        drop(disk_ownership);
1113        let data = self.paths.data(name)?;
1114        let runtime_dir = self.paths.runtime(name)?;
1115        ensure_private_dir(&data)?;
1116        ensure_private_dir(&runtime_dir)?;
1117        let files = self.runtime_files(name, &data)?;
1118        if config.firmware.uses_uefi() {
1119            prepare_uefi_vars(host, config.firmware, &files.uefi_vars)?;
1120        }
1121        for path in [
1122            &files.qmp_socket,
1123            &files.display_socket,
1124            &files.agent_socket,
1125            &files.pid_file,
1126        ] {
1127            remove_if_exists(path)?;
1128        }
1129        let mut command = build_command(&config, host, &files)?;
1130        let launch_marker = runtime_dir.join("launching");
1131        create_launch_marker(&launch_marker, std::process::id())?;
1132        if config.software_tpm2 {
1133            let result = (|| -> Result<()> {
1134                ensure_private_dir(&files.tpm_state_dir)?;
1135                validate_tpm_state_directory(&files.tpm_state_dir)?;
1136                let swtpm = build_swtpm_command(&config, host, &files)?
1137                    .context("software TPM command was unexpectedly omitted")?;
1138                launch_swtpm(&swtpm)?;
1139                wait_for_swtpm(&files, Duration::from_secs(5))?;
1140                Ok(())
1141            })();
1142            if let Err(error) = result {
1143                if let Err(cleanup_error) =
1144                    self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
1145                {
1146                    bail!(
1147                        "{error:#}; software TPM cleanup failed and runtime state was preserved: {cleanup_error:#}"
1148                    );
1149                }
1150                return Err(error);
1151            }
1152        }
1153        let launch = (|| -> Result<Output> {
1154            let mut output = launch_qemu(&command, &launch_marker)?;
1155            if !output.status.success()
1156                && config.acceleration == crate::config::Acceleration::Auto
1157                && host.kvm_available
1158                && is_kvm_initialization_failure(&output.stderr)
1159                // Retry only if QEMU failed before publishing a PID file.
1160                && fs::symlink_metadata(&files.pid_file)
1161                    .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
1162            {
1163                let mut fallback_host = host.clone();
1164                fallback_host.kvm_available = false;
1165                command = build_command(&config, &fallback_host, &files)?;
1166                output = launch_qemu(&command, &launch_marker)?;
1167            }
1168            Ok(output)
1169        })();
1170        let output = match launch {
1171            Ok(output) => output,
1172            Err(error) => {
1173                if let Err(cleanup_error) =
1174                    self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
1175                {
1176                    bail!(
1177                        "{error:#}; software TPM cleanup failed and runtime state was preserved: {cleanup_error:#}"
1178                    );
1179                }
1180                return Err(error);
1181            }
1182        };
1183        if !output.status.success() {
1184            if let Ok(pid) = read_pid(&files.pid_file)
1185                && process_exists(pid)
1186            {
1187                bail!(
1188                    "QEMU reported startup failure but PID {pid} is live; runtime files were preserved"
1189                );
1190            }
1191            if let Err(cleanup_error) =
1192                self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
1193            {
1194                bail!(
1195                    "QEMU failed to start: {}; runtime cleanup failed and runtime state was preserved: {cleanup_error:#}",
1196                    String::from_utf8_lossy(&output.stderr).trim()
1197                );
1198            }
1199            bail!(
1200                "QEMU failed to start: {}",
1201                String::from_utf8_lossy(&output.stderr).trim()
1202            );
1203        }
1204        let startup = (|| {
1205            let pid = read_pid(&files.pid_file)?;
1206            wait_for_socket(&files.qmp_socket, pid, Duration::from_secs(5))?;
1207            wait_for_socket(&files.display_socket, pid, Duration::from_secs(5))?;
1208            wait_for_socket(&files.agent_socket, pid, Duration::from_secs(5))?;
1209            let state = VmState::new(
1210                name.to_owned(),
1211                pid,
1212                files.qmp_socket.clone(),
1213                files.display_socket.clone(),
1214                Some(files.agent_socket.clone()),
1215            );
1216            state.save(&runtime_dir.join("state.json"))?;
1217            remove_if_exists(&launch_marker)?;
1218            Ok(state)
1219        })();
1220        match startup {
1221            Ok(state) => Ok(state),
1222            Err(error) => {
1223                let pid = read_pid(&files.pid_file).ok();
1224                let live = pid.is_some_and(process_exists);
1225                let stopped = if live {
1226                    QmpClient::connect(&files.qmp_socket)
1227                        .and_then(|mut qmp| qmp.quit())
1228                        .and_then(|()| {
1229                            wait_for_exit(pid.unwrap_or_default(), Duration::from_secs(3))
1230                        })
1231                        .is_ok()
1232                } else {
1233                    true
1234                };
1235                if !stopped {
1236                    bail!(
1237                        "{error:#}; QEMU may still be running and runtime files were preserved for recovery"
1238                    );
1239                }
1240                if let Err(cleanup_error) =
1241                    self.clean_runtime_with_ioctl(name, host.swtpm_ioctl.as_deref())
1242                {
1243                    bail!(
1244                        "{error:#}; runtime cleanup failed and runtime state was preserved: {cleanup_error:#}"
1245                    );
1246                }
1247                Err(error)
1248            }
1249        }
1250    }
1251
1252    /// Query QMP when possible and distinguish stopped from stale state.
1253    pub fn status(&self, name: &str) -> Result<VmStatus> {
1254        let _lock = self.lock(name)?;
1255        self.status_unlocked(name)
1256    }
1257
1258    /// Request ACPI power-off and escalate to QMP quit after the timeout.
1259    pub fn stop(&self, name: &str, timeout: Duration) -> Result<()> {
1260        let _lock = self.lock(name)?;
1261        let Some(state) = self.load_state(name)? else {
1262            let runtime = self.paths.runtime(name)?;
1263            if ["swtpm.pid", "tpm.sock", "tpm-ctrl.sock"]
1264                .iter()
1265                .any(|file| fs::symlink_metadata(runtime.join(file)).is_ok())
1266            {
1267                return self.clean_runtime(name);
1268            }
1269            bail!("VM is not running");
1270        };
1271        if !process_exists(state.pid) {
1272            self.clean_runtime(name)?;
1273            return Ok(());
1274        }
1275        // Reject an unrepresentable timeout before requesting guest shutdown.
1276        let preflight_deadline = Instant::now()
1277            .checked_add(timeout)
1278            .context("VM shutdown timeout is too large")?;
1279        if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| {
1280            qmp.resume_if_paused()?;
1281            qmp.system_powerdown()
1282        }) {
1283            return self.stop_after_control_error(name, state.pid, error);
1284        }
1285        let deadline = deadline_after_shutdown_request(Instant::now(), timeout, preflight_deadline);
1286        while Instant::now() < deadline {
1287            if !process_exists(state.pid) {
1288                self.clean_runtime(name)?;
1289                return Ok(());
1290            }
1291            thread::sleep(Duration::from_millis(100));
1292        }
1293        if !process_exists(state.pid) {
1294            self.clean_runtime(name)?;
1295            return Ok(());
1296        }
1297        if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| qmp.quit()) {
1298            return self.stop_after_control_error(name, state.pid, error);
1299        }
1300        wait_for_exit(state.pid, Duration::from_secs(3))?;
1301        self.clean_runtime(name)
1302    }
1303
1304    fn stop_after_control_error(&self, name: &str, pid: u32, error: anyhow::Error) -> Result<()> {
1305        // An endpoint may disappear during either handshake or a command.
1306        // Preserve runtime state whenever the captured process is still live.
1307        if process_exists(pid) {
1308            Err(error)
1309        } else {
1310            self.clean_runtime(name)
1311        }
1312    }
1313
1314    /// Stop QEMU immediately through QMP.
1315    pub fn kill(&self, name: &str) -> Result<()> {
1316        let _lock = self.lock(name)?;
1317        let Some(state) = self.load_state(name)? else {
1318            return self.clean_runtime(name);
1319        };
1320        if process_exists(state.pid) {
1321            if !state.qmp_socket.exists() {
1322                bail!(
1323                    "refusing to discard live state for PID {} without its QMP socket",
1324                    state.pid
1325                );
1326            }
1327            if let Err(error) = self.qmp_unlocked(name).and_then(|mut qmp| qmp.quit()) {
1328                return self.stop_after_control_error(name, state.pid, error);
1329            }
1330            wait_for_exit(state.pid, Duration::from_secs(3))?;
1331        }
1332        self.clean_runtime(name)
1333    }
1334
1335    /// Pause all virtual CPUs through QMP.
1336    pub fn pause(&self, name: &str) -> Result<()> {
1337        let _lock = self.lock(name)?;
1338        self.qmp_unlocked(name)?.pause()
1339    }
1340
1341    /// Resume all virtual CPUs through QMP.
1342    pub fn resume(&self, name: &str) -> Result<()> {
1343        let _lock = self.lock(name)?;
1344        self.qmp_unlocked(name)?.resume()
1345    }
1346
1347    /// Reset the virtual machine through QMP.
1348    pub fn reset(&self, name: &str) -> Result<()> {
1349        let _lock = self.lock(name)?;
1350        self.qmp_unlocked(name)?.reset()
1351    }
1352
1353    /// Return the running VM's guest-reported balloon state.
1354    pub fn balloon_status(&self, name: &str) -> Result<BalloonStatus> {
1355        let _lock = self.lock(name)?;
1356        let configured_mib = self.config(name)?.memory_mib;
1357        let actual_bytes = self.qmp_unlocked(name)?.query_balloon()?;
1358        Ok(BalloonStatus {
1359            actual_bytes,
1360            configured_mib,
1361        })
1362    }
1363
1364    /// Request a bounded runtime memory target for a running VM.
1365    pub fn balloon_set(&self, name: &str, memory_mib: u64) -> Result<()> {
1366        let _lock = self.lock(name)?;
1367        let configured_mib = self.config(name)?.memory_mib;
1368        let bytes = validate_balloon_target(memory_mib, configured_mib)?;
1369        self.qmp_unlocked(name)?.set_balloon(bytes)
1370    }
1371
1372    /// Restore a running VM's balloon target to its configured boot memory.
1373    pub fn balloon_restore(&self, name: &str) -> Result<u64> {
1374        let _lock = self.lock(name)?;
1375        let configured_mib = self.config(name)?.memory_mib;
1376        let bytes = validate_balloon_target(configured_mib, configured_mib)?;
1377        self.qmp_unlocked(name)?.set_balloon(bytes)?;
1378        Ok(configured_mib)
1379    }
1380
1381    /// Capture a running VM's current framebuffer as a new bounded PPM file.
1382    pub fn screenshot(&self, name: &str, destination: &Path) -> Result<u64> {
1383        let _lock = self.lock(name)?;
1384        ensure_path_absent(destination, "screenshot destination")?;
1385        let runtime = self.paths.runtime(name)?;
1386        let staging = runtime.join("screenshot.ppm");
1387        remove_if_exists(&staging)?;
1388        let result = (|| -> Result<u64> {
1389            self.qmp_unlocked(name)?.screendump(&staging)?;
1390            publish_screenshot(&staging, destination)
1391        })();
1392        let cleanup = remove_if_exists(&staging);
1393        match (result, cleanup) {
1394            (Ok(bytes), Ok(())) => Ok(bytes),
1395            (Err(error), _) | (Ok(_), Err(error)) => Err(error),
1396        }
1397    }
1398
1399    /// Verify that the QEMU Guest Agent inside a running VM responds.
1400    pub fn agent_ping(&self, name: &str) -> Result<()> {
1401        let _lock = self.lock(name)?;
1402        self.agent_unlocked(name)?.ping()
1403    }
1404
1405    /// Return the running guest agent's version and supported command list.
1406    pub fn agent_info(&self, name: &str) -> Result<serde_json::Value> {
1407        let _lock = self.lock(name)?;
1408        self.agent_unlocked(name)?.info()
1409    }
1410
1411    /// Ask the guest operating system to shut down through its guest agent.
1412    pub fn agent_shutdown(&self, name: &str, mode: ShutdownMode) -> Result<()> {
1413        let _lock = self.lock(name)?;
1414        self.agent_unlocked(name)?.shutdown(mode)
1415    }
1416
1417    /// List internal qcow2 snapshots for a stopped VM.
1418    pub fn snapshot_list(&self, name: &str) -> Result<String> {
1419        self.snapshot_command(name, &["-l"], SnapshotOperation::List)
1420    }
1421
1422    /// Create an internal qcow2 snapshot for a stopped VM.
1423    pub fn snapshot_create(&self, name: &str, snapshot: &str) -> Result<()> {
1424        validate_snapshot_name(snapshot)?;
1425        self.snapshot_command(name, &["-c", snapshot], SnapshotOperation::Create)
1426            .map(|_| ())
1427    }
1428
1429    /// Revert a stopped VM to an internal qcow2 snapshot.
1430    pub fn snapshot_revert(&self, name: &str, snapshot: &str) -> Result<()> {
1431        self.snapshot_revert_with_probe(name, snapshot, HostCapabilities::probe)
1432    }
1433
1434    fn snapshot_revert_with_probe(
1435        &self,
1436        name: &str,
1437        snapshot: &str,
1438        probe_host: impl FnOnce() -> Result<HostCapabilities>,
1439    ) -> Result<()> {
1440        self.snapshot_revert_with_probes(name, snapshot, || self.status_unlocked(name), probe_host)
1441    }
1442
1443    fn snapshot_revert_with_probes(
1444        &self,
1445        name: &str,
1446        snapshot: &str,
1447        probe_status: impl FnOnce() -> Result<VmStatus>,
1448        probe_host: impl FnOnce() -> Result<HostCapabilities>,
1449    ) -> Result<()> {
1450        validate_snapshot_name(snapshot)?;
1451        let _lock = self.lock(name)?;
1452        let disk_ownership = self.lock_disk_ownership()?;
1453        let status = probe_status()?;
1454        require_stopped_status(name, &status)?;
1455        let mut config = self.config(name)?;
1456        let original_config = config.clone();
1457        ensure_snapshot_tpm_compatible(&config, SnapshotOperation::Revert)?;
1458        self.ensure_unique_disk_owner(name, &config)?;
1459        drop(disk_ownership);
1460        if config.disk.format != DiskFormat::Qcow2 {
1461            bail!("internal snapshots require a qcow2 system disk");
1462        }
1463        let host = probe_host()?;
1464        let disk = config.disk.path.clone();
1465        let data = self.paths.data(name)?;
1466        ensure_private_dir(&data)?;
1467        let marker = data.join(SNAPSHOT_REVERT_MARKER);
1468        ensure_path_absent(&marker, "snapshot revert transaction marker")?;
1469
1470        let rollback_snapshot = format!("knottvm-revert-{}", Uuid::new_v4().simple());
1471        let marker_contents =
1472            format!("rollback_snapshot={rollback_snapshot}\nrequested_snapshot={snapshot}\n");
1473        write_new_file(&marker, marker_contents.as_bytes())
1474            .context("failed to create snapshot revert recovery marker")?;
1475        if let Err(error) = sync_directory(&data) {
1476            let cleanup = remove_if_exists(&marker);
1477            return Err(match cleanup {
1478                Ok(()) => error.context("failed to persist snapshot revert recovery marker"),
1479                Err(cleanup_error) => error.context(format!(
1480                    "failed to persist snapshot revert recovery marker; marker cleanup also failed: {cleanup_error:#}"
1481                )),
1482            });
1483        }
1484
1485        if let Err(error) = run_qemu_img_snapshot(&host, &["-c", &rollback_snapshot], &disk) {
1486            return Err(error.context(format!(
1487                "failed to create the snapshot revert safety checkpoint; VM use is blocked by {}",
1488                marker.display()
1489            )));
1490        }
1491
1492        if let Err(error) = run_qemu_img_snapshot(&host, &["-a", snapshot], &disk) {
1493            return Err(Self::finish_failed_snapshot_revert(
1494                SnapshotRevertRecovery {
1495                    host: &host,
1496                    disk: &disk,
1497                    rollback_snapshot: &rollback_snapshot,
1498                    marker: &marker,
1499                    data: &data,
1500                },
1501                error.context(format!("failed to revert VM {name} to snapshot {snapshot}")),
1502                true,
1503            ));
1504        }
1505
1506        config.generation_id = Some(Uuid::new_v4());
1507        if let Err(error) = self.save_config_unlocked(name, &config) {
1508            return Err(self.finish_failed_snapshot_revert_with_original_config(
1509                name,
1510                &original_config,
1511                SnapshotRevertRecovery {
1512                    host: &host,
1513                    disk: &disk,
1514                    rollback_snapshot: &rollback_snapshot,
1515                    marker: &marker,
1516                    data: &data,
1517                },
1518                error.context("disk snapshot reverted but VMGenID publication failed"),
1519            ));
1520        }
1521        if let Err(error) = sync_directory(&self.paths.config_root) {
1522            return Err(self.finish_failed_snapshot_revert_with_original_config(
1523                name,
1524                &original_config,
1525                SnapshotRevertRecovery {
1526                    host: &host,
1527                    disk: &disk,
1528                    rollback_snapshot: &rollback_snapshot,
1529                    marker: &marker,
1530                    data: &data,
1531                },
1532                error.context("VMGenID directory sync failed after publication"),
1533            ));
1534        }
1535
1536        if let Err(error) = run_qemu_img_snapshot(&host, &["-d", &rollback_snapshot], &disk) {
1537            return Err(error.context(format!(
1538                "snapshot revert and VMGenID publication succeeded, but safety checkpoint {rollback_snapshot} could not be removed; VM use is blocked by {}",
1539                marker.display()
1540            )));
1541        }
1542        remove_if_exists(&marker).context(format!(
1543            "snapshot revert succeeded but recovery marker {} could not be removed",
1544            marker.display()
1545        ))?;
1546        sync_directory(&data)
1547            .context("snapshot revert succeeded but syncing its data directory failed")?;
1548        Ok(())
1549    }
1550
1551    fn finish_failed_snapshot_revert(
1552        recovery: SnapshotRevertRecovery<'_>,
1553        cause: anyhow::Error,
1554        restore_disk: bool,
1555    ) -> anyhow::Error {
1556        if restore_disk
1557            && let Err(rollback_error) = run_qemu_img_snapshot(
1558                recovery.host,
1559                &["-a", recovery.rollback_snapshot],
1560                recovery.disk,
1561            )
1562        {
1563            return cause.context(format!(
1564                "failed to restore the original disk from safety checkpoint {}: {rollback_error:#}; VM use is blocked by {}",
1565                recovery.rollback_snapshot,
1566                recovery.marker.display()
1567            ));
1568        }
1569
1570        if let Err(checkpoint_error) = run_qemu_img_snapshot(
1571            recovery.host,
1572            &["-d", recovery.rollback_snapshot],
1573            recovery.disk,
1574        ) {
1575            return cause.context(format!(
1576                "original disk and VMGenID were restored, but safety checkpoint {} could not be removed: {checkpoint_error:#}; VM use is blocked by {}",
1577                recovery.rollback_snapshot,
1578                recovery.marker.display()
1579            ));
1580        }
1581        if let Err(marker_error) = remove_if_exists(recovery.marker) {
1582            return cause.context(format!(
1583                "original disk and VMGenID were restored, but recovery marker {} remains: {marker_error:#}",
1584                recovery.marker.display()
1585            ));
1586        }
1587        if let Err(sync_error) = sync_directory(recovery.data) {
1588            return cause.context(format!(
1589                "original disk and VMGenID were restored, but syncing recovery cleanup failed: {sync_error:#}"
1590            ));
1591        }
1592        cause
1593    }
1594
1595    fn finish_failed_snapshot_revert_with_original_config(
1596        &self,
1597        name: &str,
1598        original_config: &VmConfig,
1599        recovery: SnapshotRevertRecovery<'_>,
1600        cause: anyhow::Error,
1601    ) -> anyhow::Error {
1602        if let Err(rollback_error) = run_qemu_img_snapshot(
1603            recovery.host,
1604            &["-a", recovery.rollback_snapshot],
1605            recovery.disk,
1606        ) {
1607            return cause.context(format!(
1608                "failed to restore the original disk from safety checkpoint {}: {rollback_error:#}; VM use is blocked by {}",
1609                recovery.rollback_snapshot,
1610                recovery.marker.display()
1611            ));
1612        }
1613
1614        let config_restore = match self.config(name) {
1615            Ok(current) if current.generation_id == original_config.generation_id => Ok(()),
1616            Ok(_) => self
1617                .save_config_unlocked(name, original_config)
1618                .and_then(|()| sync_directory(&self.paths.config_root)),
1619            Err(error) => Err(error),
1620        };
1621        if let Err(config_error) = config_restore {
1622            return cause.context(format!(
1623                "original disk was restored but the original VM definition could not be confirmed or restored: {config_error:#}; VM use is blocked by {}",
1624                recovery.marker.display()
1625            ));
1626        }
1627
1628        Self::finish_failed_snapshot_revert(recovery, cause, false)
1629    }
1630
1631    /// Delete an internal qcow2 snapshot from a stopped VM.
1632    pub fn snapshot_delete(&self, name: &str, snapshot: &str) -> Result<()> {
1633        validate_snapshot_name(snapshot)?;
1634        self.snapshot_command(name, &["-d", snapshot], SnapshotOperation::Delete)
1635            .map(|_| ())
1636    }
1637
1638    /// Return the stable VM Generation ID exposed to the guest.
1639    pub fn generation_id(&self, name: &str) -> Result<Option<Uuid>> {
1640        Ok(self.config(name)?.generation_id)
1641    }
1642
1643    /// Replace a stopped VM's generation ID after an external duplication event.
1644    pub fn regenerate_generation_id(&self, name: &str) -> Result<Uuid> {
1645        let _lock = self.lock(name)?;
1646        self.require_stopped_unlocked(name)?;
1647        let mut config = self.config(name)?;
1648        let generation_id = Uuid::new_v4();
1649        config.generation_id = Some(generation_id);
1650        self.save_config_unlocked(name, &config)?;
1651        Ok(generation_id)
1652    }
1653
1654    /// Load current runtime state for the console.
1655    pub fn running_state(&self, name: &str) -> Result<VmState> {
1656        match self.status(name)? {
1657            VmStatus::Running { .. } => self
1658                .load_state(name)?
1659                .context("running VM did not have state metadata"),
1660            VmStatus::Stopped => bail!("VM {name} is stopped"),
1661            VmStatus::Stale { pid } => bail!("VM {name} has stale state for PID {pid}"),
1662        }
1663    }
1664
1665    /// Return definition names in deterministic order.
1666    pub fn list(&self) -> Result<Vec<String>> {
1667        let mut names = fs::read_dir(&self.paths.config_root)?
1668            .filter_map(Result::ok)
1669            .filter_map(|entry| {
1670                let path = entry.path();
1671                (path.extension().and_then(|value| value.to_str()) == Some("toml"))
1672                    .then(|| path.file_stem()?.to_str().map(ToOwned::to_owned))
1673                    .flatten()
1674            })
1675            .collect::<Vec<_>>();
1676        names.sort();
1677        Ok(names)
1678    }
1679
1680    fn status_unlocked(&self, name: &str) -> Result<VmStatus> {
1681        self.paths.config(name)?;
1682        self.ensure_no_unresolved_snapshot_revert(name)?;
1683        let Some(state) = self.load_state(name)? else {
1684            let runtime = self.paths.runtime(name)?;
1685            let swtpm_pid_file = runtime.join("swtpm.pid");
1686            match fs::symlink_metadata(&swtpm_pid_file) {
1687                Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
1688                    let pid = read_process_pid(&swtpm_pid_file, "swtpm")?;
1689                    if process_exists(pid) {
1690                        return Ok(VmStatus::Stale { pid });
1691                    }
1692                }
1693                Ok(_) => bail!("software TPM PID file is not a regular file"),
1694                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
1695                Err(error) => return Err(error.into()),
1696            }
1697            if probe_unix_socket(&runtime.join("tpm-ctrl.sock"))?
1698                || probe_unix_socket(&runtime.join("tpm.sock"))?
1699            {
1700                bail!(
1701                    "software TPM is live without recoverable PID state; use `knottvm kill {name}` after checking the process"
1702                );
1703            }
1704            return Ok(VmStatus::Stopped);
1705        };
1706        if !process_exists(state.pid) {
1707            return Ok(VmStatus::Stale { pid: state.pid });
1708        }
1709        match QmpClient::connect(&state.qmp_socket).and_then(|mut qmp| {
1710            if qmp.query_name()? != name {
1711                bail!("QMP endpoint belongs to a different VM");
1712            }
1713            qmp.query_status()
1714        }) {
1715            Ok(qemu_status) => {
1716                if self.config(name)?.software_tpm2 {
1717                    let swtpm_pid_file = self.paths.runtime(name)?.join("swtpm.pid");
1718                    if !fs::symlink_metadata(&swtpm_pid_file).is_ok_and(|metadata| {
1719                        metadata.is_file() && !metadata.file_type().is_symlink()
1720                    }) || !read_process_pid(&swtpm_pid_file, "swtpm").is_ok_and(process_exists)
1721                    {
1722                        return Ok(VmStatus::Stale { pid: state.pid });
1723                    }
1724                }
1725                Ok(VmStatus::Running {
1726                    pid: state.pid,
1727                    qemu_status,
1728                })
1729            }
1730            Err(_) => Ok(VmStatus::Stale { pid: state.pid }),
1731        }
1732    }
1733
1734    fn require_stopped_unlocked(&self, name: &str) -> Result<()> {
1735        let status = self.status_unlocked(name)?;
1736        require_stopped_status(name, &status)
1737    }
1738
1739    fn ensure_no_unresolved_snapshot_revert(&self, name: &str) -> Result<()> {
1740        let data = self.paths.data(name)?;
1741        match fs::symlink_metadata(&data) {
1742            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1743            Err(error) => return Err(error.into()),
1744            Ok(metadata) if !metadata.is_dir() || metadata.file_type().is_symlink() => {
1745                bail!(
1746                    "VM data directory {} is not a real directory",
1747                    data.display()
1748                );
1749            }
1750            Ok(_) => {}
1751        }
1752        let marker = data.join(SNAPSHOT_REVERT_MARKER);
1753        match fs::symlink_metadata(&marker) {
1754            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1755            Err(error) => Err(error.into()),
1756            Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
1757                bail!(
1758                    "VM {name} has an unresolved snapshot revert transaction at {}; inspect its rollback checkpoint before use",
1759                    marker.display()
1760                );
1761            }
1762            Ok(_) => bail!(
1763                "snapshot revert transaction marker {} is not a regular file",
1764                marker.display()
1765            ),
1766        }
1767    }
1768
1769    fn save_config_unlocked(&self, name: &str, config: &VmConfig) -> Result<()> {
1770        if config.name != name {
1771            bail!("refusing to save a VM definition under a different name");
1772        }
1773        let path = self.paths.config(name)?;
1774        let metadata = fs::symlink_metadata(&path)
1775            .with_context(|| format!("failed to inspect VM definition {}", path.display()))?;
1776        if !metadata.is_file() {
1777            bail!("VM definition {} is not a regular file", path.display());
1778        }
1779        let source = config.to_toml()?;
1780        let nonce = SystemTime::now()
1781            .duration_since(UNIX_EPOCH)
1782            .unwrap_or_default()
1783            .as_nanos();
1784        let temporary = path.with_extension(format!("toml.tmp-{}-{nonce}", std::process::id()));
1785        let result = (|| -> Result<()> {
1786            let mut file = OpenOptions::new()
1787                .write(true)
1788                .create_new(true)
1789                .open(&temporary)?;
1790            file.write_all(source.as_bytes())?;
1791            file.sync_all()?;
1792            fs::rename(&temporary, &path)?;
1793            Ok(())
1794        })();
1795        if result.is_err() {
1796            let _ = fs::remove_file(&temporary);
1797        }
1798        result.with_context(|| format!("failed to update VM definition {}", path.display()))
1799    }
1800
1801    fn qmp_unlocked(&self, name: &str) -> Result<QmpClient> {
1802        let state = self.load_state(name)?.context("VM is not running")?;
1803        if !process_exists(state.pid) {
1804            bail!("VM {name} has stale state for PID {}", state.pid);
1805        }
1806        let mut qmp = QmpClient::connect(&state.qmp_socket)?;
1807        if qmp.query_name()? != name {
1808            bail!("QMP endpoint does not belong to VM {name}");
1809        }
1810        Ok(qmp)
1811    }
1812
1813    fn agent_unlocked(&self, name: &str) -> Result<GuestAgentClient> {
1814        let state = self.load_state(name)?.context("VM is not running")?;
1815        if !process_exists(state.pid) {
1816            bail!("VM {name} has stale state for PID {}", state.pid);
1817        }
1818        let socket = match state.agent_socket {
1819            Some(socket) => socket,
1820            None => self.paths.runtime(name)?.join("agent.sock"),
1821        };
1822        GuestAgentClient::connect(&socket)
1823    }
1824
1825    fn snapshot_command(
1826        &self,
1827        name: &str,
1828        arguments: &[&str],
1829        operation: SnapshotOperation,
1830    ) -> Result<String> {
1831        let _lock = self.lock(name)?;
1832        let _disk_ownership = self.lock_disk_ownership()?;
1833        self.snapshot_command_unlocked(name, arguments, operation)
1834    }
1835
1836    fn snapshot_command_unlocked(
1837        &self,
1838        name: &str,
1839        arguments: &[&str],
1840        operation: SnapshotOperation,
1841    ) -> Result<String> {
1842        match self.status_unlocked(name)? {
1843            VmStatus::Stopped => {}
1844            VmStatus::Running { .. } => {
1845                bail!("VM {name} must be stopped before changing internal snapshots");
1846            }
1847            VmStatus::Stale { pid } => {
1848                bail!("VM {name} has stale runtime state for PID {pid}; resolve it first");
1849            }
1850        }
1851        let config = self.config(name)?;
1852        ensure_snapshot_tpm_compatible(&config, operation)?;
1853        self.ensure_unique_disk_owner(name, &config)?;
1854        if config.disk.format != DiskFormat::Qcow2 {
1855            bail!("internal snapshots require a qcow2 system disk");
1856        }
1857        let host = HostCapabilities::probe()?;
1858        run_qemu_img_snapshot(&host, arguments, &config.disk.path)
1859    }
1860
1861    fn ensure_unique_disk_owner(&self, name: &str, config: &VmConfig) -> Result<()> {
1862        let disk = disk_reference(&config.disk.path).with_context(|| {
1863            format!(
1864                "failed to resolve guest disk {}",
1865                config.disk.path.display()
1866            )
1867        })?;
1868        for (other_name, definition) in self.disk_owner_definitions()? {
1869            if other_name == name {
1870                continue;
1871            }
1872            let other = VmConfig::load(&definition).with_context(|| {
1873                format!(
1874                    "cannot verify disk ownership because VM definition {other_name} is invalid"
1875                )
1876            })?;
1877            let other_disk = disk_reference(&other.disk.path).with_context(|| {
1878                format!(
1879                    "cannot verify disk ownership because VM {other_name} references {}",
1880                    other.disk.path.display()
1881                )
1882            })?;
1883            let same_path = other_disk.path == disk.path;
1884            let same_file = matches!((disk.identity, other_disk.identity),
1885                (Some(first), Some(second)) if first == second);
1886            if same_path || same_file {
1887                bail!(
1888                    "VM definitions {name} and {other_name} reference the same system disk {}",
1889                    disk.path.display()
1890                );
1891            }
1892        }
1893        Ok(())
1894    }
1895
1896    /// Return every current or pending VM definition that can own a disk.
1897    /// Deletion tombstones remain owners until their managed artifacts are
1898    /// removed and the tombstone itself is durably cleared.
1899    fn disk_owner_definitions(&self) -> Result<Vec<(String, PathBuf)>> {
1900        let mut definitions = Vec::new();
1901        let mut names = BTreeSet::new();
1902        for entry in fs::read_dir(&self.paths.config_root)? {
1903            let entry = entry?;
1904            let path = entry.path();
1905            let filename = entry.file_name();
1906            let bytes = filename.as_bytes();
1907            let name_bytes = if let Some(name) = bytes.strip_suffix(b".toml.deleting") {
1908                name
1909            } else if let Some(name) = bytes.strip_suffix(b".toml") {
1910                name
1911            } else {
1912                continue;
1913            };
1914            let name = std::str::from_utf8(name_bytes)
1915                .context("cannot verify disk ownership for a non-UTF-8 VM definition name")?;
1916            crate::config::validate_name(name).with_context(|| {
1917                format!("cannot verify disk ownership for invalid name {name:?}")
1918            })?;
1919            let metadata = fs::symlink_metadata(&path)
1920                .with_context(|| format!("cannot inspect VM definition {}", path.display()))?;
1921            if !metadata.is_file() {
1922                bail!(
1923                    "cannot verify disk ownership because VM definition {} is not a regular file",
1924                    path.display()
1925                );
1926            }
1927            if !names.insert(name.to_owned()) {
1928                bail!(
1929                    "cannot verify disk ownership because VM {name} has both a definition and a pending deletion"
1930                );
1931            }
1932            definitions.push((name.to_owned(), path));
1933        }
1934        definitions.sort_by(|left, right| left.0.cmp(&right.0));
1935        Ok(definitions)
1936    }
1937
1938    fn runtime_files(&self, name: &str, data: &Path) -> Result<RuntimeFiles> {
1939        let runtime = self.paths.runtime(name)?;
1940        Ok(RuntimeFiles {
1941            qmp_socket: runtime.join("qmp.sock"),
1942            display_socket: runtime.join("display.sock"),
1943            agent_socket: runtime.join("agent.sock"),
1944            pid_file: runtime.join("qemu.pid"),
1945            uefi_vars: data.join("uefi-vars.fd"),
1946            tpm_socket: runtime.join("tpm.sock"),
1947            tpm_control_socket: runtime.join("tpm-ctrl.sock"),
1948            swtpm_pid_file: runtime.join("swtpm.pid"),
1949            tpm_state_dir: data.join("tpm-state"),
1950        })
1951    }
1952
1953    fn stop_swtpm(&self, name: &str, ioctl_override: Option<&Path>) -> Result<()> {
1954        let data = self.paths.data(name)?;
1955        let files = self.runtime_files(name, &data)?;
1956        stop_swtpm_files(&files, ioctl_override)
1957            .with_context(|| format!("failed to stop software TPM for VM {name}"))?;
1958        Ok(())
1959    }
1960
1961    fn load_state(&self, name: &str) -> Result<Option<VmState>> {
1962        let path = self.paths.runtime(name)?.join("state.json");
1963        if path.exists() {
1964            return VmState::load(&path).map(Some);
1965        }
1966        let runtime = self.paths.runtime(name)?;
1967        let pid_file = runtime.join("qemu.pid");
1968        if pid_file.exists() {
1969            let pid = read_pid(&pid_file)?;
1970            let state = VmState::new(
1971                name.to_owned(),
1972                pid,
1973                runtime.join("qmp.sock"),
1974                runtime.join("display.sock"),
1975                Some(runtime.join("agent.sock")),
1976            );
1977            if process_exists(pid)
1978                && let Ok(mut qmp) = QmpClient::connect(&state.qmp_socket)
1979                && matches!(qmp.query_name(), Ok(ref qemu_name) if qemu_name == name)
1980            {
1981                state.save(&path)?;
1982            }
1983            return Ok(Some(state));
1984        }
1985        let launch_marker = runtime.join("launching");
1986        if launch_marker.exists() {
1987            let qmp_socket = runtime.join("qmp.sock");
1988            if let Ok(mut qmp) = QmpClient::connect(&qmp_socket)
1989                && matches!(qmp.query_name(), Ok(ref qemu_name) if qemu_name == name)
1990            {
1991                bail!("VM {name} is running without a recoverable QEMU PID file");
1992            }
1993            if runtime.join("swtpm.pid").exists() {
1994                return Ok(None);
1995            }
1996            let marker_age = fs::metadata(&launch_marker)
1997                .and_then(|metadata| metadata.modified())
1998                .ok()
1999                .and_then(|modified| modified.elapsed().ok())
2000                .unwrap_or_default();
2001            if marker_age < Duration::from_secs(10) {
2002                bail!("VM {name} has an incomplete launch in progress; retry shortly");
2003            }
2004            let display_socket = runtime.join("display.sock");
2005            if UnixStream::connect(&display_socket).is_ok() {
2006                bail!("VM {name} has a live display endpoint without recoverable PID state");
2007            }
2008            for stale in [qmp_socket, display_socket, launch_marker] {
2009                remove_if_exists(&stale)?;
2010            }
2011        }
2012        for endpoint in [runtime.join("qmp.sock"), runtime.join("display.sock")] {
2013            if endpoint.exists() {
2014                bail!(
2015                    "orphan runtime endpoint {} exists without recoverable PID state",
2016                    endpoint.display()
2017                );
2018            }
2019        }
2020        Ok(None)
2021    }
2022
2023    fn clean_runtime(&self, name: &str) -> Result<()> {
2024        self.clean_runtime_with_ioctl(name, None)
2025    }
2026
2027    fn clean_runtime_with_ioctl(&self, name: &str, ioctl_override: Option<&Path>) -> Result<()> {
2028        self.stop_swtpm(name, ioctl_override)?;
2029        let runtime = self.paths.runtime(name)?;
2030        for file in [
2031            "state.json",
2032            "qemu.pid",
2033            "qmp.sock",
2034            "display.sock",
2035            "agent.sock",
2036            "screenshot.ppm",
2037            "launching",
2038            "swtpm.pid",
2039            "tpm.sock",
2040            "tpm-ctrl.sock",
2041        ] {
2042            remove_if_exists(&runtime.join(file))?;
2043        }
2044        Ok(())
2045    }
2046
2047    fn lock(&self, name: &str) -> Result<VmLock> {
2048        let runtime = self.paths.runtime(name)?;
2049        ensure_private_dir(&runtime)?;
2050        let file = OpenOptions::new()
2051            .read(true)
2052            .write(true)
2053            .create(true)
2054            .truncate(false)
2055            .mode(0o600)
2056            .custom_flags(libc::O_NOFOLLOW)
2057            .open(runtime.join("operation.lock"))?;
2058        file.lock_exclusive()?;
2059        Ok(VmLock(file))
2060    }
2061
2062    /// Serialize ownership scans and deletion's tombstone/unlink window across
2063    /// manager processes. Callers acquire per-VM locks first.
2064    fn lock_disk_ownership(&self) -> Result<VmLock> {
2065        let file = OpenOptions::new()
2066            .read(true)
2067            .write(true)
2068            .create(true)
2069            .truncate(false)
2070            .mode(0o600)
2071            .custom_flags(libc::O_NOFOLLOW)
2072            .open(self.paths.runtime_root.join("disk-ownership.lock"))?;
2073        file.lock_exclusive()
2074            .context("failed to acquire VM disk ownership lock")?;
2075        Ok(VmLock(file))
2076    }
2077}
2078
2079struct VmLock(File);
2080
2081struct DiskReference {
2082    path: PathBuf,
2083    identity: Option<(u64, u64)>,
2084}
2085
2086/// Resolve existing aliases and prospective paths whose final file is absent.
2087/// Missing peer parents and dangling symlinks fail closed in ownership checks.
2088fn disk_reference(path: &Path) -> Result<DiskReference> {
2089    let resolved = match fs::symlink_metadata(path) {
2090        Ok(_) => fs::canonicalize(path)
2091            .with_context(|| format!("failed to canonicalize disk path {}", path.display()))?,
2092        Err(error) if error.kind() == io::ErrorKind::NotFound => {
2093            let filename = path
2094                .file_name()
2095                .context("disk path has no final filename")?;
2096            let parent = path
2097                .parent()
2098                .filter(|parent| !parent.as_os_str().is_empty())
2099                .unwrap_or_else(|| Path::new("."));
2100            fs::canonicalize(parent)
2101                .with_context(|| format!("failed to resolve disk parent {}", parent.display()))?
2102                .join(filename)
2103        }
2104        Err(error) => {
2105            return Err(error)
2106                .with_context(|| format!("failed to inspect disk path {}", path.display()));
2107        }
2108    };
2109    let identity = match fs::metadata(&resolved) {
2110        Ok(metadata) => Some((metadata.dev(), metadata.ino())),
2111        Err(error) if error.kind() == io::ErrorKind::NotFound => None,
2112        Err(error) => {
2113            return Err(error).with_context(|| {
2114                format!("failed to inspect resolved disk {}", resolved.display())
2115            });
2116        }
2117    };
2118    Ok(DiskReference {
2119        path: resolved,
2120        identity,
2121    })
2122}
2123
2124impl Drop for VmLock {
2125    fn drop(&mut self) {
2126        let _ = FileExt::unlock(&self.0);
2127    }
2128}
2129
2130fn read_pid(path: &Path) -> Result<u32> {
2131    let mut source = String::new();
2132    File::open(path)
2133        .with_context(|| format!("QEMU did not create PID file {}", path.display()))?
2134        .read_to_string(&mut source)?;
2135    source
2136        .trim()
2137        .parse::<u32>()
2138        .with_context(|| format!("invalid QEMU PID in {}", path.display()))
2139}
2140
2141fn wait_for_socket(path: &Path, pid: u32, timeout: Duration) -> Result<()> {
2142    let deadline = Instant::now() + timeout;
2143    while Instant::now() < deadline {
2144        if path.exists() {
2145            return Ok(());
2146        }
2147        if !process_exists(pid) {
2148            bail!("QEMU exited before creating {}", path.display());
2149        }
2150        thread::sleep(Duration::from_millis(25));
2151    }
2152    bail!("timed out waiting for QEMU socket {}", path.display())
2153}
2154
2155fn wait_for_exit(pid: u32, timeout: Duration) -> Result<()> {
2156    let deadline = Instant::now()
2157        .checked_add(timeout)
2158        .context("VM exit timeout is too large")?;
2159    while Instant::now() < deadline {
2160        if !process_exists(pid) {
2161            return Ok(());
2162        }
2163        thread::sleep(
2164            deadline
2165                .saturating_duration_since(Instant::now())
2166                .min(Duration::from_millis(50)),
2167        );
2168    }
2169    if !process_exists(pid) {
2170        return Ok(());
2171    }
2172    bail!("QEMU process {pid} did not exit")
2173}
2174
2175fn deadline_after_shutdown_request(
2176    now: Instant,
2177    timeout: Duration,
2178    preflight_deadline: Instant,
2179) -> Instant {
2180    now.checked_add(timeout).unwrap_or(preflight_deadline)
2181}
2182
2183fn remove_if_exists(path: &Path) -> Result<()> {
2184    match fs::remove_file(path) {
2185        Ok(()) => Ok(()),
2186        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
2187        Err(error) => Err(error).with_context(|| format!("failed to remove {}", path.display())),
2188    }
2189}
2190
2191fn ensure_path_absent(path: &Path, label: &str) -> Result<()> {
2192    match fs::symlink_metadata(path) {
2193        Ok(_) => bail!("{label} {} already exists", path.display()),
2194        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
2195        Err(error) => Err(error.into()),
2196    }
2197}
2198
2199fn validate_tpm_state_directory(path: &Path) -> Result<()> {
2200    let metadata = fs::symlink_metadata(path)?;
2201    if !metadata.is_dir() || metadata.file_type().is_symlink() {
2202        bail!(
2203            "software TPM state {} is not a real directory",
2204            path.display()
2205        );
2206    }
2207    let uid = unsafe { libc::geteuid() };
2208    if metadata.uid() != uid {
2209        bail!(
2210            "software TPM state {} is owned by another user",
2211            path.display()
2212        );
2213    }
2214    let mut total_bytes = 0_u64;
2215    let mut count = 0_usize;
2216    for entry in fs::read_dir(path)? {
2217        let entry = entry?;
2218        let name = entry.file_name();
2219        let name = name
2220            .to_str()
2221            .context("software TPM state contains a non-UTF-8 filename")?;
2222        validate_tpm_state_name(name)?;
2223        let entry_metadata = fs::symlink_metadata(entry.path())?;
2224        if !entry_metadata.is_file() || entry_metadata.file_type().is_symlink() {
2225            bail!(
2226                "software TPM state entry {} is not a regular file",
2227                entry.path().display()
2228            );
2229        }
2230        if entry_metadata.uid() != uid {
2231            bail!(
2232                "software TPM state entry {} is owned by another user",
2233                entry.path().display()
2234            );
2235        }
2236        total_bytes = total_bytes
2237            .checked_add(entry_metadata.len())
2238            .context("software TPM state size overflow")?;
2239        count += 1;
2240        if count > crate::backup::MAX_TPM_STATE_FILES
2241            || total_bytes > crate::backup::MAX_TPM_STATE_BYTES
2242        {
2243            bail!("software TPM state exceeds the managed file or size limit");
2244        }
2245        secure_regular_file(&entry.path())?;
2246    }
2247    Ok(())
2248}
2249
2250fn copy_tpm_state_directory(source: &Path, destination: &Path, allow_missing: bool) -> Result<()> {
2251    match fs::symlink_metadata(source) {
2252        Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {}
2253        Ok(_) => bail!(
2254            "software TPM state {} is not a real directory",
2255            source.display()
2256        ),
2257        Err(error) if error.kind() == io::ErrorKind::NotFound && allow_missing => {
2258            fs::create_dir(destination)?;
2259            ensure_private_dir(destination)?;
2260            return Ok(());
2261        }
2262        Err(error) if error.kind() == io::ErrorKind::NotFound => {
2263            bail!("software TPM state {} is missing", source.display());
2264        }
2265        Err(error) => return Err(error.into()),
2266    }
2267    fs::create_dir(destination)?;
2268    ensure_private_dir(destination)?;
2269    let mut total_bytes = 0_u64;
2270    let mut count = 0_usize;
2271    for entry in fs::read_dir(source)? {
2272        let entry = entry?;
2273        let name = entry
2274            .file_name()
2275            .into_string()
2276            .map_err(|_| anyhow::anyhow!("software TPM state contains a non-UTF-8 filename"))?;
2277        validate_tpm_state_name(&name)?;
2278        let metadata = fs::symlink_metadata(entry.path())?;
2279        if !metadata.is_file() || metadata.file_type().is_symlink() {
2280            bail!(
2281                "software TPM state entry {} is not a regular file",
2282                entry.path().display()
2283            );
2284        }
2285        count += 1;
2286        if count > crate::backup::MAX_TPM_STATE_FILES {
2287            bail!("software TPM state exceeds the managed file or size limit");
2288        }
2289        let copied = copy_tpm_state_file_new(
2290            &entry.path(),
2291            &destination.join(name),
2292            crate::backup::MAX_TPM_STATE_BYTES,
2293        )?;
2294        total_bytes = total_bytes
2295            .checked_add(copied)
2296            .context("software TPM state size overflow")?;
2297        if total_bytes > crate::backup::MAX_TPM_STATE_BYTES {
2298            bail!("software TPM state exceeds the managed file or size limit");
2299        }
2300    }
2301    sync_directory(destination)
2302}
2303
2304fn copy_tpm_state_file_new(source: &Path, destination: &Path, limit: u64) -> Result<u64> {
2305    let mut source_file = OpenOptions::new()
2306        .read(true)
2307        .custom_flags(libc::O_NOFOLLOW)
2308        .open(source)
2309        .with_context(|| format!("failed to open TPM state source {}", source.display()))?;
2310    let source_metadata = source_file.metadata()?;
2311    if !source_metadata.is_file() || source_metadata.len() > limit {
2312        bail!(
2313            "TPM state source {} exceeds the managed size limit",
2314            source.display()
2315        );
2316    }
2317    let mut destination_file = OpenOptions::new()
2318        .write(true)
2319        .create_new(true)
2320        .mode(0o600)
2321        .custom_flags(libc::O_NOFOLLOW)
2322        .open(destination)
2323        .with_context(|| format!("failed to create TPM state file {}", destination.display()))?;
2324    let result = (|| -> Result<u64> {
2325        let mut copied = 0_u64;
2326        let mut buffer = vec![0_u8; 128 * 1024];
2327        loop {
2328            let read = source_file.read(&mut buffer)?;
2329            if read == 0 {
2330                break;
2331            }
2332            copied = copied
2333                .checked_add(u64::try_from(read)?)
2334                .context("TPM state copy size overflow")?;
2335            if copied > limit {
2336                bail!(
2337                    "TPM state source {} exceeds the managed size limit",
2338                    source.display()
2339                );
2340            }
2341            destination_file.write_all(&buffer[..read])?;
2342        }
2343        if copied != source_metadata.len() || source_file.metadata()?.len() != copied {
2344            bail!(
2345                "TPM state source {} changed while being copied",
2346                source.display()
2347            );
2348        }
2349        destination_file.sync_all()?;
2350        secure_regular_file(destination)?;
2351        Ok(copied)
2352    })();
2353    if result.is_err() {
2354        let _ = fs::remove_file(destination);
2355    }
2356    result
2357}
2358
2359fn launch_swtpm(command: &CommandSpec) -> Result<()> {
2360    let mut child = Command::new(&command.program)
2361        .args(&command.args)
2362        .stdin(Stdio::null())
2363        .stdout(Stdio::null())
2364        .stderr(Stdio::null())
2365        .spawn()
2366        .with_context(|| format!("failed to launch {}", command.program.display()))?;
2367    let deadline = Instant::now() + Duration::from_secs(3);
2368    loop {
2369        if let Some(status) = child.try_wait()? {
2370            if !status.success() {
2371                bail!("swtpm failed to start with {status}");
2372            }
2373            return Ok(());
2374        }
2375        if Instant::now() >= deadline {
2376            let _ = child.kill();
2377            let _ = child.wait();
2378            bail!("swtpm daemonization command timed out");
2379        }
2380        thread::sleep(Duration::from_millis(25));
2381    }
2382}
2383
2384fn wait_for_swtpm(files: &RuntimeFiles, timeout: Duration) -> Result<u32> {
2385    let deadline = Instant::now()
2386        .checked_add(timeout)
2387        .context("software TPM startup timeout is too large")?;
2388    loop {
2389        let pid = match fs::symlink_metadata(&files.swtpm_pid_file) {
2390            Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => {
2391                Some(read_process_pid(&files.swtpm_pid_file, "swtpm")?)
2392            }
2393            Ok(_) => bail!("swtpm PID path is not a regular file"),
2394            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
2395            Err(error) => return Err(error.into()),
2396        };
2397        if let Some(pid) = pid {
2398            if !process_exists(pid) {
2399                bail!("swtpm exited before creating its sockets");
2400            }
2401            let server_ready = is_unix_socket(&files.tpm_socket)?;
2402            let control_ready = is_unix_socket(&files.tpm_control_socket)?;
2403            if server_ready && control_ready {
2404                return Ok(pid);
2405            }
2406        }
2407        if Instant::now() >= deadline {
2408            bail!("timed out waiting for swtpm PID and Unix sockets");
2409        }
2410        thread::sleep(Duration::from_millis(25));
2411    }
2412}
2413
2414fn is_unix_socket(path: &Path) -> Result<bool> {
2415    match fs::symlink_metadata(path) {
2416        Ok(metadata) if metadata.file_type().is_socket() => Ok(true),
2417        Ok(_) => bail!("{} is not a Unix socket", path.display()),
2418        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
2419        Err(error) => Err(error.into()),
2420    }
2421}
2422
2423fn stop_swtpm_files(files: &RuntimeFiles, ioctl_override: Option<&Path>) -> Result<()> {
2424    let pid_metadata = match fs::symlink_metadata(&files.swtpm_pid_file) {
2425        Ok(metadata) if metadata.is_file() && !metadata.file_type().is_symlink() => Some(metadata),
2426        Ok(_) => bail!("swtpm PID file is not a regular file"),
2427        Err(error) if error.kind() == io::ErrorKind::NotFound => None,
2428        Err(error) => return Err(error.into()),
2429    };
2430    let pid = pid_metadata
2431        .as_ref()
2432        .map(|_| read_process_pid(&files.swtpm_pid_file, "swtpm"))
2433        .transpose()?;
2434    let pid_live = pid.is_some_and(process_exists);
2435    let control_exists = fs::symlink_metadata(&files.tpm_control_socket).is_ok();
2436    let command_exists = fs::symlink_metadata(&files.tpm_socket).is_ok();
2437
2438    if pid_live {
2439        if !is_unix_socket(&files.tpm_control_socket)? {
2440            bail!("live swtpm PID has no usable control socket; preserving runtime files");
2441        }
2442        let ioctl = ioctl_override
2443            .map(Path::to_path_buf)
2444            .or_else(find_swtpm_ioctl)
2445            .context("swtpm_ioctl is required to stop a live software TPM")?;
2446        run_swtpm_ioctl_stop(&ioctl, &files.tpm_control_socket)?;
2447        wait_for_process_exit(pid.unwrap_or_default(), Duration::from_secs(3), "swtpm")?;
2448    } else {
2449        let control_live = probe_unix_socket(&files.tpm_control_socket)?;
2450        let command_live = probe_unix_socket(&files.tpm_socket)?;
2451        if control_live {
2452            let ioctl = ioctl_override
2453                .map(Path::to_path_buf)
2454                .or_else(find_swtpm_ioctl)
2455                .context("swtpm_ioctl is required to stop an untracked software TPM")?;
2456            run_swtpm_ioctl_stop(&ioctl, &files.tpm_control_socket)?;
2457            wait_for_unix_socket_closed(&files.tpm_control_socket, Duration::from_secs(3))?;
2458        } else if command_live {
2459            bail!("software TPM command socket is live without recoverable control state");
2460        }
2461    }
2462
2463    if pid.is_some_and(process_exists)
2464        || probe_unix_socket(&files.tpm_control_socket)?
2465        || probe_unix_socket(&files.tpm_socket)?
2466    {
2467        bail!("software TPM is still live; preserving its runtime files");
2468    }
2469    if control_exists || command_exists || pid_metadata.is_some() {
2470        remove_swtpm_runtime_file(&files.swtpm_pid_file, false)?;
2471        remove_swtpm_runtime_file(&files.tpm_control_socket, true)?;
2472        remove_swtpm_runtime_file(&files.tpm_socket, true)?;
2473    }
2474    Ok(())
2475}
2476
2477fn remove_swtpm_runtime_file(path: &Path, socket: bool) -> Result<()> {
2478    match fs::symlink_metadata(path) {
2479        Ok(metadata)
2480            if if socket {
2481                metadata.file_type().is_socket()
2482            } else {
2483                metadata.is_file() && !metadata.file_type().is_symlink()
2484            } =>
2485        {
2486            fs::remove_file(path)?;
2487            Ok(())
2488        }
2489        Ok(_) => bail!(
2490            "refusing to remove unexpected swtpm runtime entry {}",
2491            path.display()
2492        ),
2493        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
2494        Err(error) => Err(error.into()),
2495    }
2496}
2497
2498fn probe_unix_socket(path: &Path) -> Result<bool> {
2499    if !is_unix_socket(path)? {
2500        return Ok(false);
2501    }
2502    match UnixStream::connect(path) {
2503        Ok(_) => Ok(true),
2504        Err(error)
2505            if matches!(
2506                error.kind(),
2507                io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound
2508            ) =>
2509        {
2510            Ok(false)
2511        }
2512        Err(error) if error.kind() == io::ErrorKind::PermissionDenied => Ok(true),
2513        Err(error) => Err(error.into()),
2514    }
2515}
2516
2517fn wait_for_unix_socket_closed(path: &Path, timeout: Duration) -> Result<()> {
2518    let deadline = Instant::now()
2519        .checked_add(timeout)
2520        .context("software TPM shutdown timeout is too large")?;
2521    while probe_unix_socket(path)? {
2522        if Instant::now() >= deadline {
2523            bail!("software TPM control socket remained live after stop request");
2524        }
2525        thread::sleep(Duration::from_millis(25));
2526    }
2527    Ok(())
2528}
2529
2530fn run_swtpm_ioctl_stop(ioctl: &Path, control_socket: &Path) -> Result<()> {
2531    let mut child = Command::new(ioctl)
2532        .arg("--unix")
2533        .arg(control_socket)
2534        .arg("--stop")
2535        .stdin(Stdio::null())
2536        .stdout(Stdio::null())
2537        .stderr(Stdio::null())
2538        .spawn()
2539        .with_context(|| format!("failed to execute swtpm_ioctl {}", ioctl.display()))?;
2540    let deadline = Instant::now() + Duration::from_secs(3);
2541    loop {
2542        if let Some(status) = child.try_wait()? {
2543            if !status.success() {
2544                bail!("swtpm_ioctl failed to stop the software TPM");
2545            }
2546            return Ok(());
2547        }
2548        if Instant::now() >= deadline {
2549            let _ = child.kill();
2550            let _ = child.wait();
2551            bail!("swtpm_ioctl timed out while stopping the software TPM");
2552        }
2553        thread::sleep(Duration::from_millis(25));
2554    }
2555}
2556
2557fn wait_for_process_exit(pid: u32, timeout: Duration, label: &str) -> Result<()> {
2558    let deadline = Instant::now()
2559        .checked_add(timeout)
2560        .with_context(|| format!("{label} exit timeout is too large"))?;
2561    while process_exists(pid) {
2562        if Instant::now() >= deadline {
2563            bail!("{label} process {pid} did not exit");
2564        }
2565        thread::sleep(Duration::from_millis(25));
2566    }
2567    Ok(())
2568}
2569
2570fn read_process_pid(path: &Path, label: &str) -> Result<u32> {
2571    let mut source = String::new();
2572    File::open(path)
2573        .with_context(|| format!("{label} did not create PID file {}", path.display()))?
2574        .read_to_string(&mut source)?;
2575    source
2576        .trim()
2577        .parse::<u32>()
2578        .with_context(|| format!("invalid {label} PID in {}", path.display()))
2579}
2580
2581fn find_swtpm_ioctl() -> Option<PathBuf> {
2582    std::env::var_os("PATH")
2583        .map(|path| std::env::split_paths(&path).collect::<Vec<_>>())?
2584        .into_iter()
2585        .map(|directory| directory.join("swtpm_ioctl"))
2586        .find(|candidate| candidate.is_file())
2587}
2588
2589fn require_restore_marker_clear(directory: &PinnedDir, marker: &Path) -> Result<()> {
2590    match directory.entry_type(".restore-in-progress")? {
2591        Some(FileType::RegularFile) => bail!(
2592            "an earlier restore left {}; all destination files are preserved for manual inspection",
2593            marker.display()
2594        ),
2595        Some(_) => bail!("restore marker {} is not a regular file", marker.display()),
2596        None => Ok(()),
2597    }
2598}
2599
2600fn copy_regular_file_new(source: &Path, destination: &Path) -> Result<()> {
2601    let mut source_file = OpenOptions::new()
2602        .read(true)
2603        .custom_flags(libc::O_NOFOLLOW)
2604        .open(source)
2605        .with_context(|| format!("failed to open clone source {}", source.display()))?;
2606    let metadata = source_file.metadata()?;
2607    if !metadata.is_file() {
2608        bail!("clone source {} is not a regular file", source.display());
2609    }
2610    let mut destination_file = OpenOptions::new()
2611        .write(true)
2612        .create_new(true)
2613        .open(destination)
2614        .with_context(|| format!("failed to create clone target {}", destination.display()))?;
2615    let result = (|| -> Result<()> {
2616        io::copy(&mut source_file, &mut destination_file)?;
2617        destination_file.sync_all()?;
2618        Ok(())
2619    })();
2620    if result.is_err() {
2621        let _ = fs::remove_file(destination);
2622    }
2623    result.with_context(|| {
2624        format!(
2625            "failed to copy {} to {}",
2626            source.display(),
2627            destination.display()
2628        )
2629    })?;
2630    secure_regular_file(destination)
2631}
2632
2633fn publish_screenshot(source: &Path, destination: &Path) -> Result<u64> {
2634    let mut source_file = OpenOptions::new()
2635        .read(true)
2636        .custom_flags(libc::O_NOFOLLOW)
2637        .open(source)
2638        .with_context(|| {
2639            format!(
2640                "failed to open screenshot staging file {}",
2641                source.display()
2642            )
2643        })?;
2644    let metadata = source_file.metadata()?;
2645    if !metadata.is_file() {
2646        bail!(
2647            "screenshot staging path {} is not a regular file",
2648            source.display()
2649        );
2650    }
2651    if !(3..=MAX_SCREENSHOT_BYTES).contains(&metadata.len()) {
2652        bail!("screenshot exceeded the {MAX_SCREENSHOT_BYTES}-byte limit");
2653    }
2654    let mut source_reader = BufReader::new(&mut source_file);
2655    let header = read_binary_ppm_header(&mut source_reader)?;
2656    let expected_len = u64::try_from(header.bytes.len())?
2657        .checked_add(header.raster_bytes)
2658        .context("PPM screenshot size overflow")?;
2659    if expected_len != metadata.len() {
2660        bail!("PPM dimensions do not match the screenshot raster length");
2661    }
2662    let mut destination_file = OpenOptions::new()
2663        .write(true)
2664        .create_new(true)
2665        .mode(0o600)
2666        .open(destination)
2667        .with_context(|| format!("failed to create screenshot {}", destination.display()))?;
2668    let result = (|| -> Result<()> {
2669        destination_file.write_all(&header.bytes)?;
2670        let copied = copy_validated_ppm_raster(
2671            &mut source_reader,
2672            &mut destination_file,
2673            header.raster_bytes,
2674            header.max_value,
2675        )?;
2676        if copied
2677            .checked_add(u64::try_from(header.bytes.len())?)
2678            .context("screenshot size overflow")?
2679            != metadata.len()
2680        {
2681            bail!("screenshot staging file changed while it was being published");
2682        }
2683        let mut trailing = [0_u8; 1];
2684        if source_reader.read(&mut trailing)? != 0 {
2685            bail!("screenshot staging file changed while it was being published");
2686        }
2687        destination_file.sync_all()?;
2688        secure_regular_file(destination)
2689    })();
2690    if result.is_err() {
2691        let _ = fs::remove_file(destination);
2692    }
2693    result?;
2694    Ok(metadata.len())
2695}
2696
2697struct BinaryPpmHeader {
2698    bytes: Vec<u8>,
2699    raster_bytes: u64,
2700    max_value: u64,
2701}
2702
2703fn read_binary_ppm_header(reader: &mut impl BufRead) -> Result<BinaryPpmHeader> {
2704    if peek_ppm_byte(reader)? != b'P' {
2705        bail!("QEMU screenshot did not contain binary PPM data");
2706    }
2707    let mut bytes = Vec::with_capacity(32);
2708    let magic = read_ppm_token(reader, &mut bytes)?;
2709    if magic != b"P6" {
2710        bail!("QEMU screenshot did not contain binary PPM data");
2711    }
2712    let width = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "width")?;
2713    let height = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "height")?;
2714    let max_value = parse_ppm_number(&read_ppm_token(reader, &mut bytes)?, "maxval")?;
2715    if width == 0 || height == 0 {
2716        bail!("PPM dimensions must be positive");
2717    }
2718    if !(1..=65_535).contains(&max_value) {
2719        bail!("PPM maxval must be between 1 and 65535");
2720    }
2721    let raster_bytes = width
2722        .checked_mul(height)
2723        .and_then(|pixels| pixels.checked_mul(3))
2724        .and_then(|samples| samples.checked_mul(if max_value < 256 { 1 } else { 2 }))
2725        .context("PPM raster size overflow")?;
2726    Ok(BinaryPpmHeader {
2727        bytes,
2728        raster_bytes,
2729        max_value,
2730    })
2731}
2732
2733fn read_ppm_token(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<Vec<u8>> {
2734    loop {
2735        match peek_ppm_byte(reader)? {
2736            byte if byte.is_ascii_whitespace() => {
2737                consume_ppm_byte(reader, header)?;
2738            }
2739            b'#' => consume_ppm_comment(reader, header)?,
2740            _ => break,
2741        }
2742    }
2743
2744    let mut token = Vec::with_capacity(8);
2745    loop {
2746        match peek_ppm_byte(reader)? {
2747            byte if byte.is_ascii_whitespace() => {
2748                let separator = consume_ppm_byte(reader, header)?;
2749                if separator == b'\r' && peek_ppm_byte(reader).ok() == Some(b'\n') {
2750                    consume_ppm_byte(reader, header)?;
2751                }
2752                break;
2753            }
2754            b'#' => {
2755                consume_ppm_comment(reader, header)?;
2756                break;
2757            }
2758            _ => {
2759                if token.len() == MAX_PPM_TOKEN_BYTES {
2760                    bail!("PPM header token exceeds {MAX_PPM_TOKEN_BYTES} bytes");
2761                }
2762                token.push(consume_ppm_byte(reader, header)?);
2763            }
2764        }
2765    }
2766    if token.is_empty() {
2767        bail!("PPM header contains an empty token");
2768    }
2769    Ok(token)
2770}
2771
2772fn peek_ppm_byte(reader: &mut impl BufRead) -> Result<u8> {
2773    reader
2774        .fill_buf()
2775        .context("failed to read PPM header")?
2776        .first()
2777        .copied()
2778        .context("truncated PPM header")
2779}
2780
2781fn consume_ppm_byte(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<u8> {
2782    if header.len() == MAX_PPM_HEADER_BYTES {
2783        bail!("PPM header exceeds {MAX_PPM_HEADER_BYTES} bytes");
2784    }
2785    let byte = peek_ppm_byte(reader)?;
2786    reader.consume(1);
2787    header.push(byte);
2788    Ok(byte)
2789}
2790
2791fn consume_ppm_comment(reader: &mut impl BufRead, header: &mut Vec<u8>) -> Result<()> {
2792    if consume_ppm_byte(reader, header)? != b'#' {
2793        bail!("invalid PPM comment");
2794    }
2795    loop {
2796        match consume_ppm_byte(reader, header)? {
2797            b'\n' => return Ok(()),
2798            b'\r' => {
2799                if peek_ppm_byte(reader).ok() == Some(b'\n') {
2800                    consume_ppm_byte(reader, header)?;
2801                }
2802                return Ok(());
2803            }
2804            _ => {}
2805        }
2806    }
2807}
2808
2809fn parse_ppm_number(token: &[u8], label: &str) -> Result<u64> {
2810    if token.is_empty() || !token.iter().all(u8::is_ascii_digit) {
2811        bail!("PPM {label} is not a decimal integer");
2812    }
2813    token.iter().try_fold(0_u64, |value, byte| {
2814        value
2815            .checked_mul(10)
2816            .and_then(|value| value.checked_add(u64::from(*byte - b'0')))
2817            .context("PPM integer overflow")
2818    })
2819}
2820
2821fn copy_validated_ppm_raster(
2822    reader: &mut impl Read,
2823    writer: &mut impl Write,
2824    raster_bytes: u64,
2825    max_value: u64,
2826) -> Result<u64> {
2827    let bytes_per_sample = if max_value < 256 { 1 } else { 2 };
2828    let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice();
2829    let mut remaining = raster_bytes;
2830    while remaining > 0 {
2831        let mut chunk_len = usize::try_from(remaining.min(buffer.len() as u64))?;
2832        chunk_len -= chunk_len % bytes_per_sample;
2833        reader
2834            .read_exact(&mut buffer[..chunk_len])
2835            .context("PPM raster is truncated")?;
2836        for sample in buffer[..chunk_len].chunks_exact(bytes_per_sample) {
2837            let value = if bytes_per_sample == 1 {
2838                u64::from(sample[0])
2839            } else {
2840                u64::from(u16::from_be_bytes([sample[0], sample[1]]))
2841            };
2842            if value > max_value {
2843                bail!("PPM raster sample exceeds maxval");
2844            }
2845        }
2846        writer.write_all(&buffer[..chunk_len])?;
2847        remaining -= chunk_len as u64;
2848    }
2849    Ok(raster_bytes)
2850}
2851
2852fn write_new_file(path: &Path, contents: &[u8]) -> Result<()> {
2853    let mut file = OpenOptions::new()
2854        .write(true)
2855        .create_new(true)
2856        .open(path)
2857        .with_context(|| format!("failed to create {}", path.display()))?;
2858    let result = file
2859        .write_all(contents)
2860        .and_then(|()| file.sync_all())
2861        .map_err(anyhow::Error::from)
2862        .and_then(|()| secure_regular_file(path));
2863    if result.is_err() {
2864        let _ = fs::remove_file(path);
2865    }
2866    result
2867}
2868
2869fn secure_regular_file(path: &Path) -> Result<()> {
2870    let metadata = fs::symlink_metadata(path)?;
2871    if !metadata.is_file() {
2872        bail!("{} is not a regular file", path.display());
2873    }
2874    fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
2875    Ok(())
2876}
2877
2878struct PinnedDir {
2879    fd: OwnedFd,
2880}
2881
2882impl PinnedDir {
2883    fn open(path: &Path) -> Result<Self> {
2884        let fd = rustix::fs::open(
2885            path,
2886            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
2887            Mode::empty(),
2888        )
2889        .with_context(|| format!("failed to pin directory {}", path.display()))?;
2890        Ok(Self { fd })
2891    }
2892
2893    fn open_child(&self, name: &str) -> Result<Option<Self>> {
2894        match rustix::fs::openat(
2895            &self.fd,
2896            name,
2897            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
2898            Mode::empty(),
2899        ) {
2900            Ok(fd) => Ok(Some(Self { fd })),
2901            Err(rustix::io::Errno::NOENT) => Ok(None),
2902            Err(error) => Err(error.into()),
2903        }
2904    }
2905
2906    fn remove_regular(&self, name: &str) -> Result<bool> {
2907        if self.entry_type(name)? != Some(FileType::RegularFile) {
2908            return Ok(false);
2909        }
2910        rustix::fs::unlinkat(&self.fd, name, AtFlags::empty())?;
2911        Ok(true)
2912    }
2913
2914    fn remove_child_regular_tree(&self, name: &str) -> Result<bool> {
2915        let Some(child) = self.open_child(name)? else {
2916            return Ok(false);
2917        };
2918        let fd_path = PathBuf::from(format!("/proc/self/fd/{}", child.fd.as_raw_fd()));
2919        for entry in fs::read_dir(fd_path)? {
2920            let entry = entry?;
2921            let name = entry
2922                .file_name()
2923                .into_string()
2924                .map_err(|_| anyhow::anyhow!("managed state contains a non-UTF-8 filename"))?;
2925            validate_tpm_state_name(&name)?;
2926            if child.entry_type(&name)? != Some(FileType::RegularFile) {
2927                bail!("managed TPM state entry {name} is not a regular file");
2928            }
2929            child.remove_regular(&name)?;
2930        }
2931        child.sync()?;
2932        self.remove_child_dir_if_matches(name, &child);
2933        if self.entry_type(name)?.is_some() {
2934            bail!("managed TPM state directory {name} could not be removed");
2935        }
2936        Ok(true)
2937    }
2938
2939    fn entry_type(&self, name: &str) -> Result<Option<FileType>> {
2940        match rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW) {
2941            Ok(stat) => Ok(Some(FileType::from_raw_mode(stat.st_mode))),
2942            Err(rustix::io::Errno::NOENT) => Ok(None),
2943            Err(error) => Err(error.into()),
2944        }
2945    }
2946
2947    fn copy_regular_from(&self, source: &Path, name: &str) -> Result<()> {
2948        let mut source_file = OpenOptions::new()
2949            .read(true)
2950            .custom_flags(libc::O_NOFOLLOW)
2951            .open(source)
2952            .with_context(|| format!("failed to open backup source {}", source.display()))?;
2953        if !source_file.metadata()?.is_file() {
2954            bail!("backup source {} is not a regular file", source.display());
2955        }
2956        let fd = rustix::fs::openat(
2957            &self.fd,
2958            name,
2959            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
2960            Mode::RUSR | Mode::WUSR,
2961        )?;
2962        let mut destination = File::from(fd);
2963        let result =
2964            io::copy(&mut source_file, &mut destination).and_then(|_| destination.sync_all());
2965        if result.is_err() {
2966            let _ = rustix::fs::unlinkat(&self.fd, name, AtFlags::empty());
2967        }
2968        result.map_err(Into::into)
2969    }
2970
2971    fn sync(&self) -> Result<()> {
2972        rustix::fs::fsync(&self.fd)?;
2973        Ok(())
2974    }
2975
2976    fn remove_child_dir_if_matches(&self, name: &str, child: &Self) {
2977        let Ok(pinned) = rustix::fs::fstat(&child.fd) else {
2978            return;
2979        };
2980        let Ok(current) = rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW) else {
2981            return;
2982        };
2983        if FileType::from_raw_mode(current.st_mode) == FileType::Directory
2984            && current.st_dev == pinned.st_dev
2985            && current.st_ino == pinned.st_ino
2986        {
2987            let _ = rustix::fs::unlinkat(&self.fd, name, AtFlags::REMOVEDIR);
2988            let _ = self.sync();
2989        }
2990    }
2991}
2992
2993fn cleanup_backup_directory(path: &Path) {
2994    let Ok(directory) = PinnedDir::open(path) else {
2995        return;
2996    };
2997    cleanup_pinned_backup_directory(&directory);
2998    drop(directory);
2999    let _ = fs::remove_dir(path);
3000}
3001
3002fn cleanup_pinned_backup_directory(directory: &PinnedDir) {
3003    for name in [
3004        crate::backup::MANIFEST_FILE,
3005        BACKUP_CONFIG_FILE,
3006        BACKUP_DISK_FILE,
3007        BACKUP_UEFI_VARS_FILE,
3008    ] {
3009        let _ = directory.remove_regular(name);
3010    }
3011    let _ = directory.remove_child_regular_tree(BACKUP_TPM_STATE_DIR);
3012    let _ = directory.sync();
3013}
3014
3015fn copy_tpm_state_to_pinned(
3016    parent: &PinnedDir,
3017    source: &Path,
3018    files: &std::collections::BTreeMap<String, crate::backup::FileDigest>,
3019) -> Result<()> {
3020    rustix::fs::mkdirat(&parent.fd, BACKUP_TPM_STATE_DIR, Mode::RWXU)?;
3021    let child = parent
3022        .open_child(BACKUP_TPM_STATE_DIR)?
3023        .context("new backup TPM state directory disappeared")?;
3024    for name in files.keys() {
3025        validate_tpm_state_name(name)?;
3026        child.copy_regular_from(&source.join(name), name)?;
3027    }
3028    child.sync()
3029}
3030
3031fn validate_standalone_qcow2(host: &HostCapabilities, path: &Path) -> Result<()> {
3032    let info = Command::new(&host.qemu_img)
3033        .arg("info")
3034        .arg("--output=json")
3035        .arg(path)
3036        .output()
3037        .context("failed to execute qemu-img info for backup")?;
3038    if !info.status.success() {
3039        bail!(
3040            "backup image inspection failed: {}",
3041            String::from_utf8_lossy(&info.stderr).trim()
3042        );
3043    }
3044    let info: serde_json::Value =
3045        serde_json::from_slice(&info.stdout).context("qemu-img info returned invalid JSON")?;
3046    if info.get("format").and_then(serde_json::Value::as_str) != Some("qcow2") {
3047        bail!("backup system disk is not qcow2");
3048    }
3049    for field in ["backing-filename", "full-backing-filename", "data-file"] {
3050        if info.get(field).is_some_and(|value| !value.is_null()) {
3051            bail!("backup system disk uses unsupported external {field}");
3052        }
3053    }
3054    let check = Command::new(&host.qemu_img)
3055        .arg("check")
3056        .args(["-f", "qcow2"])
3057        .arg(path)
3058        .output()
3059        .context("failed to execute qemu-img check for backup")?;
3060    if !check.status.success() {
3061        bail!(
3062            "backup qcow2 validation failed: {}",
3063            String::from_utf8_lossy(&check.stderr).trim()
3064        );
3065    }
3066    Ok(())
3067}
3068
3069fn publish_file_noreplace(source: &Path, destination: &Path) -> Result<()> {
3070    rustix::fs::renameat_with(
3071        rustix::fs::CWD,
3072        source,
3073        rustix::fs::CWD,
3074        destination,
3075        RenameFlags::NOREPLACE,
3076    )
3077    .with_context(|| {
3078        format!(
3079            "failed to publish {} without replacing a destination",
3080            source.display()
3081        )
3082    })?;
3083    Ok(())
3084}
3085
3086fn run_qemu_img_snapshot(
3087    host: &HostCapabilities,
3088    arguments: &[&str],
3089    disk: &Path,
3090) -> Result<String> {
3091    let output = Command::new(&host.qemu_img)
3092        .arg("snapshot")
3093        .args(arguments)
3094        .arg(disk)
3095        .output()
3096        .context("failed to execute qemu-img snapshot")?;
3097    if !output.status.success() {
3098        bail!(
3099            "qemu-img snapshot failed: {}",
3100            String::from_utf8_lossy(&output.stderr).trim()
3101        );
3102    }
3103    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
3104}
3105
3106fn sync_directory(path: &Path) -> Result<()> {
3107    File::open(path)?.sync_all()?;
3108    Ok(())
3109}
3110
3111fn validate_snapshot_name(name: &str) -> Result<()> {
3112    if name.is_empty()
3113        || name.len() > 64
3114        || !name.chars().all(|character| {
3115            character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_')
3116        })
3117    {
3118        bail!("snapshot name must contain 1-64 ASCII letters, digits, '.', '-', or '_' characters");
3119    }
3120    Ok(())
3121}
3122
3123fn validate_growth_amount(amount: &str) -> Result<String> {
3124    let amount = amount.trim().to_ascii_uppercase();
3125    let Some((digits, suffix)) = amount.split_at_checked(amount.len().saturating_sub(1)) else {
3126        bail!("disk growth must look like 20G, 1024M, or 1T");
3127    };
3128    if digits.is_empty()
3129        || digits.starts_with('0')
3130        || !digits.bytes().all(|byte| byte.is_ascii_digit())
3131        || !matches!(suffix, "K" | "M" | "G" | "T" | "P")
3132    {
3133        bail!("disk growth must be a positive size like 20G, 1024M, or 1T");
3134    }
3135    Ok(amount)
3136}
3137
3138fn is_kvm_initialization_failure(stderr: &[u8]) -> bool {
3139    let stderr = String::from_utf8_lossy(stderr).to_ascii_lowercase();
3140    [
3141        "failed to initialize kvm",
3142        "could not access kvm kernel module",
3143        "kvm acceleration not available",
3144        "kvm is not supported",
3145    ]
3146    .iter()
3147    .any(|message| stderr.contains(message))
3148}
3149
3150fn launch_qemu(command: &CommandSpec, launch_marker: &Path) -> Result<Output> {
3151    let mut process = Command::new(&command.program);
3152    process
3153        .args(&command.args)
3154        .stdin(Stdio::null())
3155        .stdout(Stdio::piped())
3156        .stderr(Stdio::piped());
3157    match process.spawn() {
3158        Ok(child) => child.wait_with_output().with_context(|| {
3159            format!(
3160                "failed to collect output from {}",
3161                command.program.display()
3162            )
3163        }),
3164        Err(error) => {
3165            remove_if_exists(launch_marker).with_context(|| {
3166                format!(
3167                    "failed to clean launch marker after failing to launch {}",
3168                    command.program.display()
3169                )
3170            })?;
3171            Err(error).with_context(|| format!("failed to launch {}", command.program.display()))
3172        }
3173    }
3174}
3175
3176fn create_launch_marker(path: &Path, pid: u32) -> Result<()> {
3177    create_launch_marker_with(path, |marker| {
3178        writeln!(marker, "{pid}")?;
3179        marker.sync_all()
3180    })
3181}
3182
3183fn create_launch_marker_with(
3184    path: &Path,
3185    write_marker: impl FnOnce(&mut File) -> io::Result<()>,
3186) -> Result<()> {
3187    let mut marker = OpenOptions::new()
3188        .write(true)
3189        .create_new(true)
3190        .open(path)
3191        .with_context(|| format!("failed to create launch marker {}", path.display()))?;
3192    if let Err(error) = write_marker(&mut marker) {
3193        drop(marker);
3194        remove_if_exists(path).with_context(|| {
3195            format!(
3196                "failed to remove incomplete launch marker {}",
3197                path.display()
3198            )
3199        })?;
3200        return Err(error)
3201            .with_context(|| format!("failed to write launch marker {}", path.display()));
3202    }
3203    Ok(())
3204}
3205
3206fn validate_balloon_target(memory_mib: u64, configured_mib: u64) -> Result<u64> {
3207    if !(256..=configured_mib).contains(&memory_mib) {
3208        bail!("balloon target must be between 256 and {configured_mib} MiB");
3209    }
3210    memory_mib
3211        .checked_mul(1024 * 1024)
3212        .context("balloon target byte count overflowed")
3213}
3214
3215#[cfg(test)]
3216mod tests {
3217    use super::{
3218        BACKUP_CONFIG_FILE, BACKUP_DISK_FILE, BACKUP_UEFI_VARS_FILE, CreateOptions,
3219        SNAPSHOT_REVERT_MARKER, SnapshotOperation, VmManager, VmStatus, cleanup_backup_directory,
3220        copy_tpm_state_directory, create_launch_marker_with, deadline_after_shutdown_request,
3221        ensure_snapshot_tpm_compatible, is_kvm_initialization_failure, launch_qemu, launch_swtpm,
3222        publish_file_noreplace, publish_screenshot, read_process_pid, require_restore_marker_clear,
3223        run_swtpm_ioctl_stop, stop_swtpm_files, validate_balloon_target, validate_growth_amount,
3224        validate_snapshot_name, validate_tpm_state_directory, wait_for_exit, wait_for_process_exit,
3225        wait_for_swtpm,
3226    };
3227    use crate::backup::BackupManifest;
3228    use crate::config::{Firmware, PointerDevice, UsbHostDevice, VmConfig};
3229    use crate::paths::AppPaths;
3230    use crate::qemu::{CommandSpec, HostCapabilities};
3231    use crate::state::VmState;
3232    use serde_json::{Value, json};
3233    use std::fs;
3234    use std::io::{self, BufRead, BufReader, Write};
3235    use std::os::unix::fs::{PermissionsExt, symlink};
3236    use std::os::unix::net::UnixListener;
3237    use std::path::{Path, PathBuf};
3238    use std::process::Command;
3239    use std::thread;
3240    use std::time::{Duration, Instant};
3241    use tempfile::tempdir;
3242
3243    fn snapshot_fixture(software_tpm2: bool) -> (tempfile::TempDir, VmManager, VmConfig, PathBuf) {
3244        let root = tempdir().unwrap();
3245        let manager = VmManager::new(AppPaths::new(
3246            root.path().join("config"),
3247            root.path().join("data"),
3248            root.path().join("runtime"),
3249        ))
3250        .unwrap();
3251        let data = manager.paths().data("test").unwrap();
3252        fs::create_dir_all(&data).unwrap();
3253        let disk = data.join("system.qcow2");
3254        fs::write(&disk, b"snapshot fixture disk").unwrap();
3255        let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
3256        config.software_tpm2 = software_tpm2;
3257        fs::write(
3258            manager.paths().config("test").unwrap(),
3259            config.to_toml().unwrap(),
3260        )
3261        .unwrap();
3262        (root, manager, config, disk)
3263    }
3264
3265    fn snapshot_qemu_fixture(
3266        root: &Path,
3267        manager: &VmManager,
3268        disk: &Path,
3269        mode: &str,
3270    ) -> (HostCapabilities, PathBuf, PathBuf) {
3271        let qemu_img = root.join("qemu-img-fixture");
3272        let checkpoint = root.join("snapshot-checkpoint");
3273        let checkpoint_name = root.join("snapshot-checkpoint-name");
3274        let log = root.join("snapshot-log");
3275        let observed_config = root.join("config-observed-at-revert");
3276        let config = manager.paths().config("test").unwrap();
3277        let config_root = &manager.paths().config_root;
3278        let script = format!(
3279            "#!/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",
3280            disk = shell_quote(disk),
3281            checkpoint = shell_quote(&checkpoint),
3282            checkpoint_name = shell_quote(&checkpoint_name),
3283            log = shell_quote(&log),
3284            observed_config = shell_quote(&observed_config),
3285            config = shell_quote(&config),
3286            config_root = shell_quote(config_root),
3287        );
3288        fs::write(&qemu_img, script).unwrap();
3289        fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
3290        let host = HostCapabilities {
3291            qemu: PathBuf::from("/bin/false"),
3292            qemu_img,
3293            swtpm: None,
3294            swtpm_ioctl: None,
3295            kvm_available: false,
3296            uefi_code: None,
3297            uefi_secure_code: None,
3298            uefi_vars: None,
3299            uefi_secure_vars: None,
3300        };
3301        (host, log, observed_config)
3302    }
3303
3304    #[test]
3305    fn lists_only_toml_definitions() {
3306        let root = tempdir().unwrap();
3307        let paths = AppPaths::new(
3308            root.path().join("config"),
3309            root.path().join("data"),
3310            root.path().join("runtime"),
3311        );
3312        let manager = VmManager::new(paths).unwrap();
3313        fs::write(manager.paths().config_root.join("beta.toml"), "").unwrap();
3314        fs::write(manager.paths().config_root.join("alpha.toml"), "").unwrap();
3315        fs::write(manager.paths().config_root.join("ignore.txt"), "").unwrap();
3316        assert_eq!(manager.list().unwrap(), ["alpha", "beta"]);
3317    }
3318
3319    #[test]
3320    fn operation_lock_rejects_a_symlink_without_touching_its_target() {
3321        let root = tempdir().unwrap();
3322        let manager = VmManager::new(AppPaths::new(
3323            root.path().join("config"),
3324            root.path().join("data"),
3325            root.path().join("runtime"),
3326        ))
3327        .unwrap();
3328        let runtime = manager.paths().runtime("test").unwrap();
3329        fs::create_dir(&runtime).unwrap();
3330        let target = root.path().join("unrelated-lock-target");
3331        fs::write(&target, b"preserve this file").unwrap();
3332        let lock_path = runtime.join("operation.lock");
3333        symlink(&target, &lock_path).unwrap();
3334
3335        assert!(manager.lock("test").is_err());
3336        assert_eq!(fs::read(&target).unwrap(), b"preserve this file");
3337        assert!(
3338            fs::symlink_metadata(&lock_path)
3339                .unwrap()
3340                .file_type()
3341                .is_symlink()
3342        );
3343    }
3344
3345    #[test]
3346    fn operation_lock_is_created_owner_only() {
3347        let root = tempdir().unwrap();
3348        let manager = VmManager::new(AppPaths::new(
3349            root.path().join("config"),
3350            root.path().join("data"),
3351            root.path().join("runtime"),
3352        ))
3353        .unwrap();
3354
3355        let _lock = manager.lock("test").unwrap();
3356        let path = manager
3357            .paths()
3358            .runtime("test")
3359            .unwrap()
3360            .join("operation.lock");
3361        assert_eq!(
3362            fs::metadata(path).unwrap().permissions().mode() & 0o777,
3363            0o600
3364        );
3365    }
3366
3367    #[test]
3368    fn disk_ownership_rejects_hard_link_aliases() {
3369        let root = tempdir().unwrap();
3370        let manager = VmManager::new(AppPaths::new(
3371            root.path().join("config"),
3372            root.path().join("data"),
3373            root.path().join("runtime"),
3374        ))
3375        .unwrap();
3376        let first_disk = root.path().join("first.qcow2");
3377        let second_disk = root.path().join("second.qcow2");
3378        fs::write(&first_disk, b"one shared disk inode").unwrap();
3379        fs::hard_link(&first_disk, &second_disk).unwrap();
3380        for (name, disk) in [("first", first_disk), ("second", second_disk)] {
3381            let config = VmConfig::new(name.to_owned(), disk, None);
3382            fs::write(
3383                manager.paths().config(name).unwrap(),
3384                config.to_toml().unwrap(),
3385            )
3386            .unwrap();
3387        }
3388
3389        let config = manager.config("first").unwrap();
3390        let error = manager
3391            .ensure_unique_disk_owner("first", &config)
3392            .unwrap_err();
3393
3394        assert!(error.to_string().contains("same system disk"));
3395    }
3396
3397    #[test]
3398    fn disk_ownership_rejects_a_future_path_referenced_by_another_vm() {
3399        let root = tempdir().unwrap();
3400        let manager = VmManager::new(AppPaths::new(
3401            root.path().join("config"),
3402            root.path().join("data"),
3403            root.path().join("runtime"),
3404        ))
3405        .unwrap();
3406        let target_data = manager.paths().data("target").unwrap();
3407        fs::create_dir_all(&target_data).unwrap();
3408        let future_disk = target_data.join("system.qcow2");
3409        let other = VmConfig::new("other".to_owned(), future_disk.clone(), None);
3410        fs::write(
3411            manager.paths().config("other").unwrap(),
3412            other.to_toml().unwrap(),
3413        )
3414        .unwrap();
3415        let target = VmConfig::new("target".to_owned(), future_disk.clone(), None);
3416
3417        let error = manager
3418            .ensure_unique_disk_owner("target", &target)
3419            .unwrap_err();
3420
3421        assert!(error.to_string().contains("same system disk"));
3422        assert!(!future_disk.exists());
3423    }
3424
3425    #[test]
3426    fn disk_ownership_lock_is_private_and_exclusive_across_open_files() {
3427        let root = tempdir().unwrap();
3428        let manager = VmManager::new(AppPaths::new(
3429            root.path().join("config"),
3430            root.path().join("data"),
3431            root.path().join("runtime"),
3432        ))
3433        .unwrap();
3434        let held = manager.lock_disk_ownership().unwrap();
3435        let lock_path = manager.paths().runtime_root.join("disk-ownership.lock");
3436        assert_eq!(
3437            fs::metadata(&lock_path).unwrap().permissions().mode() & 0o777,
3438            0o600
3439        );
3440        let contender = std::fs::OpenOptions::new()
3441            .read(true)
3442            .write(true)
3443            .open(lock_path)
3444            .unwrap();
3445
3446        assert!(fs2::FileExt::try_lock_exclusive(&contender).is_err());
3447        drop(held);
3448        fs2::FileExt::try_lock_exclusive(&contender).unwrap();
3449        fs2::FileExt::unlock(&contender).unwrap();
3450    }
3451
3452    #[test]
3453    fn deletion_preserves_disk_when_invalid_definition_references_it() {
3454        let root = tempdir().unwrap();
3455        let manager = VmManager::new(AppPaths::new(
3456            root.path().join("config"),
3457            root.path().join("data"),
3458            root.path().join("runtime"),
3459        ))
3460        .unwrap();
3461        let target_data = manager.paths().data("target").unwrap();
3462        fs::create_dir_all(&target_data).unwrap();
3463        let shared_disk = target_data.join("system.qcow2");
3464        fs::write(&shared_disk, b"guest data that must survive").unwrap();
3465
3466        let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
3467        fs::write(
3468            manager.paths().config("target").unwrap(),
3469            target.to_toml().unwrap(),
3470        )
3471        .unwrap();
3472        // This definition still names the same disk, but its filename and
3473        // internal name disagree, so manager.config("other") rejects it.
3474        let mismatched = VmConfig::new("not-other".to_owned(), shared_disk.clone(), None);
3475        let other_definition = manager.paths().config("other").unwrap();
3476        fs::write(&other_definition, mismatched.to_toml().unwrap()).unwrap();
3477
3478        let result = manager.delete_vm("target");
3479
3480        let error = result.unwrap_err();
3481        assert!(error.to_string().contains("same system disk"));
3482        assert_eq!(
3483            fs::read(&shared_disk).unwrap(),
3484            b"guest data that must survive"
3485        );
3486        assert!(manager.paths().config("target").unwrap().is_file());
3487        assert!(other_definition.is_file());
3488    }
3489
3490    #[test]
3491    fn qemu_spawn_failure_removes_launch_marker() {
3492        let root = tempdir().unwrap();
3493        let manager = VmManager::new(AppPaths::new(
3494            root.path().join("config"),
3495            root.path().join("data"),
3496            root.path().join("runtime"),
3497        ))
3498        .unwrap();
3499        let runtime = manager.paths().runtime("test").unwrap();
3500        fs::create_dir_all(&runtime).unwrap();
3501        let program = root.path().join("not-executable");
3502        fs::write(&program, b"not an executable").unwrap();
3503        fs::set_permissions(&program, fs::Permissions::from_mode(0o600)).unwrap();
3504        let launch_marker = runtime.join("launching");
3505        fs::write(&launch_marker, "launching\n").unwrap();
3506        let command = CommandSpec {
3507            program,
3508            args: Vec::new(),
3509        };
3510
3511        let error = launch_qemu(&command, &launch_marker).unwrap_err();
3512
3513        assert!(format!("{error:#}").contains("failed to launch"));
3514        assert!(!launch_marker.exists());
3515        assert_eq!(manager.status("test").unwrap(), VmStatus::Stopped);
3516    }
3517
3518    #[test]
3519    fn launch_marker_writer_failure_removes_created_marker() {
3520        let root = tempdir().unwrap();
3521        let launch_marker = root.path().join("launching");
3522
3523        let error = create_launch_marker_with(&launch_marker, |marker| {
3524            marker.write_all(b"partial marker\n")?;
3525            Err(io::Error::other("injected marker sync failure"))
3526        })
3527        .unwrap_err();
3528
3529        assert!(format!("{error:#}").contains("failed to write launch marker"));
3530        assert!(!launch_marker.exists());
3531    }
3532
3533    #[test]
3534    fn launch_marker_create_new_preserves_preexisting_marker() {
3535        let root = tempdir().unwrap();
3536        let launch_marker = root.path().join("launching");
3537        let original = b"pre-existing launch marker\n";
3538        fs::write(&launch_marker, original).unwrap();
3539        let writer_called = std::cell::Cell::new(false);
3540
3541        let error = create_launch_marker_with(&launch_marker, |_| {
3542            writer_called.set(true);
3543            Ok(())
3544        })
3545        .unwrap_err();
3546
3547        assert!(error.to_string().contains("failed to create launch marker"));
3548        assert!(!writer_called.get());
3549        assert_eq!(fs::read(&launch_marker).unwrap(), original);
3550    }
3551
3552    #[test]
3553    fn stop_cleans_runtime_for_an_exited_unreaped_qemu_pid() {
3554        let root = tempdir().unwrap();
3555        let paths = AppPaths::new(
3556            root.path().join("config"),
3557            root.path().join("data"),
3558            root.path().join("runtime"),
3559        );
3560        let manager = VmManager::new(paths).unwrap();
3561        let runtime = manager.paths().runtime("test").unwrap();
3562        fs::create_dir_all(&runtime).unwrap();
3563        let mut child = Command::new("/bin/sh")
3564            .args(["-c", "exit 0"])
3565            .spawn()
3566            .unwrap();
3567        let pid = child.id();
3568        let state_path = runtime.join("state.json");
3569        VmState::new(
3570            "test".to_owned(),
3571            pid,
3572            runtime.join("qmp.sock"),
3573            runtime.join("display.sock"),
3574            None,
3575        )
3576        .save(&state_path)
3577        .unwrap();
3578
3579        let deadline = Instant::now() + Duration::from_secs(2);
3580        while crate::state::process_exists(pid) {
3581            assert!(Instant::now() < deadline, "child did not exit");
3582            thread::sleep(Duration::from_millis(5));
3583        }
3584        manager.stop("test", Duration::ZERO).unwrap();
3585        assert!(!state_path.exists());
3586        assert!(child.wait().unwrap().success());
3587    }
3588
3589    #[test]
3590    fn stop_cleans_runtime_if_process_exits_during_qmp_reopen() {
3591        let root = tempdir().unwrap();
3592        let paths = AppPaths::new(
3593            root.path().join("config"),
3594            root.path().join("data"),
3595            root.path().join("runtime"),
3596        );
3597        let manager = VmManager::new(paths).unwrap();
3598        let runtime = manager.paths().runtime("test").unwrap();
3599        fs::create_dir_all(&runtime).unwrap();
3600        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3601        let pid = child.id();
3602        let state_path = runtime.join("state.json");
3603        VmState::new(
3604            "test".to_owned(),
3605            pid,
3606            runtime.join("qmp.sock"),
3607            runtime.join("display.sock"),
3608            None,
3609        )
3610        .save(&state_path)
3611        .unwrap();
3612        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
3613        let server = thread::spawn(move || {
3614            let (mut stream, _) = listener.accept().unwrap();
3615            stream
3616                .write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
3617                .unwrap();
3618            let mut reader = BufReader::new(stream.try_clone().unwrap());
3619            for (expected, response) in [
3620                ("qmp_capabilities", json!({})),
3621                ("query-name", json!({"name": "test"})),
3622                ("query-status", json!({"status": "running"})),
3623                ("system_powerdown", json!({})),
3624            ] {
3625                let mut line = String::new();
3626                reader.read_line(&mut line).unwrap();
3627                let request: Value = serde_json::from_str(&line).unwrap();
3628                assert_eq!(request["execute"], expected);
3629                serde_json::to_writer(
3630                    &mut stream,
3631                    &json!({"return": response, "id": request["id"]}),
3632                )
3633                .unwrap();
3634                stream.write_all(b"\r\n").unwrap();
3635            }
3636            // Keep the child alive through the timeout check, then exit while
3637            // the manager is opening its second QMP connection.
3638            listener.set_nonblocking(true).unwrap();
3639            let deadline = Instant::now() + Duration::from_secs(2);
3640            let second = loop {
3641                match listener.accept() {
3642                    Ok((stream, _)) => break stream,
3643                    Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
3644                        assert!(Instant::now() < deadline, "missing second QMP connection");
3645                        thread::sleep(Duration::from_millis(5));
3646                    }
3647                    Err(error) => panic!("second QMP accept failed: {error}"),
3648                }
3649            };
3650            // SAFETY: `pid` is the unreaped child created for this test.
3651            let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
3652            assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
3653            let deadline = Instant::now() + Duration::from_secs(2);
3654            while crate::state::process_exists(pid) {
3655                assert!(Instant::now() < deadline, "child did not exit");
3656                thread::sleep(Duration::from_millis(5));
3657            }
3658            drop(second);
3659        });
3660
3661        let result = manager.stop("test", Duration::ZERO);
3662        let server_result = server.join();
3663        let _ = child.kill();
3664        let status = child.wait().unwrap();
3665        server_result.unwrap();
3666        result.unwrap();
3667        assert!(!state_path.exists());
3668        assert!(!runtime.join("qmp.sock").exists());
3669        assert!(!status.success());
3670    }
3671
3672    #[test]
3673    fn stop_cleans_runtime_when_process_exits_at_timeout_boundary() {
3674        let root = tempdir().unwrap();
3675        let paths = AppPaths::new(
3676            root.path().join("config"),
3677            root.path().join("data"),
3678            root.path().join("runtime"),
3679        );
3680        let manager = VmManager::new(paths).unwrap();
3681        let runtime = manager.paths().runtime("test").unwrap();
3682        fs::create_dir_all(&runtime).unwrap();
3683        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3684        let pid = child.id();
3685        let state_path = runtime.join("state.json");
3686        VmState::new(
3687            "test".to_owned(),
3688            pid,
3689            runtime.join("qmp.sock"),
3690            runtime.join("display.sock"),
3691            None,
3692        )
3693        .save(&state_path)
3694        .unwrap();
3695        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
3696        let server = thread::spawn(move || {
3697            let (mut stream, _) = listener.accept().unwrap();
3698            stream
3699                .write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
3700                .unwrap();
3701            let mut reader = BufReader::new(stream.try_clone().unwrap());
3702            for (expected, response) in [
3703                ("qmp_capabilities", json!({})),
3704                ("query-name", json!({"name": "test"})),
3705                ("query-status", json!({"status": "running"})),
3706                ("system_powerdown", json!({})),
3707            ] {
3708                let mut line = String::new();
3709                reader.read_line(&mut line).unwrap();
3710                let request: Value = serde_json::from_str(&line).unwrap();
3711                assert_eq!(request["execute"], expected);
3712                if expected == "system_powerdown" {
3713                    let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
3714                    // SAFETY: this test owns the unreaped child identified by child_pid.
3715                    assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
3716                    let deadline = Instant::now() + Duration::from_millis(500);
3717                    while crate::state::process_exists(pid) {
3718                        assert!(
3719                            Instant::now() < deadline,
3720                            "child did not exit after SIGTERM"
3721                        );
3722                        thread::sleep(Duration::from_millis(1));
3723                    }
3724                }
3725                serde_json::to_writer(
3726                    &mut stream,
3727                    &json!({"return": response, "id": request["id"]}),
3728                )
3729                .unwrap();
3730                stream.write_all(b"\r\n").unwrap();
3731            }
3732        });
3733
3734        manager.stop("test", Duration::ZERO).unwrap();
3735        server.join().unwrap();
3736        assert!(!state_path.exists());
3737        assert!(!runtime.join("qmp.sock").exists());
3738        assert!(!child.wait().unwrap().success());
3739    }
3740
3741    #[test]
3742    fn wait_for_exit_observes_a_process_absent_at_the_deadline() {
3743        assert!(wait_for_exit(u32::MAX, Duration::ZERO).is_ok());
3744        assert!(wait_for_exit(u32::MAX, Duration::MAX).is_err());
3745    }
3746
3747    #[test]
3748    fn stop_uses_preflight_deadline_if_post_request_deadline_overflows() {
3749        let preflight_deadline = Instant::now();
3750        assert_eq!(
3751            deadline_after_shutdown_request(Instant::now(), Duration::MAX, preflight_deadline),
3752            preflight_deadline
3753        );
3754    }
3755
3756    #[test]
3757    fn stop_cleans_runtime_if_process_exits_during_initial_qmp_handshake() {
3758        let root = tempdir().unwrap();
3759        let paths = AppPaths::new(
3760            root.path().join("config"),
3761            root.path().join("data"),
3762            root.path().join("runtime"),
3763        );
3764        let manager = VmManager::new(paths).unwrap();
3765        let runtime = manager.paths().runtime("test").unwrap();
3766        fs::create_dir_all(&runtime).unwrap();
3767        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3768        let pid = child.id();
3769        let state_path = runtime.join("state.json");
3770        VmState::new(
3771            "test".to_owned(),
3772            pid,
3773            runtime.join("qmp.sock"),
3774            runtime.join("display.sock"),
3775            None,
3776        )
3777        .save(&state_path)
3778        .unwrap();
3779        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
3780        let server = thread::spawn(move || {
3781            let (stream, _) = listener.accept().unwrap();
3782            let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
3783            // SAFETY: the test owns the unreaped child identified by child_pid.
3784            assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
3785            let deadline = Instant::now() + Duration::from_secs(2);
3786            while crate::state::process_exists(pid) {
3787                assert!(Instant::now() < deadline, "child did not exit");
3788                thread::sleep(Duration::from_millis(5));
3789            }
3790            drop(stream);
3791        });
3792        let result = manager.stop("test", Duration::ZERO);
3793        let server_result = server.join();
3794        let _ = child.kill();
3795        let status = child.wait().unwrap();
3796        server_result.unwrap();
3797        result.unwrap();
3798        assert!(!status.success());
3799        assert!(!state_path.exists());
3800        assert!(!runtime.join("qmp.sock").exists());
3801    }
3802
3803    #[test]
3804    fn kill_cleans_runtime_if_process_exits_during_quit_response() {
3805        let root = tempdir().unwrap();
3806        let paths = AppPaths::new(
3807            root.path().join("config"),
3808            root.path().join("data"),
3809            root.path().join("runtime"),
3810        );
3811        let manager = VmManager::new(paths).unwrap();
3812        let runtime = manager.paths().runtime("test").unwrap();
3813        fs::create_dir_all(&runtime).unwrap();
3814        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
3815        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3816        let pid = child.id();
3817        let state_path = runtime.join("state.json");
3818        VmState::new(
3819            "test".to_owned(),
3820            pid,
3821            runtime.join("qmp.sock"),
3822            runtime.join("display.sock"),
3823            None,
3824        )
3825        .save(&state_path)
3826        .unwrap();
3827        let server = thread::spawn(move || {
3828            let (mut stream, _) = listener.accept().unwrap();
3829            stream
3830                .write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
3831                .unwrap();
3832            let mut reader = BufReader::new(stream.try_clone().unwrap());
3833            for (expected, response) in [
3834                ("qmp_capabilities", json!({})),
3835                ("query-name", json!({"name": "test"})),
3836            ] {
3837                let mut line = String::new();
3838                reader.read_line(&mut line).unwrap();
3839                let request: Value = serde_json::from_str(&line).unwrap();
3840                assert_eq!(request["execute"], expected);
3841                serde_json::to_writer(
3842                    &mut stream,
3843                    &json!({"return": response, "id": request["id"]}),
3844                )
3845                .unwrap();
3846                stream.write_all(b"\r\n").unwrap();
3847            }
3848            let mut line = String::new();
3849            reader.read_line(&mut line).unwrap();
3850            let request: Value = serde_json::from_str(&line).unwrap();
3851            assert_eq!(request["execute"], "quit");
3852            let child_pid = i32::try_from(pid).expect("test child PID fits pid_t");
3853            // SAFETY: this test owns the unreaped child identified by child_pid.
3854            assert_eq!(unsafe { libc::kill(child_pid, libc::SIGTERM) }, 0);
3855            let deadline = Instant::now() + Duration::from_secs(2);
3856            while crate::state::process_exists(pid) {
3857                assert!(Instant::now() < deadline, "child did not exit");
3858                thread::sleep(Duration::from_millis(5));
3859            }
3860            drop(stream);
3861        });
3862
3863        let result = manager.kill("test");
3864        let server_result = server.join();
3865        let _ = child.kill();
3866        let status = child.wait().unwrap();
3867        server_result.unwrap();
3868        result.unwrap();
3869        assert!(!status.success());
3870        assert!(!state_path.exists());
3871        assert!(!runtime.join("qmp.sock").exists());
3872    }
3873
3874    #[test]
3875    fn stop_preserves_runtime_if_qmp_fails_while_process_is_live() {
3876        let root = tempdir().unwrap();
3877        let paths = AppPaths::new(
3878            root.path().join("config"),
3879            root.path().join("data"),
3880            root.path().join("runtime"),
3881        );
3882        let manager = VmManager::new(paths).unwrap();
3883        let runtime = manager.paths().runtime("test").unwrap();
3884        fs::create_dir_all(&runtime).unwrap();
3885        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3886        let state_path = runtime.join("state.json");
3887        VmState::new(
3888            "test".to_owned(),
3889            child.id(),
3890            runtime.join("qmp.sock"),
3891            runtime.join("display.sock"),
3892            None,
3893        )
3894        .save(&state_path)
3895        .unwrap();
3896        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
3897        let server = thread::spawn(move || {
3898            let (stream, _) = listener.accept().unwrap();
3899            drop(stream);
3900        });
3901        let result = manager.stop("test", Duration::ZERO);
3902        let server_result = server.join();
3903        let alive = child.try_wait().unwrap().is_none();
3904        let state_retained = state_path.exists();
3905        let _ = child.kill();
3906        let _ = child.wait();
3907        server_result.unwrap();
3908        assert!(result.is_err());
3909        assert!(alive && state_retained);
3910    }
3911
3912    #[test]
3913    fn stop_rejects_an_unrepresentable_timeout_before_contacting_qmp() {
3914        let root = tempdir().unwrap();
3915        let paths = AppPaths::new(
3916            root.path().join("config"),
3917            root.path().join("data"),
3918            root.path().join("runtime"),
3919        );
3920        let manager = VmManager::new(paths).unwrap();
3921        let runtime = manager.paths().runtime("test").unwrap();
3922        fs::create_dir_all(&runtime).unwrap();
3923        let mut child = Command::new("/bin/sleep").arg("60").spawn().unwrap();
3924        VmState::new(
3925            "test".to_owned(),
3926            child.id(),
3927            runtime.join("missing-qmp.sock"),
3928            runtime.join("display.sock"),
3929            None,
3930        )
3931        .save(&runtime.join("state.json"))
3932        .unwrap();
3933        let result = manager.stop("test", Duration::MAX);
3934        let alive = child.try_wait().unwrap().is_none();
3935        let _ = child.kill();
3936        let _ = child.wait();
3937        assert!(alive, "timeout validation must not stop the process");
3938        assert!(
3939            result
3940                .unwrap_err()
3941                .to_string()
3942                .contains("timeout is too large")
3943        );
3944    }
3945
3946    #[test]
3947    fn validates_snapshot_names_before_qemu_img() {
3948        assert!(validate_snapshot_name("before-upgrade_1").is_ok());
3949        assert!(validate_snapshot_name("").is_err());
3950        assert!(validate_snapshot_name("../escape").is_err());
3951        assert!(validate_snapshot_name("has spaces").is_err());
3952    }
3953
3954    #[test]
3955    fn snapshot_tpm_guard_blocks_only_unpaired_disk_rewrites() {
3956        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
3957        let operations = [
3958            SnapshotOperation::List,
3959            SnapshotOperation::Create,
3960            SnapshotOperation::Revert,
3961            SnapshotOperation::Delete,
3962        ];
3963        for operation in operations {
3964            assert!(ensure_snapshot_tpm_compatible(&config, operation).is_ok());
3965        }
3966
3967        config.software_tpm2 = true;
3968        assert!(ensure_snapshot_tpm_compatible(&config, SnapshotOperation::List).is_ok());
3969        assert!(ensure_snapshot_tpm_compatible(&config, SnapshotOperation::Delete).is_ok());
3970        for operation in [SnapshotOperation::Create, SnapshotOperation::Revert] {
3971            let error = ensure_snapshot_tpm_compatible(&config, operation).unwrap_err();
3972            assert!(
3973                error
3974                    .to_string()
3975                    .contains("disk and TPM state can be paired")
3976            );
3977        }
3978    }
3979
3980    #[test]
3981    fn software_tpm_snapshot_create_rejects_before_host_probe_or_disk_change() {
3982        let (_root, manager, _config, disk) = snapshot_fixture(true);
3983
3984        let error = manager
3985            .snapshot_create("test", "before-upgrade")
3986            .unwrap_err();
3987
3988        assert!(error.to_string().contains("software TPM 2"));
3989        assert_eq!(fs::read(disk).unwrap(), b"snapshot fixture disk");
3990    }
3991
3992    #[test]
3993    fn software_tpm_snapshot_revert_rejects_before_rotating_generation_id() {
3994        let (_root, manager, config, _disk) = snapshot_fixture(true);
3995        let original_generation_id = config.generation_id;
3996
3997        let error = manager
3998            .snapshot_revert("test", "before-upgrade")
3999            .unwrap_err();
4000
4001        assert!(error.to_string().contains("software TPM 2"));
4002        assert_eq!(
4003            manager.config("test").unwrap().generation_id,
4004            original_generation_id
4005        );
4006    }
4007
4008    #[test]
4009    fn snapshot_revert_rejects_running_vm_before_host_probe_or_mutation() {
4010        let (_root, manager, config, disk) = snapshot_fixture(false);
4011        let status_probe_called = std::cell::Cell::new(false);
4012        let probe_called = std::cell::Cell::new(false);
4013        let error = manager
4014            .snapshot_revert_with_probes(
4015                "test",
4016                "target",
4017                || {
4018                    status_probe_called.set(true);
4019                    Ok(VmStatus::Running {
4020                        pid: 1234,
4021                        qemu_status: "running".to_owned(),
4022                    })
4023                },
4024                || {
4025                    probe_called.set(true);
4026                    panic!("host capability probe must not run for a running VM")
4027                },
4028            )
4029            .unwrap_err();
4030
4031        assert!(error.to_string().contains("must be stopped"));
4032        assert!(status_probe_called.get());
4033        assert!(!probe_called.get());
4034        assert_eq!(
4035            manager.config("test").unwrap().generation_id,
4036            config.generation_id
4037        );
4038        assert_eq!(fs::read(disk).unwrap(), b"snapshot fixture disk");
4039        assert!(
4040            !manager
4041                .paths()
4042                .data("test")
4043                .unwrap()
4044                .join(SNAPSHOT_REVERT_MARKER)
4045                .exists()
4046        );
4047    }
4048
4049    #[test]
4050    fn snapshot_revert_missing_snapshot_restores_disk_without_publishing_generation_id() {
4051        let (root, manager, config, disk) = snapshot_fixture(false);
4052        let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
4053        let original_disk = fs::read(&disk).unwrap();
4054        let (host, log, observed_config) =
4055            snapshot_qemu_fixture(root.path(), &manager, &disk, "missing-target");
4056
4057        let error = manager
4058            .snapshot_revert_with_probe("test", "target", || Ok(host))
4059            .unwrap_err();
4060
4061        assert!(format!("{error:#}").contains("does not exist"));
4062        assert_eq!(
4063            manager.config("test").unwrap().generation_id,
4064            config.generation_id
4065        );
4066        assert_eq!(
4067            fs::read(manager.paths().config("test").unwrap()).unwrap(),
4068            original_config
4069        );
4070        assert_eq!(fs::read(observed_config).unwrap(), original_config);
4071        assert_eq!(fs::read(disk).unwrap(), original_disk);
4072        assert_eq!(
4073            fs::read_to_string(log).unwrap(),
4074            "create\ntarget-attempt\nrestore\ndelete-attempt\ndelete\n"
4075        );
4076        assert!(
4077            !manager
4078                .paths()
4079                .data("test")
4080                .unwrap()
4081                .join(SNAPSHOT_REVERT_MARKER)
4082                .exists()
4083        );
4084    }
4085
4086    #[test]
4087    fn successful_snapshot_revert_publishes_generation_id_after_disk_revert() {
4088        let (root, manager, config, disk) = snapshot_fixture(false);
4089        let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
4090        let (host, log, observed_config) =
4091            snapshot_qemu_fixture(root.path(), &manager, &disk, "success");
4092
4093        manager
4094            .snapshot_revert_with_probe("test", "target", || Ok(host))
4095            .unwrap();
4096
4097        assert_eq!(fs::read(observed_config).unwrap(), original_config);
4098        assert_ne!(
4099            manager.config("test").unwrap().generation_id,
4100            config.generation_id
4101        );
4102        assert_eq!(fs::read(disk).unwrap(), b"target snapshot\n");
4103        assert_eq!(
4104            fs::read_to_string(log).unwrap(),
4105            "create\ntarget-attempt\ndelete-attempt\ndelete\n"
4106        );
4107        assert!(
4108            !manager
4109                .paths()
4110                .data("test")
4111                .unwrap()
4112                .join(SNAPSHOT_REVERT_MARKER)
4113                .exists()
4114        );
4115    }
4116
4117    #[test]
4118    fn snapshot_revert_checkpoint_cleanup_failure_leaves_marker_and_blocks_vm_use() {
4119        let (root, manager, config, disk) = snapshot_fixture(false);
4120        let (host, log, _observed_config) =
4121            snapshot_qemu_fixture(root.path(), &manager, &disk, "checkpoint-delete-fails");
4122
4123        let error = manager
4124            .snapshot_revert_with_probe("test", "target", || Ok(host))
4125            .unwrap_err();
4126
4127        assert!(format!("{error:#}").contains("safety checkpoint knottvm-revert-"));
4128        assert!(format!("{error:#}").contains("VM use is blocked"));
4129        assert_ne!(
4130            manager.config("test").unwrap().generation_id,
4131            config.generation_id
4132        );
4133        assert_eq!(fs::read(disk).unwrap(), b"target snapshot\n");
4134        assert_eq!(
4135            fs::read_to_string(log).unwrap(),
4136            "create\ntarget-attempt\ndelete-attempt\n"
4137        );
4138        assert!(
4139            manager
4140                .paths()
4141                .data("test")
4142                .unwrap()
4143                .join(SNAPSHOT_REVERT_MARKER)
4144                .is_file()
4145        );
4146        assert!(
4147            manager
4148                .status("test")
4149                .unwrap_err()
4150                .to_string()
4151                .contains("unresolved snapshot revert")
4152        );
4153    }
4154
4155    #[test]
4156    fn snapshot_revert_vmgenid_publication_failure_restores_disk_and_definition() {
4157        let (root, manager, config, disk) = snapshot_fixture(false);
4158        let original_config = fs::read(manager.paths().config("test").unwrap()).unwrap();
4159        let original_disk = fs::read(&disk).unwrap();
4160        let (host, log, _observed_config) =
4161            snapshot_qemu_fixture(root.path(), &manager, &disk, "config-publish-fails");
4162        let config_root = manager.paths().config_root.clone();
4163
4164        let result = manager.snapshot_revert_with_probe("test", "target", || Ok(host));
4165        fs::set_permissions(&config_root, fs::Permissions::from_mode(0o700)).unwrap();
4166        let error = result.unwrap_err();
4167
4168        assert!(format!("{error:#}").contains("VMGenID publication failed"));
4169        assert_eq!(
4170            manager.config("test").unwrap().generation_id,
4171            config.generation_id
4172        );
4173        assert_eq!(
4174            fs::read(manager.paths().config("test").unwrap()).unwrap(),
4175            original_config
4176        );
4177        assert_eq!(fs::read(disk).unwrap(), original_disk);
4178        assert_eq!(
4179            fs::read_to_string(log).unwrap(),
4180            "create\ntarget-attempt\nrestore\ndelete-attempt\ndelete\n"
4181        );
4182        assert!(
4183            !manager
4184                .paths()
4185                .data("test")
4186                .unwrap()
4187                .join(SNAPSHOT_REVERT_MARKER)
4188                .exists()
4189        );
4190    }
4191
4192    #[test]
4193    fn snapshot_revert_rollback_failure_leaves_marker_and_blocks_vm_use() {
4194        let (root, manager, config, disk) = snapshot_fixture(false);
4195        let original_generation_id = config.generation_id;
4196        let (host, _log, _observed_config) =
4197            snapshot_qemu_fixture(root.path(), &manager, &disk, "rollback-fails");
4198
4199        let error = manager
4200            .snapshot_revert_with_probe("test", "target", || Ok(host))
4201            .unwrap_err();
4202
4203        assert!(format!("{error:#}").contains("VM use is blocked"));
4204        assert_eq!(
4205            manager.config("test").unwrap().generation_id,
4206            original_generation_id
4207        );
4208        assert_eq!(fs::read(disk).unwrap(), b"partial target\n");
4209        assert!(
4210            manager
4211                .paths()
4212                .data("test")
4213                .unwrap()
4214                .join(SNAPSHOT_REVERT_MARKER)
4215                .is_file()
4216        );
4217        assert!(
4218            manager
4219                .status("test")
4220                .unwrap_err()
4221                .to_string()
4222                .contains("unresolved snapshot revert")
4223        );
4224    }
4225
4226    #[test]
4227    fn no_replace_disk_publication_preserves_a_destination_created_after_preflight() {
4228        let root = tempdir().unwrap();
4229        let staged = root.path().join("system.qcow2.staged");
4230        let destination = root.path().join("system.qcow2");
4231        fs::write(&staged, b"new disk").unwrap();
4232
4233        // Simulate another creator winning after our earlier absent-path check.
4234        fs::write(&destination, b"another creator's disk").unwrap();
4235        let result = publish_file_noreplace(&staged, &destination);
4236
4237        assert!(result.is_err());
4238        assert_eq!(fs::read(&destination).unwrap(), b"another creator's disk");
4239        assert_eq!(fs::read(&staged).unwrap(), b"new disk");
4240    }
4241
4242    #[test]
4243    fn refuses_to_replace_an_orphaned_system_disk() {
4244        let root = tempdir().unwrap();
4245        let paths = AppPaths::new(
4246            root.path().join("config"),
4247            root.path().join("data"),
4248            root.path().join("runtime"),
4249        );
4250        let manager = VmManager::new(paths).unwrap();
4251        let data = manager.paths().data("test").unwrap();
4252        fs::create_dir(&data).unwrap();
4253        let disk = data.join("system.qcow2");
4254        fs::write(&disk, b"keep me").unwrap();
4255        let result = manager.create(&CreateOptions {
4256            name: "test".to_owned(),
4257            disk_size: "64M".to_owned(),
4258            install_media: None,
4259            memory_mib: 512,
4260            vcpus: 1,
4261            firmware: Firmware::Uefi,
4262            software_tpm2: false,
4263        });
4264        assert!(result.is_err());
4265        assert_eq!(fs::read(&disk).unwrap(), b"keep me");
4266    }
4267
4268    #[test]
4269    fn recovers_missing_state_from_pid_and_qmp_identity() {
4270        let root = tempdir().unwrap();
4271        let paths = AppPaths::new(
4272            root.path().join("config"),
4273            root.path().join("data"),
4274            root.path().join("runtime"),
4275        );
4276        let manager = VmManager::new(paths).unwrap();
4277        let runtime = manager.paths().runtime("test").unwrap();
4278        fs::create_dir(&runtime).unwrap();
4279        fs::write(runtime.join("qemu.pid"), std::process::id().to_string()).unwrap();
4280        let listener = UnixListener::bind(runtime.join("qmp.sock")).unwrap();
4281        let server = thread::spawn(move || {
4282            let (mut stream, _) = listener.accept().unwrap();
4283            stream
4284                .write_all(b"{\"QMP\":{\"version\":{},\"capabilities\":[]}}\r\n")
4285                .unwrap();
4286            let mut reader = BufReader::new(stream.try_clone().unwrap());
4287            for response in [json!({}), json!({"name": "test"})] {
4288                let mut line = String::new();
4289                reader.read_line(&mut line).unwrap();
4290                let request: Value = serde_json::from_str(&line).unwrap();
4291                serde_json::to_writer(
4292                    &mut stream,
4293                    &json!({"return": response, "id": request["id"]}),
4294                )
4295                .unwrap();
4296                stream.write_all(b"\r\n").unwrap();
4297            }
4298        });
4299        let state = manager.load_state("test").unwrap().unwrap();
4300        assert_eq!(state.pid, std::process::id());
4301        assert!(runtime.join("state.json").is_file());
4302        server.join().unwrap();
4303    }
4304
4305    #[test]
4306    fn rejects_definition_name_mismatches() {
4307        let root = tempdir().unwrap();
4308        let paths = AppPaths::new(
4309            root.path().join("config"),
4310            root.path().join("data"),
4311            root.path().join("runtime"),
4312        );
4313        let manager = VmManager::new(paths).unwrap();
4314        let config = VmConfig::new("other".to_owned(), root.path().join("disk.qcow2"), None);
4315        fs::write(
4316            manager.paths().config("expected").unwrap(),
4317            config.to_toml().unwrap(),
4318        )
4319        .unwrap();
4320        assert!(manager.config("expected").is_err());
4321    }
4322
4323    #[test]
4324    fn clone_rejects_identical_names_before_disk_work() {
4325        let root = tempdir().unwrap();
4326        let paths = AppPaths::new(
4327            root.path().join("config"),
4328            root.path().join("data"),
4329            root.path().join("runtime"),
4330        );
4331        let manager = VmManager::new(paths).unwrap();
4332        assert!(manager.clone_vm("same", "same").is_err());
4333    }
4334
4335    #[test]
4336    fn persists_unique_offline_usb_assignments() {
4337        let root = tempdir().unwrap();
4338        let paths = AppPaths::new(
4339            root.path().join("config"),
4340            root.path().join("data"),
4341            root.path().join("runtime"),
4342        );
4343        let manager = VmManager::new(paths).unwrap();
4344        let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
4345        fs::write(
4346            manager.paths().config("test").unwrap(),
4347            config.to_toml().unwrap(),
4348        )
4349        .unwrap();
4350        let device = UsbHostDevice { bus: 1, address: 4 };
4351
4352        manager.usb_add("test", device).unwrap();
4353        assert_eq!(manager.config("test").unwrap().usb_devices, [device]);
4354        assert!(manager.usb_add("test", device).is_err());
4355        assert_eq!(manager.config("test").unwrap().usb_devices, [device]);
4356        assert_eq!(manager.usb_remove("test", device).unwrap(), device);
4357        assert!(manager.config("test").unwrap().usb_devices.is_empty());
4358    }
4359
4360    #[test]
4361    fn configures_guest_pointer_device_while_stopped() {
4362        let root = tempdir().unwrap();
4363        let paths = AppPaths::new(
4364            root.path().join("config"),
4365            root.path().join("data"),
4366            root.path().join("runtime"),
4367        );
4368        let manager = VmManager::new(paths).unwrap();
4369        let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
4370        fs::write(
4371            manager.paths().config("test").unwrap(),
4372            config.to_toml().unwrap(),
4373        )
4374        .unwrap();
4375
4376        let configured = manager
4377            .configure(
4378                "test",
4379                &super::ConfigureOptions {
4380                    pointer_device: Some(PointerDevice::Mouse),
4381                    ..super::ConfigureOptions::default()
4382                },
4383            )
4384            .unwrap();
4385        assert_eq!(configured.pointer_device, PointerDevice::Mouse);
4386        assert_eq!(
4387            manager.config("test").unwrap().pointer_device,
4388            PointerDevice::Mouse
4389        );
4390        assert!(
4391            manager
4392                .configure("test", &super::ConfigureOptions::default())
4393                .is_err()
4394        );
4395    }
4396
4397    #[test]
4398    fn persists_canonical_offline_directory_shares() {
4399        let root = tempdir().unwrap();
4400        let paths = AppPaths::new(
4401            root.path().join("config"),
4402            root.path().join("data"),
4403            root.path().join("runtime"),
4404        );
4405        let manager = VmManager::new(paths).unwrap();
4406        let config = VmConfig::new("test".to_owned(), root.path().join("disk.qcow2"), None);
4407        fs::write(
4408            manager.paths().config("test").unwrap(),
4409            config.to_toml().unwrap(),
4410        )
4411        .unwrap();
4412        let shared = root.path().join("shared");
4413        fs::create_dir(&shared).unwrap();
4414
4415        let share = manager
4416            .share_add("test", "host-data".to_owned(), &shared, true)
4417            .unwrap();
4418        assert_eq!(share.path, fs::canonicalize(&shared).unwrap());
4419        assert!(share.read_only);
4420        let configured = manager.config("test").unwrap();
4421        assert_eq!(configured.shares.as_slice(), std::slice::from_ref(&share));
4422        assert!(
4423            manager
4424                .share_add("test", "host-data".to_owned(), &shared, false)
4425                .is_err()
4426        );
4427        assert_eq!(manager.share_remove("test", "host-data").unwrap(), share);
4428        assert!(manager.config("test").unwrap().shares.is_empty());
4429    }
4430
4431    #[test]
4432    fn publishes_only_new_binary_ppm_screenshots() {
4433        let root = tempdir().unwrap();
4434        let staging = root.path().join("staging.ppm");
4435        let destination = root.path().join("screen.ppm");
4436        fs::write(&staging, b"P6\n1 1\n255\n\0\0\0").unwrap();
4437        assert_eq!(publish_screenshot(&staging, &destination).unwrap(), 14);
4438        assert_eq!(fs::read(&destination).unwrap(), b"P6\n1 1\n255\n\0\0\0");
4439        assert!(publish_screenshot(&staging, &destination).is_err());
4440        assert_eq!(fs::read(&destination).unwrap(), b"P6\n1 1\n255\n\0\0\0");
4441        fs::write(&staging, b"not a screenshot").unwrap();
4442        assert!(publish_screenshot(&staging, &root.path().join("invalid.ppm")).is_err());
4443    }
4444
4445    #[test]
4446    fn validates_ppm_dimensions_raster_length_and_samples_before_publication() {
4447        let root = tempdir().unwrap();
4448        let staging = root.path().join("staging.ppm");
4449        let cases: &[(&str, &[u8])] = &[
4450            ("zero-width", b"P6\n0 1\n255\n\0\0\0"),
4451            ("truncated", b"P6\n2 1\n255\n\0\0\0"),
4452            ("trailing", b"P6\n1 1\n255\n\0\0\0x"),
4453            ("invalid-maxval", b"P6\n1 1\n65536\n\0\0\0"),
4454            ("sample-out-of-range", b"P6\n1 1\n15\n\x10\0\0"),
4455            ("raster-overflow", b"P6\n18446744073709551615 2\n255\n"),
4456        ];
4457        for (name, bytes) in cases {
4458            fs::write(&staging, bytes).unwrap();
4459            let destination = root.path().join(format!("{name}.ppm"));
4460            assert!(
4461                publish_screenshot(&staging, &destination).is_err(),
4462                "{name}"
4463            );
4464            assert!(!destination.exists(), "{name} left a partial screenshot");
4465        }
4466    }
4467
4468    #[test]
4469    fn publishes_valid_commented_crlf_sixteen_bit_ppm() {
4470        let root = tempdir().unwrap();
4471        let staging = root.path().join("staging.ppm");
4472        let destination = root.path().join("screen.ppm");
4473        let ppm = b"P6\r\n# valid comment\n1 1\n1023\r\n\0\0\x01\xff\x03\xff";
4474        fs::write(&staging, ppm).unwrap();
4475
4476        assert_eq!(
4477            publish_screenshot(&staging, &destination).unwrap(),
4478            ppm.len() as u64
4479        );
4480        assert_eq!(fs::read(destination).unwrap(), ppm);
4481    }
4482
4483    #[test]
4484    fn validates_positive_disk_growth() {
4485        assert_eq!(validate_growth_amount("20g").unwrap(), "20G");
4486        assert!(validate_growth_amount("0G").is_err());
4487        assert!(validate_growth_amount("-1G").is_err());
4488        assert!(validate_growth_amount("20").is_err());
4489    }
4490
4491    #[test]
4492    fn retries_only_kvm_initialization_failures() {
4493        assert!(is_kvm_initialization_failure(
4494            b"qemu-system-x86_64: failed to initialize kvm: Device or resource busy"
4495        ));
4496        assert!(is_kvm_initialization_failure(
4497            b"Could not access KVM kernel module: Permission denied"
4498        ));
4499        assert!(!is_kvm_initialization_failure(
4500            b"usb-host: failed to open host usb device 1:4"
4501        ));
4502    }
4503
4504    #[test]
4505    fn kvm_failure_with_a_live_pid_does_not_start_a_second_qemu() {
4506        let (root, manager, mut config, _) = snapshot_fixture(false);
4507        config.firmware = Firmware::Bios;
4508        fs::write(
4509            manager.paths().config("test").unwrap(),
4510            config.to_toml().unwrap(),
4511        )
4512        .unwrap();
4513        let runtime = manager.paths().runtime("test").unwrap();
4514        let pid_file = runtime.join("qemu.pid");
4515        let attempts = root.path().join("qemu-attempts");
4516        let program = root.path().join("qemu-fixture");
4517        let script = format!(
4518            "#!/bin/sh\nprintf 'launch\\n' >> {}\nprintf '%s\\n' '{}' > {}\n\
4519             printf 'failed to initialize kvm: Device or resource busy\\n' >&2\nexit 1\n",
4520            shell_quote(&attempts),
4521            std::process::id(),
4522            shell_quote(&pid_file),
4523        );
4524        fs::write(&program, script).unwrap();
4525        fs::set_permissions(&program, fs::Permissions::from_mode(0o700)).unwrap();
4526        let host = HostCapabilities {
4527            qemu: program,
4528            qemu_img: PathBuf::from("/bin/false"),
4529            swtpm: None,
4530            swtpm_ioctl: None,
4531            kvm_available: true,
4532            uefi_code: None,
4533            uefi_secure_code: None,
4534            uefi_vars: None,
4535            uefi_secure_vars: None,
4536        };
4537
4538        let error = manager.start_with_host("test", &host).unwrap_err();
4539        assert!(error.to_string().contains("runtime files were preserved"));
4540        assert_eq!(fs::read_to_string(attempts).unwrap(), "launch\n");
4541        assert!(pid_file.is_file());
4542    }
4543
4544    #[test]
4545    fn bounds_balloon_targets_to_configured_memory() {
4546        assert_eq!(validate_balloon_target(256, 512).unwrap(), 268_435_456);
4547        assert_eq!(validate_balloon_target(512, 512).unwrap(), 536_870_912);
4548        assert!(validate_balloon_target(255, 512).is_err());
4549        assert!(validate_balloon_target(513, 512).is_err());
4550    }
4551
4552    #[test]
4553    fn deletion_rejects_a_symlinked_vm_data_directory() {
4554        let root = tempdir().unwrap();
4555        let paths = AppPaths::new(
4556            root.path().join("config"),
4557            root.path().join("data"),
4558            root.path().join("runtime"),
4559        );
4560        let manager = VmManager::new(paths).unwrap();
4561        let outside = root.path().join("outside");
4562        fs::create_dir(&outside).unwrap();
4563        fs::write(outside.join("system.qcow2"), b"must survive").unwrap();
4564        let data = manager.paths().data("test").unwrap();
4565        symlink(&outside, &data).unwrap();
4566        let config = VmConfig::new("test".to_owned(), data.join("system.qcow2"), None);
4567        let definition = manager.paths().config("test").unwrap();
4568        fs::write(&definition, config.to_toml().unwrap()).unwrap();
4569
4570        assert!(manager.delete_vm("test").is_err());
4571        assert!(definition.is_file());
4572        assert_eq!(
4573            fs::read(outside.join("system.qcow2")).unwrap(),
4574            b"must survive"
4575        );
4576    }
4577
4578    #[test]
4579    fn deletion_resumes_from_a_durable_tombstone() {
4580        let root = tempdir().unwrap();
4581        let paths = AppPaths::new(
4582            root.path().join("config"),
4583            root.path().join("data"),
4584            root.path().join("runtime"),
4585        );
4586        let manager = VmManager::new(paths).unwrap();
4587        let data = manager.paths().data("test").unwrap();
4588        fs::create_dir(&data).unwrap();
4589        let disk = data.join("system.qcow2");
4590        fs::write(&disk, b"disk").unwrap();
4591        fs::write(data.join("uefi-vars.fd"), b"vars").unwrap();
4592        let tpm_state = data.join("tpm-state");
4593        fs::create_dir(&tpm_state).unwrap();
4594        fs::write(tpm_state.join("tpm2-00.permall"), b"TPM identity").unwrap();
4595        let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
4596        config.software_tpm2 = true;
4597        let definition = manager.paths().config("test").unwrap();
4598        fs::write(&definition, config.to_toml().unwrap()).unwrap();
4599        let tombstone = definition.with_extension("toml.deleting");
4600        fs::rename(&definition, &tombstone).unwrap();
4601
4602        let report = manager.delete_vm("test").unwrap();
4603        assert!(report.removed_managed_disk);
4604        assert!(!disk.exists());
4605        assert!(!tpm_state.exists());
4606        assert!(!tombstone.exists());
4607        assert!(
4608            manager
4609                .paths()
4610                .runtime("test")
4611                .unwrap()
4612                .join("operation.lock")
4613                .is_file()
4614        );
4615    }
4616
4617    #[test]
4618    fn pending_deletion_tombstone_remains_in_disk_owner_checks() {
4619        let root = tempdir().unwrap();
4620        let manager = VmManager::new(AppPaths::new(
4621            root.path().join("config"),
4622            root.path().join("data"),
4623            root.path().join("runtime"),
4624        ))
4625        .unwrap();
4626        let target_data = manager.paths().data("target").unwrap();
4627        fs::create_dir_all(&target_data).unwrap();
4628        let shared_disk = target_data.join("system.qcow2");
4629        fs::write(&shared_disk, b"guest data owned by pending deletion").unwrap();
4630
4631        let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
4632        let tombstone = manager
4633            .paths()
4634            .config("target")
4635            .unwrap()
4636            .with_extension("toml.deleting");
4637        fs::write(&tombstone, target.to_toml().unwrap()).unwrap();
4638        let other = VmConfig::new("other".to_owned(), shared_disk.clone(), None);
4639        fs::write(
4640            manager.paths().config("other").unwrap(),
4641            other.to_toml().unwrap(),
4642        )
4643        .unwrap();
4644
4645        let error = manager
4646            .ensure_unique_disk_owner("other", &manager.config("other").unwrap())
4647            .unwrap_err();
4648
4649        assert!(error.to_string().contains("same system disk"));
4650        assert_eq!(
4651            fs::read(&shared_disk).unwrap(),
4652            b"guest data owned by pending deletion"
4653        );
4654    }
4655
4656    #[test]
4657    fn resumed_deletion_preserves_disk_referenced_by_another_vm() {
4658        let root = tempdir().unwrap();
4659        let manager = VmManager::new(AppPaths::new(
4660            root.path().join("config"),
4661            root.path().join("data"),
4662            root.path().join("runtime"),
4663        ))
4664        .unwrap();
4665        let target_data = manager.paths().data("target").unwrap();
4666        fs::create_dir_all(&target_data).unwrap();
4667        let shared_disk = target_data.join("system.qcow2");
4668        fs::write(&shared_disk, b"guest data owned by other").unwrap();
4669
4670        let target = VmConfig::new("target".to_owned(), shared_disk.clone(), None);
4671        let target_tombstone = manager
4672            .paths()
4673            .config("target")
4674            .unwrap()
4675            .with_extension("toml.deleting");
4676        fs::write(&target_tombstone, target.to_toml().unwrap()).unwrap();
4677        let other = VmConfig::new("other".to_owned(), shared_disk.clone(), None);
4678        let other_definition = manager.paths().config("other").unwrap();
4679        fs::write(&other_definition, other.to_toml().unwrap()).unwrap();
4680
4681        let error = manager.delete_vm("target").unwrap_err();
4682
4683        assert!(error.to_string().contains("same system disk"));
4684        assert_eq!(
4685            fs::read(&shared_disk).unwrap(),
4686            b"guest data owned by other"
4687        );
4688        assert!(target_tombstone.is_file());
4689        assert!(other_definition.is_file());
4690    }
4691
4692    #[test]
4693    fn interrupted_restore_preserves_all_destination_artifacts() {
4694        let root = tempdir().unwrap();
4695        let data = root.path().join("vm-data");
4696        fs::create_dir(&data).unwrap();
4697        fs::write(data.join(".restore-in-progress"), b"source-vm").unwrap();
4698        fs::write(data.join("system.qcow2"), b"existing disk").unwrap();
4699        fs::write(data.join("uefi-vars.fd"), b"existing vars").unwrap();
4700        fs::write(data.join(".restore-disk.tmp"), b"staged disk").unwrap();
4701        let staging = data.join(".restore-stage");
4702        fs::create_dir(&staging).unwrap();
4703        fs::write(staging.join("sentinel"), b"staged backup").unwrap();
4704        let directory = super::PinnedDir::open(&data).unwrap();
4705
4706        let error = require_restore_marker_clear(&directory, &data.join(".restore-in-progress"))
4707            .unwrap_err();
4708
4709        assert!(
4710            error
4711                .to_string()
4712                .contains("preserved for manual inspection")
4713        );
4714        assert_eq!(
4715            fs::read(data.join("system.qcow2")).unwrap(),
4716            b"existing disk"
4717        );
4718        assert_eq!(
4719            fs::read(data.join("uefi-vars.fd")).unwrap(),
4720            b"existing vars"
4721        );
4722        assert_eq!(
4723            fs::read(data.join(".restore-disk.tmp")).unwrap(),
4724            b"staged disk"
4725        );
4726        assert_eq!(
4727            fs::read(staging.join("sentinel")).unwrap(),
4728            b"staged backup"
4729        );
4730        assert!(data.join(".restore-in-progress").is_file());
4731    }
4732
4733    #[test]
4734    fn restore_failure_after_publication_preserves_every_artifact() {
4735        let root = tempdir().unwrap();
4736        let paths = AppPaths::new(
4737            root.path().join("config"),
4738            root.path().join("data"),
4739            root.path().join("runtime"),
4740        );
4741        let manager = VmManager::new(paths).unwrap();
4742        let backup = root.path().join("backup");
4743        fs::create_dir(&backup).unwrap();
4744        let config = VmConfig::new("source".to_owned(), PathBuf::from(BACKUP_DISK_FILE), None);
4745        fs::write(backup.join(BACKUP_CONFIG_FILE), config.to_toml().unwrap()).unwrap();
4746        fs::write(backup.join(BACKUP_DISK_FILE), b"source qcow2 bytes").unwrap();
4747        fs::write(backup.join(BACKUP_UEFI_VARS_FILE), b"source vars").unwrap();
4748        BackupManifest::build(&backup, "source".to_owned())
4749            .unwrap()
4750            .save(&backup)
4751            .unwrap();
4752
4753        let definition = manager.paths().config("destination").unwrap();
4754        let qemu_img = root.path().join("qemu-img");
4755        let script = format!(
4756            "#!/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",
4757            shell_quote(&definition)
4758        );
4759        fs::write(&qemu_img, script).unwrap();
4760        fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
4761        let host = HostCapabilities {
4762            qemu: PathBuf::from("/bin/false"),
4763            qemu_img,
4764            swtpm: None,
4765            swtpm_ioctl: None,
4766            kvm_available: false,
4767            uefi_code: None,
4768            uefi_secure_code: None,
4769            uefi_vars: None,
4770            uefi_secure_vars: None,
4771        };
4772
4773        let error = manager
4774            .backup_restore_with_host(&backup, "destination", &host)
4775            .unwrap_err();
4776
4777        assert!(error.to_string().contains("failed to create"));
4778        let data = manager.paths().data("destination").unwrap();
4779        assert!(data.join(".restore-in-progress").is_file());
4780        assert!(data.join(".restore-stage/manifest.json").is_file());
4781        assert_eq!(
4782            fs::read(data.join("system.qcow2")).unwrap(),
4783            b"restored disk"
4784        );
4785        assert_eq!(fs::read(data.join("uefi-vars.fd")).unwrap(), b"source vars");
4786        assert_eq!(fs::read(&definition).unwrap(), b"concurrent definition");
4787    }
4788
4789    fn shell_quote(path: &Path) -> String {
4790        format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
4791    }
4792
4793    #[test]
4794    fn backup_cleanup_never_follows_a_directory_symlink() {
4795        let root = tempdir().unwrap();
4796        let outside = root.path().join("outside");
4797        fs::create_dir(&outside).unwrap();
4798        for name in ["manifest.json", "vm.toml", "disk.qcow2", "uefi-vars.fd"] {
4799            fs::write(outside.join(name), b"must survive").unwrap();
4800        }
4801        let staging_link = root.path().join(".restore-stage");
4802        symlink(&outside, &staging_link).unwrap();
4803        cleanup_backup_directory(&staging_link);
4804        for name in ["manifest.json", "vm.toml", "disk.qcow2", "uefi-vars.fd"] {
4805            assert_eq!(fs::read(outside.join(name)).unwrap(), b"must survive");
4806        }
4807    }
4808
4809    #[test]
4810    fn swtpm_cleanup_preserves_live_helper_when_control_socket_is_missing() {
4811        let root = tempdir().unwrap();
4812        let paths = AppPaths::new(
4813            root.path().join("config"),
4814            root.path().join("data"),
4815            root.path().join("runtime"),
4816        );
4817        let manager = VmManager::new(paths).unwrap();
4818        let data = manager.paths().data("test").unwrap();
4819        let runtime = manager.paths().runtime("test").unwrap();
4820        fs::create_dir(&data).unwrap();
4821        fs::create_dir(&runtime).unwrap();
4822        let tpm_state = data.join("tpm-state");
4823        fs::create_dir(&tpm_state).unwrap();
4824        fs::write(tpm_state.join("tpm2-00.permall"), b"persistent identity").unwrap();
4825        validate_tpm_state_directory(&tpm_state).unwrap();
4826        assert_eq!(
4827            fs::metadata(tpm_state.join("tpm2-00.permall"))
4828                .unwrap()
4829                .permissions()
4830                .mode()
4831                & 0o777,
4832            0o600
4833        );
4834        let files = manager.runtime_files("test", &data).unwrap();
4835        fs::write(&files.tpm_control_socket, b"not a socket").unwrap();
4836        let fake_swtpm = format!(
4837            "/bin/sleep 60 &\nprintf '%s\\n' \"$!\" > {}\nexit 0\n",
4838            shell_quote(&files.swtpm_pid_file)
4839        );
4840        launch_swtpm(&CommandSpec {
4841            program: PathBuf::from("/bin/sh"),
4842            args: vec!["-c".into(), fake_swtpm.into()],
4843        })
4844        .unwrap();
4845        let pid = read_process_pid(&files.swtpm_pid_file, "swtpm").unwrap();
4846        assert!(crate::state::process_exists(pid));
4847        assert!(wait_for_swtpm(&files, Duration::ZERO).is_err());
4848        assert!(stop_swtpm_files(&files, None).is_err());
4849        assert!(crate::state::process_exists(pid));
4850        assert!(files.swtpm_pid_file.exists());
4851        assert!(files.tpm_control_socket.exists());
4852        assert_eq!(
4853            fs::read(tpm_state.join("tpm2-00.permall")).unwrap(),
4854            b"persistent identity"
4855        );
4856        let pid_i32 = i32::try_from(pid).unwrap();
4857        assert_eq!(unsafe { libc::kill(pid_i32, libc::SIGTERM) }, 0);
4858        wait_for_process_exit(pid, Duration::from_secs(2), "fake swtpm").unwrap();
4859    }
4860
4861    #[test]
4862    fn swtpm_ioctl_stop_invokes_bounded_control_command() {
4863        let root = tempdir().unwrap();
4864        let log = root.path().join("args");
4865        let fake_ioctl = root.path().join("swtpm_ioctl");
4866        let control = root.path().join("control.sock");
4867        fs::write(
4868            &fake_ioctl,
4869            format!("#!/bin/sh\nprintf '%s\\n' \"$*\" > {}\n", shell_quote(&log)),
4870        )
4871        .unwrap();
4872        fs::set_permissions(&fake_ioctl, fs::Permissions::from_mode(0o700)).unwrap();
4873
4874        run_swtpm_ioctl_stop(&fake_ioctl, &control).unwrap();
4875
4876        let args = fs::read_to_string(log).unwrap();
4877        assert!(args.contains("--unix"));
4878        assert!(args.contains("--stop"));
4879        assert!(args.contains(&control.display().to_string()));
4880    }
4881
4882    #[test]
4883    fn tpm_state_copy_is_private_and_does_not_copy_unsafe_entries() {
4884        let root = tempdir().unwrap();
4885        let source = root.path().join("source");
4886        let destination = root.path().join("destination");
4887        fs::create_dir(&source).unwrap();
4888        fs::set_permissions(&source, fs::Permissions::from_mode(0o700)).unwrap();
4889        fs::write(source.join("tpm2-00.permall"), b"state").unwrap();
4890        fs::write(source.join(".lock"), []).unwrap();
4891        copy_tpm_state_directory(&source, &destination, false).unwrap();
4892        assert_eq!(
4893            fs::read(destination.join("tpm2-00.permall")).unwrap(),
4894            b"state"
4895        );
4896        assert!(destination.join(".lock").is_file());
4897        assert_eq!(
4898            fs::metadata(&destination).unwrap().permissions().mode() & 0o777,
4899            0o700
4900        );
4901        assert_eq!(
4902            fs::metadata(destination.join("tpm2-00.permall"))
4903                .unwrap()
4904                .permissions()
4905                .mode()
4906                & 0o777,
4907            0o600
4908        );
4909
4910        let unsafe_source = root.path().join("unsafe");
4911        fs::create_dir(&unsafe_source).unwrap();
4912        fs::write(unsafe_source.join("unexpected"), b"must not copy").unwrap();
4913        let unsafe_destination = root.path().join("unsafe-copy");
4914        assert!(copy_tpm_state_directory(&unsafe_source, &unsafe_destination, false).is_err());
4915        assert!(!unsafe_destination.join("unexpected").exists());
4916    }
4917
4918    #[test]
4919    fn cloning_an_enabled_tpm_vm_does_not_copy_source_tpm_identity() {
4920        let root = tempdir().unwrap();
4921        let paths = AppPaths::new(
4922            root.path().join("config"),
4923            root.path().join("data"),
4924            root.path().join("runtime"),
4925        );
4926        let manager = VmManager::new(paths).unwrap();
4927        let source_data = manager.paths().data("source").unwrap();
4928        fs::create_dir(&source_data).unwrap();
4929        let disk = source_data.join("system.qcow2");
4930        fs::write(&disk, b"qcow2 source").unwrap();
4931        let tpm_state = source_data.join("tpm-state");
4932        fs::create_dir(&tpm_state).unwrap();
4933        fs::write(tpm_state.join("tpm2-00.permall"), b"source TPM identity").unwrap();
4934        let mut config = VmConfig::new("source".to_owned(), disk, None);
4935        config.firmware = Firmware::Bios;
4936        config.software_tpm2 = true;
4937        fs::write(
4938            manager.paths().config("source").unwrap(),
4939            config.to_toml().unwrap(),
4940        )
4941        .unwrap();
4942        let qemu_img = root.path().join("qemu-img");
4943        fs::write(
4944            &qemu_img,
4945            "#!/bin/sh\noutput=\nfor arg do output=\"$arg\"; done\nprintf 'independent disk' > \"$output\"\n",
4946        )
4947        .unwrap();
4948        fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
4949        let host = HostCapabilities {
4950            qemu: PathBuf::from("/bin/false"),
4951            qemu_img,
4952            swtpm: None,
4953            swtpm_ioctl: None,
4954            kvm_available: false,
4955            uefi_code: None,
4956            uefi_secure_code: None,
4957            uefi_vars: None,
4958            uefi_secure_vars: None,
4959        };
4960
4961        manager
4962            .clone_vm_with_host("source", "clone", &host)
4963            .unwrap();
4964
4965        let clone = manager.config("clone").unwrap();
4966        assert!(clone.software_tpm2);
4967        assert!(
4968            !manager
4969                .paths()
4970                .data("clone")
4971                .unwrap()
4972                .join("tpm-state")
4973                .exists()
4974        );
4975        assert_eq!(
4976            fs::read(tpm_state.join("tpm2-00.permall")).unwrap(),
4977            b"source TPM identity"
4978        );
4979    }
4980
4981    #[test]
4982    fn tpm_backup_restore_preserves_guest_identity_and_secure_modes() {
4983        let root = tempdir().unwrap();
4984        let paths = AppPaths::new(
4985            root.path().join("config"),
4986            root.path().join("data"),
4987            root.path().join("runtime"),
4988        );
4989        let manager = VmManager::new(paths).unwrap();
4990        let source_data = manager.paths().data("source").unwrap();
4991        fs::create_dir(&source_data).unwrap();
4992        let disk = source_data.join("system.qcow2");
4993        fs::write(&disk, b"qcow2 source bytes").unwrap();
4994        let state_dir = source_data.join("tpm-state");
4995        fs::create_dir(&state_dir).unwrap();
4996        fs::write(state_dir.join("tpm2-00.permall"), b"guest TPM identity").unwrap();
4997        fs::write(state_dir.join(".lock"), []).unwrap();
4998        let mut config = VmConfig::new("source".to_owned(), disk, None);
4999        config.software_tpm2 = true;
5000        fs::write(
5001            manager.paths().config("source").unwrap(),
5002            config.to_toml().unwrap(),
5003        )
5004        .unwrap();
5005
5006        let qemu_img = root.path().join("qemu-img");
5007        fs::write(
5008            &qemu_img,
5009            "#!/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",
5010        )
5011        .unwrap();
5012        fs::set_permissions(&qemu_img, fs::Permissions::from_mode(0o700)).unwrap();
5013        let host = HostCapabilities {
5014            qemu: PathBuf::from("/bin/false"),
5015            qemu_img,
5016            swtpm: None,
5017            swtpm_ioctl: None,
5018            kvm_available: false,
5019            uefi_code: None,
5020            uefi_secure_code: None,
5021            uefi_vars: None,
5022            uefi_secure_vars: None,
5023        };
5024        let backup = root.path().join("backup");
5025
5026        let manifest = manager
5027            .backup_create_with_host("source", &backup, &host)
5028            .unwrap();
5029        assert!(manifest.tpm_state.is_some());
5030        assert_eq!(
5031            fs::read(backup.join("tpm-state/tpm2-00.permall")).unwrap(),
5032            b"guest TPM identity"
5033        );
5034        assert!(backup.join("tpm-state/.lock").is_file());
5035        assert_eq!(
5036            fs::metadata(backup.join("tpm-state"))
5037                .unwrap()
5038                .permissions()
5039                .mode()
5040                & 0o777,
5041            0o700
5042        );
5043        assert_eq!(
5044            fs::metadata(backup.join("tpm-state/tpm2-00.permall"))
5045                .unwrap()
5046                .permissions()
5047                .mode()
5048                & 0o777,
5049            0o600
5050        );
5051        assert_eq!(
5052            VmManager::backup_verify_with_host(&backup, &host)
5053                .unwrap()
5054                .tpm_state,
5055            manifest.tpm_state
5056        );
5057
5058        manager
5059            .backup_restore_with_host(&backup, "restored", &host)
5060            .unwrap();
5061        assert!(manager.config("restored").unwrap().software_tpm2);
5062        assert_eq!(
5063            fs::read(
5064                manager
5065                    .paths()
5066                    .data("restored")
5067                    .unwrap()
5068                    .join("tpm-state/tpm2-00.permall")
5069            )
5070            .unwrap(),
5071            b"guest TPM identity"
5072        );
5073        assert!(
5074            manager
5075                .paths()
5076                .data("restored")
5077                .unwrap()
5078                .join("tpm-state/.lock")
5079                .is_file()
5080        );
5081    }
5082}