hyprstream_core/systemd/socket.rs
1//! Systemd socket activation for HTTP listeners
2//!
3//! Provides transparent socket activation support - if systemd passes a
4//! pre-bound socket via `LISTEN_FDS`, we use it; otherwise we bind normally.
5//!
6//! # How Socket Activation Works
7//!
8//! 1. Systemd creates and binds the socket before starting the service
9//! 2. Systemd sets `LISTEN_FDS=1` and `LISTEN_PID=<pid>` environment variables
10//! 3. The service receives the socket as file descriptor 3 (SD_LISTEN_FDS_START)
11//! 4. The service uses the pre-bound socket instead of binding itself
12//!
13//! # Benefits
14//!
15//! - Zero-downtime restarts (systemd holds the socket during restart)
16//! - Faster startup (socket already bound)
17//! - Privilege separation (systemd can bind privileged ports)
18//!
19//! # Usage
20//!
21//! ```ignore
22//! use hyprstream_core::systemd::socket::get_listener;
23//!
24//! // Get listener - uses systemd socket if available, otherwise binds normally
25//! let listener = get_listener("0.0.0.0:3000").await?;
26//!
27//! // Use with axum
28//! axum::serve(listener, app).await?;
29//! ```
30//!
31//! # Systemd Configuration
32//!
33//! ```ini
34//! # hyprstream.socket
35//! [Socket]
36//! ListenStream=0.0.0.0:3000
37//! ReusePort=yes
38//!
39//! [Install]
40//! WantedBy=sockets.target
41//! ```
42
43use anyhow::{Context, Result};
44use listenfd::ListenFd;
45use std::net::SocketAddr;
46use tokio::net::TcpListener;
47use tracing::{debug, info};
48
49/// Get a TCP listener, using systemd socket activation if available
50///
51/// This function transparently handles socket activation:
52/// - If `LISTEN_FDS` is set and valid, uses the systemd-provided socket
53/// - Otherwise, binds to the specified address normally
54///
55/// # Arguments
56///
57/// * `addr` - Address to bind to if socket activation is not available
58///
59/// # Returns
60///
61/// A `TcpListener` ready for accepting connections.
62///
63/// # Example
64///
65/// ```ignore
66/// let listener = get_listener("0.0.0.0:3000").await?;
67/// info!("Server listening on {}", listener.local_addr()?);
68/// ```
69pub async fn get_listener(addr: &str) -> Result<TcpListener> {
70 // Try socket activation first
71 if let Some(listener) = try_systemd()? {
72 let local_addr = listener
73 .local_addr()
74 .context("Failed to get local address from systemd socket")?;
75 info!(
76 "Using systemd socket activation (listening on {})",
77 local_addr
78 );
79 return Ok(listener);
80 }
81
82 // Fall back to normal binding
83 debug!("Socket activation not available, binding to {}", addr);
84 let listener = TcpListener::bind(addr)
85 .await
86 .with_context(|| format!("Failed to bind to {addr}"))?;
87
88 let local_addr = listener.local_addr()?;
89 info!("Server listening on {} (direct bind)", local_addr);
90
91 Ok(listener)
92}
93
94/// Get a TCP listener for a specific socket address
95///
96/// Same as `get_listener` but takes a `SocketAddr` directly.
97pub async fn get_listener_addr(addr: SocketAddr) -> Result<TcpListener> {
98 get_listener(&addr.to_string()).await
99}
100
101/// Try to get a listener from systemd socket activation
102///
103/// Returns `Ok(Some(listener))` if socket activation is available,
104/// `Ok(None)` if not running under systemd or no sockets passed,
105/// `Err` if socket activation is configured but failed.
106fn try_systemd() -> Result<Option<TcpListener>> {
107 // Check if we're running under systemd with socket activation
108 if !has_socket() {
109 debug!("Not running with systemd socket activation");
110 return Ok(None);
111 }
112
113 let mut listenfd = ListenFd::from_env();
114
115 // Get the first TCP listener (index 0)
116 match listenfd.take_tcp_listener(0) {
117 Ok(Some(std_listener)) => {
118 // Set non-blocking for tokio
119 std_listener
120 .set_nonblocking(true)
121 .context("Failed to set socket non-blocking")?;
122
123 // Convert to tokio TcpListener
124 let listener = TcpListener::from_std(std_listener)
125 .context("Failed to convert std TcpListener to tokio")?;
126
127 Ok(Some(listener))
128 }
129 Ok(None) => {
130 debug!("No TCP listeners passed by systemd");
131 Ok(None)
132 }
133 Err(e) => {
134 // listenfd error - socket activation configured but failed
135 Err(anyhow::anyhow!(
136 "Failed to get TCP listener from systemd: {}",
137 e
138 ))
139 }
140 }
141}
142
143/// Check if running with systemd socket activation
144///
145/// Returns `true` if `LISTEN_FDS` is set and `LISTEN_PID` matches current process.
146pub fn has_socket() -> bool {
147 let listen_fds: i32 = std::env::var("LISTEN_FDS")
148 .ok()
149 .and_then(|v| v.parse().ok())
150 .unwrap_or(0);
151
152 let listen_pid: u32 = std::env::var("LISTEN_PID")
153 .ok()
154 .and_then(|v| v.parse().ok())
155 .unwrap_or(0);
156
157 let current_pid = std::process::id();
158
159 let activated = listen_fds > 0 && listen_pid == current_pid;
160
161 if activated {
162 debug!(
163 "Socket activation detected: LISTEN_FDS={}, LISTEN_PID={}, current_pid={}",
164 listen_fds, listen_pid, current_pid
165 );
166 }
167
168 activated
169}
170
171/// Get the number of file descriptors passed by systemd
172///
173/// Returns 0 if not running under systemd socket activation.
174pub fn listen_fd_count() -> usize {
175 if !has_socket() {
176 return 0;
177 }
178
179 std::env::var("LISTEN_FDS")
180 .ok()
181 .and_then(|v| v.parse().ok())
182 .unwrap_or(0)
183}
184
185/// Get all TCP listeners passed by systemd
186///
187/// Returns a vector of TCP listeners. Useful when systemd passes multiple
188/// sockets (e.g., for HTTP and HTTPS on different ports).
189///
190/// # Example
191///
192/// ```ignore
193/// let listeners = get_all_listeners().await?;
194/// for (i, listener) in listeners.iter().enumerate() {
195/// info!("Socket {}: {}", i, listener.local_addr()?);
196/// }
197/// ```
198pub fn get_all_tcp_listeners() -> Result<Vec<TcpListener>> {
199 if !has_socket() {
200 return Ok(Vec::new());
201 }
202
203 let mut listenfd = ListenFd::from_env();
204 let mut listeners = Vec::new();
205 let mut index = 0;
206
207 loop {
208 match listenfd.take_tcp_listener(index) {
209 Ok(Some(std_listener)) => {
210 std_listener
211 .set_nonblocking(true)
212 .with_context(|| format!("Failed to set socket {index} non-blocking"))?;
213
214 let listener = TcpListener::from_std(std_listener)
215 .with_context(|| format!("Failed to convert socket {index} to tokio"))?;
216
217 listeners.push(listener);
218 index += 1;
219 }
220 Ok(None) => break,
221 Err(e) => {
222 return Err(anyhow::anyhow!(
223 "Failed to get TCP listener {} from systemd: {}",
224 index,
225 e
226 ));
227 }
228 }
229 }
230
231 Ok(listeners)
232}
233
234#[cfg(test)]
235#[allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stdout)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn test_has_socket_false() {
241 // Should return false when env vars not set
242 std::env::remove_var("LISTEN_FDS");
243 std::env::remove_var("LISTEN_PID");
244 assert!(!has_socket());
245 }
246
247 #[test]
248 fn test_has_socket_wrong_pid() {
249 // Should return false when PID doesn't match
250 std::env::set_var("LISTEN_FDS", "1");
251 std::env::set_var("LISTEN_PID", "99999999"); // Wrong PID
252 assert!(!has_socket());
253
254 // Cleanup
255 std::env::remove_var("LISTEN_FDS");
256 std::env::remove_var("LISTEN_PID");
257 }
258
259 #[test]
260 fn test_listen_fd_count_zero() {
261 std::env::remove_var("LISTEN_FDS");
262 std::env::remove_var("LISTEN_PID");
263 assert_eq!(listen_fd_count(), 0);
264 }
265
266 #[tokio::test]
267 async fn test_get_listener_fallback() {
268 // Without socket activation, should bind normally
269 std::env::remove_var("LISTEN_FDS");
270 std::env::remove_var("LISTEN_PID");
271
272 // Use port 0 to get a random available port
273 let listener = get_listener("127.0.0.1:0").await.unwrap();
274 let addr = listener.local_addr().unwrap();
275 assert!(addr.port() > 0);
276 }
277
278 #[test]
279 fn test_get_all_tcp_listeners_empty() {
280 std::env::remove_var("LISTEN_FDS");
281 std::env::remove_var("LISTEN_PID");
282
283 let listeners = get_all_tcp_listeners().unwrap();
284 assert!(listeners.is_empty());
285 }
286}