use std::collections::HashMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Output;
use std::time::Duration;
use std::time::Instant;
use crate::terminal::backend::SessionBackend;
use crate::terminal::error::SessionError;
use crate::terminal::proc::run_with_timeout;
use crate::terminal::proc::sleep_secs;
use crate::terminal::session::Session;
const TMUX: &str = "tmux";
const SESSION: &str = "termproof";
const TMUX_TIMEOUT: Duration = Duration::from_secs(30);
const KILL_SERVER_TIMEOUT: Duration = Duration::from_secs(5);
const POLL_SECONDS: f64 = 0.5;
const KEYS: [(&str, &str); 13] = [
("enter", "Enter"),
("tab", "Tab"),
("escape", "Escape"),
("backspace", "BSpace"),
("up", "Up"),
("down", "Down"),
("left", "Left"),
("right", "Right"),
("ctrl-c", "C-c"),
("ctrl-d", "C-d"),
("ctrl-p", "C-p"),
("ctrl-[", "Escape"),
("f13", "F13"),
];
fn tmux_key(key: &str) -> Option<&'static str> {
let lowered = key.to_ascii_lowercase();
KEYS.iter()
.find(|(name, _)| *name == lowered)
.map(|(_, tmux)| *tmux)
}
pub struct TmuxSession {
socket: String,
argv: Vec<String>,
cast_path: PathBuf,
cols: u16,
rows: u16,
exit_code: Option<i32>,
closed: bool,
screen: String,
raw: String,
}
impl TmuxSession {
fn tmux(&self, args: &[&str]) -> Result<Output, SessionError> {
let mut cmd = Command::new(TMUX);
cmd.arg("-S").arg(&self.socket).args(args);
match run_with_timeout(cmd, TMUX_TIMEOUT) {
Ok(output) if output.status.success() => Ok(output),
Ok(output) => Err(SessionError::Io(format!(
"tmux {:?} exited {}: {}",
args,
output.status,
String::from_utf8_lossy(&output.stderr).trim_end()
))),
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => {
let mut kill = Command::new(TMUX);
kill.arg("-S").arg(&self.socket).arg("kill-server");
let _ = run_with_timeout(kill, KILL_SERVER_TIMEOUT);
Err(SessionError::Timeout(format!(
"tmux {args:?} timed out after {}s; server killed",
TMUX_TIMEOUT.as_secs()
)))
}
Err(error) => Err(SessionError::Io(error.to_string())),
}
}
fn capture(&self, escapes: bool) -> String {
let mut args = vec!["capture-pane", "-t", SESSION, "-p"];
if escapes {
args.push("-e");
}
self.tmux(&args)
.map(|o| String::from_utf8_lossy(&o.stdout).to_string())
.unwrap_or_default()
}
fn refresh(&mut self) {
self.screen = self.capture(false);
self.raw = self.capture(true);
}
fn settled_body(&self) -> String {
let lines: Vec<&str> = self.screen.lines().collect();
let keep = lines.len().saturating_sub(2);
lines[..keep].join("\n")
}
}
impl Session for TmuxSession {
fn send_text(&mut self, text: &str) -> Result<(), SessionError> {
self.tmux(&["send-keys", "-t", SESSION, "-l", "--", text])?;
sleep_secs(0.1);
self.refresh();
Ok(())
}
fn send_line(&mut self, text: &str) -> Result<(), SessionError> {
self.send_text(text)?;
self.press("enter")
}
fn press(&mut self, key: &str) -> Result<(), SessionError> {
let Some(name) = tmux_key(key) else {
return Err(SessionError::Config(format!(
"unknown key {key:?}; known keys: {}",
KEYS.iter().map(|(k, _)| *k).collect::<Vec<_>>().join(", ")
)));
};
self.tmux(&["send-keys", "-t", SESSION, name])?;
sleep_secs(0.1);
self.refresh();
Ok(())
}
fn wait_for_text(&mut self, text: &str, timeout: Duration) -> Result<bool, SessionError> {
let deadline = Instant::now() + timeout;
loop {
self.refresh();
if self.screen.contains(text) || self.raw.contains(text) {
return Ok(true);
}
if Instant::now() >= deadline {
return Ok(false);
}
sleep_secs(POLL_SECONDS);
}
}
fn wait_for_idle(&mut self, stable: Duration, timeout: Duration) -> Result<bool, SessionError> {
let deadline = Instant::now() + timeout;
self.refresh();
let mut previous = self.settled_body();
let mut stable_since = Instant::now();
loop {
if stable_since.elapsed() >= stable {
return Ok(true);
}
if Instant::now() >= deadline {
return Ok(false);
}
sleep_secs(POLL_SECONDS);
self.refresh();
let body = self.settled_body();
if body != previous {
previous = body;
stable_since = Instant::now();
}
}
}
fn wait_for_exit(&mut self, timeout: Duration) -> Result<Option<i32>, SessionError> {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if !self.is_alive() {
return Ok(self.exit_code);
}
sleep_secs(POLL_SECONDS);
}
Ok(None)
}
fn read_available(&mut self, _timeout: Duration) -> Result<(), SessionError> {
self.refresh();
Ok(())
}
fn is_alive(&mut self) -> bool {
if self.closed {
return false;
}
self.tmux(&["has-session", "-t", SESSION]).is_ok()
}
fn close(&mut self) -> Result<(), SessionError> {
if self.closed {
return Ok(());
}
self.refresh();
let _ = self.tmux(&["kill-server"]);
self.closed = true;
Ok(())
}
fn screen(&self) -> &str {
&self.screen
}
fn raw_output(&self) -> &str {
&self.raw
}
fn screen_attributed(&mut self) -> Option<crate::terminal::attributed::AttributedScreen> {
self.refresh();
Some(
crate::terminal::attributed::attributed_screen_from_ansi_text(
&self.raw,
self.cols as usize,
self.rows as usize,
),
)
}
fn exit_code(&self) -> Option<i32> {
self.exit_code
}
fn cols(&self) -> u16 {
self.cols
}
fn rows(&self) -> u16 {
self.rows
}
fn argv(&self) -> &[String] {
&self.argv
}
fn cast_path(&self) -> &Path {
&self.cast_path
}
}
impl Drop for TmuxSession {
fn drop(&mut self) {
if !self.closed {
let _ = self.close();
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct TmuxBackend;
impl SessionBackend for TmuxBackend {
fn create_session(
&self,
argv: Vec<String>,
cast_path: PathBuf,
cwd: Option<String>,
env: HashMap<String, String>,
cols: u16,
rows: u16,
) -> Result<Box<dyn Session>, SessionError> {
if argv.is_empty() {
return Err(SessionError::Config("argv is empty".to_string()));
}
let dir = cast_path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("."));
fs::create_dir_all(&dir).map_err(|e| SessionError::Io(e.to_string()))?;
let socket = dir.join("tmux.sock").to_string_lossy().to_string();
let workdir = cwd.unwrap_or_else(|| dir.to_string_lossy().to_string());
let wrapper = write_launch_script(&dir, &env, &argv)?;
let mut session = TmuxSession {
socket,
argv,
cast_path,
cols,
rows,
exit_code: None,
closed: false,
screen: String::new(),
raw: String::new(),
};
let (cols_s, rows_s) = (cols.to_string(), rows.to_string());
session.tmux(&[
"new-session",
"-d",
"-s",
SESSION,
"-x",
&cols_s,
"-y",
&rows_s,
"-c",
&workdir,
"sh",
&wrapper,
])?;
session.refresh();
Ok(Box::new(session))
}
fn name(&self) -> &str {
"tmux"
}
}
fn write_launch_script(
dir: &Path,
env: &HashMap<String, String>,
argv: &[String],
) -> Result<String, SessionError> {
let mut script = String::from("#!/bin/sh\n");
let mut keys: Vec<&String> = env.keys().collect();
keys.sort();
for k in keys {
script.push_str(&format!("export {}={}\n", k, shell_quote(&env[k])));
}
script.push_str(&format!("exec {}\n", shell_join(argv)));
let path = dir.join("launch.sh");
fs::write(&path, script).map_err(|e| SessionError::Io(e.to_string()))?;
let mut perms = fs::metadata(&path)
.map_err(|e| SessionError::Io(e.to_string()))?
.permissions();
perms.set_mode(0o755);
fs::set_permissions(&path, perms).map_err(|e| SessionError::Io(e.to_string()))?;
Ok(path.to_string_lossy().to_string())
}
pub fn shell_quote(s: &str) -> String {
if !s.is_empty()
&& s.chars().all(|c| {
c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '/' | '=' | ':' | '-' | ',')
})
{
return s.to_string();
}
format!("'{}'", s.replace('\'', "'\\''"))
}
pub fn shell_join(args: &[String]) -> String {
args.iter()
.map(|a| shell_quote(a))
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_keys_translate() {
assert_eq!(tmux_key("enter"), Some("Enter"));
assert_eq!(tmux_key("ctrl-c"), Some("C-c"));
assert_eq!(tmux_key("backspace"), Some("BSpace"));
}
#[test]
fn key_lookup_is_case_insensitive() {
assert_eq!(tmux_key("Enter"), Some("Enter"));
assert_eq!(tmux_key("CTRL-D"), Some("C-d"));
}
#[test]
fn an_unknown_key_is_none_rather_than_a_guess() {
assert_eq!(tmux_key("hyperspace"), None);
}
#[test]
fn ctrl_bracket_maps_to_escape() {
assert_eq!(tmux_key("ctrl-["), Some("Escape"));
}
#[test]
fn plain_arguments_are_left_alone() {
assert_eq!(shell_quote("/bin/app"), "/bin/app");
assert_eq!(shell_quote("--flag=value"), "--flag=value");
}
#[test]
fn arguments_needing_quotes_get_them() {
assert_eq!(shell_quote("two words"), "'two words'");
assert_eq!(shell_quote(""), "''");
}
#[test]
fn embedded_single_quotes_survive() {
assert_eq!(shell_quote("it's"), r#"'it'\''s'"#);
}
#[test]
fn joining_quotes_each_argument() {
let args = vec!["/bin/app".to_string(), "a b".to_string()];
assert_eq!(shell_join(&args), "/bin/app 'a b'");
}
#[test]
fn the_launch_script_exports_then_execs() {
let dir = tempfile::tempdir().expect("tempdir");
let mut env = HashMap::new();
env.insert("B".to_string(), "two words".to_string());
env.insert("A".to_string(), "one".to_string());
let path = write_launch_script(
dir.path(),
&env,
&["/bin/app".to_string(), "--x".to_string()],
)
.expect("script written");
let body = fs::read_to_string(&path).expect("readable");
assert!(body.starts_with("#!/bin/sh\n"), "{body}");
let a = body.find("export A=").expect("A exported");
let b = body.find("export B=").expect("B exported");
assert!(a < b, "exports should be sorted:\n{body}");
assert!(body.contains("export B='two words'"), "{body}");
assert!(body.trim_end().ends_with("exec /bin/app --x"), "{body}");
}
#[test]
fn the_launch_script_is_executable() {
let dir = tempfile::tempdir().expect("tempdir");
let path = write_launch_script(dir.path(), &HashMap::new(), &["/bin/true".to_string()])
.expect("script written");
let mode = fs::metadata(&path).expect("metadata").permissions().mode();
assert_eq!(mode & 0o111, 0o111, "should be executable, got {mode:o}");
}
#[test]
fn an_empty_argv_is_refused() {
let dir = tempfile::tempdir().expect("tempdir");
let Err(err) = TmuxBackend.create_session(
vec![],
dir.path().join("s.cast"),
None,
HashMap::new(),
80,
24,
) else {
panic!("empty argv should be refused");
};
assert!(matches!(err, SessionError::Config(_)), "{err:?}");
}
fn unreachable_session(dir: &Path) -> TmuxSession {
TmuxSession {
socket: dir.join("absent.sock").to_string_lossy().to_string(),
argv: vec!["/bin/true".to_string()],
cast_path: dir.join("s.cast"),
cols: 80,
rows: 24,
exit_code: None,
closed: true,
screen: String::new(),
raw: String::new(),
}
}
#[test]
fn idle_waits_out_the_stable_window_rather_than_counting_polls() {
let dir = tempfile::tempdir().expect("tempdir");
let mut session = unreachable_session(dir.path());
let stable = Duration::from_millis(400);
let started = Instant::now();
let idle = session
.wait_for_idle(stable, Duration::from_secs(10))
.expect("no error");
assert!(idle, "an unchanging screen is idle");
assert!(
started.elapsed() >= stable,
"returned after {:?}, less than the {stable:?} it was asked to wait",
started.elapsed()
);
}
#[test]
fn the_backend_names_itself() {
assert_eq!(TmuxBackend.name(), "tmux");
}
}