Skip to main content

platform/
lib.rs

1//! Where Dreamer keeps per-user runtime and state files, and the checks
2//! that keep them private (owner-restricted runtime directories
3//! and sockets).
4//!
5//! | Directory | Default | Override |
6//! | --- | --- | --- |
7//! | runtime (socket, lock) | `$XDG_RUNTIME_DIR/dreamer`, else `$TMPDIR/dreamer-<uid>`, else `/tmp/dreamer-<uid>` | `DREAMER_RUNTIME_DIR` |
8//! | state (log, action ledger) | `$XDG_STATE_HOME/dreamer`, else `~/.local/state/dreamer` | `DREAMER_STATE_DIR` |
9//! | data (managed agent installs, Dreamer Web) | `$XDG_DATA_HOME/dreamer`, else `~/.local/share/dreamer` | `DREAMER_DATA_DIR` |
10
11pub 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
49/// Data Dreamer installs and keeps for the user, such as managed agent
50/// harnesses and the Dreamer Web component. The same place on macOS and Linux.
51pub 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
67/// The JSON-RPC endpoint, beside the native socket.
68pub fn rpc_socket_path() -> PathBuf {
69    runtime_dir().join("dreamerd.rpc.sock")
70}
71
72/// The longest Unix socket path the system accepts, in bytes (the size of
73/// `sun_path`, less its terminating NUL).
74pub const SOCKET_PATH_MAX: usize = if cfg!(target_os = "macos") { 103 } else { 107 };
75
76/// Refuse a socket path the system could not bind, before trying, with a
77/// reason a person can act on.
78pub 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
102/// Create `dir` (mode 0700) or check that the existing one belongs to this
103/// user and is closed to everyone else. Never loosens or takes over a
104/// directory it does not own.
105pub 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
136/// Restrict a file (the socket, the log) to its owner.
137pub 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
142/// Detach from the launching terminal: a new session has no controlling
143/// terminal, so closing the terminal or SSH session sends it no hangup.
144pub fn detach_session() -> Result<(), String> {
145    rustix::process::setsid()
146        .map(drop)
147        .map_err(|e| format!("setsid: {e}"))
148}
149
150/// Whether a process with this pid exists.
151pub 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
156/// Ask a process to stop (SIGTERM).
157pub 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
163/// Signal a whole process group: SIGTERM, or SIGKILL with `force`.
164pub 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
174/// The pid recorded in the daemon's startup lock, if any.
175pub fn lock_holder() -> Option<u32> {
176    std::fs::read_to_string(lock_path())
177        .ok()?
178        .trim()
179        .parse()
180        .ok()
181}
182
183/// The session a process belongs to (diagnostics and tests).
184pub 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/// Hand memory that the allocator holds but no longer uses back to the
192/// system: glibc's `malloc_trim`, or macOS's malloc pressure relief. A
193/// daemon that has just dropped many terminal mirrors calls this so its
194/// resident size shrinks with them. Elsewhere it does nothing.
195#[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        // SAFETY: malloc_trim takes a plain size and only touches the
203        // allocator's own free lists, under its own lock.
204        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        // SAFETY: a null zone means every zone and a goal of 0 means as
214        // much as possible; the call only releases free pages.
215        unsafe {
216            malloc_zone_pressure_relief(std::ptr::null_mut(), 0);
217        }
218    }
219}
220
221/// Bytes the allocator has handed out and not had back, without the freed
222/// memory it keeps for reuse: what a process really holds, where resident
223/// size also counts retained free pages. `None` where it cannot tell.
224#[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        // SAFETY: mallinfo2 (glibc 2.33+) takes nothing and returns a
245        // plain struct by value.
246        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        // SAFETY: a null zone sums every zone into the struct we own.
264        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/// A process's physical footprint on macOS, in bytes: the memory the
274/// kernel charges it for (dirty and compressed pages, as Activity Monitor
275/// shows), which leaves out free pages the allocator still has mapped but
276/// that resident size counts. `None` elsewhere, or when the process is
277/// gone or belongs to another user.
278#[allow(unsafe_code)]
279pub fn phys_footprint(pid: u32) -> Option<u64> {
280    #[cfg(target_os = "macos")]
281    {
282        /// `struct rusage_info_v2` from <sys/resource.h>, field for field.
283        #[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            /// From `ri_proc_start_abstime` to `ri_diskio_byteswritten`.
296            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        // SAFETY: for RUSAGE_INFO_V2 the kernel writes at most
309        // `sizeof(struct rusage_info_v2)` bytes, which is the size of the
310        // struct we own and pass.
311        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    /// Both readings of a 128 MiB block, in one test and in this order:
326    /// another test's block would move process-wide readings, and once a
327    /// block is freed the allocator may keep its pages, so a later block
328    /// can reuse them without growing the footprint.
329    #[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    /// The allocator statistics are read through hand-written C structs; a
336    /// wrong layout would read the wrong field. Other tests share the heap
337    /// and allocate or free a little meanwhile, so the block is large and
338    /// the bounds leave room for them.
339    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    /// The rusage struct is hand-written; a wrong layout would read another
376    /// field. A block written page by page must show in the footprint.
377    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}