Skip to main content

aev_vm/
qemu.rs

1//! QEMU/KVM capability probing and deterministic command construction.
2
3use std::env;
4use std::ffi::{OsStr, OsString};
5use std::fmt::Write as _;
6use std::fs::{self, OpenOptions};
7use std::io;
8use std::os::unix::ffi::{OsStrExt, OsStringExt};
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result, bail};
12use serde_json::json;
13
14use crate::config::{Acceleration, AudioMode, Firmware, NetworkMode, PointerDevice, VmConfig};
15
16/// Resolved host binaries and virtualization capabilities.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct HostCapabilities {
19    /// QEMU system emulator.
20    pub qemu: PathBuf,
21    /// QEMU disk image utility.
22    pub qemu_img: PathBuf,
23    /// Optional software TPM 2 emulator.
24    pub swtpm: Option<PathBuf>,
25    /// Optional software TPM control utility.
26    pub swtpm_ioctl: Option<PathBuf>,
27    /// Whether `/dev/kvm` can be opened read-write.
28    pub kvm_available: bool,
29    /// Optional UEFI read-only code image.
30    pub uefi_code: Option<PathBuf>,
31    /// Optional SMM-backed Secure Boot UEFI code image.
32    pub uefi_secure_code: Option<PathBuf>,
33    /// Optional UEFI variable template.
34    pub uefi_vars: Option<PathBuf>,
35    /// Optional variable template matching the Secure Boot code image.
36    pub uefi_secure_vars: Option<PathBuf>,
37}
38
39impl HostCapabilities {
40    /// Probe tools and firmware without changing host state.
41    pub fn probe() -> Result<Self> {
42        let qemu = find_executable("qemu-system-x86_64")
43            .context("qemu-system-x86_64 was not found in PATH")?;
44        let qemu_img = find_executable("qemu-img").context("qemu-img was not found in PATH")?;
45        let swtpm = find_executable("swtpm");
46        let swtpm_ioctl = find_executable("swtpm_ioctl");
47        let kvm_available = OpenOptions::new()
48            .read(true)
49            .write(true)
50            .open("/dev/kvm")
51            .is_ok();
52        let (uefi_code, uefi_vars) = discover_uefi();
53        let (uefi_secure_code, uefi_secure_vars) = discover_secure_uefi();
54        Ok(Self {
55            qemu,
56            qemu_img,
57            swtpm,
58            swtpm_ioctl,
59            kvm_available,
60            uefi_code,
61            uefi_secure_code,
62            uefi_vars,
63            uefi_secure_vars,
64        })
65    }
66}
67
68/// Runtime-only files supplied to a QEMU process.
69#[derive(Debug, Clone)]
70pub struct RuntimeFiles {
71    /// QMP control socket.
72    pub qmp_socket: PathBuf,
73    /// RFB console socket.
74    pub display_socket: PathBuf,
75    /// QEMU Guest Agent proxy socket.
76    pub agent_socket: PathBuf,
77    /// QEMU daemon PID file.
78    pub pid_file: PathBuf,
79    /// Per-VM writable UEFI variables.
80    pub uefi_vars: PathBuf,
81    /// Software TPM command socket.
82    pub tpm_socket: PathBuf,
83    /// Software TPM control socket.
84    pub tpm_control_socket: PathBuf,
85    /// Software TPM daemon PID file.
86    pub swtpm_pid_file: PathBuf,
87    /// Persistent software TPM state directory.
88    pub tpm_state_dir: PathBuf,
89}
90
91/// A shell-free executable and argument list.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct CommandSpec {
94    /// Executable path.
95    pub program: PathBuf,
96    /// Individual arguments passed directly to the executable.
97    pub args: Vec<OsString>,
98}
99
100impl CommandSpec {
101    /// Produce a readable, shell-escaped diagnostic command.
102    #[must_use]
103    pub fn display(&self) -> String {
104        std::iter::once(self.program.as_os_str())
105            .chain(self.args.iter().map(OsString::as_os_str))
106            .map(shell_quote)
107            .collect::<Vec<_>>()
108            .join(" ")
109    }
110}
111
112/// Build a hardened QEMU command for a VM definition.
113pub fn build_command(
114    config: &VmConfig,
115    host: &HostCapabilities,
116    files: &RuntimeFiles,
117) -> Result<CommandSpec> {
118    config.validate()?;
119    if !config.disk.path.is_file() {
120        bail!("guest disk {} does not exist", config.disk.path.display());
121    }
122    if let Some(media) = &config.install_media
123        && !media.is_file()
124    {
125        bail!("installation media {} does not exist", media.display());
126    }
127
128    let accelerator = match config.acceleration {
129        Acceleration::Auto | Acceleration::Kvm if host.kvm_available => "kvm",
130        Acceleration::Auto | Acceleration::Tcg => "tcg",
131        Acceleration::Kvm => bail!("KVM acceleration was requested but /dev/kvm is unavailable"),
132    };
133    let cpu = if accelerator == "kvm" { "host" } else { "max" };
134    let mut args = Vec::<OsString>::new();
135    if config.software_tpm2 {
136        push_pair(
137            &mut args,
138            "-chardev",
139            qemu_path_option("socket,id=chrtpm,path=", &files.tpm_socket, ""),
140        );
141        push_pair(&mut args, "-tpmdev", "emulator,id=tpm0,chardev=chrtpm");
142        push_pair(&mut args, "-device", "tpm-tis,tpmdev=tpm0");
143    }
144    push_pair(
145        &mut args,
146        "-name",
147        format!("{},process=knottvm", config.name),
148    );
149    let machine = if config.firmware == Firmware::UefiSecure {
150        format!("q35,accel={accelerator},smm=on")
151    } else {
152        format!("q35,accel={accelerator}")
153    };
154    push_pair(&mut args, "-machine", machine);
155    push_pair(&mut args, "-cpu", cpu);
156    push_pair(&mut args, "-m", config.memory_mib.to_string());
157    push_pair(
158        &mut args,
159        "-smp",
160        format!(
161            "cpus={},sockets=1,cores={},threads=1",
162            config.vcpus, config.vcpus
163        ),
164    );
165    args.extend(["-nodefaults".into(), "-no-user-config".into()]);
166    push_pair(&mut args, "-sandbox", "on");
167    push_pair(&mut args, "-rtc", "base=utc,clock=host,driftfix=slew");
168    push_pair(&mut args, "-boot", "menu=on,strict=on");
169
170    if config.firmware.uses_uefi() {
171        let code = match config.firmware {
172            Firmware::Uefi => host
173                .uefi_code
174                .as_ref()
175                .context("UEFI was requested but no OVMF code image was found")?,
176            Firmware::UefiSecure => host.uefi_secure_code.as_ref().context(
177                "secure UEFI was requested but no SMM-capable OVMF Secure Boot image was found",
178            )?,
179            Firmware::Bios => unreachable!(),
180        };
181        if !files.uefi_vars.is_file() {
182            bail!(
183                "writable UEFI variables {} do not exist",
184                files.uefi_vars.display()
185            );
186        }
187        push_pair(
188            &mut args,
189            "-drive",
190            qemu_path_option("if=pflash,format=raw,unit=0,readonly=on,file=", code, ""),
191        );
192        push_pair(
193            &mut args,
194            "-drive",
195            qemu_path_option("if=pflash,format=raw,unit=1,file=", &files.uefi_vars, ""),
196        );
197        if config.firmware == Firmware::UefiSecure {
198            push_pair(
199                &mut args,
200                "-global",
201                "driver=cfi.pflash01,property=secure,value=on",
202            );
203        }
204    }
205
206    let disk_file = json!({
207        "driver": "file",
208        "filename": config.disk.path,
209        "node-name": "system-file",
210        "cache": { "direct": true, "no-flush": false }
211    });
212    let disk_format = json!({
213        "driver": config.disk.format.qemu_driver(),
214        "file": "system-file",
215        "node-name": "system-disk",
216        "discard": "unmap"
217    });
218    push_pair(&mut args, "-blockdev", disk_file.to_string());
219    push_pair(&mut args, "-blockdev", disk_format.to_string());
220    push_pair(
221        &mut args,
222        "-device",
223        "virtio-blk-pci,drive=system-disk,bootindex=1",
224    );
225
226    if let Some(media) = &config.install_media {
227        let media_file = json!({
228            "driver": "file",
229            "filename": media,
230            "node-name": "install-file",
231            "read-only": true
232        });
233        let media_format = json!({
234            "driver": "raw",
235            "file": "install-file",
236            "node-name": "install-media",
237            "read-only": true
238        });
239        push_pair(&mut args, "-blockdev", media_file.to_string());
240        push_pair(&mut args, "-blockdev", media_format.to_string());
241        push_pair(&mut args, "-device", "virtio-scsi-pci,id=scsi0");
242        push_pair(
243            &mut args,
244            "-device",
245            "scsi-cd,drive=install-media,bus=scsi0.0,bootindex=2",
246        );
247    }
248
249    if config.network.mode == NetworkMode::User {
250        let mac = config
251            .network
252            .mac
253            .clone()
254            .unwrap_or_else(|| deterministic_mac(&config.name));
255        let mut netdev = "user,id=net0,restrict=off,ipv6=on".to_owned();
256        for forward in &config.network.forwards {
257            write!(
258                netdev,
259                ",hostfwd={}:{}:{}-:{}",
260                forward.protocol.qemu_name(),
261                forward.host_address,
262                forward.host_port,
263                forward.guest_port
264            )
265            .expect("writing to a String cannot fail");
266        }
267        push_pair(&mut args, "-netdev", netdev);
268        push_pair(
269            &mut args,
270            "-device",
271            format!("virtio-net-pci,netdev=net0,mac={mac}"),
272        );
273    }
274
275    push_pair(
276        &mut args,
277        "-object",
278        "rng-random,id=rng0,filename=/dev/urandom",
279    );
280    push_pair(&mut args, "-device", "virtio-rng-pci,rng=rng0");
281    push_pair(&mut args, "-device", "virtio-balloon-pci");
282    push_pair(
283        &mut args,
284        "-device",
285        config.generation_id.map_or_else(
286            || "vmgenid".to_owned(),
287            |generation_id| format!("vmgenid,guid={generation_id}"),
288        ),
289    );
290    if config.audio == AudioMode::Pipewire {
291        push_pair(&mut args, "-audiodev", "pipewire,id=audio0");
292        push_pair(&mut args, "-device", "ich9-intel-hda,id=hda0");
293        push_pair(&mut args, "-device", "hda-duplex,audiodev=audio0");
294    }
295    let mut shares = config.shares.iter().collect::<Vec<_>>();
296    shares.sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
297    for (index, share) in shares.into_iter().enumerate() {
298        if !share.path.is_dir() {
299            bail!(
300                "shared host directory {} does not exist",
301                share.path.display()
302            );
303        }
304        let id = format!("share{index}");
305        let suffix = if share.read_only {
306            ",security_model=mapped-xattr,readonly=on"
307        } else {
308            ",security_model=mapped-xattr,readonly=off"
309        };
310        push_pair(
311            &mut args,
312            "-fsdev",
313            qemu_path_option(&format!("local,id={id},path="), &share.path, suffix),
314        );
315        push_pair(
316            &mut args,
317            "-device",
318            format!("virtio-9p-pci,fsdev={id},mount_tag={}", share.tag),
319        );
320    }
321    push_pair(&mut args, "-device", "qemu-xhci,id=usb,p2=15,p3=15");
322    let pointer_device = match config.pointer_device {
323        PointerDevice::Tablet => "usb-tablet,bus=usb.0",
324        PointerDevice::Mouse => "usb-mouse,bus=usb.0",
325    };
326    push_pair(&mut args, "-device", pointer_device);
327    let mut usb_devices = config.usb_devices.iter().collect::<Vec<_>>();
328    usb_devices.sort_unstable_by_key(|device| (device.bus, device.address));
329    for device in usb_devices {
330        push_pair(
331            &mut args,
332            "-device",
333            format!(
334                "usb-host,id=usb-host-b{:03}-a{:03},bus=usb.0,hostbus={},hostaddr={}",
335                device.bus, device.address, device.bus, device.address
336            ),
337        );
338    }
339    push_pair(&mut args, "-device", "virtio-serial-pci,id=virtio-serial0");
340    push_pair(
341        &mut args,
342        "-chardev",
343        qemu_path_option(
344            "socket,id=qga0,path=",
345            &files.agent_socket,
346            ",server=on,wait=off",
347        ),
348    );
349    push_pair(
350        &mut args,
351        "-device",
352        "virtserialport,bus=virtio-serial0.0,chardev=qga0,name=org.qemu.guest_agent.0",
353    );
354    push_pair(&mut args, "-device", "virtio-vga");
355    push_pair(&mut args, "-display", "none");
356    push_pair(
357        &mut args,
358        "-vnc",
359        qemu_path_option("unix:", &files.display_socket, ",share=ignore"),
360    );
361    push_pair(
362        &mut args,
363        "-qmp",
364        qemu_path_option("unix:", &files.qmp_socket, ",server=on,wait=off"),
365    );
366    push_pair(&mut args, "-pidfile", files.pid_file.as_os_str());
367    args.push("-daemonize".into());
368
369    Ok(CommandSpec {
370        program: host.qemu.clone(),
371        args,
372    })
373}
374
375/// Build the optional software TPM daemon command for an enabled VM.
376pub fn build_swtpm_command(
377    config: &VmConfig,
378    host: &HostCapabilities,
379    files: &RuntimeFiles,
380) -> Result<Option<CommandSpec>> {
381    if !config.software_tpm2 {
382        return Ok(None);
383    }
384    let program = host
385        .swtpm
386        .as_ref()
387        .context("software TPM 2 was requested but swtpm was not found in PATH")?
388        .clone();
389    let _swtpm_ioctl = host
390        .swtpm_ioctl
391        .as_ref()
392        .context("software TPM 2 was requested but swtpm_ioctl was not found in PATH")?;
393    let server = swtpm_path_option("type=unixio,path=", &files.tpm_socket, ",mode=0600");
394    let control = swtpm_path_option(
395        "type=unixio,path=",
396        &files.tpm_control_socket,
397        ",mode=0600,terminate",
398    );
399    let state = swtpm_path_option("dir=", &files.tpm_state_dir, ",mode=0600,fsync");
400    Ok(Some(CommandSpec {
401        program,
402        args: vec![
403            "socket".into(),
404            "--server".into(),
405            server,
406            "--ctrl".into(),
407            control,
408            "--tpmstate".into(),
409            state,
410            "--pid".into(),
411            swtpm_path_option("file=", &files.swtpm_pid_file, ""),
412            "--flags".into(),
413            "not-need-init".into(),
414            "--tpm2".into(),
415            "--daemon".into(),
416        ],
417    }))
418}
419
420fn swtpm_path_option(prefix: &str, path: &Path, suffix: &str) -> OsString {
421    let mut value = Vec::with_capacity(prefix.len() + path.as_os_str().len() + suffix.len());
422    value.extend(prefix.as_bytes());
423    for &byte in path.as_os_str().as_bytes() {
424        value.push(byte);
425        if byte == b',' {
426            value.push(byte);
427        }
428    }
429    value.extend(suffix.as_bytes());
430    OsString::from_vec(value)
431}
432
433/// Copy the distribution's UEFI variable template for a new VM.
434pub fn prepare_uefi_vars(
435    host: &HostCapabilities,
436    firmware: Firmware,
437    destination: &Path,
438) -> Result<()> {
439    let template = match firmware {
440        Firmware::Uefi => host
441            .uefi_vars
442            .as_ref()
443            .context("no OVMF variable template was found")?,
444        Firmware::UefiSecure => host
445            .uefi_secure_vars
446            .as_ref()
447            .context("no variable template matching the Secure Boot OVMF image was found")?,
448        Firmware::Bios => bail!("legacy BIOS does not use UEFI variable storage"),
449    };
450    let template_metadata = fs::metadata(template)
451        .with_context(|| format!("failed to inspect UEFI template {}", template.display()))?;
452    match fs::symlink_metadata(destination) {
453        Ok(metadata) => {
454            if !metadata.is_file() || metadata.len() != template_metadata.len() {
455                bail!(
456                    "existing UEFI variables {} are not a regular {}-byte image",
457                    destination.display(),
458                    template_metadata.len()
459                );
460            }
461            return Ok(());
462        }
463        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
464        Err(error) => return Err(error.into()),
465    }
466    let temporary = destination.with_extension(format!("tmp-{}", std::process::id()));
467    let result = (|| {
468        let mut source = fs::File::open(template)?;
469        let mut target = OpenOptions::new()
470            .write(true)
471            .create_new(true)
472            .open(&temporary)?;
473        io::copy(&mut source, &mut target)?;
474        target.sync_all()?;
475        if fs::symlink_metadata(destination).is_ok() {
476            bail!(
477                "UEFI variables {} appeared during creation",
478                destination.display()
479            );
480        }
481        fs::rename(&temporary, destination)?;
482        Ok(())
483    })();
484    if result.is_err() {
485        let _ = fs::remove_file(&temporary);
486    }
487    result.with_context(|| {
488        format!(
489            "failed to copy UEFI variables from {} to {}",
490            template.display(),
491            destination.display()
492        )
493    })?;
494    Ok(())
495}
496
497fn push_pair(args: &mut Vec<OsString>, option: impl Into<OsString>, value: impl Into<OsString>) {
498    args.push(option.into());
499    args.push(value.into());
500}
501
502fn deterministic_mac(name: &str) -> String {
503    let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
504        (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
505    });
506    format!(
507        "52:54:00:{:02x}:{:02x}:{:02x}",
508        (hash >> 16) & 0xff,
509        (hash >> 8) & 0xff,
510        hash & 0xff
511    )
512}
513
514fn qemu_path_option(prefix: &str, path: &Path, suffix: &str) -> OsString {
515    let mut value = Vec::with_capacity(prefix.len() + path.as_os_str().len() + suffix.len());
516    value.extend(prefix.as_bytes());
517    for &byte in path.as_os_str().as_bytes() {
518        value.push(byte);
519        if byte == b',' {
520            value.push(byte);
521        }
522    }
523    value.extend(suffix.as_bytes());
524    OsString::from_vec(value)
525}
526
527fn find_executable(name: &str) -> Option<PathBuf> {
528    let path = env::var_os("PATH")?;
529    env::split_paths(&path)
530        .map(|directory| directory.join(name))
531        .find(|candidate| candidate.is_file())
532}
533
534fn discover_uefi() -> (Option<PathBuf>, Option<PathBuf>) {
535    const CANDIDATES: &[(&str, &str)] = &[
536        (
537            "/usr/share/edk2/x64/OVMF_CODE.4m.fd",
538            "/usr/share/edk2/x64/OVMF_VARS.4m.fd",
539        ),
540        (
541            "/usr/share/edk2/ovmf/OVMF_CODE.fd",
542            "/usr/share/edk2/ovmf/OVMF_VARS.fd",
543        ),
544        (
545            "/usr/share/OVMF/OVMF_CODE_4M.fd",
546            "/usr/share/OVMF/OVMF_VARS_4M.fd",
547        ),
548        (
549            "/usr/share/OVMF/OVMF_CODE.fd",
550            "/usr/share/OVMF/OVMF_VARS.fd",
551        ),
552        (
553            "/usr/share/qemu/OVMF_CODE.fd",
554            "/usr/share/qemu/OVMF_VARS.fd",
555        ),
556    ];
557    CANDIDATES
558        .iter()
559        .find(|(code, vars)| Path::new(code).is_file() && Path::new(vars).is_file())
560        .map_or((None, None), |(code, vars)| {
561            (Some(PathBuf::from(code)), Some(PathBuf::from(vars)))
562        })
563}
564
565fn discover_secure_uefi() -> (Option<PathBuf>, Option<PathBuf>) {
566    const CANDIDATES: &[(&str, &str)] = &[
567        (
568            "/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd",
569            "/usr/share/edk2/x64/OVMF_VARS.4m.fd",
570        ),
571        (
572            "/usr/share/edk2/ovmf/OVMF_CODE.secboot.4m.fd",
573            "/usr/share/edk2/ovmf/OVMF_VARS.4m.fd",
574        ),
575        (
576            "/usr/share/edk2/ovmf/OVMF_CODE.secboot.fd",
577            "/usr/share/edk2/ovmf/OVMF_VARS.fd",
578        ),
579        (
580            "/usr/share/OVMF/OVMF_CODE_4M.secboot.fd",
581            "/usr/share/OVMF/OVMF_VARS_4M.fd",
582        ),
583        (
584            "/usr/share/OVMF/OVMF_CODE.secboot.fd",
585            "/usr/share/OVMF/OVMF_VARS.fd",
586        ),
587        (
588            "/usr/share/qemu/OVMF_CODE.secboot.fd",
589            "/usr/share/qemu/OVMF_VARS.fd",
590        ),
591    ];
592    CANDIDATES
593        .iter()
594        .find(|(code, vars)| Path::new(code).is_file() && Path::new(vars).is_file())
595        .map_or((None, None), |(code, vars)| {
596            (Some(PathBuf::from(code)), Some(PathBuf::from(vars)))
597        })
598}
599
600fn shell_quote(value: &OsStr) -> String {
601    let value = value.to_string_lossy();
602    if value
603        .chars()
604        .all(|character| character.is_ascii_alphanumeric() || "_@%+=:,./-".contains(character))
605    {
606        value.into_owned()
607    } else {
608        format!("'{}'", value.replace('\'', "'\\''"))
609    }
610}
611
612#[cfg(test)]
613mod tests {
614    use super::{CommandSpec, HostCapabilities, RuntimeFiles, build_command, build_swtpm_command};
615    use crate::config::{
616        Acceleration, AudioMode, DirectoryShare, Firmware, NetworkProtocol, PointerDevice,
617        PortForward, UsbHostDevice, VmConfig,
618    };
619    use std::ffi::OsString;
620    use std::fs;
621    use std::net::Ipv4Addr;
622    use std::path::PathBuf;
623    use tempfile::tempdir;
624
625    #[test]
626    fn command_uses_private_unix_control_and_display_sockets() {
627        let root = tempdir().unwrap();
628        let comma_root = root.path().join("path,with,commas");
629        fs::create_dir(&comma_root).unwrap();
630        let disk = comma_root.join("disk with spaces.qcow2");
631        let vars = comma_root.join("vars.fd");
632        let code = root.path().join("code.fd");
633        let secure_code = root.path().join("secure-code.fd");
634        let writable_share = root.path().join("writable-share");
635        fs::write(&disk, []).unwrap();
636        fs::write(&vars, []).unwrap();
637        fs::write(&code, []).unwrap();
638        fs::write(&secure_code, []).unwrap();
639        fs::create_dir(&writable_share).unwrap();
640        let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
641        config.acceleration = Acceleration::Tcg;
642        config.audio = AudioMode::Pipewire;
643        config.network.forwards.push(PortForward {
644            protocol: NetworkProtocol::Tcp,
645            host_address: Ipv4Addr::LOCALHOST,
646            host_port: 2222,
647            guest_port: 22,
648        });
649        config.usb_devices.extend([
650            UsbHostDevice { bus: 2, address: 9 },
651            UsbHostDevice { bus: 1, address: 4 },
652        ]);
653        config.shares.push(DirectoryShare {
654            tag: "host-data".to_owned(),
655            path: comma_root.clone(),
656            read_only: true,
657        });
658        config.shares.push(DirectoryShare {
659            tag: "writable".to_owned(),
660            path: writable_share,
661            read_only: false,
662        });
663        let host = HostCapabilities {
664            qemu: PathBuf::from("/usr/bin/qemu-system-x86_64"),
665            qemu_img: PathBuf::from("/usr/bin/qemu-img"),
666            swtpm: None,
667            swtpm_ioctl: None,
668            kvm_available: false,
669            uefi_code: Some(code),
670            uefi_secure_code: Some(secure_code),
671            uefi_vars: Some(vars.clone()),
672            uefi_secure_vars: Some(vars.clone()),
673        };
674        let files = RuntimeFiles {
675            qmp_socket: root.path().join("qmp.sock"),
676            display_socket: root.path().join("display.sock"),
677            agent_socket: root.path().join("agent.sock"),
678            pid_file: root.path().join("qemu.pid"),
679            uefi_vars: vars,
680            tpm_socket: root.path().join("tpm.sock"),
681            tpm_control_socket: root.path().join("tpm-ctrl.sock"),
682            swtpm_pid_file: root.path().join("swtpm.pid"),
683            tpm_state_dir: root.path().join("tpm-state"),
684        };
685        let command = build_command(&config, &host, &files).unwrap();
686        assert!(command.args.contains(&OsString::from("-daemonize")));
687        assert!(
688            command
689                .args
690                .windows(2)
691                .any(|pair| { pair[0] == "-device" && pair[1] == "virtio-vga" })
692        );
693        assert!(
694            command
695                .args
696                .windows(2)
697                .any(|pair| pair[0] == "-device" && pair[1] == "usb-tablet,bus=usb.0")
698        );
699        let mut relative_config = config.clone();
700        relative_config.pointer_device = PointerDevice::Mouse;
701        let relative_command = build_command(&relative_config, &host, &files).unwrap();
702        assert!(
703            relative_command
704                .args
705                .windows(2)
706                .any(|pair| pair[0] == "-device" && pair[1] == "usb-mouse,bus=usb.0")
707        );
708        assert!(
709            !relative_command
710                .args
711                .windows(2)
712                .any(|pair| pair[0] == "-device" && pair[1] == "usb-tablet,bus=usb.0")
713        );
714        assert!(command.args.windows(2).any(|pair| {
715            pair[0] == "-device"
716                && pair[1]
717                    == "virtserialport,bus=virtio-serial0.0,chardev=qga0,name=org.qemu.guest_agent.0"
718        }));
719        assert!(command.args.windows(2).any(|pair| {
720            pair[0] == "-fsdev"
721                && pair[1]
722                    .to_string_lossy()
723                    .contains("path,,with,,commas,security_model=mapped-xattr,readonly=on")
724        }));
725        assert!(command.args.windows(2).any(|pair| {
726            pair[0] == "-device" && pair[1] == "virtio-9p-pci,fsdev=share0,mount_tag=host-data"
727        }));
728        assert!(command.args.windows(2).any(|pair| {
729            pair[0] == "-fsdev"
730                && pair[1].to_string_lossy().contains("local,id=share1,path=")
731                && pair[1].to_string_lossy().ends_with("readonly=off")
732        }));
733        assert!(command.args.windows(2).any(|pair| {
734            pair[0] == "-device" && pair[1] == "virtio-9p-pci,fsdev=share1,mount_tag=writable"
735        }));
736        assert!(
737            command
738                .args
739                .windows(2)
740                .any(|pair| { pair[0] == "-audiodev" && pair[1] == "pipewire,id=audio0" })
741        );
742        assert!(command.args.windows(2).any(|pair| {
743            pair[0] == "-device" && pair[1].to_string_lossy().starts_with("vmgenid,guid=")
744        }));
745        assert!(
746            command.args.windows(2).any(|pair| {
747                pair[0] == "-qmp" && pair[1].to_string_lossy().starts_with("unix:")
748            })
749        );
750        assert!(
751            command.args.windows(2).any(|pair| {
752                pair[0] == "-vnc" && pair[1].to_string_lossy().starts_with("unix:")
753            })
754        );
755        assert!(command.args.windows(2).any(|pair| {
756            pair[0] == "-drive" && pair[1].to_string_lossy().contains("path,,with,,commas")
757        }));
758        assert!(command.args.windows(2).any(|pair| {
759            pair[0] == "-netdev"
760                && pair[1]
761                    .to_string_lossy()
762                    .contains("hostfwd=tcp:127.0.0.1:2222-:22")
763        }));
764        let usb_devices = command
765            .args
766            .windows(2)
767            .filter(|pair| {
768                pair[0] == "-device" && pair[1].to_string_lossy().starts_with("usb-host,")
769            })
770            .map(|pair| pair[1].to_string_lossy().into_owned())
771            .collect::<Vec<_>>();
772        assert_eq!(
773            usb_devices,
774            [
775                "usb-host,id=usb-host-b001-a004,bus=usb.0,hostbus=1,hostaddr=4",
776                "usb-host,id=usb-host-b002-a009,bus=usb.0,hostbus=2,hostaddr=9",
777            ]
778        );
779        assert!(command.args.iter().any(|argument| {
780            argument
781                .to_string_lossy()
782                .contains("disk with spaces.qcow2")
783        }));
784
785        config.firmware = Firmware::UefiSecure;
786        let command = build_command(&config, &host, &files).unwrap();
787        assert!(
788            command.args.windows(2).any(|pair| {
789                pair[0] == "-machine" && pair[1].to_string_lossy().contains("smm=on")
790            })
791        );
792        assert!(command.args.windows(2).any(|pair| {
793            pair[0] == "-global" && pair[1] == "driver=cfi.pflash01,property=secure,value=on"
794        }));
795        assert!(command.args.windows(2).any(|pair| {
796            pair[0] == "-drive" && pair[1].to_string_lossy().contains("secure-code.fd")
797        }));
798    }
799
800    #[test]
801    fn display_quotes_diagnostic_arguments() {
802        let command = CommandSpec {
803            program: PathBuf::from("qemu"),
804            args: vec![OsString::from("a b")],
805        };
806        assert_eq!(command.display(), "qemu 'a b'");
807    }
808
809    #[test]
810    fn software_tpm_is_opt_in_and_builds_swtpm_and_qemu_commands() {
811        let root = tempdir().unwrap();
812        let disk = root.path().join("disk.qcow2");
813        fs::write(&disk, []).unwrap();
814        let mut config = VmConfig::new("test".to_owned(), disk, None);
815        config.firmware = Firmware::Bios;
816        let files = RuntimeFiles {
817            qmp_socket: root.path().join("qmp.sock"),
818            display_socket: root.path().join("display.sock"),
819            agent_socket: root.path().join("agent.sock"),
820            pid_file: root.path().join("qemu.pid"),
821            uefi_vars: root.path().join("uefi-vars.fd"),
822            tpm_socket: root.path().join("tpm.sock"),
823            tpm_control_socket: root.path().join("tpm-ctrl.sock"),
824            swtpm_pid_file: root.path().join("swtpm.pid"),
825            tpm_state_dir: root.path().join("tpm-state"),
826        };
827        let host = HostCapabilities {
828            qemu: PathBuf::from("qemu-system-x86_64"),
829            qemu_img: PathBuf::from("qemu-img"),
830            swtpm: Some(PathBuf::from("/usr/bin/swtpm")),
831            swtpm_ioctl: Some(PathBuf::from("/usr/bin/swtpm_ioctl")),
832            kvm_available: false,
833            uefi_code: None,
834            uefi_secure_code: None,
835            uefi_vars: None,
836            uefi_secure_vars: None,
837        };
838
839        assert!(
840            build_swtpm_command(&config, &host, &files)
841                .unwrap()
842                .is_none()
843        );
844        let disabled = build_command(&config, &host, &files).unwrap();
845        assert!(!disabled.args.iter().any(|arg| arg == "-tpmdev"));
846
847        config.software_tpm2 = true;
848        let qemu = build_command(&config, &host, &files).unwrap();
849        assert!(qemu.args.windows(2).any(|pair| {
850            pair[0] == "-chardev" && pair[1].to_string_lossy().contains("socket,id=chrtpm,path=")
851        }));
852        assert!(
853            qemu.args.windows(2).any(|pair| {
854                pair[0] == "-tpmdev" && pair[1] == "emulator,id=tpm0,chardev=chrtpm"
855            })
856        );
857        assert!(
858            qemu.args
859                .windows(2)
860                .any(|pair| { pair[0] == "-device" && pair[1] == "tpm-tis,tpmdev=tpm0" })
861        );
862
863        let swtpm = build_swtpm_command(&config, &host, &files)
864            .unwrap()
865            .unwrap();
866        assert_eq!(swtpm.program, PathBuf::from("/usr/bin/swtpm"));
867        assert!(swtpm.args.iter().any(|arg| arg == "--tpm2"));
868        assert!(swtpm.args.iter().any(|arg| arg == "--daemon"));
869        assert!(
870            swtpm
871                .args
872                .iter()
873                .any(|arg| { arg.to_string_lossy().contains("mode=0600,fsync") })
874        );
875
876        let missing_swtpm = HostCapabilities {
877            swtpm: None,
878            ..host
879        };
880        assert!(build_swtpm_command(&config, &missing_swtpm, &files).is_err());
881    }
882}