use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::{Path, PathBuf},
time::{Duration, Instant},
};
use anyhow::Context as _;
use rho_protocol::{BridgeToken, BridgeUrl, Pairing};
use rho_providers::credentials::CredentialStoreBackend;
use super::{
cli::NO_SERVICE_MANAGER,
server::RECHECK_INTERVAL,
setup_overlay::{find_overlay, Overlay},
setup_service::{self, Installed, PairWith, ServiceSpec},
tokens::DaemonTokenSet,
};
use crate::{
app::{
config_repository::ConfigRepository,
http_guard::{is_private, validate_name, AllowedHost},
mcp_server::token_store,
},
cli::{BridgeSetupArgs, Cli},
daemon::{ServiceFiles, ServiceManager},
};
const DEFAULT_PORT: u16 = 8766;
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
const PROBE_INTERVAL: Duration = Duration::from_millis(200);
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Listen {
Overlay,
Address(SocketAddr),
Proxy {
url: BridgeUrl,
host: String,
listen: SocketAddr,
},
}
impl Listen {
pub(super) fn of(args: &BridgeSetupArgs) -> anyhow::Result<Self> {
match (&args.url, args.http) {
(Some(url), http) => {
let url: BridgeUrl = url.parse().context("--url")?;
if !url.is_secure() {
anyhow::bail!(
"--url {url} must be wss://: a bridge reached through a proxy carries its token over TLS; for an overlay or LAN address use --http"
);
}
let host = url::Url::parse(url.as_str())?
.host_str()
.map(|host| host.trim_matches(['[', ']']).to_owned())
.context("--url has no host")?;
let listen = http.unwrap_or(SocketAddr::from((Ipv4Addr::LOCALHOST, DEFAULT_PORT)));
if !listen.ip().is_loopback() {
anyhow::bail!(
"--http {listen} with --url: bind loopback, such as 127.0.0.1:{DEFAULT_PORT}, for the proxy to reach"
);
}
Ok(Self::Proxy { url, host, listen })
}
(None, Some(listen)) if !is_private(listen.ip()) => anyhow::bail!(
"--http {listen} is not a loopback or private address: a public address needs TLS, so bind 127.0.0.1:{DEFAULT_PORT} behind a TLS proxy and pass its address as --url wss://…"
),
(None, Some(listen)) => Ok(Self::Address(listen)),
(None, None) => Ok(Self::Overlay),
}
}
pub(super) fn wants_overlay(&self) -> bool {
match self {
Self::Overlay => true,
Self::Address(listen) => !listen.ip().is_loopback(),
Self::Proxy { .. } => false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Plan {
pub(super) listen: SocketAddr,
pub(super) allow_hosts: Vec<String>,
pub(super) url: BridgeUrl,
}
pub(super) fn plan(
listen: Listen,
overlay: Option<Result<Overlay, String>>,
extra_hosts: &[String],
) -> anyhow::Result<Plan> {
let (listen, mut allow_hosts, url) = match listen {
Listen::Proxy { url, host, listen } => (listen, vec![host], url),
Listen::Address(listen) => {
let names = overlay
.and_then(Result::ok)
.filter(|found| IpAddr::V4(found.ip) == listen.ip())
.map(|found| found.names())
.unwrap_or_default();
(listen, names, ws_url(listen)?)
}
Listen::Overlay => {
let found = overlay
.unwrap_or_else(|| Err("not asked".to_owned()))
.map_err(|why| {
anyhow::anyhow!(
"found no Tailscale or NetBird address for the bridge ({why}); pass --http with this machine's private address, such as 192.168.1.20:{DEFAULT_PORT}, or --url wss://… for a TLS proxy"
)
})?;
let listen = SocketAddr::from((found.ip, DEFAULT_PORT));
(listen, found.names(), ws_url(listen)?)
}
};
for host in extra_hosts {
if !allow_hosts.contains(host) {
allow_hosts.push(host.clone());
}
}
for host in &allow_hosts {
AllowedHost::parse(host)?;
}
Ok(Plan {
listen,
allow_hosts,
url,
})
}
fn ws_url(listen: SocketAddr) -> anyhow::Result<BridgeUrl> {
Ok(format!("ws://{listen}/ws").parse()?)
}
pub(super) fn serve_args(plan: &Plan) -> Vec<String> {
let mut args = vec![
"daemon".to_owned(),
"serve".to_owned(),
"--http".to_owned(),
plan.listen.to_string(),
];
for host in &plan.allow_hosts {
args.extend(["--allow-host".to_owned(), host.clone()]);
}
args
}
fn this_manager() -> anyhow::Result<ServiceManager> {
if cfg!(target_os = "linux") {
Ok(ServiceManager::Systemd)
} else if cfg!(target_os = "macos") {
Ok(ServiceManager::Launchd)
} else {
anyhow::bail!("{NO_SERVICE_MANAGER}")
}
}
fn installed_rho() -> anyhow::Result<PathBuf> {
let started = std::env::args_os().next().map(PathBuf::from);
if let Some(found) = started
.filter(|name| name.components().count() == 1)
.and_then(|name| which::which(name).ok())
{
return Ok(found);
}
crate::daemon::started_path().context("could not find the rho executable")
}
fn service_environment() -> Vec<(String, String)> {
["PATH", "RHO_HOME", "RHO_CREDENTIAL_STORE"]
.into_iter()
.filter_map(|name| Some((name.to_owned(), std::env::var(name).ok()?)))
.collect()
}
pub(super) fn bridge_service() -> anyhow::Result<(ServiceFiles, PathBuf)> {
let manager = this_manager()?;
let home = crate::paths::home_dir().context("could not determine the home directory")?;
let xdg_config_home = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
let service = ServiceFiles::daemon_http(manager, &home, xdg_config_home.as_deref());
Ok((service, home))
}
pub(crate) async fn setup(args: &BridgeSetupArgs, cli: &Cli) -> anyhow::Result<()> {
let (service, home) = bridge_service()?;
validate_name("token", &args.token)?;
let listen = Listen::of(args)?;
let overlay = if listen.wants_overlay() {
Some(find_overlay().await)
} else {
None
};
let plan = plan(listen, overlay, &args.allow_host)?;
ConfigRepository::new(cli.config.clone()).open_credential_store()?;
if service.manager == ServiceManager::Systemd
&& crate::credential_store::configured_backend()? == CredentialStoreBackend::Os
{
eprintln!(
"the bridge's tokens are in the OS keyring, which stays locked after a reboot until you log in to the desktop; for a bridge that answers from boot, run `rho credential-store set file` and set it up again"
);
}
let config = match &cli.config {
Some(path) => vec![
"--config".to_owned(),
std::path::absolute(path)?
.to_str()
.context("--config is not UTF-8")?
.to_owned(),
],
None => Vec::new(),
};
let spec = ServiceSpec {
program: installed_rho()?,
args: config.into_iter().chain(serve_args(&plan)).collect(),
environment: service_environment(),
pair_with: PairWith {
url: plan.url.clone(),
listen: plan.listen,
},
};
let text = setup_service::render(&service, &spec, &home)?;
install(&service, &text, plan.listen)?;
if service.manager == ServiceManager::Systemd {
match crate::daemon::keep_user_services_running() {
Ok(true) => {}
Ok(false) => eprintln!(
"turned on systemd linger for this user, so the bridge starts at boot and keeps running after logout"
),
Err(error) => eprintln!(
"could not turn on systemd linger, so the bridge stops when you log out and waits for a login after a reboot: {error}; run `sudo loginctl enable-linger $USER`"
),
}
}
issue_pairing(
&service,
&home,
&spec.pair_with,
&args.token,
"rho daemon bridge setup",
)
.await?;
eprintln!(
"the bridge serves {} as {}; paste the line above in rho-ui. It holds token {:?} and is shown only this once: running setup again replaces it.",
plan.url, service.unit, args.token
);
Ok(())
}
async fn issue_pairing(
service: &ServiceFiles,
home: &Path,
target: &PairWith,
name: &str,
again: &str,
) -> anyhow::Result<()> {
let (rotated, token) = token_store::update(|tokens: &mut DaemonTokenSet| {
Ok((tokens.contains(name), tokens.rotate(name)?))
})?;
if rotated {
eprintln!(
"rotated token {name:?}: the device it paired before stops reaching the bridge within {} s",
RECHECK_INTERVAL.as_secs()
);
}
probe(target.listen, &token).await.with_context(|| {
let earlier = if rotated {
format!(", and token {name:?}'s earlier pairing no longer works")
} else {
String::new()
};
format!(
"the bridge did not accept the new token on {}{earlier}. See {}; a bridge set up with another RHO_HOME, RHO_CREDENTIAL_STORE or --config reads another store, so run `{again}` with the same",
target.listen,
setup_service::log_location(service, home)
)
})?;
let machine = gethostname::gethostname().to_string_lossy().into_owned();
let machine = machine.split('.').next().unwrap_or_default().to_owned();
println!("{}", Pairing::new(target.url.clone(), token, machine));
Ok(())
}
const LISTENING_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) async fn pair(name: &str, cli: &Cli) -> anyhow::Result<()> {
let (service, home) = bridge_service()?;
validate_name("token", name)?;
let target = Installed::of(&service)?.pair_with()?;
match tokio::time::timeout(LISTENING_TIMEOUT, tokio::net::TcpStream::connect(target.listen)).await {
Ok(Ok(_)) => {}
Ok(Err(error)) => anyhow::bail!(
"the bridge does not answer on {}: {error}; start it with {}",
target.listen,
setup_service::start_command(&service)
),
Err(_) => anyhow::bail!(
"the bridge did not answer on {} within LISTENING_TIMEOUT ({LISTENING_TIMEOUT:?}); start it with {}",
target.listen,
setup_service::start_command(&service)
),
}
ConfigRepository::new(cli.config.clone()).open_credential_store()?;
issue_pairing(&service, &home, &target, name, "rho daemon bridge pair").await?;
eprintln!(
"paired {name:?} with the bridge at {}; paste the line above in rho-ui on that device. It is shown only this once: running pair again with this name replaces it.",
target.url
);
Ok(())
}
fn install(service: &ServiceFiles, text: &str, listen: SocketAddr) -> anyhow::Result<()> {
let replaced = match Installed::of(service)? {
Installed::ByHand => anyhow::bail!(
"{} was saved by hand, so setup leaves it alone; move it aside to let setup manage the bridge",
service.definition.display()
),
Installed::BySetup(installed) if installed == text => return Ok(service.start()?),
Installed::BySetup(_) => true,
Installed::Absent => false,
};
if replaced {
let _ = service.stop();
}
if let Err(error) = std::net::TcpListener::bind(listen) {
if replaced {
let _ = service.start();
}
return Err(error).with_context(|| {
format!("could not listen on {listen}; pass --http with a free port")
});
}
service
.install(text)
.with_context(|| format!("could not install {}", service.definition.display()))
}
async fn probe(listen: SocketAddr, token: &BridgeToken) -> anyhow::Result<()> {
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, http::HeaderValue};
let started = Instant::now();
loop {
let mut request = format!("ws://{listen}/ws").into_client_request()?;
request.headers_mut().insert(
"authorization",
HeaderValue::from_str(&format!("Bearer {}", token.secret()))?,
);
let error = match tokio_tungstenite::connect_async(request).await {
Ok((mut socket, _)) => {
let _ = socket.close(None).await;
return Ok(());
}
Err(error) => error,
};
let waited = started.elapsed();
if waited >= PROBE_TIMEOUT {
anyhow::bail!("{error} (PROBE_TIMEOUT {PROBE_TIMEOUT:?}; waited {waited:?})");
}
tokio::time::sleep(PROBE_INTERVAL).await;
}
}
pub(crate) fn remove(token: &str, cli: &Cli) -> anyhow::Result<()> {
let (service, _home) = bridge_service()?;
ConfigRepository::new(cli.config.clone()).open_credential_store()?;
let installed = match Installed::of(&service)? {
Installed::ByHand => {
eprintln!(
"left {}: it was saved by hand, not by setup",
service.definition.display()
);
false
}
Installed::BySetup(_) => true,
Installed::Absent => false,
};
if installed {
if let Err(error) = service.stop() {
eprintln!("could not stop {}: {error}", service.unit);
}
service.delete()?;
if let Err(error) = service.forget() {
eprintln!(
"could not have the service manager forget {}: {error}",
service.unit
);
}
println!("removed {}", service.unit);
}
let (revoked, left) = token_store::update(|tokens: &mut DaemonTokenSet| {
let revoked = tokens.revoke(token);
let left: Vec<String> = tokens
.tokens
.iter()
.map(|token| token.name.clone())
.collect();
Ok((revoked, left))
})?;
if revoked {
println!("revoked daemon token {token:?}");
}
if !installed && !revoked {
println!("no bridge service or daemon token {token:?} to remove");
}
if !left.is_empty() {
println!(
"daemon tokens still valid: {}; unpair each with `rho daemon token revoke <name>`",
left.join(", ")
);
}
Ok(())
}
#[cfg(test)]
#[path = "setup_tests.rs"]
mod tests;