1use crate::{
2 RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
3 remote_client::{CommandTemplate, RemoteConnection, RemoteConnectionOptions},
4 transport::{parse_platform, parse_shell},
5};
6use anyhow::{Context as _, Result, anyhow};
7use async_trait::async_trait;
8use collections::HashMap;
9use futures::{
10 AsyncReadExt as _, FutureExt as _,
11 channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
12 select_biased,
13};
14use gpui::{App, AppContext as _, AsyncApp, Task};
15use parking_lot::Mutex;
16use paths::remote_server_dir_relative;
17use release_channel::{AppVersion, ReleaseChannel};
18use rpc::proto::Envelope;
19use semver::Version;
20pub use settings::SshPortForwardOption;
21use smol::{
22 fs,
23 process::{self, Child, Stdio},
24};
25use std::{
26 net::IpAddr,
27 path::{Path, PathBuf},
28 sync::Arc,
29 time::Instant,
30};
31use tempfile::TempDir;
32use util::{
33 paths::{PathStyle, RemotePathBuf},
34 rel_path::RelPath,
35 shell::ShellKind,
36};
37
38pub(crate) struct SshRemoteConnection {
39 socket: SshSocket,
40 master_process: Mutex<Option<MasterProcess>>,
41 remote_binary_path: Option<Arc<RelPath>>,
42 ssh_platform: RemotePlatform,
43 ssh_path_style: PathStyle,
44 ssh_shell: String,
45 ssh_shell_kind: ShellKind,
46 ssh_default_system_shell: String,
47 _temp_dir: TempDir,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub enum SshConnectionHost {
52 IpAddr(IpAddr),
53 Hostname(String),
54}
55
56impl SshConnectionHost {
57 pub fn to_bracketed_string(&self) -> String {
58 match self {
59 Self::IpAddr(IpAddr::V4(ip)) => ip.to_string(),
60 Self::IpAddr(IpAddr::V6(ip)) => format!("[{}]", ip),
61 Self::Hostname(hostname) => hostname.clone(),
62 }
63 }
64
65 pub fn to_string(&self) -> String {
66 match self {
67 Self::IpAddr(ip) => ip.to_string(),
68 Self::Hostname(hostname) => hostname.clone(),
69 }
70 }
71}
72
73impl From<&str> for SshConnectionHost {
74 fn from(value: &str) -> Self {
75 if let Ok(address) = value.parse() {
76 Self::IpAddr(address)
77 } else {
78 Self::Hostname(value.to_string())
79 }
80 }
81}
82
83impl From<String> for SshConnectionHost {
84 fn from(value: String) -> Self {
85 if let Ok(address) = value.parse() {
86 Self::IpAddr(address)
87 } else {
88 Self::Hostname(value)
89 }
90 }
91}
92
93impl Default for SshConnectionHost {
94 fn default() -> Self {
95 Self::Hostname(Default::default())
96 }
97}
98
99#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
100pub struct SshConnectionOptions {
101 pub host: SshConnectionHost,
102 pub username: Option<String>,
103 pub port: Option<u16>,
104 pub password: Option<String>,
105 pub args: Option<Vec<String>>,
106 pub port_forwards: Option<Vec<SshPortForwardOption>>,
107 pub connection_timeout: Option<u16>,
108
109 pub nickname: Option<String>,
110 pub upload_binary_over_ssh: bool,
111}
112
113impl From<settings::SshConnection> for SshConnectionOptions {
114 fn from(val: settings::SshConnection) -> Self {
115 SshConnectionOptions {
116 host: val.host.to_string().into(),
117 username: val.username,
118 port: val.port,
119 password: None,
120 args: Some(val.args),
121 nickname: val.nickname,
122 upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
123 port_forwards: val.port_forwards,
124 connection_timeout: val.connection_timeout,
125 }
126 }
127}
128
129struct SshSocket {
130 connection_options: SshConnectionOptions,
131 #[cfg(not(target_os = "windows"))]
132 socket_path: std::path::PathBuf,
133 envs: HashMap<String, String>,
134 #[cfg(target_os = "windows")]
135 _proxy: askpass::PasswordProxy,
136}
137
138struct MasterProcess {
139 process: Child,
140}
141
142#[cfg(not(target_os = "windows"))]
143impl MasterProcess {
144 pub fn new(
145 askpass_script_path: &std::ffi::OsStr,
146 additional_args: Vec<String>,
147 socket_path: &std::path::Path,
148 destination: &str,
149 ) -> Result<Self> {
150 let args = [
151 "-N",
152 "-o",
153 "ControlPersist=no",
154 "-o",
155 "ControlMaster=yes",
156 "-o",
157 ];
158
159 let mut master_process = util::command::new_smol_command("ssh");
160 master_process
161 .kill_on_drop(true)
162 .stdin(Stdio::null())
163 .stdout(Stdio::piped())
164 .stderr(Stdio::piped())
165 .env("SSH_ASKPASS_REQUIRE", "force")
166 .env("SSH_ASKPASS", askpass_script_path)
167 .args(additional_args)
168 .args(args);
169
170 master_process.arg(format!("ControlPath={}", socket_path.display()));
171
172 let process = master_process.arg(&destination).spawn()?;
173
174 Ok(MasterProcess { process })
175 }
176
177 pub async fn wait_connected(&mut self) -> Result<()> {
178 let Some(mut stdout) = self.process.stdout.take() else {
179 anyhow::bail!("ssh process stdout capture failed");
180 };
181
182 let mut output = Vec::new();
183 stdout.read_to_end(&mut output).await?;
184 Ok(())
185 }
186}
187
188#[cfg(target_os = "windows")]
189impl MasterProcess {
190 const CONNECTION_ESTABLISHED_MAGIC: &str = "ZED_SSH_CONNECTION_ESTABLISHED";
191
192 pub fn new(
193 askpass_script_path: &std::ffi::OsStr,
194 additional_args: Vec<String>,
195 destination: &str,
196 ) -> Result<Self> {
197 // On Windows, `ControlMaster` and `ControlPath` are not supported:
198 // https://github.com/PowerShell/Win32-OpenSSH/issues/405
199 // https://github.com/PowerShell/Win32-OpenSSH/wiki/Project-Scope
200 //
201 // Using an ugly workaround to detect connection establishment
202 // -N doesn't work with JumpHosts as windows openssh never closes stdin in that case
203 let args = [
204 "-t",
205 &format!("echo '{}'; exec $0", Self::CONNECTION_ESTABLISHED_MAGIC),
206 ];
207
208 let mut master_process = util::command::new_smol_command("ssh");
209 master_process
210 .kill_on_drop(true)
211 .stdin(Stdio::null())
212 .stdout(Stdio::piped())
213 .stderr(Stdio::piped())
214 .env("SSH_ASKPASS_REQUIRE", "force")
215 .env("SSH_ASKPASS", askpass_script_path)
216 .args(additional_args)
217 .arg(destination)
218 .args(args);
219
220 let process = master_process.spawn()?;
221
222 Ok(MasterProcess { process })
223 }
224
225 pub async fn wait_connected(&mut self) -> Result<()> {
226 use smol::io::AsyncBufReadExt;
227
228 let Some(stdout) = self.process.stdout.take() else {
229 anyhow::bail!("ssh process stdout capture failed");
230 };
231
232 let mut reader = smol::io::BufReader::new(stdout);
233
234 let mut line = String::new();
235
236 loop {
237 let n = reader.read_line(&mut line).await?;
238 if n == 0 {
239 anyhow::bail!("ssh process exited before connection established");
240 }
241
242 if line.contains(Self::CONNECTION_ESTABLISHED_MAGIC) {
243 return Ok(());
244 }
245 }
246 }
247}
248
249impl AsRef<Child> for MasterProcess {
250 fn as_ref(&self) -> &Child {
251 &self.process
252 }
253}
254
255impl AsMut<Child> for MasterProcess {
256 fn as_mut(&mut self) -> &mut Child {
257 &mut self.process
258 }
259}
260
261#[async_trait(?Send)]
262impl RemoteConnection for SshRemoteConnection {
263 async fn kill(&self) -> Result<()> {
264 let Some(mut process) = self.master_process.lock().take() else {
265 return Ok(());
266 };
267 process.as_mut().kill().ok();
268 process.as_mut().status().await?;
269 Ok(())
270 }
271
272 fn has_been_killed(&self) -> bool {
273 self.master_process.lock().is_none()
274 }
275
276 fn connection_options(&self) -> RemoteConnectionOptions {
277 RemoteConnectionOptions::Ssh(self.socket.connection_options.clone())
278 }
279
280 fn shell(&self) -> String {
281 self.ssh_shell.clone()
282 }
283
284 fn default_system_shell(&self) -> String {
285 self.ssh_default_system_shell.clone()
286 }
287
288 fn build_command(
289 &self,
290 input_program: Option<String>,
291 input_args: &[String],
292 input_env: &HashMap<String, String>,
293 working_dir: Option<String>,
294 port_forward: Option<(u16, String, u16)>,
295 ) -> Result<CommandTemplate> {
296 let Self {
297 ssh_path_style,
298 socket,
299 ssh_shell_kind,
300 ssh_shell,
301 ..
302 } = self;
303 let env = socket.envs.clone();
304 build_command(
305 input_program,
306 input_args,
307 input_env,
308 working_dir,
309 port_forward,
310 env,
311 *ssh_path_style,
312 ssh_shell,
313 *ssh_shell_kind,
314 socket.ssh_args(),
315 )
316 }
317
318 fn build_forward_ports_command(
319 &self,
320 forwards: Vec<(u16, String, u16)>,
321 ) -> Result<CommandTemplate> {
322 let Self { socket, .. } = self;
323 let mut args = socket.ssh_args();
324 args.push("-N".into());
325 for (local_port, host, remote_port) in forwards {
326 args.push("-L".into());
327 args.push(format!("{local_port}:{host}:{remote_port}"));
328 }
329 Ok(CommandTemplate {
330 program: "ssh".into(),
331 args,
332 env: Default::default(),
333 })
334 }
335
336 fn upload_directory(
337 &self,
338 src_path: PathBuf,
339 dest_path: RemotePathBuf,
340 cx: &App,
341 ) -> Task<Result<()>> {
342 let dest_path_str = dest_path.to_string();
343 let src_path_display = src_path.display().to_string();
344
345 let mut sftp_command = self.build_sftp_command();
346 let mut scp_command =
347 self.build_scp_command(&src_path, &dest_path_str, Some(&["-C", "-r"]));
348
349 cx.background_spawn(async move {
350 // We will try SFTP first, and if that fails, we will fall back to SCP.
351 // If SCP fails also, we give up and return an error.
352 // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
353 // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
354 // This is for example the case on Windows as evidenced by this implementation snippet:
355 // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
356 if Self::is_sftp_available().await {
357 log::debug!("using SFTP for directory upload");
358 let mut child = sftp_command.spawn()?;
359 if let Some(mut stdin) = child.stdin.take() {
360 use futures::AsyncWriteExt;
361 let sftp_batch = format!("put -r \"{src_path_display}\" \"{dest_path_str}\"\n");
362 stdin.write_all(sftp_batch.as_bytes()).await?;
363 stdin.flush().await?;
364 }
365
366 let output = child.output().await?;
367 if output.status.success() {
368 return Ok(());
369 }
370
371 let stderr = String::from_utf8_lossy(&output.stderr);
372 log::debug!("failed to upload directory via SFTP {src_path_display} -> {dest_path_str}: {stderr}");
373 }
374
375 log::debug!("using SCP for directory upload");
376 let output = scp_command.output().await?;
377
378 if output.status.success() {
379 return Ok(());
380 }
381
382 let stderr = String::from_utf8_lossy(&output.stderr);
383 log::debug!("failed to upload directory via SCP {src_path_display} -> {dest_path_str}: {stderr}");
384
385 anyhow::bail!(
386 "failed to upload directory via SFTP/SCP {} -> {}: {}",
387 src_path_display,
388 dest_path_str,
389 stderr,
390 );
391 })
392 }
393
394 fn start_proxy(
395 &self,
396 unique_identifier: String,
397 reconnect: bool,
398 incoming_tx: UnboundedSender<Envelope>,
399 outgoing_rx: UnboundedReceiver<Envelope>,
400 connection_activity_tx: Sender<()>,
401 delegate: Arc<dyn RemoteClientDelegate>,
402 cx: &mut AsyncApp,
403 ) -> Task<Result<i32>> {
404 const VARS: [&str; 3] = ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"];
405 delegate.set_status(Some("Starting proxy"), cx);
406
407 let Some(remote_binary_path) = self.remote_binary_path.clone() else {
408 return Task::ready(Err(anyhow!("Remote binary path not set")));
409 };
410
411 let mut ssh_command = if self.ssh_platform.os.is_windows() {
412 // TODO: Set the `VARS` environment variables, we do not have `env` on windows
413 // so this needs a different approach
414 let mut proxy_args = vec![];
415 proxy_args.push("proxy".to_owned());
416 proxy_args.push("--identifier".to_owned());
417 proxy_args.push(unique_identifier);
418
419 if reconnect {
420 proxy_args.push("--reconnect".to_owned());
421 }
422 self.socket.ssh_command(
423 self.ssh_shell_kind,
424 &remote_binary_path.display(self.path_style()),
425 &proxy_args,
426 false,
427 )
428 } else {
429 let mut proxy_args = vec![];
430 for env_var in VARS {
431 if let Some(value) = std::env::var(env_var).ok() {
432 proxy_args.push(format!("{}='{}'", env_var, value));
433 }
434 }
435 proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
436 proxy_args.push("proxy".to_owned());
437 proxy_args.push("--identifier".to_owned());
438 proxy_args.push(unique_identifier);
439
440 if reconnect {
441 proxy_args.push("--reconnect".to_owned());
442 }
443 self.socket
444 .ssh_command(self.ssh_shell_kind, "env", &proxy_args, false)
445 };
446
447 let ssh_proxy_process = match ssh_command
448 // IMPORTANT: we kill this process when we drop the task that uses it.
449 .kill_on_drop(true)
450 .spawn()
451 {
452 Ok(process) => process,
453 Err(error) => {
454 return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
455 }
456 };
457
458 super::handle_rpc_messages_over_child_process_stdio(
459 ssh_proxy_process,
460 incoming_tx,
461 outgoing_rx,
462 connection_activity_tx,
463 cx,
464 )
465 }
466
467 fn path_style(&self) -> PathStyle {
468 self.ssh_path_style
469 }
470
471 fn has_wsl_interop(&self) -> bool {
472 false
473 }
474}
475
476impl SshRemoteConnection {
477 pub(crate) async fn new(
478 connection_options: SshConnectionOptions,
479 delegate: Arc<dyn RemoteClientDelegate>,
480 cx: &mut AsyncApp,
481 ) -> Result<Self> {
482 use askpass::AskPassResult;
483
484 let destination = connection_options.ssh_destination();
485
486 let temp_dir = tempfile::Builder::new()
487 .prefix("zed-ssh-session")
488 .tempdir()?;
489 let askpass_delegate = askpass::AskPassDelegate::new(cx, {
490 let delegate = delegate.clone();
491 move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
492 });
493
494 let mut askpass =
495 askpass::AskPassSession::new(cx.background_executor().clone(), askpass_delegate)
496 .await?;
497
498 delegate.set_status(Some("Connecting"), cx);
499
500 // Start the master SSH process, which does not do anything except for establish
501 // the connection and keep it open, allowing other ssh commands to reuse it
502 // via a control socket.
503 #[cfg(not(target_os = "windows"))]
504 let socket_path = temp_dir.path().join("ssh.sock");
505
506 #[cfg(target_os = "windows")]
507 let mut master_process = MasterProcess::new(
508 askpass.script_path().as_ref(),
509 connection_options.additional_args(),
510 &destination,
511 )?;
512 #[cfg(not(target_os = "windows"))]
513 let mut master_process = MasterProcess::new(
514 askpass.script_path().as_ref(),
515 connection_options.additional_args(),
516 &socket_path,
517 &destination,
518 )?;
519
520 let result = select_biased! {
521 result = askpass.run().fuse() => {
522 match result {
523 AskPassResult::CancelledByUser => {
524 master_process.as_mut().kill().ok();
525 anyhow::bail!("SSH connection canceled")
526 }
527 AskPassResult::Timedout => {
528 anyhow::bail!("connecting to host timed out")
529 }
530 }
531 }
532 _ = master_process.wait_connected().fuse() => {
533 anyhow::Ok(())
534 }
535 };
536
537 if let Err(e) = result {
538 return Err(e.context("Failed to connect to host"));
539 }
540
541 if master_process.as_mut().try_status()?.is_some() {
542 let mut output = Vec::new();
543 output.clear();
544 let mut stderr = master_process.as_mut().stderr.take().unwrap();
545 stderr.read_to_end(&mut output).await?;
546
547 let error_message = format!(
548 "failed to connect: {}",
549 String::from_utf8_lossy(&output).trim()
550 );
551 anyhow::bail!(error_message);
552 }
553
554 #[cfg(not(target_os = "windows"))]
555 let socket = SshSocket::new(connection_options, socket_path).await?;
556 #[cfg(target_os = "windows")]
557 let socket = SshSocket::new(
558 connection_options,
559 askpass
560 .get_password()
561 .or_else(|| askpass::EncryptedPassword::try_from("").ok())
562 .context("Failed to fetch askpass password")?,
563 cx.background_executor().clone(),
564 )
565 .await?;
566 drop(askpass);
567
568 let is_windows = socket.probe_is_windows().await;
569 log::info!("Remote is windows: {}", is_windows);
570
571 let ssh_shell = socket.shell(is_windows).await;
572 log::info!("Remote shell discovered: {}", ssh_shell);
573
574 let ssh_shell_kind = ShellKind::new(&ssh_shell, is_windows);
575 let ssh_platform = socket.platform(ssh_shell_kind, is_windows).await?;
576 log::info!("Remote platform discovered: {:?}", ssh_platform);
577
578 let (ssh_path_style, ssh_default_system_shell) = match ssh_platform.os {
579 RemoteOs::Windows => (PathStyle::Windows, ssh_shell.clone()),
580 _ => (PathStyle::Posix, String::from("/bin/sh")),
581 };
582
583 let mut this = Self {
584 socket,
585 master_process: Mutex::new(Some(master_process)),
586 _temp_dir: temp_dir,
587 remote_binary_path: None,
588 ssh_path_style,
589 ssh_platform,
590 ssh_shell,
591 ssh_shell_kind,
592 ssh_default_system_shell,
593 };
594
595 let (release_channel, version) =
596 cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)));
597 this.remote_binary_path = Some(
598 this.ensure_server_binary(&delegate, release_channel, version, cx)
599 .await?,
600 );
601
602 Ok(this)
603 }
604
605 async fn ensure_server_binary(
606 &self,
607 delegate: &Arc<dyn RemoteClientDelegate>,
608 release_channel: ReleaseChannel,
609 version: Version,
610 cx: &mut AsyncApp,
611 ) -> Result<Arc<RelPath>> {
612 let version_str = match release_channel {
613 ReleaseChannel::Dev => "build".to_string(),
614 _ => version.to_string(),
615 };
616 let binary_name = format!(
617 "zed-remote-server-{}-{}{}",
618 release_channel.dev_name(),
619 version_str,
620 if self.ssh_platform.os.is_windows() {
621 ".exe"
622 } else {
623 ""
624 }
625 );
626 let dst_path =
627 paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
628
629 #[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
630 if let Some(remote_server_path) =
631 super::build_remote_server_from_source(&self.ssh_platform, delegate.as_ref(), cx)
632 .await?
633 {
634 let tmp_path = paths::remote_server_dir_relative().join(
635 RelPath::unix(&format!(
636 "download-{}-{}",
637 std::process::id(),
638 remote_server_path.file_name().unwrap().to_string_lossy()
639 ))
640 .unwrap(),
641 );
642 self.upload_local_server_binary(&remote_server_path, &tmp_path, delegate, cx)
643 .await?;
644 self.extract_server_binary(&dst_path, &tmp_path, delegate, cx)
645 .await?;
646 return Ok(dst_path);
647 }
648
649 if self
650 .socket
651 .run_command(
652 self.ssh_shell_kind,
653 &dst_path.display(self.path_style()),
654 &["version"],
655 true,
656 )
657 .await
658 .is_ok()
659 {
660 return Ok(dst_path);
661 }
662
663 let wanted_version = cx.update(|cx| match release_channel {
664 ReleaseChannel::Nightly => Ok(None),
665 ReleaseChannel::Dev => {
666 anyhow::bail!(
667 "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
668 dst_path
669 )
670 }
671 _ => Ok(Some(AppVersion::global(cx))),
672 })?;
673
674 let tmp_path_gz = remote_server_dir_relative().join(
675 RelPath::unix(&format!(
676 "{}-download-{}.gz",
677 binary_name,
678 std::process::id()
679 ))
680 .unwrap(),
681 );
682 if !self.socket.connection_options.upload_binary_over_ssh
683 && let Some(url) = delegate
684 .get_download_url(
685 self.ssh_platform,
686 release_channel,
687 wanted_version.clone(),
688 cx,
689 )
690 .await?
691 {
692 match self
693 .download_binary_on_server(&url, &tmp_path_gz, delegate, cx)
694 .await
695 {
696 Ok(_) => {
697 self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
698 .await
699 .context("extracting server binary")?;
700 return Ok(dst_path);
701 }
702 Err(e) => {
703 log::error!(
704 "Failed to download binary on server, attempting to download locally and then upload it the server: {e:#}",
705 )
706 }
707 }
708 }
709
710 let src_path = delegate
711 .download_server_binary_locally(
712 self.ssh_platform,
713 release_channel,
714 wanted_version.clone(),
715 cx,
716 )
717 .await
718 .context("downloading server binary locally")?;
719 self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
720 .await
721 .context("uploading server binary")?;
722 self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
723 .await
724 .context("extracting server binary")?;
725 Ok(dst_path)
726 }
727
728 async fn download_binary_on_server(
729 &self,
730 url: &str,
731 tmp_path_gz: &RelPath,
732 delegate: &Arc<dyn RemoteClientDelegate>,
733 cx: &mut AsyncApp,
734 ) -> Result<()> {
735 if let Some(parent) = tmp_path_gz.parent() {
736 let res = self
737 .socket
738 .run_command(
739 self.ssh_shell_kind,
740 "mkdir",
741 &["-p", parent.display(self.path_style()).as_ref()],
742 true,
743 )
744 .await;
745 if !self.ssh_platform.os.is_windows() {
746 // mkdir fails on windows if the path already exists ...
747 res?;
748 }
749 }
750
751 delegate.set_status(Some("Downloading remote development server on host"), cx);
752
753 let connection_timeout = self
754 .socket
755 .connection_options
756 .connection_timeout
757 .unwrap_or(10)
758 .to_string();
759
760 match self
761 .socket
762 .run_command(
763 self.ssh_shell_kind,
764 "curl",
765 &[
766 "-f",
767 "-L",
768 "--connect-timeout",
769 &connection_timeout,
770 url,
771 "-o",
772 &tmp_path_gz.display(self.path_style()),
773 ],
774 true,
775 )
776 .await
777 {
778 Ok(_) => {}
779 Err(e) => {
780 if self
781 .socket
782 .run_command(self.ssh_shell_kind, "which", &["curl"], true)
783 .await
784 .is_ok()
785 {
786 return Err(e);
787 }
788
789 log::info!("curl is not available, trying wget");
790 match self
791 .socket
792 .run_command(
793 self.ssh_shell_kind,
794 "wget",
795 &[
796 "--connect-timeout",
797 &connection_timeout,
798 "--tries",
799 "1",
800 url,
801 "-O",
802 &tmp_path_gz.display(self.path_style()),
803 ],
804 true,
805 )
806 .await
807 {
808 Ok(_) => {}
809 Err(e) => {
810 if self
811 .socket
812 .run_command(self.ssh_shell_kind, "which", &["wget"], true)
813 .await
814 .is_ok()
815 {
816 return Err(e);
817 } else {
818 anyhow::bail!("Neither curl nor wget is available");
819 }
820 }
821 }
822 }
823 }
824
825 Ok(())
826 }
827
828 async fn upload_local_server_binary(
829 &self,
830 src_path: &Path,
831 tmp_path_gz: &RelPath,
832 delegate: &Arc<dyn RemoteClientDelegate>,
833 cx: &mut AsyncApp,
834 ) -> Result<()> {
835 if let Some(parent) = tmp_path_gz.parent() {
836 let res = self
837 .socket
838 .run_command(
839 self.ssh_shell_kind,
840 "mkdir",
841 &["-p", parent.display(self.path_style()).as_ref()],
842 true,
843 )
844 .await;
845 if !self.ssh_platform.os.is_windows() {
846 // mkdir fails on windows if the path already exists ...
847 res?;
848 }
849 }
850
851 let src_stat = fs::metadata(&src_path)
852 .await
853 .with_context(|| format!("failed to get metadata for {:?}", src_path))?;
854 let size = src_stat.len();
855
856 let t0 = Instant::now();
857 delegate.set_status(Some("Uploading remote development server"), cx);
858 log::info!(
859 "uploading remote development server to {:?} ({}kb)",
860 tmp_path_gz,
861 size / 1024
862 );
863 self.upload_file(src_path, tmp_path_gz)
864 .await
865 .context("failed to upload server binary")?;
866 log::info!("uploaded remote development server in {:?}", t0.elapsed());
867 Ok(())
868 }
869
870 async fn extract_server_binary(
871 &self,
872 dst_path: &RelPath,
873 tmp_path: &RelPath,
874 delegate: &Arc<dyn RemoteClientDelegate>,
875 cx: &mut AsyncApp,
876 ) -> Result<()> {
877 delegate.set_status(Some("Extracting remote development server"), cx);
878 let server_mode = 0o755;
879
880 let shell_kind = ShellKind::Posix;
881 let orig_tmp_path = tmp_path.display(self.path_style());
882 let server_mode = format!("{:o}", server_mode);
883 let server_mode = shell_kind
884 .try_quote(&server_mode)
885 .context("shell quoting")?;
886 let dst_path = dst_path.display(self.path_style());
887 let dst_path = shell_kind.try_quote(&dst_path).context("shell quoting")?;
888 let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
889 let orig_tmp_path = shell_kind
890 .try_quote(&orig_tmp_path)
891 .context("shell quoting")?;
892 let tmp_path = shell_kind.try_quote(&tmp_path).context("shell quoting")?;
893 format!(
894 "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
895 )
896 } else {
897 let orig_tmp_path = shell_kind
898 .try_quote(&orig_tmp_path)
899 .context("shell quoting")?;
900 format!("chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",)
901 };
902 let args = shell_kind.args_for_shell(false, script.to_string());
903 self.socket
904 .run_command(self.ssh_shell_kind, "sh", &args, true)
905 .await?;
906 Ok(())
907 }
908
909 fn build_scp_command(
910 &self,
911 src_path: &Path,
912 dest_path_str: &str,
913 args: Option<&[&str]>,
914 ) -> process::Command {
915 let mut command = util::command::new_smol_command("scp");
916 self.socket.ssh_options(&mut command, false).args(
917 self.socket
918 .connection_options
919 .port
920 .map(|port| vec!["-P".to_string(), port.to_string()])
921 .unwrap_or_default(),
922 );
923 if let Some(args) = args {
924 command.args(args);
925 }
926 command.arg(src_path).arg(format!(
927 "{}:{}",
928 self.socket.connection_options.scp_destination(),
929 dest_path_str
930 ));
931 command
932 }
933
934 fn build_sftp_command(&self) -> process::Command {
935 let mut command = util::command::new_smol_command("sftp");
936 self.socket.ssh_options(&mut command, false).args(
937 self.socket
938 .connection_options
939 .port
940 .map(|port| vec!["-P".to_string(), port.to_string()])
941 .unwrap_or_default(),
942 );
943 command.arg("-b").arg("-");
944 command.arg(self.socket.connection_options.scp_destination());
945 command.stdin(Stdio::piped());
946 command
947 }
948
949 async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
950 log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
951
952 let src_path_display = src_path.display().to_string();
953 let dest_path_str = dest_path.display(self.path_style());
954
955 // We will try SFTP first, and if that fails, we will fall back to SCP.
956 // If SCP fails also, we give up and return an error.
957 // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
958 // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
959 // This is for example the case on Windows as evidenced by this implementation snippet:
960 // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
961 if Self::is_sftp_available().await {
962 log::debug!("using SFTP for file upload");
963 let mut command = self.build_sftp_command();
964 let sftp_batch = format!("put {src_path_display} {dest_path_str}\n");
965
966 let mut child = command.spawn()?;
967 if let Some(mut stdin) = child.stdin.take() {
968 use futures::AsyncWriteExt;
969 stdin.write_all(sftp_batch.as_bytes()).await?;
970 stdin.flush().await?;
971 }
972
973 let output = child.output().await?;
974 if output.status.success() {
975 return Ok(());
976 }
977
978 let stderr = String::from_utf8_lossy(&output.stderr);
979 log::debug!(
980 "failed to upload file via SFTP {src_path_display} -> {dest_path_str}: {stderr}"
981 );
982 }
983
984 log::debug!("using SCP for file upload");
985 let mut command = self.build_scp_command(src_path, &dest_path_str, None);
986 let output = command.output().await?;
987
988 if output.status.success() {
989 return Ok(());
990 }
991
992 let stderr = String::from_utf8_lossy(&output.stderr);
993 log::debug!(
994 "failed to upload file via SCP {src_path_display} -> {dest_path_str}: {stderr}",
995 );
996 anyhow::bail!(
997 "failed to upload file via STFP/SCP {} -> {}: {}",
998 src_path_display,
999 dest_path_str,
1000 stderr,
1001 );
1002 }
1003
1004 async fn is_sftp_available() -> bool {
1005 which::which("sftp").is_ok()
1006 }
1007}
1008
1009impl SshSocket {
1010 #[cfg(not(target_os = "windows"))]
1011 async fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
1012 Ok(Self {
1013 connection_options: options,
1014 envs: HashMap::default(),
1015 socket_path,
1016 })
1017 }
1018
1019 #[cfg(target_os = "windows")]
1020 async fn new(
1021 options: SshConnectionOptions,
1022 password: askpass::EncryptedPassword,
1023 executor: gpui::BackgroundExecutor,
1024 ) -> Result<Self> {
1025 let mut envs = HashMap::default();
1026 let get_password =
1027 move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
1028
1029 let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
1030 envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
1031 envs.insert(
1032 "SSH_ASKPASS".into(),
1033 _proxy.script_path().as_ref().display().to_string(),
1034 );
1035
1036 Ok(Self {
1037 connection_options: options,
1038 envs,
1039 _proxy,
1040 })
1041 }
1042
1043 // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
1044 // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
1045 // and passes -l as an argument to sh, not to ls.
1046 // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
1047 // into a machine. You must use `cd` to get back to $HOME.
1048 // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
1049 fn ssh_command(
1050 &self,
1051 shell_kind: ShellKind,
1052 program: &str,
1053 args: &[impl AsRef<str>],
1054 allow_pseudo_tty: bool,
1055 ) -> process::Command {
1056 let mut command = util::command::new_smol_command("ssh");
1057 let program = shell_kind.prepend_command_prefix(program);
1058 let mut to_run = shell_kind
1059 .try_quote_prefix_aware(&program)
1060 .expect("shell quoting")
1061 .into_owned();
1062 for arg in args {
1063 // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
1064 debug_assert!(
1065 !arg.as_ref().contains('\n'),
1066 "multiline arguments do not work in all shells"
1067 );
1068 to_run.push(' ');
1069 to_run.push_str(&shell_kind.try_quote(arg.as_ref()).expect("shell quoting"));
1070 }
1071 let separator = shell_kind.sequential_commands_separator();
1072 let to_run = format!("cd{separator} {to_run}");
1073 self.ssh_options(&mut command, true)
1074 .arg(self.connection_options.ssh_destination());
1075 if !allow_pseudo_tty {
1076 command.arg("-T");
1077 }
1078 command.arg(to_run);
1079 log::debug!("ssh {:?}", command);
1080 command
1081 }
1082
1083 async fn run_command(
1084 &self,
1085 shell_kind: ShellKind,
1086 program: &str,
1087 args: &[impl AsRef<str>],
1088 allow_pseudo_tty: bool,
1089 ) -> Result<String> {
1090 let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);
1091 let output = command.output().await?;
1092 log::debug!("{:?}: {:?}", command, output);
1093 anyhow::ensure!(
1094 output.status.success(),
1095 "failed to run command {command:?}: {}",
1096 String::from_utf8_lossy(&output.stderr)
1097 );
1098 Ok(String::from_utf8_lossy(&output.stdout).to_string())
1099 }
1100
1101 #[cfg(not(target_os = "windows"))]
1102 fn ssh_options<'a>(
1103 &self,
1104 command: &'a mut process::Command,
1105 include_port_forwards: bool,
1106 ) -> &'a mut process::Command {
1107 let args = if include_port_forwards {
1108 self.connection_options.additional_args()
1109 } else {
1110 self.connection_options.additional_args_for_scp()
1111 };
1112
1113 command
1114 .stdin(Stdio::piped())
1115 .stdout(Stdio::piped())
1116 .stderr(Stdio::piped())
1117 .args(args)
1118 .args(["-o", "ControlMaster=no", "-o"])
1119 .arg(format!("ControlPath={}", self.socket_path.display()))
1120 }
1121
1122 #[cfg(target_os = "windows")]
1123 fn ssh_options<'a>(
1124 &self,
1125 command: &'a mut process::Command,
1126 include_port_forwards: bool,
1127 ) -> &'a mut process::Command {
1128 let args = if include_port_forwards {
1129 self.connection_options.additional_args()
1130 } else {
1131 self.connection_options.additional_args_for_scp()
1132 };
1133
1134 command
1135 .stdin(Stdio::piped())
1136 .stdout(Stdio::piped())
1137 .stderr(Stdio::piped())
1138 .args(args)
1139 .envs(self.envs.clone())
1140 }
1141
1142 // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
1143 // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
1144 #[cfg(not(target_os = "windows"))]
1145 fn ssh_args(&self) -> Vec<String> {
1146 let mut arguments = self.connection_options.additional_args();
1147 arguments.extend(vec![
1148 "-o".to_string(),
1149 "ControlMaster=no".to_string(),
1150 "-o".to_string(),
1151 format!("ControlPath={}", self.socket_path.display()),
1152 self.connection_options.ssh_destination(),
1153 ]);
1154 arguments
1155 }
1156
1157 #[cfg(target_os = "windows")]
1158 fn ssh_args(&self) -> Vec<String> {
1159 let mut arguments = self.connection_options.additional_args();
1160 arguments.push(self.connection_options.ssh_destination());
1161 arguments
1162 }
1163
1164 async fn platform(&self, shell: ShellKind, is_windows: bool) -> Result<RemotePlatform> {
1165 if is_windows {
1166 self.platform_windows(shell).await
1167 } else {
1168 self.platform_posix(shell).await
1169 }
1170 }
1171
1172 async fn platform_posix(&self, shell: ShellKind) -> Result<RemotePlatform> {
1173 let output = self
1174 .run_command(shell, "uname", &["-sm"], false)
1175 .await
1176 .context("Failed to run 'uname -sm' to determine platform")?;
1177 parse_platform(&output)
1178 }
1179
1180 async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {
1181 let output = self
1182 .run_command(
1183 shell,
1184 "cmd",
1185 &["/c", "echo", "%PROCESSOR_ARCHITECTURE%"],
1186 false,
1187 )
1188 .await
1189 .context(
1190 "Failed to run 'echo %PROCESSOR_ARCHITECTURE%' to determine Windows architecture",
1191 )?;
1192
1193 Ok(RemotePlatform {
1194 os: RemoteOs::Windows,
1195 arch: match output.trim() {
1196 "AMD64" => RemoteArch::X86_64,
1197 "ARM64" => RemoteArch::Aarch64,
1198 arch => anyhow::bail!(
1199 "Prebuilt remote servers are not yet available for windows-{arch}. See https://zed.dev/docs/remote-development"
1200 ),
1201 },
1202 })
1203 }
1204
1205 /// Probes whether the remote host is running Windows.
1206 ///
1207 /// This is done by attempting to run a simple Windows-specific command.
1208 /// If it succeeds and returns Windows-like output, we assume it's Windows.
1209 async fn probe_is_windows(&self) -> bool {
1210 match self
1211 .run_command(ShellKind::PowerShell, "cmd", &["/c", "ver"], false)
1212 .await
1213 {
1214 // Windows 'ver' command outputs something like "Microsoft Windows [Version 10.0.19045.5011]"
1215 Ok(output) => output.trim().contains("indows"),
1216 Err(_) => false,
1217 }
1218 }
1219
1220 async fn shell(&self, is_windows: bool) -> String {
1221 if is_windows {
1222 self.shell_windows().await
1223 } else {
1224 self.shell_posix().await
1225 }
1226 }
1227
1228 async fn shell_posix(&self) -> String {
1229 const DEFAULT_SHELL: &str = "sh";
1230 match self
1231 .run_command(ShellKind::Posix, "sh", &["-c", "echo $SHELL"], false)
1232 .await
1233 {
1234 Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1235 Err(e) => {
1236 log::error!("Failed to detect remote shell: {e}");
1237 DEFAULT_SHELL.to_owned()
1238 }
1239 }
1240 }
1241
1242 async fn shell_windows(&self) -> String {
1243 // powershell is always the default, and cannot really be removed from the system
1244 // so we can rely on that fact and reasonably assume that we will be running in a
1245 // powershell environment
1246 "powershell.exe".to_owned()
1247 }
1248}
1249
1250fn parse_port_number(port_str: &str) -> Result<u16> {
1251 port_str
1252 .parse()
1253 .with_context(|| format!("parsing port number: {port_str}"))
1254}
1255
1256fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1257 let parts: Vec<&str> = spec.split(':').collect();
1258
1259 match parts.len() {
1260 4 => {
1261 let local_port = parse_port_number(parts[1])?;
1262 let remote_port = parse_port_number(parts[3])?;
1263
1264 Ok(SshPortForwardOption {
1265 local_host: Some(parts[0].to_string()),
1266 local_port,
1267 remote_host: Some(parts[2].to_string()),
1268 remote_port,
1269 })
1270 }
1271 3 => {
1272 let local_port = parse_port_number(parts[0])?;
1273 let remote_port = parse_port_number(parts[2])?;
1274
1275 Ok(SshPortForwardOption {
1276 local_host: None,
1277 local_port,
1278 remote_host: Some(parts[1].to_string()),
1279 remote_port,
1280 })
1281 }
1282 _ => anyhow::bail!("Invalid port forward format"),
1283 }
1284}
1285
1286impl SshConnectionOptions {
1287 pub fn parse_command_line(input: &str) -> Result<Self> {
1288 let input = input.trim_start_matches("ssh ");
1289 let mut hostname: Option<String> = None;
1290 let mut username: Option<String> = None;
1291 let mut port: Option<u16> = None;
1292 let mut args = Vec::new();
1293 let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1294
1295 // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1296 const ALLOWED_OPTS: &[&str] = &[
1297 "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1298 ];
1299 const ALLOWED_ARGS: &[&str] = &[
1300 "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1301 "-w",
1302 ];
1303
1304 let mut tokens = ShellKind::Posix
1305 .split(input)
1306 .context("invalid input")?
1307 .into_iter();
1308
1309 'outer: while let Some(arg) = tokens.next() {
1310 if ALLOWED_OPTS.contains(&(&arg as &str)) {
1311 args.push(arg.to_string());
1312 continue;
1313 }
1314 if arg == "-p" {
1315 port = tokens.next().and_then(|arg| arg.parse().ok());
1316 continue;
1317 } else if let Some(p) = arg.strip_prefix("-p") {
1318 port = p.parse().ok();
1319 continue;
1320 }
1321 if arg == "-l" {
1322 username = tokens.next();
1323 continue;
1324 } else if let Some(l) = arg.strip_prefix("-l") {
1325 username = Some(l.to_string());
1326 continue;
1327 }
1328 if arg == "-L" || arg.starts_with("-L") {
1329 let forward_spec = if arg == "-L" {
1330 tokens.next()
1331 } else {
1332 Some(arg.strip_prefix("-L").unwrap().to_string())
1333 };
1334
1335 if let Some(spec) = forward_spec {
1336 port_forwards.push(parse_port_forward_spec(&spec)?);
1337 } else {
1338 anyhow::bail!("Missing port forward format");
1339 }
1340 }
1341
1342 for a in ALLOWED_ARGS {
1343 if arg == *a {
1344 args.push(arg);
1345 if let Some(next) = tokens.next() {
1346 args.push(next);
1347 }
1348 continue 'outer;
1349 } else if arg.starts_with(a) {
1350 args.push(arg);
1351 continue 'outer;
1352 }
1353 }
1354 if arg.starts_with("-") || hostname.is_some() {
1355 anyhow::bail!("unsupported argument: {:?}", arg);
1356 }
1357 let mut input = &arg as &str;
1358 // Destination might be: username1@username2@ip2@ip1
1359 if let Some((u, rest)) = input.rsplit_once('@') {
1360 input = rest;
1361 username = Some(u.to_string());
1362 }
1363
1364 // Handle port parsing, accounting for IPv6 addresses
1365 // IPv6 addresses can be: 2001:db8::1 or [2001:db8::1]:22
1366 if input.starts_with('[') {
1367 if let Some((rest, p)) = input.rsplit_once("]:") {
1368 input = rest.strip_prefix('[').unwrap_or(rest);
1369 port = p.parse().ok();
1370 } else if input.ends_with(']') {
1371 input = input.strip_prefix('[').unwrap_or(input);
1372 input = input.strip_suffix(']').unwrap_or(input);
1373 }
1374 } else if let Some((rest, p)) = input.rsplit_once(':')
1375 && !rest.contains(":")
1376 {
1377 input = rest;
1378 port = p.parse().ok();
1379 }
1380
1381 hostname = Some(input.to_string())
1382 }
1383
1384 let Some(hostname) = hostname else {
1385 anyhow::bail!("missing hostname");
1386 };
1387
1388 let port_forwards = match port_forwards.len() {
1389 0 => None,
1390 _ => Some(port_forwards),
1391 };
1392
1393 Ok(Self {
1394 host: hostname.into(),
1395 username,
1396 port,
1397 port_forwards,
1398 args: Some(args),
1399 password: None,
1400 nickname: None,
1401 upload_binary_over_ssh: false,
1402 connection_timeout: None,
1403 })
1404 }
1405
1406 pub fn ssh_destination(&self) -> String {
1407 let mut result = String::default();
1408 if let Some(username) = &self.username {
1409 // Username might be: username1@username2@ip2
1410 let username = urlencoding::encode(username);
1411 result.push_str(&username);
1412 result.push('@');
1413 }
1414
1415 result.push_str(&self.host.to_string());
1416 result
1417 }
1418
1419 pub fn additional_args_for_scp(&self) -> Vec<String> {
1420 self.args.iter().flatten().cloned().collect::<Vec<String>>()
1421 }
1422
1423 pub fn additional_args(&self) -> Vec<String> {
1424 let mut args = self.additional_args_for_scp();
1425
1426 if let Some(timeout) = self.connection_timeout {
1427 args.extend(["-o".to_string(), format!("ConnectTimeout={}", timeout)]);
1428 }
1429
1430 if let Some(port) = self.port {
1431 args.push("-p".to_string());
1432 args.push(port.to_string());
1433 }
1434
1435 if let Some(forwards) = &self.port_forwards {
1436 args.extend(forwards.iter().map(|pf| {
1437 let local_host = match &pf.local_host {
1438 Some(host) => host,
1439 None => "localhost",
1440 };
1441 let remote_host = match &pf.remote_host {
1442 Some(host) => host,
1443 None => "localhost",
1444 };
1445
1446 format!(
1447 "-L{}:{}:{}:{}",
1448 local_host, pf.local_port, remote_host, pf.remote_port
1449 )
1450 }));
1451 }
1452
1453 args
1454 }
1455
1456 fn scp_destination(&self) -> String {
1457 if let Some(username) = &self.username {
1458 format!("{}@{}", username, self.host.to_bracketed_string())
1459 } else {
1460 self.host.to_string()
1461 }
1462 }
1463
1464 pub fn connection_string(&self) -> String {
1465 let host = if let Some(port) = &self.port {
1466 format!("{}:{}", self.host.to_bracketed_string(), port)
1467 } else {
1468 self.host.to_string()
1469 };
1470
1471 if let Some(username) = &self.username {
1472 format!("{}@{}", username, host)
1473 } else {
1474 host
1475 }
1476 }
1477}
1478
1479fn build_command(
1480 input_program: Option<String>,
1481 input_args: &[String],
1482 input_env: &HashMap<String, String>,
1483 working_dir: Option<String>,
1484 port_forward: Option<(u16, String, u16)>,
1485 ssh_env: HashMap<String, String>,
1486 ssh_path_style: PathStyle,
1487 ssh_shell: &str,
1488 ssh_shell_kind: ShellKind,
1489 ssh_args: Vec<String>,
1490) -> Result<CommandTemplate> {
1491 use std::fmt::Write as _;
1492
1493 let mut exec = String::new();
1494 if let Some(working_dir) = working_dir {
1495 let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1496
1497 // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1498 // replace with something that works
1499 const TILDE_PREFIX: &'static str = "~/";
1500 if working_dir.starts_with(TILDE_PREFIX) {
1501 let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1502 write!(
1503 exec,
1504 "cd \"$HOME/{working_dir}\" {} ",
1505 ssh_shell_kind.sequential_and_commands_separator()
1506 )?;
1507 } else {
1508 write!(
1509 exec,
1510 "cd \"{working_dir}\" {} ",
1511 ssh_shell_kind.sequential_and_commands_separator()
1512 )?;
1513 }
1514 } else {
1515 write!(
1516 exec,
1517 "cd {} ",
1518 ssh_shell_kind.sequential_and_commands_separator()
1519 )?;
1520 };
1521 write!(exec, "exec env ")?;
1522
1523 for (k, v) in input_env.iter() {
1524 write!(
1525 exec,
1526 "{}={} ",
1527 k,
1528 ssh_shell_kind.try_quote(v).context("shell quoting")?
1529 )?;
1530 }
1531
1532 if let Some(input_program) = input_program {
1533 write!(
1534 exec,
1535 "{}",
1536 ssh_shell_kind
1537 .try_quote_prefix_aware(&input_program)
1538 .context("shell quoting")?
1539 )?;
1540 for arg in input_args {
1541 let arg = ssh_shell_kind.try_quote(&arg).context("shell quoting")?;
1542 write!(exec, " {}", &arg)?;
1543 }
1544 } else {
1545 write!(exec, "{ssh_shell} -l")?;
1546 };
1547
1548 let mut args = Vec::new();
1549 args.extend(ssh_args);
1550
1551 if let Some((local_port, host, remote_port)) = port_forward {
1552 args.push("-L".into());
1553 args.push(format!("{local_port}:{host}:{remote_port}"));
1554 }
1555
1556 // -q suppresses the "Connection to ... closed." message that SSH prints when
1557 // the connection terminates with -t (pseudo-terminal allocation)
1558 args.push("-q".into());
1559 args.push("-t".into());
1560 args.push(exec);
1561
1562 Ok(CommandTemplate {
1563 program: "ssh".into(),
1564 args,
1565 env: ssh_env,
1566 })
1567}
1568
1569#[cfg(test)]
1570mod tests {
1571 use super::*;
1572
1573 #[test]
1574 fn test_build_command() -> Result<()> {
1575 let mut input_env = HashMap::default();
1576 input_env.insert("INPUT_VA".to_string(), "val".to_string());
1577 let mut env = HashMap::default();
1578 env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1579
1580 let command = build_command(
1581 Some("remote_program".to_string()),
1582 &["arg1".to_string(), "arg2".to_string()],
1583 &input_env,
1584 Some("~/work".to_string()),
1585 None,
1586 env.clone(),
1587 PathStyle::Posix,
1588 "/bin/fish",
1589 ShellKind::Fish,
1590 vec!["-p".to_string(), "2222".to_string()],
1591 )?;
1592
1593 assert_eq!(command.program, "ssh");
1594 assert_eq!(
1595 command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1596 [
1597 "-p",
1598 "2222",
1599 "-q",
1600 "-t",
1601 "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1602 ]
1603 );
1604 assert_eq!(command.env, env);
1605
1606 let mut input_env = HashMap::default();
1607 input_env.insert("INPUT_VA".to_string(), "val".to_string());
1608 let mut env = HashMap::default();
1609 env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1610
1611 let command = build_command(
1612 None,
1613 &["arg1".to_string(), "arg2".to_string()],
1614 &input_env,
1615 None,
1616 Some((1, "foo".to_owned(), 2)),
1617 env.clone(),
1618 PathStyle::Posix,
1619 "/bin/fish",
1620 ShellKind::Fish,
1621 vec!["-p".to_string(), "2222".to_string()],
1622 )?;
1623
1624 assert_eq!(command.program, "ssh");
1625 assert_eq!(
1626 command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1627 [
1628 "-p",
1629 "2222",
1630 "-L",
1631 "1:foo:2",
1632 "-q",
1633 "-t",
1634 "cd && exec env INPUT_VA=val /bin/fish -l"
1635 ]
1636 );
1637 assert_eq!(command.env, env);
1638
1639 Ok(())
1640 }
1641
1642 #[test]
1643 fn scp_args_exclude_port_forward_flags() {
1644 let options = SshConnectionOptions {
1645 host: "example.com".into(),
1646 args: Some(vec![
1647 "-p".to_string(),
1648 "2222".to_string(),
1649 "-o".to_string(),
1650 "StrictHostKeyChecking=no".to_string(),
1651 ]),
1652 port_forwards: Some(vec![SshPortForwardOption {
1653 local_host: Some("127.0.0.1".to_string()),
1654 local_port: 8080,
1655 remote_host: Some("127.0.0.1".to_string()),
1656 remote_port: 80,
1657 }]),
1658 ..Default::default()
1659 };
1660
1661 let ssh_args = options.additional_args();
1662 assert!(
1663 ssh_args.iter().any(|arg| arg.starts_with("-L")),
1664 "expected ssh args to include port-forward: {ssh_args:?}"
1665 );
1666
1667 let scp_args = options.additional_args_for_scp();
1668 assert_eq!(
1669 scp_args,
1670 vec![
1671 "-p".to_string(),
1672 "2222".to_string(),
1673 "-o".to_string(),
1674 "StrictHostKeyChecking=no".to_string(),
1675 ]
1676 );
1677 }
1678
1679 #[test]
1680 fn test_host_parsing() -> Result<()> {
1681 let opts = SshConnectionOptions::parse_command_line("user@2001:db8::1")?;
1682 assert_eq!(opts.host, "2001:db8::1".into());
1683 assert_eq!(opts.username, Some("user".to_string()));
1684 assert_eq!(opts.port, None);
1685
1686 let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]:2222")?;
1687 assert_eq!(opts.host, "2001:db8::1".into());
1688 assert_eq!(opts.username, Some("user".to_string()));
1689 assert_eq!(opts.port, Some(2222));
1690
1691 let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]")?;
1692 assert_eq!(opts.host, "2001:db8::1".into());
1693 assert_eq!(opts.username, Some("user".to_string()));
1694 assert_eq!(opts.port, None);
1695
1696 let opts = SshConnectionOptions::parse_command_line("2001:db8::1")?;
1697 assert_eq!(opts.host, "2001:db8::1".into());
1698 assert_eq!(opts.username, None);
1699 assert_eq!(opts.port, None);
1700
1701 let opts = SshConnectionOptions::parse_command_line("[2001:db8::1]:2222")?;
1702 assert_eq!(opts.host, "2001:db8::1".into());
1703 assert_eq!(opts.username, None);
1704 assert_eq!(opts.port, Some(2222));
1705
1706 let opts = SshConnectionOptions::parse_command_line("user@example.com:2222")?;
1707 assert_eq!(opts.host, "example.com".into());
1708 assert_eq!(opts.username, Some("user".to_string()));
1709 assert_eq!(opts.port, Some(2222));
1710
1711 let opts = SshConnectionOptions::parse_command_line("user@192.168.1.1:2222")?;
1712 assert_eq!(opts.host, "192.168.1.1".into());
1713 assert_eq!(opts.username, Some("user".to_string()));
1714 assert_eq!(opts.port, Some(2222));
1715
1716 Ok(())
1717 }
1718}