From 6e7e4172b173cd4bd43cbdf2285188150552b656 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Thu, 15 Oct 2026 18:01:37 -0400 Subject: [PATCH] WS-A: review follow-ups (name/state validation, reconnect, error mapping) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs --- src/sources/systemd.rs | 261 ++++++++++++++++++++++++++++++++--------- 1 file changed, 207 insertions(+), 54 deletions(-) diff --git a/src/sources/systemd.rs b/src/sources/systemd.rs index f12f970..03f002f 100644 --- a/src/sources/systemd.rs +++ b/src/sources/systemd.rs @@ -1,9 +1,11 @@ //! 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 jiff::Timestamp; -use tokio::sync::OnceCell; use tokio_util::sync::CancellationToken; use zbus::zvariant::OwnedObjectPath; use zbus::Connection; @@ -15,6 +17,64 @@ use crate::error::AppError; const NO_SUCH_UNIT: &str = "org.freedesktop.systemd1.NoSuchUnit"; +/// Known unit-type suffixes; a valid name is ``. +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, /// unit path, job id, job type, job path. type UnitRow = ( @@ -31,7 +91,8 @@ type UnitRow = ( ); pub struct DbusSystemd { - conn: OnceCell, + /// Cached bus connection; cleared when found dead. + conn: Mutex>, #[allow(dead_code)] shutdown: CancellationToken, } @@ -41,29 +102,43 @@ impl DbusSystemd { /// failures map to `AppError::Unavailable`. pub fn new(_config: &Config, shutdown: CancellationToken) -> Self { Self { - conn: OnceCell::new(), + conn: Mutex::new(None), shutdown, } } - async fn conn(&self) -> Result<&Connection, AppError> { - self.conn - .get_or_try_init(|| async { - Connection::system() - .await - .map_err(|e| AppError::Unavailable(format!("system bus: {e}"))) - }) + async fn conn(&self) -> Result { + if let Some(c) = self.conn.lock().unwrap().clone() { + return Ok(c); + } + let c = Connection::system() .await + .map_err(|e| AppError::Unavailable(format!("system bus: {e}")))?; + *self.conn.lock().unwrap() = Some(c.clone()); + Ok(c) } - async fn manager(&self) -> Result, AppError> { - ManagerProxy::new(self.conn().await?).await.map_err(map_err) + /// Map a zbus error, dropping the cached connection if it looks dead. + 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, 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> { - 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 .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. pub(crate) fn usec_to_ts(usec: u64) -> Option { 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 { - 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 { if is_no_such_unit(&e) { return AppError::NotFound("unit not found".into()); } - match &e { - zbus::Error::InputOutput(_) | zbus::Error::Address(_) => { - AppError::Unavailable(format!("system bus: {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}")), + if dbus_name(&e) == Some("org.freedesktop.DBus.Error.InvalidArgs") + || matches!(fdo(&e), Some(zbus::fdo::Error::InvalidArgs(_))) + { + return AppError::BadRequest(format!("invalid argument: {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] 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, AppError> { + if let Some(s) = state { + validate_state(s)?; + } let mgr = self.manager().await?; let rows: Vec = match state { Some(s) => mgr .list_units_filtered(vec![s.to_string()]) .await - .map_err(map_err)?, - None => mgr.list_units().await.map_err(map_err)?, + .map_err(|e| self.err(e))?, + None => mgr.list_units().await.map_err(|e| self.err(e))?, }; 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, AppError> { let conn = self.conn().await?; let mgr = self.manager().await?; let rows: Vec = mgr .list_units_by_patterns(vec![], vec!["*.timer".to_string()]) .await - .map_err(map_err)?; + .map_err(|e| self.err(e))?; let mut out = Vec::with_capacity(rows.len()); for row in rows { - let timer = TimerProxy::builder(conn) - .path(row.6.clone()) - .map_err(map_err)? - .build() - .await - .map_err(map_err)?; - let (unit, next, last) = futures::try_join!( - timer.unit(), - timer.next_elapse_u_sec_realtime(), - timer.last_trigger_u_sec() - ) - .map_err(map_err)?; + let read = async { + let timer = TimerProxy::builder(&conn) + .path(row.6.clone())? + .build() + .await?; + futures::try_join!( + timer.unit(), + timer.next_elapse_u_sec_realtime(), + timer.last_trigger_u_sec() + ) + }; + 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 { name: row.0, unit, @@ -159,23 +296,26 @@ impl SystemdSource for DbusSystemd { 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 { validate_unit_name(name)?; let conn = self.conn().await?; let mgr = self.manager().await?; let path = match mgr.get_unit(name.to_string()).await { Ok(p) => p, - Err(e) if is_no_such_unit(&e) => { - mgr.load_unit(name.to_string()).await.map_err(map_err)? - } - Err(e) => return Err(map_err(e)), + Err(e) if is_no_such_unit(&e) => mgr + .load_unit(name.to_string()) + .await + .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()) - .map_err(map_err)? + .map_err(|e| self.err(e))? .build() .await - .map_err(map_err)?; + .map_err(|e| self.err(e))?; let (desc, load, active, sub, enter, exit, frag, ufs) = futures::try_join!( unit.description(), unit.load_state(), @@ -186,7 +326,7 @@ impl SystemdSource for DbusSystemd { unit.fragment_path(), unit.unit_file_state(), ) - .map_err(map_err)?; + .map_err(|e| self.err(e))?; if load == "not-found" { return Err(AppError::NotFound(format!("unit not found: {name}"))); } @@ -206,19 +346,19 @@ impl SystemdSource for DbusSystemd { result: None, }; if name.ends_with(".service") { - let svc = ServiceProxy::builder(conn) + let svc = ServiceProxy::builder(&conn) .path(path) - .map_err(map_err)? + .map_err(|e| self.err(e))? .build() .await - .map_err(map_err)?; + .map_err(|e| self.err(e))?; let (pid, status, restarts, result) = futures::try_join!( svc.main_pid(), svc.exec_main_status(), svc.n_restarts(), svc.result() ) - .map_err(map_err)?; + .map_err(|e| self.err(e))?; st.main_pid = Some(pid); st.exec_main_status = Some(status); st.n_restarts = Some(restarts); @@ -272,11 +412,24 @@ mod tests { assert!(validate_unit_name("sshd.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("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!( - validate_unit_name("../etc"), + validate_state("Failed"), Err(AppError::BadRequest(_)) )); - assert!(validate_unit_name("").is_err()); - assert!(validate_unit_name(&"a".repeat(256)).is_err()); + assert!(validate_state("bogus").is_err()); } }