aev-vm 0.1.0

Manage QEMU virtual machines in Rust and open their consoles in Aen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Persistent virtual machine definitions.

use std::fs;
use std::net::Ipv4Addr;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Current on-disk VM configuration schema.
pub const CONFIG_SCHEMA_VERSION: u32 = 1;

/// A persistent virtual machine definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VmConfig {
    /// Configuration schema version.
    pub schema_version: u32,
    /// User-visible and filesystem-safe VM name.
    pub name: String,
    /// Stable generation identifier exposed to the guest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generation_id: Option<Uuid>,
    /// Guest RAM in mebibytes.
    pub memory_mib: u64,
    /// Number of virtual CPUs.
    pub vcpus: u16,
    /// Preferred accelerator.
    #[serde(default)]
    pub acceleration: Acceleration,
    /// Boot firmware selection.
    #[serde(default)]
    pub firmware: Firmware,
    /// Attach a per-VM software TPM 2.0 device.
    #[serde(default, skip_serializing_if = "is_false")]
    pub software_tpm2: bool,
    /// Primary system disk.
    pub disk: DiskConfig,
    /// Optional read-only installation image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub install_media: Option<PathBuf>,
    /// Guest network configuration.
    #[serde(default)]
    pub network: NetworkConfig,
    /// Guest audio backend.
    #[serde(default)]
    pub audio: AudioMode,
    /// QEMU USB pointer device; the tablet remains the compatibility default.
    #[serde(default)]
    pub pointer_device: PointerDevice,
    /// Host USB devices cold-plugged into the guest.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub usb_devices: Vec<UsbHostDevice>,
    /// Host directories exposed through virtio-9p.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shares: Vec<DirectoryShare>,
}

impl VmConfig {
    /// Construct a VM definition with secure, broadly compatible defaults.
    #[must_use]
    pub fn new(name: String, disk: PathBuf, install_media: Option<PathBuf>) -> Self {
        Self {
            schema_version: CONFIG_SCHEMA_VERSION,
            name,
            generation_id: Some(Uuid::new_v4()),
            memory_mib: 4096,
            vcpus: 4,
            acceleration: Acceleration::Auto,
            firmware: Firmware::Uefi,
            software_tpm2: false,
            disk: DiskConfig {
                path: disk,
                format: DiskFormat::Qcow2,
            },
            install_media,
            network: NetworkConfig::default(),
            audio: AudioMode::None,
            pointer_device: PointerDevice::Tablet,
            usb_devices: Vec::new(),
            shares: Vec::new(),
        }
    }

    /// Load and validate a definition, resolving relative paths beside it.
    pub fn load(path: &Path) -> Result<Self> {
        let source = fs::read_to_string(path)
            .with_context(|| format!("failed to read VM definition {}", path.display()))?;
        let mut config: Self = toml::from_str(&source)
            .with_context(|| format!("failed to parse VM definition {}", path.display()))?;
        let base = path.parent().unwrap_or_else(|| Path::new("."));
        if config.disk.path.is_relative() {
            config.disk.path = base.join(&config.disk.path);
        }
        if let Some(media) = &mut config.install_media
            && media.is_relative()
        {
            *media = base.join(&*media);
        }
        for share in &mut config.shares {
            if share.path.is_relative() {
                share.path = base.join(&share.path);
            }
        }
        config.validate()?;
        Ok(config)
    }

    /// Serialize a definition to TOML.
    pub fn to_toml(&self) -> Result<String> {
        self.validate()?;
        toml::to_string_pretty(self).context("failed to serialize VM definition")
    }

    /// Validate values that must be safe before they reach QEMU or the filesystem.
    pub fn validate(&self) -> Result<()> {
        if self.schema_version != CONFIG_SCHEMA_VERSION {
            bail!(
                "unsupported VM configuration schema {}; expected {}",
                self.schema_version,
                CONFIG_SCHEMA_VERSION
            );
        }
        validate_name(&self.name)?;
        if !(256..=1_048_576).contains(&self.memory_mib) {
            bail!("memory_mib must be between 256 and 1048576");
        }
        if !(1..=1024).contains(&self.vcpus) {
            bail!("vcpus must be between 1 and 1024");
        }
        if self.disk.path.as_os_str().is_empty() {
            bail!("disk path cannot be empty");
        }
        if let Some(mac) = &self.network.mac {
            validate_mac(mac)?;
        }
        if self.network.mode == NetworkMode::None && !self.network.forwards.is_empty() {
            bail!("network port forwards require network mode 'user'");
        }
        let mut listeners = std::collections::BTreeSet::new();
        for forward in &self.network.forwards {
            forward.validate()?;
            if !listeners.insert((forward.protocol, forward.host_address, forward.host_port)) {
                bail!(
                    "duplicate {:?} port forward on {}:{}",
                    forward.protocol,
                    forward.host_address,
                    forward.host_port
                );
            }
        }
        if self.usb_devices.len() > 14 {
            bail!("at most 14 USB host devices can be configured");
        }
        let mut usb_devices = std::collections::BTreeSet::new();
        for device in &self.usb_devices {
            device.validate()?;
            if !usb_devices.insert((device.bus, device.address)) {
                bail!(
                    "duplicate USB host device at bus {} address {}",
                    device.bus,
                    device.address
                );
            }
        }
        if self.shares.len() > 16 {
            bail!("at most 16 host directory shares can be configured");
        }
        let mut tags = std::collections::BTreeSet::new();
        let mut paths = std::collections::BTreeSet::new();
        for share in &self.shares {
            share.validate()?;
            if !tags.insert(&share.tag) {
                bail!("duplicate host directory share tag {}", share.tag);
            }
            if !paths.insert(&share.path) {
                bail!(
                    "host directory {} is shared more than once",
                    share.path.display()
                );
            }
        }
        Ok(())
    }
}

#[allow(clippy::trivially_copy_pass_by_ref)] // serde's skip predicate receives &T.
fn is_false(value: &bool) -> bool {
    !value
}

fn validate_mac(mac: &str) -> Result<()> {
    let octets = mac
        .split(':')
        .map(|octet| {
            if octet.len() != 2 {
                bail!("network MAC octets must contain exactly two hexadecimal digits");
            }
            u8::from_str_radix(octet, 16).context("network MAC contains a non-hexadecimal octet")
        })
        .collect::<Result<Vec<_>>>()?;
    if octets.len() != 6 {
        bail!("network MAC must contain six octets");
    }
    if octets[0] & 1 != 0 {
        bail!("network MAC must be a unicast address");
    }
    if octets[0] & 2 == 0 {
        bail!("network MAC must be locally administered");
    }
    Ok(())
}

/// Validate a VM name used in configuration and runtime paths.
pub fn validate_name(name: &str) -> Result<()> {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        bail!("VM name cannot be empty");
    };
    if !first.is_ascii_alphanumeric()
        || !chars.all(|character| {
            character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
        })
    {
        bail!(
            "VM name must start with an ASCII letter or digit and contain only letters, digits, '.', '-', or '_'"
        );
    }
    if name.len() > 64 {
        bail!("VM name cannot exceed 64 bytes");
    }
    Ok(())
}

/// QEMU acceleration preference.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Acceleration {
    /// Use KVM when available, otherwise use TCG.
    #[default]
    Auto,
    /// Require Linux KVM hardware acceleration.
    Kvm,
    /// Use QEMU's software translator.
    Tcg,
}

/// Guest firmware type.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Firmware {
    /// UEFI with per-VM variable storage.
    #[default]
    Uefi,
    /// SMM-backed UEFI firmware capable of Secure Boot enforcement.
    #[serde(rename = "uefi-secure")]
    UefiSecure,
    /// QEMU's legacy PC firmware.
    Bios,
}

impl Firmware {
    /// Return whether this firmware uses persistent UEFI variable storage.
    #[must_use]
    pub const fn uses_uefi(self) -> bool {
        matches!(self, Self::Uefi | Self::UefiSecure)
    }
}

/// Primary guest disk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DiskConfig {
    /// Host path to the disk image.
    pub path: PathBuf,
    /// Disk image format.
    #[serde(default)]
    pub format: DiskFormat,
}

/// Supported disk image formats.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DiskFormat {
    /// Copy-on-write QEMU image.
    #[default]
    Qcow2,
    /// Raw block image.
    Raw,
}

impl DiskFormat {
    /// Return QEMU's driver name.
    #[must_use]
    pub const fn qemu_driver(self) -> &'static str {
        match self {
            Self::Qcow2 => "qcow2",
            Self::Raw => "raw",
        }
    }
}

/// Guest network definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct NetworkConfig {
    /// Network attachment mode.
    pub mode: NetworkMode,
    /// Optional fixed locally administered MAC address.
    pub mac: Option<String>,
    /// Host-loopback ports forwarded into the guest.
    pub forwards: Vec<PortForward>,
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            mode: NetworkMode::User,
            mac: None,
            forwards: Vec::new(),
        }
    }
}

/// Supported network attachment modes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NetworkMode {
    /// Unprivileged NAT with an isolated QEMU user network.
    #[default]
    User,
    /// No virtual network adapter.
    None,
}

/// Host audio backend exposed through an Intel HDA guest device.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AudioMode {
    /// Do not create an audio device.
    #[default]
    None,
    /// Connect QEMU audio to the user's `PipeWire` session.
    Pipewire,
}

/// Guest pointer device used by the native Aen console.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PointerDevice {
    /// Absolute USB tablet coordinates, compatible with existing VM definitions.
    #[default]
    Tablet,
    /// Relative USB mouse events, used with Aen pointer capture.
    Mouse,
}

/// Exact Linux USB bus and device address assigned to a guest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UsbHostDevice {
    /// Linux USB bus number.
    pub bus: u16,
    /// Device address on the bus.
    pub address: u16,
}

impl UsbHostDevice {
    fn validate(self) -> Result<()> {
        if !(1..=255).contains(&self.bus) {
            bail!("USB host bus must be between 1 and 255");
        }
        if !(1..=127).contains(&self.address) {
            bail!("USB host address must be between 1 and 127");
        }
        Ok(())
    }
}

/// A host directory exposed to the guest through virtio-9p.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DirectoryShare {
    /// Guest-visible 9p mount tag.
    pub tag: String,
    /// Canonical host directory path.
    pub path: PathBuf,
    /// Whether guest writes are disabled.
    #[serde(default = "default_true")]
    pub read_only: bool,
}

impl DirectoryShare {
    fn validate(&self) -> Result<()> {
        let mut chars = self.tag.chars();
        let Some(first) = chars.next() else {
            bail!("directory share tag cannot be empty");
        };
        if !first.is_ascii_alphanumeric()
            || !chars.all(|character| {
                character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
            })
            || self.tag.len() > 32
        {
            bail!(
                "directory share tag must contain 1-32 ASCII letters, digits, '.', '-', or '_' and start with a letter or digit"
            );
        }
        if self.path.as_os_str().is_empty() {
            bail!("directory share path cannot be empty");
        }
        Ok(())
    }
}

const fn default_true() -> bool {
    true
}

/// A host-loopback QEMU user-network port forward.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortForward {
    /// Transport protocol.
    #[serde(default)]
    pub protocol: NetworkProtocol,
    /// Loopback address on which QEMU listens.
    #[serde(default = "default_forward_address")]
    pub host_address: Ipv4Addr,
    /// Host-side listener port.
    pub host_port: u16,
    /// Destination port inside the guest.
    pub guest_port: u16,
}

impl PortForward {
    fn validate(&self) -> Result<()> {
        if !self.host_address.is_loopback() {
            bail!("port-forward host address must be IPv4 loopback");
        }
        if self.host_port == 0 || self.guest_port == 0 {
            bail!("port-forward host and guest ports must be non-zero");
        }
        Ok(())
    }
}

/// Transport protocol for a user-network port forward.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NetworkProtocol {
    /// Transmission Control Protocol.
    #[default]
    Tcp,
    /// User Datagram Protocol.
    Udp,
}

impl NetworkProtocol {
    /// Return QEMU's protocol spelling.
    #[must_use]
    pub const fn qemu_name(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Udp => "udp",
        }
    }
}

const fn default_forward_address() -> Ipv4Addr {
    Ipv4Addr::LOCALHOST
}

#[cfg(test)]
mod tests {
    use super::{
        CONFIG_SCHEMA_VERSION, DirectoryShare, NetworkProtocol, PortForward, UsbHostDevice,
        VmConfig, validate_mac, validate_name,
    };
    use std::net::Ipv4Addr;
    use std::path::PathBuf;

    #[test]
    fn rejects_unsafe_names() {
        for name in ["", "-guest", "../guest", "guest name", "guest/one"] {
            assert!(validate_name(name).is_err(), "accepted {name:?}");
        }
        assert!(validate_name("dev.vm-01").is_ok());
    }

    #[test]
    fn configuration_round_trips() {
        let mut config = VmConfig::new(
            "test-vm".to_owned(),
            PathBuf::from("/var/lib/test.qcow2"),
            Some(PathBuf::from("/tmp/install.iso")),
        );
        config
            .usb_devices
            .push(UsbHostDevice { bus: 1, address: 4 });
        config.firmware = super::Firmware::UefiSecure;
        config.shares.push(DirectoryShare {
            tag: "host-data".to_owned(),
            path: PathBuf::from("/srv/host-data"),
            read_only: true,
        });
        let text = config.to_toml().unwrap();
        assert!(text.contains("firmware = \"uefi-secure\""));
        let decoded: VmConfig = toml::from_str(&text).unwrap();
        assert_eq!(decoded.schema_version, CONFIG_SCHEMA_VERSION);
        assert_eq!(decoded, config);
        let mut tpm_config = config;
        tpm_config.software_tpm2 = true;
        let decoded: VmConfig = toml::from_str(&tpm_config.to_toml().unwrap()).unwrap();
        assert!(decoded.software_tpm2);
    }

    #[test]
    fn older_definitions_default_to_the_absolute_tablet() {
        let config: VmConfig = toml::from_str(
            r#"
schema_version = 1
name = "legacy-vm"
memory_mib = 4096
vcpus = 4

[disk]
path = "/tmp/legacy.qcow2"
format = "qcow2"
"#,
        )
        .unwrap();
        assert_eq!(config.pointer_device, super::PointerDevice::Tablet);
        assert!(!config.software_tpm2);
    }

    #[test]
    fn validates_local_unicast_mac_addresses() {
        assert!(validate_mac("52:54:00:12:34:56").is_ok());
        assert!(validate_mac("ff:54:00:12:34:56").is_err());
        assert!(validate_mac("00:11:22:33:44:55").is_err());
        assert!(validate_mac("52:54:00:12:34:zz").is_err());
    }

    #[test]
    fn validates_unique_loopback_port_forwards() {
        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
        let forward = PortForward {
            protocol: NetworkProtocol::Tcp,
            host_address: Ipv4Addr::LOCALHOST,
            host_port: 2222,
            guest_port: 22,
        };
        config.network.forwards.push(forward.clone());
        assert!(config.validate().is_ok());
        config.network.forwards.push(forward);
        assert!(config.validate().is_err());
        config.network.forwards.pop();
        config.network.forwards[0].host_address = Ipv4Addr::UNSPECIFIED;
        assert!(config.validate().is_err());
    }

    #[test]
    fn validates_exact_unique_usb_host_addresses() {
        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
        config.usb_devices.push(UsbHostDevice {
            bus: 1,
            address: 127,
        });
        assert!(config.validate().is_ok());
        config.usb_devices.push(UsbHostDevice {
            bus: 1,
            address: 127,
        });
        assert!(config.validate().is_err());
        config.usb_devices[1] = UsbHostDevice {
            bus: 256,
            address: 1,
        };
        assert!(config.validate().is_err());
        config.usb_devices[1] = UsbHostDevice {
            bus: 2,
            address: 128,
        };
        assert!(config.validate().is_err());
        config.usb_devices[1] = UsbHostDevice { bus: 0, address: 1 };
        assert!(config.validate().is_err());
        config.usb_devices = (2..=16)
            .map(|address| UsbHostDevice { bus: 1, address })
            .collect();
        assert!(config.validate().is_err());
    }

    #[test]
    fn validates_unique_safe_directory_shares() {
        let mut config = VmConfig::new("test".to_owned(), PathBuf::from("/tmp/test.qcow2"), None);
        let share = DirectoryShare {
            tag: "host-data".to_owned(),
            path: PathBuf::from("/srv/data"),
            read_only: true,
        };
        config.shares.push(share.clone());
        assert!(config.validate().is_ok());
        config.shares.push(share);
        assert!(config.validate().is_err());
        config.shares[1] = DirectoryShare {
            tag: "../unsafe".to_owned(),
            path: PathBuf::from("/srv/other"),
            read_only: false,
        };
        assert!(config.validate().is_err());
    }
}