use std::{
io::{BufRead as _, BufReader, Write as _},
net::{IpAddr, SocketAddr},
process::{Command, Stdio},
};
use anyhow::{Context as _, Result, bail};
use libmoshpit::{ServerHello, ServerTarget, client_hello, parse_server_hello};
use tracing::{info, warn};
#[derive(Debug)]
pub(crate) struct Bootstrapped {
pub(crate) target: ServerTarget,
pub(crate) user: String,
pub(crate) host_key: Vec<u8>,
}
pub(crate) fn ssh_destination(destination: &str) -> Result<String> {
let (user, host) = destination
.split_once('@')
.map_or((None, destination), |(user, host)| (Some(user), host));
if user.is_some_and(str::is_empty) {
bail!("empty username before '@' in {destination:?}");
}
let port_hint = "with --ssh, set the SSH port in ~/.ssh/config or with \
--ssh-command 'ssh -p PORT'";
let host = if let Some(rest) = host.strip_prefix('[') {
let (inner, after) = rest
.split_once(']')
.with_context(|| format!("unclosed '[' in {destination:?}"))?;
if !after.is_empty() {
bail!("a port in {destination:?} isn't used: {port_hint}");
}
inner
} else {
if host.matches(':').count() == 1 {
bail!("a port in {destination:?} isn't used: {port_hint}");
}
host
};
if host.is_empty() || host.starts_with('-') || host.contains(char::is_whitespace) {
bail!("unusable host in {destination:?}");
}
Ok(user.map_or_else(|| host.to_string(), |user| format!("{user}@{host}")))
}
fn split_command(command: &str, what: &str) -> Result<(String, Vec<String>)> {
let mut words = command.split_whitespace().map(str::to_string);
let program = words.next().with_context(|| format!("{what} is empty"))?;
Ok((program, words.collect()))
}
fn ssh_hostname(ssh_command: &str, destination: &str) -> Option<String> {
let (program, args) = split_command(ssh_command, "ssh_command").ok()?;
let output = Command::new(program)
.args(args)
.arg("-G")
.arg("--")
.arg(destination)
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
hostname_from_ssh_g(&String::from_utf8_lossy(&output.stdout))
}
fn hostname_from_ssh_g(output: &str) -> Option<String> {
output.lines().find_map(|line| {
let (key, value) = line.split_once(' ')?;
(key == "hostname" && !value.trim().is_empty()).then(|| value.trim().to_string())
})
}
fn target(host: &str, port: u16) -> ServerTarget {
let bare = host.trim_start_matches('[').trim_end_matches(']');
match bare.parse::<IpAddr>() {
Ok(ip) => ServerTarget::Addr(SocketAddr::new(ip, port)),
Err(_) => ServerTarget::Name {
host: host.to_string(),
port,
},
}
}
fn destination_host(destination: &str) -> &str {
destination
.split_once('@')
.map_or(destination, |(_, host)| host)
}
pub(crate) fn start_server(
ssh_command: &str,
mps_command: &str,
destination: &str,
public_key: &[u8],
) -> Result<Bootstrapped> {
let (program, args) = split_command(ssh_command, "ssh_command")?;
if mps_command.trim().is_empty() {
bail!("mps_command is empty");
}
let hello = client_hello(public_key)?;
info!("bootstrap: running {ssh_command} {destination} {mps_command} --bootstrap");
let mut ssh = Command::new(&program)
.args(&args)
.arg("-T")
.arg("--")
.arg(destination)
.arg(mps_command)
.arg("--bootstrap")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.with_context(|| format!("running {program}"))?;
if let Some(mut stdin) = ssh.stdin.take() {
if let Err(e) = stdin.write_all(hello.as_bytes()) {
warn!("bootstrap: writing to ssh: {e}");
}
}
let mut answer: Option<ServerHello> = None;
let mut bad_answer = None;
if let Some(stdout) = ssh.stdout.take() {
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
match parse_server_hello(&line) {
Ok(Some(hello)) => {
answer = Some(hello);
break;
}
Ok(None) => info!("bootstrap: ignoring remote output: {line}"),
Err(e) => {
bad_answer = Some(e);
break;
}
}
}
}
let status = ssh.wait().context("waiting for ssh")?;
if let Some(e) = bad_answer {
return Err(e.context(format!("the reply from mps --bootstrap on {destination}")));
}
let Some(answer) = answer else {
bail!(
"mps --bootstrap on {destination} didn't reply (ssh {status}). Is mps 0.21.0 or \
later installed there? If it isn't on the PATH of SSH commands, set its path with \
--mps-command or mps_command."
);
};
if !status.success() {
warn!("bootstrap: ssh {status} after mps replied");
}
let host = ssh_hostname(ssh_command, destination)
.unwrap_or_else(|| destination_host(destination).to_string());
info!(
"bootstrap: mps listens on {host}:{} as {}",
answer.port(),
answer.user()
);
Ok(Bootstrapped {
target: target(&host, answer.port()),
user: answer.user().clone(),
host_key: answer.host_key().clone(),
})
}
#[cfg(test)]
mod tests {
use std::net::SocketAddr;
use libmoshpit::ServerTarget;
use super::{destination_host, hostname_from_ssh_g, split_command, ssh_destination, target};
#[test]
fn destinations_pass_through_to_ssh() -> anyhow::Result<()> {
assert_eq!(ssh_destination("box")?, "box");
assert_eq!(ssh_destination("me@box.example.com")?, "me@box.example.com");
assert_eq!(ssh_destination("my_alias")?, "my_alias");
assert_eq!(ssh_destination("10.0.0.3")?, "10.0.0.3");
assert_eq!(ssh_destination("me@[::1]")?, "me@::1");
assert_eq!(ssh_destination("fe80::1")?, "fe80::1");
Ok(())
}
#[test]
fn ports_and_junk_are_refused() {
for bad in [
"box:2222",
"me@box:40404",
"[::1]:22",
"@box",
"",
"me@",
"-oProxyCommand=x",
"[::1",
] {
assert!(ssh_destination(bad).is_err(), "{bad:?} should be refused");
}
}
#[test]
fn ssh_g_hostname_is_found() {
let output = "user me\nhostname box.internal.example.com\nport 22\n";
assert_eq!(
hostname_from_ssh_g(output).as_deref(),
Some("box.internal.example.com")
);
assert_eq!(hostname_from_ssh_g("user me\nport 22\n"), None);
}
#[test]
fn targets_keep_ips_and_names_apart() {
assert_eq!(
target("10.0.0.3", 50001),
ServerTarget::Addr("10.0.0.3:50001".parse::<SocketAddr>().expect("addr"))
);
assert_eq!(
target("::1", 50001),
ServerTarget::Addr("[::1]:50001".parse::<SocketAddr>().expect("addr"))
);
assert_eq!(
target("box.example.com", 50001),
ServerTarget::Name {
host: "box.example.com".to_string(),
port: 50001
}
);
assert_eq!(destination_host("me@box"), "box");
assert_eq!(destination_host("box"), "box");
}
#[test]
fn commands_split_on_whitespace() -> anyhow::Result<()> {
let (program, args) = split_command("ssh -p 2222 -i key", "ssh_command")?;
assert_eq!(program, "ssh");
assert_eq!(args, vec!["-p", "2222", "-i", "key"]);
assert!(split_command(" ", "ssh_command").is_err());
Ok(())
}
}