use std::collections::HashSet;
use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use super::session::SshSession;
const MAX_INCLUDE_DEPTH: usize = 4;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct SshConfigHost {
pub(in crate::desktop) alias: String,
pub(in crate::desktop) hostname: Option<String>,
pub(in crate::desktop) user: Option<String>,
pub(in crate::desktop) port: Option<String>,
}
impl SshConfigHost {
pub(in crate::desktop) fn detail(&self) -> String {
let mut out = String::new();
if let Some(user) = &self.user {
out.push_str(user);
out.push('@');
}
if let Some(host) = &self.hostname {
out.push_str(host);
} else {
out.push_str(&self.alias);
}
if let Some(port) = &self.port
&& port != "22"
{
out.push(':');
out.push_str(port);
}
out
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) struct SshLaunchSpec {
pub(in crate::desktop) destination: String,
pub(in crate::desktop) user: Option<String>,
pub(in crate::desktop) port: Option<String>,
pub(in crate::desktop) config_file: Option<PathBuf>,
pub(in crate::desktop) identity_file: Option<PathBuf>,
}
impl SshLaunchSpec {
pub(in crate::desktop) fn from_session(session: &SshSession) -> Self {
Self {
destination: session.destination.clone(),
user: session.user.clone(),
port: session.port.clone(),
config_file: session.config_file.clone(),
identity_file: None,
}
}
pub(in crate::desktop) fn from_alias(alias: String) -> Self {
Self {
destination: alias,
user: None,
port: None,
config_file: None,
identity_file: None,
}
}
pub(in crate::desktop) fn parse_user_input(raw: &str) -> Option<Self> {
let mut tokens: Vec<&str> = raw.split_whitespace().collect();
if tokens.is_empty() {
return None;
}
if tokens.first().copied() == Some("ssh") {
tokens.remove(0);
}
let mut destination: Option<String> = None;
let mut user: Option<String> = None;
let mut port: Option<String> = None;
let mut config_file: Option<PathBuf> = None;
let mut identity_file: Option<PathBuf> = None;
let mut i = 0;
while i < tokens.len() {
let tok = tokens[i];
i += 1;
match tok {
"-p" => {
port = Some(tokens.get(i)?.to_string());
i += 1;
}
"-l" => {
user = Some(tokens.get(i)?.to_string());
i += 1;
}
"-F" => {
config_file = Some(PathBuf::from(tokens.get(i)?));
i += 1;
}
"-i" => {
identity_file = Some(PathBuf::from(tokens.get(i)?));
i += 1;
}
"--" => {
if destination.is_none() {
destination = Some(tokens.get(i)?.to_string());
}
break;
}
other if !other.starts_with('-') && destination.is_none() => {
destination = Some(other.to_owned());
}
_ => {}
}
}
let destination = destination.filter(|d| !d.is_empty())?;
Some(Self {
destination,
user,
port,
config_file,
identity_file,
})
}
pub(in crate::desktop) fn display_label(&self) -> String {
if let Some(user) = &self.user
&& !self.destination.contains('@')
{
format!("{user}@{}", self.destination)
} else {
self.destination.clone()
}
}
pub(in crate::desktop) fn build_argv(&self, control_socket: Option<&Path>) -> Vec<OsString> {
let mut argv = Vec::with_capacity(14);
argv.push(OsString::from("ssh"));
if let Some(sock) = control_socket {
argv.push(OsString::from("-o"));
argv.push(OsString::from("ControlMaster=auto"));
argv.push(OsString::from("-o"));
let mut cp = OsString::from("ControlPath=");
cp.push(sock.as_os_str());
argv.push(cp);
argv.push(OsString::from("-o"));
argv.push(OsString::from("ControlPersist=no"));
}
if let Some(cfg) = &self.config_file {
argv.push(OsString::from("-F"));
argv.push(cfg.as_os_str().to_owned());
}
if let Some(id) = &self.identity_file {
argv.push(OsString::from("-i"));
argv.push(id.as_os_str().to_owned());
}
if let Some(port) = &self.port {
argv.push(OsString::from("-p"));
argv.push(OsString::from(port));
}
if let Some(user) = &self.user {
argv.push(OsString::from("-l"));
argv.push(OsString::from(user));
}
argv.push(OsString::from("--"));
argv.push(OsString::from(&self.destination));
argv
}
}
pub(in crate::desktop) fn load_ssh_config_hosts() -> Vec<SshConfigHost> {
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
return Vec::new();
};
let ssh_dir = home.join(".ssh");
let config_path = ssh_dir.join("config");
let mut hosts = Vec::new();
let mut seen_aliases = HashSet::new();
let mut visited_files = HashSet::new();
parse_config_file(
&config_path,
&ssh_dir,
&home,
0,
&mut visited_files,
&mut seen_aliases,
&mut hosts,
);
hosts
}
fn parse_config_file(
path: &Path,
ssh_dir: &Path,
home: &Path,
depth: usize,
visited_files: &mut HashSet<PathBuf>,
seen_aliases: &mut HashSet<String>,
hosts: &mut Vec<SshConfigHost>,
) {
if depth > MAX_INCLUDE_DEPTH {
return;
}
let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
if !visited_files.insert(canonical) {
return;
}
let Ok(content) = fs::read_to_string(path) else {
return;
};
parse_config_text(
&content,
ssh_dir,
home,
depth,
visited_files,
seen_aliases,
hosts,
);
}
fn parse_config_text(
content: &str,
ssh_dir: &Path,
home: &Path,
depth: usize,
visited_files: &mut HashSet<PathBuf>,
seen_aliases: &mut HashSet<String>,
hosts: &mut Vec<SshConfigHost>,
) {
let mut current_indices: Vec<usize> = Vec::new();
for raw_line in content.lines() {
let line = strip_comment(raw_line).trim();
if line.is_empty() {
continue;
}
let Some((keyword, value)) = split_keyword_value(line) else {
continue;
};
if keyword.eq_ignore_ascii_case("include") {
for pattern in value.split_whitespace() {
for included in expand_include_pattern(pattern, ssh_dir, home) {
parse_config_file(
&included,
ssh_dir,
home,
depth + 1,
visited_files,
seen_aliases,
hosts,
);
}
}
} else if keyword.eq_ignore_ascii_case("host") {
current_indices.clear();
for token in value.split_whitespace() {
let alias = token.trim_matches('"');
if alias.is_empty()
|| alias.starts_with('!')
|| alias.contains('*')
|| alias.contains('?')
{
continue;
}
if seen_aliases.insert(alias.to_owned()) {
let idx = hosts.len();
hosts.push(SshConfigHost {
alias: alias.to_owned(),
hostname: None,
user: None,
port: None,
});
current_indices.push(idx);
}
}
} else if keyword.eq_ignore_ascii_case("match") {
current_indices.clear();
} else if !current_indices.is_empty() {
let val = value.trim().trim_matches('"');
if val.is_empty() {
continue;
}
if keyword.eq_ignore_ascii_case("hostname") {
for &idx in ¤t_indices {
if hosts[idx].hostname.is_none() {
hosts[idx].hostname = Some(val.to_owned());
}
}
} else if keyword.eq_ignore_ascii_case("user") {
for &idx in ¤t_indices {
if hosts[idx].user.is_none() {
hosts[idx].user = Some(val.to_owned());
}
}
} else if keyword.eq_ignore_ascii_case("port") {
for &idx in ¤t_indices {
if hosts[idx].port.is_none() {
hosts[idx].port = Some(val.to_owned());
}
}
}
}
}
}
fn strip_comment(line: &str) -> &str {
let mut in_quotes = false;
for (idx, ch) in line.char_indices() {
match ch {
'"' => in_quotes = !in_quotes,
'#' if !in_quotes => return &line[..idx],
_ => {}
}
}
line
}
fn split_keyword_value(line: &str) -> Option<(&str, &str)> {
let eq = line.find('=');
let ws = line.find(char::is_whitespace);
let split = match (eq, ws) {
(Some(e), Some(w)) => e.min(w),
(Some(e), None) => e,
(None, Some(w)) => w,
(None, None) => return None,
};
let keyword = line[..split].trim();
let rest = line[split + 1..].trim_start_matches([' ', '\t', '=']);
if keyword.is_empty() || rest.is_empty() {
return None;
}
Some((keyword, rest))
}
fn expand_include_pattern(pattern: &str, ssh_dir: &Path, home: &Path) -> Vec<PathBuf> {
let unquoted = pattern.trim_matches('"');
let expanded = if let Some(rest) = unquoted.strip_prefix("~/") {
home.join(rest)
} else if Path::new(unquoted).is_absolute() {
PathBuf::from(unquoted)
} else {
ssh_dir.join(unquoted)
};
let Some(file_name) = expanded.file_name().and_then(|n| n.to_str()) else {
return Vec::new();
};
if !file_name.contains('*') && !file_name.contains('?') {
return if expanded.is_file() {
vec![expanded]
} else {
Vec::new()
};
}
let Some(parent) = expanded.parent() else {
return Vec::new();
};
let Ok(read_dir) = fs::read_dir(parent) else {
return Vec::new();
};
let mut matches: Vec<PathBuf> = read_dir
.flatten()
.map(|entry| entry.path())
.filter(|path| {
path.is_file()
&& path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|name| simple_glob_match(file_name, name))
})
.collect();
matches.sort();
matches
}
fn simple_glob_match(pattern: &str, text: &str) -> bool {
let p: Vec<char> = pattern.chars().collect();
let t: Vec<char> = text.chars().collect();
let (mut pi, mut ti) = (0usize, 0usize);
let mut star: Option<(usize, usize)> = None;
while ti < t.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {
pi += 1;
ti += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi, ti));
pi += 1;
} else if let Some((s_pi, s_ti)) = star {
pi = s_pi + 1;
ti = s_ti + 1;
star = Some((s_pi, ti));
} else {
return false;
}
}
while pi < p.len() && p[pi] == '*' {
pi += 1;
}
pi == p.len()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_ssh_config_hosts_skipping_wildcards_and_formatting_details() {
let sample = r#"
# Global defaults
Host *
ServerAliveInterval 60
Host prod-api prod-alias
HostName 10.20.30.40
User deploy
Port 2222
Host dev-box
HostName=10.20.30.41
User=alice
Port=22
Host *.internal !bastion
User ops
"#;
let mut visited = HashSet::new();
let mut seen = HashSet::new();
let mut hosts = Vec::new();
parse_config_text(
sample,
Path::new("/tmp"),
Path::new("/tmp"),
0,
&mut visited,
&mut seen,
&mut hosts,
);
assert_eq!(hosts.len(), 3);
assert_eq!(hosts[0].alias, "prod-api");
assert_eq!(hosts[0].detail(), "deploy@10.20.30.40:2222");
assert_eq!(hosts[1].alias, "prod-alias");
assert_eq!(hosts[1].detail(), "deploy@10.20.30.40:2222");
assert_eq!(hosts[2].alias, "dev-box");
assert_eq!(hosts[2].detail(), "alice@10.20.30.41");
}
#[test]
fn parses_user_input_and_builds_multiplexed_ssh_argv() {
let spec = SshLaunchSpec::parse_user_input("ssh alice@10.0.0.5 -p 2200").unwrap();
assert_eq!(spec.destination, "alice@10.0.0.5");
assert_eq!(spec.port.as_deref(), Some("2200"));
assert_eq!(spec.display_label(), "alice@10.0.0.5");
let argv: Vec<String> = spec
.build_argv(Some(Path::new("/tmp/lune-ssh/p2-1.sock")))
.into_iter()
.map(|s| s.to_string_lossy().into_owned())
.collect();
assert_eq!(
argv,
vec![
"ssh",
"-o",
"ControlMaster=auto",
"-o",
"ControlPath=/tmp/lune-ssh/p2-1.sock",
"-o",
"ControlPersist=no",
"-p",
"2200",
"--",
"alice@10.0.0.5",
]
);
assert!(SshLaunchSpec::parse_user_input(" ").is_none());
}
}