hyprstream_service/service/manager/
systemd.rs1use super::{units, ServiceManager};
6use crate::service::spawner::{Spawnable, SpawnedService};
7use anyhow::{anyhow, Context as _, Result};
8use async_trait::async_trait;
9use std::path::PathBuf;
10use tracing::{debug, info};
11use zbus_systemd::login1::ManagerProxy as LoginProxy;
12use zbus_systemd::systemd1::ManagerProxy;
13use zbus_systemd::zbus::Connection;
14
15async fn user_systemd_connection() -> Result<Connection> {
26 if let Ok(conn) = Connection::session().await {
28 return Ok(conn);
29 }
30
31 let uid = nix::unistd::getuid().as_raw();
33 let rt = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| format!("/run/user/{uid}"));
34 let bus_path = format!("{rt}/bus");
35 zbus_systemd::zbus::ConnectionBuilder::address(format!("unix:path={bus_path}").as_str())?
36 .build()
37 .await
38 .with_context(|| {
39 format!(
40 "could not connect to user D-Bus (tried $DBUS_SESSION_BUS_ADDRESS and {bus_path})"
41 )
42 })
43}
44
45pub struct SystemdManager {
50 #[allow(dead_code)]
51 connection: Connection,
52 systemd: ManagerProxy<'static>,
53}
54
55impl SystemdManager {
56 pub async fn new() -> Result<Self> {
64 let connection = user_systemd_connection().await?;
65 let systemd = ManagerProxy::new(&connection).await?;
66
67 let system_connection = Connection::system().await?;
71 let login = LoginProxy::new(&system_connection).await?;
72 let uid = nix::unistd::getuid().as_raw();
73 if let Err(e) = login.set_user_linger(uid, true, false).await {
74 debug!(
75 "Failed to enable user linger (may already be enabled): {}",
76 e
77 );
78 } else {
79 debug!("User lingering enabled");
80 }
81
82 Ok(Self {
83 connection,
84 systemd,
85 })
86 }
87
88 pub async fn new_session() -> Result<Self> {
94 let connection = Connection::session().await.context(
95 "could not connect to D-Bus session bus (is $DBUS_SESSION_BUS_ADDRESS set?)",
96 )?;
97 let systemd = ManagerProxy::new(&connection).await?;
98 Ok(Self {
99 connection,
100 systemd,
101 })
102 }
103
104 #[allow(dead_code)]
105 fn socket_unit(service: &str) -> String {
106 format!("hyprstream-{service}.socket")
107 }
108
109 fn service_unit(service: &str) -> String {
110 format!("hyprstream-{service}.service")
111 }
112
113 fn units_dir() -> Result<PathBuf> {
114 dirs::config_dir()
115 .map(|d| d.join("systemd/user"))
116 .ok_or_else(|| anyhow!("cannot determine config directory"))
117 }
118}
119
120pub struct SystemdSystemManager {
125 #[allow(dead_code)]
126 connection: Connection,
127 systemd: ManagerProxy<'static>,
128}
129
130impl SystemdSystemManager {
131 pub async fn new() -> Result<Self> {
132 let connection = Connection::system().await?;
133 let systemd = ManagerProxy::new(&connection).await?;
134 Ok(Self {
135 connection,
136 systemd,
137 })
138 }
139
140 fn service_unit(service: &str) -> String {
141 format!("hyprstream-{service}.service")
142 }
143
144 fn units_dir() -> PathBuf {
145 PathBuf::from("/etc/systemd/system")
146 }
147}
148
149#[async_trait]
150impl ServiceManager for SystemdSystemManager {
151 async fn install(&self, service: &str) -> Result<()> {
152 let units_dir = Self::units_dir();
153 std::fs::create_dir_all(&units_dir)?;
154
155 let depends_on = crate::service::factory::get_factory(service)
156 .map(|f| f.depends_on)
157 .unwrap_or(&[]);
158
159 let service_content = units::system_service_unit(service, depends_on)?;
160 let service_path = units_dir.join(Self::service_unit(service));
161
162 if std::fs::read_to_string(&service_path).ok().as_deref() != Some(&service_content) {
163 std::fs::write(&service_path, &service_content)?;
164 info!("Installed system service unit: {}", service_path.display());
165 self.reload().await?;
166 }
167
168 Ok(())
169 }
170
171 async fn uninstall(&self, service: &str) -> Result<()> {
172 let _ = self.stop(service).await;
173 let path = Self::units_dir().join(Self::service_unit(service));
174 if path.exists() {
175 std::fs::remove_file(&path)?;
176 info!("Removed: {}", path.display());
177 }
178 self.reload().await
179 }
180
181 async fn start(&self, service: &str) -> Result<()> {
182 self.systemd
183 .start_unit(Self::service_unit(service), "replace".into())
184 .await?;
185 info!(
186 "Started system service unit: {}",
187 Self::service_unit(service)
188 );
189 Ok(())
190 }
191
192 async fn stop(&self, service: &str) -> Result<()> {
193 self.systemd
194 .stop_unit(Self::service_unit(service), "replace".into())
195 .await?;
196 info!(
197 "Stopped system service unit: {}",
198 Self::service_unit(service)
199 );
200 Ok(())
201 }
202
203 async fn is_active(&self, service: &str) -> Result<bool> {
204 match self.systemd.get_unit(Self::service_unit(service)).await {
205 Ok(unit_path) => {
206 let unit =
207 zbus_systemd::systemd1::UnitProxy::builder(self.systemd.inner().connection())
208 .path(unit_path)?
209 .build()
210 .await?;
211 let state = unit.active_state().await?;
212 Ok(state == "active")
213 }
214 Err(_) => Ok(false),
215 }
216 }
217
218 async fn reload(&self) -> Result<()> {
219 let status = tokio::process::Command::new("systemctl")
220 .arg("daemon-reload")
221 .status()
222 .await
223 .context("failed to spawn systemctl daemon-reload")?;
224 if !status.success() {
225 anyhow::bail!("systemctl daemon-reload failed (exit {})", status);
226 }
227 debug!("Reloaded systemd system daemon");
228 Ok(())
229 }
230
231 async fn enable(&self, service: &str) -> Result<()> {
232 let status = tokio::process::Command::new("systemctl")
233 .args(["enable", &Self::service_unit(service)])
234 .status()
235 .await
236 .context("failed to spawn systemctl enable")?;
237 if !status.success() {
238 anyhow::bail!(
239 "systemctl enable {} failed (exit {})",
240 Self::service_unit(service),
241 status
242 );
243 }
244 debug!(
245 "Enabled system service unit: {}",
246 Self::service_unit(service)
247 );
248 Ok(())
249 }
250
251 async fn spawn(&self, service: Box<dyn Spawnable>) -> Result<SpawnedService> {
252 self.ensure(service.name()).await?;
253 Ok(SpawnedService::dummy())
254 }
255}
256
257#[async_trait]
258impl ServiceManager for SystemdManager {
259 async fn install(&self, service: &str) -> Result<()> {
260 let units_dir = Self::units_dir()?;
261 std::fs::create_dir_all(&units_dir)?;
262
263 let use_creds = credstore_has_credentials();
268
269 let depends_on = crate::service::factory::get_factory(service)
271 .map(|f| f.depends_on)
272 .unwrap_or(&[]);
273
274 let service_content = units::service_unit(service, use_creds, depends_on)?;
275 let service_path = units_dir.join(Self::service_unit(service));
276
277 if std::fs::read_to_string(&service_path).ok().as_deref() != Some(&service_content) {
280 std::fs::write(&service_path, &service_content)?;
281 info!("Installed service unit: {}", service_path.display());
282 self.reload().await?;
283 }
284
285 Ok(())
286 }
287
288 async fn start(&self, service: &str) -> Result<()> {
289 self.systemd
290 .start_unit(Self::service_unit(service), "replace".into())
291 .await?;
292 info!("Started service unit: {}", Self::service_unit(service));
293 Ok(())
294 }
295
296 async fn stop(&self, service: &str) -> Result<()> {
297 self.systemd
298 .stop_unit(Self::service_unit(service), "replace".into())
299 .await?;
300 info!("Stopped service unit: {}", Self::service_unit(service));
301 Ok(())
302 }
303
304 async fn is_active(&self, service: &str) -> Result<bool> {
305 match self.systemd.get_unit(Self::service_unit(service)).await {
307 Ok(unit_path) => {
308 let unit =
310 zbus_systemd::systemd1::UnitProxy::builder(self.systemd.inner().connection())
311 .path(unit_path)?
312 .build()
313 .await?;
314 let state = unit.active_state().await?;
315 Ok(state == "active")
316 }
317 Err(_) => Ok(false),
318 }
319 }
320
321 async fn reload(&self) -> Result<()> {
322 let status = tokio::process::Command::new("systemctl")
326 .args(["--user", "daemon-reload"])
327 .status()
328 .await
329 .context("failed to spawn systemctl --user daemon-reload")?;
330 if !status.success() {
331 anyhow::bail!("systemctl --user daemon-reload failed (exit {})", status);
332 }
333 debug!("Reloaded systemd user daemon");
334 Ok(())
335 }
336
337 async fn enable(&self, service: &str) -> Result<()> {
338 let status = tokio::process::Command::new("systemctl")
339 .args(["--user", "enable", &Self::service_unit(service)])
340 .status()
341 .await
342 .context("failed to spawn systemctl --user enable")?;
343 if !status.success() {
344 anyhow::bail!(
345 "systemctl --user enable {} failed (exit {})",
346 Self::service_unit(service),
347 status
348 );
349 }
350 debug!("Enabled service unit: {}", Self::service_unit(service));
351 Ok(())
352 }
353
354 async fn uninstall(&self, service: &str) -> Result<()> {
355 let _ = self.stop(service).await;
357
358 let units_dir = Self::units_dir()?;
360 let service_path = units_dir.join(Self::service_unit(service));
361
362 if service_path.exists() {
363 std::fs::remove_file(&service_path)?;
364 info!("Removed: {}", service_path.display());
365 }
366
367 self.reload().await
368 }
369
370 async fn spawn(&self, service: Box<dyn Spawnable>) -> Result<SpawnedService> {
371 self.ensure(service.name()).await?;
373 Ok(SpawnedService::dummy())
374 }
375}
376
377fn credstore_has_credentials() -> bool {
386 let Some(credstore) = dirs::config_dir().map(|d| d.join("credstore.encrypted")) else {
387 return false;
388 };
389 if !credstore.exists() {
390 return false;
391 }
392 units::ALL_CREDENTIAL_NAMES
393 .iter()
394 .any(|name| credstore.join(name).exists())
395}
396
397fn has_systemd_creds() -> bool {
401 std::process::Command::new("systemd-creds")
402 .arg("--version")
403 .stdout(std::process::Stdio::null())
404 .stderr(std::process::Stdio::null())
405 .status()
406 .map(|s| s.success())
407 .unwrap_or(false)
408}
409
410fn systemd_creds_encrypt(name: &str, plaintext: &[u8], credstore: &std::path::Path) -> Result<()> {
415 use std::io::Write as _;
416 let output_path = credstore.join(name);
417 let mut child = std::process::Command::new("systemd-creds")
418 .args([
419 "encrypt",
420 "--user",
421 &format!("--name={name}"),
422 "--with-key=auto",
423 "-", output_path.to_str().unwrap_or("-"),
425 ])
426 .stdin(std::process::Stdio::piped())
427 .stdout(std::process::Stdio::null())
428 .stderr(std::process::Stdio::piped())
429 .spawn()
430 .with_context(|| format!("failed to spawn systemd-creds for '{name}'"))?;
431
432 child
433 .stdin
434 .as_mut()
435 .ok_or_else(|| anyhow!("no stdin on systemd-creds"))?
436 .write_all(plaintext)
437 .context("failed to write plaintext to systemd-creds stdin")?;
438
439 let output = child
440 .wait_with_output()
441 .with_context(|| format!("systemd-creds failed for '{name}'"))?;
442
443 if !output.status.success() {
444 let stderr = String::from_utf8_lossy(&output.stderr);
445 anyhow::bail!("systemd-creds encrypt failed for '{name}': {stderr}");
446 }
447
448 debug!("Encrypted credential '{name}' → {}", output_path.display());
449 Ok(())
450}
451
452pub fn encrypt_credentials_if_available(secrets_dir: Option<&std::path::Path>) -> bool {
470 if !has_systemd_creds() {
471 tracing::warn!(
472 "systemd-creds not found on $PATH; service unit will not use ImportCredential=.\n\
473 Secret files will be stored as plain files (mode 0600).\n\
474 Install systemd 250+ and re-run 'hyprstream service install' to enable \
475 TPM2/host-key-backed credential protection."
476 );
477 return false;
478 }
479
480 let default_dir;
481 let dir: &std::path::Path = match secrets_dir {
482 Some(d) => d,
483 None => {
484 default_dir = match units::hyprstream_config_dir() {
485 Ok(dir) => dir.map(|d| d.join("credentials")),
486 Err(error) => {
487 tracing::error!(
488 "Invalid instance name while resolving credentials directory: {error}"
489 );
490 return false;
491 }
492 };
493 match default_dir.as_deref() {
494 Some(d) => d,
495 None => {
496 tracing::warn!(
497 "Could not determine config dir for secrets; skipping credential encryption"
498 );
499 return false;
500 }
501 }
502 }
503 };
504
505 let credstore = match dirs::config_dir() {
506 Some(d) => d.join("credstore.encrypted"),
507 None => {
508 tracing::warn!(
509 "Could not determine config dir for credstore; skipping credential encryption"
510 );
511 return false;
512 }
513 };
514
515 if let Err(e) = std::fs::create_dir_all(&credstore) {
516 tracing::warn!(
517 "Could not create credstore directory '{}': {e}",
518 credstore.display()
519 );
520 return false;
521 }
522
523 let mut encrypted_count = 0usize;
524
525 for name in units::NODE_CREDENTIAL_NAMES
529 .iter()
530 .chain(std::iter::once(&"signing-key"))
531 {
532 let secret_path = dir.join(name);
533 if !secret_path.exists() {
534 debug!("Skipping node credential '{}' (not yet generated)", name);
535 continue;
536 }
537 let plaintext = match std::fs::read(&secret_path) {
538 Ok(b) => b,
539 Err(e) => {
540 tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
541 continue;
542 }
543 };
544 match systemd_creds_encrypt(name, &plaintext, &credstore) {
545 Ok(()) => encrypted_count += 1,
546 Err(e) => tracing::warn!("Failed to encrypt credential '{name}': {e}"),
547 }
548 }
549
550 if let Ok(entries) = std::fs::read_dir(dir) {
553 for entry in entries.flatten() {
554 let path = entry.path();
555 if !path.is_dir() {
556 continue;
557 }
558 let service_name = match entry.file_name().to_str() {
559 Some(n) => n.to_owned(),
560 None => continue,
561 };
562 for name in units::SERVICE_CREDENTIAL_NAMES {
563 let secret_path = path.join(name);
564 if !secret_path.exists() {
565 continue;
566 }
567 let plaintext = match std::fs::read(&secret_path) {
568 Ok(b) => b,
569 Err(e) => {
570 tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
571 continue;
572 }
573 };
574 let prefixed_name = format!("{service_name}-{name}");
575 match systemd_creds_encrypt(&prefixed_name, &plaintext, &credstore) {
576 Ok(()) => encrypted_count += 1,
577 Err(e) => tracing::warn!("Failed to encrypt credential '{prefixed_name}': {e}"),
578 }
579 }
580 }
581 }
582 for name in units::POLICY_CREDENTIAL_NAMES {
589 let secret_path = dir.join(name);
590 if !secret_path.exists() {
591 continue;
592 }
593 let plaintext = match std::fs::read(&secret_path) {
594 Ok(b) => b,
595 Err(e) => {
596 tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
597 continue;
598 }
599 };
600 match systemd_creds_encrypt(name, &plaintext, &credstore) {
601 Ok(()) => encrypted_count += 1,
602 Err(e) => tracing::warn!("Failed to encrypt credential '{name}': {e}"),
603 }
604 }
605
606 if encrypted_count > 0 {
607 info!(
608 "Encrypted {encrypted_count} credential(s) into '{}'",
609 credstore.display()
610 );
611 true
612 } else {
613 tracing::warn!("No credentials found to encrypt; units will not use ImportCredential=");
614 false
615 }
616}