local_forward_socket_path built {TMPDIR}/herdr-remote-{pid}-{target}-
{session}.sock. On macOS std::env::temp_dir() returns /var/folders/.../T/
(~49 chars), so a ~24-char target was enough to push the path past
sun_path's 104-byte ceiling and UnixListener::bind rejected it with
"path must be shorter than SUN_LEN". Per-component sanitization capped
each piece at 32 chars but ignored the directory prefix.
The function now picks the first form that fits within 103 bytes (one
byte of headroom for the trailing NUL; portable across macOS' 104 and
Linux's 108) measured via OsStrExt::as_bytes:
1. Readable name in TMPDIR (unchanged when it fits).
2. Hashed short name in TMPDIR.
3. Hashed short name in /tmp (rare fallback for over-long TMPDIRs).
The hash covers the full unsanitized target/session so uniqueness does
not depend on prefix truncation; the truncated prefix is kept only for
debuggability of the short-form filename.
Co-authored-by: jett <jett@pingcap.cn>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1065 lines
33 KiB
Rust
1065 lines
33 KiB
Rust
//! Remote thin-client launcher over SSH command stdio.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fs::{self, File};
|
|
use std::io::{self, IsTerminal, Write as _};
|
|
use std::os::unix::net::{UnixListener, UnixStream};
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::{Command, Output, Stdio};
|
|
|
|
use serde::Deserialize;
|
|
use std::sync::{
|
|
atomic::{AtomicBool, Ordering},
|
|
Arc,
|
|
};
|
|
use std::thread::{self, JoinHandle};
|
|
use std::time::Duration;
|
|
|
|
const BRIDGE_ACCEPT_POLL: Duration = Duration::from_millis(50);
|
|
const BRIDGE_SOCKET_PERMISSION_MODE: u32 = 0o600;
|
|
const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
|
|
const UPDATE_MANIFEST_URL: &str = "https://herdr.dev/latest.json";
|
|
const REMOTE_BINARY_ENV_VAR: &str = "HERDR_REMOTE_BINARY";
|
|
pub(crate) const REATTACH_COMMAND_ENV_VAR: &str = "HERDR_REATTACH_COMMAND";
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub(crate) struct RemoteLaunch {
|
|
pub(crate) target: String,
|
|
}
|
|
|
|
pub(crate) fn extract_remote_args(
|
|
args: &[String],
|
|
) -> Result<(Vec<String>, Option<RemoteLaunch>), String> {
|
|
let mut cleaned = Vec::with_capacity(args.len());
|
|
if let Some(program) = args.first() {
|
|
cleaned.push(program.clone());
|
|
}
|
|
|
|
let mut remote = None;
|
|
let mut index = 1;
|
|
while index < args.len() {
|
|
let arg = &args[index];
|
|
if arg == "--remote" {
|
|
if remote.is_some() {
|
|
return Err("--remote can only be specified once".to_string());
|
|
}
|
|
let Some(value) = args.get(index + 1) else {
|
|
return Err("missing value for --remote".to_string());
|
|
};
|
|
remote = Some(RemoteLaunch {
|
|
target: validate_remote_target(value)?.to_owned(),
|
|
});
|
|
index += 2;
|
|
continue;
|
|
}
|
|
if let Some(value) = arg.strip_prefix("--remote=") {
|
|
if remote.is_some() {
|
|
return Err("--remote can only be specified once".to_string());
|
|
}
|
|
remote = Some(RemoteLaunch {
|
|
target: validate_remote_target(value)?.to_owned(),
|
|
});
|
|
index += 1;
|
|
continue;
|
|
}
|
|
|
|
cleaned.push(arg.clone());
|
|
index += 1;
|
|
}
|
|
|
|
Ok((cleaned, remote))
|
|
}
|
|
|
|
fn validate_remote_target(target: &str) -> Result<&str, String> {
|
|
if target.is_empty() {
|
|
return Err("missing value for --remote".to_string());
|
|
}
|
|
if target.starts_with('-') {
|
|
return Err("--remote target must not start with '-'".to_string());
|
|
}
|
|
Ok(target)
|
|
}
|
|
|
|
pub(crate) fn run_remote(remote: RemoteLaunch) -> io::Result<()> {
|
|
let session_name = crate::session::active_name()
|
|
.unwrap_or_else(|| crate::session::DEFAULT_SESSION_NAME.to_string());
|
|
let local_socket = local_forward_socket_path(&remote.target, &session_name);
|
|
let program = std::env::args()
|
|
.next()
|
|
.unwrap_or_else(|| "herdr".to_string());
|
|
let reattach_command = reattach_command(&program, &remote.target, &session_name);
|
|
let remote_herdr = prepare_remote_herdr(&remote.target)?;
|
|
|
|
let _bridge = SshStdioBridge::start(
|
|
remote.target,
|
|
remote_herdr,
|
|
local_socket.clone(),
|
|
session_name,
|
|
)?;
|
|
|
|
run_client_process(&local_socket, &reattach_command)
|
|
}
|
|
|
|
pub(crate) fn run_remote_client_bridge() -> io::Result<()> {
|
|
ensure_remote_server_running()?;
|
|
|
|
let socket_path = crate::server::headless::client_socket_path();
|
|
let stream = UnixStream::connect(&socket_path).map_err(|err| {
|
|
io::Error::new(
|
|
err.kind(),
|
|
format!(
|
|
"failed to connect to remote Herdr client socket {}: {err}",
|
|
socket_path.display()
|
|
),
|
|
)
|
|
})?;
|
|
|
|
let mut stdout = io::stdout().lock();
|
|
let mut socket_to_stdout = stream.try_clone()?;
|
|
let mut stdin_to_socket = stream;
|
|
|
|
let _upload = thread::spawn(move || {
|
|
let mut stdin = io::stdin();
|
|
let _ = copy_flush(&mut stdin, &mut stdin_to_socket);
|
|
let _ = stdin_to_socket.shutdown(std::net::Shutdown::Write);
|
|
});
|
|
|
|
copy_flush(&mut socket_to_stdout, &mut stdout).map(|_| ())
|
|
}
|
|
|
|
fn ensure_remote_server_running() -> io::Result<()> {
|
|
let socket_path = crate::server::headless::client_socket_path();
|
|
if crate::server::autodetect::is_server_listening() {
|
|
return Ok(());
|
|
}
|
|
|
|
crate::server::autodetect::spawn_server_daemon()?;
|
|
crate::server::autodetect::wait_for_server_socket(&socket_path, Duration::from_secs(5))
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
struct RemotePlatform {
|
|
os: &'static str,
|
|
arch: &'static str,
|
|
}
|
|
|
|
impl RemotePlatform {
|
|
fn from_uname(os: &str, arch: &str) -> Option<Self> {
|
|
let os = match os.trim() {
|
|
"Linux" => "linux",
|
|
"Darwin" => "macos",
|
|
_ => return None,
|
|
};
|
|
let arch = match arch.trim() {
|
|
"x86_64" | "amd64" => "x86_64",
|
|
"aarch64" | "arm64" => "aarch64",
|
|
_ => return None,
|
|
};
|
|
Some(Self { os, arch })
|
|
}
|
|
|
|
fn local() -> Self {
|
|
let os = if cfg!(target_os = "linux") {
|
|
"linux"
|
|
} else if cfg!(target_os = "macos") {
|
|
"macos"
|
|
} else {
|
|
"unknown"
|
|
};
|
|
|
|
let arch = if cfg!(target_arch = "x86_64") {
|
|
"x86_64"
|
|
} else if cfg!(target_arch = "aarch64") {
|
|
"aarch64"
|
|
} else {
|
|
"unknown"
|
|
};
|
|
|
|
Self { os, arch }
|
|
}
|
|
|
|
fn asset_key(&self) -> String {
|
|
format!("{}-{}", self.os, self.arch)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct RemoteHerdr {
|
|
install_suffix: String,
|
|
shell_path: String,
|
|
platform: RemotePlatform,
|
|
}
|
|
|
|
impl RemoteHerdr {
|
|
fn for_platform(platform: RemotePlatform) -> Self {
|
|
let install_suffix = ".local/bin/herdr".to_string();
|
|
let shell_path = format!("\"$HOME/{install_suffix}\"");
|
|
Self {
|
|
install_suffix,
|
|
shell_path,
|
|
platform,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct RemoteUpdateManifest {
|
|
version: String,
|
|
assets: BTreeMap<String, String>,
|
|
}
|
|
|
|
struct InstallSource {
|
|
path: PathBuf,
|
|
temporary_dir: Option<PathBuf>,
|
|
}
|
|
|
|
impl InstallSource {
|
|
fn persistent(path: PathBuf) -> Self {
|
|
Self {
|
|
path,
|
|
temporary_dir: None,
|
|
}
|
|
}
|
|
|
|
fn temporary(path: PathBuf, temporary_dir: PathBuf) -> Self {
|
|
Self {
|
|
path,
|
|
temporary_dir: Some(temporary_dir),
|
|
}
|
|
}
|
|
|
|
fn cleanup(&self) {
|
|
if let Some(dir) = &self.temporary_dir {
|
|
let _ = fs::remove_dir_all(dir);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn prepare_remote_herdr(target: &str) -> io::Result<RemoteHerdr> {
|
|
let platform = detect_remote_platform(target)?;
|
|
let remote_herdr = RemoteHerdr::for_platform(platform);
|
|
let override_binary = remote_binary_override_path()?;
|
|
|
|
if override_binary.is_none() && remote_binary_matches(target, &remote_herdr)? {
|
|
return Ok(remote_herdr);
|
|
}
|
|
|
|
confirm_remote_install(
|
|
target,
|
|
&remote_herdr,
|
|
&install_source_description(&remote_herdr.platform, override_binary.as_deref()),
|
|
)?;
|
|
let source = resolve_install_source(&remote_herdr.platform, override_binary)?;
|
|
let install_result = install_remote_herdr(target, &remote_herdr, &source.path);
|
|
source.cleanup();
|
|
install_result?;
|
|
|
|
if !remote_binary_matches(target, &remote_herdr)? {
|
|
return Err(io::Error::other(format!(
|
|
"installed remote herdr at {}, but it did not report version {CURRENT_VERSION}",
|
|
remote_herdr.shell_path
|
|
)));
|
|
}
|
|
warn_if_remote_bin_not_on_path(target)?;
|
|
|
|
Ok(remote_herdr)
|
|
}
|
|
|
|
fn detect_remote_platform(target: &str) -> io::Result<RemotePlatform> {
|
|
let output = ssh_output(target, "uname -s; uname -m")?;
|
|
if !output.status.success() {
|
|
return Err(command_failed("remote platform detection failed", &output));
|
|
}
|
|
|
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
let mut lines = stdout.lines();
|
|
let os = lines.next().unwrap_or_default();
|
|
let arch = lines.next().unwrap_or_default();
|
|
RemotePlatform::from_uname(os, arch).ok_or_else(|| {
|
|
io::Error::other(format!(
|
|
"unsupported remote platform: {} {}",
|
|
os.trim(),
|
|
arch.trim()
|
|
))
|
|
})
|
|
}
|
|
|
|
fn remote_binary_matches(target: &str, remote_herdr: &RemoteHerdr) -> io::Result<bool> {
|
|
let command = format!("test -x {0} && {0} --version", remote_herdr.shell_path);
|
|
let output = ssh_output(target, &command)?;
|
|
if !output.status.success() {
|
|
return Ok(false);
|
|
}
|
|
|
|
let version = String::from_utf8_lossy(&output.stdout);
|
|
Ok(version.trim() == format!("herdr {CURRENT_VERSION}"))
|
|
}
|
|
|
|
fn remote_binary_override_path() -> io::Result<Option<PathBuf>> {
|
|
let Some(value) = std::env::var_os(REMOTE_BINARY_ENV_VAR) else {
|
|
return Ok(None);
|
|
};
|
|
if value.is_empty() {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
format!("{REMOTE_BINARY_ENV_VAR} must not be empty"),
|
|
));
|
|
}
|
|
|
|
let path = PathBuf::from(value);
|
|
let metadata = fs::metadata(&path).map_err(|err| {
|
|
io::Error::new(
|
|
err.kind(),
|
|
format!(
|
|
"failed to inspect {REMOTE_BINARY_ENV_VAR} path {}: {err}",
|
|
path.display()
|
|
),
|
|
)
|
|
})?;
|
|
if !metadata.is_file() {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
format!(
|
|
"{REMOTE_BINARY_ENV_VAR} path is not a file: {}",
|
|
path.display()
|
|
),
|
|
));
|
|
}
|
|
|
|
Ok(Some(path))
|
|
}
|
|
|
|
fn install_source_description(platform: &RemotePlatform, override_binary: Option<&Path>) -> String {
|
|
if let Some(path) = override_binary {
|
|
return format!("{REMOTE_BINARY_ENV_VAR} ({})", path.display());
|
|
}
|
|
|
|
if *platform == RemotePlatform::local() {
|
|
"the current local herdr binary".to_string()
|
|
} else {
|
|
format!(
|
|
"the {CURRENT_VERSION} release asset for {}",
|
|
platform.asset_key()
|
|
)
|
|
}
|
|
}
|
|
|
|
fn resolve_install_source(
|
|
platform: &RemotePlatform,
|
|
override_binary: Option<PathBuf>,
|
|
) -> io::Result<InstallSource> {
|
|
if let Some(path) = override_binary {
|
|
return Ok(InstallSource::persistent(path));
|
|
}
|
|
|
|
if *platform == RemotePlatform::local() {
|
|
let path = std::env::current_exe()?;
|
|
return Ok(InstallSource::persistent(path));
|
|
}
|
|
|
|
download_release_asset(platform)
|
|
}
|
|
|
|
fn warn_if_remote_bin_not_on_path(target: &str) -> io::Result<()> {
|
|
let output = ssh_output(
|
|
target,
|
|
"case \":$PATH:\" in *\":$HOME/.local/bin:\"*) exit 0 ;; *) exit 1 ;; esac",
|
|
)?;
|
|
if !output.status.success() {
|
|
eprintln!(
|
|
"herdr: installed remote binary to ~/.local/bin/herdr, but ~/.local/bin is not in the remote PATH"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn download_release_asset(platform: &RemotePlatform) -> io::Result<InstallSource> {
|
|
let manifest_output = Command::new("curl")
|
|
.args([
|
|
"-sfL",
|
|
"--retry",
|
|
"3",
|
|
"--connect-timeout",
|
|
"10",
|
|
"--max-time",
|
|
"20",
|
|
UPDATE_MANIFEST_URL,
|
|
])
|
|
.output()
|
|
.map_err(|err| io::Error::new(err.kind(), format!("curl failed: {err}")))?;
|
|
if !manifest_output.status.success() {
|
|
return Err(command_failed(
|
|
"failed to fetch update manifest",
|
|
&manifest_output,
|
|
));
|
|
}
|
|
|
|
let manifest: RemoteUpdateManifest = serde_json::from_slice(&manifest_output.stdout)
|
|
.map_err(|err| io::Error::other(format!("failed to parse update manifest JSON: {err}")))?;
|
|
if manifest.version.trim_start_matches('v') != CURRENT_VERSION {
|
|
return Err(io::Error::other(format!(
|
|
"remote host is {}, but this local herdr is {CURRENT_VERSION} and the latest release manifest is {}; build herdr for the remote platform or install it there manually",
|
|
platform.asset_key(),
|
|
manifest.version
|
|
)));
|
|
}
|
|
|
|
let asset_key = platform.asset_key();
|
|
let url = manifest.assets.get(&asset_key).ok_or_else(|| {
|
|
io::Error::other(format!(
|
|
"no {asset_key} binary in the release manifest for herdr {CURRENT_VERSION}"
|
|
))
|
|
})?;
|
|
|
|
let dir = private_download_dir(&asset_key)?;
|
|
let path = dir.join("herdr.tmp");
|
|
let status = Command::new("curl")
|
|
.args(["-sfL", "--max-time", "120", "-o"])
|
|
.arg(&path)
|
|
.arg(url)
|
|
.status()
|
|
.map_err(|err| io::Error::new(err.kind(), format!("download failed: {err}")))?;
|
|
if !status.success() {
|
|
let _ = fs::remove_dir_all(&dir);
|
|
return Err(io::Error::other("download failed"));
|
|
}
|
|
|
|
Ok(InstallSource::temporary(path, dir))
|
|
}
|
|
|
|
fn private_download_dir(asset_key: &str) -> io::Result<PathBuf> {
|
|
let base = std::env::temp_dir();
|
|
for attempt in 0..100 {
|
|
let dir = base.join(format!(
|
|
"herdr-remote-{}-{}-{attempt}",
|
|
std::process::id(),
|
|
asset_key
|
|
));
|
|
match fs::create_dir(&dir) {
|
|
Ok(()) => return Ok(dir),
|
|
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
|
|
Err(err) => return Err(err),
|
|
}
|
|
}
|
|
|
|
Err(io::Error::new(
|
|
io::ErrorKind::AlreadyExists,
|
|
"failed to create private herdr remote download directory",
|
|
))
|
|
}
|
|
|
|
fn confirm_remote_install(
|
|
target: &str,
|
|
remote_herdr: &RemoteHerdr,
|
|
source_description: &str,
|
|
) -> io::Result<()> {
|
|
if !io::stdin().is_terminal() {
|
|
return Err(io::Error::other(format!(
|
|
"matching remote herdr {CURRENT_VERSION} is not installed at {}; run from an interactive terminal to approve installation",
|
|
remote_herdr.shell_path
|
|
)));
|
|
}
|
|
|
|
eprintln!(
|
|
"matching herdr {CURRENT_VERSION} is not installed on {target} for {}.",
|
|
remote_herdr.platform.asset_key()
|
|
);
|
|
eprint!(
|
|
"Install {} to {}? [Y/n] ",
|
|
source_description, remote_herdr.shell_path
|
|
);
|
|
io::stderr().flush()?;
|
|
|
|
let mut answer = String::new();
|
|
io::stdin().read_line(&mut answer)?;
|
|
let answer = answer.trim().to_ascii_lowercase();
|
|
if answer == "n" || answer == "no" {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::Interrupted,
|
|
"remote herdr installation cancelled",
|
|
));
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn install_remote_herdr(
|
|
target: &str,
|
|
remote_herdr: &RemoteHerdr,
|
|
source_path: &Path,
|
|
) -> io::Result<()> {
|
|
let script = format!(
|
|
r#"dest="$HOME/{install_suffix}"
|
|
dir="${{dest%/*}}"
|
|
mkdir -p "$dir"
|
|
tmp="${{dest}}.tmp.$$"
|
|
cat > "$tmp"
|
|
chmod 755 "$tmp"
|
|
mv "$tmp" "$dest"
|
|
"#,
|
|
install_suffix = remote_herdr.install_suffix
|
|
);
|
|
|
|
let mut child = Command::new("ssh")
|
|
.arg("-T")
|
|
.arg(target)
|
|
.arg(format!("sh -eu -c {}", shell_quote(&script)))
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::inherit())
|
|
.stderr(Stdio::inherit())
|
|
.spawn()
|
|
.map_err(|err| io::Error::new(err.kind(), format!("failed to start ssh install: {err}")))?;
|
|
|
|
let mut source = File::open(source_path)?;
|
|
let copy_result = if let Some(mut stdin) = child.stdin.take() {
|
|
io::copy(&mut source, &mut stdin).map(|_| ())
|
|
} else {
|
|
Err(io::Error::new(
|
|
io::ErrorKind::BrokenPipe,
|
|
"ssh install stdin missing",
|
|
))
|
|
};
|
|
let status = child.wait()?;
|
|
copy_result?;
|
|
|
|
if status.success() {
|
|
Ok(())
|
|
} else {
|
|
Err(io::Error::other(format!(
|
|
"remote install exited with {status}"
|
|
)))
|
|
}
|
|
}
|
|
|
|
fn ssh_output(target: &str, command: &str) -> io::Result<Output> {
|
|
Command::new("ssh")
|
|
.arg("-T")
|
|
.arg(target)
|
|
.arg(command)
|
|
.output()
|
|
}
|
|
|
|
fn remote_bridge_command(remote_herdr: &RemoteHerdr, session_name: &str) -> String {
|
|
let mut command = format!("exec {}", remote_herdr.shell_path);
|
|
if session_name != crate::session::DEFAULT_SESSION_NAME {
|
|
command.push_str(" --session ");
|
|
command.push_str(&shell_quote(session_name));
|
|
}
|
|
command.push_str(" remote-client-bridge");
|
|
command
|
|
}
|
|
|
|
fn reattach_command(program: &str, target: &str, session_name: &str) -> String {
|
|
let program = if program.is_empty() { "herdr" } else { program };
|
|
let mut command = format!("{} --remote {}", shell_quote(program), shell_quote(target));
|
|
if session_name != crate::session::DEFAULT_SESSION_NAME {
|
|
command.push_str(" --session ");
|
|
command.push_str(&shell_quote(session_name));
|
|
}
|
|
command
|
|
}
|
|
|
|
fn shell_quote(value: &str) -> String {
|
|
if !value.is_empty()
|
|
&& value.chars().all(|ch| {
|
|
ch.is_ascii_alphanumeric()
|
|
|| matches!(
|
|
ch,
|
|
'@' | '%' | '_' | '+' | '=' | ':' | ',' | '.' | '/' | '-'
|
|
)
|
|
})
|
|
{
|
|
return value.to_string();
|
|
}
|
|
|
|
format!("'{}'", value.replace('\'', "'\\''"))
|
|
}
|
|
|
|
fn command_failed(context: &str, output: &Output) -> io::Error {
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
let stderr = stderr.trim();
|
|
if stderr.is_empty() {
|
|
io::Error::other(format!("{context}: {}", output.status))
|
|
} else {
|
|
io::Error::other(format!("{context}: {stderr}"))
|
|
}
|
|
}
|
|
|
|
struct SshStdioBridge {
|
|
local_socket: PathBuf,
|
|
should_stop: Arc<AtomicBool>,
|
|
thread: Option<JoinHandle<()>>,
|
|
}
|
|
|
|
impl SshStdioBridge {
|
|
fn start(
|
|
target: String,
|
|
remote_herdr: RemoteHerdr,
|
|
local_socket: PathBuf,
|
|
session_name: String,
|
|
) -> io::Result<Self> {
|
|
let _ = std::fs::remove_file(&local_socket);
|
|
let listener = UnixListener::bind(&local_socket)?;
|
|
crate::ipc::restrict_socket_permissions(&local_socket, BRIDGE_SOCKET_PERMISSION_MODE)?;
|
|
listener.set_nonblocking(true)?;
|
|
|
|
let should_stop = Arc::new(AtomicBool::new(false));
|
|
let thread_stop = Arc::clone(&should_stop);
|
|
let thread = thread::spawn(move || {
|
|
while !thread_stop.load(Ordering::Acquire) {
|
|
match listener.accept() {
|
|
Ok((stream, _addr)) => {
|
|
if let Err(err) = stream.set_nonblocking(false) {
|
|
eprintln!(
|
|
"herdr: remote bridge failed to prepare client socket: {err}"
|
|
);
|
|
continue;
|
|
}
|
|
if let Err(err) =
|
|
bridge_connection(stream, &target, &remote_herdr, &session_name)
|
|
{
|
|
eprintln!("herdr: remote bridge failed: {err}");
|
|
}
|
|
}
|
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
|
|
thread::sleep(BRIDGE_ACCEPT_POLL);
|
|
}
|
|
Err(err) => {
|
|
eprintln!("herdr: remote bridge listener failed: {err}");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
Ok(Self {
|
|
local_socket,
|
|
should_stop,
|
|
thread: Some(thread),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl Drop for SshStdioBridge {
|
|
fn drop(&mut self) {
|
|
self.should_stop.store(true, Ordering::Release);
|
|
let _ = std::fs::remove_file(&self.local_socket);
|
|
if let Some(thread) = self.thread.take() {
|
|
let _ = thread.join();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn bridge_connection(
|
|
stream: UnixStream,
|
|
target: &str,
|
|
remote_herdr: &RemoteHerdr,
|
|
session_name: &str,
|
|
) -> io::Result<()> {
|
|
let mut command = Command::new("ssh");
|
|
command
|
|
.arg("-T")
|
|
.arg(target)
|
|
.arg(remote_bridge_command(remote_herdr, session_name));
|
|
command
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::inherit());
|
|
|
|
let mut child = command
|
|
.spawn()
|
|
.map_err(|err| io::Error::new(err.kind(), format!("failed to start ssh bridge: {err}")))?;
|
|
let mut child_stdin = child
|
|
.stdin
|
|
.take()
|
|
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "ssh bridge stdin missing"))?;
|
|
let mut child_stdout = child
|
|
.stdout
|
|
.take()
|
|
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "ssh bridge stdout missing"))?;
|
|
let mut stream_to_child = stream.try_clone()?;
|
|
let mut child_to_stream = stream;
|
|
|
|
let upload = thread::spawn(move || {
|
|
let _ = copy_flush(&mut stream_to_child, &mut child_stdin);
|
|
});
|
|
let download = thread::spawn(move || {
|
|
let _ = copy_flush(&mut child_stdout, &mut child_to_stream);
|
|
let _ = child_to_stream.shutdown(std::net::Shutdown::Write);
|
|
});
|
|
|
|
let status = child.wait()?;
|
|
let _ = upload.join();
|
|
let _ = download.join();
|
|
|
|
if status.success() {
|
|
Ok(())
|
|
} else {
|
|
Err(io::Error::new(
|
|
io::ErrorKind::ConnectionAborted,
|
|
format!("ssh bridge exited with {status}"),
|
|
))
|
|
}
|
|
}
|
|
|
|
fn copy_flush<R: io::Read, W: io::Write>(reader: &mut R, writer: &mut W) -> io::Result<u64> {
|
|
let mut buffer = [0_u8; 16 * 1024];
|
|
let mut total = 0;
|
|
|
|
loop {
|
|
let bytes_read = match reader.read(&mut buffer) {
|
|
Ok(0) => return Ok(total),
|
|
Ok(bytes_read) => bytes_read,
|
|
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
|
Err(err) => return Err(err),
|
|
};
|
|
|
|
writer.write_all(&buffer[..bytes_read])?;
|
|
writer.flush()?;
|
|
total += bytes_read as u64;
|
|
}
|
|
}
|
|
|
|
fn run_client_process(local_socket: &Path, reattach_command: &str) -> io::Result<()> {
|
|
let exe = std::env::current_exe()?;
|
|
let status = Command::new(exe)
|
|
.arg("client")
|
|
.env(
|
|
crate::server::headless::CLIENT_SOCKET_PATH_ENV_VAR,
|
|
local_socket,
|
|
)
|
|
.env("HERDR_RENDER_ENCODING", "terminal-ansi")
|
|
.env(REATTACH_COMMAND_ENV_VAR, reattach_command)
|
|
.env_remove(crate::api::SOCKET_PATH_ENV_VAR)
|
|
.stdin(Stdio::inherit())
|
|
.stdout(Stdio::inherit())
|
|
.stderr(Stdio::inherit())
|
|
.status()?;
|
|
|
|
if status.success() {
|
|
Ok(())
|
|
} else {
|
|
Err(io::Error::new(
|
|
io::ErrorKind::Interrupted,
|
|
format!("remote client exited with {status}"),
|
|
))
|
|
}
|
|
}
|
|
|
|
fn local_forward_socket_path(target: &str, session_name: &str) -> PathBuf {
|
|
let pid = std::process::id();
|
|
let target_clean = sanitize_path_component(target);
|
|
let session_clean = sanitize_path_component(session_name);
|
|
|
|
let tmpdir = std::env::temp_dir();
|
|
let readable = tmpdir.join(format!(
|
|
"herdr-remote-{pid}-{target_clean}-{session_clean}.sock"
|
|
));
|
|
if fits_unix_socket_path(&readable) {
|
|
return readable;
|
|
}
|
|
|
|
// macOS' per-user TMPDIR (~49 chars under /var/folders/...) can push the
|
|
// readable name past sun_path's 104-byte ceiling. Fall back to a hashed
|
|
// short name in TMPDIR, then to /tmp as a last resort when TMPDIR itself
|
|
// is longer than the budget. The hash covers the full unsanitized
|
|
// target/session so uniqueness does not depend on the prefix truncation;
|
|
// the prefix is kept only for debuggability.
|
|
let target_prefix: String = target_clean.chars().take(8).collect();
|
|
let hash = short_socket_hash(target, session_name);
|
|
let short_name = format!("herdr-r-{pid}-{target_prefix}-{hash}.sock");
|
|
let short_in_tmp = tmpdir.join(&short_name);
|
|
if fits_unix_socket_path(&short_in_tmp) {
|
|
return short_in_tmp;
|
|
}
|
|
PathBuf::from("/tmp").join(short_name)
|
|
}
|
|
|
|
fn fits_unix_socket_path(path: &Path) -> bool {
|
|
use std::os::unix::ffi::OsStrExt;
|
|
// sun_path is byte-limited: 104 bytes on macOS, 108 on Linux. Reserve
|
|
// 1 byte for the trailing NUL and use the smaller cap for portability.
|
|
const MAX: usize = 103;
|
|
path.as_os_str().as_bytes().len() <= MAX
|
|
}
|
|
|
|
fn short_socket_hash(target: &str, session: &str) -> String {
|
|
use std::collections::hash_map::DefaultHasher;
|
|
use std::hash::{Hash, Hasher};
|
|
let mut hasher = DefaultHasher::new();
|
|
target.hash(&mut hasher);
|
|
0u8.hash(&mut hasher);
|
|
session.hash(&mut hasher);
|
|
format!("{:016x}", hasher.finish())
|
|
}
|
|
|
|
fn sanitize_path_component(input: &str) -> String {
|
|
let sanitized: String = input
|
|
.chars()
|
|
.map(|ch| {
|
|
if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '-') {
|
|
ch
|
|
} else {
|
|
'-'
|
|
}
|
|
})
|
|
.collect();
|
|
|
|
sanitized.trim_matches('-').chars().take(32).collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn bridge_socket_is_user_only() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
|
|
let socket = std::env::temp_dir().join(format!(
|
|
"herdr-bridge-permissions-test-{}.sock",
|
|
std::process::id()
|
|
));
|
|
let remote_herdr = RemoteHerdr::for_platform(RemotePlatform {
|
|
os: "linux",
|
|
arch: "x86_64",
|
|
});
|
|
let bridge = SshStdioBridge::start(
|
|
"example".to_string(),
|
|
remote_herdr,
|
|
socket.clone(),
|
|
"default".to_string(),
|
|
)
|
|
.expect("start bridge listener");
|
|
|
|
let mode = std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777;
|
|
assert_eq!(mode, BRIDGE_SOCKET_PERMISSION_MODE);
|
|
|
|
drop(bridge);
|
|
let _ = std::fs::remove_file(socket);
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_removes_space_form() {
|
|
let args = vec![
|
|
"herdr".into(),
|
|
"--remote".into(),
|
|
"dev".into(),
|
|
"--help".into(),
|
|
];
|
|
let (cleaned, remote) = extract_remote_args(&args).unwrap();
|
|
assert_eq!(cleaned, vec!["herdr", "--help"]);
|
|
assert_eq!(remote.unwrap().target, "dev");
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_removes_equals_form() {
|
|
let args = vec!["herdr".into(), "--remote=user@host".into()];
|
|
let (cleaned, remote) = extract_remote_args(&args).unwrap();
|
|
assert_eq!(cleaned, vec!["herdr"]);
|
|
assert_eq!(remote.unwrap().target, "user@host");
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_requires_value() {
|
|
let args = vec!["herdr".into(), "--remote".into()];
|
|
let err = extract_remote_args(&args).unwrap_err();
|
|
assert_eq!(err, "missing value for --remote");
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_rejects_empty_value() {
|
|
let args = vec!["herdr".into(), "--remote=".into()];
|
|
let err = extract_remote_args(&args).unwrap_err();
|
|
assert_eq!(err, "missing value for --remote");
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_rejects_duplicate_values() {
|
|
let args = vec![
|
|
"herdr".into(),
|
|
"--remote=dev".into(),
|
|
"--remote=prod".into(),
|
|
];
|
|
let err = extract_remote_args(&args).unwrap_err();
|
|
assert_eq!(err, "--remote can only be specified once");
|
|
}
|
|
|
|
#[test]
|
|
fn extract_remote_args_rejects_option_like_target() {
|
|
let args = vec!["herdr".into(), "--remote".into(), "-oProxyCommand=x".into()];
|
|
let err = extract_remote_args(&args).unwrap_err();
|
|
assert_eq!(err, "--remote target must not start with '-'");
|
|
}
|
|
|
|
#[test]
|
|
fn sanitize_path_component_removes_shell_sensitive_chars() {
|
|
assert_eq!(sanitize_path_component("user@host:22"), "user-host-22");
|
|
}
|
|
|
|
#[test]
|
|
fn remote_platform_maps_uname_values() {
|
|
assert_eq!(
|
|
RemotePlatform::from_uname("Linux", "amd64")
|
|
.unwrap()
|
|
.asset_key(),
|
|
"linux-x86_64"
|
|
);
|
|
assert_eq!(
|
|
RemotePlatform::from_uname("Darwin", "arm64")
|
|
.unwrap()
|
|
.asset_key(),
|
|
"macos-aarch64"
|
|
);
|
|
assert!(RemotePlatform::from_uname("FreeBSD", "x86_64").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn reattach_command_includes_remote_and_session() {
|
|
assert_eq!(
|
|
reattach_command("target/release/herdr", "user@host", "work"),
|
|
"target/release/herdr --remote user@host --session work"
|
|
);
|
|
assert_eq!(
|
|
reattach_command("herdr", "host name", crate::session::DEFAULT_SESSION_NAME),
|
|
"herdr --remote 'host name'"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn remote_bridge_command_uses_installed_binary() {
|
|
let remote_herdr = RemoteHerdr::for_platform(RemotePlatform {
|
|
os: "linux",
|
|
arch: "x86_64",
|
|
});
|
|
assert_eq!(
|
|
remote_bridge_command(&remote_herdr, crate::session::DEFAULT_SESSION_NAME),
|
|
"exec \"$HOME/.local/bin/herdr\" remote-client-bridge"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn install_source_description_uses_override_binary() {
|
|
let platform = RemotePlatform {
|
|
os: "linux",
|
|
arch: "aarch64",
|
|
};
|
|
assert_eq!(
|
|
install_source_description(&platform, Some(Path::new("/tmp/herdr-aarch64"))),
|
|
"HERDR_REMOTE_BINARY (/tmp/herdr-aarch64)"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn resolve_install_source_uses_override_binary_without_temporary_cleanup() {
|
|
let platform = RemotePlatform {
|
|
os: "linux",
|
|
arch: "aarch64",
|
|
};
|
|
let source = resolve_install_source(&platform, Some(PathBuf::from("/tmp/herdr-aarch64")))
|
|
.expect("override source");
|
|
assert_eq!(source.path, PathBuf::from("/tmp/herdr-aarch64"));
|
|
assert!(source.temporary_dir.is_none());
|
|
}
|
|
|
|
fn remote_env_lock() -> &'static std::sync::Mutex<()> {
|
|
static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
|
|
LOCK.get_or_init(|| std::sync::Mutex::new(()))
|
|
}
|
|
|
|
fn socket_path_byte_len(path: &Path) -> usize {
|
|
use std::os::unix::ffi::OsStrExt;
|
|
path.as_os_str().as_bytes().len()
|
|
}
|
|
|
|
#[test]
|
|
fn local_forward_socket_path_uses_readable_name_when_it_fits() {
|
|
let _guard = remote_env_lock().lock().unwrap();
|
|
// Short target + session leave plenty of room — keep the human-
|
|
// readable form so the socket path stays grep-friendly.
|
|
let path = local_forward_socket_path("dev", "default");
|
|
let filename = path
|
|
.file_name()
|
|
.and_then(|s| s.to_str())
|
|
.unwrap_or("")
|
|
.to_string();
|
|
assert!(
|
|
filename.starts_with("herdr-remote-"),
|
|
"expected readable name, got {filename}"
|
|
);
|
|
assert!(filename.contains("-dev-default."), "got {filename}");
|
|
assert!(
|
|
fits_unix_socket_path(&path),
|
|
"socket path too long: {} ({} bytes)",
|
|
path.display(),
|
|
socket_path_byte_len(&path)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn local_forward_socket_path_fits_in_sun_path() {
|
|
let _guard = remote_env_lock().lock().unwrap();
|
|
// Worst case for the readable form: macOS-style 49-char TMPDIR +
|
|
// max-length sanitized components. Should fall back to the hashed
|
|
// short name, which fits under TMPDIR.
|
|
let target = "longish-host.example.com";
|
|
let session = "a-fairly-long-session-name-here";
|
|
let path = local_forward_socket_path(target, session);
|
|
assert!(
|
|
fits_unix_socket_path(&path),
|
|
"socket path too long for sun_path: {} ({} bytes)",
|
|
path.display(),
|
|
socket_path_byte_len(&path)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn local_forward_socket_path_falls_back_to_tmp_when_dir_is_long() {
|
|
let _guard = remote_env_lock().lock().unwrap();
|
|
// Force a TMPDIR long enough that even the hashed short name cannot
|
|
// fit inside it. The fallback should drop to /tmp.
|
|
let prior = std::env::var_os("TMPDIR");
|
|
let long_dir = std::env::temp_dir().join("a".repeat(80));
|
|
let _ = fs::create_dir_all(&long_dir);
|
|
std::env::set_var("TMPDIR", &long_dir);
|
|
|
|
let path = local_forward_socket_path("longish-host.example.com", "default");
|
|
let fits = fits_unix_socket_path(&path);
|
|
let parent = path.parent().map(Path::to_path_buf);
|
|
let filename = path
|
|
.file_name()
|
|
.and_then(|s| s.to_str())
|
|
.unwrap_or("")
|
|
.to_string();
|
|
|
|
match prior {
|
|
Some(v) => std::env::set_var("TMPDIR", v),
|
|
None => std::env::remove_var("TMPDIR"),
|
|
}
|
|
let _ = fs::remove_dir_all(&long_dir);
|
|
|
|
assert!(fits, "fallback path still overflows: {}", path.display());
|
|
assert_eq!(parent.as_deref(), Some(Path::new("/tmp")));
|
|
assert!(
|
|
filename.starts_with("herdr-r-"),
|
|
"expected hashed fallback, got {filename}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn install_source_cleanup_removes_temporary_directory() {
|
|
let dir = std::env::temp_dir().join(format!(
|
|
"herdr-install-source-cleanup-test-{}",
|
|
std::process::id()
|
|
));
|
|
let _ = fs::remove_dir_all(&dir);
|
|
fs::create_dir(&dir).expect("create temp dir");
|
|
let path = dir.join("herdr.tmp");
|
|
fs::write(&path, b"test").expect("write temp file");
|
|
|
|
InstallSource::temporary(path, dir.clone()).cleanup();
|
|
|
|
assert!(!dir.exists());
|
|
}
|
|
}
|