1use std::net::{IpAddr, Ipv4Addr, SocketAddr};
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16use super::no_console;
17use crate::Result;
18use crate::error::Error;
19use crate::name::RunName;
20use crate::process::ProcessSpec;
21use crate::process::ledger::Recorded;
22use crate::project::platform::Protocol;
23use crate::runner::Runner;
24use crate::ssh::Login;
25
26const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
28
29const OPENING: Duration = Duration::from_secs(20);
31
32const SAYING_WHY: Duration = Duration::from_secs(2);
34
35const STEP: &str = "console";
37
38#[derive(Debug, Clone, PartialEq, Eq)]
40pub(crate) struct To {
41 pub(crate) via: Login,
43 pub(crate) host: String,
45 pub(crate) port: u16,
47 pub(crate) key: Option<PathBuf>,
50 pub(crate) known_hosts: Option<PathBuf>,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(crate) enum Purpose<'a> {
57 Console(&'a str),
59 Endpoint(&'a str),
61}
62
63impl Purpose<'_> {
64 pub(crate) fn refused(self, why: impl Into<String>) -> Error {
66 match self {
67 Purpose::Console(machine) => no_console(machine, why),
68 Purpose::Endpoint(name) => Error::ToolFailed {
69 step: "endpoint".to_owned(),
70 reason: format!("`{name}`: {}", why.into()),
71 },
72 }
73 }
74}
75
76#[derive(Debug)]
79pub struct Tunnel {
80 local: SocketAddr,
82 via: String,
84 ssh: tokio::process::Child,
86 drain: Option<tokio::task::JoinHandle<()>>,
88 _recorded: Option<Recorded>,
90}
91
92impl Drop for Tunnel {
93 fn drop(&mut self) {
94 if let Err(e) = self.ssh.start_kill() {
96 tracing::debug!(error = %e, "a console's tunnel had ended already");
97 }
98 if let Some(drain) = self.drain.take() {
99 drain.abort();
100 }
101 }
102}
103
104impl Tunnel {
105 #[must_use]
107 pub fn local(&self) -> SocketAddr {
108 self.local
109 }
110
111 pub(crate) fn runs(&mut self) -> bool {
113 matches!(self.ssh.try_wait(), Ok(None))
114 }
115
116 #[must_use]
118 pub fn via(&self) -> &str {
119 &self.via
120 }
121
122 pub async fn closed(&mut self) -> String {
126 match self.ssh.wait().await {
127 Ok(status) => match status.code() {
128 Some(code) => format!("its ssh exited with code {code}"),
129 None => "its ssh was ended by a signal".to_owned(),
130 },
131 Err(e) => format!("its ssh couldn't be waited for: {e}"),
132 }
133 }
134
135 async fn why_closed(&mut self) -> Option<String> {
138 use tokio::io::AsyncReadExt;
139 if tokio::time::timeout(SAYING_WHY, self.ssh.wait()).await.is_err()
141 && let Err(e) = self.ssh.start_kill()
142 {
143 tracing::debug!(error = %e, "a console's tunnel couldn't be stopped");
144 }
145 let mut stderr = self.ssh.stderr.take()?;
146 let mut said = Vec::new();
147 if let Ok(Err(e)) = tokio::time::timeout(SAYING_WHY, stderr.read_to_end(&mut said)).await {
148 tracing::debug!(error = %e, "a console's tunnel's standard error couldn't be read");
149 }
150 String::from_utf8_lossy(&said)
151 .lines()
152 .map(str::trim)
153 .rfind(|l| !l.is_empty())
154 .map(str::to_owned)
155 }
156
157 fn drain(&mut self) {
160 let Some(stderr) = self.ssh.stderr.take() else { return };
161 self.drain = Some(tokio::spawn(async move {
162 use tokio::io::AsyncBufReadExt;
163 let mut lines = tokio::io::BufReader::new(stderr).lines();
164 while let Ok(Some(line)) = lines.next_line().await {
165 tracing::debug!(%line, "a console's tunnel's ssh said");
166 }
167 }));
168 }
169}
170
171fn ssh_spec(purpose: Purpose<'_>, to: &To, key: &Path, state_dir: &Path, local: u16) -> Result<ProcessSpec> {
174 let address = |h: &str| !h.is_empty() && !h.starts_with('-') && h.chars().all(|c| c.is_ascii_alphanumeric() || ".:-".contains(c));
175 if !address(&to.host) {
176 return Err(purpose.refused(format!("its address `{}` isn't one a tunnel goes to", to.host.escape_debug())));
177 }
178 let forward = format!("{LOOPBACK}:{local}:{}:{}", bracketed(&to.host), to.port);
179 let mut args = crate::ssh::options(key, state_dir, crate::ssh::First::given(to.known_hosts.as_deref()))?;
180 args.extend(["-N", "-o", "ExitOnForwardFailure=yes", "-L", &forward].map(String::from));
181 args.push(to.via.target());
182 let mut spec = ProcessSpec::new("ssh", args);
183 spec.cwd = Some(state_dir.to_path_buf());
184 Ok(spec)
185}
186
187fn bracketed(host: &str) -> String {
189 if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
190}
191
192pub(crate) async fn open(runner: &Runner, run: &RunName, state_dir: &Path, purpose: Purpose<'_>, to: &To) -> Result<Tunnel> {
197 let config = &runner.config;
198 crate::ssh::ready(
199 config.processes.as_ref(),
200 state_dir,
201 &to.via.host,
202 crate::ssh::First::given(to.known_hosts.as_deref()),
203 )
204 .await?;
205 let key = to.key.clone().unwrap_or_else(|| crate::ssh::key_path(&config.home));
206 let free = runner
207 .pick_unreserved(run, Protocol::Tcp)
208 .map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?
209 .ok_or_else(|| purpose.refused("no free port on this computer's loopback for its tunnel"))?;
210 let local = free.port.get();
211 drop(free);
213 let spec = ssh_spec(purpose, to, &key, state_dir, local)?;
214 let ledger = state_dir.join(crate::process::ledger::DIR);
215 let mut tunnel = started(purpose, &spec, SocketAddr::new(LOOPBACK, local), &to.via.target(), &ledger)?;
216 let probe = || config.ports.reachable(LOOPBACK_TEXT, local, PROBE);
217 if !answers(&mut tunnel, probe, OPENING).await {
218 let because = tunnel.why_closed().await.map_or_else(String::new, |line| format!(": ssh said `{line}`"));
219 return Err(purpose.refused(format!(
220 "its tunnel through {} didn't open (SSH refused, or {}:{} doesn't answer from there){because}",
221 tunnel.via, to.host, to.port
222 )));
223 }
224 tunnel.drain();
225 Ok(tunnel)
226}
227
228const PROBE: Duration = Duration::from_secs(2);
230
231const POLL: Duration = Duration::from_millis(200);
233
234const LOOPBACK_TEXT: &str = "127.0.0.1";
236
237async fn answers<'a>(tunnel: &mut Tunnel, probe: impl Fn() -> crate::BoxFuture<'a, bool>, within: Duration) -> bool {
242 let deadline = tokio::time::Instant::now() + within;
243 loop {
244 if probe().await {
245 return true;
246 }
247 if !tunnel.runs() || tokio::time::Instant::now() >= deadline {
248 return false;
249 }
250 tokio::time::sleep(POLL).await;
251 }
252}
253
254fn started(purpose: Purpose<'_>, spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> Result<Tunnel> {
257 start(spec, local, via, ledger).map_err(|e| match e.kind() {
258 std::io::ErrorKind::NotFound => Error::ToolMissing {
259 step: STEP.to_owned(),
260 tool: spec.program.clone(),
261 },
262 _ => purpose.refused(format!("its tunnel's `{}` didn't start: {e}", spec.program)),
263 })
264}
265
266#[expect(
270 clippy::disallowed_methods,
271 reason = "the SSH tunnel is a long-lived child its `Tunnel` owns and stops, not a call the process module waits on"
272)]
273fn start(spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> std::io::Result<Tunnel> {
274 let mut command = tokio::process::Command::new(&spec.program);
275 command
276 .args(&spec.args)
277 .envs(spec.env.iter().map(|(k, v)| (k, v)))
278 .stdin(std::process::Stdio::null())
279 .stdout(std::process::Stdio::null())
280 .stderr(std::process::Stdio::piped())
281 .kill_on_drop(true);
282 if let Some(cwd) = &spec.cwd {
283 command.current_dir(cwd);
284 }
285 own_group(&mut command);
286 let ssh = command.spawn()?;
287 let recorded = ssh.id().and_then(|pid| Recorded::tunnel(ledger, pid));
288 Ok(Tunnel {
289 local,
290 via: via.to_owned(),
291 ssh,
292 drain: None,
293 _recorded: recorded,
294 })
295}
296
297#[cfg(unix)]
300fn own_group(command: &mut tokio::process::Command) {
301 command.process_group(0);
302}
303
304#[cfg(windows)]
307fn own_group(command: &mut tokio::process::Command) {
308 use windows::Win32::System::Threading::CREATE_NO_WINDOW;
309 command.creation_flags(CREATE_NO_WINDOW.0);
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 fn to(host: &str) -> To {
317 To {
318 via: Login::new("admin", "203.0.113.7").unwrap(),
319 host: host.to_owned(),
320 port: 3389,
321 key: None,
322 known_hosts: None,
323 }
324 }
325
326 #[test]
327 fn the_forward_listens_on_the_loopback_and_checks_the_pinned_keys() {
328 use crate::process::fake::CallView as _;
329 let dir = tempfile::tempdir().unwrap();
330 let spec = ssh_spec(Purpose::Console("dc"), &to("10.9.0.20"), Path::new("/k/id"), dir.path(), 40000).unwrap();
331 assert_eq!(spec.flag("-L"), Some("127.0.0.1:40000:10.9.0.20:3389"), "{:?}", spec.args);
332 for never_waits in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ConnectTimeout=10"] {
333 assert!(spec.has_run(&["-o", never_waits]), "{never_waits}: {:?}", spec.args);
334 }
335 assert!(!spec.args.iter().any(|a| a.ends_with("=accept-new")), "{:?}", spec.args);
336 assert_eq!((spec.flag("-F"), spec.flag("-i")), (Some("none"), Some("/k/id")), "{:?}", spec.args);
337 assert_eq!(spec.args.last().map(String::as_str), Some("admin@203.0.113.7"));
338 let refused = ssh_spec(Purpose::Console("dc"), &to("-oProxyCommand=x"), Path::new("/k"), dir.path(), 1).unwrap_err();
339 assert_eq!(refused.code(), crate::ErrorCode::NoConsole, "an option, never an address: {refused}");
340 }
341
342 #[test]
343 fn an_ipv6_host_is_bracketed_in_the_forward() {
344 assert_eq!(bracketed("fd00::5"), "[fd00::5]");
345 assert_eq!(bracketed("10.0.1.5"), "10.0.1.5");
346 }
347
348 #[test]
349 fn a_missing_ssh_is_a_tool_missing() {
350 let dir = tempfile::tempdir().unwrap();
351 let spec = ProcessSpec::new("isothrum-no-such-ssh", ["-N"]);
352 let err = started(Purpose::Console("dc"), &spec, "127.0.0.1:1".parse().unwrap(), "a@b", dir.path()).unwrap_err();
353 assert_eq!(err.code(), crate::ErrorCode::ToolMissing, "{err}");
354 }
355
356 #[cfg(unix)]
358 fn stand_in(script: &str, dir: &Path) -> Tunnel {
359 let spec = ProcessSpec::new("sh", ["-c", script]);
360 start(&spec, "127.0.0.1:1".parse().unwrap(), "admin@203.0.113.7", dir).unwrap()
361 }
362
363 #[cfg(unix)]
366 #[tokio::test]
367 async fn a_tunnel_that_closed_says_the_last_line_its_ssh_said() {
368 let dir = tempfile::tempdir().unwrap();
369 let mut refused = stand_in("echo 'debug1: x' >&2; echo 'Host key verification failed.' >&2; exit 255", dir.path());
370 assert_eq!(refused.why_closed().await.as_deref(), Some("Host key verification failed."));
371 assert_eq!(stand_in("exit 255", dir.path()).why_closed().await, None, "nothing said, nothing made up");
372 }
373
374 #[cfg(unix)]
377 #[tokio::test]
378 async fn a_tunnel_says_when_its_ssh_ended() {
379 let dir = tempfile::tempdir().unwrap();
380 let mut tunnel = stand_in("exit 255", dir.path());
381 tunnel.drain();
382 let said = tokio::time::timeout(Duration::from_secs(10), tunnel.closed()).await.expect("seen closing");
383 assert_eq!(said, "its ssh exited with code 255");
384 }
385
386 #[cfg(unix)]
389 #[tokio::test]
390 async fn a_tunnel_is_waited_for_while_its_ssh_opens_it_and_given_up_once_it_ended() {
391 let dir = tempfile::tempdir().unwrap();
392 let mut opening = stand_in("sleep 30", dir.path());
393 let probes = std::sync::atomic::AtomicUsize::new(0);
394 let third = || -> crate::BoxFuture<'_, bool> {
395 let n = probes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
396 Box::pin(async move { n >= 2 })
397 };
398 assert!(answers(&mut opening, third, Duration::from_secs(10)).await, "answering at the third probe");
399 let mut ended = stand_in("exit 255", dir.path());
400 tokio::time::sleep(Duration::from_millis(300)).await;
401 let never = || -> crate::BoxFuture<'_, bool> { Box::pin(async { false }) };
402 let started = std::time::Instant::now();
403 assert!(!answers(&mut ended, never, Duration::from_secs(10)).await);
404 assert!(started.elapsed() < Duration::from_secs(5), "given up once its ssh ended");
405 }
406}