use std::{path::PathBuf, process::Command};
use anyhow::{Context, Result, bail};
use clap::{Args, Subcommand};
#[derive(Debug, Args)]
pub struct TmuxCli {
#[arg(long, global = true)]
on: Option<String>,
#[arg(long, global = true)]
socket: Option<PathBuf>,
#[arg(long, global = true, requires = "on")]
remote_program: Option<String>,
#[command(subcommand)]
action: TmuxAction,
}
#[derive(Debug, Subcommand)]
enum TmuxAction {
Clients {
#[arg(long)]
json: bool,
},
List {
#[arg(long)]
json: bool,
},
Attach { session: String },
}
enum TmuxTarget {
Local,
Ssh(String),
}
impl TmuxTarget {
fn parse(on: Option<String>) -> Result<Self> {
match on {
None => Ok(Self::Local),
Some(host)
if !host.is_empty()
&& !host.starts_with('-')
&& !host.chars().any(|c| c.is_whitespace() || c.is_control()) =>
{
Ok(Self::Ssh(host))
}
Some(_) => {
bail!("SSH target must be a nonempty host alias, not an option or whitespace")
}
}
}
}
pub fn run(cli: TmuxCli) -> Result<()> {
match TmuxTarget::parse(cli.on.clone())? {
TmuxTarget::Local => run_local(cli),
TmuxTarget::Ssh(host) => handoff(&mut ssh_command(&cli, &host)?),
}
}
fn ssh_command(cli: &TmuxCli, host: &str) -> Result<Command> {
let program = cli.remote_program.as_deref().unwrap_or("agent-ssh");
if program.is_empty() || program.chars().any(char::is_control) {
bail!(
"remote program must be a nonempty executable name or path without control characters"
);
}
let mut remote = vec![program.to_owned(), "tmux".into()];
if let Some(socket) = &cli.socket {
remote.extend([
"--socket".into(),
socket
.to_str()
.context("remote socket path must be UTF-8")?
.to_owned(),
]);
}
let attach = match &cli.action {
TmuxAction::Clients { json } => {
remote.push("clients".into());
if *json {
remote.push("--json".into());
}
false
}
TmuxAction::List { json } => {
remote.push("list".into());
if *json {
remote.push("--json".into());
}
false
}
TmuxAction::Attach { session } => {
remote.extend(["attach".into(), "--".into(), session.clone()]);
true
}
};
#[cfg(windows)]
let mut command = Command::new(crate::terminal::SSH_EXE);
#[cfg(not(windows))]
let mut command = Command::new("ssh");
command.args(["-o", "ConnectTimeout=8"]);
if attach {
command.arg("-t");
#[cfg(windows)]
command.env(
"TERM",
ssh_terminal_type(std::env::var_os("TERM").as_deref()),
);
}
command.arg("--").arg(host).arg(
remote
.iter()
.map(|arg| shell_quote(arg))
.collect::<Vec<_>>()
.join(" "),
);
Ok(command)
}
#[cfg(windows)]
fn ssh_terminal_type(term: Option<&std::ffi::OsStr>) -> &std::ffi::OsStr {
term.filter(|value| !value.is_empty() && *value != "dumb")
.unwrap_or_else(|| std::ffi::OsStr::new("xterm-256color"))
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
#[cfg(unix)]
fn run_local(cli: TmuxCli) -> Result<()> {
use serde::Serialize;
use std::time::Duration;
use tmux_session::{Limits, Runtime, SessionName, Tmux};
#[derive(Serialize)]
struct SessionSummary {
id: String,
name: String,
windows: u32,
attached_clients: u32,
}
let limits = Limits {
timeout: Duration::from_secs(8),
..Limits::default()
};
let mut builder = Tmux::builder().limits(limits);
if let Some(socket) = cli.socket {
builder = builder.socket_path(socket);
}
let server = builder
.build()
.context("could not select the tmux server")?;
let runtime = Runtime::new()?;
match cli.action {
TmuxAction::Clients { json } => {
let snapshot = crate::observations::observe(&server, &runtime)?;
if json {
println!("{}", serde_json::to_string_pretty(&snapshot)?);
} else {
println!("{:<8} {:<8} SESSION", "PID", "TTY");
for client in snapshot.clients {
println!(
"{:<8} {:<8} {}",
client.pid,
client.tty,
serde_json::to_string(&client.session)?
);
}
}
Ok(())
}
TmuxAction::List { json } => {
let sessions = runtime.block_on(server.sessions())?;
let summaries = sessions
.iter()
.map(|session| {
Ok(SessionSummary {
id: session.id.to_string(),
name: session
.name
.to_str()
.context("session name is not UTF-8")?
.to_owned(),
windows: session.window_count,
attached_clients: session.attached_clients,
})
})
.collect::<Result<Vec<_>>>()?;
if json {
println!("{}", serde_json::to_string_pretty(&summaries)?);
} else {
println!("{:<8} {:<8} {:<8} NAME", "ID", "WINDOWS", "CLIENTS");
for session in summaries {
println!(
"{:<8} {:<8} {:<8} {}",
session.id,
session.windows,
session.attached_clients,
serde_json::to_string(&session.name)?
);
}
}
Ok(())
}
TmuxAction::Attach { session } => {
let name = SessionName::new(session.as_str())?;
let target = runtime
.block_on(server.session_exact(&name))?
.with_context(|| format!("tmux session does not exist: {session:?}"))?;
let mut command = server.attach_command(&target);
drop(runtime);
handoff(&mut command)
}
}
}
#[cfg(not(unix))]
fn run_local(_cli: TmuxCli) -> Result<()> {
bail!("local tmux requires Unix; use --on HOST to attach through an installed Unix agent-ssh")
}
fn handoff(command: &mut Command) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
Err(command.exec()).context("could not hand off the terminal")
}
#[cfg(not(unix))]
{
let status = command
.status()
.context("could not hand off the terminal")?;
if !status.success() {
bail!("terminal attachment exited with {status}");
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ssh_preserves_remote_arguments_as_literal_shell_words() {
let cli = TmuxCli {
on: Some("example-host".into()),
socket: Some("/tmp/a socket 'x'".into()),
remote_program: Some("/opt/agent tools/agent-ssh".into()),
action: TmuxAction::Attach {
session: "name; $(touch wrong) 'quoted'".into(),
},
};
let command = ssh_command(&cli, "example-host").unwrap();
let args = command
.get_args()
.map(|x| x.to_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(
&args[..5],
&["-o", "ConnectTimeout=8", "-t", "--", "example-host"]
);
assert_eq!(
args[5],
r#"'/opt/agent tools/agent-ssh' 'tmux' '--socket' '/tmp/a socket '\''x'\''' 'attach' '--' 'name; $(touch wrong) '\''quoted'\'''"#
);
}
#[test]
fn list_does_not_allocate_a_remote_pty_or_forward_its_destination() {
let cli = TmuxCli {
on: Some("example-host".into()),
socket: None,
remote_program: None,
action: TmuxAction::List { json: true },
};
let command = ssh_command(&cli, "example-host").unwrap();
let args = command
.get_args()
.map(|x| x.to_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(
args,
[
"-o",
"ConnectTimeout=8",
"--",
"example-host",
"'agent-ssh' 'tmux' 'list' '--json'"
]
);
}
#[test]
fn ssh_rejects_destination_option_injection() {
for host in ["", "-oProxyCommand=anything", "two hosts", "host\nother"] {
assert!(TmuxTarget::parse(Some(host.into())).is_err());
}
}
#[cfg(windows)]
#[test]
fn windows_ssh_pty_has_a_usable_terminal_type() {
use std::ffi::OsStr;
for term in [None, Some(OsStr::new("")), Some(OsStr::new("dumb"))] {
assert_eq!(ssh_terminal_type(term), "xterm-256color");
}
assert_eq!(
ssh_terminal_type(Some(OsStr::new("xterm-direct"))),
"xterm-direct"
);
}
}