1use 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#[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 Program(String),
35 MacApp(PathBuf),
37 Browser,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
44#[non_exhaustive]
45pub struct NativeApp {
46 pub name: String,
48 pub needs: Vec<NativeNeed>,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum NativeOpen {
57 Program {
59 program: String,
61 args: Vec<String>,
63 },
64 MacApp {
66 app: PathBuf,
68 args: Vec<String>,
70 },
71 Url {
73 url: String,
75 },
76}
77
78impl NativeOpen {
79 #[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#[derive(Debug, Clone, PartialEq, Eq)]
92#[non_exhaustive]
93pub struct NativeConsole {
94 pub machine: String,
96 pub app: String,
98 pub ways: Vec<NativeOpen>,
101}
102
103const 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
109const FUSION: &str = "/Applications/VMware Fusion.app";
111const PARALLELS: &str = "/Applications/Parallels Desktop.app";
112const UTM: &str = "/Applications/UTM.app";
113
114pub(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
137fn proxmox(m: &Machine) -> bool {
139 m.consoles.iter().any(|c| matches!(c.source, Some(ConsoleSource::ProxmoxApi { .. })))
140}
141
142pub(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
193fn 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
201fn 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
213fn 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
227async 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
240async 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
260fn 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
277fn 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
310fn 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
315fn 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
325pub(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}