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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! QEMU/KVM capability probing and deterministic command construction.

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};

/// Resolved host binaries and virtualization capabilities.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostCapabilities {
    /// QEMU system emulator.
    pub qemu: PathBuf,
    /// QEMU disk image utility.
    pub qemu_img: PathBuf,
    /// Optional software TPM 2 emulator.
    pub swtpm: Option<PathBuf>,
    /// Optional software TPM control utility.
    pub swtpm_ioctl: Option<PathBuf>,
    /// Whether `/dev/kvm` can be opened read-write.
    pub kvm_available: bool,
    /// Optional UEFI read-only code image.
    pub uefi_code: Option<PathBuf>,
    /// Optional SMM-backed Secure Boot UEFI code image.
    pub uefi_secure_code: Option<PathBuf>,
    /// Optional UEFI variable template.
    pub uefi_vars: Option<PathBuf>,
    /// Optional variable template matching the Secure Boot code image.
    pub uefi_secure_vars: Option<PathBuf>,
}

impl HostCapabilities {
    /// Probe tools and firmware without changing host state.
    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,
        })
    }
}

/// Runtime-only files supplied to a QEMU process.
#[derive(Debug, Clone)]
pub struct RuntimeFiles {
    /// QMP control socket.
    pub qmp_socket: PathBuf,
    /// RFB console socket.
    pub display_socket: PathBuf,
    /// QEMU Guest Agent proxy socket.
    pub agent_socket: PathBuf,
    /// QEMU daemon PID file.
    pub pid_file: PathBuf,
    /// Per-VM writable UEFI variables.
    pub uefi_vars: PathBuf,
    /// Software TPM command socket.
    pub tpm_socket: PathBuf,
    /// Software TPM control socket.
    pub tpm_control_socket: PathBuf,
    /// Software TPM daemon PID file.
    pub swtpm_pid_file: PathBuf,
    /// Persistent software TPM state directory.
    pub tpm_state_dir: PathBuf,
}

/// A shell-free executable and argument list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandSpec {
    /// Executable path.
    pub program: PathBuf,
    /// Individual arguments passed directly to the executable.
    pub args: Vec<OsString>,
}

impl CommandSpec {
    /// Produce a readable, shell-escaped diagnostic command.
    #[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(" ")
    }
}

/// Build a hardened QEMU command for a VM definition.
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,
    })
}

/// Build the optional software TPM daemon command for an enabled VM.
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)
}

/// Copy the distribution's UEFI variable template for a new VM.
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());
    }
}