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