tmux-tango 2.13.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
//! Where a tmux server lives: this machine, or one reachable over ssh.
//!
//! This is the *only* module that knows how to prefix a command with `ssh`. Everything else
//! builds an argv for `tmux` (or `tango`) and asks [`Host::command`] to run it.
//!
//! Two non-obvious constraints shape the remote branch:
//!
//! - ssh joins its trailing arguments with spaces into one string and the remote *login shell*
//!   re-parses it. A tmux format like `#{session_name}\t#{session_windows}` would be split on
//!   the tab and `#` could start a comment, so every argument is single-quoted into a single
//!   trailing ssh argument ([`remote_shell_line`]). Single quotes are literal in sh, bash, zsh,
//!   dash, fish and tcsh; the only character needing care is `'` itself.
//! - Polling a host every few seconds must not pay a fresh TCP + key-exchange handshake each
//!   time, so tango passes its own `ControlMaster`/`ControlPath`/`ControlPersist`. Command-line
//!   `-o` options beat `~/.ssh/config`, so the user's own multiplexing setup is untouched, and
//!   the socket lives in `~/.ssh` because macOS caps unix-socket paths at 104 bytes and
//!   `$TMPDIR` there is already ~50 bytes long.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

/// Seconds ssh waits for a TCP connection before giving up on a poll.
const CONNECT_TIMEOUT_SECS: u32 = 5;
/// How long the shared master connection outlives its last client.
const CONTROL_PERSIST: &str = "60s";

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Host {
    Local,
    Remote { alias: Arc<str> },
}

impl Host {
    pub fn remote(alias: &str) -> Self {
        Host::Remote { alias: alias.into() }
    }

    pub fn is_remote(&self) -> bool {
        matches!(self, Host::Remote { .. })
    }

    /// Build a command that runs `program args…` on this host. `tty` requests a remote
    /// pseudo-terminal (`ssh -t`) and is only meaningful for interactive attaches; local
    /// commands ignore it.
    pub fn command(&self, program: &str, args: &[&str], tty: bool) -> Command {
        match self {
            Host::Local => {
                let mut cmd = Command::new(program);
                cmd.args(args);
                cmd
            }
            Host::Remote { alias } => {
                let mut cmd = Command::new("ssh");
                cmd.args(ssh_base_args(control_path_dir().as_deref()));
                if tty {
                    cmd.arg("-t");
                }
                cmd.arg("--").arg(alias.as_ref()).arg(remote_shell_line(program, args));
                cmd
            }
        }
    }
}

/// Quote `s` for a POSIX-style shell: wrap in single quotes, with each embedded `'` spliced
/// out as `'\''`. Tabs, `#`, `{`, `$` and spaces all survive verbatim.
pub fn sh_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        if c == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(c);
        }
    }
    out.push('\'');
    out
}

/// The single string ssh will hand to the remote shell: the program followed by every
/// argument, each quoted, so the remote shell reproduces exactly our argv.
pub fn remote_shell_line(program: &str, args: &[&str]) -> String {
    let mut line = sh_quote(program);
    for arg in args {
        line.push(' ');
        line.push_str(&sh_quote(arg));
    }
    line
}

/// Directory for tango's ControlMaster sockets: `$HOME/.ssh` when it already exists.
/// We never create it — an absent `~/.ssh` means the user has no keys and multiplexing
/// would not help them anyway.
pub fn control_path_dir() -> Option<PathBuf> {
    let home = std::env::var("HOME").ok()?;
    let dir = Path::new(&home).join(".ssh");
    dir.is_dir().then_some(dir)
}

/// ssh options shared by every poll and attach. `BatchMode` stops a poll thread from ever
/// blocking on a password prompt.
pub fn ssh_base_args(control_dir: Option<&Path>) -> Vec<String> {
    let mut args = vec!["-o".to_string(), "BatchMode=yes".to_string()];
    args.extend(connection_args(control_dir));
    args
}

/// The connect timeout plus the `Control*` trio, which is omitted when there is no directory
/// to put the socket in. Shared by the batch commands and [`remote_login_command`], so a login
/// lands on the very socket the pollers reuse.
fn connection_args(control_dir: Option<&Path>) -> Vec<String> {
    let mut args = vec![
        "-o".to_string(),
        format!("ConnectTimeout={}", CONNECT_TIMEOUT_SECS),
    ];
    if let Some(dir) = control_dir {
        // `%C` is a 40-hex hash of user/host/port, so the path stays short and fixed-length.
        let socket = dir.join("tango-%C");
        args.extend([
            "-o".to_string(),
            "ControlMaster=auto".to_string(),
            "-o".to_string(),
            format!("ControlPath={}", socket.display()),
            "-o".to_string(),
            format!("ControlPersist={}", CONTROL_PERSIST),
        ]);
    }
    args
}

/// The interactive attach over ssh. `program` is the absolute path of the remote `tango` (when
/// `has_tango`) or `tmux` binary, resolved by the poller's probe so a minimal non-interactive
/// ssh PATH cannot break it.
pub fn remote_attach_command(
    alias: &str,
    program: &str,
    session: &str,
    window: Option<u32>,
    has_tango: bool,
) -> Command {
    let target = match window {
        Some(w) => format!("{}:{}", session, w),
        None => session.to_string(),
    };
    let args: Vec<&str> = if has_tango {
        vec!["attach", &target]
    } else {
        vec!["attach-session", "-t", &target]
    };
    Host::remote(alias).command(program, &args, true)
}

/// An interactive ssh that only connects (`true`), for hosts the batch pollers cannot reach
/// because ssh wants a human: a Tailscale SSH check link, a password, a 2FA prompt. It shares
/// tango's `ControlPath` with `ControlMaster=auto`, so the connection the user authenticates
/// becomes the master every later poll, preview and attach rides on.
pub fn remote_login_command(alias: &str) -> Command {
    let mut cmd = Command::new("ssh");
    cmd.args(["-o", "BatchMode=no"])
        .args(connection_args(control_path_dir().as_deref()))
        .arg("--")
        .arg(alias)
        .arg(remote_shell_line("true", &[]));
    cmd
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsStr;

    fn argv(cmd: &Command) -> Vec<String> {
        std::iter::once(cmd.get_program())
            .chain(cmd.get_args())
            .map(|s| s.to_string_lossy().into_owned())
            .collect()
    }

    fn opt_values(argv: &[String]) -> Vec<&str> {
        argv.windows(2)
            .filter(|w| w[0] == "-o")
            .map(|w| w[1].as_str())
            .collect()
    }

    #[test]
    fn sh_quote_wraps_plain_text() {
        assert_eq!(sh_quote("abc"), "'abc'");
    }

    #[test]
    fn sh_quote_escapes_embedded_single_quote() {
        assert_eq!(sh_quote("a'b"), "'a'\\''b'");
    }

    #[test]
    fn sh_quote_keeps_tab_and_format_braces_verbatim() {
        assert_eq!(sh_quote("#{a}\t#{b}"), "'#{a}\t#{b}'");
    }

    #[test]
    fn sh_quote_empty_string_is_empty_quotes() {
        assert_eq!(sh_quote(""), "''");
    }

    #[test]
    fn remote_shell_line_quotes_every_argument() {
        let line = remote_shell_line("tmux", &["list-sessions", "-F", "#{session_name}\t#{n}"]);
        assert_eq!(line, "'tmux' 'list-sessions' '-F' '#{session_name}\t#{n}'");
    }

    #[test]
    fn local_command_is_plain_program() {
        let cmd = Host::Local.command("tmux", &["list-sessions"], true);
        assert_eq!(argv(&cmd), vec!["tmux", "list-sessions"]);
    }

    #[test]
    fn remote_command_goes_through_ssh_with_one_shell_line() {
        let cmd = Host::remote("box").command("tmux", &["list-sessions", "-F", "#{a}\tb"], false);
        let argv = argv(&cmd);
        assert_eq!(argv[0], "ssh");
        assert!(opt_values(&argv).contains(&"BatchMode=yes"), "{:?}", argv);
        let sep = argv.iter().position(|a| a == "--").expect("-- before alias");
        assert_eq!(argv[sep + 1], "box");
        assert_eq!(argv.len(), sep + 3, "exactly one argument after the alias: {:?}", argv);
        assert_eq!(argv[sep + 2], "'tmux' 'list-sessions' '-F' '#{a}\tb'");
        assert!(!argv.contains(&"-t".to_string()), "no tty for a poll: {:?}", argv);
    }

    #[test]
    fn remote_command_requests_tty_when_asked() {
        let cmd = Host::remote("box").command("tmux", &["attach-session", "-t", "s"], true);
        let argv = argv(&cmd);
        let t = argv.iter().position(|a| a == "-t").expect("-t present");
        let sep = argv.iter().position(|a| a == "--").unwrap();
        assert!(t < sep, "-t must come before --: {:?}", argv);
    }

    #[test]
    fn ssh_base_args_without_control_dir_has_no_multiplexing() {
        let args = ssh_base_args(None);
        let values = opt_values(&args);
        assert!(values.contains(&"BatchMode=yes"));
        assert!(values.contains(&"ConnectTimeout=5"));
        assert!(!values.iter().any(|v| v.starts_with("Control")), "{:?}", args);
    }

    #[test]
    fn ssh_base_args_with_control_dir_points_socket_into_it() {
        let args = ssh_base_args(Some(Path::new("/home/k/.ssh")));
        let values = opt_values(&args);
        assert!(values.contains(&"ControlMaster=auto"), "{:?}", args);
        assert!(values.contains(&"ControlPath=/home/k/.ssh/tango-%C"), "{:?}", args);
        assert!(values.contains(&"ControlPersist=60s"), "{:?}", args);
    }

    #[test]
    fn control_socket_path_fits_macos_limit_for_typical_home() {
        // sun_path is 104 bytes on macOS; %C expands to 40 hex chars.
        let dir = Path::new("/Users/averagelengthname/.ssh");
        let args = ssh_base_args(Some(dir));
        let path = opt_values(&args)
            .into_iter()
            .find_map(|v| v.strip_prefix("ControlPath="))
            .unwrap()
            .replace("%C", &"0".repeat(40));
        assert!(path.len() < 104, "{} bytes: {}", path.len(), path);
    }

    #[test]
    fn remote_attach_prefers_tango_when_present() {
        let cmd = remote_attach_command("box", "/usr/local/bin/tango", "dev", Some(2), true);
        let argv = argv(&cmd);
        assert_eq!(argv.last().unwrap(), "'/usr/local/bin/tango' 'attach' 'dev:2'");
        assert!(argv.contains(&"-t".to_string()), "attach needs a tty: {:?}", argv);
    }

    #[test]
    fn remote_attach_falls_back_to_tmux() {
        let cmd = remote_attach_command("box", "/usr/bin/tmux", "dev", None, false);
        assert_eq!(
            argv(&cmd).last().unwrap(),
            "'/usr/bin/tmux' 'attach-session' '-t' 'dev'"
        );
    }

    #[test]
    fn login_command_is_interactive_but_shares_the_pollers_socket() {
        let login = argv(&remote_login_command("box"));
        let poll = argv(&Host::remote("box").command("tmux", &["list-sessions"], false));
        let login_opts = opt_values(&login);
        assert!(login_opts.contains(&"BatchMode=no"), "{:?}", login);
        assert!(!login_opts.contains(&"BatchMode=yes"), "{:?}", login);
        // The login is only useful if the master it authenticates is the one polls reuse.
        let control = |opts: Vec<&str>| -> Vec<String> {
            opts.into_iter().filter(|v| v.starts_with("Control")).map(String::from).collect()
        };
        assert_eq!(control(login_opts), control(opt_values(&poll)), "login {:?}\npoll {:?}", login, poll);
        assert_eq!(login[login.len() - 2..], ["box", "'true'"], "{:?}", login);
    }

    #[test]
    fn host_remote_is_remote_and_local_is_not() {
        assert!(Host::remote("x").is_remote());
        assert!(!Host::Local.is_remote());
        let _: &OsStr = Host::Local.command("true", &[], false).get_program();
    }
}