mux: add proxy_command to unix_domains

Potentially enables using the mux with WSL 2 on Windows,
although this commit was authored and tested on a mac.
This commit is contained in:
Wez Furlong committed 2021-12-11 17:29:37 -07:00
1 parent fa70a50af4
commit 1ce261f7a9
5 files changed
+119 -22

No files matched your search

+20
View File
@@ -30,6 +30,11 @@ pub struct UnixDomain {
/// a unix domain inside a wsl container.
pub serve_command: Option<Vec<String>>,
/// Instead of directly connecting to `socket_path`,
/// spawn this command and use its stdin/stdout in place of
/// the socket.
pub proxy_command: Option<Vec<String>>,
/// 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<String>),
}
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<Self> {
vec![UnixDomain {
read_timeout: default_read_timeout(),
+2
View File
@@ -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)
+22
View File
@@ -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)*
+73 -20
View File
@@ -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<UnixStream, std::io::Error> {
let mut error = std::io::Error::last_os_error();
) -> anyhow::Result<UnixStream> {
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)
})?
}
};
+2 -2
View File
@@ -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