use std::ffi::OsStr;
use std::io;
use std::os::fd::AsRawFd;
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
use std::os::unix::net::UnixListener;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result};
pub type Stream = std::os::unix::net::UnixStream;
pub const SOCKET_FILE: &str = "serve.sock";
pub const LOCK_FILE: &str = "serve.lock";
pub const LOG_FILE: &str = "serve.log";
pub fn socket_dir_from(runtime: Option<&OsStr>, state: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
xdg_base(runtime).map(|r| r.join("devsandbox")).or_else(|| state_dir_from(state, home))
}
pub fn state_dir_from(state: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
let base = xdg_base(state).or_else(|| xdg_base(home).map(|h| h.join(".local/state")))?;
Some(base.join("devsandbox"))
}
fn xdg_base(value: Option<&OsStr>) -> Option<PathBuf> {
let path = PathBuf::from(value?);
path.is_absolute().then_some(path)
}
pub fn socket_dir() -> Result<PathBuf> {
let var = std::env::var_os;
socket_dir_from(var("XDG_RUNTIME_DIR").as_deref(), var("XDG_STATE_HOME").as_deref(), var("HOME").as_deref())
.context("cannot determine the devsandbox serve socket dir ($XDG_RUNTIME_DIR, $XDG_STATE_HOME or $HOME)")
}
pub fn log_path() -> Result<PathBuf> {
let var = std::env::var_os;
let dir = state_dir_from(var("XDG_STATE_HOME").as_deref(), var("HOME").as_deref())
.context("cannot determine the devsandbox state dir ($XDG_STATE_HOME or $HOME)")?;
Ok(dir.join(LOG_FILE))
}
pub fn socket_path(dir: &Path) -> PathBuf {
dir.join(SOCKET_FILE)
}
pub fn lock_path(dir: &Path) -> PathBuf {
dir.join(LOCK_FILE)
}
const AGENT_CLIENT_MAX: usize = 40;
pub fn agent_socket(dir: &Path, client: &str) -> PathBuf {
dir.join(format!("agent-{}.sock", agent_socket_name(client)))
}
fn agent_socket_name(client: &str) -> String {
let safe: String = client
.chars()
.map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { c } else { '_' })
.collect();
if safe.len() <= AGENT_CLIENT_MAX {
return safe;
}
let hash = crate::config::short_hash(client);
format!("{}-{}", &safe[..AGENT_CLIENT_MAX - 9], &hash[..8])
}
pub fn agent_sockets(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
.flatten()
.filter(|e| {
let name = e.file_name();
let name = name.to_string_lossy();
name.starts_with("agent-") && name.ends_with(".sock")
})
.filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
found.into_iter().map(|(_, p)| p).collect()
}
pub fn ensure_private_dir(dir: &Path) -> Result<()> {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)
.with_context(|| format!("cannot create {}", dir.display()))?;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.with_context(|| format!("cannot chmod {}", dir.display()))
}
pub struct Listener {
inner: UnixListener,
path: PathBuf,
}
impl Listener {
pub fn bind(dir: &Path) -> Result<Self> {
let path = socket_path(dir);
match std::fs::remove_file(&path) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e).with_context(|| format!("cannot remove stale {}", path.display())),
}
let inner = UnixListener::bind(&path).with_context(|| format!("cannot bind {}", path.display()))?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
.with_context(|| format!("cannot chmod {}", path.display()))?;
inner.set_nonblocking(true).context("cannot make the listener non-blocking")?;
Ok(Self { inner, path })
}
pub fn accept_timeout(&self, timeout: Duration) -> io::Result<Option<Stream>> {
accept_timeout(&self.inner, timeout)
}
pub fn remove(self) {
drop(self.inner);
let _ = std::fs::remove_file(&self.path);
}
}
pub fn accept_timeout(listener: &UnixListener, timeout: Duration) -> io::Result<Option<Stream>> {
let mut fd = libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 };
let ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int;
let n = unsafe { libc::poll(&mut fd, 1, ms) };
if n < 0 {
let e = io::Error::last_os_error();
return if e.kind() == io::ErrorKind::Interrupted { Ok(None) } else { Err(e) };
}
if n == 0 {
return Ok(None);
}
match listener.accept() {
Ok((stream, _)) => {
stream.set_nonblocking(false)?;
Ok(Some(stream))
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None),
Err(e) => Err(e),
}
}
pub fn connect(dir: &Path) -> io::Result<Stream> {
Stream::connect(socket_path(dir))
}
#[cfg(test)]
mod tests {
use super::*;
fn os(s: &str) -> Option<&OsStr> {
Some(OsStr::new(s))
}
#[test]
fn socket_dir_prefers_runtime_then_state_then_home() {
let p = |r, s, h| socket_dir_from(r, s, h).map(|p| p.display().to_string());
assert_eq!(p(os("/run/user/1000"), os("/st"), os("/home/u")).as_deref(), Some("/run/user/1000/devsandbox"));
assert_eq!(p(None, os("/st"), os("/home/u")).as_deref(), Some("/st/devsandbox"));
assert_eq!(p(None, None, os("/home/u")).as_deref(), Some("/home/u/.local/state/devsandbox"));
assert_eq!(p(None, None, None), None);
}
#[test]
fn empty_or_relative_xdg_values_are_ignored() {
let p = |r, s, h| socket_dir_from(r, s, h).map(|p| p.display().to_string());
assert_eq!(p(os(""), os("rel"), os("/home/u")).as_deref(), Some("/home/u/.local/state/devsandbox"));
assert_eq!(p(os("rel"), None, os("")), None);
}
#[test]
fn state_dir_falls_back_to_home() {
let p = |s, h| state_dir_from(s, h).map(|p| p.display().to_string());
assert_eq!(p(os("/st"), os("/home/u")).as_deref(), Some("/st/devsandbox"));
assert_eq!(p(None, os("/home/u")).as_deref(), Some("/home/u/.local/state/devsandbox"));
assert_eq!(p(None, None), None);
}
#[test]
fn bind_makes_dir_0700_and_socket_0600() {
let root = std::env::temp_dir().join(format!("devsandbox-serve-perm-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let dir = root.join("devsandbox");
std::fs::create_dir_all(&dir).unwrap();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(socket_path(&dir), "").unwrap();
ensure_private_dir(&dir).unwrap();
let listener = Listener::bind(&dir).unwrap();
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&dir), 0o700);
assert_eq!(mode(&socket_path(&dir)), 0o600);
assert!(listener.accept_timeout(Duration::from_millis(10)).unwrap().is_none());
let _client = connect(&dir).unwrap();
assert!(listener.accept_timeout(Duration::from_secs(5)).unwrap().is_some());
listener.remove();
assert!(!socket_path(&dir).exists());
assert!(connect(&dir).is_err());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn agent_socket_names_are_sanitized_and_bounded() {
let dir = Path::new("/run/user/1000/devsandbox");
assert_eq!(agent_socket(dir, "machine:lap-top.local"), dir.join("agent-machine_lap-top.local.sock"));
assert_eq!(agent_socket(dir, "machine:a b/c\u{e9}"), dir.join("agent-machine_a_b_c_.sock"));
let long = |host: &str| agent_socket(dir, &format!("machine:{}{host}", "h".repeat(60)));
let (a, b) = (long("a"), long("b"));
assert_ne!(a, b, "two long names that share a prefix don't collide");
assert_eq!(a, long("a"), "stable");
let name = a.file_name().unwrap().to_str().unwrap();
assert_eq!(name.len(), "agent-".len() + AGENT_CLIENT_MAX + ".sock".len());
assert!(name.starts_with("agent-machine_hhh"), "{name}");
}
#[test]
fn agent_sockets_are_newest_first() {
let dir = std::env::temp_dir().join(format!("dsv-as-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let now = std::time::SystemTime::now();
for (name, age) in [("agent-old.sock", 20), ("agent-new.sock", 0), ("agent-mid.sock", 10), ("serve.sock", 0), ("agent-x.tmp", 0)] {
let f = std::fs::File::create(dir.join(name)).unwrap();
f.set_modified(now - Duration::from_secs(age)).unwrap();
}
let names: Vec<_> = agent_sockets(&dir).iter().map(|p| p.file_name().unwrap().to_owned()).collect();
assert_eq!(names, ["agent-new.sock", "agent-mid.sock", "agent-old.sock"]);
assert!(agent_sockets(&dir.join("missing")).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}