server.rs

   1mod headless_project;
   2
   3#[cfg(test)]
   4mod remote_editing_tests;
   5
   6#[cfg(windows)]
   7pub mod windows;
   8
   9pub use headless_project::{HeadlessAppState, HeadlessProject};
  10
  11use anyhow::{Context as _, Result, anyhow};
  12use clap::Subcommand;
  13use client::ProxySettings;
  14use collections::HashMap;
  15use extension::ExtensionHostProxy;
  16use fs::{Fs, RealFs};
  17use futures::{
  18    AsyncRead, AsyncWrite, AsyncWriteExt, FutureExt, SinkExt,
  19    channel::{mpsc, oneshot},
  20    select, select_biased,
  21};
  22use git::GitHostingProviderRegistry;
  23use gpui::{App, AppContext as _, Context, Entity, UpdateGlobal as _};
  24use gpui_tokio::Tokio;
  25use http_client::{Url, read_proxy_from_env};
  26use language::LanguageRegistry;
  27use net::async_net::{UnixListener, UnixStream};
  28use node_runtime::{NodeBinaryOptions, NodeRuntime};
  29use paths::logs_dir;
  30use project::{project_settings::ProjectSettings, trusted_worktrees};
  31use proto::CrashReport;
  32use release_channel::{AppCommitSha, AppVersion, RELEASE_CHANNEL, ReleaseChannel};
  33use remote::{
  34    RemoteClient,
  35    json_log::LogRecord,
  36    protocol::{read_message, write_message},
  37    proxy::ProxyLaunchError,
  38};
  39use reqwest_client::ReqwestClient;
  40use rpc::proto::{self, Envelope, REMOTE_SERVER_PROJECT_ID};
  41use rpc::{AnyProtoClient, TypedEnvelope};
  42use settings::{Settings, SettingsStore, watch_config_file};
  43use smol::{
  44    channel::{Receiver, Sender},
  45    io::AsyncReadExt,
  46    stream::StreamExt as _,
  47};
  48use std::{
  49    env,
  50    ffi::OsStr,
  51    fs::File,
  52    io::Write,
  53    mem,
  54    path::{Path, PathBuf},
  55    str::FromStr,
  56    sync::{Arc, LazyLock},
  57};
  58use thiserror::Error;
  59use util::{ResultExt, command::new_smol_command};
  60
  61#[derive(Subcommand)]
  62pub enum Commands {
  63    Run {
  64        #[arg(long)]
  65        log_file: PathBuf,
  66        #[arg(long)]
  67        pid_file: PathBuf,
  68        #[arg(long)]
  69        stdin_socket: PathBuf,
  70        #[arg(long)]
  71        stdout_socket: PathBuf,
  72        #[arg(long)]
  73        stderr_socket: PathBuf,
  74    },
  75    Proxy {
  76        #[arg(long)]
  77        reconnect: bool,
  78        #[arg(long)]
  79        identifier: String,
  80    },
  81    Version,
  82}
  83
  84pub fn run(command: Commands) -> anyhow::Result<()> {
  85    use anyhow::Context;
  86    use release_channel::{RELEASE_CHANNEL, ReleaseChannel};
  87
  88    match command {
  89        Commands::Run {
  90            log_file,
  91            pid_file,
  92            stdin_socket,
  93            stdout_socket,
  94            stderr_socket,
  95        } => execute_run(
  96            log_file,
  97            pid_file,
  98            stdin_socket,
  99            stdout_socket,
 100            stderr_socket,
 101        ),
 102        Commands::Proxy {
 103            identifier,
 104            reconnect,
 105        } => execute_proxy(identifier, reconnect).context("running proxy on the remote server"),
 106        Commands::Version => {
 107            let release_channel = *RELEASE_CHANNEL;
 108            match release_channel {
 109                ReleaseChannel::Stable | ReleaseChannel::Preview => {
 110                    println!("{}", env!("ZED_PKG_VERSION"))
 111                }
 112                ReleaseChannel::Nightly | ReleaseChannel::Dev => {
 113                    let commit_sha =
 114                        option_env!("ZED_COMMIT_SHA").unwrap_or(release_channel.dev_name());
 115                    let build_id = option_env!("ZED_BUILD_ID");
 116                    if let Some(build_id) = build_id {
 117                        println!("{}+{}", build_id, commit_sha)
 118                    } else {
 119                        println!("{commit_sha}");
 120                    }
 121                }
 122            };
 123            Ok(())
 124        }
 125    }
 126}
 127
 128pub static VERSION: LazyLock<String> = LazyLock::new(|| match *RELEASE_CHANNEL {
 129    ReleaseChannel::Stable | ReleaseChannel::Preview => env!("ZED_PKG_VERSION").to_owned(),
 130    ReleaseChannel::Nightly | ReleaseChannel::Dev => {
 131        let commit_sha = option_env!("ZED_COMMIT_SHA").unwrap_or("missing-zed-commit-sha");
 132        let build_identifier = option_env!("ZED_BUILD_ID");
 133        if let Some(build_id) = build_identifier {
 134            format!("{build_id}+{commit_sha}")
 135        } else {
 136            commit_sha.to_owned()
 137        }
 138    }
 139});
 140
 141fn init_logging_proxy() {
 142    env_logger::builder()
 143        .format(|buf, record| {
 144            let mut log_record = LogRecord::new(record);
 145            log_record.message =
 146                std::borrow::Cow::Owned(format!("(remote proxy) {}", log_record.message));
 147            serde_json::to_writer(&mut *buf, &log_record)?;
 148            buf.write_all(b"\n")?;
 149            Ok(())
 150        })
 151        .init();
 152}
 153
 154fn init_logging_server(log_file_path: &Path) -> Result<Receiver<Vec<u8>>> {
 155    struct MultiWrite {
 156        file: File,
 157        channel: Sender<Vec<u8>>,
 158        buffer: Vec<u8>,
 159    }
 160
 161    impl Write for MultiWrite {
 162        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
 163            let written = self.file.write(buf)?;
 164            self.buffer.extend_from_slice(&buf[..written]);
 165            Ok(written)
 166        }
 167
 168        fn flush(&mut self) -> std::io::Result<()> {
 169            self.channel
 170                .send_blocking(self.buffer.clone())
 171                .map_err(std::io::Error::other)?;
 172            self.buffer.clear();
 173            self.file.flush()
 174        }
 175    }
 176
 177    let log_file = std::fs::OpenOptions::new()
 178        .create(true)
 179        .append(true)
 180        .open(log_file_path)
 181        .context("Failed to open log file in append mode")?;
 182
 183    let (tx, rx) = smol::channel::unbounded();
 184
 185    let target = Box::new(MultiWrite {
 186        file: log_file,
 187        channel: tx,
 188        buffer: Vec::new(),
 189    });
 190
 191    let old_hook = std::panic::take_hook();
 192    std::panic::set_hook(Box::new(move |info| {
 193        let backtrace = std::backtrace::Backtrace::force_capture();
 194        let message = info.payload_as_str().unwrap_or("Box<Any>").to_owned();
 195        let location = info
 196            .location()
 197            .map_or_else(|| "<unknown>".to_owned(), |location| location.to_string());
 198        let current_thread = std::thread::current();
 199        let thread_name = current_thread.name().unwrap_or("<unnamed>");
 200
 201        let msg = format!("thread '{thread_name}' panicked at {location}:\n{message}\n{backtrace}");
 202        // NOTE: This log never reaches the client, as the communication is handled on a main thread task
 203        // which will never run once we panic.
 204        log::error!("{msg}");
 205        old_hook(info);
 206    }));
 207    env_logger::Builder::new()
 208        .filter_level(log::LevelFilter::Info)
 209        .parse_default_env()
 210        .target(env_logger::Target::Pipe(target))
 211        .format(|buf, record| {
 212            let mut log_record = LogRecord::new(record);
 213            log_record.message =
 214                std::borrow::Cow::Owned(format!("(remote server) {}", log_record.message));
 215            serde_json::to_writer(&mut *buf, &log_record)?;
 216            buf.write_all(b"\n")?;
 217            Ok(())
 218        })
 219        .init();
 220
 221    Ok(rx)
 222}
 223
 224fn handle_crash_files_requests(project: &Entity<HeadlessProject>, client: &AnyProtoClient) {
 225    client.add_request_handler(
 226        project.downgrade(),
 227        |_, _: TypedEnvelope<proto::GetCrashFiles>, _cx| async move {
 228            let mut legacy_panics = Vec::new();
 229            let mut crashes = Vec::new();
 230            let mut children = smol::fs::read_dir(paths::logs_dir()).await?;
 231            while let Some(child) = children.next().await {
 232                let child = child?;
 233                let child_path = child.path();
 234
 235                let extension = child_path.extension();
 236                if extension == Some(OsStr::new("panic")) {
 237                    let filename = if let Some(filename) = child_path.file_name() {
 238                        filename.to_string_lossy()
 239                    } else {
 240                        continue;
 241                    };
 242
 243                    if !filename.starts_with("zed") {
 244                        continue;
 245                    }
 246
 247                    let file_contents = smol::fs::read_to_string(&child_path)
 248                        .await
 249                        .context("error reading panic file")?;
 250
 251                    legacy_panics.push(file_contents);
 252                    smol::fs::remove_file(&child_path)
 253                        .await
 254                        .context("error removing panic")
 255                        .log_err();
 256                } else if extension == Some(OsStr::new("dmp")) {
 257                    let mut json_path = child_path.clone();
 258                    json_path.set_extension("json");
 259                    if let Ok(json_content) = smol::fs::read_to_string(&json_path).await {
 260                        crashes.push(CrashReport {
 261                            metadata: json_content,
 262                            minidump_contents: smol::fs::read(&child_path).await?,
 263                        });
 264                        smol::fs::remove_file(&child_path).await.log_err();
 265                        smol::fs::remove_file(&json_path).await.log_err();
 266                    } else {
 267                        log::error!("Couldn't find json metadata for crash: {child_path:?}");
 268                    }
 269                }
 270            }
 271
 272            anyhow::Ok(proto::GetCrashFilesResponse { crashes })
 273        },
 274    );
 275}
 276
 277struct ServerListeners {
 278    stdin: UnixListener,
 279    stdout: UnixListener,
 280    stderr: UnixListener,
 281}
 282
 283impl ServerListeners {
 284    pub fn new(stdin_path: PathBuf, stdout_path: PathBuf, stderr_path: PathBuf) -> Result<Self> {
 285        Ok(Self {
 286            stdin: UnixListener::bind(stdin_path).context("failed to bind stdin socket")?,
 287            stdout: UnixListener::bind(stdout_path).context("failed to bind stdout socket")?,
 288            stderr: UnixListener::bind(stderr_path).context("failed to bind stderr socket")?,
 289        })
 290    }
 291}
 292
 293fn start_server(
 294    listeners: ServerListeners,
 295    log_rx: Receiver<Vec<u8>>,
 296    cx: &mut App,
 297    is_wsl_interop: bool,
 298) -> AnyProtoClient {
 299    // This is the server idle timeout. If no connection comes in this timeout, the server will shut down.
 300    const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
 301
 302    let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 303    let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded::<Envelope>();
 304    let (app_quit_tx, mut app_quit_rx) = mpsc::unbounded::<()>();
 305
 306    cx.on_app_quit(move |_| {
 307        let mut app_quit_tx = app_quit_tx.clone();
 308        async move {
 309            log::info!("app quitting. sending signal to server main loop");
 310            app_quit_tx.send(()).await.ok();
 311        }
 312    })
 313    .detach();
 314
 315    cx.spawn(async move |cx| {
 316        loop {
 317            let streams = futures::future::join3(
 318                listeners.stdin.accept(),
 319                listeners.stdout.accept(),
 320                listeners.stderr.accept(),
 321            );
 322
 323            log::info!("accepting new connections");
 324            let result = select! {
 325                streams = streams.fuse() => {
 326                    let (Ok((stdin_stream, _)), Ok((stdout_stream, _)), Ok((stderr_stream, _))) = streams else {
 327                        log::error!("failed to accept new connections");
 328                        break;
 329                    };
 330                    log::info!("accepted new connections");
 331                    anyhow::Ok((stdin_stream, stdout_stream, stderr_stream))
 332                }
 333                _ = futures::FutureExt::fuse(cx.background_executor().timer(IDLE_TIMEOUT)) => {
 334                    log::warn!("timed out waiting for new connections after {:?}. exiting.", IDLE_TIMEOUT);
 335                    cx.update(|cx| {
 336                        // TODO: This is a hack, because in a headless project, shutdown isn't executed
 337                        // when calling quit, but it should be.
 338                        cx.shutdown();
 339                        cx.quit();
 340                    });
 341                    break;
 342                }
 343                _ = app_quit_rx.next().fuse() => {
 344                    log::info!("app quit requested");
 345                    break;
 346                }
 347            };
 348
 349            let Ok((mut stdin_stream, mut stdout_stream, mut stderr_stream)) = result else {
 350                break;
 351            };
 352
 353            let mut input_buffer = Vec::new();
 354            let mut output_buffer = Vec::new();
 355
 356            let (mut stdin_msg_tx, mut stdin_msg_rx) = mpsc::unbounded::<Envelope>();
 357            cx.background_spawn(async move {
 358                while let Ok(msg) = read_message(&mut stdin_stream, &mut input_buffer).await {
 359                    if (stdin_msg_tx.send(msg).await).is_err() {
 360                        break;
 361                    }
 362                }
 363            }).detach();
 364
 365            loop {
 366
 367                select_biased! {
 368                    _ = app_quit_rx.next().fuse() => {
 369                        return anyhow::Ok(());
 370                    }
 371
 372                    stdin_message = stdin_msg_rx.next().fuse() => {
 373                        let Some(message) = stdin_message else {
 374                            log::warn!("error reading message on stdin, dropping connection.");
 375                            break;
 376                        };
 377                        if let Err(error) = incoming_tx.unbounded_send(message) {
 378                            log::error!("failed to send message to application: {error:?}. exiting.");
 379                            return Err(anyhow!(error));
 380                        }
 381                    }
 382
 383                    outgoing_message  = outgoing_rx.next().fuse() => {
 384                        let Some(message) = outgoing_message else {
 385                            log::error!("stdout handler, no message");
 386                            break;
 387                        };
 388
 389                        if let Err(error) =
 390                            write_message(&mut stdout_stream, &mut output_buffer, message).await
 391                        {
 392                            log::error!("failed to write stdout message: {:?}", error);
 393                            break;
 394                        }
 395                        if let Err(error) = stdout_stream.flush().await {
 396                            log::error!("failed to flush stdout message: {:?}", error);
 397                            break;
 398                        }
 399                    }
 400
 401                    log_message = log_rx.recv().fuse() => {
 402                        if let Ok(log_message) = log_message {
 403                            if let Err(error) = stderr_stream.write_all(&log_message).await {
 404                                log::error!("failed to write log message to stderr: {:?}", error);
 405                                break;
 406                            }
 407                            if let Err(error) = stderr_stream.flush().await {
 408                                log::error!("failed to flush stderr stream: {:?}", error);
 409                                break;
 410                            }
 411                        }
 412                    }
 413                }
 414            }
 415        }
 416        anyhow::Ok(())
 417    })
 418    .detach();
 419
 420    RemoteClient::proto_client_from_channels(incoming_rx, outgoing_tx, cx, "server", is_wsl_interop)
 421}
 422
 423fn init_paths() -> anyhow::Result<()> {
 424    for path in [
 425        paths::config_dir(),
 426        paths::extensions_dir(),
 427        paths::languages_dir(),
 428        paths::logs_dir(),
 429        paths::temp_dir(),
 430        paths::hang_traces_dir(),
 431        paths::remote_extensions_dir(),
 432        paths::remote_extensions_uploads_dir(),
 433    ]
 434    .iter()
 435    {
 436        std::fs::create_dir_all(path).with_context(|| format!("creating directory {path:?}"))?;
 437    }
 438    Ok(())
 439}
 440
 441pub fn execute_run(
 442    log_file: PathBuf,
 443    pid_file: PathBuf,
 444    stdin_socket: PathBuf,
 445    stdout_socket: PathBuf,
 446    stderr_socket: PathBuf,
 447) -> Result<()> {
 448    init_paths()?;
 449
 450    let app = gpui::Application::headless();
 451    let pid = std::process::id();
 452    let id = pid.to_string();
 453    app.background_executor()
 454        .spawn(crashes::init(crashes::InitCrashHandler {
 455            session_id: id,
 456            zed_version: VERSION.to_owned(),
 457            binary: "zed-remote-server".to_string(),
 458            release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
 459            commit_sha: option_env!("ZED_COMMIT_SHA").unwrap_or("no_sha").to_owned(),
 460        }))
 461        .detach();
 462    let log_rx = init_logging_server(&log_file)?;
 463    log::info!(
 464        "starting up with PID {}:\npid_file: {:?}, log_file: {:?}, stdin_socket: {:?}, stdout_socket: {:?}, stderr_socket: {:?}",
 465        pid,
 466        pid_file,
 467        log_file,
 468        stdin_socket,
 469        stdout_socket,
 470        stderr_socket
 471    );
 472
 473    write_pid_file(&pid_file, pid)
 474        .with_context(|| format!("failed to write pid file: {:?}", &pid_file))?;
 475
 476    let listeners = ServerListeners::new(stdin_socket, stdout_socket, stderr_socket)?;
 477
 478    rayon::ThreadPoolBuilder::new()
 479        .num_threads(std::thread::available_parallelism().map_or(1, |n| n.get().div_ceil(2)))
 480        .stack_size(10 * 1024 * 1024)
 481        .thread_name(|ix| format!("RayonWorker{}", ix))
 482        .build_global()
 483        .unwrap();
 484
 485    #[cfg(unix)]
 486    let shell_env_loaded_rx = {
 487        let (shell_env_loaded_tx, shell_env_loaded_rx) = oneshot::channel();
 488        app.background_executor()
 489            .spawn(async {
 490                util::load_login_shell_environment().await.log_err();
 491                shell_env_loaded_tx.send(()).ok();
 492            })
 493            .detach();
 494        Some(shell_env_loaded_rx)
 495    };
 496    #[cfg(windows)]
 497    let shell_env_loaded_rx: Option<oneshot::Receiver<()>> = None;
 498
 499    let git_hosting_provider_registry = Arc::new(GitHostingProviderRegistry::new());
 500    let run = move |cx: &mut _| {
 501        settings::init(cx);
 502        let app_commit_sha = option_env!("ZED_COMMIT_SHA").map(|s| AppCommitSha::new(s.to_owned()));
 503        let app_version = AppVersion::load(
 504            env!("ZED_PKG_VERSION"),
 505            option_env!("ZED_BUILD_ID"),
 506            app_commit_sha,
 507        );
 508        release_channel::init(app_version, cx);
 509        gpui_tokio::init(cx);
 510
 511        HeadlessProject::init(cx);
 512
 513        let is_wsl_interop = if cfg!(target_os = "linux") {
 514            // See: https://learn.microsoft.com/en-us/windows/wsl/filesystems#disable-interoperability
 515            matches!(std::fs::read_to_string("/proc/sys/fs/binfmt_misc/WSLInterop"), Ok(s) if s.contains("enabled"))
 516        } else {
 517            false
 518        };
 519
 520        log::info!("gpui app started, initializing server");
 521        let session = start_server(listeners, log_rx, cx, is_wsl_interop);
 522        trusted_worktrees::init(HashMap::default(), cx);
 523
 524        GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
 525        git_hosting_providers::init(cx);
 526        dap_adapters::init(cx);
 527
 528        extension::init(cx);
 529        let extension_host_proxy = ExtensionHostProxy::global(cx);
 530
 531        json_schema_store::init(cx);
 532
 533        let project = cx.new(|cx| {
 534            let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
 535            let node_settings_rx = initialize_settings(session.clone(), fs.clone(), cx);
 536
 537            let proxy_url = read_proxy_settings(cx);
 538
 539            let http_client = {
 540                let _guard = Tokio::handle(cx).enter();
 541                Arc::new(
 542                    ReqwestClient::proxy_and_user_agent(
 543                        proxy_url,
 544                        &format!(
 545                            "Zed-Server/{} ({}; {})",
 546                            env!("CARGO_PKG_VERSION"),
 547                            std::env::consts::OS,
 548                            std::env::consts::ARCH
 549                        ),
 550                    )
 551                    .expect("Could not start HTTP client"),
 552                )
 553            };
 554
 555            let node_runtime =
 556                NodeRuntime::new(http_client.clone(), shell_env_loaded_rx, node_settings_rx);
 557
 558            let mut languages = LanguageRegistry::new(cx.background_executor().clone());
 559            languages.set_language_server_download_dir(paths::languages_dir().clone());
 560            let languages = Arc::new(languages);
 561
 562            HeadlessProject::new(
 563                HeadlessAppState {
 564                    session: session.clone(),
 565                    fs,
 566                    http_client,
 567                    node_runtime,
 568                    languages,
 569                    extension_host_proxy,
 570                },
 571                true,
 572                cx,
 573            )
 574        });
 575
 576        handle_crash_files_requests(&project, &session);
 577
 578        cx.background_spawn(async move { cleanup_old_binaries() })
 579            .detach();
 580
 581        mem::forget(project);
 582    };
 583    // We do not reuse any of the state after unwinding, so we don't run risk of observing broken invariants.
 584    let app = std::panic::AssertUnwindSafe(app);
 585    let run = std::panic::AssertUnwindSafe(run);
 586    let res = std::panic::catch_unwind(move || { app }.0.run({ run }.0));
 587    if let Err(_) = res {
 588        log::error!("app panicked. quitting.");
 589        Err(anyhow::anyhow!("panicked"))
 590    } else {
 591        log::info!("gpui app is shut down. quitting.");
 592        Ok(())
 593    }
 594}
 595
 596#[derive(Debug, Error)]
 597pub enum ServerPathError {
 598    #[error("Failed to create server_dir `{path}`")]
 599    CreateServerDir {
 600        #[source]
 601        source: std::io::Error,
 602        path: PathBuf,
 603    },
 604    #[error("Failed to create logs_dir `{path}`")]
 605    CreateLogsDir {
 606        #[source]
 607        source: std::io::Error,
 608        path: PathBuf,
 609    },
 610}
 611
 612#[derive(Clone, Debug)]
 613struct ServerPaths {
 614    log_file: PathBuf,
 615    pid_file: PathBuf,
 616    stdin_socket: PathBuf,
 617    stdout_socket: PathBuf,
 618    stderr_socket: PathBuf,
 619}
 620
 621impl ServerPaths {
 622    fn new(identifier: &str) -> Result<Self, ServerPathError> {
 623        let server_dir = paths::remote_server_state_dir().join(identifier);
 624        std::fs::create_dir_all(&server_dir).map_err(|source| {
 625            ServerPathError::CreateServerDir {
 626                source,
 627                path: server_dir.clone(),
 628            }
 629        })?;
 630        let log_dir = logs_dir();
 631        std::fs::create_dir_all(log_dir).map_err(|source| ServerPathError::CreateLogsDir {
 632            source,
 633            path: log_dir.clone(),
 634        })?;
 635
 636        let pid_file = server_dir.join("server.pid");
 637        let stdin_socket = server_dir.join("stdin.sock");
 638        let stdout_socket = server_dir.join("stdout.sock");
 639        let stderr_socket = server_dir.join("stderr.sock");
 640        let log_file = logs_dir().join(format!("server-{}.log", identifier));
 641
 642        Ok(Self {
 643            pid_file,
 644            stdin_socket,
 645            stdout_socket,
 646            stderr_socket,
 647            log_file,
 648        })
 649    }
 650}
 651
 652#[derive(Debug, Error)]
 653pub enum ExecuteProxyError {
 654    #[error("Failed to init server paths: {0:#}")]
 655    ServerPath(#[from] ServerPathError),
 656
 657    #[error(transparent)]
 658    ServerNotRunning(#[from] ProxyLaunchError),
 659
 660    #[error("Failed to check PidFile '{path}': {source:#}")]
 661    CheckPidFile {
 662        #[source]
 663        source: CheckPidError,
 664        path: PathBuf,
 665    },
 666
 667    #[error("Failed to kill existing server with pid '{pid}'")]
 668    KillRunningServer { pid: u32 },
 669
 670    #[error("failed to spawn server")]
 671    SpawnServer(#[source] SpawnServerError),
 672
 673    #[error("stdin_task failed: {0:#}")]
 674    StdinTask(#[source] anyhow::Error),
 675    #[error("stdout_task failed: {0:#}")]
 676    StdoutTask(#[source] anyhow::Error),
 677    #[error("stderr_task failed: {0:#}")]
 678    StderrTask(#[source] anyhow::Error),
 679}
 680
 681impl ExecuteProxyError {
 682    pub fn to_exit_code(&self) -> i32 {
 683        match self {
 684            ExecuteProxyError::ServerNotRunning(proxy_launch_error) => {
 685                proxy_launch_error.to_exit_code()
 686            }
 687            _ => 1,
 688        }
 689    }
 690}
 691
 692pub(crate) fn execute_proxy(
 693    identifier: String,
 694    is_reconnecting: bool,
 695) -> Result<(), ExecuteProxyError> {
 696    init_logging_proxy();
 697
 698    let server_paths = ServerPaths::new(&identifier)?;
 699
 700    let id = std::process::id().to_string();
 701    smol::spawn(crashes::init(crashes::InitCrashHandler {
 702        session_id: id,
 703        zed_version: VERSION.to_owned(),
 704        binary: "zed-remote-server".to_string(),
 705        release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
 706        commit_sha: option_env!("ZED_COMMIT_SHA").unwrap_or("no_sha").to_owned(),
 707    }))
 708    .detach();
 709
 710    log::info!("starting proxy process. PID: {}", std::process::id());
 711    let server_pid = {
 712        let server_pid = check_pid_file(&server_paths.pid_file).map_err(|source| {
 713            ExecuteProxyError::CheckPidFile {
 714                source,
 715                path: server_paths.pid_file.clone(),
 716            }
 717        })?;
 718        if is_reconnecting {
 719            match server_pid {
 720                None => {
 721                    log::error!("attempted to reconnect, but no server running");
 722                    return Err(ExecuteProxyError::ServerNotRunning(
 723                        ProxyLaunchError::ServerNotRunning,
 724                    ));
 725                }
 726                Some(server_pid) => server_pid,
 727            }
 728        } else {
 729            if let Some(pid) = server_pid {
 730                log::info!(
 731                    "proxy found server already running with PID {}. Killing process and cleaning up files...",
 732                    pid
 733                );
 734                kill_running_server(pid, &server_paths)?;
 735            }
 736            smol::block_on(spawn_server(&server_paths)).map_err(ExecuteProxyError::SpawnServer)?;
 737            std::fs::read_to_string(&server_paths.pid_file)
 738                .and_then(|contents| {
 739                    contents.parse::<u32>().map_err(|_| {
 740                        std::io::Error::new(
 741                            std::io::ErrorKind::InvalidData,
 742                            "Invalid PID file contents",
 743                        )
 744                    })
 745                })
 746                .map_err(SpawnServerError::ProcessStatus)
 747                .map_err(ExecuteProxyError::SpawnServer)?
 748        }
 749    };
 750
 751    let stdin_task = smol::spawn(async move {
 752        let stdin = smol::Unblock::new(std::io::stdin());
 753        let stream = UnixStream::connect(&server_paths.stdin_socket)
 754            .await
 755            .with_context(|| {
 756                format!(
 757                    "Failed to connect to stdin socket {}",
 758                    server_paths.stdin_socket.display()
 759                )
 760            })?;
 761        handle_io(stdin, stream, "stdin").await
 762    });
 763
 764    let stdout_task: smol::Task<Result<()>> = smol::spawn(async move {
 765        let stdout = smol::Unblock::new(std::io::stdout());
 766        let stream = UnixStream::connect(&server_paths.stdout_socket)
 767            .await
 768            .with_context(|| {
 769                format!(
 770                    "Failed to connect to stdout socket {}",
 771                    server_paths.stdout_socket.display()
 772                )
 773            })?;
 774        handle_io(stream, stdout, "stdout").await
 775    });
 776
 777    let stderr_task: smol::Task<Result<()>> = smol::spawn(async move {
 778        let mut stderr = smol::Unblock::new(std::io::stderr());
 779        let mut stream = UnixStream::connect(&server_paths.stderr_socket)
 780            .await
 781            .with_context(|| {
 782                format!(
 783                    "Failed to connect to stderr socket {}",
 784                    server_paths.stderr_socket.display()
 785                )
 786            })?;
 787        let mut stderr_buffer = vec![0; 2048];
 788        loop {
 789            match stream
 790                .read(&mut stderr_buffer)
 791                .await
 792                .context("reading stderr")?
 793            {
 794                0 => {
 795                    let error =
 796                        std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "stderr closed");
 797                    Err(anyhow!(error))?;
 798                }
 799                n => {
 800                    stderr.write_all(&stderr_buffer[..n]).await?;
 801                    stderr.flush().await?;
 802                }
 803            }
 804        }
 805    });
 806
 807    if let Err(forwarding_result) = smol::block_on(async move {
 808        futures::select! {
 809            result = stdin_task.fuse() => result.map_err(ExecuteProxyError::StdinTask),
 810            result = stdout_task.fuse() => result.map_err(ExecuteProxyError::StdoutTask),
 811            result = stderr_task.fuse() => result.map_err(ExecuteProxyError::StderrTask),
 812        }
 813    }) {
 814        log::error!("encountered error while forwarding messages: {forwarding_result:#}",);
 815        if !matches!(smol::block_on(check_server_running(server_pid)), Ok(true)) {
 816            log::error!("server exited unexpectedly");
 817            return Err(ExecuteProxyError::ServerNotRunning(
 818                ProxyLaunchError::ServerNotRunning,
 819            ));
 820        }
 821        return Err(forwarding_result);
 822    }
 823
 824    Ok(())
 825}
 826
 827fn kill_running_server(pid: u32, paths: &ServerPaths) -> Result<(), ExecuteProxyError> {
 828    log::info!("killing existing server with PID {}", pid);
 829    let system = sysinfo::System::new_with_specifics(
 830        sysinfo::RefreshKind::nothing().with_processes(sysinfo::ProcessRefreshKind::nothing()),
 831    );
 832
 833    if let Some(process) = system.process(sysinfo::Pid::from_u32(pid)) {
 834        let killed = process.kill();
 835        if !killed {
 836            return Err(ExecuteProxyError::KillRunningServer { pid });
 837        }
 838    }
 839
 840    for file in [
 841        &paths.pid_file,
 842        &paths.stdin_socket,
 843        &paths.stdout_socket,
 844        &paths.stderr_socket,
 845    ] {
 846        log::debug!("cleaning up file {:?} before starting new server", file);
 847        std::fs::remove_file(file).ok();
 848    }
 849
 850    Ok(())
 851}
 852
 853#[derive(Debug, Error)]
 854pub enum SpawnServerError {
 855    #[error("failed to remove stdin socket")]
 856    RemoveStdinSocket(#[source] std::io::Error),
 857
 858    #[error("failed to remove stdout socket")]
 859    RemoveStdoutSocket(#[source] std::io::Error),
 860
 861    #[error("failed to remove stderr socket")]
 862    RemoveStderrSocket(#[source] std::io::Error),
 863
 864    #[error("failed to get current_exe")]
 865    CurrentExe(#[source] std::io::Error),
 866
 867    #[error("failed to launch server process")]
 868    ProcessStatus(#[source] std::io::Error),
 869
 870    #[error("failed to wait for server to be ready to accept connections")]
 871    Timeout,
 872}
 873
 874async fn spawn_server(paths: &ServerPaths) -> Result<(), SpawnServerError> {
 875    log::info!("spawning server process",);
 876    if paths.stdin_socket.exists() {
 877        std::fs::remove_file(&paths.stdin_socket).map_err(SpawnServerError::RemoveStdinSocket)?;
 878    }
 879    if paths.stdout_socket.exists() {
 880        std::fs::remove_file(&paths.stdout_socket).map_err(SpawnServerError::RemoveStdoutSocket)?;
 881    }
 882    if paths.stderr_socket.exists() {
 883        std::fs::remove_file(&paths.stderr_socket).map_err(SpawnServerError::RemoveStderrSocket)?;
 884    }
 885
 886    let binary_name = std::env::current_exe().map_err(SpawnServerError::CurrentExe)?;
 887
 888    #[cfg(windows)]
 889    {
 890        spawn_server_windows(&binary_name, paths)?;
 891    }
 892
 893    #[cfg(not(windows))]
 894    {
 895        spawn_server_normal(&binary_name, paths)?;
 896    }
 897
 898    let mut total_time_waited = std::time::Duration::from_secs(0);
 899    let wait_duration = std::time::Duration::from_millis(20);
 900    while !paths.stdout_socket.exists()
 901        || !paths.stdin_socket.exists()
 902        || !paths.stderr_socket.exists()
 903    {
 904        log::debug!("waiting for server to be ready to accept connections...");
 905        std::thread::sleep(wait_duration);
 906        total_time_waited += wait_duration;
 907        if total_time_waited > std::time::Duration::from_secs(10) {
 908            return Err(SpawnServerError::Timeout);
 909        }
 910    }
 911
 912    log::info!(
 913        "server ready to accept connections. total time waited: {:?}",
 914        total_time_waited
 915    );
 916
 917    Ok(())
 918}
 919
 920#[cfg(windows)]
 921fn spawn_server_windows(binary_name: &Path, paths: &ServerPaths) -> Result<(), SpawnServerError> {
 922    let binary_path = binary_name.to_string_lossy().to_string();
 923    let parameters = format!(
 924        "run --log-file \"{}\" --pid-file \"{}\" --stdin-socket \"{}\" --stdout-socket \"{}\" --stderr-socket \"{}\"",
 925        paths.log_file.to_string_lossy(),
 926        paths.pid_file.to_string_lossy(),
 927        paths.stdin_socket.to_string_lossy(),
 928        paths.stdout_socket.to_string_lossy(),
 929        paths.stderr_socket.to_string_lossy()
 930    );
 931
 932    let directory = binary_name
 933        .parent()
 934        .map(|p| p.to_string_lossy().to_string())
 935        .unwrap_or_default();
 936
 937    crate::windows::shell_execute_from_explorer(&binary_path, &parameters, &directory)
 938        .map_err(|e| SpawnServerError::ProcessStatus(std::io::Error::other(e)))?;
 939
 940    Ok(())
 941}
 942
 943#[cfg(not(windows))]
 944fn spawn_server_normal(binary_name: &Path, paths: &ServerPaths) -> Result<(), SpawnServerError> {
 945    let mut server_process = new_smol_command(binary_name);
 946    server_process
 947        .stdin(std::process::Stdio::null())
 948        .stdout(std::process::Stdio::null())
 949        .stderr(std::process::Stdio::null())
 950        .arg("run")
 951        .arg("--log-file")
 952        .arg(&paths.log_file)
 953        .arg("--pid-file")
 954        .arg(&paths.pid_file)
 955        .arg("--stdin-socket")
 956        .arg(&paths.stdin_socket)
 957        .arg("--stdout-socket")
 958        .arg(&paths.stdout_socket)
 959        .arg("--stderr-socket")
 960        .arg(&paths.stderr_socket);
 961
 962    server_process
 963        .spawn()
 964        .map_err(SpawnServerError::ProcessStatus)?;
 965
 966    Ok(())
 967}
 968
 969#[derive(Debug, Error)]
 970#[error("Failed to remove PID file for missing process (pid `{pid}`")]
 971pub struct CheckPidError {
 972    #[source]
 973    source: std::io::Error,
 974    pid: u32,
 975}
 976async fn check_server_running(pid: u32) -> std::io::Result<bool> {
 977    new_smol_command("kill")
 978        .arg("-0")
 979        .arg(pid.to_string())
 980        .output()
 981        .await
 982        .map(|output| output.status.success())
 983}
 984
 985fn check_pid_file(path: &Path) -> Result<Option<u32>, CheckPidError> {
 986    let Some(pid) = std::fs::read_to_string(path)
 987        .ok()
 988        .and_then(|contents| contents.parse::<u32>().ok())
 989    else {
 990        return Ok(None);
 991    };
 992
 993    log::debug!("Checking if process with PID {} exists...", pid);
 994
 995    let system = sysinfo::System::new_with_specifics(
 996        sysinfo::RefreshKind::nothing().with_processes(sysinfo::ProcessRefreshKind::nothing()),
 997    );
 998
 999    if system.process(sysinfo::Pid::from_u32(pid)).is_some() {
1000        log::debug!(
1001            "Process with PID {} exists. NOT spawning new server, but attaching to existing one.",
1002            pid
1003        );
1004        Ok(Some(pid))
1005    } else {
1006        log::debug!("Found PID file, but process with that PID does not exist. Removing PID file.");
1007        std::fs::remove_file(path).map_err(|source| CheckPidError { source, pid })?;
1008        Ok(None)
1009    }
1010}
1011
1012fn write_pid_file(path: &Path, pid: u32) -> Result<()> {
1013    if path.exists() {
1014        std::fs::remove_file(path)?;
1015    }
1016    log::debug!("writing PID {} to file {:?}", pid, path);
1017    std::fs::write(path, pid.to_string()).context("Failed to write PID file")
1018}
1019
1020async fn handle_io<R, W>(mut reader: R, mut writer: W, socket_name: &str) -> Result<()>
1021where
1022    R: AsyncRead + Unpin,
1023    W: AsyncWrite + Unpin,
1024{
1025    use remote::protocol::{read_message_raw, write_size_prefixed_buffer};
1026
1027    let mut buffer = Vec::new();
1028    loop {
1029        read_message_raw(&mut reader, &mut buffer)
1030            .await
1031            .with_context(|| format!("failed to read message from {}", socket_name))?;
1032        write_size_prefixed_buffer(&mut writer, &mut buffer)
1033            .await
1034            .with_context(|| format!("failed to write message to {}", socket_name))?;
1035        writer.flush().await?;
1036        buffer.clear();
1037    }
1038}
1039
1040fn initialize_settings(
1041    session: AnyProtoClient,
1042    fs: Arc<dyn Fs>,
1043    cx: &mut App,
1044) -> watch::Receiver<Option<NodeBinaryOptions>> {
1045    let (user_settings_file_rx, watcher_task) =
1046        watch_config_file(cx.background_executor(), fs, paths::settings_file().clone());
1047
1048    handle_settings_file_changes(user_settings_file_rx, watcher_task, cx, {
1049        move |err, _cx| {
1050            if let Some(e) = err {
1051                log::info!("Server settings failed to change: {}", e);
1052
1053                session
1054                    .send(proto::Toast {
1055                        project_id: REMOTE_SERVER_PROJECT_ID,
1056                        notification_id: "server-settings-failed".to_string(),
1057                        message: format!(
1058                            "Error in settings on remote host {:?}: {}",
1059                            paths::settings_file(),
1060                            e
1061                        ),
1062                    })
1063                    .log_err();
1064            } else {
1065                session
1066                    .send(proto::HideToast {
1067                        project_id: REMOTE_SERVER_PROJECT_ID,
1068                        notification_id: "server-settings-failed".to_string(),
1069                    })
1070                    .log_err();
1071            }
1072        }
1073    });
1074
1075    let (mut tx, rx) = watch::channel(None);
1076    let mut node_settings = None;
1077    cx.observe_global::<SettingsStore>(move |cx| {
1078        let new_node_settings = &ProjectSettings::get_global(cx).node;
1079        if Some(new_node_settings) != node_settings.as_ref() {
1080            log::info!("Got new node settings: {new_node_settings:?}");
1081            let options = NodeBinaryOptions {
1082                allow_path_lookup: !new_node_settings.ignore_system_version,
1083                // TODO: Implement this setting
1084                allow_binary_download: true,
1085                use_paths: new_node_settings.path.as_ref().map(|node_path| {
1086                    let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
1087                    let npm_path = new_node_settings
1088                        .npm_path
1089                        .as_ref()
1090                        .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
1091                    (
1092                        node_path.clone(),
1093                        npm_path.unwrap_or_else(|| {
1094                            let base_path = PathBuf::new();
1095                            node_path.parent().unwrap_or(&base_path).join("npm")
1096                        }),
1097                    )
1098                }),
1099            };
1100            node_settings = Some(new_node_settings.clone());
1101            tx.send(Some(options)).ok();
1102        }
1103    })
1104    .detach();
1105
1106    rx
1107}
1108
1109pub fn handle_settings_file_changes(
1110    mut server_settings_file: mpsc::UnboundedReceiver<String>,
1111    watcher_task: gpui::Task<()>,
1112    cx: &mut App,
1113    settings_changed: impl Fn(Option<anyhow::Error>, &mut App) + 'static,
1114) {
1115    let server_settings_content = cx
1116        .foreground_executor()
1117        .block_on(server_settings_file.next())
1118        .unwrap();
1119    SettingsStore::update_global(cx, |store, cx| {
1120        store
1121            .set_server_settings(&server_settings_content, cx)
1122            .log_err();
1123    });
1124    cx.spawn(async move |cx| {
1125        let _watcher_task = watcher_task;
1126        while let Some(server_settings_content) = server_settings_file.next().await {
1127            cx.update_global(|store: &mut SettingsStore, cx| {
1128                let result = store.set_server_settings(&server_settings_content, cx);
1129                if let Err(err) = &result {
1130                    log::error!("Failed to load server settings: {err}");
1131                }
1132                settings_changed(result.err(), cx);
1133                cx.refresh_windows();
1134            });
1135        }
1136    })
1137    .detach();
1138}
1139
1140fn read_proxy_settings(cx: &mut Context<HeadlessProject>) -> Option<Url> {
1141    let proxy_str = ProxySettings::get_global(cx).proxy.to_owned();
1142
1143    proxy_str
1144        .as_deref()
1145        .map(str::trim)
1146        .filter(|input| !input.is_empty())
1147        .and_then(|input| {
1148            input
1149                .parse::<Url>()
1150                .inspect_err(|e| log::error!("Error parsing proxy settings: {}", e))
1151                .ok()
1152        })
1153        .or_else(read_proxy_from_env)
1154}
1155
1156fn cleanup_old_binaries() -> Result<()> {
1157    let server_dir = paths::remote_server_dir_relative();
1158    let release_channel = release_channel::RELEASE_CHANNEL.dev_name();
1159    let prefix = format!("zed-remote-server-{}-", release_channel);
1160
1161    for entry in std::fs::read_dir(server_dir.as_std_path())? {
1162        let path = entry?.path();
1163
1164        if let Some(file_name) = path.file_name()
1165            && let Some(version) = file_name.to_string_lossy().strip_prefix(&prefix)
1166            && !is_new_version(version)
1167            && !is_file_in_use(file_name)
1168        {
1169            log::info!("removing old remote server binary: {:?}", path);
1170            std::fs::remove_file(&path)?;
1171        }
1172    }
1173
1174    Ok(())
1175}
1176
1177fn is_new_version(version: &str) -> bool {
1178    semver::Version::from_str(version)
1179        .ok()
1180        .zip(semver::Version::from_str(env!("ZED_PKG_VERSION")).ok())
1181        .is_some_and(|(version, current_version)| version >= current_version)
1182}
1183
1184fn is_file_in_use(file_name: &OsStr) -> bool {
1185    let info = sysinfo::System::new_with_specifics(sysinfo::RefreshKind::nothing().with_processes(
1186        sysinfo::ProcessRefreshKind::nothing().with_exe(sysinfo::UpdateKind::Always),
1187    ));
1188
1189    for process in info.processes().values() {
1190        if process
1191            .exe()
1192            .is_some_and(|exe| exe.file_name().is_some_and(|name| name == file_name))
1193        {
1194            return true;
1195        }
1196    }
1197
1198    false
1199}