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