unix.rs

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