Skip to main content

hyprstream_rpc/
socket.rs

1//! Socket activation helpers
2//!
3//! Wraps systemd socket activation for receiving file descriptors
4//! passed by systemd when a socket is activated.
5
6use std::os::unix::io::RawFd;
7
8/// Check if running under systemd socket activation
9///
10/// Returns true if:
11/// 1. System was booted with systemd
12/// 2. `LISTEN_FDS` environment variable is set
13#[cfg(feature = "systemd")]
14pub fn has_socket() -> bool {
15    systemd::daemon::booted().unwrap_or(false) && std::env::var("LISTEN_FDS").is_ok()
16}
17
18#[cfg(not(feature = "systemd"))]
19pub fn has_socket() -> bool {
20    false
21}
22
23/// Get socket activation file descriptors
24///
25/// Returns a vector of file descriptors passed by systemd.
26/// The first fd is always 3 (SD_LISTEN_FDS_START), subsequent ones
27/// are 4, 5, etc.
28///
29/// Returns `None` if not running under socket activation.
30#[cfg(feature = "systemd")]
31pub fn listen_fds() -> Option<Vec<RawFd>> {
32    systemd::daemon::listen_fds(false)
33        .ok()
34        .map(|fds| fds.iter().collect())
35}
36
37#[cfg(not(feature = "systemd"))]
38pub fn listen_fds() -> Option<Vec<RawFd>> {
39    None
40}
41
42/// Get the number of listening file descriptors
43///
44/// Returns 0 if not running under socket activation.
45#[cfg(feature = "systemd")]
46pub fn listen_fds_count() -> usize {
47    std::env::var("LISTEN_FDS")
48        .ok()
49        .and_then(|s| s.parse().ok())
50        .unwrap_or(0)
51}
52
53#[cfg(not(feature = "systemd"))]
54pub fn listen_fds_count() -> usize {
55    0
56}
57
58/// Check if a specific fd name matches
59///
60/// When multiple sockets are passed, `LISTEN_FDNAMES` contains
61/// colon-separated names. This checks if a given fd index matches
62/// the expected name.
63#[cfg(feature = "systemd")]
64pub fn fd_name_matches(fd_index: usize, expected_name: &str) -> bool {
65    if let Ok(names) = std::env::var("LISTEN_FDNAMES") {
66        if let Some(name) = names.split(':').nth(fd_index) {
67            return name == expected_name;
68        }
69    }
70    false
71}
72
73#[cfg(not(feature = "systemd"))]
74pub fn fd_name_matches(_fd_index: usize, _expected_name: &str) -> bool {
75    false
76}