wsl.rs

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