Skip to main content

hyprstream_rpc/
paths.rs

1//! Runtime path resolution for system vs user mode
2//!
3//! Provides FHS/XDG-compliant path resolution based on execution context:
4//! - Root/system service: `/run/hyprstream/`
5//! - User service: `$XDG_RUNTIME_DIR/hyprstream/`
6//! - Fallback: `/tmp/hyprstream-<uid>/`
7
8use std::path::PathBuf;
9
10use anyhow::{bail, Result};
11
12fn validate_instance_name(instance: &str) -> Result<()> {
13    if matches!(instance, "." | "..")
14        || !instance
15            .bytes()
16            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
17    {
18        bail!(
19            "HYPRSTREAM_INSTANCE must contain only ASCII letters, digits, '.', '_', or '-' and must not be '.' or '..'"
20        );
21    }
22    Ok(())
23}
24
25/// Apply HYPRSTREAM_INSTANCE namespacing to a base path.
26///
27/// When `HYPRSTREAM_INSTANCE` is set and non-empty, appends `instances/{value}`
28/// to the base path.  This allows multiple hyprstream instances to coexist on
29/// the same host without IPC socket or data directory collisions.
30fn apply_instance_namespace(base: PathBuf) -> Result<PathBuf> {
31    match std::env::var("HYPRSTREAM_INSTANCE") {
32        Ok(inst) if !inst.is_empty() => {
33            validate_instance_name(&inst)?;
34            Ok(base.join("instances").join(inst))
35        }
36        Ok(_) | Err(std::env::VarError::NotPresent) => Ok(base),
37        Err(std::env::VarError::NotUnicode(_)) => {
38            bail!("HYPRSTREAM_INSTANCE must be valid Unicode")
39        }
40    }
41}
42
43/// Get the appropriate runtime directory based on execution context
44///
45/// Path selection follows FHS 3.0 and XDG Base Directory specifications:
46/// - Root/system service: `/run/hyprstream/`
47/// - User service: `$XDG_RUNTIME_DIR/hyprstream/`
48/// - Fallback (no systemd): `/tmp/hyprstream-<uid>/`
49pub fn runtime_dir() -> PathBuf {
50    let base = if nix::unistd::geteuid().is_root() {
51        PathBuf::from("/run/hyprstream")
52    } else if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR") {
53        PathBuf::from(xdg).join("hyprstream")
54    } else {
55        // XDG_RUNTIME_DIR not set (e.g. headless SSH before pam_systemd runs).
56        // Prefer /run/user/$UID (set up by PAM on login) over /tmp to avoid
57        // stale sockets surviving reboots.
58        let uid = nix::unistd::getuid().as_raw();
59        let run_user = PathBuf::from(format!("/run/user/{uid}"));
60        if run_user.exists() {
61            run_user.join("hyprstream")
62        } else {
63            PathBuf::from(format!("/tmp/hyprstream-{uid}"))
64        }
65    };
66    apply_instance_namespace(base)
67        .unwrap_or_else(|error| panic!("invalid HYPRSTREAM_INSTANCE: {error}"))
68}
69
70/// Socket directory for EventService
71pub fn events_dir() -> PathBuf {
72    runtime_dir().join("events")
73}
74
75/// Publisher socket path for EventService
76pub fn events_pub_socket() -> PathBuf {
77    events_dir().join("pub.sock")
78}
79
80/// Subscriber socket path for EventService
81pub fn events_sub_socket() -> PathBuf {
82    events_dir().join("sub.sock")
83}
84
85/// Sandbox runtime directory
86pub fn sandboxes_dir() -> PathBuf {
87    runtime_dir().join("sandboxes")
88}
89
90/// RegistryService IPC socket
91pub fn registry_socket() -> PathBuf {
92    runtime_dir().join("registry.sock")
93}
94
95/// PolicyService IPC socket
96pub fn policy_socket() -> PathBuf {
97    runtime_dir().join("policy.sock")
98}
99
100/// WorkerService IPC socket
101pub fn worker_socket() -> PathBuf {
102    runtime_dir().join("worker.sock")
103}
104
105/// WorkflowService IPC socket
106pub fn workflow_socket() -> PathBuf {
107    runtime_dir().join("workflow.sock")
108}
109
110/// EventService IPC socket
111pub fn event_socket() -> PathBuf {
112    runtime_dir().join("event.sock")
113}
114
115/// Nydus runtime directory
116pub fn nydus_dir() -> PathBuf {
117    runtime_dir().join("nydus")
118}
119
120/// PID file location for main process
121pub fn pid_file() -> PathBuf {
122    runtime_dir().join("hyprstream.pid")
123}
124
125/// PID file for a named service (subprocess mode)
126///
127/// Path: `<runtime_dir>/<name>.pid`
128/// Example: `/run/user/1000/hyprstream/events.pid`
129pub fn service_pid_file(name: &str) -> PathBuf {
130    runtime_dir().join(format!("{name}.pid"))
131}
132
133/// Set appropriate permissions on a directory
134///
135/// - System (root): 0755
136/// - User: 0700
137#[cfg(unix)]
138fn set_runtime_permissions(dir: &std::path::Path) -> std::io::Result<()> {
139    use std::os::unix::fs::PermissionsExt;
140    let mode = if nix::unistd::geteuid().is_root() {
141        0o755
142    } else {
143        0o700
144    };
145    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode))
146}
147
148/// Ensure runtime directory exists with correct permissions
149///
150/// Creates the directory tree and sets appropriate permissions:
151/// - System (root): 0755
152/// - User: 0700
153pub fn ensure_runtime_dir() -> std::io::Result<()> {
154    let dir = runtime_dir();
155    std::fs::create_dir_all(&dir)?;
156
157    #[cfg(unix)]
158    set_runtime_permissions(&dir)?;
159
160    Ok(())
161}
162
163/// Ensure events directory exists with correct permissions
164pub fn ensure_events_dir() -> std::io::Result<()> {
165    ensure_runtime_dir()?;
166    let dir = events_dir();
167    std::fs::create_dir_all(&dir)?;
168
169    #[cfg(unix)]
170    set_runtime_permissions(&dir)?;
171
172    Ok(())
173}
174
175/// Check if running as root
176pub fn is_root() -> bool {
177    nix::unistd::geteuid().is_root()
178}
179
180/// Get the stable executable path for spawning subprocesses.
181///
182/// When running from an AppImage, `current_exe()` returns the temporary mount path
183/// (e.g., `/tmp/.mount_hyprXXX/usr/bin/hyprstream`) which becomes invalid when the
184/// AppImage exits. Instead, we use the `$APPIMAGE` environment variable which
185/// points to the stable AppImage file path.
186///
187/// See: <https://docs.appimage.org/packaging-guide/environment-variables.html>
188///
189/// # Returns
190/// - `$APPIMAGE` path if set and the file exists
191/// - `current_exe()` otherwise
192pub fn executable_path() -> std::io::Result<PathBuf> {
193    // Check for AppImage environment variable first
194    if let Ok(appimage_path) = std::env::var("APPIMAGE") {
195        let path = PathBuf::from(&appimage_path);
196        if path.exists() {
197            return Ok(path);
198        }
199    }
200
201    // Fall back to current executable
202    std::env::current_exe()
203}
204
205// =============================================================================
206// Install paths
207// =============================================================================
208
209/// User's executable directory (`~/.local/bin`)
210pub fn bin_dir() -> Option<PathBuf> {
211    dirs::executable_dir()
212}
213
214/// Hyprstream data directory (`~/.local/share/hyprstream`)
215///
216/// When `HYPRSTREAM_INSTANCE` is set, returns
217/// `~/.local/share/hyprstream/instances/{instance}`.
218pub fn data_dir() -> Option<PathBuf> {
219    try_data_dir().ok().flatten()
220}
221
222/// Resolve the data directory while reporting an invalid instance namespace.
223///
224/// Deployment-owned storage must use this checked variant so a malformed
225/// `HYPRSTREAM_INSTANCE` cannot be mistaken for an unavailable data directory.
226pub fn try_data_dir() -> Result<Option<PathBuf>> {
227    dirs::data_local_dir()
228        .map(|dir| apply_instance_namespace(dir.join("hyprstream")))
229        .transpose()
230}
231
232/// Versions directory (`~/.local/share/hyprstream/versions`)
233pub fn versions_dir() -> Option<PathBuf> {
234    data_dir().map(|d| d.join("versions"))
235}
236
237/// Version-specific directory (`~/.local/share/hyprstream/versions/$VERSION`)
238pub fn version_dir(version: &str) -> Option<PathBuf> {
239    versions_dir().map(|d| d.join(version))
240}
241
242/// Path to installed binary in version directory
243///
244/// Returns path to `hyprstream` or `hyprstream.appimage` in version dir.
245/// Checks for both filenames, preferring `.appimage` if both exist.
246pub fn version_binary(version: &str) -> Option<PathBuf> {
247    let dir = version_dir(version)?;
248    let appimage = dir.join("hyprstream.appimage");
249    if appimage.is_file() {
250        return Some(appimage);
251    }
252    let binary = dir.join("hyprstream");
253    if binary.is_file() {
254        return Some(binary);
255    }
256    None
257}
258
259/// Get the path where hyprstream is installed (if installed)
260///
261/// Returns `~/.local/bin/hyprstream` if it exists (file or symlink).
262pub fn installed_executable_path() -> Option<PathBuf> {
263    let path = bin_dir()?.join("hyprstream");
264    if path.symlink_metadata().is_ok() {
265        Some(path)
266    } else {
267        None
268    }
269}
270
271/// Get the current user's UID
272pub fn current_uid() -> u32 {
273    nix::unistd::getuid().as_raw()
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn test_runtime_dir_structure() {
282        let rt = runtime_dir();
283        assert!(rt.to_string_lossy().contains("hyprstream"));
284    }
285
286    #[test]
287    fn test_events_paths() {
288        let pub_sock = events_pub_socket();
289        let sub_sock = events_sub_socket();
290
291        assert!(pub_sock.to_string_lossy().contains("events"));
292        assert!(pub_sock.to_string_lossy().ends_with("pub.sock"));
293        assert!(sub_sock.to_string_lossy().ends_with("sub.sock"));
294    }
295
296    #[test]
297    fn test_sandboxes_dir() {
298        let dir = sandboxes_dir();
299        assert!(dir.to_string_lossy().contains("sandboxes"));
300    }
301
302    #[test]
303    fn test_instance_namespace_default() {
304        // When HYPRSTREAM_INSTANCE is unset, paths should not contain "instances"
305        std::env::remove_var("HYPRSTREAM_INSTANCE");
306        let base = PathBuf::from("/tmp/test-hyprstream");
307        let result = apply_instance_namespace(base.clone())
308            .unwrap_or_else(|error| panic!("unset instance must be accepted: {error}"));
309        assert_eq!(result, base);
310    }
311
312    #[test]
313    fn test_instance_namespace_set() {
314        std::env::set_var("HYPRSTREAM_INSTANCE", "foo");
315        let base = PathBuf::from("/tmp/test-hyprstream");
316        let result = apply_instance_namespace(base)
317            .unwrap_or_else(|error| panic!("safe instance must be accepted: {error}"));
318        assert_eq!(result, PathBuf::from("/tmp/test-hyprstream/instances/foo"));
319        std::env::remove_var("HYPRSTREAM_INSTANCE");
320    }
321
322    #[test]
323    fn test_instance_namespace_empty_string() {
324        std::env::set_var("HYPRSTREAM_INSTANCE", "");
325        let base = PathBuf::from("/tmp/test-hyprstream");
326        let result = apply_instance_namespace(base.clone())
327            .unwrap_or_else(|error| panic!("empty instance must be accepted: {error}"));
328        assert_eq!(
329            result, base,
330            "empty HYPRSTREAM_INSTANCE should be treated as unset"
331        );
332        std::env::remove_var("HYPRSTREAM_INSTANCE");
333    }
334
335    #[test]
336    fn test_instance_namespace_rejects_non_names() {
337        for instance in [
338            ".",
339            "..",
340            "../escape",
341            "nested/path",
342            r"nested\path",
343            "bad name",
344        ] {
345            assert!(
346                validate_instance_name(instance).is_err(),
347                "{instance:?} must be rejected"
348            );
349        }
350    }
351
352    #[test]
353    fn test_instance_namespace_accepts_safe_names() {
354        for instance in ["foo", "did-trust-123", "node_1", "node.example"] {
355            validate_instance_name(instance)
356                .unwrap_or_else(|error| panic!("{instance:?} must be accepted: {error}"));
357        }
358    }
359}