Skip to main content

aev_vm/
config.rs

1//! Persistent virtual machine definitions.
2
3use std::fs;
4use std::net::Ipv4Addr;
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Result, bail};
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10
11/// Current on-disk VM configuration schema.
12pub const CONFIG_SCHEMA_VERSION: u32 = 1;
13
14/// A persistent virtual machine definition.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct VmConfig {
18    /// Configuration schema version.
19    pub schema_version: u32,
20    /// User-visible and filesystem-safe VM name.
21    pub name: String,
22    /// Stable generation identifier exposed to the guest.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub generation_id: Option<Uuid>,
25    /// Guest RAM in mebibytes.
26    pub memory_mib: u64,
27    /// Number of virtual CPUs.
28    pub vcpus: u16,
29    /// Preferred accelerator.
30    #[serde(default)]
31    pub acceleration: Acceleration,
32    /// Boot firmware selection.
33    #[serde(default)]
34    pub firmware: Firmware,
35    /// Attach a per-VM software TPM 2.0 device.
36    #[serde(default, skip_serializing_if = "is_false")]
37    pub software_tpm2: bool,
38    /// Primary system disk.
39    pub disk: DiskConfig,
40    /// Optional read-only installation image.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub install_media: Option<PathBuf>,
43    /// Guest network configuration.
44    #[serde(default)]
45    pub network: NetworkConfig,
46    /// Guest audio backend.
47    #[serde(default)]
48    pub audio: AudioMode,
49    /// QEMU USB pointer device; the tablet remains the compatibility default.
50    #[serde(default)]
51    pub pointer_device: PointerDevice,
52    /// Host USB devices cold-plugged into the guest.
53    #[serde(default, skip_serializing_if = "Vec::is_empty")]
54    pub usb_devices: Vec<UsbHostDevice>,
55    /// Host directories exposed through virtio-9p.
56    #[serde(default, skip_serializing_if = "Vec::is_empty")]
57    pub shares: Vec<DirectoryShare>,
58}
59
60impl VmConfig {
61    /// Construct a VM definition with secure, broadly compatible defaults.
62    #[must_use]
63    pub fn new(name: String, disk: PathBuf, install_media: Option<PathBuf>) -> Self {
64        Self {
65            schema_version: CONFIG_SCHEMA_VERSION,
66            name,
67            generation_id: Some(Uuid::new_v4()),
68            memory_mib: 4096,
69            vcpus: 4,
70            acceleration: Acceleration::Auto,
71            firmware: Firmware::Uefi,
72            software_tpm2: false,
73            disk: DiskConfig {
74                path: disk,
75                format: DiskFormat::Qcow2,
76            },
77            install_media,
78            network: NetworkConfig::default(),
79            audio: AudioMode::None,
80            pointer_device: PointerDevice::Tablet,
81            usb_devices: Vec::new(),
82            shares: Vec::new(),
83        }
84    }
85
86    /// Load and validate a definition, resolving relative paths beside it.
87    pub fn load(path: &Path) -> Result<Self> {
88        let source = fs::read_to_string(path)
89            .with_context(|| format!("failed to read VM definition {}", path.display()))?;
90        let mut config: Self = toml::from_str(&source)
91            .with_context(|| format!("failed to parse VM definition {}", path.display()))?;
92        let base = path.parent().unwrap_or_else(|| Path::new("."));
93        if config.disk.path.is_relative() {
94            config.disk.path = base.join(&config.disk.path);
95        }
96        if let Some(media) = &mut config.install_media
97            && media.is_relative()
98        {
99            *media = base.join(&*media);
100        }
101        for share in &mut config.shares {
102            if share.path.is_relative() {
103                share.path = base.join(&share.path);
104            }
105        }
106        config.validate()?;
107        Ok(config)
108    }
109
110    /// Serialize a definition to TOML.
111    pub fn to_toml(&self) -> Result<String> {
112        self.validate()?;
113        toml::to_string_pretty(self).context("failed to serialize VM definition")
114    }
115
116    /// Validate values that must be safe before they reach QEMU or the filesystem.
117    pub fn validate(&self) -> Result<()> {
118        if self.schema_version != CONFIG_SCHEMA_VERSION {
119            bail!(
120                "unsupported VM configuration schema {}; expected {}",
121                self.schema_version,
122                CONFIG_SCHEMA_VERSION
123            );
124        }
125        validate_name(&self.name)?;
126        if !(256..=1_048_576).contains(&self.memory_mib) {
127            bail!("memory_mib must be between 256 and 1048576");
128        }
129        if !(1..=1024).contains(&self.vcpus) {
130            bail!("vcpus must be between 1 and 1024");
131        }
132        if self.disk.path.as_os_str().is_empty() {
133            bail!("disk path cannot be empty");
134        }
135        if let Some(mac) = &self.network.mac {
136            validate_mac(mac)?;
137        }
138        if self.network.mode == NetworkMode::None && !self.network.forwards.is_empty() {
139            bail!("network port forwards require network mode 'user'");
140        }
141        let mut listeners = std::collections::BTreeSet::new();
142        for forward in &self.network.forwards {
143            forward.validate()?;
144            if !listeners.insert((forward.protocol, forward.host_address, forward.host_port)) {
145                bail!(
146                    "duplicate {:?} port forward on {}:{}",
147                    forward.protocol,
148                    forward.host_address,
149                    forward.host_port
150                );
151            }
152        }
153        if self.usb_devices.len() > 14 {
154            bail!("at most 14 USB host devices can be configured");
155        }
156        let mut usb_devices = std::collections::BTreeSet::new();
157        for device in &self.usb_devices {
158            device.validate()?;
159            if !usb_devices.insert((device.bus, device.address)) {
160                bail!(
161                    "duplicate USB host device at bus {} address {}",
162                    device.bus,
163                    device.address
164                );
165            }
166        }
167        if self.shares.len() > 16 {
168            bail!("at most 16 host directory shares can be configured");
169        }
170        let mut tags = std::collections::BTreeSet::new();
171        let mut paths = std::collections::BTreeSet::new();
172        for share in &self.shares {
173            share.validate()?;
174            if !tags.insert(&share.tag) {
175                bail!("duplicate host directory share tag {}", share.tag);
176            }
177            if !paths.insert(&share.path) {
178                bail!(
179                    "host directory {} is shared more than once",
180                    share.path.display()
181                );
182            }
183        }
184        Ok(())
185    }
186}
187
188#[allow(clippy::trivially_copy_pass_by_ref)] // serde's skip predicate receives &T.
189fn is_false(value: &bool) -> bool {
190    !value
191}
192
193fn validate_mac(mac: &str) -> Result<()> {
194    let octets = mac
195        .split(':')
196        .map(|octet| {
197            if octet.len() != 2 {
198                bail!("network MAC octets must contain exactly two hexadecimal digits");
199            }
200            u8::from_str_radix(octet, 16).context("network MAC contains a non-hexadecimal octet")
201        })
202        .collect::<Result<Vec<_>>>()?;
203    if octets.len() != 6 {
204        bail!("network MAC must contain six octets");
205    }
206    if octets[0] & 1 != 0 {
207        bail!("network MAC must be a unicast address");
208    }
209    if octets[0] & 2 == 0 {
210        bail!("network MAC must be locally administered");
211    }
212    Ok(())
213}
214
215/// Validate a VM name used in configuration and runtime paths.
216pub fn validate_name(name: &str) -> Result<()> {
217    let mut chars = name.chars();
218    let Some(first) = chars.next() else {
219        bail!("VM name cannot be empty");
220    };
221    if !first.is_ascii_alphanumeric()
222        || !chars.all(|character| {
223            character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
224        })
225    {
226        bail!(
227            "VM name must start with an ASCII letter or digit and contain only letters, digits, '.', '-', or '_'"
228        );
229    }
230    if name.len() > 64 {
231        bail!("VM name cannot exceed 64 bytes");
232    }
233    Ok(())
234}
235
236/// QEMU acceleration preference.
237#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "lowercase")]
239pub enum Acceleration {
240    /// Use KVM when available, otherwise use TCG.
241    #[default]
242    Auto,
243    /// Require Linux KVM hardware acceleration.
244    Kvm,
245    /// Use QEMU's software translator.
246    Tcg,
247}
248
249/// Guest firmware type.
250#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "lowercase")]
252pub enum Firmware {
253    /// UEFI with per-VM variable storage.
254    #[default]
255    Uefi,
256    /// SMM-backed UEFI firmware capable of Secure Boot enforcement.
257    #[serde(rename = "uefi-secure")]
258    UefiSecure,
259    /// QEMU's legacy PC firmware.
260    Bios,
261}
262
263impl Firmware {
264    /// Return whether this firmware uses persistent UEFI variable storage.
265    #[must_use]
266    pub const fn uses_uefi(self) -> bool {
267        matches!(self, Self::Uefi | Self::UefiSecure)
268    }
269}
270
271/// Primary guest disk.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(deny_unknown_fields)]
274pub struct DiskConfig {
275    /// Host path to the disk image.
276    pub path: PathBuf,
277    /// Disk image format.
278    #[serde(default)]
279    pub format: DiskFormat,
280}
281
282/// Supported disk image formats.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
284#[serde(rename_all = "lowercase")]
285pub enum DiskFormat {
286    /// Copy-on-write QEMU image.
287    #[default]
288    Qcow2,
289    /// Raw block image.
290    Raw,
291}
292
293impl DiskFormat {
294    /// Return QEMU's driver name.
295    #[must_use]
296    pub const fn qemu_driver(self) -> &'static str {
297        match self {
298            Self::Qcow2 => "qcow2",
299            Self::Raw => "raw",
300        }
301    }
302}
303
304/// Guest network definition.
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
306#[serde(default, deny_unknown_fields)]
307pub struct NetworkConfig {
308    /// Network attachment mode.
309    pub mode: NetworkMode,
310    /// Optional fixed locally administered MAC address.
311    pub mac: Option<String>,
312    /// Host-loopback ports forwarded into the guest.
313    pub forwards: Vec<PortForward>,
314}
315
316impl Default for NetworkConfig {
317    fn default() -> Self {
318        Self {
319            mode: NetworkMode::User,
320            mac: None,
321            forwards: Vec::new(),
322        }
323    }
324}
325
326/// Supported network attachment modes.
327#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(rename_all = "lowercase")]
329pub enum NetworkMode {
330    /// Unprivileged NAT with an isolated QEMU user network.
331    #[default]
332    User,
333    /// No virtual network adapter.
334    None,
335}
336
337/// Host audio backend exposed through an Intel HDA guest device.
338#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "lowercase")]
340pub enum AudioMode {
341    /// Do not create an audio device.
342    #[default]
343    None,
344    /// Connect QEMU audio to the user's `PipeWire` session.
345    Pipewire,
346}
347
348/// Guest pointer device used by the native Aen console.
349#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "lowercase")]
351pub enum PointerDevice {
352    /// Absolute USB tablet coordinates, compatible with existing VM definitions.
353    #[default]
354    Tablet,
355    /// Relative USB mouse events, used with Aen pointer capture.
356    Mouse,
357}
358
359/// Exact Linux USB bus and device address assigned to a guest.
360#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
361#[serde(deny_unknown_fields)]
362pub struct UsbHostDevice {
363    /// Linux USB bus number.
364    pub bus: u16,
365    /// Device address on the bus.
366    pub address: u16,
367}
368
369impl UsbHostDevice {
370    fn validate(self) -> Result<()> {
371        if !(1..=255).contains(&self.bus) {
372            bail!("USB host bus must be between 1 and 255");
373        }
374        if !(1..=127).contains(&self.address) {
375            bail!("USB host address must be between 1 and 127");
376        }
377        Ok(())
378    }
379}
380
381/// A host directory exposed to the guest through virtio-9p.
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383#[serde(deny_unknown_fields)]
384pub struct DirectoryShare {
385    /// Guest-visible 9p mount tag.
386    pub tag: String,
387    /// Canonical host directory path.
388    pub path: PathBuf,
389    /// Whether guest writes are disabled.
390    #[serde(default = "default_true")]
391    pub read_only: bool,
392}
393
394impl DirectoryShare {
395    fn validate(&self) -> Result<()> {
396        let mut chars = self.tag.chars();
397        let Some(first) = chars.next() else {
398            bail!("directory share tag cannot be empty");
399        };
400        if !first.is_ascii_alphanumeric()
401            || !chars.all(|character| {
402                character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
403            })
404            || self.tag.len() > 32
405        {
406            bail!(
407                "directory share tag must contain 1-32 ASCII letters, digits, '.', '-', or '_' and start with a letter or digit"
408            );
409        }
410        if self.path.as_os_str().is_empty() {
411            bail!("directory share path cannot be empty");
412        }
413        Ok(())
414    }
415}
416
417const fn default_true() -> bool {
418    true
419}
420
421/// A host-loopback QEMU user-network port forward.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(deny_unknown_fields)]
424pub struct PortForward {
425    /// Transport protocol.
426    #[serde(default)]
427    pub protocol: NetworkProtocol,
428    /// Loopback address on which QEMU listens.
429    #[serde(default = "default_forward_address")]
430    pub host_address: Ipv4Addr,
431    /// Host-side listener port.
432    pub host_port: u16,
433    /// Destination port inside the guest.
434    pub guest_port: u16,
435}
436
437impl PortForward {
438    fn validate(&self) -> Result<()> {
439        if !self.host_address.is_loopback() {
440            bail!("port-forward host address must be IPv4 loopback");
441        }
442        if self.host_port == 0 || self.guest_port == 0 {
443            bail!("port-forward host and guest ports must be non-zero");
444        }
445        Ok(())
446    }
447}
448
449/// Transport protocol for a user-network port forward.
450#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
451#[serde(rename_all = "lowercase")]
452pub enum NetworkProtocol {
453    /// Transmission Control Protocol.
454    #[default]
455    Tcp,
456    /// User Datagram Protocol.
457    Udp,
458}
459
460impl NetworkProtocol {
461    /// Return QEMU's protocol spelling.
462    #[must_use]
463    pub const fn qemu_name(self) -> &'static str {
464        match self {
465            Self::Tcp => "tcp",
466            Self::Udp => "udp",
467        }
468    }
469}
470
471const fn default_forward_address() -> Ipv4Addr {
472    Ipv4Addr::LOCALHOST
473}
474
475#[cfg(test)]
476mod tests {
477    use super::{
478        CONFIG_SCHEMA_VERSION, DirectoryShare, NetworkProtocol, PortForward, UsbHostDevice,
479        VmConfig, validate_mac, validate_name,
480    };
481    use std::net::Ipv4Addr;
482    use std::path::PathBuf;
483
484    #[test]
485    fn rejects_unsafe_names() {
486        for name in ["", "-guest", "../guest", "guest name", "guest/one"] {
487            assert!(validate_name(name).is_err(), "accepted {name:?}");
488        }
489        assert!(validate_name("dev.vm-01").is_ok());
490    }
491
492    #[test]
493    fn configuration_round_trips() {
494        let mut config = VmConfig::new(
495            "test-vm".to_owned(),
496            PathBuf::from("/var/lib/test.qcow2"),
497            Some(PathBuf::from("/tmp/install.iso")),
498        );
499        config
500            .usb_devices
501            .push(UsbHostDevice { bus: 1, address: 4 });
502        config.firmware = super::Firmware::UefiSecure;
503        config.shares.push(DirectoryShare {
504            tag: "host-data".to_owned(),
505            path: PathBuf::from("/srv/host-data"),
506            read_only: true,
507        });
508        let text = config.to_toml().unwrap();
509        assert!(text.contains("firmware = \"uefi-secure\""));
510        let decoded: VmConfig = toml::from_str(&text).unwrap();
511        assert_eq!(decoded.schema_version, CONFIG_SCHEMA_VERSION);
512        assert_eq!(decoded, config);
513        let mut tpm_config = config;
514        tpm_config.software_tpm2 = true;
515        let decoded: VmConfig = toml::from_str(&tpm_config.to_toml().unwrap()).unwrap();
516        assert!(decoded.software_tpm2);
517    }
518
519    #[test]
520    fn older_definitions_default_to_the_absolute_tablet() {
521        let config: VmConfig = toml::from_str(
522            r#"
523schema_version = 1
524name = "legacy-vm"
525memory_mib = 4096
526vcpus = 4
527
528[disk]
529path = "/tmp/legacy.qcow2"
530format = "qcow2"
531"#,
532        )
533        .unwrap();
534        assert_eq!(config.pointer_device, super::PointerDevice::Tablet);
535        assert!(!config.software_tpm2);
536    }
537
538    #[test]
539    fn validates_local_unicast_mac_addresses() {
540        assert!(validate_mac("52:54:00:12:34:56").is_ok());
541        assert!(validate_mac("ff:54:00:12:34:56").is_err());
542        assert!(validate_mac("00:11:22:33:44:55").is_err());
543        assert!(validate_mac("52:54:00:12:34:zz").is_err());
544    }
545
546    #[test]
547    fn validates_unique_loopback_port_forwards() {
548        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
549        let forward = PortForward {
550            protocol: NetworkProtocol::Tcp,
551            host_address: Ipv4Addr::LOCALHOST,
552            host_port: 2222,
553            guest_port: 22,
554        };
555        config.network.forwards.push(forward.clone());
556        assert!(config.validate().is_ok());
557        config.network.forwards.push(forward);
558        assert!(config.validate().is_err());
559        config.network.forwards.pop();
560        config.network.forwards[0].host_address = Ipv4Addr::UNSPECIFIED;
561        assert!(config.validate().is_err());
562    }
563
564    #[test]
565    fn validates_exact_unique_usb_host_addresses() {
566        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
567        config.usb_devices.push(UsbHostDevice {
568            bus: 1,
569            address: 127,
570        });
571        assert!(config.validate().is_ok());
572        config.usb_devices.push(UsbHostDevice {
573            bus: 1,
574            address: 127,
575        });
576        assert!(config.validate().is_err());
577        config.usb_devices[1] = UsbHostDevice {
578            bus: 256,
579            address: 1,
580        };
581        assert!(config.validate().is_err());
582        config.usb_devices[1] = UsbHostDevice {
583            bus: 2,
584            address: 128,
585        };
586        assert!(config.validate().is_err());
587        config.usb_devices[1] = UsbHostDevice { bus: 0, address: 1 };
588        assert!(config.validate().is_err());
589        config.usb_devices = (2..=16)
590            .map(|address| UsbHostDevice { bus: 1, address })
591            .collect();
592        assert!(config.validate().is_err());
593    }
594
595    #[test]
596    fn validates_unique_safe_directory_shares() {
597        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
598        let share = DirectoryShare {
599            tag: "host-data".to_owned(),
600            path: PathBuf::from("/srv/data"),
601            read_only: true,
602        };
603        config.shares.push(share.clone());
604        assert!(config.validate().is_ok());
605        config.shares.push(share);
606        assert!(config.validate().is_err());
607        config.shares[1] = DirectoryShare {
608            tag: "../unsafe".to_owned(),
609            path: PathBuf::from("/srv/other"),
610            read_only: false,
611        };
612        assert!(config.validate().is_err());
613    }
614}