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
11use 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
47/// Data Dreamer installs and keeps for the user, such as managed agent
48/// harnesses and the Dreamer Web component. The same place on macOS and Linux.
49pub 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
65/// The JSON-RPC endpoint, beside the native socket.
66pub fn rpc_socket_path() -> PathBuf {
67    runtime_dir().join("dreamerd.rpc.sock")
68}
69
70/// The longest Unix socket path the system accepts, in bytes (the size of
71/// `sun_path`, less its terminating NUL).
72pub const SOCKET_PATH_MAX: usize = if cfg!(target_os = "macos") { 103 } else { 107 };
73
74/// Refuse a socket path the system could not bind, before trying, with a
75/// reason a person can act on.
76pub 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
100/// Create `dir` (mode 0700) or check that the existing one belongs to this
101/// user and is closed to everyone else. Never loosens or takes over a
102/// directory it does not own.
103pub 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
134/// Restrict a file (the socket, the log) to its owner.
135pub 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
140/// Detach from the launching terminal: a new session has no controlling
141/// terminal, so closing the terminal or SSH session sends it no hangup.
142pub fn detach_session() -> Result<(), String> {
143    rustix::process::setsid()
144        .map(drop)
145        .map_err(|e| format!("setsid: {e}"))
146}
147
148/// Whether a process with this pid exists.
149pub 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
154/// Ask a process to stop (SIGTERM).
155pub 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
161/// Signal a whole process group: SIGTERM, or SIGKILL with `force`.
162pub 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
172/// The pid recorded in the daemon's startup lock, if any.
173pub fn lock_holder() -> Option<u32> {
174    std::fs::read_to_string(lock_path())
175        .ok()?
176        .trim()
177        .parse()
178        .ok()
179}
180
181/// The session a process belongs to (diagnostics and tests).
182pub 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/// Hand memory that the allocator holds but no longer uses back to the
190/// system: glibc's `malloc_trim`, or macOS's malloc pressure relief. A
191/// daemon that has just dropped many terminal mirrors calls this so its
192/// resident size shrinks with them. Elsewhere it does nothing.
193#[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        // SAFETY: malloc_trim takes a plain size and only touches the
201        // allocator's own free lists, under its own lock.
202        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        // SAFETY: a null zone means every zone and a goal of 0 means as
212        // much as possible; the call only releases free pages.
213        unsafe {
214            malloc_zone_pressure_relief(std::ptr::null_mut(), 0);
215        }
216    }
217}
218
219/// Bytes the allocator has handed out and not had back, without the freed
220/// memory it keeps for reuse: what a process really holds, where resident
221/// size also counts retained free pages. `None` where it cannot tell.
222#[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        // SAFETY: mallinfo2 (glibc 2.33+) takes nothing and returns a
243        // plain struct by value.
244        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        // SAFETY: a null zone sums every zone into the struct we own.
262        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/// A process's physical footprint on macOS, in bytes: the memory the
272/// kernel charges it for (dirty and compressed pages, as Activity Monitor
273/// shows), which leaves out free pages the allocator still has mapped but
274/// that resident size counts. `None` elsewhere, or when the process is
275/// gone or belongs to another user.
276#[allow(unsafe_code)]
277pub fn phys_footprint(pid: u32) -> Option<u64> {
278    #[cfg(target_os = "macos")]
279    {
280        /// `struct rusage_info_v2` from <sys/resource.h>, field for field.
281        #[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            /// From `ri_proc_start_abstime` to `ri_diskio_byteswritten`.
294            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        // SAFETY: for RUSAGE_INFO_V2 the kernel writes at most
307        // `sizeof(struct rusage_info_v2)` bytes, which is the size of the
308        // struct we own and pass.
309        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    /// Both readings of a 128 MiB block, in one test and in this order:
324    /// another test's block would move process-wide readings, and once a
325    /// block is freed the allocator may keep its pages, so a later block
326    /// can reuse them without growing the footprint.
327    #[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    /// The allocator statistics are read through hand-written C structs; a
334    /// wrong layout would read the wrong field. Other tests share the heap
335    /// and allocate or free a little meanwhile, so the block is large and
336    /// the bounds leave room for them.
337    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    /// The rusage struct is hand-written; a wrong layout would read another
374    /// field. A block written page by page must show in the footprint.
375    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}