platform/sandbox/
fence.rs1use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::RwLock;
8
9static SERVED: RwLock<Vec<(u64, Served)>> = RwLock::new(Vec::new());
11
12static NEXT_FENCE: AtomicU64 = AtomicU64::new(0);
13
14#[cfg_attr(not(feature = "sandbox"), allow(dead_code))]
15enum Served {
16 Socket(PathBuf),
17 Port(SocketAddr),
18 Secret(PathBuf),
19}
20
21#[must_use = "the fence comes down when this is dropped"]
26pub struct Fence(u64);
27
28impl Drop for Fence {
29 fn drop(&mut self) {
30 let mut served = SERVED.write().unwrap_or_else(|e| e.into_inner());
31 served.retain(|(id, _)| *id != self.0);
32 }
33}
34
35fn fence(entry: Served) -> Fence {
36 let id = NEXT_FENCE.fetch_add(1, Ordering::Relaxed);
37 let mut served = SERVED.write().unwrap_or_else(|e| e.into_inner());
38 served.push((id, entry));
39 Fence(id)
40}
41
42pub fn fence_socket(path: &Path) -> Fence {
46 fence(Served::Socket(
47 path.canonicalize().unwrap_or_else(|_| path.to_path_buf()),
48 ))
49}
50
51pub fn fence_port(addr: SocketAddr) -> Fence {
55 fence(Served::Port(addr))
56}
57
58pub fn fence_secret(path: &Path) -> Fence {
63 fence(Served::Secret(
64 path.canonicalize().unwrap_or_else(|_| path.to_path_buf()),
65 ))
66}
67
68#[cfg(feature = "sandbox")]
69fn fenced<T: Ord>(pick: impl Fn(&Served) -> Option<T>) -> Vec<T> {
70 let served = SERVED.read().unwrap_or_else(|e| e.into_inner());
71 let mut found: Vec<T> = served.iter().filter_map(|(_, s)| pick(s)).collect();
72 found.sort();
73 found.dedup();
74 found
75}
76
77#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
79pub(super) fn fenced_secrets() -> Vec<PathBuf> {
80 fenced(|s| match s {
81 Served::Secret(p) if p.exists() => Some(p.clone()),
82 _ => None,
83 })
84}
85
86#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
88pub(super) fn fenced_sockets() -> Vec<PathBuf> {
89 fenced(|s| match s {
90 Served::Socket(p) if is_socket(p) => Some(p.clone()),
91 _ => None,
92 })
93}
94
95#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
96pub(super) fn fenced_ports() -> Vec<SocketAddr> {
97 fenced(|s| match s {
98 Served::Port(addr) => Some(*addr),
99 _ => None,
100 })
101}
102
103#[cfg(all(feature = "sandbox", any(target_os = "macos", target_os = "linux")))]
104pub(super) fn is_socket(path: &Path) -> bool {
105 use std::os::unix::fs::FileTypeExt;
106 path.symlink_metadata()
107 .is_ok_and(|m| m.file_type().is_socket())
108}