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