WS-A: review follow-ups (name/state validation, reconnect, error mapping)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-15 18:01:37 -04:00
1 parent 5e7a323020
commit 6e7e4172b1
1 file changed
+207 -54
+207 -54
View File
@@ -1,9 +1,11 @@
//! systemd source over D-Bus (WS-A). Every call hits the bus live; only the //! systemd source over D-Bus (WS-A). Every call hits the bus live; only the
//! connection is cached, and it is opened lazily on first use. //! connection is cached, and it is opened lazily on first use. A connection
//! found dead is dropped so the next call reconnects.
use std::sync::Mutex;
use async_trait::async_trait; use async_trait::async_trait;
use jiff::Timestamp; use jiff::Timestamp;
use tokio::sync::OnceCell;
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use zbus::zvariant::OwnedObjectPath; use zbus::zvariant::OwnedObjectPath;
use zbus::Connection; use zbus::Connection;
@@ -15,6 +17,64 @@ use crate::error::AppError;
const NO_SUCH_UNIT: &str = "org.freedesktop.systemd1.NoSuchUnit"; const NO_SUCH_UNIT: &str = "org.freedesktop.systemd1.NoSuchUnit";
/// Known unit-type suffixes; a valid name is `<non-empty stem><suffix>`.
const UNIT_SUFFIXES: &[&str] = &[
".service",
".timer",
".socket",
".target",
".mount",
".path",
".slice",
".scope",
".automount",
".swap",
".device",
];
/// Accepted values for the `state` filter of `list_units`. `ListUnitsFiltered`
/// matches a unit if the value equals its load, active or sub state.
const KNOWN_STATES: &[&str] = &[
// active states
"active",
"reloading",
"inactive",
"failed",
"activating",
"deactivating",
"maintenance",
"refreshing",
// load states
"loaded",
"not-found",
"bad-setting",
"error",
"masked",
"stub",
"merged",
// common sub states
"running",
"exited",
"dead",
"waiting",
"listening",
"mounted",
"plugged",
"elapsed",
"start-pre",
"start",
"start-post",
"stop",
"stop-sigterm",
"stop-sigkill",
"stop-post",
"auto-restart",
"condition",
"final-sigterm",
"final-sigkill",
"abandoned",
];
/// One `ListUnits` row: name, description, load, active, sub, followed, /// One `ListUnits` row: name, description, load, active, sub, followed,
/// unit path, job id, job type, job path. /// unit path, job id, job type, job path.
type UnitRow = ( type UnitRow = (
@@ -31,7 +91,8 @@ type UnitRow = (
); );
pub struct DbusSystemd { pub struct DbusSystemd {
conn: OnceCell<Connection>, /// Cached bus connection; cleared when found dead.
conn: Mutex<Option<Connection>>,
#[allow(dead_code)] #[allow(dead_code)]
shutdown: CancellationToken, shutdown: CancellationToken,
} }
@@ -41,29 +102,43 @@ impl DbusSystemd {
/// failures map to `AppError::Unavailable`. /// failures map to `AppError::Unavailable`.
pub fn new(_config: &Config, shutdown: CancellationToken) -> Self { pub fn new(_config: &Config, shutdown: CancellationToken) -> Self {
Self { Self {
conn: OnceCell::new(), conn: Mutex::new(None),
shutdown, shutdown,
} }
} }
async fn conn(&self) -> Result<&Connection, AppError> { async fn conn(&self) -> Result<Connection, AppError> {
self.conn if let Some(c) = self.conn.lock().unwrap().clone() {
.get_or_try_init(|| async { return Ok(c);
Connection::system() }
.await let c = Connection::system()
.map_err(|e| AppError::Unavailable(format!("system bus: {e}")))
})
.await .await
.map_err(|e| AppError::Unavailable(format!("system bus: {e}")))?;
*self.conn.lock().unwrap() = Some(c.clone());
Ok(c)
} }
async fn manager(&self) -> Result<ManagerProxy<'_>, AppError> { /// Map a zbus error, dropping the cached connection if it looks dead.
ManagerProxy::new(self.conn().await?).await.map_err(map_err) fn err(&self, e: zbus::Error) -> AppError {
if is_dead_bus(&e) {
*self.conn.lock().unwrap() = None;
}
map_err(e)
}
async fn manager(&self) -> Result<ManagerProxy<'static>, AppError> {
let conn = self.conn().await?;
ManagerProxy::new(&conn).await.map_err(|e| self.err(e))
} }
} }
/// Validate a unit name against systemd's charset and length limit. /// Validate a unit name: known type suffix, non-empty stem, systemd charset,
/// at most 255 bytes.
pub(crate) fn validate_unit_name(name: &str) -> Result<(), AppError> { pub(crate) fn validate_unit_name(name: &str) -> Result<(), AppError> {
let ok = !name.is_empty() let stem_ok = UNIT_SUFFIXES
.iter()
.any(|suf| name.strip_suffix(suf).is_some_and(|stem| !stem.is_empty()));
let ok = stem_ok
&& name.len() <= 255 && name.len() <= 255
&& name && name
.chars() .chars()
@@ -75,6 +150,15 @@ pub(crate) fn validate_unit_name(name: &str) -> Result<(), AppError> {
} }
} }
/// Validate a `list_units` state filter (case-sensitive, single value).
pub(crate) fn validate_state(state: &str) -> Result<(), AppError> {
if KNOWN_STATES.contains(&state) {
Ok(())
} else {
Err(AppError::BadRequest(format!("unknown state: {state:?}")))
}
}
/// Microseconds since the epoch to a timestamp. `0` and `u64::MAX` mean unset. /// Microseconds since the epoch to a timestamp. `0` and `u64::MAX` mean unset.
pub(crate) fn usec_to_ts(usec: u64) -> Option<Timestamp> { pub(crate) fn usec_to_ts(usec: u64) -> Option<Timestamp> {
if usec == 0 || usec == u64::MAX { if usec == 0 || usec == u64::MAX {
@@ -94,60 +178,113 @@ pub(crate) fn row_to_summary(row: UnitRow) -> UnitSummary {
} }
} }
fn dbus_name(e: &zbus::Error) -> Option<&str> {
match e {
zbus::Error::MethodError(n, _, _) => Some(n.as_str()),
_ => None,
}
}
fn fdo(e: &zbus::Error) -> Option<&zbus::fdo::Error> {
match e {
zbus::Error::FDO(f) => Some(f),
_ => None,
}
}
fn is_no_such_unit(e: &zbus::Error) -> bool { fn is_no_such_unit(e: &zbus::Error) -> bool {
matches!(e, zbus::Error::MethodError(n, _, _) if n.as_str() == NO_SUCH_UNIT) dbus_name(e) == Some(NO_SUCH_UNIT)
}
fn is_unknown_object(e: &zbus::Error) -> bool {
is_no_such_unit(e)
|| dbus_name(e) == Some("org.freedesktop.DBus.Error.UnknownObject")
|| matches!(fdo(e), Some(zbus::fdo::Error::UnknownObject(_)))
}
fn is_dead_bus(e: &zbus::Error) -> bool {
matches!(e, zbus::Error::InputOutput(_))
|| matches!(
fdo(e),
Some(zbus::fdo::Error::Disconnected(_) | zbus::fdo::Error::NoReply(_))
)
|| matches!(
dbus_name(e),
Some("org.freedesktop.DBus.Error.Disconnected" | "org.freedesktop.DBus.Error.NoReply")
)
} }
fn map_err(e: zbus::Error) -> AppError { fn map_err(e: zbus::Error) -> AppError {
if is_no_such_unit(&e) { if is_no_such_unit(&e) {
return AppError::NotFound("unit not found".into()); return AppError::NotFound("unit not found".into());
} }
match &e { if dbus_name(&e) == Some("org.freedesktop.DBus.Error.InvalidArgs")
zbus::Error::InputOutput(_) | zbus::Error::Address(_) => { || matches!(fdo(&e), Some(zbus::fdo::Error::InvalidArgs(_)))
AppError::Unavailable(format!("system bus: {e}")) {
} return AppError::BadRequest(format!("invalid argument: {e}"));
zbus::Error::FDO(f) if matches!(**f, zbus::fdo::Error::ServiceUnknown(_)) => {
AppError::Unavailable(format!("systemd not reachable: {e}"))
}
_ => AppError::Internal(format!("systemd d-bus: {e}")),
} }
let denied = dbus_name(&e) == Some("org.freedesktop.DBus.Error.AccessDenied")
|| matches!(fdo(&e), Some(zbus::fdo::Error::AccessDenied(_)));
if is_dead_bus(&e)
|| denied
|| matches!(e, zbus::Error::Address(_))
|| matches!(fdo(&e), Some(zbus::fdo::Error::ServiceUnknown(_)))
{
return AppError::Unavailable(format!("systemd not reachable: {e}"));
}
AppError::Internal(format!("systemd d-bus: {e}"))
} }
#[async_trait] #[async_trait]
impl SystemdSource for DbusSystemd { impl SystemdSource for DbusSystemd {
/// `state` is a single, case-sensitive value from a known set (active,
/// failed, running, masked, ...); `ListUnitsFiltered` matches it against
/// load, active and sub state. Unknown values are `BadRequest`.
async fn list_units(&self, state: Option<&str>) -> Result<Vec<UnitSummary>, AppError> { async fn list_units(&self, state: Option<&str>) -> Result<Vec<UnitSummary>, AppError> {
if let Some(s) = state {
validate_state(s)?;
}
let mgr = self.manager().await?; let mgr = self.manager().await?;
let rows: Vec<UnitRow> = match state { let rows: Vec<UnitRow> = match state {
Some(s) => mgr Some(s) => mgr
.list_units_filtered(vec![s.to_string()]) .list_units_filtered(vec![s.to_string()])
.await .await
.map_err(map_err)?, .map_err(|e| self.err(e))?,
None => mgr.list_units().await.map_err(map_err)?, None => mgr.list_units().await.map_err(|e| self.err(e))?,
}; };
Ok(rows.into_iter().map(row_to_summary).collect()) Ok(rows.into_iter().map(row_to_summary).collect())
} }
/// `next_elapse` comes from `NextElapseUSecRealtime` only. Purely
/// monotonic timers (`OnBootSec=`, `OnUnitActiveSec=`) report `0` there and
/// show `None`; deriving a wall-clock time would need the boot-relative
/// monotonic clock and is deliberately not attempted.
async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError> { async fn list_timers(&self) -> Result<Vec<TimerInfo>, AppError> {
let conn = self.conn().await?; let conn = self.conn().await?;
let mgr = self.manager().await?; let mgr = self.manager().await?;
let rows: Vec<UnitRow> = mgr let rows: Vec<UnitRow> = mgr
.list_units_by_patterns(vec![], vec!["*.timer".to_string()]) .list_units_by_patterns(vec![], vec!["*.timer".to_string()])
.await .await
.map_err(map_err)?; .map_err(|e| self.err(e))?;
let mut out = Vec::with_capacity(rows.len()); let mut out = Vec::with_capacity(rows.len());
for row in rows { for row in rows {
let timer = TimerProxy::builder(conn) let read = async {
.path(row.6.clone()) let timer = TimerProxy::builder(&conn)
.map_err(map_err)? .path(row.6.clone())?
.build() .build()
.await .await?;
.map_err(map_err)?; futures::try_join!(
let (unit, next, last) = futures::try_join!( timer.unit(),
timer.unit(), timer.next_elapse_u_sec_realtime(),
timer.next_elapse_u_sec_realtime(), timer.last_trigger_u_sec()
timer.last_trigger_u_sec() )
) };
.map_err(map_err)?; let (unit, next, last) = match read.await {
Ok(v) => v,
// Timer vanished between list and read.
Err(e) if is_unknown_object(&e) => continue,
Err(e) => return Err(self.err(e)),
};
out.push(TimerInfo { out.push(TimerInfo {
name: row.0, name: row.0,
unit, unit,
@@ -159,23 +296,26 @@ impl SystemdSource for DbusSystemd {
Ok(out) Ok(out)
} }
/// Note: for a name that is not loaded this calls `LoadUnit`, which asks
/// systemd to load the unit (a side effect, though it does not start it).
async fn unit_status(&self, name: &str) -> Result<UnitStatus, AppError> { async fn unit_status(&self, name: &str) -> Result<UnitStatus, AppError> {
validate_unit_name(name)?; validate_unit_name(name)?;
let conn = self.conn().await?; let conn = self.conn().await?;
let mgr = self.manager().await?; let mgr = self.manager().await?;
let path = match mgr.get_unit(name.to_string()).await { let path = match mgr.get_unit(name.to_string()).await {
Ok(p) => p, Ok(p) => p,
Err(e) if is_no_such_unit(&e) => { Err(e) if is_no_such_unit(&e) => mgr
mgr.load_unit(name.to_string()).await.map_err(map_err)? .load_unit(name.to_string())
} .await
Err(e) => return Err(map_err(e)), .map_err(|e| self.err(e))?,
Err(e) => return Err(self.err(e)),
}; };
let unit = UnitProxy::builder(conn) let unit = UnitProxy::builder(&conn)
.path(path.clone()) .path(path.clone())
.map_err(map_err)? .map_err(|e| self.err(e))?
.build() .build()
.await .await
.map_err(map_err)?; .map_err(|e| self.err(e))?;
let (desc, load, active, sub, enter, exit, frag, ufs) = futures::try_join!( let (desc, load, active, sub, enter, exit, frag, ufs) = futures::try_join!(
unit.description(), unit.description(),
unit.load_state(), unit.load_state(),
@@ -186,7 +326,7 @@ impl SystemdSource for DbusSystemd {
unit.fragment_path(), unit.fragment_path(),
unit.unit_file_state(), unit.unit_file_state(),
) )
.map_err(map_err)?; .map_err(|e| self.err(e))?;
if load == "not-found" { if load == "not-found" {
return Err(AppError::NotFound(format!("unit not found: {name}"))); return Err(AppError::NotFound(format!("unit not found: {name}")));
} }
@@ -206,19 +346,19 @@ impl SystemdSource for DbusSystemd {
result: None, result: None,
}; };
if name.ends_with(".service") { if name.ends_with(".service") {
let svc = ServiceProxy::builder(conn) let svc = ServiceProxy::builder(&conn)
.path(path) .path(path)
.map_err(map_err)? .map_err(|e| self.err(e))?
.build() .build()
.await .await
.map_err(map_err)?; .map_err(|e| self.err(e))?;
let (pid, status, restarts, result) = futures::try_join!( let (pid, status, restarts, result) = futures::try_join!(
svc.main_pid(), svc.main_pid(),
svc.exec_main_status(), svc.exec_main_status(),
svc.n_restarts(), svc.n_restarts(),
svc.result() svc.result()
) )
.map_err(map_err)?; .map_err(|e| self.err(e))?;
st.main_pid = Some(pid); st.main_pid = Some(pid);
st.exec_main_status = Some(status); st.exec_main_status = Some(status);
st.n_restarts = Some(restarts); st.n_restarts = Some(restarts);
@@ -272,11 +412,24 @@ mod tests {
assert!(validate_unit_name("sshd.service").is_ok()); assert!(validate_unit_name("sshd.service").is_ok());
assert!(validate_unit_name("getty@tty1.service").is_ok()); assert!(validate_unit_name("getty@tty1.service").is_ok());
assert!(validate_unit_name("dev-disk-by\\x2did.device").is_ok()); assert!(validate_unit_name("dev-disk-by\\x2did.device").is_ok());
assert!(validate_unit_name("a.timer").is_ok());
for bad in ["", "..", "../etc", "foo", "a.b", ".service", "x/y.service"] {
assert!(
matches!(validate_unit_name(bad), Err(AppError::BadRequest(_))),
"{bad}"
);
}
assert!(validate_unit_name(&format!("{}.service", "a".repeat(250))).is_err());
}
#[test]
fn state_validation() {
assert!(validate_state("failed").is_ok());
assert!(validate_state("running").is_ok());
assert!(matches!( assert!(matches!(
validate_unit_name("../etc"), validate_state("Failed"),
Err(AppError::BadRequest(_)) Err(AppError::BadRequest(_))
)); ));
assert!(validate_unit_name("").is_err()); assert!(validate_state("bogus").is_err());
assert!(validate_unit_name(&"a".repeat(256)).is_err());
} }
} }