krunkit 1.2.0

CLI tool to start VMs with libkrun
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
// SPDX-License-Identifier: Apache-2.0

use crate::cmdline::{
    check_required_args, check_unknown_args, cstring_to_ptr, parse_args, parse_boolean,
};

use std::{
    ffi::{c_char, c_int, CString},
    os::fd::RawFd,
    os::unix::ffi::OsStrExt,
    path::{Path, PathBuf},
    str::FromStr,
};

use anyhow::{anyhow, Context, Result};
use mac_address::MacAddress;

/// Taken from https://github.com/containers/libkrun/blob/7116644749c7b1028a970c9e8bd2d0163745a225/include/libkrun.h#L269
const NET_FEATURE_CSUM: u32 = 1 << 0;
const NET_FEATURE_GUEST_CSUM: u32 = 1 << 1;
const NET_FEATURE_GUEST_TSO4: u32 = 1 << 7;
const NET_FEATURE_GUEST_TSO6: u32 = 1 << 8;
const NET_FEATURE_GUEST_UFO: u32 = 1 << 10;
const NET_FEATURE_HOST_TSO4: u32 = 1 << 11;
const NET_FEATURE_HOST_TSO6: u32 = 1 << 12;
const NET_FEATURE_HOST_UFO: u32 = 1 << 14;

/// These are the features enabled by krun_set_passt_fd and krun_set_gvproxy_path.
const COMPAT_NET_FEATURES: u32 = NET_FEATURE_CSUM
    | NET_FEATURE_GUEST_CSUM
    | NET_FEATURE_GUEST_TSO4
    | NET_FEATURE_GUEST_UFO
    | NET_FEATURE_HOST_TSO4
    | NET_FEATURE_HOST_UFO;

/// Send the VFKIT magic after establishing the connection,
/// as required by gvproxy in vfkit mode.
const NET_FLAG_VFKIT: u32 = 1 << 0;

const SOCK_TYPE_UNIX_SOCKET_PATH: &str = "unixSocketPath";
const SOCK_TYPE_UNIXGRAM: &str = "unixgram";
const SOCK_TYPE_UNIXSTREAM: &str = "unixstream";

#[link(name = "krun")]
extern "C" {
    fn krun_add_disk2(
        ctx_id: u32,
        c_block_id: *const c_char,
        c_disk_path: *const c_char,
        disk_format: u32,
        read_only: bool,
    ) -> i32;
    fn krun_add_vsock_port2(ctx_id: u32, port: u32, c_filepath: *const c_char, listen: bool)
        -> i32;
    fn krun_add_virtiofs(ctx_id: u32, c_tag: *const c_char, c_path: *const c_char) -> i32;
    fn krun_set_console_output(ctx_id: u32, c_filepath: *const c_char) -> i32;
    fn krun_add_net_unixgram(
        ctx_id: u32,
        c_path: *const c_char,
        fd: c_int,
        c_mac: *const u8,
        features: u32,
        flags: u32,
    ) -> i32;
    fn krun_add_net_unixstream(
        ctx_id: u32,
        c_path: *const c_char,
        fd: c_int,
        c_mac: *const u8,
        features: u32,
        flags: u32,
    ) -> i32;
}

#[repr(u32)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum DiskImageFormat {
    #[default]
    Raw = 0,
    Qcow2 = 1,
}

impl FromStr for DiskImageFormat {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "raw" => Ok(DiskImageFormat::Raw),
            "qcow2" => Ok(DiskImageFormat::Qcow2),
            _ => Err(anyhow!("unsupported disk image format")),
        }
    }
}

/// Each virito device configures itself with krun differently. This is used by each virtio device
/// to set their respective configurations with libkrun.
pub trait KrunContextSet {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error>;
}

/// virtio device configurations.
#[derive(Clone, Debug, PartialEq)]
pub enum VirtioDeviceConfig {
    Blk(BlkConfig),
    Rng,
    Serial(SerialConfig),
    Vsock(VsockConfig),
    Net(NetConfig),
    Fs(FsConfig),
    Gpu(GpuConfig),
    Input(InputConfig),
}

/// Parse a virtio device configuration with its respective information/data.
impl FromStr for VirtioDeviceConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let args: Vec<String> = s.split(',').map(|s| s.to_string()).collect();

        if args.is_empty() {
            return Err(anyhow!("no virtio device config found"));
        }

        // The first string is the virtio device identifier. Subsequent arguments are
        // device-specific.
        let rest = args[1..].join(",");

        match &args[0][..] {
            "virtio-blk" => Ok(Self::Blk(BlkConfig::from_str(&rest)?)),
            "virtio-rng" => Ok(Self::Rng),
            "virtio-serial" => Ok(Self::Serial(SerialConfig::from_str(&rest)?)),
            "virtio-vsock" => Ok(Self::Vsock(VsockConfig::from_str(&rest)?)),
            "virtio-net" => Ok(Self::Net(NetConfig::from_str(&rest)?)),
            "virtio-fs" => Ok(Self::Fs(FsConfig::from_str(&rest)?)),
            "virtio-gpu" => Ok(Self::Gpu(GpuConfig::from_str(&rest)?)),
            "virtio-input" => Ok(Self::Input(InputConfig::from_str(&rest)?)),
            _ => Err(anyhow!(format!(
                "invalid virtio device label specified: {}",
                args[0]
            ))),
        }
    }
}

/// Configure the device in the krun context based on which underlying device is contained.
impl KrunContextSet for VirtioDeviceConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        match self {
            Self::Blk(blk) => blk.krun_ctx_set(id),
            Self::Vsock(vsock) => vsock.krun_ctx_set(id),
            Self::Net(net) => net.krun_ctx_set(id),
            Self::Fs(fs) => fs.krun_ctx_set(id),
            Self::Serial(serial) => serial.krun_ctx_set(id),

            // virtio-input, virtio-gpu, and virtio-rng devices are currently not configured in
            // krun.
            _ => Ok(()),
        }
    }
}

/// Configuration of a virtio-blk device.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BlkConfig {
    /// Path of the file to store as the root disk.
    pub path: PathBuf,

    /// Format of the disk image.
    pub format: DiskImageFormat,
}

impl FromStr for BlkConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut blk_config = Self::default();
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-blk", &["path"])?;

        let path = args.remove("path").unwrap();
        blk_config.path =
            PathBuf::from_str(path.as_str()).context("path argument not a valid path")?;

        if let Some(f) = args.remove("format") {
            blk_config.format = DiskImageFormat::from_str(f.as_str())?;
        }

        check_unknown_args(args, "virtio-blk")?;

        Ok(blk_config)
    }
}

/// Set the virtio-blk device to be the krun VM's root disk.
impl KrunContextSet for BlkConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        let basename = match self.path.file_name() {
            Some(osstr) => osstr.to_str().unwrap_or("disk"),
            None => "disk",
        };
        let block_id_cstr = CString::new(basename).context("can't convert basename to cstring")?;
        let path_cstr = path_to_cstring(&self.path)?;

        if krun_add_disk2(
            id,
            block_id_cstr.as_ptr(),
            path_cstr.as_ptr(),
            self.format as u32,
            false,
        ) < 0
        {
            return Err(anyhow!(format!(
                "unable to set virtio-blk disk for {}",
                self.path.display()
            )));
        }

        Ok(())
    }
}

/// Configuration of a virtio-serial device.
#[derive(Clone, Debug, PartialEq)]
pub struct SerialConfig {
    /// Path of a file to use as the device's log.
    pub log_file_path: PathBuf,
}

impl FromStr for SerialConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-serial", &["logFilePath"])?;

        let log_file_path = args.remove("logFilePath").unwrap();
        check_unknown_args(args, "virtio-serial")?;

        Ok(Self {
            log_file_path: PathBuf::from_str(log_file_path.as_str())
                .context("logFilePath argument not a valid path")?,
        })
    }
}

/// Set the krun console output to be written to the virtio-serial's log file.
impl KrunContextSet for SerialConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        let path_cstr = path_to_cstring(&self.log_file_path)?;

        if krun_set_console_output(id, path_cstr.as_ptr()) < 0 {
            return Err(anyhow!(
                "unable to set krun console output redirection to virtio-serial log file"
            ));
        }

        Ok(())
    }
}

/// Configuration of a virtio-vsock device.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VsockConfig {
    /// Port to connect to on VM.
    pub port: u32,

    /// Path of underlying socket.
    pub socket_url: PathBuf,

    /// Action of socket.
    pub action: VsockAction,
}

impl FromStr for VsockConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut vsock_config = Self::default();
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-vsock", &["port", "socketURL"])?;

        let port = args.remove("port").unwrap();
        vsock_config.port = u32::from_str(port.as_str()).context("port argument invalid")?;

        let socket_url = args.remove("socketURL").unwrap();
        vsock_config.socket_url = PathBuf::from_str(socket_url.as_str())
            .context("socketURL argument not a valid path")?;

        if let Some(v) = args.remove("connect") {
            if !v.is_empty() {
                return Err(anyhow!(format!(
                    "unexpected value for virtio-vsock argument: connect={v}"
                )));
            }
            vsock_config.action = VsockAction::from_str("connect")?
        }
        if let Some(v) = args.remove("listen") {
            if !v.is_empty() {
                return Err(anyhow!(format!(
                    "unexpected value for virtio-vsock argument: listen={v}"
                )));
            }
            if vsock_config.action == VsockAction::Connect {
                return Err(anyhow!(
                    "virtio-vsock argument \"listen\" and \"connect\" are mutually exclusive and cannot be used together."
                ));
            }
            vsock_config.action = VsockAction::from_str("listen")?
        }

        check_unknown_args(args, "virtio-vsock")?;

        Ok(vsock_config)
    }
}

/// Map the virtio-vsock's guest port and host path to enable the krun VM to communicate with the
/// socket on the host.
impl KrunContextSet for VsockConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        let path_cstr = path_to_cstring(&self.socket_url)?;

        // libkrun's `listen` parameter means "guest expects connections from host" which is true when VsockAction::Connect.
        if krun_add_vsock_port2(
            id,
            self.port,
            path_cstr.as_ptr(),
            self.action == VsockAction::Connect,
        ) < 0
        {
            return Err(anyhow!(format!(
                "unable to add vsock port {} for path {}",
                self.port,
                &self.socket_url.display()
            )));
        }

        Ok(())
    }
}

/// virtio-vsock action.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum VsockAction {
    /// Host listens for guest-initiated connections (default).
    #[default]
    Listen,
    /// Host connects to guest; guest listens for host-initiated connections.
    Connect,
}

impl FromStr for VsockAction {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.to_string().to_lowercase();

        match &s[..] {
            "listen" => Ok(Self::Listen),
            "connect" => Ok(Self::Connect),
            _ => Err(anyhow!("invalid vsock action")),
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SocketConfig {
    pub path: Option<PathBuf>,
    pub fd: Option<RawFd>,
    pub offloading: bool,
    pub send_vfkit_magic: bool,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SocketType {
    /// Socket type for creating an independent virtio-net device with a
    /// unixgram-based backend.
    UnixGram,
    /// Socket type for creating an independent virtio-net device with a
    /// unixstream-based backend.
    UnixStream,
}

/// Configuration of a virtio-net device.
#[derive(Clone, Debug, PartialEq)]
pub struct NetConfig {
    /// Socket type.
    pub socket_type: SocketType,

    /// Socket config information.
    pub socket_config: SocketConfig,

    /// Network MAC address.
    pub mac_address: MacAddress,
}

impl FromStr for NetConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-net", &["mac"])?;

        let mut socket_type: Option<SocketType> = None;
        let mut socket_config = SocketConfig::default();

        if let Some(path) = args.remove(SOCK_TYPE_UNIX_SOCKET_PATH) {
            let path = PathBuf::from_str(path.as_str())
                .context("virtio-net \"unixSocketPath\" is not a valid path")?;
            socket_config = SocketConfig {
                path: Some(path),
                fd: None,
                offloading: true,
                send_vfkit_magic: true,
            };

            socket_type = Some(SocketType::UnixGram);
        }

        if let Some(t) = args.remove("type") {
            if socket_type.is_some() {
                return Err(anyhow!(
                    "virtio-net \"type\" and \"unixSocketPath\" are mutually exclusive and cannot be used together."
                ));
            }

            let (_type, _conf) = parse_socket_config(&t, &mut args)?;
            socket_config = _conf;
            socket_type = Some(_type);
        }

        if socket_type.is_none() {
            return Err(anyhow!(
                "virtio-net device is missing \"type\" or \"unixSocketPath\""
            ));
        };

        let mac = args.remove("mac").unwrap();

        let net_config = NetConfig {
            socket_type: socket_type.unwrap(),
            socket_config,
            mac_address: MacAddress::from_str(mac.as_str())
                .context("virtio-net unable to parse address from \"mac\" argument")?,
        };

        check_unknown_args(args, "virtio-net")?;

        Ok(net_config)
    }
}

fn parse_socket_config(
    socket_type: &str,
    args: &mut std::collections::HashMap<String, String>,
) -> Result<(SocketType, SocketConfig), anyhow::Error> {
    let mut socket_config = SocketConfig::default();

    let socket_type = match socket_type {
        SOCK_TYPE_UNIXGRAM => SocketType::UnixGram,
        SOCK_TYPE_UNIXSTREAM => SocketType::UnixStream,
        _ => {
            return Err(anyhow!(
                "virtio-net unsupported \"type\" input {socket_type}"
            ))
        }
    };

    if let Some(path) = args.remove("path") {
        socket_config.path = Some(
            PathBuf::from_str(path.as_ref()).context("virtio-net \"path\" is not a valid path")?,
        );
    }

    if let Some(fd) = args.remove("fd") {
        socket_config.fd = Some(
            fd.parse::<RawFd>()
                .context("virtio-net unable to convert \"fd\" value {fd} to a file descriptor")?,
        );
    }

    if socket_config.fd.is_some() && socket_config.path.is_some() {
        return Err(anyhow!(
                    "virtio-net device arguments \"path\" and \"fd\" are mutually exclusive and cannot be used together"
                ));
    }

    if let Some(offloading) = args.remove("offloading") {
        socket_config.offloading = parse_boolean(&offloading)?;
    }

    if let Some(send_vfkit_magic) = args.remove("vfkitMagic") {
        if socket_type != SocketType::UnixGram {
            return Err(anyhow!(
                "virtio-net only \"type=unixgram\" supports the vfkitMagic argument"
            ));
        }
        socket_config.send_vfkit_magic = parse_boolean(&send_vfkit_magic)?;
    }

    Ok((socket_type, socket_config))
}

/// Set the gvproxy's path and network MAC address.
impl KrunContextSet for NetConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        match &self.socket_type {
            SocketType::UnixGram => {
                let features = if self.socket_config.offloading {
                    COMPAT_NET_FEATURES
                } else {
                    0
                };

                let path = match &self.socket_config.path {
                    Some(path) => path_to_cstring(path)?,
                    None => path_to_cstring(&PathBuf::new())?,
                };

                let flags = if self.socket_config.send_vfkit_magic {
                    NET_FLAG_VFKIT
                } else {
                    0
                };

                if krun_add_net_unixgram(
                    id,
                    cstring_to_ptr(&path),
                    self.socket_config.fd.unwrap_or(-1),
                    self.mac_address.bytes().as_ptr(),
                    features,
                    flags,
                ) < 0
                {
                    // TODO(jakecorrenti): if this fails, we should display all of the values the
                    // user provided to the virtio-net cmdline
                    return Err(anyhow!(format!(
                        "virtio-net unable to add device with unix datagram backend {:#?}",
                        self.socket_config
                    )));
                }
            }
            SocketType::UnixStream => {
                let features = if self.socket_config.offloading {
                    COMPAT_NET_FEATURES
                } else {
                    0
                };

                let path = match &self.socket_config.path {
                    Some(path) => path_to_cstring(path)?,
                    None => path_to_cstring(&PathBuf::new())?,
                };

                if krun_add_net_unixstream(
                    id,
                    cstring_to_ptr(&path),
                    self.socket_config.fd.unwrap_or(-1),
                    self.mac_address.bytes().as_ptr(),
                    features,
                    0,
                ) < 0
                {
                    // TODO(jakecorrenti): if this fails, we should display all of the values the
                    // user provided to the virtio-net cmdline
                    return Err(anyhow!(format!(
                        "virtio-net unable to add device with unix stream backend {:#?}",
                        self.socket_config
                    )));
                }
            }
        }

        Ok(())
    }
}

/// Configuration of a virtio-fs device.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FsConfig {
    /// Shared directory with the host.
    pub shared_dir: PathBuf,

    /// Guest mount tag for shared directory.
    pub mount_tag: PathBuf,
}

impl FromStr for FsConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut fs_config = FsConfig::default();
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-fs", &["sharedDir", "mountTag"])?;

        let shared_dir = args.remove("sharedDir").unwrap();
        fs_config.shared_dir = PathBuf::from_str(shared_dir.as_str())
            .context("sharedDir argument is not a valid path")?;

        let mount_tag = args.remove("mountTag").unwrap();
        fs_config.mount_tag =
            PathBuf::from_str(mount_tag.as_str()).context("mountTag argument not a valid path")?;

        check_unknown_args(args, "virtio-fs")?;

        Ok(fs_config)
    }
}

/// Set the shared directory with its guest mount tag.
impl KrunContextSet for FsConfig {
    unsafe fn krun_ctx_set(&self, id: u32) -> Result<(), anyhow::Error> {
        let shared_dir_cstr = path_to_cstring(&self.shared_dir)?;
        let mount_tag_cstr = path_to_cstring(&self.mount_tag)?;

        if krun_add_virtiofs(id, mount_tag_cstr.as_ptr(), shared_dir_cstr.as_ptr()) < 0 {
            return Err(anyhow!(format!(
                "unable to add virtiofs shared directory {} with mount tag {}",
                &self.shared_dir.display(),
                &self.mount_tag.display()
            )));
        }

        Ok(())
    }
}

/// Configuration of a virtio-gpu device.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GpuConfig {
    /// Width (pixels).
    pub width: u32,

    /// Height (pixels).
    pub height: u32,
}

impl FromStr for GpuConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut gpu_config = GpuConfig::default();
        let mut args = parse_args(s.to_string())?;
        check_required_args(&args, "virtio-gpu", &["height", "width"])?;

        let width = args.remove("width").unwrap();
        gpu_config.width = u32::from_str(width.as_str()).context(format!(
            "GPU width argument out of range (0x0 - 0x{:x})",
            u32::MAX
        ))?;

        let height = args.remove("height").unwrap();
        gpu_config.height = u32::from_str(height.as_str()).context(format!(
            "GPU height argument out of range (0x0 - 0x{:x})",
            u32::MAX
        ))?;

        check_unknown_args(args, "virtio-gpu")?;

        Ok(gpu_config)
    }
}

/// Configuration of a virtio-input device. This is an enum indicating which virtio-input device a
/// user would like to include with the VM.
#[derive(Clone, Debug, PartialEq)]
pub enum InputConfig {
    Keyboard,
    Pointing,
}

impl FromStr for InputConfig {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let args = parse_args(s.to_string())?;

        if args.len() != 1 {
            return Err(anyhow!("invalid virtio-input config: {s}"));
        }

        let (key, value) = args.into_iter().next().unwrap();
        if !value.is_empty() {
            return Err(anyhow!(format!(
                "unexpected value for virtio-input argument: {key}={value}"
            )));
        }
        match key.as_str() {
            "keyboard" => Ok(Self::Keyboard),
            "pointing" => Ok(Self::Pointing),
            _ => Err(anyhow!("unknown virtio-input argument: {key}")),
        }
    }
}

/// Construct a NULL-terminated C string from a Rust Path object.
fn path_to_cstring(path: &Path) -> Result<CString, anyhow::Error> {
    let cstring = CString::new(path.as_os_str().as_bytes()).context(format!(
        "unable to convert path {} into NULL-terminated C string",
        path.display()
    ))?;

    Ok(cstring)
}