1#![allow(dead_code)]
2
3use crate::error::{Result, VirtuosoError};
4use std::cell::Cell;
5use std::collections::HashMap;
6use std::io::Write;
7use std::process::{Command, Stdio};
8use std::time::Instant;
9
10use crate::models::RemoteTaskResult;
11
12fn shell_quote(s: &str) -> String {
13 shlex::try_quote(s)
14 .unwrap_or(std::borrow::Cow::Borrowed(s))
15 .into_owned()
16}
17
18pub struct SSHRunner {
19 pub host: String,
20 pub user: Option<String>,
21 pub jump_host: Option<String>,
22 pub jump_user: Option<String>,
23 pub ssh_port: Option<u16>,
24 pub ssh_key_path: Option<String>,
25 pub ssh_config_path: Option<String>,
26 pub timeout: u64,
27 pub connect_timeout: u64,
28 pub verbose: bool,
29 pub use_control_master: Cell<bool>,
31}
32
33impl SSHRunner {
34 pub fn new(host: &str) -> Self {
35 Self {
36 host: host.into(),
37 user: None,
38 jump_host: None,
39 jump_user: None,
40 ssh_port: None,
41 ssh_key_path: None,
42 ssh_config_path: None,
43 timeout: 30,
44 connect_timeout: 10,
45 verbose: false,
46 use_control_master: Cell::new(true),
47 }
48 }
49
50 pub fn is_cm_failure(stderr: &str) -> bool {
54 stderr.contains("mux_client_request_session")
55 || stderr.contains("could not create named pipe")
56 || stderr.contains("ControlPath")
57 || stderr.contains("Control socket connect")
58 || stderr.contains("multiplexing not supported")
59 || stderr.contains("mux_client_hello_exchange")
60 }
61
62 pub fn with_jump(mut self, jump: &str) -> Self {
63 self.jump_host = Some(jump.into());
64 self
65 }
66
67 pub fn with_user(mut self, user: &str) -> Self {
68 self.user = Some(user.into());
69 self
70 }
71
72 pub fn test_connection(&self, timeout: Option<u64>) -> Result<bool> {
73 let effective_timeout = timeout.unwrap_or(self.connect_timeout);
74 let output = self.run_test_connection(effective_timeout)?;
75
76 if !output.status.success() {
77 let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
78 if Self::is_cm_failure(&stderr) && self.use_control_master.get() {
79 tracing::warn!(
80 "ControlMaster failure in test_connection, retrying without CM: {}",
81 stderr.lines().next().unwrap_or("")
82 );
83 self.use_control_master.set(false);
84 let output2 = self.run_test_connection(effective_timeout)?;
85 return Ok(output2.status.success());
86 }
87 }
88 Ok(output.status.success())
89 }
90
91 fn run_test_connection(&self, connect_timeout: u64) -> Result<std::process::Output> {
92 let mut cmd = self.build_ssh_cmd_with_timeout(connect_timeout);
93 cmd.arg("exit").arg("0");
94 cmd.stdin(Stdio::null())
95 .stdout(Stdio::null())
96 .stderr(Stdio::piped())
97 .output()
98 .map_err(|e| VirtuosoError::Ssh(format!("failed to run ssh: {e}")))
99 }
100
101 pub fn run_command(&self, command: &str, timeout: Option<u64>) -> Result<RemoteTaskResult> {
102 let result = self.run_command_inner(command, timeout)?;
103 if !result.success && Self::is_cm_failure(&result.stderr) && self.use_control_master.get() {
104 tracing::warn!(
105 "ControlMaster failure detected, retrying without CM: {}",
106 result.stderr.lines().next().unwrap_or("")
107 );
108 self.use_control_master.set(false);
109 return self.run_command_inner(command, timeout);
110 }
111 Ok(result)
112 }
113
114 fn run_command_inner(&self, command: &str, timeout: Option<u64>) -> Result<RemoteTaskResult> {
115 let _timeout = timeout.unwrap_or(self.timeout);
116 let start = Instant::now();
117
118 let mut cmd = self.build_ssh_cmd();
119 cmd.arg("sh").arg("-l").arg("-s");
122
123 let output = cmd
124 .stdin(Stdio::piped())
125 .stdout(Stdio::piped())
126 .stderr(Stdio::piped())
127 .spawn()
128 .map_err(|e| VirtuosoError::Ssh(format!("failed to spawn ssh: {e}")))?;
129
130 if let Some(mut stdin) = output.stdin.as_ref() {
131 stdin
132 .write_all(command.as_bytes())
133 .map_err(|e| VirtuosoError::Ssh(format!("failed to write command: {e}")))?;
134 }
135
136 let output = output
137 .wait_with_output()
138 .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
139
140 let elapsed = start.elapsed().as_secs_f64();
141 let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
142 let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
143 let error = if output.status.success() {
144 None
145 } else {
146 Some(self.summarize_error(&stderr))
147 };
148
149 let mut timings = HashMap::new();
150 timings.insert("total".into(), elapsed);
151
152 Ok(RemoteTaskResult {
153 success: output.status.success(),
154 returncode: output.status.code().unwrap_or(-1),
155 stdout,
156 stderr,
157 remote_dir: None,
158 error,
159 timings,
160 })
161 }
162
163 pub fn upload(&self, local: &str, remote: &str) -> Result<()> {
164 let _target = self.remote_target();
165
166 let status = Command::new("tar")
167 .arg("cf")
168 .arg("-")
169 .arg("-C")
170 .arg(
171 std::path::Path::new(local)
172 .parent()
173 .unwrap_or_else(|| std::path::Path::new(".")),
174 )
175 .arg(std::path::Path::new(local).file_name().unwrap_or_default())
176 .stdout(Stdio::piped())
177 .spawn()
178 .map_err(|e| VirtuosoError::Ssh(format!("tar failed: {e}")))?;
179
180 let tar_stdout = status.stdout.unwrap();
181
182 let remote_dir = std::path::Path::new(remote)
183 .parent()
184 .unwrap_or_else(|| std::path::Path::new("."))
185 .to_string_lossy();
186
187 let mut ssh = self.build_ssh_cmd();
188 let quoted_dir = shell_quote(&remote_dir);
189 let inner_cmd = format!("mkdir -p {quoted_dir} && cd {quoted_dir} && tar xf -");
193 ssh.arg(format!("sh -c {}", shell_quote(&inner_cmd)));
194 ssh.stdin(tar_stdout);
195
196 let output = ssh
197 .stdout(Stdio::null())
198 .stderr(Stdio::piped())
199 .output()
200 .map_err(|e| VirtuosoError::Ssh(format!("ssh upload failed: {e}")))?;
201
202 if !output.status.success() {
203 let stderr = String::from_utf8_lossy(&output.stderr);
204 return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
205 }
206
207 Ok(())
208 }
209
210 pub fn upload_text(&self, text: &str, remote: &str) -> Result<()> {
211 let remote_dir = std::path::Path::new(remote)
212 .parent()
213 .unwrap_or_else(|| std::path::Path::new("."))
214 .to_string_lossy();
215
216 let quoted_dir = shell_quote(&remote_dir);
217 let mkdir_cmd = format!("mkdir -p {quoted_dir}");
218 let mkdir = self.run_command(&mkdir_cmd, None)?;
219 if !mkdir.success {
220 return Err(VirtuosoError::Ssh(format!(
221 "failed to create remote dir: {}",
222 mkdir.stderr
223 )));
224 }
225
226 let mut cmd = self.build_ssh_cmd();
227 let quoted_remote = shell_quote(remote);
228 cmd.arg(format!(
232 "sh -c {}",
233 shell_quote(&format!("cat > {quoted_remote}"))
234 ));
235
236 let output = cmd
237 .stdin(Stdio::piped())
238 .stdout(Stdio::null())
239 .stderr(Stdio::piped())
240 .spawn()
241 .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
242
243 if let Some(mut stdin) = output.stdin.as_ref() {
244 stdin
245 .write_all(text.as_bytes())
246 .map_err(|e| VirtuosoError::Ssh(format!("write failed: {e}")))?;
247 }
248
249 let output = output
250 .wait_with_output()
251 .map_err(|e| VirtuosoError::Ssh(format!("upload failed: {e}")))?;
252
253 if !output.status.success() {
254 let stderr = String::from_utf8_lossy(&output.stderr);
255 return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
256 }
257
258 Ok(())
259 }
260
261 pub fn download(&self, remote: &str, local: &str) -> Result<()> {
262 let _target = self.remote_target();
263
264 let local_path = std::path::Path::new(local);
265 if let Some(parent) = local_path.parent() {
266 std::fs::create_dir_all(parent)
267 .map_err(|e| VirtuosoError::Ssh(format!("failed to create local dir: {e}")))?;
268 }
269
270 let mut cmd = self.build_ssh_cmd();
271 cmd.arg("cat").arg(remote);
272
273 let output = cmd
274 .stdout(Stdio::piped())
275 .stderr(Stdio::piped())
276 .output()
277 .map_err(|e| VirtuosoError::Ssh(format!("ssh download failed: {e}")))?;
278
279 if !output.status.success() {
280 let stderr = String::from_utf8_lossy(&output.stderr);
281 return Err(VirtuosoError::Ssh(format!("download failed: {stderr}")));
282 }
283
284 std::fs::write(local, output.stdout)
285 .map_err(|e| VirtuosoError::Ssh(format!("failed to write local file: {e}")))?;
286
287 Ok(())
288 }
289
290 pub fn detect_python(&self) -> Result<Option<String>> {
291 for py in &["python3", "python", "python2.7"] {
292 let result = self.run_command(&format!("which {py} 2>/dev/null"), None)?;
293 if result.success && !result.stdout.trim().is_empty() {
294 return Ok(Some(py.to_string()));
295 }
296 }
297 Ok(None)
298 }
299
300 pub fn detect_arch(&self) -> Result<String> {
301 let result = self.run_command("uname -m", None)?;
302 if result.success {
303 Ok(result.stdout.trim().to_string())
304 } else {
305 Err(VirtuosoError::Ssh(format!(
306 "failed to detect arch: {}",
307 result.stderr
308 )))
309 }
310 }
311
312 pub(crate) fn build_ssh_cmd(&self) -> Command {
313 self.build_ssh_cmd_with_timeout(self.connect_timeout)
314 }
315
316 fn build_ssh_cmd_with_timeout(&self, connect_timeout: u64) -> Command {
317 let mut cmd = Command::new("ssh");
318 cmd.args([
319 "-o",
320 "BatchMode=yes",
321 "-o",
322 "StrictHostKeyChecking=accept-new",
323 "-o",
324 &format!("ConnectTimeout={connect_timeout}"),
325 "-o",
328 "GSSAPIAuthentication=no",
329 "-o",
330 "HostbasedAuthentication=no",
331 ]);
332
333 if self.use_control_master.get() {
334 let control_dir = dirs::cache_dir()
338 .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
339 .join("virtuoso_bridge")
340 .join("ssh");
341 let _ = std::fs::create_dir_all(&control_dir);
342 let control_path = control_dir.join("%h-%p-%r");
343 cmd.args([
344 "-o",
345 "ControlMaster=auto",
346 "-o",
347 &format!("ControlPath={}", control_path.display()),
348 "-o",
349 "ControlPersist=600",
350 ]);
351 }
352
353 if let Some(port) = self.ssh_port {
354 cmd.arg("-p").arg(port.to_string());
355 }
356 if let Some(ref key) = self.ssh_key_path {
357 cmd.arg("-i").arg(key);
358 }
359 if let Some(ref config) = self.ssh_config_path {
360 cmd.arg("-F").arg(config);
361 }
362 if let Some(ref jump) = self.jump_host {
363 let jump_target = match &self.jump_user {
364 Some(u) => format!("{u}@{jump}"),
365 None => jump.clone(),
366 };
367 cmd.arg("-J").arg(jump_target);
368 }
369
370 cmd.arg(self.remote_target());
371 cmd
372 }
373
374 pub fn remote_target(&self) -> String {
375 match &self.user {
376 Some(u) => format!("{u}@{}", self.host),
377 None => self.host.clone(),
378 }
379 }
380
381 pub fn verify_cmd_hint(&self) -> String {
384 let mut parts = vec!["ssh".to_string()];
385 if let Some(ref jump) = self.jump_host {
386 let jump_target = match &self.jump_user {
387 Some(u) => format!("{u}@{jump}"),
388 None => jump.clone(),
389 };
390 parts.push(format!("-J {jump_target}"));
391 }
392 if let Some(port) = self.ssh_port {
393 parts.push(format!("-p {port}"));
394 }
395 if let Some(ref key) = self.ssh_key_path {
396 parts.push(format!("-i {key}"));
397 }
398 parts.push(self.remote_target());
399 parts.join(" ")
400 }
401
402 pub(crate) fn summarize_error(&self, stderr: &str) -> String {
403 let lower = stderr.to_lowercase();
404 if lower.contains("connection refused") {
405 "connection refused - check if SSH is running".into()
406 } else if lower.contains("authentication") || lower.contains("permission denied") {
407 "authentication failed - check SSH keys".into()
408 } else if lower.contains("timeout") || lower.contains("timed out") {
409 "connection timed out - check network".into()
410 } else if lower.contains("could not resolve") {
411 "hostname resolution failed - check DNS".into()
412 } else {
413 stderr.lines().take(3).collect::<Vec<_>>().join("; ")
414 }
415 }
416}