unix.rs

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