1use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
12use std::path::{Path, PathBuf};
13
14pub fn uid() -> u32 {
15 rustix::process::getuid().as_raw()
16}
17
18fn env_dir(name: &str) -> Option<PathBuf> {
19 std::env::var_os(name)
20 .map(PathBuf::from)
21 .filter(|p| p.is_absolute())
22}
23
24pub fn runtime_dir() -> PathBuf {
25 if let Some(d) = env_dir("DREAMER_RUNTIME_DIR") {
26 return d;
27 }
28 if let Some(d) = env_dir("XDG_RUNTIME_DIR") {
29 return d.join("dreamer");
30 }
31 let base = env_dir("TMPDIR").unwrap_or_else(|| PathBuf::from("/tmp"));
32 base.join(format!("dreamer-{}", uid()))
33}
34
35pub fn state_dir() -> PathBuf {
36 if let Some(d) = env_dir("DREAMER_STATE_DIR") {
37 return d;
38 }
39 if let Some(d) = env_dir("XDG_STATE_HOME") {
40 return d.join("dreamer");
41 }
42 env_dir("HOME")
43 .unwrap_or_else(|| PathBuf::from("/"))
44 .join(".local/state/dreamer")
45}
46
47pub fn data_dir() -> PathBuf {
50 if let Some(d) = env_dir("DREAMER_DATA_DIR") {
51 return d;
52 }
53 if let Some(d) = env_dir("XDG_DATA_HOME") {
54 return d.join("dreamer");
55 }
56 env_dir("HOME")
57 .unwrap_or_else(|| PathBuf::from("/"))
58 .join(".local/share/dreamer")
59}
60
61pub fn socket_path() -> PathBuf {
62 runtime_dir().join("dreamerd.sock")
63}
64
65pub fn rpc_socket_path() -> PathBuf {
67 runtime_dir().join("dreamerd.rpc.sock")
68}
69
70pub const SOCKET_PATH_MAX: usize = if cfg!(target_os = "macos") { 103 } else { 107 };
73
74pub fn check_socket_path(p: &Path) -> Result<(), String> {
77 let n = p.as_os_str().len();
78 if n > SOCKET_PATH_MAX {
79 return Err(format!(
80 "the socket path {} is {n} bytes, longer than the {SOCKET_PATH_MAX} this system allows; \
81 use a shorter DREAMER_RUNTIME_DIR",
82 p.display()
83 ));
84 }
85 Ok(())
86}
87
88pub fn lock_path() -> PathBuf {
89 runtime_dir().join("dreamerd.lock")
90}
91
92pub fn log_path() -> PathBuf {
93 state_dir().join("dreamerd.log")
94}
95
96pub fn ledger_path() -> PathBuf {
97 state_dir().join("actions.jsonl")
98}
99
100pub fn private_dir(dir: &Path) -> Result<(), String> {
104 match std::fs::DirBuilder::new()
105 .recursive(true)
106 .mode(0o700)
107 .create(dir)
108 {
109 Ok(()) => {}
110 Err(e) => return Err(format!("{}: {e}", dir.display())),
111 }
112 let meta = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
113 if !meta.is_dir() {
114 return Err(format!("{} is not a directory", dir.display()));
115 }
116 if meta.uid() != uid() {
117 return Err(format!(
118 "{} belongs to uid {}, not this user ({}); refusing to use it",
119 dir.display(),
120 meta.uid(),
121 uid()
122 ));
123 }
124 let mode = meta.permissions().mode() & 0o777;
125 if mode & 0o077 != 0 {
126 return Err(format!(
127 "{} is accessible to other users (mode {mode:o}); it must be 0700",
128 dir.display()
129 ));
130 }
131 Ok(())
132}
133
134pub fn owner_only(path: &Path) -> Result<(), String> {
136 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
137 .map_err(|e| format!("{}: {e}", path.display()))
138}
139
140pub fn detach_session() -> Result<(), String> {
143 rustix::process::setsid()
144 .map(drop)
145 .map_err(|e| format!("setsid: {e}"))
146}
147
148pub fn process_alive(pid: u32) -> bool {
150 rustix::process::Pid::from_raw(pid as i32)
151 .is_some_and(|p| rustix::process::test_kill_process(p).is_ok())
152}
153
154pub fn terminate(pid: u32) -> Result<(), String> {
156 let p = rustix::process::Pid::from_raw(pid as i32).ok_or("invalid pid")?;
157 rustix::process::kill_process(p, rustix::process::Signal::TERM)
158 .map_err(|e| format!("kill {pid}: {e}"))
159}
160
161pub fn terminate_group(pgid: u32, force: bool) -> Result<(), String> {
163 let p = rustix::process::Pid::from_raw(pgid as i32).ok_or("invalid process group")?;
164 let signal = if force {
165 rustix::process::Signal::KILL
166 } else {
167 rustix::process::Signal::TERM
168 };
169 rustix::process::kill_process_group(p, signal).map_err(|e| format!("kill -{pgid}: {e}"))
170}
171
172pub fn lock_holder() -> Option<u32> {
174 std::fs::read_to_string(lock_path())
175 .ok()?
176 .trim()
177 .parse()
178 .ok()
179}
180
181pub fn session_of(pid: u32) -> Option<u32> {
183 let p = rustix::process::Pid::from_raw(pid as i32)?;
184 rustix::process::getsid(Some(p))
185 .ok()
186 .map(|s| s.as_raw_nonzero().get() as u32)
187}
188
189#[allow(unsafe_code)]
194pub fn release_free_memory() {
195 #[cfg(all(target_os = "linux", target_env = "gnu"))]
196 {
197 unsafe extern "C" {
198 fn malloc_trim(pad: usize) -> std::ffi::c_int;
199 }
200 unsafe {
203 malloc_trim(0);
204 }
205 }
206 #[cfg(target_os = "macos")]
207 {
208 unsafe extern "C" {
209 fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
210 }
211 unsafe {
214 malloc_zone_pressure_relief(std::ptr::null_mut(), 0);
215 }
216 }
217}
218
219#[allow(unsafe_code)]
223pub fn heap_in_use() -> Option<u64> {
224 #[cfg(all(target_os = "linux", target_env = "gnu"))]
225 {
226 #[repr(C)]
227 struct Mallinfo2 {
228 arena: usize,
229 ordblks: usize,
230 smblks: usize,
231 hblks: usize,
232 hblkhd: usize,
233 usmblks: usize,
234 fsmblks: usize,
235 uordblks: usize,
236 fordblks: usize,
237 keepcost: usize,
238 }
239 unsafe extern "C" {
240 fn mallinfo2() -> Mallinfo2;
241 }
242 let m = unsafe { mallinfo2() };
245 Some((m.uordblks + m.hblkhd) as u64)
246 }
247 #[cfg(target_os = "macos")]
248 {
249 #[repr(C)]
250 #[derive(Default)]
251 struct MallocStatistics {
252 blocks_in_use: u32,
253 size_in_use: usize,
254 max_size_in_use: usize,
255 size_allocated: usize,
256 }
257 unsafe extern "C" {
258 fn malloc_zone_statistics(zone: *mut std::ffi::c_void, stats: *mut MallocStatistics);
259 }
260 let mut s = MallocStatistics::default();
261 unsafe { malloc_zone_statistics(std::ptr::null_mut(), &mut s) };
263 Some(s.size_in_use as u64)
264 }
265 #[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "macos")))]
266 {
267 None
268 }
269}
270
271#[allow(unsafe_code)]
277pub fn phys_footprint(pid: u32) -> Option<u64> {
278 #[cfg(target_os = "macos")]
279 {
280 #[repr(C)]
282 #[derive(Default)]
283 struct RusageInfoV2 {
284 uuid: [u8; 16],
285 user_time: u64,
286 system_time: u64,
287 pkg_idle_wkups: u64,
288 interrupt_wkups: u64,
289 pageins: u64,
290 wired_size: u64,
291 resident_size: u64,
292 phys_footprint: u64,
293 rest: [u64; 10],
295 }
296 const RUSAGE_INFO_V2: std::ffi::c_int = 2;
297 unsafe extern "C" {
298 fn proc_pid_rusage(
299 pid: std::ffi::c_int,
300 flavor: std::ffi::c_int,
301 buffer: *mut RusageInfoV2,
302 ) -> std::ffi::c_int;
303 }
304 let pid = std::ffi::c_int::try_from(pid).ok()?;
305 let mut info = RusageInfoV2::default();
306 let rc = unsafe { proc_pid_rusage(pid, RUSAGE_INFO_V2, &mut info) };
310 (rc == 0).then_some(info.phys_footprint)
311 }
312 #[cfg(not(target_os = "macos"))]
313 {
314 let _ = pid;
315 None
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
328 fn memory_readings_follow_a_large_block() {
329 footprint_follows_a_written_block();
330 heap_in_use_follows_a_large_allocation();
331 }
332
333 fn heap_in_use_follows_a_large_allocation() {
338 const BLOCK: u64 = 128 << 20;
339 const SLACK: u64 = 32 << 20;
340 let Some(before) = heap_in_use() else {
341 return;
342 };
343 let block = vec![1u8; BLOCK as usize];
344 let during = heap_in_use().unwrap_or(0);
345 assert!(
346 during + SLACK >= before + BLOCK,
347 "{before} then {during} with 128 MiB more held"
348 );
349 drop(block);
350 release_free_memory();
351 let after = heap_in_use().unwrap_or(u64::MAX);
352 assert!(
353 after + BLOCK <= during + SLACK,
354 "{during} then {after} after freeing 128 MiB"
355 );
356 }
357
358 #[test]
359 fn private_dirs_are_created_closed_and_open_ones_refused() {
360 let base = std::env::temp_dir().join(format!("dreamer-platform-{}", std::process::id()));
361 let _ = std::fs::remove_dir_all(&base);
362 let dir = base.join("rt");
363 private_dir(&dir).expect("create");
364 let mode = std::fs::metadata(&dir).expect("meta").permissions().mode() & 0o777;
365 assert_eq!(mode, 0o700);
366 private_dir(&dir).expect("reuse");
367 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("chmod");
368 let err = private_dir(&dir).expect_err("open dir refused");
369 assert!(err.contains("must be 0700"), "{err}");
370 let _ = std::fs::remove_dir_all(&base);
371 }
372
373 fn footprint_follows_a_written_block() {
376 const BLOCK: u64 = 128 << 20;
377 const SLACK: u64 = 32 << 20;
378 let me = std::process::id();
379 if !cfg!(target_os = "macos") {
380 assert_eq!(phys_footprint(me), None);
381 return;
382 }
383 let before = phys_footprint(me).expect("footprint of this process");
384 let block = vec![1u8; BLOCK as usize];
385 let during = phys_footprint(me).unwrap_or(0);
386 assert!(
387 during + SLACK >= before + BLOCK && during <= before + 2 * BLOCK + SLACK,
388 "{before} then {during} with 128 MiB more written"
389 );
390 drop(block);
391 }
392
393 #[test]
394 fn this_process_is_alive_and_has_a_session() {
395 assert!(process_alive(std::process::id()));
396 assert!(session_of(std::process::id()).is_some());
397 }
398}