use std::{
net::{IpAddr, Ipv4Addr},
time::Duration,
};
use serde::Deserialize;
const OVERLAY_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Overlay {
pub(super) ip: Ipv4Addr,
pub(super) fqdn: Option<String>,
}
impl Overlay {
pub(super) fn names(&self) -> Vec<String> {
let Some(fqdn) = &self.fqdn else {
return Vec::new();
};
let mut names = vec![fqdn.clone()];
if let Some((short, _)) = fqdn.split_once('.') {
names.push(short.to_owned());
}
names
}
}
#[derive(Deserialize)]
struct TailscaleStatus {
#[serde(rename = "BackendState")]
backend_state: String,
#[serde(rename = "Self")]
this: Option<TailscalePeer>,
}
#[derive(Deserialize)]
struct TailscalePeer {
#[serde(rename = "DNSName", default)]
dns_name: String,
#[serde(rename = "TailscaleIPs", default)]
tailscale_ips: Vec<IpAddr>,
}
pub(super) fn parse_tailscale(json: &[u8]) -> Result<Overlay, String> {
let status: TailscaleStatus =
serde_json::from_slice(json).map_err(|error| format!("unreadable status: {error}"))?;
if status.backend_state != "Running" {
return Err(format!("state {}", status.backend_state));
}
let this = status.this.ok_or("no address")?;
let ip = this
.tailscale_ips
.iter()
.find_map(|ip| match ip {
IpAddr::V4(ip) => Some(*ip),
IpAddr::V6(_) => None,
})
.ok_or("no IPv4 address")?;
let fqdn = this.dns_name.trim_end_matches('.');
Ok(Overlay {
ip,
fqdn: (!fqdn.is_empty()).then(|| fqdn.to_owned()),
})
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct NetbirdStatus {
daemon_status: String,
#[serde(default)]
netbird_ip: String,
#[serde(default)]
fqdn: String,
}
pub(super) fn parse_netbird(json: &[u8]) -> Result<Overlay, String> {
let status: NetbirdStatus =
serde_json::from_slice(json).map_err(|error| format!("unreadable status: {error}"))?;
if status.daemon_status != "Connected" {
return Err(format!("state {}", status.daemon_status));
}
let address = status.netbird_ip.split('/').next().unwrap_or_default();
let ip = address
.parse()
.map_err(|_| format!("no IPv4 address in {:?}", status.netbird_ip))?;
Ok(Overlay {
ip,
fqdn: (!status.fqdn.is_empty()).then_some(status.fqdn),
})
}
type ParseStatus = fn(&[u8]) -> Result<Overlay, String>;
pub(super) async fn find_overlay() -> Result<Overlay, String> {
let tailscale: &[&str] = if cfg!(target_os = "macos") {
&[
"tailscale",
"/Applications/Tailscale.app/Contents/MacOS/Tailscale",
]
} else {
&["tailscale"]
};
let overlays: [(&str, &[&str], ParseStatus); 2] = [
("Tailscale", tailscale, parse_tailscale),
("NetBird", &["netbird"], parse_netbird),
];
let mut why = Vec::new();
for (name, programs, parse) in overlays {
let mut said = "not installed".to_owned();
for program in programs {
match status_json(program).await {
Ok(Some(json)) => match parse(&json) {
Ok(overlay) => return Ok(overlay),
Err(error) => said = error,
},
Ok(None) => {}
Err(error) => said = error,
}
}
why.push(format!("{name}: {said}"));
}
Err(why.join("; "))
}
async fn status_json(program: &str) -> Result<Option<Vec<u8>>, String> {
let child = tokio::process::Command::new(program)
.args(["status", "--json"])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.kill_on_drop(true)
.output();
match tokio::time::timeout(OVERLAY_TIMEOUT, child).await {
Err(_) => Err(format!(
"`{program} status --json` did not answer within OVERLAY_TIMEOUT ({OVERLAY_TIMEOUT:?})"
)),
Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Ok(Err(error)) => Err(format!("could not run `{program}`: {error}")),
Ok(Ok(output)) if output.status.success() => Ok(Some(output.stdout)),
Ok(Ok(output)) => Err(format!("`{program} status` failed with {}", output.status)),
}
}
#[cfg(test)]
#[path = "setup_overlay_tests.rs"]
mod tests;