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    fmt::Write as _,
 15    path::{Path, PathBuf},
 16    process::Stdio,
 17    sync::Arc,
 18    time::Instant,
 19};
 20use util::{
 21    paths::{PathStyle, RemotePathBuf},
 22    rel_path::RelPath,
 23};
 24
 25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 26pub struct WslConnectionOptions {
 27    pub distro_name: String,
 28    pub user: Option<String>,
 29}
 30
 31impl From<settings::WslConnection> for WslConnectionOptions {
 32    fn from(val: settings::WslConnection) -> Self {
 33        WslConnectionOptions {
 34            distro_name: val.distro_name.into(),
 35            user: val.user,
 36        }
 37    }
 38}
 39
 40pub(crate) struct WslRemoteConnection {
 41    remote_binary_path: Option<Arc<RelPath>>,
 42    platform: RemotePlatform,
 43    shell: String,
 44    default_system_shell: String,
 45    connection_options: WslConnectionOptions,
 46}
 47
 48impl WslRemoteConnection {
 49    pub(crate) async fn new(
 50        connection_options: WslConnectionOptions,
 51        delegate: Arc<dyn RemoteClientDelegate>,
 52        cx: &mut AsyncApp,
 53    ) -> Result<Self> {
 54        log::info!(
 55            "Connecting to WSL distro {} with user {:?}",
 56            connection_options.distro_name,
 57            connection_options.user
 58        );
 59        let (release_channel, version, commit) = cx.update(|cx| {
 60            (
 61                ReleaseChannel::global(cx),
 62                AppVersion::global(cx),
 63                AppCommitSha::try_global(cx),
 64            )
 65        })?;
 66
 67        let mut this = Self {
 68            connection_options,
 69            remote_binary_path: None,
 70            platform: RemotePlatform { os: "", arch: "" },
 71            shell: String::new(),
 72            default_system_shell: String::from("/bin/sh"),
 73        };
 74        delegate.set_status(Some("Detecting WSL environment"), cx);
 75        this.platform = this.detect_platform().await?;
 76        this.shell = this.detect_shell().await?;
 77        this.remote_binary_path = Some(
 78            this.ensure_server_binary(&delegate, release_channel, version, commit, cx)
 79                .await?,
 80        );
 81
 82        Ok(this)
 83    }
 84
 85    async fn detect_platform(&self) -> Result<RemotePlatform> {
 86        let arch_str = self.run_wsl_command("uname", &["-m"]).await?;
 87        let arch_str = arch_str.trim().to_string();
 88        let arch = match arch_str.as_str() {
 89            "x86_64" => "x86_64",
 90            "aarch64" | "arm64" => "aarch64",
 91            _ => "x86_64",
 92        };
 93        Ok(RemotePlatform { os: "linux", arch })
 94    }
 95
 96    async fn detect_shell(&self) -> Result<String> {
 97        Ok(self
 98            .run_wsl_command("sh", &["-c", "echo $SHELL"])
 99            .await
100            .ok()
101            .and_then(|shell_path| {
102                Path::new(shell_path.trim())
103                    .file_name()
104                    .map(|it| it.to_str().unwrap().to_owned())
105            })
106            .unwrap_or_else(|| "bash".to_string()))
107    }
108
109    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
110        windows_path_to_wsl_path_impl(&self.connection_options, source).await
111    }
112
113    fn wsl_command(&self, program: &str, args: &[&str]) -> process::Command {
114        wsl_command_impl(&self.connection_options, program, args)
115    }
116
117    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<String> {
118        run_wsl_command_impl(&self.connection_options, program, args).await
119    }
120
121    async fn ensure_server_binary(
122        &self,
123        delegate: &Arc<dyn RemoteClientDelegate>,
124        release_channel: ReleaseChannel,
125        version: SemanticVersion,
126        commit: Option<AppCommitSha>,
127        cx: &mut AsyncApp,
128    ) -> Result<Arc<RelPath>> {
129        let version_str = match release_channel {
130            ReleaseChannel::Nightly => {
131                let commit = commit.map(|s| s.full()).unwrap_or_default();
132                format!("{}-{}", version, commit)
133            }
134            ReleaseChannel::Dev => "build".to_string(),
135            _ => version.to_string(),
136        };
137
138        let binary_name = format!(
139            "zed-remote-server-{}-{}",
140            release_channel.dev_name(),
141            version_str
142        );
143
144        let dst_path =
145            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
146
147        if let Some(parent) = dst_path.parent() {
148            self.run_wsl_command("mkdir", &["-p", &parent.display(PathStyle::Posix)])
149                .await
150                .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
151        }
152
153        #[cfg(debug_assertions)]
154        if let Some(remote_server_path) =
155            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
156        {
157            let tmp_path = paths::remote_wsl_server_dir_relative().join(
158                &RelPath::unix(&format!(
159                    "download-{}-{}",
160                    std::process::id(),
161                    remote_server_path.file_name().unwrap().to_string_lossy()
162                ))
163                .unwrap(),
164            );
165            self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
166                .await?;
167            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
168                .await?;
169            return Ok(dst_path);
170        }
171
172        if self
173            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
174            .await
175            .is_ok()
176        {
177            return Ok(dst_path);
178        }
179
180        delegate.set_status(Some("Installing remote server"), cx);
181
182        let wanted_version = match release_channel {
183            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
184            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
185        };
186
187        let src_path = delegate
188            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
189            .await?;
190
191        let tmp_path = format!(
192            "{}.{}.gz",
193            dst_path.display(PathStyle::Posix),
194            std::process::id()
195        );
196        let tmp_path = RelPath::unix(&tmp_path).unwrap();
197
198        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
199        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
200            .await?;
201
202        Ok(dst_path)
203    }
204
205    async fn upload_file(
206        &self,
207        src_path: &Path,
208        dst_path: &RelPath,
209        delegate: &Arc<dyn RemoteClientDelegate>,
210        cx: &mut AsyncApp,
211    ) -> Result<()> {
212        delegate.set_status(Some("Uploading remote server to WSL"), cx);
213
214        if let Some(parent) = dst_path.parent() {
215            self.run_wsl_command("mkdir", &["-p", &parent.display(PathStyle::Posix)])
216                .await
217                .map_err(|e| anyhow!("Failed to create directory when uploading file: {}", e))?;
218        }
219
220        let t0 = Instant::now();
221        let src_stat = fs::metadata(&src_path).await?;
222        let size = src_stat.len();
223        log::info!(
224            "uploading remote server to WSL {:?} ({}kb)",
225            dst_path,
226            size / 1024
227        );
228
229        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
230        self.run_wsl_command(
231            "cp",
232            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
233        )
234        .await
235        .map_err(|e| {
236            anyhow!(
237                "Failed to copy file {}({}) to WSL {:?}: {}",
238                src_path.display(),
239                src_path_in_wsl,
240                dst_path,
241                e
242            )
243        })?;
244
245        log::info!("uploaded remote server in {:?}", t0.elapsed());
246        Ok(())
247    }
248
249    async fn extract_and_install(
250        &self,
251        tmp_path: &RelPath,
252        dst_path: &RelPath,
253        delegate: &Arc<dyn RemoteClientDelegate>,
254        cx: &mut AsyncApp,
255    ) -> Result<()> {
256        delegate.set_status(Some("Extracting remote server"), cx);
257
258        let tmp_path_str = tmp_path.display(PathStyle::Posix);
259        let dst_path_str = dst_path.display(PathStyle::Posix);
260
261        // Build extraction script with proper error handling
262        let script = if tmp_path_str.ends_with(".gz") {
263            let uncompressed = tmp_path_str.trim_end_matches(".gz");
264            format!(
265                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
266                tmp_path_str, uncompressed, uncompressed, dst_path_str
267            )
268        } else {
269            format!(
270                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
271                tmp_path_str, tmp_path_str, dst_path_str
272            )
273        };
274
275        self.run_wsl_command("sh", &["-c", &script])
276            .await
277            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
278        Ok(())
279    }
280}
281
282#[async_trait(?Send)]
283impl RemoteConnection for WslRemoteConnection {
284    fn start_proxy(
285        &self,
286        unique_identifier: String,
287        reconnect: bool,
288        incoming_tx: UnboundedSender<Envelope>,
289        outgoing_rx: UnboundedReceiver<Envelope>,
290        connection_activity_tx: Sender<()>,
291        delegate: Arc<dyn RemoteClientDelegate>,
292        cx: &mut AsyncApp,
293    ) -> Task<Result<i32>> {
294        delegate.set_status(Some("Starting proxy"), cx);
295
296        let Some(remote_binary_path) = &self.remote_binary_path else {
297            return Task::ready(Err(anyhow!("Remote binary path not set")));
298        };
299
300        let mut proxy_command = format!(
301            "exec {} proxy --identifier {}",
302            remote_binary_path.display(PathStyle::Posix),
303            unique_identifier
304        );
305
306        if reconnect {
307            proxy_command.push_str(" --reconnect");
308        }
309
310        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
311            if let Some(value) = std::env::var(env_var).ok() {
312                proxy_command = format!("{}='{}' {}", env_var, value, proxy_command);
313            }
314        }
315        let proxy_process = match self
316            .wsl_command("sh", &["-lc", &proxy_command])
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 script = String::new();
391
392        for (k, v) in env.iter() {
393            write!(&mut script, "{}='{}' ", k, v).unwrap();
394        }
395
396        if let Some(program) = program {
397            let command = shlex::try_quote(&program)?;
398            script.push_str(&command);
399            for arg in args {
400                let arg = shlex::try_quote(&arg)?;
401                script.push_str(" ");
402                script.push_str(&arg);
403            }
404        } else {
405            write!(&mut script, "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                script,
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                script,
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: &[&str],
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    command
499}
500
501async fn run_wsl_command_impl(
502    options: &WslConnectionOptions,
503    program: &str,
504    args: &[&str],
505) -> Result<String> {
506    let output = wsl_command_impl(options, program, args).output().await?;
507
508    if !output.status.success() {
509        return Err(anyhow!(
510            "Command '{}' failed: {}",
511            program,
512            String::from_utf8_lossy(&output.stderr).trim()
513        ));
514    }
515
516    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
517}