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