Skip to main content

isothrum_runner/graphical/
native.rs

1//! A VM's screen in its hypervisor's own app, beside the embedder's viewer: which app the run's
2//! provider has ([`NativeApp`], in a status), and what opens a running VM in it
3//! ([`NativeConsole`], [`crate::Running::native_console`]). The runner runs nothing to open it:
4//! it hands the embedder a program and its arguments (never a shell line), a macOS app and what
5//! it opens, or an `https` URL, each argument checked first.
6//!
7//! - **VirtualBox**: `VBoxManage startvm <vm> --type separate`, a window on the headless VM.
8//! - **Hyper-V**: `vmconnect.exe localhost <vm>`.
9//! - **libvirt**: `virt-viewer --connect <uri> <domain>`, else `remote-viewer vnc://…`.
10//! - **VMware**: Fusion on a Mac, Workstation elsewhere, on the VM's `.vmx` (Vagrant's record).
11//! - **Parallels Desktop**: on the VM's bundle, as `prlctl` says where it is.
12//! - **UTM**: its `utm://` link to the VM.
13//! - **ESXi**: the Host Client's console of the VM (Vagrant's record of its id).
14//! - **Proxmox VE**: its web console of the VM.
15//! - **QEMU** (vagrant-qemu) has no app: none is offered.
16
17use std::path::PathBuf;
18
19use isoloom_manifest::{ConsoleSource, Driver, HostOs, Machine, Provider};
20use serde::{Deserialize, Serialize};
21
22use super::{none, vagrant};
23use crate::Result;
24use crate::error::Error;
25use crate::executor::{Cx, Echo, call};
26use crate::process::ProcessSpec;
27
28/// What of a hypervisor's app must be on this computer for a way to open it.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
30#[serde(rename_all = "snake_case", tag = "kind", content = "at")]
31#[non_exhaustive]
32pub enum NativeNeed {
33    /// A program, by its name on `PATH` or its full path.
34    Program(String),
35    /// A macOS app bundle.
36    MacApp(PathBuf),
37    /// The default browser (a web console).
38    Browser,
39}
40
41/// The hypervisor's own app that shows a running VM's screen in a window of its own, and what of
42/// it this computer must have (any one of `needs`).
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
44#[non_exhaustive]
45pub struct NativeApp {
46    /// Its name as its maker writes it (`VirtualBox`, `VMware Fusion`): what a button names.
47    pub name: String,
48    /// What opens it, best first: the program or app [`NativeConsole::ways`] runs, in the same
49    /// order.
50    pub needs: Vec<NativeNeed>,
51}
52
53/// One way to open a VM in its hypervisor's app: what to run, never through a shell.
54#[derive(Debug, Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum NativeOpen {
57    /// Run `program` (a name on `PATH`, or a full path) with `args`, each passed as it is.
58    Program {
59        /// The program.
60        program: String,
61        /// Its arguments.
62        args: Vec<String>,
63    },
64    /// Open the macOS app `app` on `args` (`open -a <app> <args>…`: a file or link it opens).
65    MacApp {
66        /// The app bundle.
67        app: PathBuf,
68        /// What it opens.
69        args: Vec<String>,
70    },
71    /// Open `url` (`https`) in the default browser.
72    Url {
73        /// The URL.
74        url: String,
75    },
76}
77
78impl NativeOpen {
79    /// What of the app this way needs on this computer.
80    #[must_use]
81    pub fn need(&self) -> NativeNeed {
82        match self {
83            NativeOpen::Program { program, .. } => NativeNeed::Program(program.clone()),
84            NativeOpen::MacApp { app, .. } => NativeNeed::MacApp(app.clone()),
85            NativeOpen::Url { .. } => NativeNeed::Browser,
86        }
87    }
88}
89
90/// What opens a running VM's screen in its hypervisor's own app.
91#[derive(Debug, Clone, PartialEq, Eq)]
92#[non_exhaustive]
93pub struct NativeConsole {
94    /// The machine.
95    pub machine: String,
96    /// The app's name ([`NativeApp::name`]).
97    pub app: String,
98    /// The ways to open it, best first: the first whose program or app this computer has is
99    /// the one to take.
100    pub ways: Vec<NativeOpen>,
101}
102
103/// Where VMware Workstation installs on Windows, newest layout first.
104const WORKSTATION_WINDOWS: [&str; 2] = [
105    r"C:\Program Files (x86)\VMware\VMware Workstation\vmware.exe",
106    r"C:\Program Files\VMware\VMware Workstation\vmware.exe",
107];
108
109/// Where the macOS apps install.
110const FUSION: &str = "/Applications/VMware Fusion.app";
111const PARALLELS: &str = "/Applications/Parallels Desktop.app";
112const UTM: &str = "/Applications/UTM.app";
113
114/// The app a run on `provider` (its manifest `manifest`) shows its VMs in on host `host`; none
115/// where it has none (vagrant-qemu), or for a run of containers.
116pub(crate) fn app(manifest: &isoloom_manifest::Manifest, provider: Option<Provider>, host: HostOs) -> Option<NativeApp> {
117    let program = |p: &str| NativeNeed::Program(p.to_owned());
118    let mac = |p: &str| NativeNeed::MacApp(PathBuf::from(p));
119    let (name, needs) = match (manifest.driver, provider) {
120        (Driver::Vagrant, Some(Provider::Virtualbox)) => ("VirtualBox", vec![program("VBoxManage")]),
121        (Driver::Vagrant, Some(Provider::Hyperv)) => ("Hyper-V", vec![program("vmconnect.exe")]),
122        (Driver::Vagrant, Some(Provider::Libvirt)) => ("virt-viewer", vec![program("virt-viewer"), program("remote-viewer")]),
123        (Driver::Vagrant, Some(Provider::VmwareDesktop)) => match host {
124            HostOs::Macos => ("VMware Fusion", vec![mac(FUSION)]),
125            HostOs::Windows => ("VMware Workstation", WORKSTATION_WINDOWS.iter().map(|p| program(p)).collect()),
126            HostOs::Linux => ("VMware Workstation", vec![program("vmware")]),
127        },
128        (Driver::Vagrant, Some(Provider::Parallels)) => ("Parallels Desktop", vec![mac(PARALLELS)]),
129        (Driver::Vagrant, Some(Provider::Utm)) => ("UTM", vec![mac(UTM)]),
130        (Driver::Vagrant, Some(Provider::VmwareEsxi)) => ("ESXi", vec![NativeNeed::Browser]),
131        (Driver::Terraform, _) if manifest.machines.iter().any(proxmox) => ("Proxmox VE", vec![NativeNeed::Browser]),
132        _ => return None,
133    };
134    Some(NativeApp { name: name.to_owned(), needs })
135}
136
137/// Whether `m`'s console is Proxmox VE's.
138fn proxmox(m: &Machine) -> bool {
139    m.consoles.iter().any(|c| matches!(c.source, Some(ConsoleSource::ProxmoxApi { .. })))
140}
141
142/// What opens running machine `machine` in the app the run's provider has, `app` being it: the
143/// ways [`NativeApp::needs`] names, with their arguments.
144pub(crate) async fn console(cx: &Cx<'_>, machine: &Machine, app: &NativeApp) -> Result<NativeConsole> {
145    let provider = cx.scope.provider;
146    let ways = match provider {
147        _ if cx.run.manifest().driver == Driver::Terraform => vec![proxmox_url(cx, machine)?],
148        Some(Provider::Virtualbox) => {
149            let vm = argument(machine, vagrant::vm_name(machine, Provider::Virtualbox)?)?;
150            vec![program("VBoxManage", ["startvm", vm, "--type", "separate"])]
151        }
152        Some(Provider::Hyperv) => vec![program(
153            "vmconnect.exe",
154            ["localhost", argument(machine, vagrant::vm_name(machine, Provider::Hyperv)?)?],
155        )],
156        Some(Provider::Libvirt) => libvirt(cx, machine).await?,
157        Some(Provider::VmwareDesktop) => {
158            let vmx = recorded(cx, machine, "vmware_desktop")?;
159            let vmx = argument(machine, &vmx)?.to_owned();
160            app.needs
161                .iter()
162                .filter_map(|need| match need {
163                    NativeNeed::MacApp(bundle) => Some(NativeOpen::MacApp {
164                        app: bundle.clone(),
165                        args: vec![vmx.clone()],
166                    }),
167                    NativeNeed::Program(p) => Some(program(p, [vmx.as_str()])),
168                    NativeNeed::Browser => None,
169                })
170                .collect()
171        }
172        Some(Provider::Parallels) => vec![NativeOpen::MacApp {
173            app: PathBuf::from(PARALLELS),
174            args: vec![parallels_bundle(cx, machine).await?],
175        }],
176        Some(Provider::Utm) => {
177            let vm = argument(machine, vagrant::vm_name(machine, Provider::Utm)?)?;
178            vec![NativeOpen::MacApp {
179                app: PathBuf::from(UTM),
180                args: vec![format!("utm://start?name={}", percent(vm))],
181            }]
182        }
183        Some(Provider::VmwareEsxi) => vec![esxi_url(cx, machine)?],
184        Some(Provider::Qemu) | None => return Err(no_app(machine)),
185    };
186    Ok(NativeConsole {
187        machine: machine.name.to_string(),
188        app: app.name.clone(),
189        ways,
190    })
191}
192
193/// `program` with `args`.
194fn program<'a>(program: &str, args: impl IntoIterator<Item = &'a str>) -> NativeOpen {
195    NativeOpen::Program {
196        program: program.to_owned(),
197        args: args.into_iter().map(str::to_owned).collect(),
198    }
199}
200
201/// `value` as one argument of a program: refused when it could be read as anything else (empty,
202/// an option, a control character, a line break).
203fn argument<'a>(machine: &Machine, value: &'a str) -> Result<&'a str> {
204    if value.trim().is_empty() || value.starts_with('-') || value.chars().any(char::is_control) {
205        return Err(none(
206            machine,
207            format!("its VM's name or file `{}` can't be handed to its app", value.escape_debug()),
208        ));
209    }
210    Ok(value)
211}
212
213/// What Vagrant records of `machine`'s VM under `provider_dir` (`<dotfile>/machines/<define>/<provider>/id`):
214/// VMware's `.vmx` path, ESXi's VM id, Parallels' VM UUID.
215fn recorded(cx: &Cx<'_>, machine: &Machine, provider_dir: &str) -> Result<String> {
216    let path = vagrant::dotfile(cx)?
217        .join("machines")
218        .join(vagrant::define(machine)?)
219        .join(provider_dir)
220        .join("id");
221    vagrant::read_if_there(&path)?
222        .map(|s| s.trim().to_owned())
223        .filter(|s| !s.is_empty())
224        .ok_or_else(|| none(machine, "Vagrant records no VM for it: it isn't up"))
225}
226
227/// libvirt's viewers: `virt-viewer` on the domain, over the run's connection; else
228/// `remote-viewer` on the display libvirt says, when it says one.
229async fn libvirt(cx: &Cx<'_>, machine: &Machine) -> Result<Vec<NativeOpen>> {
230    let domain = argument(machine, vagrant::vm_name(machine, Provider::Libvirt)?)?;
231    let uri = vagrant::libvirt_uri(&cx.run.runner.config.host_env);
232    let mut ways = vec![program("virt-viewer", ["--connect", argument(machine, &uri)?, domain])];
233    if let Ok(super::Endpoint::Loopback(at)) = vagrant::libvirt(cx, machine).await {
234        let display = at.port().saturating_sub(5900);
235        ways.push(program("remote-viewer", [format!("vnc://{}:{display}", at.ip()).as_str()]));
236    }
237    Ok(ways)
238}
239
240/// The bundle of `machine`'s Parallels VM: where `prlctl list --info --json <uuid>` says it is
241/// (`Home`).
242async fn parallels_bundle(cx: &Cx<'_>, machine: &Machine) -> Result<String> {
243    let uuid = recorded(cx, machine, "parallels")?;
244    let uuid = argument(machine, &uuid)?;
245    let spec = ProcessSpec::new("prlctl", ["list", "--info", "--json", uuid]);
246    let out = call(cx, "console", &spec, std::time::Duration::from_secs(30), Echo::Quiet).await?;
247    if !out.success() {
248        return Err(none(machine, format!("Parallels didn't say where its VM is: {}", out.reason())));
249    }
250    let said: serde_json::Value = serde_json::from_str(&out.stdout.join("\n")).unwrap_or_default();
251    let home = said
252        .as_array()
253        .and_then(|vms| vms.first())
254        .and_then(|vm| vm.get("Home"))
255        .and_then(serde_json::Value::as_str)
256        .ok_or_else(|| none(machine, "Parallels didn't say where its VM is"))?;
257    Ok(argument(machine, home.trim_end_matches('/'))?.to_owned())
258}
259
260/// The ESXi Host Client's console of `machine`'s VM: `https://<host>/ui/#/console/<id>`.
261fn esxi_url(cx: &Cx<'_>, machine: &Machine) -> Result<NativeOpen> {
262    let host = cx
263        .vars
264        .params()
265        .get(isoloom_manifest::contract::ESXI_HOSTNAME)
266        .filter(|h| host_name(h))
267        .ok_or_else(|| none(machine, "the run names no ESXi host"))?;
268    let id = recorded(cx, machine, "vmware_esxi")?;
269    if !id.chars().all(|c| c.is_ascii_digit()) {
270        return Err(none(machine, format!("its ESXi VM id `{}` isn't one", id.escape_debug())));
271    }
272    Ok(NativeOpen::Url {
273        url: format!("https://{host}/ui/#/console/{id}"),
274    })
275}
276
277/// Proxmox VE's web console of `machine`'s VM: `<endpoint>?console=kvm&novnc=1&vmid=<id>&node=<node>`.
278fn proxmox_url(cx: &Cx<'_>, machine: &Machine) -> Result<NativeOpen> {
279    let Some(ConsoleSource::ProxmoxApi { endpoint, node, vm_id, .. }) = machine
280        .consoles
281        .iter()
282        .find_map(|c| c.source.as_ref().filter(|s| matches!(s, ConsoleSource::ProxmoxApi { .. })))
283    else {
284        return Err(none(machine, "it isn't a Proxmox VE VM"));
285    };
286    let at = |field: &str| format!("machines.{}.consoles.source.{field}", machine.name);
287    let endpoint = cx.vars.render(endpoint, &at("endpoint"))?;
288    let node = cx.vars.render(node, &at("node"))?;
289    let vm_id = cx.vars.render(vm_id, &at("vm_id"))?;
290    let base = endpoint.trim_end_matches('/');
291    let server = base.strip_prefix("https://").filter(|s| host_name(s.split(':').next().unwrap_or_default()));
292    let port_ok = base
293        .split_once("://")
294        .and_then(|(_, rest)| rest.split_once(':'))
295        .is_none_or(|(_, p)| p.parse::<u16>().is_ok());
296    if server.is_none() || !port_ok {
297        return Err(none(
298            machine,
299            format!("its Proxmox VE address `{}` isn't an https server", endpoint.escape_debug()),
300        ));
301    }
302    if !vm_id.chars().all(|c| c.is_ascii_digit()) || vm_id.is_empty() || !host_name(&node) {
303        return Err(none(machine, "its Proxmox VE node or VM id isn't one"));
304    }
305    Ok(NativeOpen::Url {
306        url: format!("{base}/?console=kvm&novnc=1&vmid={vm_id}&node={node}"),
307    })
308}
309
310/// Whether `h` is a host name or an IPv4 address, nothing else (no user, path or query).
311fn host_name(h: &str) -> bool {
312    !h.is_empty() && h.len() <= 253 && h.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.') && !h.starts_with('-')
313}
314
315/// `s` percent-encoded for a URL's query value: unreserved characters as they are.
316fn percent(s: &str) -> String {
317    s.bytes()
318        .map(|b| match b {
319            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => char::from(b).to_string(),
320            other => format!("%{other:02X}"),
321        })
322        .collect()
323}
324
325/// The error a machine whose run has no app gets.
326pub(crate) fn no_app(machine: &Machine) -> Error {
327    none(machine, "its hypervisor has no app of its own to show it in")
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn an_argument_that_could_be_read_as_more_is_refused() {
336        let m: Machine = serde_json::from_value(serde_json::json!({ "name": "web", "role": "member", "addresses": {} })).unwrap();
337        assert_eq!(argument(&m, "web-vm - web").unwrap(), "web-vm - web");
338        for bad in ["", "  ", "--type=gui", "a\nb", "a\u{0}b"] {
339            assert!(argument(&m, bad).is_err(), "{bad:?}");
340        }
341    }
342
343    #[test]
344    fn a_host_name_is_only_a_name() {
345        assert!(host_name("172.16.1.20") && host_name("pve.lab.example"));
346        for bad in ["", "-x", "a b", "user@host", "host/path", "host?q", "host#x", "h:1"] {
347            assert!(!host_name(bad), "{bad}");
348        }
349    }
350
351    #[test]
352    fn a_name_in_a_link_is_percent_encoded() {
353        assert_eq!(percent("web-vm - web"), "web-vm%20-%20web");
354        assert_eq!(percent("a&b=c"), "a%26b%3Dc");
355    }
356}