Skip to content

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.

feat(ssh): connect through a registered network

RoversX30267d56944b
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 50371f73..2be7fdf7 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -1225,6 +1225,67 @@ fn connect_to_spawned_server(path: &Path) -> anyhow::Result<UnixStream> {
}
}
+/// Starts the server of `unix_dom` as its serve command says, with `extra`
+/// arguments after it and with the umask this process started with. Returns
+/// once it is spawned, with the command as run for showing; `--daemonize`
+/// forks and exits at once, and how that went is logged when it has.
+pub fn spawn_server(unix_dom: &UnixDomain, extra: &[&str]) -> anyhow::Result<String> {
+ let mut argv = unix_dom.serve_command()?;
+ argv.extend(extra.iter().map(std::ffi::OsString::from));
+
+ let mut cmd = std::process::Command::new(&argv[0]);
+ cmd.args(&argv[1..]);
+
+ #[cfg(unix)]
+ if let Some(mask) = umask::UmaskSaver::saved_umask() {
+ unsafe {
+ cmd.pre_exec(move || {
+ libc::umask(mask);
+ Ok(())
+ });
+ }
+ }
+
+ // The server is a console-subsystem binary; without this a console
+ // window flashes every time the GUI starts it.
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt as _;
+ cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
+ }
+
+ let running = format!("{:?}", cmd);
+ log::warn!("Running: {}", running);
+
+ let child = cmd
+ .spawn()
+ .with_context(|| format!("while spawning {}", running))?;
+ std::thread::spawn(move || match child.wait_with_output() {
+ Ok(out) => {
+ // `--daemonize` returns once it has forked, so a failing status
+ // is a server that never started at all: it lost the pid lock,
+ // or could not bind.
+ if !out.status.success() {
+ log::warn!("the server we spawned exited with {}", out.status);
+ }
+ if let Ok(stdout) = std::str::from_utf8(&out.stdout) {
+ if !stdout.is_empty() {
+ log::warn!("stdout: {}", stdout);
+ }
+ }
+ if let Ok(stderr) = std::str::from_utf8(&out.stderr) {
+ if !stderr.is_empty() {
+ log::warn!("stderr: {}", stderr);
+ }
+ }
+ }
+ Err(err) => {
+ log::error!("spawn: {:#}", err);
+ }
+ });
+ Ok(running)
+}
+
pub fn unix_connect_with_retry(
target: &UnixTarget,
just_spawned: bool,
@@ -1617,61 +1678,11 @@ impl Reconnectable {
);
ui.output_str(&format!("Error: {}. Will try spawning server.\n", e));
- let argv = unix_dom.serve_command()?;
-
- let mut cmd = std::process::Command::new(&argv[0]);
- cmd.args(&argv[1..]);
-
- #[cfg(unix)]
- if let Some(mask) = umask::UmaskSaver::saved_umask() {
- unsafe {
- cmd.pre_exec(move || {
- libc::umask(mask);
- Ok(())
- });
- }
- }
-
- // The server is a console-subsystem binary; without this a
- // console window flashes every time the GUI starts it.
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt as _;
- cmd.creation_flags(winapi::um::winbase::CREATE_NO_WINDOW);
- }
-
- log::warn!("Running: {:?}", cmd);
- ui.output_str(&format!("Running: {:?}\n", cmd));
-
- let child = cmd
- .spawn()
- .with_context(|| format!("while spawning {:?}", cmd))?;
+ let running = spawn_server(&unix_dom, &[])?;
+ ui.output_str(&format!("Running: {}\n", running));
if unix_dom.local_session_host {
crate::local_update::note_local_session_host_started();
}
- std::thread::spawn(move || match child.wait_with_output() {
- Ok(out) => {
- // `--daemonize` returns once it has forked, so a
- // failing status is a server that never started at
- // all: it lost the pid lock, or could not bind.
- if !out.status.success() {
- log::warn!("the server we spawned exited with {}", out.status);
- }
- if let Ok(stdout) = std::str::from_utf8(&out.stdout) {
- if !stdout.is_empty() {
- log::warn!("stdout: {}", stdout);
- }
- }
- if let Ok(stderr) = std::str::from_utf8(&out.stderr) {
- if !stderr.is_empty() {
- log::warn!("stderr: {}", stderr);
- }
- }
- }
- Err(err) => {
- log::error!("spawn: {:#}", err);
- }
- });
unix_connect_with_retry(&target, true, None).with_context(|| {
format!("(after spawning server) failed to connect to {:?}", target)
@@ -1704,11 +1715,21 @@ impl Reconnectable {
)
})?;
+ let network = match tls_client.ssh_parameters().transpose()? {
+ Some(params) => {
+ let mut config = wezterm_ssh::Config::new();
+ config.add_default_config_files();
+ let host = params.host_and_port.split(':').next().unwrap_or("");
+ wezterm_ssh::Network::from_config(&config.for_host(host))?
+ }
+ None => wezterm_ssh::Network::System,
+ };
+
// If we are reconnecting and already bootstrapped via SSH, let's see if
// we can connect using those same credentials and avoid running through
// the SSH authentication flow.
if let Some(Ok(_)) = tls_client.ssh_parameters() {
- match self.try_connect(&tls_client, ui, &remote_address, remote_host_name) {
+ match self.try_connect(&tls_client, ui, &remote_address, remote_host_name, network) {
Ok(stream) => {
self.stream.replace(stream);
return Ok(());
@@ -1812,7 +1833,7 @@ impl Reconnectable {
let cloned_ui = ui.clone();
let stream = cloned_ui.run_and_log_error({
- || self.try_connect(&tls_client, ui, &remote_address, remote_host_name)
+ || self.try_connect(&tls_client, ui, &remote_address, remote_host_name, network)
})?;
self.stream.replace(stream);
Ok(())
@@ -1824,6 +1845,7 @@ impl Reconnectable {
ui: &mut ConnectionUI,
remote_address: &str,
remote_host_name: &str,
+ network: wezterm_ssh::Network,
) -> anyhow::Result<Box<dyn AsyncReadAndWrite>> {
let mut connector = SslConnector::builder(SslMethod::tls())?;
@@ -1888,9 +1910,27 @@ impl Reconnectable {
.verify_hostname(!tls_client.accept_invalid_hostnames);
ui.output_str(&format!("Connecting to {} using TLS\n", remote_address));
- let stream = TcpStream::connect(remote_address)
- .with_context(|| format!("connecting to {}", remote_address))?;
- stream.set_nodelay(true)?;
+ // A machine the SSH that bootstrapped the domain reached another way
+ // than the OS network -- through an embedded tailnet -- is reached
+ // that way here too.
+ let (host, port) = split_host_port(remote_address).context("invalid TLS remote address")?;
+ let registered = wezterm_ssh::dial_registered(network, host, port, None);
+ let stream = match registered {
+ Some(dialed) => {
+ let stream = TcpStream::from(
+ dialed.with_context(|| format!("connecting to {}", remote_address))?,
+ );
+ // Not TCP underneath, and so no delay to turn off.
+ let _ = stream.set_nodelay(true);
+ stream
+ }
+ None => {
+ let stream = TcpStream::connect(remote_address)
+ .with_context(|| format!("connecting to {}", remote_address))?;
+ stream.set_nodelay(true)?;
+ stream
+ }
+ };
stream.set_write_timeout(Some(tls_client.write_timeout))?;
stream.set_read_timeout(Some(tls_client.read_timeout))?;
@@ -1915,6 +1955,16 @@ impl Reconnectable {
}
}
+/// `host:port` or `[v6]:port`, as `remote_address` spells it.
+fn split_host_port(address: &str) -> Option<(&str, u16)> {
+ let (host, port) = address.rsplit_once(':')?;
+ let host = host
+ .strip_prefix('[')
+ .and_then(|host| host.strip_suffix(']'))
+ .unwrap_or(host);
+ Some((host, port.parse().ok()?))
+}
+
impl Client {
fn new(local_domain_id: Option<DomainId>, mut reconnectable: Reconnectable) -> Self {
let client_domain_config = reconnectable.config.clone();
@@ -2835,10 +2885,18 @@ fn outage_clock_after_session(
#[cfg(test)]
mod tests {
- use super::{is_auth_cancelled, outage_clock_after_session, Reconnectable};
+ use super::{is_auth_cancelled, outage_clock_after_session, split_host_port, Reconnectable};
use crate::domain::ClientDomainConfig;
use std::time::{Duration, Instant};
+ #[test]
+ fn a_tls_address_splits_into_host_and_port() {
+ assert_eq!(split_host_port("server-a:8080"), Some(("server-a", 8080)));
+ assert_eq!(split_host_port("[fd7a::2]:8080"), Some(("fd7a::2", 8080)));
+ assert_eq!(split_host_port("server-a"), None);
+ assert_eq!(split_host_port("server-a:port"), None);
+ }
+
#[test]
fn a_restored_session_ends_the_outage() {
let old = Some(Instant::now() - Duration::from_secs(3600));
diff --git a/wezterm-ssh/src/addresses.rs b/wezterm-ssh/src/addresses.rs
index 48362f58..624b194e 100644
--- a/wezterm-ssh/src/addresses.rs
+++ b/wezterm-ssh/src/addresses.rs
@@ -13,10 +13,12 @@
//! time, for a while.
use crate::config::ConfigMap;
+use crate::through::{AddressFamily, Network};
use anyhow::{bail, Context};
use socket2::{Domain, Socket, Type};
use std::collections::VecDeque;
use std::net::ToSocketAddrs;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::{Duration, Instant};
@@ -111,46 +113,58 @@ pub fn forget_reached(hostname: &str, port: u16) {
/// What opening one TCP connection needs from the config, so that it can
/// be done off the session's thread.
pub struct Dialer {
- family: Option<String>,
+ network: Network,
+ family: AddressFamily,
bind: Option<String>,
timeout: Option<Duration>,
}
impl Dialer {
- pub fn from_config(config: &ConfigMap) -> Self {
- Self {
- family: config.get("addressfamily").cloned(),
+ pub fn from_config(config: &ConfigMap) -> anyhow::Result<Self> {
+ Ok(Self {
+ network: Network::from_config(config)?,
+ family: match config.get("addressfamily").map(String::as_str) {
+ Some("inet") => AddressFamily::Inet,
+ Some("inet6") => AddressFamily::Inet6,
+ None | Some("any") | Some(_) => AddressFamily::Any,
+ },
bind: config.get("bindaddress").cloned(),
timeout: config
.get("connecttimeout")
.and_then(|value| value.parse::<u64>().ok())
.filter(|seconds| *seconds > 0)
.map(Duration::from_secs),
- }
+ })
}
fn family_allows(&self, addr: &std::net::SocketAddr) -> bool {
- match self.family.as_deref() {
- Some("inet") => addr.is_ipv4(),
- Some("inet6") => addr.is_ipv6(),
- None | Some("any") | Some(_) => true,
+ match self.family {
+ AddressFamily::Inet => addr.is_ipv4(),
+ AddressFamily::Inet6 => addr.is_ipv6(),
+ AddressFamily::Any => true,
}
}
- pub fn dial(&self, host: &str, port: u16) -> anyhow::Result<Socket> {
- self.dial_with(host, port, false, |_| Ok(()))
- }
-
/// `dial`, logging what it resolves and binds when `verbose`, and
/// handing the socket to `before_connect` before the connect that can
- /// block: a session watches it there, to cut it short on shutdown.
+ /// block: a session watches it there, to cut it short on shutdown. The
+ /// selected network alone is asked, and the embedded tailnet gives up
+ /// soon after `closed` says so.
pub fn dial_with(
&self,
host: &str,
port: u16,
verbose: bool,
+ closed: &dyn Fn() -> bool,
before_connect: impl FnOnce(&Socket) -> anyhow::Result<()>,
) -> anyhow::Result<Socket> {
+ if self.network == Network::Tailnet {
+ let sock = crate::through::dial(host, port, self.family, self.timeout, closed)?;
+ if verbose {
+ log::info!("{host}:{port} reached through the embedded tailnet");
+ }
+ return Ok(sock);
+ }
let addr = (host, port)
.to_socket_addrs()?
.find(|addr| self.family_allows(addr))
@@ -189,6 +203,15 @@ impl Dialer {
}
}
+/// Sets its flag when dropped: however `race` ends.
+struct OverOnDrop(std::sync::Arc<AtomicBool>);
+
+impl Drop for OverOnDrop {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+}
+
/// Connect to the first of `candidates` that answers, starting each a
/// moment after the one before, or as soon as every one started so far has
/// failed. Gives back the socket and which candidate it reached. `stop`
@@ -199,6 +222,10 @@ pub fn race(
stop: impl Fn() -> anyhow::Result<()>,
) -> anyhow::Result<(Socket, usize)> {
let dialer = std::sync::Arc::new(dialer);
+ // Set once the race is over, won or given up, for a dial still going
+ // to stop soon after: one waiting on the registered dialer would wait
+ // out its whole timeout otherwise.
+ let over = OverOnDrop(std::sync::Arc::new(AtomicBool::new(false)));
let (tx, rx) = std::sync::mpsc::channel();
let start = Instant::now();
let mut started = 0;
@@ -211,9 +238,12 @@ pub fn race(
let index = started;
let tx = tx.clone();
let dialer = std::sync::Arc::clone(&dialer);
+ let over = std::sync::Arc::clone(&over.0);
std::thread::spawn(move || {
+ let closed = || over.load(Ordering::SeqCst);
+ let dialed = dialer.dial_with(&host, port, false, &closed, |_| Ok(()));
// Nobody listening any more just means another won.
- let _ = tx.send((index, dialer.dial(&host, port)));
+ let _ = tx.send((index, dialed));
});
started += 1;
pending += 1;
@@ -324,13 +354,206 @@ mod tests {
("127.0.0.1".to_string(), port),
];
let started = Instant::now();
- let (_sock, index) = race(&candidates, Dialer::from_config(&config), || Ok(())).unwrap();
+ let (_sock, index) = race(
+ &candidates,
+ Dialer::from_config(&config).unwrap(),
+ || Ok(()),
+ )
+ .unwrap();
assert_eq!(index, 1);
// The refusal starts the next one at once, without the stagger.
assert!(started.elapsed() < STAGGER, "took {:?}", started.elapsed());
let all_refused = vec![("127.0.0.1".to_string(), refused_port)];
- let err = race(&all_refused, Dialer::from_config(&config), || Ok(())).unwrap_err();
+ let err = race(&all_refused, Dialer::from_config(&config).unwrap(), || {
+ Ok(())
+ })
+ .unwrap_err();
assert!(format!("{err:#}").contains("none of the host's addresses answered"));
}
+
+ #[test]
+ fn every_address_stays_on_the_selected_tailnet() {
+ let _one = DIALER_TESTS.lock().unwrap();
+ // Stands in for a machine only the registered way reaches.
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let machine = listener.local_addr().unwrap();
+ let refused = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let refused_port = refused.local_addr().unwrap().port();
+ drop(refused);
+
+ let asked = std::sync::Arc::new(Mutex::new(vec![]));
+ crate::through::set_dialer(Some(std::sync::Arc::new({
+ let asked = std::sync::Arc::clone(&asked);
+ move |host: &str, port: u16, family, _timeout, _closed: &dyn Fn() -> bool| {
+ asked.lock().unwrap().push((host.to_string(), port, family));
+ (host == "server.tailnet").then(|| -> anyhow::Result<Socket> {
+ let sock = Socket::new(Domain::IPV4, Type::STREAM, None)?;
+ sock.connect(&machine.into())?;
+ Ok(sock)
+ })
+ }
+ })));
+ let mut config = ConfigMap::new();
+ config.insert("addressfamily".to_string(), "inet".to_string());
+ config.insert(crate::NETWORK.into(), "tailnet".into());
+ let candidates = vec![
+ ("127.0.0.1".to_string(), refused_port),
+ ("server.tailnet".to_string(), 2200),
+ ];
+ let raced = race(
+ &candidates,
+ Dialer::from_config(&config).unwrap(),
+ || Ok(()),
+ );
+ crate::through::set_dialer(None);
+ assert_eq!(raced.unwrap().1, 1);
+ // Other tests may dial meanwhile: only these two are looked for.
+ let asked = asked.lock().unwrap();
+ for address in [
+ ("127.0.0.1".to_string(), refused_port, AddressFamily::Inet),
+ ("server.tailnet".to_string(), 2200, AddressFamily::Inet),
+ ] {
+ assert!(asked.contains(&address), "{:?} not in {:?}", address, asked);
+ }
+ }
+
+ /// The registered dialer is one for the whole process: the tests that
+ /// set it take turns.
+ static DIALER_TESTS: Mutex<()> = Mutex::new(());
+
+ #[test]
+ fn a_dial_still_going_when_the_race_is_won_is_told_it_is_over() {
+ let _one = DIALER_TESTS.lock().unwrap();
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let machine = listener.local_addr().unwrap();
+ let (told, heard) = std::sync::mpsc::channel();
+ crate::through::set_dialer(Some(std::sync::Arc::new(
+ move |host: &str, _port: u16, _family, _timeout, closed: &dyn Fn() -> bool| {
+ if host != "slow.tailnet" {
+ return Some((|| {
+ let sock = Socket::new(Domain::IPV4, Type::STREAM, None)?;
+ sock.connect(&machine.into())?;
+ Ok(sock)
+ })());
+ }
+ // Waits as a connection through a node still starting would.
+ let started = Instant::now();
+ while !closed() && started.elapsed() < Duration::from_secs(10) {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let _ = told.send(closed());
+ Some(Err(anyhow::anyhow!("gave up")))
+ },
+ )));
+ let candidates = vec![
+ ("slow.tailnet".to_string(), 2200),
+ (machine.ip().to_string(), machine.port()),
+ ];
+ let config = ConfigMap::from([(crate::NETWORK.into(), "tailnet".into())]);
+ let raced = race(
+ &candidates,
+ Dialer::from_config(&config).unwrap(),
+ || Ok(()),
+ );
+ assert_eq!(raced.unwrap().1, 1);
+ let was_closed = heard.recv_timeout(Duration::from_secs(5));
+ crate::through::set_dialer(None);
+ assert_eq!(was_closed, Ok(true));
+ }
+
+ #[test]
+ fn system_connections_never_ask_the_embedded_node() {
+ let _one = DIALER_TESTS.lock().unwrap();
+ crate::through::set_dialer(Some(std::sync::Arc::new(|_, _, _, _, _| {
+ panic!("a system connection reached the tailnet")
+ })));
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let config = ConfigMap::from([("addressfamily".into(), "inet".into())]);
+ let dialer = Dialer::from_config(&config).unwrap();
+ for host in ["127.0.0.1", "localhost"] {
+ dialer
+ .dial_with(host, port, false, &|| false, |_| Ok(()))
+ .unwrap();
+ }
+ assert!(crate::dial_registered(Network::System, "localhost", port, None).is_none());
+ crate::through::set_dialer(None);
+ }
+
+ #[test]
+ fn a_tailnet_failure_never_uses_a_reachable_system_address() {
+ let _one = DIALER_TESTS.lock().unwrap();
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let config = ConfigMap::from([(crate::NETWORK.into(), "tailnet".into())]);
+ let dialer = Dialer::from_config(&config).unwrap();
+ for refused in [false, true] {
+ crate::through::set_dialer(Some(std::sync::Arc::new(move |_, _, _, _, _| {
+ refused.then(|| Err(anyhow::anyhow!("no tailnet route")))
+ })));
+ for host in ["127.0.0.1", "localhost", "100.64.0.2"] {
+ assert!(dialer
+ .dial_with(host, port, false, &|| false, |_| Ok(()))
+ .is_err());
+ }
+ assert!(
+ crate::dial_registered(Network::Tailnet, "localhost", port, None)
+ .unwrap()
+ .is_err()
+ );
+ }
+ crate::through::set_dialer(None);
+ assert!(dialer
+ .dial_with("localhost", port, false, &|| false, |_| Ok(()))
+ .is_err());
+ listener.set_nonblocking(true).unwrap();
+ assert_eq!(
+ listener.accept().unwrap_err().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+
+ #[test]
+ fn a_tailnet_cannot_be_overridden_by_system_routing_options() {
+ for (key, value) in [("bindaddress", "127.0.0.1"), ("proxycommand", "example")] {
+ let config = ConfigMap::from([
+ (crate::NETWORK.into(), "tailnet".into()),
+ (key.into(), value.into()),
+ ]);
+ assert!(Dialer::from_config(&config).is_err());
+ }
+ let config = ConfigMap::from([(crate::NETWORK.into(), "unknown".into())]);
+ assert!(Dialer::from_config(&config).is_err());
+ }
+
+ #[test]
+ fn a_bind_address_goes_out_the_os_way() {
+ let _one = DIALER_TESTS.lock().unwrap();
+ let asked = std::sync::Arc::new(Mutex::new(0));
+ crate::through::set_dialer(Some(std::sync::Arc::new({
+ let asked = std::sync::Arc::clone(&asked);
+ move |_host: &str, _port: u16, _family, _timeout, _closed: &dyn Fn() -> bool| {
+ *asked.lock().unwrap() += 1;
+ Some(Err(anyhow::anyhow!("not this way")))
+ }
+ })));
+ let refused = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let refused_port = refused.local_addr().unwrap().port();
+ drop(refused);
+ let mut config = ConfigMap::new();
+ config.insert("bindaddress".to_string(), "127.0.0.1".to_string());
+ let dialed = Dialer::from_config(&config).unwrap().dial_with(
+ "127.0.0.1",
+ refused_port,
+ false,
+ &|| false,
+ |_| Ok(()),
+ );
+ crate::through::set_dialer(None);
+ // Refused by nothing listening there, not by the registered way.
+ let err = format!("{:#}", dialed.unwrap_err());
+ assert!(!err.contains("not this way"), "{}", err);
+ assert_eq!(*asked.lock().unwrap(), 0);
+ }
}
diff --git a/wezterm-ssh/src/lib.rs b/wezterm-ssh/src/lib.rs
index 3b2e4911..789bc994 100644
--- a/wezterm-ssh/src/lib.rs
+++ b/wezterm-ssh/src/lib.rs
@@ -14,6 +14,7 @@ mod sessioninner;
mod sessionwrap;
mod sftp;
mod sftpwrap;
+mod through;
pub use addresses::OTHER_ADDRESSES;
pub use auth::*;
@@ -24,6 +25,7 @@ pub use session::*;
pub use sftp::error::*;
pub use sftp::types::*;
pub use sftp::*;
+pub use through::{dial_registered, set_dialer, AddressFamily, Dialer, Network, NETWORK};
// NOTE: Re-exported as is exposed in a public API of this crate
pub use camino::{Utf8Path, Utf8PathBuf};
diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rs
index ab6701c8..72d19b6a 100644
--- a/wezterm-ssh/src/sessioninner.rs
+++ b/wezterm-ssh/src/sessioninner.rs
@@ -411,6 +411,7 @@ impl SessionInner {
not_this_host: &[(String, u16)],
) -> anyhow::Result<(Socket, Option<KillOnDropChild>, Option<(String, u16)>)> {
self.shutdown.check()?;
+ let dialer = crate::addresses::Dialer::from_config(&self.config)?;
match self.config.get("proxycommand").map(|s| s.as_str()) {
Some("none") | None => {}
Some(proxy_command) => {
@@ -467,7 +468,6 @@ impl SessionInner {
let mut candidates = crate::addresses::candidates(&self.config, hostname, port);
candidates.retain(|address| !not_this_host.contains(address));
- let dialer = crate::addresses::Dialer::from_config(&self.config);
if candidates.len() > 1 {
if verbose {
log::info!("trying {hostname}:{port} at {candidates:?}");
@@ -493,7 +493,10 @@ impl SessionInner {
return Ok((sock, None, Some(reached)));
}
- let sock = dialer.dial_with(hostname, port, verbose, |sock| self.shutdown.watch(sock))?;
+ let closed = || self.shutdown.check().is_err();
+ let sock = dialer.dial_with(hostname, port, verbose, &closed, |sock| {
+ self.shutdown.watch(sock)
+ })?;
self.shutdown.check()?;
Ok((sock, None, None))
}
diff --git a/wezterm-ssh/src/through.rs b/wezterm-ssh/src/through.rs
new file mode 100644
index 00000000..a77b6884
--- /dev/null
+++ b/wezterm-ssh/src/through.rs
@@ -0,0 +1,100 @@
+//! Connections that go another way than the OS network, as an embedded
+//! tailnet reaches its machines. Whoever offers such a way registers it with
+//! [`set_dialer`]; only connections selecting that network use it.
+
+use crate::config::ConfigMap;
+use anyhow::{bail, Context};
+use socket2::Socket;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+/// Selects `system` (the default) or `tailnet` for every candidate address.
+pub const NETWORK: &str = "thinkterm_network";
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum Network {
+ #[default]
+ System,
+ Tailnet,
+}
+
+impl Network {
+ pub fn from_config(config: &ConfigMap) -> anyhow::Result<Self> {
+ match config.get(NETWORK).map(String::as_str) {
+ None | Some("system") => Ok(Self::System),
+ Some("tailnet") => {
+ if config.contains_key("bindaddress")
+ || config
+ .get("proxycommand")
+ .is_some_and(|value| value != "none")
+ {
+ bail!("the embedded tailnet cannot use BindAddress or ProxyCommand");
+ }
+ Ok(Self::Tailnet)
+ }
+ Some(value) => bail!("unknown SSH network {value:?}: use system or tailnet"),
+ }
+ }
+}
+
+/// Which IP addresses a connection may use, as AddressFamily in the SSH
+/// config says.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AddressFamily {
+ Any,
+ Inet,
+ Inet6,
+}
+
+/// Given one of the addresses a host is tried at -- its own as the SSH
+/// config resolved it, or one of its others (see crate::addresses) -- the
+/// IP addresses the connection may use, the ConnectTimeout if one is set,
+/// and a probe that turns true once the session is closed (so a slow dial
+/// can give up): a connected socket, why there is none, or None when the
+/// node cannot reach that host. None never falls back to the OS.
+pub type Dialer = dyn Fn(
+ &str,
+ u16,
+ AddressFamily,
+ Option<Duration>,
+ &dyn Fn() -> bool,
+ ) -> Option<anyhow::Result<Socket>>
+ + Send
+ + Sync;
+
+static DIALER: Mutex<Option<Arc<Dialer>>> = Mutex::new(None);
+
+/// Registers the way sessions selecting the embedded tailnet connect.
+pub fn set_dialer(dialer: Option<Arc<Dialer>>) {
+ *DIALER.lock().unwrap() = dialer;
+}
+
+/// The registered dialer's connection to `host:port` for a connection that
+/// is no SSH session's -- the TLS one a domain bootstrapped over SSH makes
+/// to the same machine. None only when the system network was selected.
+pub fn dial_registered(
+ network: Network,
+ host: &str,
+ port: u16,
+ timeout: Option<Duration>,
+) -> Option<anyhow::Result<Socket>> {
+ (network == Network::Tailnet).then(|| dial(host, port, AddressFamily::Any, timeout, &|| false))
+}
+
+/// The selected tailnet's connection to `host:port`. A missing node or an
+/// unknown host ends the attempt on that network.
+pub(crate) fn dial(
+ host: &str,
+ port: u16,
+ family: AddressFamily,
+ timeout: Option<Duration>,
+ closed: &dyn Fn() -> bool,
+) -> anyhow::Result<Socket> {
+ let dialer = DIALER
+ .lock()
+ .unwrap()
+ .clone()
+ .context("the embedded tailnet is unavailable")?;
+ dialer(host, port, family, timeout, closed)
+ .with_context(|| format!("{host}:{port} is not reachable through the embedded tailnet"))?
+}