unix.rs

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