unix.rs

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