1use crate::{
  2    json_log::LogRecord,
  3    protocol::{MESSAGE_LEN_SIZE, message_len_from_buffer, read_message_with_len, write_message},
  4};
  5use anyhow::{Context as _, Result};
  6use futures::{
  7    AsyncReadExt as _, FutureExt as _, StreamExt as _,
  8    channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
  9};
 10use gpui::{AppContext as _, AsyncApp, Task};
 11use rpc::proto::Envelope;
 12use smol::process::Child;
 13
 14pub mod ssh;
 15pub mod wsl;
 16
 17fn handle_rpc_messages_over_child_process_stdio(
 18    mut ssh_proxy_process: Child,
 19    incoming_tx: UnboundedSender<Envelope>,
 20    mut outgoing_rx: UnboundedReceiver<Envelope>,
 21    mut connection_activity_tx: Sender<()>,
 22    cx: &AsyncApp,
 23) -> Task<Result<i32>> {
 24    let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
 25    let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
 26    let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
 27
 28    let mut stdin_buffer = Vec::new();
 29    let mut stdout_buffer = Vec::new();
 30    let mut stderr_buffer = Vec::new();
 31    let mut stderr_offset = 0;
 32
 33    let stdin_task = cx.background_spawn(async move {
 34        while let Some(outgoing) = outgoing_rx.next().await {
 35            write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
 36        }
 37        anyhow::Ok(())
 38    });
 39
 40    let stdout_task = cx.background_spawn({
 41        let mut connection_activity_tx = connection_activity_tx.clone();
 42        async move {
 43            loop {
 44                stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
 45                let len = child_stdout.read(&mut stdout_buffer).await?;
 46
 47                if len == 0 {
 48                    return anyhow::Ok(());
 49                }
 50
 51                if len < MESSAGE_LEN_SIZE {
 52                    child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
 53                }
 54
 55                let message_len = message_len_from_buffer(&stdout_buffer);
 56                let envelope =
 57                    read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
 58                        .await?;
 59                connection_activity_tx.try_send(()).ok();
 60                incoming_tx.unbounded_send(envelope).ok();
 61            }
 62        }
 63    });
 64
 65    let stderr_task: Task<anyhow::Result<()>> = cx.background_spawn(async move {
 66        loop {
 67            stderr_buffer.resize(stderr_offset + 1024, 0);
 68
 69            let len = child_stderr
 70                .read(&mut stderr_buffer[stderr_offset..])
 71                .await?;
 72            if len == 0 {
 73                return anyhow::Ok(());
 74            }
 75
 76            stderr_offset += len;
 77            let mut start_ix = 0;
 78            while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
 79                .iter()
 80                .position(|b| b == &b'\n')
 81            {
 82                let line_ix = start_ix + ix;
 83                let content = &stderr_buffer[start_ix..line_ix];
 84                start_ix = line_ix + 1;
 85                if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
 86                    record.log(log::logger())
 87                } else {
 88                    eprintln!("(remote) {}", String::from_utf8_lossy(content));
 89                }
 90            }
 91            stderr_buffer.drain(0..start_ix);
 92            stderr_offset -= start_ix;
 93
 94            connection_activity_tx.try_send(()).ok();
 95        }
 96    });
 97
 98    cx.background_spawn(async move {
 99        let result = futures::select! {
100            result = stdin_task.fuse() => {
101                result.context("stdin")
102            }
103            result = stdout_task.fuse() => {
104                result.context("stdout")
105            }
106            result = stderr_task.fuse() => {
107                result.context("stderr")
108            }
109        };
110        let status = ssh_proxy_process.status().await?.code().unwrap_or(1);
111        match result {
112            Ok(_) => Ok(status),
113            Err(error) => Err(error),
114        }
115    })
116}
117
118#[cfg(debug_assertions)]
119async fn build_remote_server_from_source(
120    platform: &crate::RemotePlatform,
121    delegate: &dyn crate::RemoteClientDelegate,
122    cx: &mut AsyncApp,
123) -> Result<Option<std::path::PathBuf>> {
124    use smol::process::{Command, Stdio};
125    use std::env::VarError;
126    use std::path::Path;
127
128    // By default, we make building remote server from source opt-out and we do not force artifact compression
129    // for quicker builds.
130    let build_remote_server =
131        std::env::var("ZED_BUILD_REMOTE_SERVER").unwrap_or("nocompress".into());
132
133    if build_remote_server == "false"
134        || build_remote_server == "no"
135        || build_remote_server == "off"
136        || build_remote_server == "0"
137    {
138        return Ok(None);
139    }
140
141    async fn run_cmd(command: &mut Command) -> Result<()> {
142        let output = command
143            .kill_on_drop(true)
144            .stderr(Stdio::inherit())
145            .output()
146            .await?;
147        anyhow::ensure!(
148            output.status.success(),
149            "Failed to run command: {command:?}"
150        );
151        Ok(())
152    }
153
154    let use_musl = !build_remote_server.contains("nomusl");
155    let triple = format!(
156        "{}-{}",
157        platform.arch,
158        match platform.os {
159            "linux" =>
160                if use_musl {
161                    "unknown-linux-musl"
162                } else {
163                    "unknown-linux-gnu"
164                },
165            "macos" => "apple-darwin",
166            _ => anyhow::bail!("can't cross compile for: {:?}", platform),
167        }
168    );
169    let mut rust_flags = match std::env::var("RUSTFLAGS") {
170        Ok(val) => val,
171        Err(VarError::NotPresent) => String::new(),
172        Err(e) => {
173            log::error!("Failed to get env var `RUSTFLAGS` value: {e}");
174            String::new()
175        }
176    };
177    if platform.os == "linux" && use_musl {
178        rust_flags.push_str(" -C target-feature=+crt-static");
179
180        if let Ok(path) = std::env::var("ZED_ZSTD_MUSL_LIB") {
181            rust_flags.push_str(&format!(" -C link-arg=-L{path}"));
182        }
183    }
184    if build_remote_server.contains("mold") {
185        rust_flags.push_str(" -C link-arg=-fuse-ld=mold");
186    }
187
188    if platform.arch == std::env::consts::ARCH && platform.os == std::env::consts::OS {
189        delegate.set_status(Some("Building remote server binary from source"), cx);
190        log::info!("building remote server binary from source");
191        run_cmd(
192            Command::new("cargo")
193                .current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
194                .args([
195                    "build",
196                    "--package",
197                    "remote_server",
198                    "--features",
199                    "debug-embed",
200                    "--target-dir",
201                    "target/remote_server",
202                    "--target",
203                    &triple,
204                ])
205                .env("RUSTFLAGS", &rust_flags),
206        )
207        .await?;
208    } else {
209        if which("zig", cx).await?.is_none() {
210            anyhow::bail!(if cfg!(not(windows)) {
211                "zig not found on $PATH, install zig (see https://ziglang.org/learn/getting-started or use zigup)"
212            } else {
213                "zig not found on $PATH, install zig (use `winget install -e --id zig.zig` or see https://ziglang.org/learn/getting-started or use zigup)"
214            });
215        }
216
217        let rustup = which("rustup", cx)
218            .await?
219            .context("rustup not found on $PATH, install rustup (see https://rustup.rs/)")?;
220        delegate.set_status(Some("Adding rustup target for cross-compilation"), cx);
221        log::info!("adding rustup target");
222        run_cmd(Command::new(rustup).args(["target", "add"]).arg(&triple)).await?;
223
224        if which("cargo-zigbuild", cx).await?.is_none() {
225            delegate.set_status(Some("Installing cargo-zigbuild for cross-compilation"), cx);
226            log::info!("installing cargo-zigbuild");
227            run_cmd(Command::new("cargo").args(["install", "--locked", "cargo-zigbuild"])).await?;
228        }
229
230        delegate.set_status(
231            Some(&format!(
232                "Building remote binary from source for {triple} with Zig"
233            )),
234            cx,
235        );
236        log::info!("building remote binary from source for {triple} with Zig");
237        run_cmd(
238            Command::new("cargo")
239                .args([
240                    "zigbuild",
241                    "--package",
242                    "remote_server",
243                    "--features",
244                    "debug-embed",
245                    "--target-dir",
246                    "target/remote_server",
247                    "--target",
248                    &triple,
249                ])
250                .env("RUSTFLAGS", &rust_flags),
251        )
252        .await?;
253    };
254    let bin_path = Path::new("target")
255        .join("remote_server")
256        .join(&triple)
257        .join("debug")
258        .join("remote_server");
259
260    let path = if !build_remote_server.contains("nocompress") {
261        delegate.set_status(Some("Compressing binary"), cx);
262
263        #[cfg(not(target_os = "windows"))]
264        {
265            run_cmd(Command::new("gzip").args(["-f", &bin_path.to_string_lossy()])).await?;
266        }
267
268        #[cfg(target_os = "windows")]
269        {
270            // On Windows, we use 7z to compress the binary
271            let seven_zip = which("7z.exe",cx)
272                .await?
273                .context("7z.exe not found on $PATH, install it (e.g. with `winget install -e --id 7zip.7zip`) or, if you don't want this behaviour, set $env:ZED_BUILD_REMOTE_SERVER=\"nocompress\"")?;
274            let gz_path = format!("target/remote_server/{}/debug/remote_server.gz", triple);
275            if smol::fs::metadata(&gz_path).await.is_ok() {
276                smol::fs::remove_file(&gz_path).await?;
277            }
278            run_cmd(Command::new(seven_zip).args([
279                "a",
280                "-tgzip",
281                &gz_path,
282                &bin_path.to_string_lossy(),
283            ]))
284            .await?;
285        }
286
287        let mut archive_path = bin_path;
288        archive_path.set_extension("gz");
289        std::env::current_dir()?.join(archive_path)
290    } else {
291        bin_path
292    };
293
294    Ok(Some(path))
295}
296
297#[cfg(debug_assertions)]
298async fn which(
299    binary_name: impl AsRef<str>,
300    cx: &mut AsyncApp,
301) -> Result<Option<std::path::PathBuf>> {
302    let binary_name = binary_name.as_ref().to_string();
303    let binary_name_cloned = binary_name.clone();
304    let res = cx
305        .background_spawn(async move { which::which(binary_name_cloned) })
306        .await;
307    match res {
308        Ok(path) => Ok(Some(path)),
309        Err(which::Error::CannotFindBinaryPath) => Ok(None),
310        Err(err) => Err(anyhow::anyhow!(
311            "Failed to run 'which' to find the binary '{binary_name}': {err}"
312        )),
313    }
314}