use std::ffi::OsStr;
use std::fs;
use std::io;
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::path::{Path, PathBuf};
use crate::desktop::shell_integration;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct SshSession {
pub(in crate::desktop) destination: String,
pub(in crate::desktop) control_socket: PathBuf,
pub(in crate::desktop) user: Option<String>,
pub(in crate::desktop) port: Option<String>,
pub(in crate::desktop) config_file: Option<PathBuf>,
}
impl SshSession {
pub(in crate::desktop) fn key(&self) -> String {
format!("{}|{}", self.control_socket.display(), self.destination)
}
pub(in crate::desktop) fn display_host(&self) -> String {
if let Some(user) = &self.user
&& !self.destination.contains('@')
{
format!("{user}@{}", self.destination)
} else {
self.destination.clone()
}
}
pub(in crate::desktop) fn is_socket_live(&self) -> bool {
fs::symlink_metadata(&self.control_socket)
.map(|meta| meta.file_type().is_socket())
.unwrap_or(false)
}
}
pub(in crate::desktop) fn ensure_socket_dir() -> io::Result<PathBuf> {
let dir = shell_integration::runtime_base().join("ssh");
fs::create_dir_all(&dir)?;
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
Ok(dir)
}
pub(in crate::desktop) fn detect_pane_ssh(
foreground_pgid: Option<u32>,
child_pid: u32,
) -> Option<SshSession> {
if let Some(pgid) = foreground_pgid
&& let Some(session) = inspect_pid(pgid)
{
return Some(session);
}
if child_pid != 0 {
let mut stack = vec![(child_pid, 0u8)];
let mut visited = 0usize;
while let Some((pid, depth)) = stack.pop() {
if visited >= 32 {
break;
}
visited += 1;
if Some(pid) != foreground_pgid
&& let Some(session) = inspect_pid(pid)
{
return Some(session);
}
if depth < 3 {
for child in proc_children(pid) {
stack.push((child, depth + 1));
}
}
}
}
None
}
fn inspect_pid(pid: u32) -> Option<SshSession> {
if pid == 0 {
return None;
}
let raw = fs::read(format!("/proc/{pid}/cmdline")).ok()?;
let args: Vec<String> = raw
.split(|&b| b == 0)
.filter(|slice| !slice.is_empty())
.map(|slice| String::from_utf8_lossy(slice).into_owned())
.collect();
parse_ssh_cmdline(&args)
}
fn proc_children(pid: u32) -> Vec<u32> {
let path = format!("/proc/{pid}/task/{pid}/children");
let Ok(text) = fs::read_to_string(path) else {
return Vec::new();
};
text.split_whitespace()
.filter_map(|token| token.parse::<u32>().ok())
.collect()
}
pub(super) fn parse_ssh_cmdline(args: &[String]) -> Option<SshSession> {
let exe = args.first()?;
let name = Path::new(exe).file_name().and_then(OsStr::to_str)?;
if name != "ssh" {
return None;
}
let mut control_socket: Option<PathBuf> = None;
let mut user: Option<String> = None;
let mut port: Option<String> = None;
let mut config_file: Option<PathBuf> = None;
let mut destination: Option<String> = None;
let mut control_master_disabled = false;
let mut idx = 1usize;
let mut after_double_dash = false;
while idx < args.len() {
let arg = &args[idx];
idx += 1;
if after_double_dash {
destination = Some(arg.clone());
break;
}
if arg == "--" {
after_double_dash = true;
continue;
}
if !arg.starts_with('-') || arg == "-" {
destination = Some(arg.clone());
break;
}
let bytes = arg.as_bytes();
let mut pos = 1usize;
while pos < bytes.len() {
let flag = bytes[pos] as char;
pos += 1;
if ssh_option_takes_arg(flag) {
let value = if pos < bytes.len() {
let inline = arg[pos..].to_owned();
pos = bytes.len();
inline
} else if idx < args.len() {
let next = args[idx].clone();
idx += 1;
next
} else {
return None;
};
match flag {
'S' => control_socket = parse_control_path_value(&value),
'l' => user = Some(value),
'p' => port = Some(value),
'F' => config_file = Some(PathBuf::from(value)),
'o' => {
if let Some((key, val)) = split_ssh_option(&value) {
if key.eq_ignore_ascii_case("controlpath") {
control_socket = parse_control_path_value(val);
} else if key.eq_ignore_ascii_case("controlmaster")
&& val.eq_ignore_ascii_case("no")
{
control_master_disabled = true;
} else if key.eq_ignore_ascii_case("user") && user.is_none() {
user = Some(val.to_owned());
} else if key.eq_ignore_ascii_case("port") && port.is_none() {
port = Some(val.to_owned());
}
}
}
'O' | 'W' => return None,
_ => {}
}
} else if matches!(flag, 'V' | 'G' | 's' | 'N') {
return None;
}
}
}
if control_master_disabled {
return None;
}
let destination = destination?;
let control_socket = control_socket?;
Some(SshSession {
destination,
control_socket,
user,
port,
config_file,
})
}
fn ssh_option_takes_arg(flag: char) -> bool {
matches!(
flag,
'B' | 'b'
| 'c'
| 'D'
| 'E'
| 'e'
| 'F'
| 'I'
| 'i'
| 'J'
| 'L'
| 'l'
| 'm'
| 'O'
| 'o'
| 'P'
| 'p'
| 'Q'
| 'R'
| 'S'
| 'W'
| 'w'
)
}
fn split_ssh_option(spec: &str) -> Option<(&str, &str)> {
let trimmed = spec.trim();
if let Some((k, v)) = trimmed.split_once('=') {
return Some((k.trim(), v.trim()));
}
let split = trimmed.find(char::is_whitespace)?;
Some((trimmed[..split].trim(), trimmed[split..].trim()))
}
fn parse_control_path_value(val: &str) -> Option<PathBuf> {
let trimmed = val.trim().trim_matches('"').trim_matches('\'');
if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") {
return None;
}
Some(PathBuf::from(trimmed))
}
#[cfg(test)]
mod tests {
use super::*;
fn vec_s(items: &[&str]) -> Vec<String> {
items.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn parses_wrapped_ssh_cmdline_with_control_path_and_flags() {
let args = vec_s(&[
"/usr/bin/ssh",
"-o",
"ControlMaster=auto",
"-o",
"ControlPath=/tmp/lune-ssh/p1-1.sock",
"-o",
"ControlPersist=no",
"-p",
"2222",
"-l",
"ops",
"prod.example",
]);
let session = parse_ssh_cmdline(&args).unwrap();
assert_eq!(session.destination, "prod.example");
assert_eq!(
session.control_socket,
PathBuf::from("/tmp/lune-ssh/p1-1.sock")
);
assert_eq!(session.user.as_deref(), Some("ops"));
assert_eq!(session.port.as_deref(), Some("2222"));
assert_eq!(session.display_host(), "ops@prod.example");
}
#[test]
fn ignores_sftp_subsystems_and_control_master_no_invocations() {
let sftp_child = vec_s(&[
"ssh",
"-S",
"/tmp/lune-ssh/p1-1.sock",
"-o",
"ControlMaster=no",
"-T",
"-s",
"--",
"prod.example",
"sftp",
]);
assert!(parse_ssh_cmdline(&sftp_child).is_none());
let check = vec_s(&["ssh", "-S", "/tmp/x.sock", "-O", "check", "prod.example"]);
assert!(parse_ssh_cmdline(&check).is_none());
}
}