diff --git a/config/src/unix.rs b/config/src/unix.rs index 497f34767..79d6d6404 100644 --- a/config/src/unix.rs +++ b/config/src/unix.rs @@ -30,6 +30,11 @@ pub struct UnixDomain { /// a unix domain inside a wsl container. pub serve_command: Option>, + /// Instead of directly connecting to `socket_path`, + /// spawn this command and use its stdin/stdout in place of + /// the socket. + pub proxy_command: Option>, + /// If true, bypass checking for secure ownership of the /// socket_path. This is not recommended on a multi-user /// system, but is useful for example when running the @@ -57,10 +62,17 @@ impl Default for UnixDomain { skip_permissions_check: false, read_timeout: default_read_timeout(), write_timeout: default_write_timeout(), + proxy_command: None, } } } +#[derive(Debug)] +pub enum UnixTarget { + Socket(PathBuf), + Proxy(Vec), +} + impl UnixDomain { pub fn socket_path(&self) -> PathBuf { self.socket_path @@ -69,6 +81,14 @@ impl UnixDomain { .unwrap_or_else(|| RUNTIME_DIR.join("sock")) } + pub fn target(&self) -> UnixTarget { + if let Some(proxy) = &self.proxy_command { + UnixTarget::Proxy(proxy.clone()) + } else { + UnixTarget::Socket(self.socket_path()) + } + } + pub fn default_unix_domains() -> Vec { vec![UnixDomain { read_timeout: default_read_timeout(), diff --git a/docs/changelog.md b/docs/changelog.md index 0f5d16bd6..cfc4f6e7b 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -13,6 +13,8 @@ As features stabilize some brief notes about them will accumulate here. #### New +* unix domains now support an optional `proxy_command` to use in place of a direct unix socket connection. [Read more about multiplexing unix domains](multiplexing.html#unix-domains) + #### Changed * quickselect: we now de-duplicate labels for results with the same textual content. [#1271](https://github.com/wez/wezterm/issues/1271) diff --git a/docs/multiplexing.md b/docs/multiplexing.md index af361a61d..3084e558b 100644 --- a/docs/multiplexing.md +++ b/docs/multiplexing.md @@ -127,6 +127,28 @@ return { } ``` +*Since: nightly builds only* + +It is now possible to specify a `proxy_command` that will be used +in place of making a direct unix connection. When `proxy_command` +is specified, it will be used instead of the optional `socket_path`. + +This example shows a redundant use of `nc` (netcat) to connect to +the unix socket path on my mac. This isn't useful on its own, +but may help with the WSL 2 issue mentioned below when translated +to an appropriate invocation of netcat/socat on Windows: + +```lua +return { + unix_domains = { + { + name = "unix", + proxy_command = {"nc", "-U", "/Users/wez/.local/share/wezterm/sock"}, + } + } +} +``` + ### Connecting into Windows Subsystem for Linux *Note: this only works with WSL 1. [WSL 2 doesn't support AF_UNIX interop](https://github.com/microsoft/WSL/issues/5961)* diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs index 1495f89bf..90d19ccb1 100644 --- a/wezterm-client/src/client.rs +++ b/wezterm-client/src/client.rs @@ -5,7 +5,7 @@ use anyhow::{anyhow, bail, Context}; use async_ossl::AsyncSslStream; use async_trait::async_trait; use codec::*; -use config::{configuration, SshBackend, SshDomain, TlsDomainClient, UnixDomain}; +use config::{configuration, SshBackend, SshDomain, TlsDomainClient, UnixDomain, UnixTarget}; use filedescriptor::FileDescriptor; use futures::FutureExt; use mux::connui::ConnectionUI; @@ -268,10 +268,10 @@ async fn client_thread_async( } pub fn unix_connect_with_retry( - path: &Path, + target: &UnixTarget, just_spawned: bool, -) -> Result { - let mut error = std::io::Error::last_os_error(); +) -> anyhow::Result { + let mut error = None; if just_spawned { std::thread::sleep(std::time::Duration::from_millis(200)); @@ -281,13 +281,69 @@ pub fn unix_connect_with_retry( if iter > 0 { std::thread::sleep(std::time::Duration::from_millis(iter * 10)); } - match UnixStream::connect(path) { - Ok(stream) => return Ok(stream), - Err(err) => error = err, + match target { + UnixTarget::Socket(path) => match UnixStream::connect(path) { + Ok(stream) => return Ok(stream), + Err(err) => { + error = + Some(Err(err).with_context(|| format!("connecting to {}", path.display()))) + } + }, + UnixTarget::Proxy(argv) => { + let mut cmd = std::process::Command::new(&argv[0]); + cmd.args(&argv[1..]); + + let (a, b) = filedescriptor::socketpair()?; + + cmd.stdin(b.as_stdio()?); + cmd.stdout(b.as_stdio()?); + cmd.stderr(std::process::Stdio::inherit()); + let mut child = cmd + .spawn() + .with_context(|| format!("spawning proxy command {:?}", cmd))?; + + error.take(); + + // Grace period to detect whether connection failed + for _ in 0..5 { + std::thread::sleep(std::time::Duration::from_millis(10)); + match child.try_wait() { + Ok(Some(status)) => { + error = Some(Err(anyhow!( + "{:?} exited already with status {:?}", + cmd, + status + ))); + continue; + } + Ok(None) => { + error.take(); + } + Err(err) => { + error = + Some(Err(err).context(format!("spawning proxy command {:?}", cmd))); + continue; + } + } + } + + if error.is_none() { + #[cfg(unix)] + unsafe { + use std::os::unix::io::{FromRawFd, IntoRawFd}; + return Ok(UnixStream::from_raw_fd(a.into_raw_fd())); + } + #[cfg(windows)] + unsafe { + use std::os::windows::io::{FromRawSocket, IntoRawSocket}; + return Ok(UnixStream::from_raw_socket(a.into_raw_socket())); + } + } + } } } - Err(error) + error.expect("only get here after at least one unix fail") } #[async_trait(?Send)] @@ -524,19 +580,19 @@ impl Reconnectable { ui: &mut ConnectionUI, no_auto_start: bool, ) -> anyhow::Result<()> { - let sock_path = unix_dom.socket_path(); - ui.output_str(&format!("Connect to {}\n", sock_path.display())); - log::trace!("connect to {}", sock_path.display()); + let target = unix_dom.target(); + ui.output_str(&format!("Connect to {:?}\n", target)); + log::trace!("connect to {:?}", target); - let stream = match unix_connect_with_retry(&sock_path, false) { + let stream = match unix_connect_with_retry(&target, false) { Ok(stream) => stream, Err(e) => { if no_auto_start || unix_dom.no_serve_automatically || !initial { - bail!("failed to connect to {}: {}", sock_path.display(), e); + bail!("failed to connect to {:?}: {}", target, e); } log::warn!( - "While connecting to {}: {}. Will try spawning the server.", - sock_path.display(), + "While connecting to {:?}: {}. Will try spawning the server.", + target, e ); ui.output_str(&format!("Error: {}. Will try spawning server.\n", e)); @@ -570,11 +626,8 @@ impl Reconnectable { } }); - unix_connect_with_retry(&sock_path, true).with_context(|| { - format!( - "(after spawning server) failed to connect to {}", - sock_path.display() - ) + unix_connect_with_retry(&target, true).with_context(|| { + format!("(after spawning server) failed to connect to {:?}", target) })? } }; diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs index a7d9c11ae..dbc548539 100644 --- a/wezterm/src/main.rs +++ b/wezterm/src/main.rs @@ -549,8 +549,8 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: let mux = Rc::new(mux::Mux::new(None)); Mux::set_mux(&mux); let unix_dom = config.unix_domains.first().unwrap(); - let sock_path = unix_dom.socket_path(); - let stream = unix_connect_with_retry(&sock_path, false)?; + let target = unix_dom.target(); + let stream = unix_connect_with_retry(&target, false)?; // Spawn a thread to pull data from the socket and write // it to stdout