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