1use 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
25fn 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
43pub 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 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
70pub fn events_dir() -> PathBuf {
72 runtime_dir().join("events")
73}
74
75pub fn events_pub_socket() -> PathBuf {
77 events_dir().join("pub.sock")
78}
79
80pub fn events_sub_socket() -> PathBuf {
82 events_dir().join("sub.sock")
83}
84
85pub fn sandboxes_dir() -> PathBuf {
87 runtime_dir().join("sandboxes")
88}
89
90pub fn registry_socket() -> PathBuf {
92 runtime_dir().join("registry.sock")
93}
94
95pub fn policy_socket() -> PathBuf {
97 runtime_dir().join("policy.sock")
98}
99
100pub fn worker_socket() -> PathBuf {
102 runtime_dir().join("worker.sock")
103}
104
105pub fn workflow_socket() -> PathBuf {
107 runtime_dir().join("workflow.sock")
108}
109
110pub fn event_socket() -> PathBuf {
112 runtime_dir().join("event.sock")
113}
114
115pub fn nydus_dir() -> PathBuf {
117 runtime_dir().join("nydus")
118}
119
120pub fn pid_file() -> PathBuf {
122 runtime_dir().join("hyprstream.pid")
123}
124
125pub fn service_pid_file(name: &str) -> PathBuf {
130 runtime_dir().join(format!("{name}.pid"))
131}
132
133#[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
148pub 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
163pub 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
175pub fn is_root() -> bool {
177 nix::unistd::geteuid().is_root()
178}
179
180pub fn executable_path() -> std::io::Result<PathBuf> {
193 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 std::env::current_exe()
203}
204
205pub fn bin_dir() -> Option<PathBuf> {
211 dirs::executable_dir()
212}
213
214pub fn data_dir() -> Option<PathBuf> {
219 try_data_dir().ok().flatten()
220}
221
222pub 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
232pub fn versions_dir() -> Option<PathBuf> {
234 data_dir().map(|d| d.join("versions"))
235}
236
237pub fn version_dir(version: &str) -> Option<PathBuf> {
239 versions_dir().map(|d| d.join(version))
240}
241
242pub 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
259pub 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
271pub 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 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}