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//! hypervisor 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 ([`argument`]).
6//!
7//! Each format's driver says which app its machines open in and how; this module holds what they
8//! share.
9
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14use super::no_console;
15use crate::Result;
16
17/// What of a hypervisor's app must be on this computer for a way to open it.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
19#[serde(rename_all = "snake_case", tag = "kind", content = "at")]
20#[non_exhaustive]
21pub enum NativeNeed {
22    /// A program, by its name on `PATH` or its full path.
23    Program(String),
24    /// A macOS app bundle.
25    MacApp(PathBuf),
26    /// The default browser (a web console).
27    Browser,
28}
29
30/// The hypervisor's own app that shows a running VM's screen in a window of its own, and what of
31/// it this computer must have (any one of `needs`).
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
33#[non_exhaustive]
34pub struct NativeApp {
35    /// Its name as its maker writes it (`VirtualBox`, `VMware Fusion`): what a button names.
36    pub name: String,
37    /// What opens it, best first: the program or app [`NativeConsole::ways`] runs, in the same
38    /// order.
39    pub needs: Vec<NativeNeed>,
40}
41
42impl NativeApp {
43    /// App `name`, opened by `needs`.
44    pub(crate) fn new(name: &str, needs: Vec<NativeNeed>) -> NativeApp {
45        NativeApp { name: name.to_owned(), needs }
46    }
47}
48
49/// One way to open a VM in its hypervisor's app: what to run, never through a shell.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case", tag = "way")]
52#[non_exhaustive]
53pub enum NativeOpen {
54    /// Run `program` (a name on `PATH`, or a full path) with `args`, each passed as it is.
55    Program {
56        /// The program.
57        program: String,
58        /// Its arguments.
59        args: Vec<String>,
60    },
61    /// Open the macOS app `app` on `args` (`open -a <app> <args>…`: a file or link it opens).
62    MacApp {
63        /// The app bundle.
64        app: PathBuf,
65        /// What it opens.
66        args: Vec<String>,
67    },
68    /// Open `url` (`https`) in the default browser.
69    Url {
70        /// The URL.
71        url: String,
72    },
73}
74
75impl NativeOpen {
76    /// What of the app this way needs on this computer.
77    #[must_use]
78    pub fn need(&self) -> NativeNeed {
79        match self {
80            NativeOpen::Program { program, .. } => NativeNeed::Program(program.clone()),
81            NativeOpen::MacApp { app, .. } => NativeNeed::MacApp(app.clone()),
82            NativeOpen::Url { .. } => NativeNeed::Browser,
83        }
84    }
85}
86
87/// What opens a running VM's screen in its hypervisor's own app.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[non_exhaustive]
90pub struct NativeConsole {
91    /// The machine.
92    pub machine: String,
93    /// The app's name ([`NativeApp::name`]).
94    pub app: String,
95    /// The ways to open it, best first: the first whose program or app this computer has is
96    /// the one to take.
97    pub ways: Vec<NativeOpen>,
98}
99
100impl NativeConsole {
101    /// `machine` opened in `app` by `ways`.
102    pub(crate) fn new(machine: &str, app: &NativeApp, ways: Vec<NativeOpen>) -> NativeConsole {
103        NativeConsole {
104            machine: machine.to_owned(),
105            app: app.name.clone(),
106            ways,
107        }
108    }
109}
110
111/// `program` with `args`.
112pub(crate) fn program<'a>(program: &str, args: impl IntoIterator<Item = &'a str>) -> NativeOpen {
113    NativeOpen::Program {
114        program: program.to_owned(),
115        args: args.into_iter().map(str::to_owned).collect(),
116    }
117}
118
119/// `program` as a need.
120pub(crate) fn needs_program(program: &str) -> NativeNeed {
121    NativeNeed::Program(program.to_owned())
122}
123
124/// `value` as one argument of a program: refused when it could be read as anything else (empty,
125/// an option, a control character, a line break).
126pub(crate) fn argument<'a>(machine: &str, value: &'a str) -> Result<&'a str> {
127    if value.trim().is_empty() || value.starts_with('-') || value.chars().any(char::is_control) {
128        return Err(no_console(
129            machine,
130            format!("its VM's name or file `{}` can't be handed to its app", value.escape_debug()),
131        ));
132    }
133    Ok(value)
134}
135
136/// Whether `h` is a host name or an IPv4 address, nothing else (no user, path or query).
137pub(crate) fn host_name(h: &str) -> bool {
138    !h.is_empty() && h.len() <= 253 && h.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.') && !h.starts_with('-')
139}
140
141/// The error a machine whose hypervisor has no app gets.
142pub(crate) fn no_app(machine: &str) -> crate::error::Error {
143    no_console(machine, "its hypervisor has no app of its own to show it in")
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn an_argument_that_could_be_read_as_more_is_refused() {
152        assert_eq!(argument("web", "web-vm - web").unwrap(), "web-vm - web");
153        for bad in ["", "  ", "--type=gui", "a\nb", "a\u{0}b"] {
154            assert_eq!(argument("web", bad).unwrap_err().code(), crate::ErrorCode::NoConsole, "{bad:?}");
155        }
156    }
157
158    #[test]
159    fn a_host_name_is_only_a_name() {
160        assert!(host_name("172.16.1.20") && host_name("pve.stack.example"));
161        for bad in ["", "-x", "a b", "user@host", "host/path", "host?q", "host#x", "h:1"] {
162            assert!(!host_name(bad), "{bad}");
163        }
164    }
165}