unix.rs

  1use crate::HeadlessProject;
  2use crate::headless_project::HeadlessAppState;
  3use anyhow::{Context as _, Result, anyhow};
  4use chrono::Utc;
  5use client::{ProxySettings, telemetry};
  6
  7use extension::ExtensionHostProxy;
  8use fs::{Fs, RealFs};
  9use futures::channel::mpsc;
 10use futures::{AsyncRead, AsyncWrite, AsyncWriteExt, FutureExt, SinkExt, select, select_biased};
 11use git::GitHostingProviderRegistry;
 12use gpui::{App, AppContext as _, Context, Entity, SemanticVersion, UpdateGlobal as _};
 13use gpui_tokio::Tokio;
 14use http_client::{Url, read_proxy_from_env};
 15use language::LanguageRegistry;
 16use node_runtime::{NodeBinaryOptions, NodeRuntime};
 17use paths::logs_dir;
 18use project::project_settings::ProjectSettings;
 19
 20use release_channel::{AppVersion, RELEASE_CHANNEL, ReleaseChannel};
 21use remote::proxy::ProxyLaunchError;
 22use remote::ssh_session::ChannelClient;
 23use remote::{
 24    json_log::LogRecord,
 25    protocol::{read_message, write_message},
 26};
 27use reqwest_client::ReqwestClient;
 28use rpc::proto::{self, Envelope, SSH_PROJECT_ID};
 29use rpc::{AnyProtoClient, TypedEnvelope};
 30use settings::{Settings, SettingsStore, watch_config_file};
 31use smol::channel::{Receiver, Sender};
 32use smol::io::AsyncReadExt;
 33
 34use smol::Async;
 35use smol::{net::unix::UnixListener, stream::StreamExt as _};
 36use std::ffi::OsStr;
 37use std::ops::ControlFlow;
 38use std::str::FromStr;
 39use std::{env, thread};
 40use std::{
 41    io::Write,
 42    mem,
 43    path::{Path, PathBuf},
 44    sync::Arc,
 45};
 46use telemetry_events::LocationData;
 47use util::ResultExt;
 48
 49fn init_logging_proxy() {
 50    env_logger::builder()
 51        .format(|buf, record| {
 52            let mut log_record = LogRecord::new(record);
 53            log_record.message = format!("(remote proxy) {}", log_record.message);
 54            serde_json::to_writer(&mut *buf, &log_record)?;
 55            buf.write_all(b"\n")?;
 56            Ok(())
 57        })
 58        .init();
 59}
 60
 61fn init_logging_server(log_file_path: PathBuf) -> Result<Receiver<Vec<u8>>> {
 62    struct MultiWrite {
 63        file: std::fs::File,
 64        channel: Sender<Vec<u8>>,
 65        buffer: Vec<u8>,
 66    }
 67
 68    impl std::io::Write for MultiWrite {
 69        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
 70            let written = self.file.write(buf)?;
 71            self.buffer.extend_from_slice(&buf[..written]);
 72            Ok(written)
 73        }
 74
 75        fn flush(&mut self) -> std::io::Result<()> {
 76            self.channel
 77                .send_blocking(self.buffer.clone())
 78                .map_err(|error| std::io::Error::new(std::io::ErrorKind::Other, error))?;
 79            self.buffer.clear();
 80            self.file.flush()
 81        }
 82    }
 83
 84    let log_file = std::fs::OpenOptions::new()
 85        .create(true)
 86        .append(true)
 87        .open(&log_file_path)
 88        .context("Failed to open log file in append mode")?;
 89
 90    let (tx, rx) = smol::channel::unbounded();
 91
 92    let target = Box::new(MultiWrite {
 93        file: log_file,
 94        channel: tx,
 95        buffer: Vec::new(),
 96    });
 97
 98    env_logger::Builder::from_default_env()
 99        .target(env_logger::Target::Pipe(target))
100        .format(|buf, record| {
101            let mut log_record = LogRecord::new(record);
102            log_record.message = format!("(remote server) {}", log_record.message);
103            serde_json::to_writer(&mut *buf, &log_record)?;
104            buf.write_all(b"\n")?;
105            Ok(())
106        })
107        .init();
108
109    Ok(rx)
110}
111
112fn init_panic_hook() {
113    std::panic::set_hook(Box::new(|info| {
114        let payload = info
115            .payload()
116            .downcast_ref::<&str>()
117            .map(|s| s.to_string())
118            .or_else(|| info.payload().downcast_ref::<String>().cloned())
119            .unwrap_or_else(|| "Box<Any>".to_string());
120
121        let backtrace = backtrace::Backtrace::new();
122        let mut backtrace = backtrace
123            .frames()
124            .iter()
125            .flat_map(|frame| {
126                frame
127                    .symbols()
128                    .iter()
129                    .filter_map(|frame| Some(format!("{:#}", frame.name()?)))
130            })
131            .collect::<Vec<_>>();
132
133        // Strip out leading stack frames for rust panic-handling.
134        if let Some(ix) = backtrace
135            .iter()
136            .position(|name| name == "rust_begin_unwind")
137        {
138            backtrace.drain(0..=ix);
139        }
140
141        let thread = thread::current();
142        let thread_name = thread.name().unwrap_or("<unnamed>");
143
144        log::error!(
145            "panic occurred: {}\nBacktrace:\n{}",
146            &payload,
147            (&backtrace).join("\n")
148        );
149
150        let release_channel = *RELEASE_CHANNEL;
151        let version = match release_channel {
152            ReleaseChannel::Stable | ReleaseChannel::Preview => env!("ZED_PKG_VERSION"),
153            ReleaseChannel::Nightly | ReleaseChannel::Dev => {
154                option_env!("ZED_COMMIT_SHA").unwrap_or("missing-zed-commit-sha")
155            }
156        };
157
158        let panic_data = telemetry_events::Panic {
159            thread: thread_name.into(),
160            payload: payload.clone(),
161            location_data: info.location().map(|location| LocationData {
162                file: location.file().into(),
163                line: location.line(),
164            }),
165            app_version: format!("remote-server-{version}"),
166            app_commit_sha: option_env!("ZED_COMMIT_SHA").map(|sha| sha.into()),
167            release_channel: release_channel.dev_name().into(),
168            target: env!("TARGET").to_owned().into(),
169            os_name: telemetry::os_name(),
170            os_version: Some(telemetry::os_version()),
171            architecture: env::consts::ARCH.into(),
172            panicked_on: Utc::now().timestamp_millis(),
173            backtrace,
174            system_id: None,            // Set on SSH client
175            installation_id: None,      // Set on SSH client
176            session_id: "".to_string(), // Set on SSH client
177        };
178
179        if let Some(panic_data_json) = serde_json::to_string(&panic_data).log_err() {
180            let timestamp = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
181            let panic_file_path = paths::logs_dir().join(format!("zed-{timestamp}.panic"));
182            let panic_file = std::fs::OpenOptions::new()
183                .append(true)
184                .create(true)
185                .open(&panic_file_path)
186                .log_err();
187            if let Some(mut panic_file) = panic_file {
188                writeln!(&mut panic_file, "{panic_data_json}").log_err();
189                panic_file.flush().log_err();
190            }
191        }
192
193        std::process::abort();
194    }));
195}
196
197fn handle_panic_requests(project: &Entity<HeadlessProject>, client: &Arc<ChannelClient>) {
198    let client: AnyProtoClient = client.clone().into();
199    client.add_request_handler(
200        project.downgrade(),
201        |_, _: TypedEnvelope<proto::GetPanicFiles>, _cx| async move {
202            let mut children = smol::fs::read_dir(paths::logs_dir()).await?;
203            let mut panic_files = Vec::new();
204            while let Some(child) = children.next().await {
205                let child = child?;
206                let child_path = child.path();
207
208                if child_path.extension() != Some(OsStr::new("panic")) {
209                    continue;
210                }
211                let filename = if let Some(filename) = child_path.file_name() {
212                    filename.to_string_lossy()
213                } else {
214                    continue;
215                };
216
217                if !filename.starts_with("zed") {
218                    continue;
219                }
220
221                let file_contents = smol::fs::read_to_string(&child_path)
222                    .await
223                    .context("error reading panic file")?;
224
225                panic_files.push(file_contents);
226
227                // We've done what we can, delete the file
228                std::fs::remove_file(child_path)
229                    .context("error removing panic")
230                    .log_err();
231            }
232            anyhow::Ok(proto::GetPanicFilesResponse {
233                file_contents: panic_files,
234            })
235        },
236    );
237}
238
239struct ServerListeners {
240    stdin: UnixListener,
241    stdout: UnixListener,
242    stderr: UnixListener,
243}
244
245impl ServerListeners {
246    pub fn new(stdin_path: PathBuf, stdout_path: PathBuf, stderr_path: PathBuf) -> Result<Self> {
247        Ok(Self {
248            stdin: UnixListener::bind(stdin_path).context("failed to bind stdin socket")?,
249            stdout: UnixListener::bind(stdout_path).context("failed to bind stdout socket")?,
250            stderr: UnixListener::bind(stderr_path).context("failed to bind stderr socket")?,
251        })
252    }
253}
254
255fn start_server(
256    listeners: ServerListeners,
257    log_rx: Receiver<Vec<u8>>,
258    cx: &mut App,
259) -> Arc<ChannelClient> {
260    // This is the server idle timeout. If no connection comes in this timeout, the server will shut down.
261    const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
262
263    let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
264    let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded::<Envelope>();
265    let (app_quit_tx, mut app_quit_rx) = mpsc::unbounded::<()>();
266
267    cx.on_app_quit(move |_| {
268        let mut app_quit_tx = app_quit_tx.clone();
269        async move {
270            log::info!("app quitting. sending signal to server main loop");
271            app_quit_tx.send(()).await.ok();
272        }
273    })
274    .detach();
275
276    cx.spawn(async move |cx| {
277        let mut stdin_incoming = listeners.stdin.incoming();
278        let mut stdout_incoming = listeners.stdout.incoming();
279        let mut stderr_incoming = listeners.stderr.incoming();
280
281        loop {
282            let streams = futures::future::join3(stdin_incoming.next(), stdout_incoming.next(), stderr_incoming.next());
283
284            log::info!("accepting new connections");
285            let result = select! {
286                streams = streams.fuse() => {
287                    let (Some(Ok(stdin_stream)), Some(Ok(stdout_stream)), Some(Ok(stderr_stream))) = streams else {
288                        break;
289                    };
290                    anyhow::Ok((stdin_stream, stdout_stream, stderr_stream))
291                }
292                _ = futures::FutureExt::fuse(smol::Timer::after(IDLE_TIMEOUT)) => {
293                    log::warn!("timed out waiting for new connections after {:?}. exiting.", IDLE_TIMEOUT);
294                    cx.update(|cx| {
295                        // TODO: This is a hack, because in a headless project, shutdown isn't executed
296                        // when calling quit, but it should be.
297                        cx.shutdown();
298                        cx.quit();
299                    })?;
300                    break;
301                }
302                _ = app_quit_rx.next().fuse() => {
303                    break;
304                }
305            };
306
307            let Ok((mut stdin_stream, mut stdout_stream, mut stderr_stream)) = result else {
308                break;
309            };
310
311            let mut input_buffer = Vec::new();
312            let mut output_buffer = Vec::new();
313
314            let (mut stdin_msg_tx, mut stdin_msg_rx) = mpsc::unbounded::<Envelope>();
315            cx.background_spawn(async move {
316                while let Ok(msg) = read_message(&mut stdin_stream, &mut input_buffer).await {
317                    if let Err(_) = stdin_msg_tx.send(msg).await {
318                        break;
319                    }
320                }
321            }).detach();
322
323            loop {
324
325                select_biased! {
326                    _ = app_quit_rx.next().fuse() => {
327                        return anyhow::Ok(());
328                    }
329
330                    stdin_message = stdin_msg_rx.next().fuse() => {
331                        let Some(message) = stdin_message else {
332                            log::warn!("error reading message on stdin. exiting.");
333                            break;
334                        };
335                        if let Err(error) = incoming_tx.unbounded_send(message) {
336                            log::error!("failed to send message to application: {error:?}. exiting.");
337                            return Err(anyhow!(error));
338                        }
339                    }
340
341                    outgoing_message  = outgoing_rx.next().fuse() => {
342                        let Some(message) = outgoing_message else {
343                            log::error!("stdout handler, no message");
344                            break;
345                        };
346
347                        if let Err(error) =
348                            write_message(&mut stdout_stream, &mut output_buffer, message).await
349                        {
350                            log::error!("failed to write stdout message: {:?}", error);
351                            break;
352                        }
353                        if let Err(error) = stdout_stream.flush().await {
354                            log::error!("failed to flush stdout message: {:?}", error);
355                            break;
356                        }
357                    }
358
359                    log_message = log_rx.recv().fuse() => {
360                        if let Ok(log_message) = log_message {
361                            if let Err(error) = stderr_stream.write_all(&log_message).await {
362                                log::error!("failed to write log message to stderr: {:?}", error);
363                                break;
364                            }
365                            if let Err(error) = stderr_stream.flush().await {
366                                log::error!("failed to flush stderr stream: {:?}", error);
367                                break;
368                            }
369                        }
370                    }
371                }
372            }
373        }
374        anyhow::Ok(())
375    })
376    .detach();
377
378    ChannelClient::new(incoming_rx, outgoing_tx, cx, "server")
379}
380
381fn init_paths() -> anyhow::Result<()> {
382    for path in [
383        paths::config_dir(),
384        paths::extensions_dir(),
385        paths::languages_dir(),
386        paths::logs_dir(),
387        paths::temp_dir(),
388        paths::remote_extensions_dir(),
389        paths::remote_extensions_uploads_dir(),
390    ]
391    .iter()
392    {
393        std::fs::create_dir_all(path).with_context(|| format!("creating directory {path:?}"))?;
394    }
395    Ok(())
396}
397
398pub fn execute_run(
399    log_file: PathBuf,
400    pid_file: PathBuf,
401    stdin_socket: PathBuf,
402    stdout_socket: PathBuf,
403    stderr_socket: PathBuf,
404) -> Result<()> {
405    init_paths()?;
406
407    match daemonize()? {
408        ControlFlow::Break(_) => return Ok(()),
409        ControlFlow::Continue(_) => {}
410    }
411
412    init_panic_hook();
413    let log_rx = init_logging_server(log_file)?;
414    log::info!(
415        "starting up. pid_file: {:?}, stdin_socket: {:?}, stdout_socket: {:?}, stderr_socket: {:?}",
416        pid_file,
417        stdin_socket,
418        stdout_socket,
419        stderr_socket
420    );
421
422    write_pid_file(&pid_file)
423        .with_context(|| format!("failed to write pid file: {:?}", &pid_file))?;
424
425    let listeners = ServerListeners::new(stdin_socket, stdout_socket, stderr_socket)?;
426
427    let git_hosting_provider_registry = Arc::new(GitHostingProviderRegistry::new());
428    gpui::Application::headless().run(move |cx| {
429        settings::init(cx);
430        let app_version = AppVersion::load(env!("ZED_PKG_VERSION"));
431        release_channel::init(app_version, cx);
432        gpui_tokio::init(cx);
433
434        HeadlessProject::init(cx);
435
436        log::info!("gpui app started, initializing server");
437        let session = start_server(listeners, log_rx, cx);
438
439        client::init_settings(cx);
440
441        GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
442        git_hosting_providers::init(cx);
443        dap_adapters::init(cx);
444
445        extension::init(cx);
446        let extension_host_proxy = ExtensionHostProxy::global(cx);
447
448        let project = cx.new(|cx| {
449            let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
450            let node_settings_rx = initialize_settings(session.clone(), fs.clone(), cx);
451
452            let proxy_url = read_proxy_settings(cx);
453
454            let http_client = {
455                let _guard = Tokio::handle(cx).enter();
456                Arc::new(
457                    ReqwestClient::proxy_and_user_agent(
458                        proxy_url,
459                        &format!(
460                            "Zed-Server/{} ({}; {})",
461                            env!("CARGO_PKG_VERSION"),
462                            std::env::consts::OS,
463                            std::env::consts::ARCH
464                        ),
465                    )
466                    .expect("Could not start HTTP client"),
467                )
468            };
469
470            let node_runtime = NodeRuntime::new(http_client.clone(), None, node_settings_rx);
471
472            let mut languages = LanguageRegistry::new(cx.background_executor().clone());
473            languages.set_language_server_download_dir(paths::languages_dir().clone());
474            let languages = Arc::new(languages);
475
476            HeadlessProject::new(
477                HeadlessAppState {
478                    session: session.clone(),
479                    fs,
480                    http_client,
481                    node_runtime,
482                    languages,
483                    extension_host_proxy,
484                },
485                cx,
486            )
487        });
488
489        handle_panic_requests(&project, &session);
490
491        cx.background_spawn(async move { cleanup_old_binaries() })
492            .detach();
493
494        mem::forget(project);
495    });
496    log::info!("gpui app is shut down. quitting.");
497    Ok(())
498}
499
500#[derive(Clone)]
501struct ServerPaths {
502    log_file: PathBuf,
503    pid_file: PathBuf,
504    stdin_socket: PathBuf,
505    stdout_socket: PathBuf,
506    stderr_socket: PathBuf,
507}
508
509impl ServerPaths {
510    fn new(identifier: &str) -> Result<Self> {
511        let server_dir = paths::remote_server_state_dir().join(identifier);
512        std::fs::create_dir_all(&server_dir)?;
513        std::fs::create_dir_all(&logs_dir())?;
514
515        let pid_file = server_dir.join("server.pid");
516        let stdin_socket = server_dir.join("stdin.sock");
517        let stdout_socket = server_dir.join("stdout.sock");
518        let stderr_socket = server_dir.join("stderr.sock");
519        let log_file = logs_dir().join(format!("server-{}.log", identifier));
520
521        Ok(Self {
522            pid_file,
523            stdin_socket,
524            stdout_socket,
525            stderr_socket,
526            log_file,
527        })
528    }
529}
530
531pub fn execute_proxy(identifier: String, is_reconnecting: bool) -> Result<()> {
532    init_logging_proxy();
533    init_panic_hook();
534
535    log::info!("starting proxy process. PID: {}", std::process::id());
536
537    let server_paths = ServerPaths::new(&identifier)?;
538
539    let server_pid = check_pid_file(&server_paths.pid_file)?;
540    let server_running = server_pid.is_some();
541    if is_reconnecting {
542        if !server_running {
543            log::error!("attempted to reconnect, but no server running");
544            anyhow::bail!(ProxyLaunchError::ServerNotRunning);
545        }
546    } else {
547        if let Some(pid) = server_pid {
548            log::info!(
549                "proxy found server already running with PID {}. Killing process and cleaning up files...",
550                pid
551            );
552            kill_running_server(pid, &server_paths)?;
553        }
554
555        spawn_server(&server_paths)?;
556    };
557
558    let stdin_task = smol::spawn(async move {
559        let stdin = Async::new(std::io::stdin())?;
560        let stream = smol::net::unix::UnixStream::connect(&server_paths.stdin_socket).await?;
561        handle_io(stdin, stream, "stdin").await
562    });
563
564    let stdout_task: smol::Task<Result<()>> = smol::spawn(async move {
565        let stdout = Async::new(std::io::stdout())?;
566        let stream = smol::net::unix::UnixStream::connect(&server_paths.stdout_socket).await?;
567        handle_io(stream, stdout, "stdout").await
568    });
569
570    let stderr_task: smol::Task<Result<()>> = smol::spawn(async move {
571        let mut stderr = Async::new(std::io::stderr())?;
572        let mut stream = smol::net::unix::UnixStream::connect(&server_paths.stderr_socket).await?;
573        let mut stderr_buffer = vec![0; 2048];
574        loop {
575            match stream
576                .read(&mut stderr_buffer)
577                .await
578                .context("reading stderr")?
579            {
580                0 => {
581                    let error =
582                        std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "stderr closed");
583                    Err(anyhow!(error))?;
584                }
585                n => {
586                    stderr.write_all(&mut stderr_buffer[..n]).await?;
587                    stderr.flush().await?;
588                }
589            }
590        }
591    });
592
593    if let Err(forwarding_result) = smol::block_on(async move {
594        futures::select! {
595            result = stdin_task.fuse() => result.context("stdin_task failed"),
596            result = stdout_task.fuse() => result.context("stdout_task failed"),
597            result = stderr_task.fuse() => result.context("stderr_task failed"),
598        }
599    }) {
600        log::error!(
601            "encountered error while forwarding messages: {:?}, terminating...",
602            forwarding_result
603        );
604        return Err(forwarding_result);
605    }
606
607    Ok(())
608}
609
610fn kill_running_server(pid: u32, paths: &ServerPaths) -> Result<()> {
611    log::info!("killing existing server with PID {}", pid);
612    std::process::Command::new("kill")
613        .arg(pid.to_string())
614        .output()
615        .context("failed to kill existing server")?;
616
617    for file in [
618        &paths.pid_file,
619        &paths.stdin_socket,
620        &paths.stdout_socket,
621        &paths.stderr_socket,
622    ] {
623        log::debug!("cleaning up file {:?} before starting new server", file);
624        std::fs::remove_file(file).ok();
625    }
626    Ok(())
627}
628
629fn spawn_server(paths: &ServerPaths) -> Result<()> {
630    if paths.stdin_socket.exists() {
631        std::fs::remove_file(&paths.stdin_socket)?;
632    }
633    if paths.stdout_socket.exists() {
634        std::fs::remove_file(&paths.stdout_socket)?;
635    }
636    if paths.stderr_socket.exists() {
637        std::fs::remove_file(&paths.stderr_socket)?;
638    }
639
640    let binary_name = std::env::current_exe()?;
641    let mut server_process = std::process::Command::new(binary_name);
642    server_process
643        .arg("run")
644        .arg("--log-file")
645        .arg(&paths.log_file)
646        .arg("--pid-file")
647        .arg(&paths.pid_file)
648        .arg("--stdin-socket")
649        .arg(&paths.stdin_socket)
650        .arg("--stdout-socket")
651        .arg(&paths.stdout_socket)
652        .arg("--stderr-socket")
653        .arg(&paths.stderr_socket);
654
655    let status = server_process
656        .status()
657        .context("failed to launch server process")?;
658    anyhow::ensure!(
659        status.success(),
660        "failed to launch and detach server process"
661    );
662
663    let mut total_time_waited = std::time::Duration::from_secs(0);
664    let wait_duration = std::time::Duration::from_millis(20);
665    while !paths.stdout_socket.exists()
666        || !paths.stdin_socket.exists()
667        || !paths.stderr_socket.exists()
668    {
669        log::debug!("waiting for server to be ready to accept connections...");
670        std::thread::sleep(wait_duration);
671        total_time_waited += wait_duration;
672    }
673
674    log::info!(
675        "server ready to accept connections. total time waited: {:?}",
676        total_time_waited
677    );
678
679    Ok(())
680}
681
682fn check_pid_file(path: &Path) -> Result<Option<u32>> {
683    let Some(pid) = std::fs::read_to_string(&path)
684        .ok()
685        .and_then(|contents| contents.parse::<u32>().ok())
686    else {
687        return Ok(None);
688    };
689
690    log::debug!("Checking if process with PID {} exists...", pid);
691    match std::process::Command::new("kill")
692        .arg("-0")
693        .arg(pid.to_string())
694        .output()
695    {
696        Ok(output) if output.status.success() => {
697            log::debug!(
698                "Process with PID {} exists. NOT spawning new server, but attaching to existing one.",
699                pid
700            );
701            Ok(Some(pid))
702        }
703        _ => {
704            log::debug!(
705                "Found PID file, but process with that PID does not exist. Removing PID file."
706            );
707            std::fs::remove_file(&path).context("Failed to remove PID file")?;
708            Ok(None)
709        }
710    }
711}
712
713fn write_pid_file(path: &Path) -> Result<()> {
714    if path.exists() {
715        std::fs::remove_file(path)?;
716    }
717    let pid = std::process::id().to_string();
718    log::debug!("writing PID {} to file {:?}", pid, path);
719    std::fs::write(path, pid).context("Failed to write PID file")
720}
721
722async fn handle_io<R, W>(mut reader: R, mut writer: W, socket_name: &str) -> Result<()>
723where
724    R: AsyncRead + Unpin,
725    W: AsyncWrite + Unpin,
726{
727    use remote::protocol::read_message_raw;
728
729    let mut buffer = Vec::new();
730    loop {
731        read_message_raw(&mut reader, &mut buffer)
732            .await
733            .with_context(|| format!("failed to read message from {}", socket_name))?;
734
735        write_size_prefixed_buffer(&mut writer, &mut buffer)
736            .await
737            .with_context(|| format!("failed to write message to {}", socket_name))?;
738
739        writer.flush().await?;
740
741        buffer.clear();
742    }
743}
744
745async fn write_size_prefixed_buffer<S: AsyncWrite + Unpin>(
746    stream: &mut S,
747    buffer: &mut Vec<u8>,
748) -> Result<()> {
749    let len = buffer.len() as u32;
750    stream.write_all(len.to_le_bytes().as_slice()).await?;
751    stream.write_all(buffer).await?;
752    Ok(())
753}
754
755fn initialize_settings(
756    session: Arc<ChannelClient>,
757    fs: Arc<dyn Fs>,
758    cx: &mut App,
759) -> watch::Receiver<Option<NodeBinaryOptions>> {
760    let user_settings_file_rx = watch_config_file(
761        &cx.background_executor(),
762        fs,
763        paths::settings_file().clone(),
764    );
765
766    handle_settings_file_changes(user_settings_file_rx, cx, {
767        let session = session.clone();
768        move |err, _cx| {
769            if let Some(e) = err {
770                log::info!("Server settings failed to change: {}", e);
771
772                session
773                    .send(proto::Toast {
774                        project_id: SSH_PROJECT_ID,
775                        notification_id: "server-settings-failed".to_string(),
776                        message: format!(
777                            "Error in settings on remote host {:?}: {}",
778                            paths::settings_file(),
779                            e
780                        ),
781                    })
782                    .log_err();
783            } else {
784                session
785                    .send(proto::HideToast {
786                        project_id: SSH_PROJECT_ID,
787                        notification_id: "server-settings-failed".to_string(),
788                    })
789                    .log_err();
790            }
791        }
792    });
793
794    let (mut tx, rx) = watch::channel(None);
795    cx.observe_global::<SettingsStore>(move |cx| {
796        let settings = &ProjectSettings::get_global(cx).node;
797        log::info!("Got new node settings: {:?}", settings);
798        let options = NodeBinaryOptions {
799            allow_path_lookup: !settings.ignore_system_version,
800            // TODO: Implement this setting
801            allow_binary_download: true,
802            use_paths: settings.path.as_ref().map(|node_path| {
803                let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
804                let npm_path = settings
805                    .npm_path
806                    .as_ref()
807                    .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
808                (
809                    node_path.clone(),
810                    npm_path.unwrap_or_else(|| {
811                        let base_path = PathBuf::new();
812                        node_path.parent().unwrap_or(&base_path).join("npm")
813                    }),
814                )
815            }),
816        };
817        tx.send(Some(options)).log_err();
818    })
819    .detach();
820
821    rx
822}
823
824pub fn handle_settings_file_changes(
825    mut server_settings_file: mpsc::UnboundedReceiver<String>,
826    cx: &mut App,
827    settings_changed: impl Fn(Option<anyhow::Error>, &mut App) + 'static,
828) {
829    let server_settings_content = cx
830        .background_executor()
831        .block(server_settings_file.next())
832        .unwrap();
833    SettingsStore::update_global(cx, |store, cx| {
834        store
835            .set_server_settings(&server_settings_content, cx)
836            .log_err();
837    });
838    cx.spawn(async move |cx| {
839        while let Some(server_settings_content) = server_settings_file.next().await {
840            let result = cx.update_global(|store: &mut SettingsStore, cx| {
841                let result = store.set_server_settings(&server_settings_content, cx);
842                if let Err(err) = &result {
843                    log::error!("Failed to load server settings: {err}");
844                }
845                settings_changed(result.err(), cx);
846                cx.refresh_windows();
847            });
848            if result.is_err() {
849                break; // App dropped
850            }
851        }
852    })
853    .detach();
854}
855
856fn read_proxy_settings(cx: &mut Context<HeadlessProject>) -> Option<Url> {
857    let proxy_str = ProxySettings::get_global(cx).proxy.to_owned();
858    let proxy_url = proxy_str
859        .as_ref()
860        .and_then(|input: &String| {
861            input
862                .parse::<Url>()
863                .inspect_err(|e| log::error!("Error parsing proxy settings: {}", e))
864                .ok()
865        })
866        .or_else(read_proxy_from_env);
867    proxy_url
868}
869
870fn daemonize() -> Result<ControlFlow<()>> {
871    match fork::fork().map_err(|e| anyhow!("failed to call fork with error code {e}"))? {
872        fork::Fork::Parent(_) => {
873            return Ok(ControlFlow::Break(()));
874        }
875        fork::Fork::Child => {}
876    }
877
878    // Once we've detached from the parent, we want to close stdout/stderr/stdin
879    // so that the outer SSH process is not attached to us in any way anymore.
880    unsafe { redirect_standard_streams() }?;
881
882    Ok(ControlFlow::Continue(()))
883}
884
885unsafe fn redirect_standard_streams() -> Result<()> {
886    let devnull_fd = unsafe { libc::open(b"/dev/null\0" as *const [u8; 10] as _, libc::O_RDWR) };
887    anyhow::ensure!(devnull_fd != -1, "failed to open /dev/null");
888
889    let process_stdio = |name, fd| {
890        let reopened_fd = unsafe { libc::dup2(devnull_fd, fd) };
891        anyhow::ensure!(
892            reopened_fd != -1,
893            format!("failed to redirect {} to /dev/null", name)
894        );
895        Ok(())
896    };
897
898    process_stdio("stdin", libc::STDIN_FILENO)?;
899    process_stdio("stdout", libc::STDOUT_FILENO)?;
900    process_stdio("stderr", libc::STDERR_FILENO)?;
901
902    anyhow::ensure!(
903        unsafe { libc::close(devnull_fd) != -1 },
904        "failed to close /dev/null fd after redirecting"
905    );
906
907    Ok(())
908}
909
910fn cleanup_old_binaries() -> Result<()> {
911    let server_dir = paths::remote_server_dir_relative();
912    let release_channel = release_channel::RELEASE_CHANNEL.dev_name();
913    let prefix = format!("zed-remote-server-{}-", release_channel);
914
915    for entry in std::fs::read_dir(server_dir)? {
916        let path = entry?.path();
917
918        if let Some(file_name) = path.file_name() {
919            if let Some(version) = file_name.to_string_lossy().strip_prefix(&prefix) {
920                if !is_new_version(version) && !is_file_in_use(file_name) {
921                    log::info!("removing old remote server binary: {:?}", path);
922                    std::fs::remove_file(&path)?;
923                }
924            }
925        }
926    }
927
928    Ok(())
929}
930
931fn is_new_version(version: &str) -> bool {
932    SemanticVersion::from_str(version)
933        .ok()
934        .zip(SemanticVersion::from_str(env!("ZED_PKG_VERSION")).ok())
935        .is_some_and(|(version, current_version)| version >= current_version)
936}
937
938fn is_file_in_use(file_name: &OsStr) -> bool {
939    let info =
940        sysinfo::System::new_with_specifics(sysinfo::RefreshKind::new().with_processes(
941            sysinfo::ProcessRefreshKind::new().with_exe(sysinfo::UpdateKind::Always),
942        ));
943
944    for process in info.processes().values() {
945        if process
946            .exe()
947            .is_some_and(|exe| exe.file_name().is_some_and(|name| name == file_name))
948        {
949            return true;
950        }
951    }
952
953    false
954}