unix.rs

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