1use crate::{
  2    RemoteClientDelegate, RemotePlatform,
  3    remote_client::{CommandTemplate, RemoteConnection, RemoteConnectionOptions},
  4};
  5use anyhow::{Context, Result, anyhow, bail};
  6use async_trait::async_trait;
  7use collections::HashMap;
  8use futures::channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender};
  9use gpui::{App, AppContext as _, AsyncApp, SemanticVersion, Task};
 10use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
 11use rpc::proto::Envelope;
 12use smol::{fs, process};
 13use std::{
 14    ffi::OsStr,
 15    fmt::Write as _,
 16    path::{Path, PathBuf},
 17    process::Stdio,
 18    sync::Arc,
 19    time::Instant,
 20};
 21use util::{
 22    paths::{PathStyle, RemotePathBuf},
 23    rel_path::RelPath,
 24    shell::ShellKind,
 25};
 26
 27#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, schemars::JsonSchema)]
 28pub struct WslConnectionOptions {
 29    pub distro_name: String,
 30    pub user: Option<String>,
 31}
 32
 33impl From<settings::WslConnection> for WslConnectionOptions {
 34    fn from(val: settings::WslConnection) -> Self {
 35        WslConnectionOptions {
 36            distro_name: val.distro_name.into(),
 37            user: val.user,
 38        }
 39    }
 40}
 41
 42#[derive(Debug)]
 43pub(crate) struct WslRemoteConnection {
 44    remote_binary_path: Option<Arc<RelPath>>,
 45    platform: RemotePlatform,
 46    shell: String,
 47    default_system_shell: String,
 48    connection_options: WslConnectionOptions,
 49    can_exec: bool,
 50}
 51
 52impl WslRemoteConnection {
 53    pub(crate) async fn new(
 54        connection_options: WslConnectionOptions,
 55        delegate: Arc<dyn RemoteClientDelegate>,
 56        cx: &mut AsyncApp,
 57    ) -> Result<Self> {
 58        log::info!(
 59            "Connecting to WSL distro {} with user {:?}",
 60            connection_options.distro_name,
 61            connection_options.user
 62        );
 63        let (release_channel, version, commit) = cx.update(|cx| {
 64            (
 65                ReleaseChannel::global(cx),
 66                AppVersion::global(cx),
 67                AppCommitSha::try_global(cx),
 68            )
 69        })?;
 70
 71        let mut this = Self {
 72            connection_options,
 73            remote_binary_path: None,
 74            platform: RemotePlatform { os: "", arch: "" },
 75            shell: String::new(),
 76            default_system_shell: String::from("/bin/sh"),
 77            can_exec: true,
 78        };
 79        delegate.set_status(Some("Detecting WSL environment"), cx);
 80        this.shell = this.detect_shell().await?;
 81        let shell = ShellKind::new(&this.shell, false);
 82        this.can_exec = this.detect_can_exec(shell).await?;
 83        this.platform = this.detect_platform(shell).await?;
 84        this.remote_binary_path = Some(
 85            this.ensure_server_binary(&delegate, release_channel, version, commit, shell, cx)
 86                .await?,
 87        );
 88        log::debug!("Detected WSL environment: {this:#?}");
 89
 90        Ok(this)
 91    }
 92
 93    async fn detect_can_exec(&self, shell: ShellKind) -> Result<bool> {
 94        let options = &self.connection_options;
 95        let program = if shell == ShellKind::Nushell {
 96            "^uname"
 97        } else {
 98            "uname"
 99        };
100        let args = &["-m"];
101        let output = wsl_command_impl(options, program, args, true)
102            .output()
103            .await?;
104
105        if !output.status.success() {
106            let output = wsl_command_impl(options, program, args, false)
107                .output()
108                .await?;
109
110            if !output.status.success() {
111                return Err(anyhow!(
112                    "Command '{}' failed: {}",
113                    program,
114                    String::from_utf8_lossy(&output.stderr).trim()
115                ));
116            }
117
118            Ok(false)
119        } else {
120            Ok(true)
121        }
122    }
123    async fn detect_platform(&self, shell: ShellKind) -> Result<RemotePlatform> {
124        let arch_str = if shell == ShellKind::Nushell {
125            // https://github.com/nushell/nushell/issues/12570
126            self.run_wsl_command("sh", &["-c", "uname -m"])
127        } else {
128            self.run_wsl_command("uname", &["-m"])
129        }
130        .await?;
131        let arch_str = arch_str.trim().to_string();
132        let arch = match arch_str.as_str() {
133            "x86_64" => "x86_64",
134            "aarch64" | "arm64" => "aarch64",
135            _ => "x86_64",
136        };
137        Ok(RemotePlatform { os: "linux", arch })
138    }
139
140    async fn detect_shell(&self) -> Result<String> {
141        Ok(self
142            .run_wsl_command("sh", &["-c", "echo $SHELL"])
143            .await
144            .ok()
145            .unwrap_or_else(|| "/bin/sh".to_string()))
146    }
147
148    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
149        windows_path_to_wsl_path_impl(&self.connection_options, source, self.can_exec).await
150    }
151
152    fn wsl_command(&self, program: &str, args: &[impl AsRef<OsStr>]) -> process::Command {
153        wsl_command_impl(&self.connection_options, program, args, self.can_exec)
154    }
155
156    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<String> {
157        run_wsl_command_impl(&self.connection_options, program, args, self.can_exec).await
158    }
159
160    async fn ensure_server_binary(
161        &self,
162        delegate: &Arc<dyn RemoteClientDelegate>,
163        release_channel: ReleaseChannel,
164        version: SemanticVersion,
165        commit: Option<AppCommitSha>,
166        shell: ShellKind,
167        cx: &mut AsyncApp,
168    ) -> Result<Arc<RelPath>> {
169        let version_str = match release_channel {
170            ReleaseChannel::Nightly => {
171                let commit = commit.map(|s| s.full()).unwrap_or_default();
172                format!("{}-{}", version, commit)
173            }
174            ReleaseChannel::Dev => "build".to_string(),
175            _ => version.to_string(),
176        };
177
178        let binary_name = format!(
179            "zed-remote-server-{}-{}",
180            release_channel.dev_name(),
181            version_str
182        );
183
184        let dst_path =
185            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
186
187        if let Some(parent) = dst_path.parent() {
188            let parent = parent.display(PathStyle::Posix);
189            if shell == ShellKind::Nushell {
190                self.run_wsl_command("mkdir", &[&parent]).await
191            } else {
192                self.run_wsl_command("mkdir", &["-p", &parent]).await
193            }
194            .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
195        }
196
197        #[cfg(debug_assertions)]
198        if let Some(remote_server_path) =
199            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
200        {
201            let tmp_path = paths::remote_wsl_server_dir_relative().join(
202                &RelPath::unix(&format!(
203                    "download-{}-{}",
204                    std::process::id(),
205                    remote_server_path.file_name().unwrap().to_string_lossy()
206                ))
207                .unwrap(),
208            );
209            self.upload_file(&remote_server_path, &tmp_path, delegate, &shell, cx)
210                .await?;
211            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
212                .await?;
213            return Ok(dst_path);
214        }
215
216        if self
217            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
218            .await
219            .is_ok()
220        {
221            return Ok(dst_path);
222        }
223
224        delegate.set_status(Some("Installing remote server"), cx);
225
226        let wanted_version = match release_channel {
227            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
228            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
229        };
230
231        let src_path = delegate
232            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
233            .await?;
234
235        let tmp_path = format!(
236            "{}.{}.gz",
237            dst_path.display(PathStyle::Posix),
238            std::process::id()
239        );
240        let tmp_path = RelPath::unix(&tmp_path).unwrap();
241
242        self.upload_file(&src_path, &tmp_path, delegate, &shell, cx)
243            .await?;
244        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
245            .await?;
246
247        Ok(dst_path)
248    }
249
250    async fn upload_file(
251        &self,
252        src_path: &Path,
253        dst_path: &RelPath,
254        delegate: &Arc<dyn RemoteClientDelegate>,
255        shell: &ShellKind,
256        cx: &mut AsyncApp,
257    ) -> Result<()> {
258        delegate.set_status(Some("Uploading remote server to WSL"), cx);
259
260        if let Some(parent) = dst_path.parent() {
261            let parent = parent.display(PathStyle::Posix);
262            if *shell == ShellKind::Nushell {
263                self.run_wsl_command("mkdir", &[&parent]).await
264            } else {
265                self.run_wsl_command("mkdir", &["-p", &parent]).await
266            }
267            .map_err(|e| anyhow!("Failed to create directory when uploading file: {}", e))?;
268        }
269
270        let t0 = Instant::now();
271        let src_stat = fs::metadata(&src_path).await?;
272        let size = src_stat.len();
273        log::info!(
274            "uploading remote server to WSL {:?} ({}kb)",
275            dst_path,
276            size / 1024
277        );
278
279        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
280        self.run_wsl_command(
281            "cp",
282            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
283        )
284        .await
285        .map_err(|e| {
286            anyhow!(
287                "Failed to copy file {}({}) to WSL {:?}: {}",
288                src_path.display(),
289                src_path_in_wsl,
290                dst_path,
291                e
292            )
293        })?;
294
295        log::info!("uploaded remote server in {:?}", t0.elapsed());
296        Ok(())
297    }
298
299    async fn extract_and_install(
300        &self,
301        tmp_path: &RelPath,
302        dst_path: &RelPath,
303        delegate: &Arc<dyn RemoteClientDelegate>,
304        cx: &mut AsyncApp,
305    ) -> Result<()> {
306        delegate.set_status(Some("Extracting remote server"), cx);
307
308        let tmp_path_str = tmp_path.display(PathStyle::Posix);
309        let dst_path_str = dst_path.display(PathStyle::Posix);
310
311        // Build extraction script with proper error handling
312        let script = if tmp_path_str.ends_with(".gz") {
313            let uncompressed = tmp_path_str.trim_end_matches(".gz");
314            format!(
315                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
316                tmp_path_str, uncompressed, uncompressed, dst_path_str
317            )
318        } else {
319            format!(
320                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
321                tmp_path_str, tmp_path_str, dst_path_str
322            )
323        };
324
325        self.run_wsl_command("sh", &["-c", &script])
326            .await
327            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
328        Ok(())
329    }
330}
331
332#[async_trait(?Send)]
333impl RemoteConnection for WslRemoteConnection {
334    fn start_proxy(
335        &self,
336        unique_identifier: String,
337        reconnect: bool,
338        incoming_tx: UnboundedSender<Envelope>,
339        outgoing_rx: UnboundedReceiver<Envelope>,
340        connection_activity_tx: Sender<()>,
341        delegate: Arc<dyn RemoteClientDelegate>,
342        cx: &mut AsyncApp,
343    ) -> Task<Result<i32>> {
344        delegate.set_status(Some("Starting proxy"), cx);
345
346        let Some(remote_binary_path) = &self.remote_binary_path else {
347            return Task::ready(Err(anyhow!("Remote binary path not set")));
348        };
349
350        let mut proxy_args = vec![];
351        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
352            if let Some(value) = std::env::var(env_var).ok() {
353                // We don't quote the value here as it seems excessive and may result in invalid envs for the
354                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
355                // in the proxy server. Therefore, we pass the env vars as is.
356                proxy_args.push(format!("{}={}", env_var, value));
357            }
358        }
359        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
360        proxy_args.push("proxy".to_owned());
361        proxy_args.push("--identifier".to_owned());
362        proxy_args.push(unique_identifier);
363
364        if reconnect {
365            proxy_args.push("--reconnect".to_owned());
366        }
367        let proxy_process = match self
368            .wsl_command("env", &proxy_args)
369            .kill_on_drop(true)
370            .spawn()
371        {
372            Ok(process) => process,
373            Err(error) => {
374                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
375            }
376        };
377
378        super::handle_rpc_messages_over_child_process_stdio(
379            proxy_process,
380            incoming_tx,
381            outgoing_rx,
382            connection_activity_tx,
383            cx,
384        )
385    }
386
387    fn upload_directory(
388        &self,
389        src_path: PathBuf,
390        dest_path: RemotePathBuf,
391        cx: &App,
392    ) -> Task<Result<()>> {
393        cx.background_spawn({
394            let options = self.connection_options.clone();
395            let can_exec = self.can_exec;
396            async move {
397                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path, can_exec).await?;
398
399                run_wsl_command_impl(
400                    &options,
401                    "cp",
402                    &["-r", &wsl_src, &dest_path.to_string()],
403                    can_exec,
404                )
405                .await
406                .map_err(|e| {
407                    anyhow!(
408                        "failed to upload directory {} -> {}: {}",
409                        src_path.display(),
410                        dest_path,
411                        e
412                    )
413                })?;
414
415                Ok(())
416            }
417        })
418    }
419
420    async fn kill(&self) -> Result<()> {
421        Ok(())
422    }
423
424    fn has_been_killed(&self) -> bool {
425        false
426    }
427
428    fn shares_network_interface(&self) -> bool {
429        true
430    }
431
432    fn build_command(
433        &self,
434        program: Option<String>,
435        args: &[String],
436        env: &HashMap<String, String>,
437        working_dir: Option<String>,
438        port_forward: Option<(u16, String, u16)>,
439    ) -> Result<CommandTemplate> {
440        if port_forward.is_some() {
441            bail!("WSL shares the network interface with the host system");
442        }
443
444        let shell_kind = ShellKind::new(&self.shell, false);
445        let working_dir = working_dir
446            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
447            .unwrap_or("~".to_string());
448
449        let mut exec = String::from("exec env ");
450
451        for (k, v) in env.iter() {
452            write!(
453                exec,
454                "{}={} ",
455                k,
456                shell_kind.try_quote(v).context("shell quoting")?
457            )?;
458        }
459
460        if let Some(program) = program {
461            write!(
462                exec,
463                "{}",
464                shell_kind.try_quote(&program).context("shell quoting")?
465            )?;
466            for arg in args {
467                let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
468                write!(exec, " {}", &arg)?;
469            }
470        } else {
471            write!(&mut exec, "{} -l", self.shell)?;
472        }
473
474        let wsl_args = if let Some(user) = &self.connection_options.user {
475            vec![
476                "--distribution".to_string(),
477                self.connection_options.distro_name.clone(),
478                "--user".to_string(),
479                user.clone(),
480                "--cd".to_string(),
481                working_dir,
482                "--".to_string(),
483                self.shell.clone(),
484                "-c".to_string(),
485                exec,
486            ]
487        } else {
488            vec![
489                "--distribution".to_string(),
490                self.connection_options.distro_name.clone(),
491                "--cd".to_string(),
492                working_dir,
493                "--".to_string(),
494                self.shell.clone(),
495                "-c".to_string(),
496                exec,
497            ]
498        };
499
500        Ok(CommandTemplate {
501            program: "wsl.exe".to_string(),
502            args: wsl_args,
503            env: HashMap::default(),
504        })
505    }
506
507    fn build_forward_ports_command(
508        &self,
509        _: Vec<(u16, String, u16)>,
510    ) -> anyhow::Result<CommandTemplate> {
511        Err(anyhow!("WSL shares a network interface with the host"))
512    }
513
514    fn connection_options(&self) -> RemoteConnectionOptions {
515        RemoteConnectionOptions::Wsl(self.connection_options.clone())
516    }
517
518    fn path_style(&self) -> PathStyle {
519        PathStyle::Posix
520    }
521
522    fn shell(&self) -> String {
523        self.shell.clone()
524    }
525
526    fn default_system_shell(&self) -> String {
527        self.default_system_shell.clone()
528    }
529}
530
531/// `wslpath` is a executable available in WSL, it's a linux binary.
532/// So it doesn't support Windows style paths.
533async fn sanitize_path(path: &Path) -> Result<String> {
534    let path = smol::fs::canonicalize(path).await?;
535    let path_str = path.to_string_lossy();
536
537    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
538    Ok(sanitized.replace('\\', "/"))
539}
540
541async fn windows_path_to_wsl_path_impl(
542    options: &WslConnectionOptions,
543    source: &Path,
544    exec: bool,
545) -> Result<String> {
546    let source = sanitize_path(source).await?;
547    run_wsl_command_impl(options, "wslpath", &["-u", &source], exec).await
548}
549
550async fn run_wsl_command_impl(
551    options: &WslConnectionOptions,
552    program: &str,
553    args: &[&str],
554    exec: bool,
555) -> Result<String> {
556    let output = wsl_command_impl(options, program, args, exec)
557        .output()
558        .await?;
559
560    if !output.status.success() {
561        return Err(anyhow!(
562            "Command '{}' failed: {}",
563            program,
564            String::from_utf8_lossy(&output.stderr).trim()
565        ));
566    }
567
568    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
569}
570
571/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
572///
573/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
574fn wsl_command_impl(
575    options: &WslConnectionOptions,
576    program: &str,
577    args: &[impl AsRef<OsStr>],
578    exec: bool,
579) -> process::Command {
580    let mut command = util::command::new_smol_command("wsl.exe");
581
582    if let Some(user) = &options.user {
583        command.arg("--user").arg(user);
584    }
585
586    command
587        .stdin(Stdio::piped())
588        .stdout(Stdio::piped())
589        .stderr(Stdio::piped())
590        .arg("--distribution")
591        .arg(&options.distro_name)
592        .arg("--cd")
593        .arg("~");
594
595    if exec {
596        command.arg("--exec");
597    }
598
599    command.arg(program).args(args);
600
601    log::debug!("wsl {:?}", command);
602    command
603}