//! systemd source over D-Bus. Every call hits the bus live; only the //! 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 zbus::zvariant::OwnedObjectPath; use zbus::Connection; use zbus_systemd::systemd1::{ManagerProxy, ServiceProxy, TimerProxy, UnitProxy}; use super::{SystemdSource, TimerInfo, UnitStatus, UnitSummary}; 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 = ( String, String, String, String, String, String, OwnedObjectPath, u32, String, OwnedObjectPath, ); /// Does not touch the bus on construction; the connection is made on first /// use and failures map to `AppError::Unavailable`. #[derive(Default)] pub struct DbusSystemd { /// Cached bus connection; cleared when found dead. conn: Mutex>, } impl DbusSystemd { 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) } /// 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: known type suffix, non-empty stem, systemd charset, /// at most 255 bytes. pub(crate) fn validate_unit_name(name: &str) -> Result<(), AppError> { 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() .all(|c| c.is_ascii_alphanumeric() || matches!(c, ':' | '_' | '.' | '@' | '-' | '\\')); if ok { Ok(()) } else { Err(AppError::BadRequest(format!("invalid unit name: {name:?}"))) } } /// 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 { return None; } let micros = i64::try_from(usec).ok()?; Timestamp::from_microsecond(micros).ok() } pub(crate) fn row_to_summary(row: UnitRow) -> UnitSummary { UnitSummary { name: row.0, description: row.1, load_state: row.2, active_state: row.3, sub_state: row.4, } } 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 { 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()); } 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(|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(|e| self.err(e))?; let mut out = Vec::with_capacity(rows.len()); for row in rows { 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, active_state: row.3, next_elapse: usec_to_ts(next), last_trigger: usec_to_ts(last), }); } Ok(out) } /// Read-only: uses `GetUnit`, so only units systemd already has in memory /// are visible. `LoadUnit` is never called (it would load arbitrary /// installed units); an unloaded unit is reported as not found. 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) => { return Err(AppError::NotFound(format!( "unit not loaded or unknown: {name}" ))) } Err(e) => return Err(self.err(e)), }; let unit = UnitProxy::builder(&conn) .path(path.clone()) .map_err(|e| self.err(e))? .build() .await .map_err(|e| self.err(e))?; let (desc, load, active, sub, enter, exit, frag, ufs) = futures::try_join!( unit.description(), unit.load_state(), unit.active_state(), unit.sub_state(), unit.active_enter_timestamp(), unit.active_exit_timestamp(), unit.fragment_path(), unit.unit_file_state(), ) .map_err(|e| self.err(e))?; if load == "not-found" { return Err(AppError::NotFound(format!("unit not found: {name}"))); } let mut st = UnitStatus { name: name.to_string(), description: desc, load_state: load, active_state: active, sub_state: sub, fragment_path: (!frag.is_empty()).then_some(frag), unit_file_state: (!ufs.is_empty()).then_some(ufs), active_enter_time: usec_to_ts(enter), active_exit_time: usec_to_ts(exit), main_pid: None, exec_main_status: None, n_restarts: None, result: None, }; if name.ends_with(".service") { let svc = ServiceProxy::builder(&conn) .path(path) .map_err(|e| self.err(e))? .build() .await .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(|e| self.err(e))?; st.main_pid = Some(pid); st.exec_main_status = Some(status); st.n_restarts = Some(restarts); st.result = Some(result); } Ok(st) } } #[cfg(test)] mod tests { use super::*; #[test] fn usec_conversion() { let ts = usec_to_ts(1_700_000_000_123_456).unwrap(); assert_eq!(ts.to_string(), "2023-11-14T22:13:20.123456Z"); } #[test] fn usec_sentinels() { assert!(usec_to_ts(0).is_none()); assert!(usec_to_ts(u64::MAX).is_none()); } #[test] fn tuple_mapping() { let p = OwnedObjectPath::try_from("/org/freedesktop/systemd1/unit/a_2eservice").unwrap(); let row: UnitRow = ( "a.service".into(), "A".into(), "loaded".into(), "active".into(), "running".into(), String::new(), p.clone(), 0, String::new(), p, ); let s = row_to_summary(row); assert_eq!(s.name, "a.service"); assert_eq!(s.description, "A"); assert_eq!(s.load_state, "loaded"); assert_eq!(s.active_state, "active"); assert_eq!(s.sub_state, "running"); } #[test] fn name_validation() { 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_state("Failed"), Err(AppError::BadRequest(_)) )); assert!(validate_state("bogus").is_err()); } }