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