use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
pub fn uid() -> u32 {
rustix::process::getuid().as_raw()
}
fn env_dir(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.map(PathBuf::from)
.filter(|p| p.is_absolute())
}
pub fn runtime_dir() -> PathBuf {
if let Some(d) = env_dir("DREAMER_RUNTIME_DIR") {
return d;
}
if let Some(d) = env_dir("XDG_RUNTIME_DIR") {
return d.join("dreamer");
}
let base = env_dir("TMPDIR").unwrap_or_else(|| PathBuf::from("/tmp"));
base.join(format!("dreamer-{}", uid()))
}
pub fn state_dir() -> PathBuf {
if let Some(d) = env_dir("DREAMER_STATE_DIR") {
return d;
}
if let Some(d) = env_dir("XDG_STATE_HOME") {
return d.join("dreamer");
}
env_dir("HOME")
.unwrap_or_else(|| PathBuf::from("/"))
.join(".local/state/dreamer")
}
pub fn data_dir() -> PathBuf {
if let Some(d) = env_dir("DREAMER_DATA_DIR") {
return d;
}
if let Some(d) = env_dir("XDG_DATA_HOME") {
return d.join("dreamer");
}
env_dir("HOME")
.unwrap_or_else(|| PathBuf::from("/"))
.join(".local/share/dreamer")
}
pub fn socket_path() -> PathBuf {
runtime_dir().join("dreamerd.sock")
}
pub fn rpc_socket_path() -> PathBuf {
runtime_dir().join("dreamerd.rpc.sock")
}
pub const SOCKET_PATH_MAX: usize = if cfg!(target_os = "macos") { 103 } else { 107 };
pub fn check_socket_path(p: &Path) -> Result<(), String> {
let n = p.as_os_str().len();
if n > SOCKET_PATH_MAX {
return Err(format!(
"the socket path {} is {n} bytes, longer than the {SOCKET_PATH_MAX} this system allows; \
use a shorter DREAMER_RUNTIME_DIR",
p.display()
));
}
Ok(())
}
pub fn lock_path() -> PathBuf {
runtime_dir().join("dreamerd.lock")
}
pub fn log_path() -> PathBuf {
state_dir().join("dreamerd.log")
}
pub fn ledger_path() -> PathBuf {
state_dir().join("actions.jsonl")
}
pub fn private_dir(dir: &Path) -> Result<(), String> {
match std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)
{
Ok(()) => {}
Err(e) => return Err(format!("{}: {e}", dir.display())),
}
let meta = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
if !meta.is_dir() {
return Err(format!("{} is not a directory", dir.display()));
}
if meta.uid() != uid() {
return Err(format!(
"{} belongs to uid {}, not this user ({}); refusing to use it",
dir.display(),
meta.uid(),
uid()
));
}
let mode = meta.permissions().mode() & 0o777;
if mode & 0o077 != 0 {
return Err(format!(
"{} is accessible to other users (mode {mode:o}); it must be 0700",
dir.display()
));
}
Ok(())
}
pub fn owner_only(path: &Path) -> Result<(), String> {
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
.map_err(|e| format!("{}: {e}", path.display()))
}
pub fn detach_session() -> Result<(), String> {
rustix::process::setsid()
.map(drop)
.map_err(|e| format!("setsid: {e}"))
}
pub fn process_alive(pid: u32) -> bool {
rustix::process::Pid::from_raw(pid as i32)
.is_some_and(|p| rustix::process::test_kill_process(p).is_ok())
}
pub fn terminate(pid: u32) -> Result<(), String> {
let p = rustix::process::Pid::from_raw(pid as i32).ok_or("invalid pid")?;
rustix::process::kill_process(p, rustix::process::Signal::TERM)
.map_err(|e| format!("kill {pid}: {e}"))
}
pub fn terminate_group(pgid: u32, force: bool) -> Result<(), String> {
let p = rustix::process::Pid::from_raw(pgid as i32).ok_or("invalid process group")?;
let signal = if force {
rustix::process::Signal::KILL
} else {
rustix::process::Signal::TERM
};
rustix::process::kill_process_group(p, signal).map_err(|e| format!("kill -{pgid}: {e}"))
}
pub fn lock_holder() -> Option<u32> {
std::fs::read_to_string(lock_path())
.ok()?
.trim()
.parse()
.ok()
}
pub fn session_of(pid: u32) -> Option<u32> {
let p = rustix::process::Pid::from_raw(pid as i32)?;
rustix::process::getsid(Some(p))
.ok()
.map(|s| s.as_raw_nonzero().get() as u32)
}
#[allow(unsafe_code)]
pub fn release_free_memory() {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
unsafe extern "C" {
fn malloc_trim(pad: usize) -> std::ffi::c_int;
}
unsafe {
malloc_trim(0);
}
}
#[cfg(target_os = "macos")]
{
unsafe extern "C" {
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
}
unsafe {
malloc_zone_pressure_relief(std::ptr::null_mut(), 0);
}
}
}
#[allow(unsafe_code)]
pub fn heap_in_use() -> Option<u64> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
#[repr(C)]
struct Mallinfo2 {
arena: usize,
ordblks: usize,
smblks: usize,
hblks: usize,
hblkhd: usize,
usmblks: usize,
fsmblks: usize,
uordblks: usize,
fordblks: usize,
keepcost: usize,
}
unsafe extern "C" {
fn mallinfo2() -> Mallinfo2;
}
let m = unsafe { mallinfo2() };
Some((m.uordblks + m.hblkhd) as u64)
}
#[cfg(target_os = "macos")]
{
#[repr(C)]
#[derive(Default)]
struct MallocStatistics {
blocks_in_use: u32,
size_in_use: usize,
max_size_in_use: usize,
size_allocated: usize,
}
unsafe extern "C" {
fn malloc_zone_statistics(zone: *mut std::ffi::c_void, stats: *mut MallocStatistics);
}
let mut s = MallocStatistics::default();
unsafe { malloc_zone_statistics(std::ptr::null_mut(), &mut s) };
Some(s.size_in_use as u64)
}
#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_os = "macos")))]
{
None
}
}
#[allow(unsafe_code)]
pub fn phys_footprint(pid: u32) -> Option<u64> {
#[cfg(target_os = "macos")]
{
#[repr(C)]
#[derive(Default)]
struct RusageInfoV2 {
uuid: [u8; 16],
user_time: u64,
system_time: u64,
pkg_idle_wkups: u64,
interrupt_wkups: u64,
pageins: u64,
wired_size: u64,
resident_size: u64,
phys_footprint: u64,
rest: [u64; 10],
}
const RUSAGE_INFO_V2: std::ffi::c_int = 2;
unsafe extern "C" {
fn proc_pid_rusage(
pid: std::ffi::c_int,
flavor: std::ffi::c_int,
buffer: *mut RusageInfoV2,
) -> std::ffi::c_int;
}
let pid = std::ffi::c_int::try_from(pid).ok()?;
let mut info = RusageInfoV2::default();
let rc = unsafe { proc_pid_rusage(pid, RUSAGE_INFO_V2, &mut info) };
(rc == 0).then_some(info.phys_footprint)
}
#[cfg(not(target_os = "macos"))]
{
let _ = pid;
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memory_readings_follow_a_large_block() {
footprint_follows_a_written_block();
heap_in_use_follows_a_large_allocation();
}
fn heap_in_use_follows_a_large_allocation() {
const BLOCK: u64 = 128 << 20;
const SLACK: u64 = 32 << 20;
let Some(before) = heap_in_use() else {
return;
};
let block = vec![1u8; BLOCK as usize];
let during = heap_in_use().unwrap_or(0);
assert!(
during + SLACK >= before + BLOCK,
"{before} then {during} with 128 MiB more held"
);
drop(block);
release_free_memory();
let after = heap_in_use().unwrap_or(u64::MAX);
assert!(
after + BLOCK <= during + SLACK,
"{during} then {after} after freeing 128 MiB"
);
}
#[test]
fn private_dirs_are_created_closed_and_open_ones_refused() {
let base = std::env::temp_dir().join(format!("dreamer-platform-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let dir = base.join("rt");
private_dir(&dir).expect("create");
let mode = std::fs::metadata(&dir).expect("meta").permissions().mode() & 0o777;
assert_eq!(mode, 0o700);
private_dir(&dir).expect("reuse");
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let err = private_dir(&dir).expect_err("open dir refused");
assert!(err.contains("must be 0700"), "{err}");
let _ = std::fs::remove_dir_all(&base);
}
fn footprint_follows_a_written_block() {
const BLOCK: u64 = 128 << 20;
const SLACK: u64 = 32 << 20;
let me = std::process::id();
if !cfg!(target_os = "macos") {
assert_eq!(phys_footprint(me), None);
return;
}
let before = phys_footprint(me).expect("footprint of this process");
let block = vec![1u8; BLOCK as usize];
let during = phys_footprint(me).unwrap_or(0);
assert!(
during + SLACK >= before + BLOCK && during <= before + 2 * BLOCK + SLACK,
"{before} then {during} with 128 MiB more written"
);
drop(block);
}
#[test]
fn this_process_is_alive_and_has_a_session() {
assert!(process_alive(std::process::id()));
assert!(session_of(std::process::id()).is_some());
}
}