isothrum_runner/graphical.rs
1//! A machine's graphical console (its screen, keyboard and mouse), found where its hypervisor
2//! keeps it, asked through the run's format driver ([`crate::formats::FormatDriver::graphical`]):
3//! [`ConsoleOffer`], what a status says of each machine's, and [`Console`], what
4//! [`crate::Running::graphical_console`] reaches.
5//!
6//! The runner guarantees where a console answers: a TCP port of this computer's loopback
7//! ([`Endpoint::Loopback`]), refusing one the hypervisor says listens anywhere else and one that
8//! doesn't answer, or, for Proxmox VE, its API's own VNC websocket with a ticket for this session
9//! ([`Endpoint::ProxmoxVnc`]).
10//!
11//! - **VirtualBox** (Vagrant): its remote display (RDP), as `VBoxManage showvminfo` says of the
12//! VM Vagrant records.
13//! - **libvirt** (Vagrant): `virsh domdisplay` of the domain Vagrant records.
14//! - **QEMU** (vagrant-qemu): `info vnc` on the VM's monitor socket.
15//! - **Proxmox VE** (Terraform): `vncproxy` over its API, the VM's node and id from the module's
16//! state.
17//! - **A module's Windows VM** (Terraform): its Remote Desktop (or a VNC server the module names),
18//! which answers only on the module's own networks, through an SSH tunnel from this computer's
19//! loopback to the Linux machine beside it ([`tunnel`]): a [`Tunnel`] the [`Console`] owns.
20//!
21//! The other hypervisors give no screen the runner reaches: their VMs open in the hypervisor's
22//! own app ([`native`]).
23
24pub(crate) mod native;
25pub(crate) mod tunnel;
26
27use std::net::SocketAddr;
28
29use serde::{Deserialize, Serialize};
30
31use crate::error::Error;
32use crate::secrets::SecretValue;
33
34pub use native::{NativeApp, NativeConsole, NativeNeed, NativeOpen};
35pub use tunnel::Tunnel;
36
37/// The protocol a graphical console speaks.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
39#[serde(rename_all = "snake_case")]
40#[non_exhaustive]
41pub enum ConsoleProtocol {
42 /// VNC (RFB).
43 Vnc,
44 /// RDP (VirtualBox's remote display).
45 Rdp,
46 /// None the runner reaches.
47 None,
48}
49
50/// What a status says of a machine's graphical console: its protocol, or `none` and why.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
52#[non_exhaustive]
53pub struct ConsoleOffer {
54 /// `vnc`, `rdp`, or `none`.
55 pub protocol: ConsoleProtocol,
56 /// Why there is none, or what it needs (an extension pack).
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub note: Option<String>,
59 /// Why it can't be shown now, as the status found it on a running machine: its hypervisor
60 /// gives it no display (a VM started without one). None when it can, or wasn't looked at: the
61 /// machine doesn't run, it has none, or it is reached through Proxmox's API, which a status
62 /// doesn't open.
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub unavailable: Option<String>,
65}
66
67impl ConsoleOffer {
68 /// A console of `protocol`, saying `note`.
69 pub(crate) fn of(protocol: ConsoleProtocol, note: Option<&str>) -> ConsoleOffer {
70 ConsoleOffer {
71 protocol,
72 note: note.map(str::to_owned),
73 unavailable: None,
74 }
75 }
76
77 /// No console the runner reaches, saying why.
78 pub(crate) fn none(why: &str) -> ConsoleOffer {
79 ConsoleOffer::of(ConsoleProtocol::None, Some(why))
80 }
81
82 /// This offer, unavailable now for the reason `why` gives (none: it is).
83 pub(crate) fn unavailable(mut self, why: Option<String>) -> ConsoleOffer {
84 self.unavailable = why;
85 self
86 }
87}
88
89/// Where a graphical console answers.
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub enum Endpoint {
93 /// A TCP port of this computer's loopback speaking the console's protocol (VNC, RDP).
94 Loopback(SocketAddr),
95 /// Proxmox VE's VNC websocket, through its API.
96 ProxmoxVnc(ProxmoxVnc),
97}
98
99/// Proxmox VE's VNC websocket for one VM, opened for one session: connect to `websocket` with
100/// the `authorization` header (its certificate pinned, not chain-verified, when `insecure`), then speak VNC with `ticket` as
101/// the password. Every secret is a [`SecretValue`]: never print or log one.
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct ProxmoxVnc {
105 /// `wss://<server>/api2/json/nodes/<node>/qemu/<id>/vncwebsocket?port=<port>&vncticket=<ticket>`:
106 /// it holds the ticket.
107 pub websocket: SecretValue,
108 /// The VNC port `vncproxy` opened on the node (in the URL already).
109 pub port: u16,
110 /// The ticket: the VNC password, and in the URL.
111 pub ticket: SecretValue,
112 /// The header that signs the websocket in: its name (`Authorization`, `Cookie`) and value.
113 pub authorization: (String, SecretValue),
114 /// The server's certificate is trusted by the SHA-256 fingerprint the run pins
115 /// (`PROXMOX_VE_TLS_FINGERPRINT`, a self-signed one), not by a trusted authority's chain: the
116 /// websocket's client checks it by the same pin.
117 pub insecure: bool,
118}
119
120/// A machine's graphical console the runner reached: where it answers, and how to sign in.
121#[derive(Debug)]
122#[non_exhaustive]
123pub struct Console {
124 /// The machine.
125 pub machine: String,
126 /// The protocol it speaks: VNC or RDP.
127 pub protocol: ConsoleProtocol,
128 /// Where it answers.
129 pub endpoint: Endpoint,
130 /// The account to sign in as, when it signs in to the machine's own OS (a Windows VM's
131 /// Remote Desktop: its administrator).
132 pub user: Option<String>,
133 /// Its password (Proxmox's ticket, a Windows VM's administrator password, from the module's
134 /// sensitive output). Never print or log it.
135 pub password: Option<SecretValue>,
136 /// What to know of it (the extension pack VirtualBox's takes, the machine a tunnel goes
137 /// through).
138 pub note: Option<String>,
139 /// The SSH tunnel it is reached through, when it is ([`Endpoint::Loopback`] is the tunnel's
140 /// end): open for as long as this console is kept, ended when it is dropped. A viewer keeps
141 /// the console while it shows the screen, and can wait on [`Tunnel::closed`] beside its own
142 /// end.
143 pub tunnel: Option<Tunnel>,
144 /// Where the tunnel goes, as the driver read it, until the core opens it
145 /// ([`crate::Running::graphical_console`]): the endpoint is no address until then.
146 pub(crate) through: Option<tunnel::To>,
147}
148
149impl Console {
150 /// `machine`'s console speaking `protocol` at `endpoint`, reached through no tunnel: what an
151 /// engine other than the runner's gives (the runner's service answers through one).
152 #[must_use]
153 pub fn new(machine: &str, protocol: ConsoleProtocol, endpoint: Endpoint) -> Console {
154 Console {
155 machine: machine.to_owned(),
156 protocol,
157 endpoint,
158 user: None,
159 password: None,
160 note: None,
161 tunnel: None,
162 through: None,
163 }
164 }
165
166 /// `machine`'s console speaking `protocol`, reached through a tunnel to `to` the core opens:
167 /// its endpoint is the tunnel's end once it is.
168 pub(crate) fn tunnelled(machine: &str, protocol: ConsoleProtocol, to: tunnel::To) -> Console {
169 let unopened = Endpoint::Loopback(SocketAddr::from(([127, 0, 0, 1], 0)));
170 let mut console = Console::new(machine, protocol, unopened);
171 console.through = Some(to);
172 console
173 }
174
175 /// The console, saying `note`.
176 pub(crate) fn with_note(mut self, note: Option<&str>) -> Console {
177 self.note = note.map(str::to_owned);
178 self
179 }
180}
181
182/// [`Error::NoConsole`] for `machine`, saying `why`.
183pub(crate) fn no_console(machine: &str, why: impl Into<String>) -> Error {
184 Error::NoConsole {
185 machine: machine.to_owned(),
186 why: why.into(),
187 }
188}
189
190/// `at`, when it is on this computer's loopback; refused otherwise, whatever the hypervisor says:
191/// the runner never hands out a console on the network.
192pub(crate) fn on_loopback(machine: &str, at: SocketAddr) -> crate::Result<SocketAddr> {
193 if at.ip().is_loopback() {
194 Ok(at)
195 } else {
196 Err(no_console(
197 machine,
198 format!("its console listens on {at}, not on this computer's loopback: the runner refuses it"),
199 ))
200 }
201}
202
203/// Why `found` (an attempt to reach a console) gives none, as a status says it: the error's own
204/// words for a console the hypervisor doesn't give, any other error's text.
205pub(crate) fn why_not<T>(found: crate::Result<T>) -> Option<String> {
206 match found {
207 Ok(_) => None,
208 Err(Error::NoConsole { why, .. }) => Some(why),
209 Err(e) => Some(e.to_string()),
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 #[test]
218 fn a_console_off_the_loopback_is_refused() {
219 assert!(on_loopback("web", "127.0.0.1:5900".parse().unwrap()).is_ok());
220 assert!(on_loopback("web", "[::1]:5900".parse().unwrap()).is_ok());
221 for lan in ["0.0.0.0:5900", "192.168.1.20:5900", "[::]:5900"] {
222 let err = on_loopback("web", lan.parse().unwrap()).unwrap_err();
223 assert_eq!(err.code(), crate::ErrorCode::NoConsole, "{lan}");
224 assert!(err.to_string().contains("not on this computer's loopback"), "{err}");
225 }
226 }
227
228 #[test]
229 fn an_offer_says_its_protocol_and_why_it_cant_be_shown() {
230 let offer = ConsoleOffer::of(ConsoleProtocol::Rdp, Some("needs the extension pack")).unavailable(Some("off".into()));
231 let json = serde_json::to_value(&offer).unwrap();
232 assert_eq!(
233 json,
234 serde_json::json!({ "protocol": "rdp", "note": "needs the extension pack", "unavailable": "off" })
235 );
236 assert_eq!(serde_json::to_value(ConsoleOffer::none("x")).unwrap()["protocol"], "none");
237 }
238}