use std::{
env::{set_current_dir, var},
fs::OpenOptions,
io::{BufRead as _, Error, ErrorKind, Write as _, stdin, stdout},
net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener},
ops::RangeInclusive,
os::fd::AsRawFd as _,
process::id,
};
use anyhow::{Context as _, Result, bail};
use libmoshpit::{
HostIdentity, MoshpitError, PinnedClient, load, parse_client_hello, server_hello,
};
use crate::{cli::Cli, config::Config};
pub(crate) struct Prepared {
pub(crate) cli: Cli,
pub(crate) config: Config,
pub(crate) listener: TcpListener,
pub(crate) host: HostIdentity,
pub(crate) client: PinnedClient,
}
#[allow(unsafe_code)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub(crate) fn prepare(cli: Cli) -> Result<Prepared> {
let config =
load::<Cli, Config, Cli>(&cli, &cli, false).with_context(|| MoshpitError::ConfigLoad)?;
let user = whoami::username().context("looking up the account mps runs as")?;
let mut line = String::new();
let _ = stdin()
.lock()
.read_line(&mut line)
.context("reading the client's bootstrap line")?;
if line.is_empty() {
bail!("no MP-BOOTSTRAP line on stdin: mps --bootstrap is started by `mp --ssh`");
}
let client_key = parse_client_hello(&line)?;
let host = HostIdentity::generate_ephemeral(&host_key_comment())?;
let listener = bind_listener(listen_ip(var("SSH_CONNECTION").ok().as_deref()), &config)?;
let port = listener.local_addr()?.port();
let mut out = stdout().lock();
out.write_all(server_hello(port, &user, host.full_public_key())?.as_bytes())?;
out.flush()?;
drop(out);
daemonize()?;
Ok(Prepared {
cli,
config,
listener,
host,
client: PinnedClient::new(user, client_key),
})
}
fn host_key_comment() -> String {
let host: String = whoami::hostname()
.unwrap_or_default()
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if host.is_empty() {
"mps-bootstrap".to_string()
} else {
format!("mps-bootstrap@{host}")
}
}
fn listen_ip(ssh_connection: Option<&str>) -> IpAddr {
ssh_connection
.and_then(|value| value.split_whitespace().nth(2))
.and_then(|ip| ip.parse::<IpAddr>().ok())
.unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
}
fn port_order(range: &RangeInclusive<u16>, start: u32) -> Vec<u16> {
let ports: Vec<u16> = range.clone().collect();
if ports.is_empty() {
return ports;
}
let offset = usize::try_from(start).unwrap_or(0) % ports.len();
ports[offset..]
.iter()
.chain(&ports[..offset])
.copied()
.collect()
}
fn bind_listener(ip: IpAddr, config: &Config) -> Result<TcpListener> {
let ports = config.data_ports()?;
for port in port_order(&ports, id()) {
match TcpListener::bind(SocketAddr::new(ip, port)) {
Ok(listener) => return Ok(listener),
Err(e) if e.kind() == ErrorKind::AddrInUse => {}
Err(e) => return Err(e).with_context(|| format!("binding {ip}:{port}")),
}
}
bail!(
"no free TCP port in {}-{} on {ip} for the key exchange",
ports.start(),
ports.end()
)
}
#[allow(unsafe_code)]
fn daemonize() -> Result<()> {
let null = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/null")
.context("opening /dev/null")?;
match unsafe { libc::fork() } {
-1 => return Err(Error::last_os_error()).context("fork"),
0 => {}
_ => unsafe { libc::_exit(0) },
}
unsafe {
if libc::setsid() < 0 {
return Err(Error::last_os_error()).context("setsid");
}
for fd in 0..=2 {
if libc::dup2(null.as_raw_fd(), fd) < 0 {
return Err(Error::last_os_error()).context("redirecting stdio");
}
}
}
set_current_dir("/").context("chdir /")?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, Ipv4Addr};
use super::{host_key_comment, listen_ip, port_order};
#[test]
fn listens_where_ssh_came_in() {
assert_eq!(
listen_ip(Some("10.0.0.9 51000 10.0.0.3 22")),
"10.0.0.3".parse::<IpAddr>().expect("ip")
);
assert_eq!(
listen_ip(Some("2001:db8::9 51000 2001:db8::3 22")),
"2001:db8::3".parse::<IpAddr>().expect("ip")
);
assert_eq!(listen_ip(None), IpAddr::V4(Ipv4Addr::UNSPECIFIED));
assert_eq!(
listen_ip(Some("garbage")),
IpAddr::V4(Ipv4Addr::UNSPECIFIED)
);
}
#[test]
fn port_order_wraps_from_the_start_offset() {
assert_eq!(
port_order(&(60000..=60003), 6),
vec![60002, 60003, 60000, 60001]
);
assert_eq!(port_order(&(60000..=60000), 7), vec![60000]);
assert_eq!(port_order(&(60000..=60003), 0).len(), 4);
}
#[test]
fn host_key_comment_has_no_whitespace() {
let comment = host_key_comment();
assert!(comment.starts_with("mps-bootstrap"));
assert!(!comment.contains(char::is_whitespace));
}
}