use std::{
fmt::Write as _,
net::SocketAddr,
path::{Path, PathBuf},
};
use anyhow::Context as _;
use rho_protocol::BridgeUrl;
use serde::{Deserialize, Serialize};
use crate::daemon::{xml_escape, ServiceFiles, ServiceManager};
const WRITTEN_BY_SETUP: &str =
"Written by `rho daemon bridge setup`, which rewrites it; `rho daemon bridge remove` removes it.";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Installed {
Absent,
ByHand,
BySetup(String),
}
impl Installed {
pub(super) fn of(service: &ServiceFiles) -> anyhow::Result<Self> {
match std::fs::read_to_string(&service.definition) {
Ok(text) if text.contains(WRITTEN_BY_SETUP) => Ok(Self::BySetup(text)),
Ok(_) => Ok(Self::ByHand),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::Absent),
Err(error) => Err(error)
.with_context(|| format!("could not read {}", service.definition.display())),
}
}
pub(super) fn pair_with(&self) -> anyhow::Result<PairWith> {
match self {
Self::Absent => Err(Unpairable::NotInstalled.into()),
Self::ByHand => Err(Unpairable::ByHand.into()),
Self::BySetup(text) => Ok(PairWith::read(text)?.ok_or(Unpairable::Unrecorded)?),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub(super) enum Unpairable {
#[error("no bridge is installed; set one up with `rho daemon bridge setup`")]
NotInstalled,
#[error(
"the bridge's service was saved by hand, so pair cannot tell where clients reach it; pair by hand with `rho daemon token rotate <name>`"
)]
ByHand,
#[error(
"the bridge was set up by an earlier rho, which did not record where clients reach it; run `rho daemon bridge setup` again"
)]
Unrecorded,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct PairWith {
pub(super) url: BridgeUrl,
pub(super) listen: SocketAddr,
}
const PAIR_WITH: &str = "rho-bridge-pair ";
#[derive(Serialize, Deserialize)]
struct PairWithRecord {
url: String,
listen: SocketAddr,
}
impl PairWith {
fn record(&self) -> String {
let record = PairWithRecord {
url: self.url.to_string(),
listen: self.listen,
};
let json = serde_json::to_string(&record).expect("strings and an address encode");
format!("{PAIR_WITH}{}", json.replace('-', "\\u002d"))
}
pub(super) fn read(text: &str) -> anyhow::Result<Option<Self>> {
let Some(json) = text.lines().find_map(|line| {
let line = line.trim();
let comment = line
.strip_prefix('#')
.or_else(|| line.strip_prefix("<!--")?.strip_suffix("-->"))?;
comment.trim().strip_prefix(PAIR_WITH)
}) else {
return Ok(None);
};
let record: PairWithRecord = serde_json::from_str(json)
.context("the bridge's service file has a damaged pairing record")?;
Ok(Some(Self {
url: record
.url
.parse()
.context("the bridge's service file has a damaged pairing record")?,
listen: record.listen,
}))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ServiceSpec {
pub(super) program: PathBuf,
pub(super) args: Vec<String>,
pub(super) environment: Vec<(String, String)>,
pub(super) pair_with: PairWith,
}
pub(super) fn render(
service: &ServiceFiles,
spec: &ServiceSpec,
home: &Path,
) -> anyhow::Result<String> {
match service.manager {
ServiceManager::Systemd => systemd_unit(spec),
ServiceManager::Launchd => launchd_plist(service.unit, spec, &launchd_log(home)),
}
}
pub(super) fn log_location(service: &ServiceFiles, home: &Path) -> String {
match service.manager {
ServiceManager::Systemd => format!("`journalctl --user -u {}`", service.unit),
ServiceManager::Launchd => launchd_log(home).display().to_string(),
}
}
pub(super) fn start_command(service: &ServiceFiles) -> String {
match service.manager {
ServiceManager::Systemd => format!("`systemctl --user start {}`", service.unit),
ServiceManager::Launchd => format!("`launchctl kickstart gui/$UID/{}`", service.unit),
}
}
fn launchd_log(home: &Path) -> PathBuf {
home.join("Library/Logs/rho-daemon-http.log")
}
fn systemd_unit(spec: &ServiceSpec) -> anyhow::Result<String> {
let program = utf8(&spec.program)?;
if program.contains(['"', '\'', '\\']) {
anyhow::bail!(
"systemd cannot run {program}: its path holds a quote or a backslash; install rho elsewhere"
);
}
let exec: Vec<String> = std::iter::once(program.replace('%', "%%"))
.chain(
spec.args
.iter()
.map(|arg| systemd_escape(arg, true)),
)
.map(|arg| format!("\"{arg}\""))
.collect();
let mut unit = format!(
"# {WRITTEN_BY_SETUP}\n\
# {}\n\
[Unit]\n\
Description=rho daemon HTTP WebSocket bridge\n\
After=network.target\n\
\n\
[Service]\n",
spec.pair_with.record()
);
let _ = writeln!(unit, "ExecStart={}", exec.join(" "));
for (name, value) in &spec.environment {
let assignment =
systemd_escape(&format!("{name}={value}"), false);
let _ = writeln!(unit, "Environment=\"{assignment}\"");
}
unit.push_str(
"# Stop only the bridge. The daemon keeps running its turns.\n\
KillMode=process\n\
Restart=always\n\
RestartSec=10\n\
\n\
[Install]\n\
WantedBy=default.target\n",
);
Ok(unit)
}
fn systemd_escape(value: &str, expands_variables: bool) -> String {
let mut escaped = String::with_capacity(value.len());
for c in value.chars() {
match c {
'\\' => escaped.push_str("\\\\"),
'"' => escaped.push_str("\\\""),
'%' => escaped.push_str("%%"),
'$' if expands_variables => escaped.push_str("$$"),
'\n' => escaped.push_str("\\n"),
c => escaped.push(c),
}
}
escaped
}
fn launchd_plist(label: &str, spec: &ServiceSpec, log: &Path) -> anyhow::Result<String> {
let mut plist = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
<!-- {WRITTEN_BY_SETUP} -->\n\
<!-- {} -->\n\
<plist version=\"1.0\">\n\
<dict>\n",
spec.pair_with.record()
);
let _ = writeln!(plist, " <key>Label</key>\n <string>{label}</string>");
plist.push_str(" <key>ProgramArguments</key>\n <array>\n");
for arg in std::iter::once(utf8(&spec.program)?).chain(spec.args.iter().map(String::as_str)) {
let _ = writeln!(plist, " <string>{}</string>", xml_escape(arg));
}
plist.push_str(" </array>\n <key>EnvironmentVariables</key>\n <dict>\n");
for (name, value) in &spec.environment {
let _ = writeln!(
plist,
" <key>{}</key>\n <string>{}</string>",
xml_escape(name),
xml_escape(value)
);
}
plist.push_str(
" </dict>\n\
\x20 <!-- Stop only the bridge. The daemon keeps running its turns. -->\n\
\x20 <key>AbandonProcessGroup</key>\n <true/>\n\
\x20 <key>RunAtLoad</key>\n <true/>\n\
\x20 <key>KeepAlive</key>\n <true/>\n",
);
let _ = writeln!(
plist,
" <key>StandardErrorPath</key>\n <string>{}</string>\n</dict>\n</plist>",
xml_escape(utf8(log)?)
);
Ok(plist)
}
fn utf8(path: &Path) -> anyhow::Result<&str> {
path.to_str().with_context(|| {
format!(
"{} is not UTF-8, which a service file cannot hold",
path.display()
)
})
}
#[cfg(test)]
#[path = "setup_service_tests.rs"]
mod tests;