use std::env;
use std::ffi::{OsStr, OsString};
use std::fmt::Write as _;
use std::fs::{self, OpenOptions};
use std::io;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde_json::json;
use crate::config::{Acceleration, AudioMode, Firmware, NetworkMode, PointerDevice, VmConfig};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostCapabilities {
pub qemu: PathBuf,
pub qemu_img: PathBuf,
pub swtpm: Option<PathBuf>,
pub swtpm_ioctl: Option<PathBuf>,
pub kvm_available: bool,
pub uefi_code: Option<PathBuf>,
pub uefi_secure_code: Option<PathBuf>,
pub uefi_vars: Option<PathBuf>,
pub uefi_secure_vars: Option<PathBuf>,
}
impl HostCapabilities {
pub fn probe() -> Result<Self> {
let qemu = find_executable("qemu-system-x86_64")
.context("qemu-system-x86_64 was not found in PATH")?;
let qemu_img = find_executable("qemu-img").context("qemu-img was not found in PATH")?;
let swtpm = find_executable("swtpm");
let swtpm_ioctl = find_executable("swtpm_ioctl");
let kvm_available = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/kvm")
.is_ok();
let (uefi_code, uefi_vars) = discover_uefi();
let (uefi_secure_code, uefi_secure_vars) = discover_secure_uefi();
Ok(Self {
qemu,
qemu_img,
swtpm,
swtpm_ioctl,
kvm_available,
uefi_code,
uefi_secure_code,
uefi_vars,
uefi_secure_vars,
})
}
}
#[derive(Debug, Clone)]
pub struct RuntimeFiles {
pub qmp_socket: PathBuf,
pub display_socket: PathBuf,
pub agent_socket: PathBuf,
pub pid_file: PathBuf,
pub uefi_vars: PathBuf,
pub tpm_socket: PathBuf,
pub tpm_control_socket: PathBuf,
pub swtpm_pid_file: PathBuf,
pub tpm_state_dir: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandSpec {
pub program: PathBuf,
pub args: Vec<OsString>,
}
impl CommandSpec {
#[must_use]
pub fn display(&self) -> String {
std::iter::once(self.program.as_os_str())
.chain(self.args.iter().map(OsString::as_os_str))
.map(shell_quote)
.collect::<Vec<_>>()
.join(" ")
}
}
pub fn build_command(
config: &VmConfig,
host: &HostCapabilities,
files: &RuntimeFiles,
) -> Result<CommandSpec> {
config.validate()?;
if !config.disk.path.is_file() {
bail!("guest disk {} does not exist", config.disk.path.display());
}
if let Some(media) = &config.install_media
&& !media.is_file()
{
bail!("installation media {} does not exist", media.display());
}
let accelerator = match config.acceleration {
Acceleration::Auto | Acceleration::Kvm if host.kvm_available => "kvm",
Acceleration::Auto | Acceleration::Tcg => "tcg",
Acceleration::Kvm => bail!("KVM acceleration was requested but /dev/kvm is unavailable"),
};
let cpu = if accelerator == "kvm" { "host" } else { "max" };
let mut args = Vec::<OsString>::new();
if config.software_tpm2 {
push_pair(
&mut args,
"-chardev",
qemu_path_option("socket,id=chrtpm,path=", &files.tpm_socket, ""),
);
push_pair(&mut args, "-tpmdev", "emulator,id=tpm0,chardev=chrtpm");
push_pair(&mut args, "-device", "tpm-tis,tpmdev=tpm0");
}
push_pair(
&mut args,
"-name",
format!("{},process=knottvm", config.name),
);
let machine = if config.firmware == Firmware::UefiSecure {
format!("q35,accel={accelerator},smm=on")
} else {
format!("q35,accel={accelerator}")
};
push_pair(&mut args, "-machine", machine);
push_pair(&mut args, "-cpu", cpu);
push_pair(&mut args, "-m", config.memory_mib.to_string());
push_pair(
&mut args,
"-smp",
format!(
"cpus={},sockets=1,cores={},threads=1",
config.vcpus, config.vcpus
),
);
args.extend(["-nodefaults".into(), "-no-user-config".into()]);
push_pair(&mut args, "-sandbox", "on");
push_pair(&mut args, "-rtc", "base=utc,clock=host,driftfix=slew");
push_pair(&mut args, "-boot", "menu=on,strict=on");
if config.firmware.uses_uefi() {
let code = match config.firmware {
Firmware::Uefi => host
.uefi_code
.as_ref()
.context("UEFI was requested but no OVMF code image was found")?,
Firmware::UefiSecure => host.uefi_secure_code.as_ref().context(
"secure UEFI was requested but no SMM-capable OVMF Secure Boot image was found",
)?,
Firmware::Bios => unreachable!(),
};
if !files.uefi_vars.is_file() {
bail!(
"writable UEFI variables {} do not exist",
files.uefi_vars.display()
);
}
push_pair(
&mut args,
"-drive",
qemu_path_option("if=pflash,format=raw,unit=0,readonly=on,file=", code, ""),
);
push_pair(
&mut args,
"-drive",
qemu_path_option("if=pflash,format=raw,unit=1,file=", &files.uefi_vars, ""),
);
if config.firmware == Firmware::UefiSecure {
push_pair(
&mut args,
"-global",
"driver=cfi.pflash01,property=secure,value=on",
);
}
}
let disk_file = json!({
"driver": "file",
"filename": config.disk.path,
"node-name": "system-file",
"cache": { "direct": true, "no-flush": false }
});
let disk_format = json!({
"driver": config.disk.format.qemu_driver(),
"file": "system-file",
"node-name": "system-disk",
"discard": "unmap"
});
push_pair(&mut args, "-blockdev", disk_file.to_string());
push_pair(&mut args, "-blockdev", disk_format.to_string());
push_pair(
&mut args,
"-device",
"virtio-blk-pci,drive=system-disk,bootindex=1",
);
if let Some(media) = &config.install_media {
let media_file = json!({
"driver": "file",
"filename": media,
"node-name": "install-file",
"read-only": true
});
let media_format = json!({
"driver": "raw",
"file": "install-file",
"node-name": "install-media",
"read-only": true
});
push_pair(&mut args, "-blockdev", media_file.to_string());
push_pair(&mut args, "-blockdev", media_format.to_string());
push_pair(&mut args, "-device", "virtio-scsi-pci,id=scsi0");
push_pair(
&mut args,
"-device",
"scsi-cd,drive=install-media,bus=scsi0.0,bootindex=2",
);
}
if config.network.mode == NetworkMode::User {
let mac = config
.network
.mac
.clone()
.unwrap_or_else(|| deterministic_mac(&config.name));
let mut netdev = "user,id=net0,restrict=off,ipv6=on".to_owned();
for forward in &config.network.forwards {
write!(
netdev,
",hostfwd={}:{}:{}-:{}",
forward.protocol.qemu_name(),
forward.host_address,
forward.host_port,
forward.guest_port
)
.expect("writing to a String cannot fail");
}
push_pair(&mut args, "-netdev", netdev);
push_pair(
&mut args,
"-device",
format!("virtio-net-pci,netdev=net0,mac={mac}"),
);
}
push_pair(
&mut args,
"-object",
"rng-random,id=rng0,filename=/dev/urandom",
);
push_pair(&mut args, "-device", "virtio-rng-pci,rng=rng0");
push_pair(&mut args, "-device", "virtio-balloon-pci");
push_pair(
&mut args,
"-device",
config.generation_id.map_or_else(
|| "vmgenid".to_owned(),
|generation_id| format!("vmgenid,guid={generation_id}"),
),
);
if config.audio == AudioMode::Pipewire {
push_pair(&mut args, "-audiodev", "pipewire,id=audio0");
push_pair(&mut args, "-device", "ich9-intel-hda,id=hda0");
push_pair(&mut args, "-device", "hda-duplex,audiodev=audio0");
}
let mut shares = config.shares.iter().collect::<Vec<_>>();
shares.sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
for (index, share) in shares.into_iter().enumerate() {
if !share.path.is_dir() {
bail!(
"shared host directory {} does not exist",
share.path.display()
);
}
let id = format!("share{index}");
let suffix = if share.read_only {
",security_model=mapped-xattr,readonly=on"
} else {
",security_model=mapped-xattr,readonly=off"
};
push_pair(
&mut args,
"-fsdev",
qemu_path_option(&format!("local,id={id},path="), &share.path, suffix),
);
push_pair(
&mut args,
"-device",
format!("virtio-9p-pci,fsdev={id},mount_tag={}", share.tag),
);
}
push_pair(&mut args, "-device", "qemu-xhci,id=usb,p2=15,p3=15");
let pointer_device = match config.pointer_device {
PointerDevice::Tablet => "usb-tablet,bus=usb.0",
PointerDevice::Mouse => "usb-mouse,bus=usb.0",
};
push_pair(&mut args, "-device", pointer_device);
let mut usb_devices = config.usb_devices.iter().collect::<Vec<_>>();
usb_devices.sort_unstable_by_key(|device| (device.bus, device.address));
for device in usb_devices {
push_pair(
&mut args,
"-device",
format!(
"usb-host,id=usb-host-b{:03}-a{:03},bus=usb.0,hostbus={},hostaddr={}",
device.bus, device.address, device.bus, device.address
),
);
}
push_pair(&mut args, "-device", "virtio-serial-pci,id=virtio-serial0");
push_pair(
&mut args,
"-chardev",
qemu_path_option(
"socket,id=qga0,path=",
&files.agent_socket,
",server=on,wait=off",
),
);
push_pair(
&mut args,
"-device",
"virtserialport,bus=virtio-serial0.0,chardev=qga0,name=org.qemu.guest_agent.0",
);
push_pair(&mut args, "-device", "virtio-vga");
push_pair(&mut args, "-display", "none");
push_pair(
&mut args,
"-vnc",
qemu_path_option("unix:", &files.display_socket, ",share=ignore"),
);
push_pair(
&mut args,
"-qmp",
qemu_path_option("unix:", &files.qmp_socket, ",server=on,wait=off"),
);
push_pair(&mut args, "-pidfile", files.pid_file.as_os_str());
args.push("-daemonize".into());
Ok(CommandSpec {
program: host.qemu.clone(),
args,
})
}
pub fn build_swtpm_command(
config: &VmConfig,
host: &HostCapabilities,
files: &RuntimeFiles,
) -> Result<Option<CommandSpec>> {
if !config.software_tpm2 {
return Ok(None);
}
let program = host
.swtpm
.as_ref()
.context("software TPM 2 was requested but swtpm was not found in PATH")?
.clone();
let _swtpm_ioctl = host
.swtpm_ioctl
.as_ref()
.context("software TPM 2 was requested but swtpm_ioctl was not found in PATH")?;
let server = swtpm_path_option("type=unixio,path=", &files.tpm_socket, ",mode=0600");
let control = swtpm_path_option(
"type=unixio,path=",
&files.tpm_control_socket,
",mode=0600,terminate",
);
let state = swtpm_path_option("dir=", &files.tpm_state_dir, ",mode=0600,fsync");
Ok(Some(CommandSpec {
program,
args: vec![
"socket".into(),
"--server".into(),
server,
"--ctrl".into(),
control,
"--tpmstate".into(),
state,
"--pid".into(),
swtpm_path_option("file=", &files.swtpm_pid_file, ""),
"--flags".into(),
"not-need-init".into(),
"--tpm2".into(),
"--daemon".into(),
],
}))
}
fn swtpm_path_option(prefix: &str, path: &Path, suffix: &str) -> OsString {
let mut value = Vec::with_capacity(prefix.len() + path.as_os_str().len() + suffix.len());
value.extend(prefix.as_bytes());
for &byte in path.as_os_str().as_bytes() {
value.push(byte);
if byte == b',' {
value.push(byte);
}
}
value.extend(suffix.as_bytes());
OsString::from_vec(value)
}
pub fn prepare_uefi_vars(
host: &HostCapabilities,
firmware: Firmware,
destination: &Path,
) -> Result<()> {
let template = match firmware {
Firmware::Uefi => host
.uefi_vars
.as_ref()
.context("no OVMF variable template was found")?,
Firmware::UefiSecure => host
.uefi_secure_vars
.as_ref()
.context("no variable template matching the Secure Boot OVMF image was found")?,
Firmware::Bios => bail!("legacy BIOS does not use UEFI variable storage"),
};
let template_metadata = fs::metadata(template)
.with_context(|| format!("failed to inspect UEFI template {}", template.display()))?;
match fs::symlink_metadata(destination) {
Ok(metadata) => {
if !metadata.is_file() || metadata.len() != template_metadata.len() {
bail!(
"existing UEFI variables {} are not a regular {}-byte image",
destination.display(),
template_metadata.len()
);
}
return Ok(());
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
let temporary = destination.with_extension(format!("tmp-{}", std::process::id()));
let result = (|| {
let mut source = fs::File::open(template)?;
let mut target = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
io::copy(&mut source, &mut target)?;
target.sync_all()?;
if fs::symlink_metadata(destination).is_ok() {
bail!(
"UEFI variables {} appeared during creation",
destination.display()
);
}
fs::rename(&temporary, destination)?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result.with_context(|| {
format!(
"failed to copy UEFI variables from {} to {}",
template.display(),
destination.display()
)
})?;
Ok(())
}
fn push_pair(args: &mut Vec<OsString>, option: impl Into<OsString>, value: impl Into<OsString>) {
args.push(option.into());
args.push(value.into());
}
fn deterministic_mac(name: &str) -> String {
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
});
format!(
"52:54:00:{:02x}:{:02x}:{:02x}",
(hash >> 16) & 0xff,
(hash >> 8) & 0xff,
hash & 0xff
)
}
fn qemu_path_option(prefix: &str, path: &Path, suffix: &str) -> OsString {
let mut value = Vec::with_capacity(prefix.len() + path.as_os_str().len() + suffix.len());
value.extend(prefix.as_bytes());
for &byte in path.as_os_str().as_bytes() {
value.push(byte);
if byte == b',' {
value.push(byte);
}
}
value.extend(suffix.as_bytes());
OsString::from_vec(value)
}
fn find_executable(name: &str) -> Option<PathBuf> {
let path = env::var_os("PATH")?;
env::split_paths(&path)
.map(|directory| directory.join(name))
.find(|candidate| candidate.is_file())
}
fn discover_uefi() -> (Option<PathBuf>, Option<PathBuf>) {
const CANDIDATES: &[(&str, &str)] = &[
(
"/usr/share/edk2/x64/OVMF_CODE.4m.fd",
"/usr/share/edk2/x64/OVMF_VARS.4m.fd",
),
(
"/usr/share/edk2/ovmf/OVMF_CODE.fd",
"/usr/share/edk2/ovmf/OVMF_VARS.fd",
),
(
"/usr/share/OVMF/OVMF_CODE_4M.fd",
"/usr/share/OVMF/OVMF_VARS_4M.fd",
),
(
"/usr/share/OVMF/OVMF_CODE.fd",
"/usr/share/OVMF/OVMF_VARS.fd",
),
(
"/usr/share/qemu/OVMF_CODE.fd",
"/usr/share/qemu/OVMF_VARS.fd",
),
];
CANDIDATES
.iter()
.find(|(code, vars)| Path::new(code).is_file() && Path::new(vars).is_file())
.map_or((None, None), |(code, vars)| {
(Some(PathBuf::from(code)), Some(PathBuf::from(vars)))
})
}
fn discover_secure_uefi() -> (Option<PathBuf>, Option<PathBuf>) {
const CANDIDATES: &[(&str, &str)] = &[
(
"/usr/share/edk2/x64/OVMF_CODE.secboot.4m.fd",
"/usr/share/edk2/x64/OVMF_VARS.4m.fd",
),
(
"/usr/share/edk2/ovmf/OVMF_CODE.secboot.4m.fd",
"/usr/share/edk2/ovmf/OVMF_VARS.4m.fd",
),
(
"/usr/share/edk2/ovmf/OVMF_CODE.secboot.fd",
"/usr/share/edk2/ovmf/OVMF_VARS.fd",
),
(
"/usr/share/OVMF/OVMF_CODE_4M.secboot.fd",
"/usr/share/OVMF/OVMF_VARS_4M.fd",
),
(
"/usr/share/OVMF/OVMF_CODE.secboot.fd",
"/usr/share/OVMF/OVMF_VARS.fd",
),
(
"/usr/share/qemu/OVMF_CODE.secboot.fd",
"/usr/share/qemu/OVMF_VARS.fd",
),
];
CANDIDATES
.iter()
.find(|(code, vars)| Path::new(code).is_file() && Path::new(vars).is_file())
.map_or((None, None), |(code, vars)| {
(Some(PathBuf::from(code)), Some(PathBuf::from(vars)))
})
}
fn shell_quote(value: &OsStr) -> String {
let value = value.to_string_lossy();
if value
.chars()
.all(|character| character.is_ascii_alphanumeric() || "_@%+=:,./-".contains(character))
{
value.into_owned()
} else {
format!("'{}'", value.replace('\'', "'\\''"))
}
}
#[cfg(test)]
mod tests {
use super::{CommandSpec, HostCapabilities, RuntimeFiles, build_command, build_swtpm_command};
use crate::config::{
Acceleration, AudioMode, DirectoryShare, Firmware, NetworkProtocol, PointerDevice,
PortForward, UsbHostDevice, VmConfig,
};
use std::ffi::OsString;
use std::fs;
use std::net::Ipv4Addr;
use std::path::PathBuf;
use tempfile::tempdir;
#[test]
fn command_uses_private_unix_control_and_display_sockets() {
let root = tempdir().unwrap();
let comma_root = root.path().join("path,with,commas");
fs::create_dir(&comma_root).unwrap();
let disk = comma_root.join("disk with spaces.qcow2");
let vars = comma_root.join("vars.fd");
let code = root.path().join("code.fd");
let secure_code = root.path().join("secure-code.fd");
let writable_share = root.path().join("writable-share");
fs::write(&disk, []).unwrap();
fs::write(&vars, []).unwrap();
fs::write(&code, []).unwrap();
fs::write(&secure_code, []).unwrap();
fs::create_dir(&writable_share).unwrap();
let mut config = VmConfig::new("test".to_owned(), disk.clone(), None);
config.acceleration = Acceleration::Tcg;
config.audio = AudioMode::Pipewire;
config.network.forwards.push(PortForward {
protocol: NetworkProtocol::Tcp,
host_address: Ipv4Addr::LOCALHOST,
host_port: 2222,
guest_port: 22,
});
config.usb_devices.extend([
UsbHostDevice { bus: 2, address: 9 },
UsbHostDevice { bus: 1, address: 4 },
]);
config.shares.push(DirectoryShare {
tag: "host-data".to_owned(),
path: comma_root.clone(),
read_only: true,
});
config.shares.push(DirectoryShare {
tag: "writable".to_owned(),
path: writable_share,
read_only: false,
});
let host = HostCapabilities {
qemu: PathBuf::from("/usr/bin/qemu-system-x86_64"),
qemu_img: PathBuf::from("/usr/bin/qemu-img"),
swtpm: None,
swtpm_ioctl: None,
kvm_available: false,
uefi_code: Some(code),
uefi_secure_code: Some(secure_code),
uefi_vars: Some(vars.clone()),
uefi_secure_vars: Some(vars.clone()),
};
let files = RuntimeFiles {
qmp_socket: root.path().join("qmp.sock"),
display_socket: root.path().join("display.sock"),
agent_socket: root.path().join("agent.sock"),
pid_file: root.path().join("qemu.pid"),
uefi_vars: vars,
tpm_socket: root.path().join("tpm.sock"),
tpm_control_socket: root.path().join("tpm-ctrl.sock"),
swtpm_pid_file: root.path().join("swtpm.pid"),
tpm_state_dir: root.path().join("tpm-state"),
};
let command = build_command(&config, &host, &files).unwrap();
assert!(command.args.contains(&OsString::from("-daemonize")));
assert!(
command
.args
.windows(2)
.any(|pair| { pair[0] == "-device" && pair[1] == "virtio-vga" })
);
assert!(
command
.args
.windows(2)
.any(|pair| pair[0] == "-device" && pair[1] == "usb-tablet,bus=usb.0")
);
let mut relative_config = config.clone();
relative_config.pointer_device = PointerDevice::Mouse;
let relative_command = build_command(&relative_config, &host, &files).unwrap();
assert!(
relative_command
.args
.windows(2)
.any(|pair| pair[0] == "-device" && pair[1] == "usb-mouse,bus=usb.0")
);
assert!(
!relative_command
.args
.windows(2)
.any(|pair| pair[0] == "-device" && pair[1] == "usb-tablet,bus=usb.0")
);
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-device"
&& pair[1]
== "virtserialport,bus=virtio-serial0.0,chardev=qga0,name=org.qemu.guest_agent.0"
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-fsdev"
&& pair[1]
.to_string_lossy()
.contains("path,,with,,commas,security_model=mapped-xattr,readonly=on")
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-device" && pair[1] == "virtio-9p-pci,fsdev=share0,mount_tag=host-data"
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-fsdev"
&& pair[1].to_string_lossy().contains("local,id=share1,path=")
&& pair[1].to_string_lossy().ends_with("readonly=off")
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-device" && pair[1] == "virtio-9p-pci,fsdev=share1,mount_tag=writable"
}));
assert!(
command
.args
.windows(2)
.any(|pair| { pair[0] == "-audiodev" && pair[1] == "pipewire,id=audio0" })
);
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-device" && pair[1].to_string_lossy().starts_with("vmgenid,guid=")
}));
assert!(
command.args.windows(2).any(|pair| {
pair[0] == "-qmp" && pair[1].to_string_lossy().starts_with("unix:")
})
);
assert!(
command.args.windows(2).any(|pair| {
pair[0] == "-vnc" && pair[1].to_string_lossy().starts_with("unix:")
})
);
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-drive" && pair[1].to_string_lossy().contains("path,,with,,commas")
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-netdev"
&& pair[1]
.to_string_lossy()
.contains("hostfwd=tcp:127.0.0.1:2222-:22")
}));
let usb_devices = command
.args
.windows(2)
.filter(|pair| {
pair[0] == "-device" && pair[1].to_string_lossy().starts_with("usb-host,")
})
.map(|pair| pair[1].to_string_lossy().into_owned())
.collect::<Vec<_>>();
assert_eq!(
usb_devices,
[
"usb-host,id=usb-host-b001-a004,bus=usb.0,hostbus=1,hostaddr=4",
"usb-host,id=usb-host-b002-a009,bus=usb.0,hostbus=2,hostaddr=9",
]
);
assert!(command.args.iter().any(|argument| {
argument
.to_string_lossy()
.contains("disk with spaces.qcow2")
}));
config.firmware = Firmware::UefiSecure;
let command = build_command(&config, &host, &files).unwrap();
assert!(
command.args.windows(2).any(|pair| {
pair[0] == "-machine" && pair[1].to_string_lossy().contains("smm=on")
})
);
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-global" && pair[1] == "driver=cfi.pflash01,property=secure,value=on"
}));
assert!(command.args.windows(2).any(|pair| {
pair[0] == "-drive" && pair[1].to_string_lossy().contains("secure-code.fd")
}));
}
#[test]
fn display_quotes_diagnostic_arguments() {
let command = CommandSpec {
program: PathBuf::from("qemu"),
args: vec![OsString::from("a b")],
};
assert_eq!(command.display(), "qemu 'a b'");
}
#[test]
fn software_tpm_is_opt_in_and_builds_swtpm_and_qemu_commands() {
let root = tempdir().unwrap();
let disk = root.path().join("disk.qcow2");
fs::write(&disk, []).unwrap();
let mut config = VmConfig::new("test".to_owned(), disk, None);
config.firmware = Firmware::Bios;
let files = RuntimeFiles {
qmp_socket: root.path().join("qmp.sock"),
display_socket: root.path().join("display.sock"),
agent_socket: root.path().join("agent.sock"),
pid_file: root.path().join("qemu.pid"),
uefi_vars: root.path().join("uefi-vars.fd"),
tpm_socket: root.path().join("tpm.sock"),
tpm_control_socket: root.path().join("tpm-ctrl.sock"),
swtpm_pid_file: root.path().join("swtpm.pid"),
tpm_state_dir: root.path().join("tpm-state"),
};
let host = HostCapabilities {
qemu: PathBuf::from("qemu-system-x86_64"),
qemu_img: PathBuf::from("qemu-img"),
swtpm: Some(PathBuf::from("/usr/bin/swtpm")),
swtpm_ioctl: Some(PathBuf::from("/usr/bin/swtpm_ioctl")),
kvm_available: false,
uefi_code: None,
uefi_secure_code: None,
uefi_vars: None,
uefi_secure_vars: None,
};
assert!(
build_swtpm_command(&config, &host, &files)
.unwrap()
.is_none()
);
let disabled = build_command(&config, &host, &files).unwrap();
assert!(!disabled.args.iter().any(|arg| arg == "-tpmdev"));
config.software_tpm2 = true;
let qemu = build_command(&config, &host, &files).unwrap();
assert!(qemu.args.windows(2).any(|pair| {
pair[0] == "-chardev" && pair[1].to_string_lossy().contains("socket,id=chrtpm,path=")
}));
assert!(
qemu.args.windows(2).any(|pair| {
pair[0] == "-tpmdev" && pair[1] == "emulator,id=tpm0,chardev=chrtpm"
})
);
assert!(
qemu.args
.windows(2)
.any(|pair| { pair[0] == "-device" && pair[1] == "tpm-tis,tpmdev=tpm0" })
);
let swtpm = build_swtpm_command(&config, &host, &files)
.unwrap()
.unwrap();
assert_eq!(swtpm.program, PathBuf::from("/usr/bin/swtpm"));
assert!(swtpm.args.iter().any(|arg| arg == "--tpm2"));
assert!(swtpm.args.iter().any(|arg| arg == "--daemon"));
assert!(
swtpm
.args
.iter()
.any(|arg| { arg.to_string_lossy().contains("mode=0600,fsync") })
);
let missing_swtpm = HostCapabilities {
swtpm: None,
..host
};
assert!(build_swtpm_command(&config, &missing_swtpm, &files).is_err());
}
}