A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
mux-server: refuse to bind over a live socket, and start with no pane on request
RoversX0fd8e7ddb4be
diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rsindex c3a9b69f..d644fd34 100644--- a/wezterm-mux-server-impl/src/handoff.rs+++ b/wezterm-mux-server-impl/src/handoff.rs@@ -271,11 +271,7 @@ pub fn report_takeover(outcome: Result<(), &str>) {/// time; a failed one leaves this server as it was.pub fn spawn_handoff_listener(socket_path: PathBuf) -> anyhow::Result<()> {let path = handoff_socket_path(&socket_path);- match std::fs::remove_file(&path) {- Ok(()) => {}- Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}- Err(err) => return Err(err).with_context(|| format!("removing {}", path.display())),- }+ crate::local::claim_socket_path(&path)?;let listener =UnixListener::bind(&path).with_context(|| format!("binding {}", path.display()))?;config::set_sticky_bit(&path);diff --git a/wezterm-mux-server-impl/src/local.rs b/wezterm-mux-server-impl/src/local.rsindex 3cf3265c..e5c15f79 100644--- a/wezterm-mux-server-impl/src/local.rs+++ b/wezterm-mux-server-impl/src/local.rs@@ -1,6 +1,8 @@use anyhow::{anyhow, Context as _};use config::{create_user_owned_dirs, UnixDomain};use wezterm_uds::UnixListener;+#[cfg(unix)]+use std::os::fd::{AsRawFd, FromRawFd};#[cfg(unix)]lazy_static::lazy_static! {@@ -80,6 +82,83 @@ impl LocalListener {}}+/// Make `path` free to bind: remove the socket file a previous server+/// left there, unless a server still answers on it. A server that is not+/// the daemon -- one run in the foreground, say by mistaking+/// `thinkterm-mux-server cli list` for the client -- takes no pid lock,+/// and without this it would bind the path out from under the running one:+/// that one keeps serving its connections on an inode nothing can reach,+/// and every later `thinkterm cli` is refused.+pub fn claim_socket_path(path: &std::path::Path) -> anyhow::Result<()> {+ if someone_listens(path) {+ anyhow::bail!(+ "a mux server is already listening on {}; refusing to bind over it. \+ `thinkterm cli list` talks to it; `thinkterm-mux-server --daemonize --takeover` \+ replaces it",+ path.display()+ );+ }+ // On windows, we can't tell if the unix domain socket exists using the+ // methods on Path, so we just unconditionally remove it and see what+ // error occurs.+ match std::fs::remove_file(path) {+ Ok(_) => Ok(()),+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(err) => Err(err).context(format!("Unable to remove {}", path.display())),+ }+}++/// Whether a connect to `path` reaches a listener. Only a missing file+/// and a refused connection mean nobody does; everything else -- a+/// connection, EAGAIN from a full backlog, or any other failure -- counts+/// as someone, because binding over a live server is the one outcome+/// this must never allow. Non-blocking, so a full backlog cannot hang+/// the caller.+#[cfg(unix)]+pub fn someone_listens(path: &std::path::Path) -> bool {+ use std::os::unix::ffi::OsStrExt;+ let bytes = path.as_os_str().as_bytes();+ let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() };+ if bytes.len() >= addr.sun_path.len() {+ // Cannot be probed (nor bound): let the bind report it.+ return true;+ }+ addr.sun_family = libc::AF_UNIX as libc::sa_family_t;+ for (dst, src) in addr.sun_path.iter_mut().zip(bytes) {+ *dst = *src as libc::c_char;+ }+ let fd = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0) };+ if fd < 0 {+ return true;+ }+ let fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) };+ unsafe {+ libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC);+ let flags = libc::fcntl(fd.as_raw_fd(), libc::F_GETFL);+ libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK);+ }+ let len = std::mem::size_of::<libc::sa_family_t>() + bytes.len() + 1;+ let res = unsafe {+ libc::connect(+ fd.as_raw_fd(),+ &addr as *const libc::sockaddr_un as *const libc::sockaddr,+ len as libc::socklen_t,+ )+ };+ if res == 0 {+ return true;+ }+ !matches!(+ std::io::Error::last_os_error().raw_os_error(),+ Some(libc::ENOENT) | Some(libc::ECONNREFUSED)+ )+}++#[cfg(not(unix))]+pub fn someone_listens(_path: &std::path::Path) -> bool {+ false+}+/// Take care when setting up the listener socket;/// we need to be sure that the directory that we create it in/// is owned by the user and has appropriate file permissions@@ -115,17 +194,7 @@ fn safely_create_sock_path(unix_dom: &UnixDomain) -> anyhow::Result<UnixListener}}- // We want to remove the socket if it exists.- // However, on windows, we can't tell if the unix domain socket- // exists using the methods on Path, so instead we just unconditionally- // remove it and see what error occurs.- match std::fs::remove_file(sock_path) {- Ok(_) => {}- Err(err) => match err.kind() {- std::io::ErrorKind::NotFound => {}- _ => return Err(err).context(format!("Unable to remove {}", sock_path.display())),- },- }+ claim_socket_path(sock_path)?;let listener = UnixListener::bind(sock_path).with_context(|| format!("Failed to bind to {}", sock_path.display()))?;@@ -134,3 +203,45 @@ fn safely_create_sock_path(unix_dom: &UnixDomain) -> anyhow::Result<UnixListenerOk(listener)}++#[cfg(all(test, unix))]+mod tests {+ use super::claim_socket_path;++ fn short_dir() -> tempfile::TempDir {+ // Socket paths are short; the default temp dir on macOS is not.+ tempfile::Builder::new()+ .prefix("tt-")+ .tempdir_in("/tmp")+ .unwrap()+ }++ #[test]+ fn a_path_with_a_listener_is_refused() {+ let dir = short_dir();+ let path = dir.path().join("sock");+ let _listener = std::os::unix::net::UnixListener::bind(&path).unwrap();+ let err = claim_socket_path(&path).unwrap_err();+ assert!(+ err.to_string().contains("already listening"),+ "{err:#}"+ );+ assert!(path.exists(), "the live socket file must stay");+ }++ #[test]+ fn a_stale_socket_file_is_removed() {+ let dir = short_dir();+ let path = dir.path().join("sock");+ drop(std::os::unix::net::UnixListener::bind(&path).unwrap());+ assert!(path.exists());+ claim_socket_path(&path).unwrap();+ assert!(!path.exists());+ }++ #[test]+ fn a_missing_file_is_free() {+ let dir = short_dir();+ claim_socket_path(&dir.path().join("sock")).unwrap();+ }+}diff --git a/wezterm-mux-server/src/daemonize.rs b/wezterm-mux-server/src/daemonize.rsindex 52cc899f..739f9a21 100644--- a/wezterm-mux-server/src/daemonize.rs+++ b/wezterm-mux-server/src/daemonize.rs@@ -56,7 +56,16 @@ pub fn lock_pid_file(config: &config::ConfigHandle) -> anyhow::Result<std::fs::Flet res = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };if res != 0 {let err = std::io::Error::last_os_error();- anyhow::bail!("unable to lock pid file {}: {}", pid_file.display(), err);+ let holder = std::fs::read_to_string(&pid_file)+ .ok()+ .and_then(|s| s.trim().parse::<u32>().ok())+ .map(|pid| format!(" (a mux server with pid {pid} holds it)"))+ .unwrap_or_default();+ anyhow::bail!(+ "unable to lock pid file {}{holder}: {}",+ pid_file.display(),+ err+ );}unsafe { libc::ftruncate(file.as_raw_fd(), 0) };diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex 4f7bdb93..cba59418 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -55,6 +55,12 @@ struct Opt {#[arg(long = "takeover")]takeover: bool,+ /// Start with no pane at all instead of one running the default+ /// program: for a server whose panes are all spawned by a client,+ /// such as the GUI keeping its local terminals in it.+ #[arg(long = "no-initial-pane")]+ no_initial_pane: bool,+/// Specify the current working directory for the initially/// spawned program#[arg(long = "cwd", value_parser, value_hint=ValueHint::DirPath)]@@ -170,6 +176,9 @@ fn run() -> anyhow::Result<()> {if opts.takeover {cmd.arg("--takeover");}+ if opts.no_initial_pane {+ cmd.arg("--no-initial-pane");+ }if let Some(f) = &opts.config_file {cmd.arg("--config-file");cmd.arg(f);@@ -246,6 +255,7 @@ fn run() -> anyhow::Result<()> {wezterm_blob_leases::simple_tempdir::SimpleTempDir::new_in(&*config::CACHE_DIR)?,))?;+ let no_initial_pane = opts.no_initial_pane;let need_builder = !opts.prog.is_empty() || opts.cwd.is_some();let cmd = if need_builder {@@ -327,7 +337,7 @@ fn run() -> anyhow::Result<()> {let daemonized = opts.daemonize;promise::spawn::spawn(async move {- if let Err(err) = async_run(cmd, takeover, daemonized).await {+ if let Err(err) = async_run(cmd, takeover, daemonized, no_initial_pane).await {terminate_with_error(err);}drop(activity);@@ -366,6 +376,7 @@ async fn async_run(cmd: Option<CommandBuilder>,takeover: Option<TakeoverHandle>,daemonized: bool,+ no_initial_pane: bool,) -> anyhow::Result<()> {let mux = Mux::get();let config = config::configuration();@@ -416,15 +427,42 @@ async fn async_run(},None => {}}- // Everything is ours already; not listening for the next successor- // is worth a log line, not an exit.- if let Err(err) = wezterm_mux_server_impl::handoff::spawn_handoff_listener(socket_path) {- log::error!("not listening for a successor: {err:#}");- }- // The TCP listeners wait for the old server to release its ports.+ // The handoff listener and the TCP listeners wait for the old+ // server to exit: it still answers on the handoff path and holds+ // the ports until then, and a path someone answers on is not bound+ // over. Everything is ours already; not listening for the next+ // successor is worth a log line, not an exit.let tls_servers = config.tls_servers.clone();thread::spawn(move || {wezterm_mux_server_impl::handoff::wait_for_predecessor_exit(stream);+ // Its descriptors close one after another as it exits; the+ // handoff socket may answer for a while after the stream did.+ // A server that cannot be taken over is one whose sessions the+ // next update ends, so this keeps trying for a long time+ // rather than giving up at once.+ let handoff_path = wezterm_mux_server_impl::handoff::handoff_socket_path(&socket_path);+ let give_up = std::time::Instant::now() + std::time::Duration::from_secs(600);+ let mut last_err = None;+ loop {+ if !wezterm_mux_server_impl::local::someone_listens(&handoff_path) {+ match wezterm_mux_server_impl::handoff::spawn_handoff_listener(+ socket_path.clone(),+ ) {+ Ok(()) => break,+ Err(err) => last_err = Some(err),+ }+ }+ if std::time::Instant::now() >= give_up {+ log::error!(+ "not listening for a successor: {}",+ last_err+ .map(|err| format!("{err:#}"))+ .unwrap_or_else(|| "the predecessor's handoff socket kept answering".into())+ );+ break;+ }+ thread::sleep(std::time::Duration::from_millis(250));+ }for tls_server in &tls_servers {if let Err(err) = ossl::spawn_tls_listener(tls_server) {log::error!("problem spawning TLS listener after the takeover: {err:#}");@@ -459,7 +497,7 @@ async fn async_run(.iter().any(|p| p.domain_id() == domain.domain_id());- if !have_panes_in_domain {+ if !have_panes_in_domain && !no_initial_pane {let workspace = None;let position = None;let window_id = mux.new_empty_window(workspace, position);@@ -537,7 +575,17 @@ pub fn spawn_listener() -> anyhow::Result<()> {if let Some(unix_dom) = config.unix_domains.last() {std::env::set_var("WEZTERM_UNIX_SOCKET", unix_dom.socket_path());}+ // Two domains naming one socket path would have the second bind over+ // the first (now refused): one listener per path.+ let mut bound = std::collections::HashSet::new();for unix_dom in &config.unix_domains {+ if !bound.insert(unix_dom.socket_path()) {+ log::warn!(+ "unix domain {} shares the socket path of an earlier domain; not binding it twice",+ unix_dom.name+ );+ continue;+ }let mut listener = wezterm_mux_server_impl::local::LocalListener::with_domain(unix_dom)?;thread::spawn(move || {listener.run();