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