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 fleet_socket(dir: &Path, machine: &str) -> PathBuf {
dir.join(format!("fleet-{}.sock", agent_socket_name(machine)))
}
pub fn route_socket(dir: &Path, member: &str) -> PathBuf {
dir.join(format!("{ROUTE_PREFIX}{}.sock", agent_socket_name(member)))
}
pub const ROUTE_PREFIX: &str = "route-";
pub fn link_agent_socket(dir: &Path, dialer: &str) -> PathBuf {
dir.join(format!("agent-link-{}.sock", agent_socket_name(dialer)))
}
pub fn route_agent_socket(dir: &Path, member: &str) -> PathBuf {
dir.join(format!("{ROUTE_AGENT_PREFIX}{}.sock", agent_socket_name(member)))
}
pub const ROUTE_AGENT_PREFIX: &str = "agent-route-";
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>> {
Ok(accept_any(&[listener], timeout)?.map(|(_, stream)| stream))
}
pub fn accept_any(listeners: &[&UnixListener], timeout: Duration) -> io::Result<Option<(usize, Stream)>> {
let mut fds: Vec<libc::pollfd> =
listeners.iter().map(|l| libc::pollfd { fd: l.as_raw_fd(), events: libc::POLLIN, revents: 0 }).collect();
let ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int;
let n = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, ms) };
if n < 0 {
let e = io::Error::last_os_error();
return if e.kind() == io::ErrorKind::Interrupted { Ok(None) } else { Err(e) };
}
let Some(i) = fds.iter().position(|fd| fd.revents != 0) else { return Ok(None) };
match listeners[i].accept().map(|(stream, _)| (i, stream)) {
Ok((i, stream)) => {
stream.set_nonblocking(false)?;
Ok(Some((i, 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))
}
pub fn peer_is_own_user(stream: &Stream) -> bool {
let ours = unsafe { libc::getuid() };
peer_uid(stream) == Some(ours)
}
#[cfg(target_os = "linux")]
fn peer_uid(stream: &Stream) -> Option<u32> {
let mut cred = libc::ucred { pid: 0, uid: 0, gid: 0 };
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
let r = unsafe {
libc::getsockopt(
stream.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERCRED,
(&mut cred as *mut libc::ucred).cast(),
&mut len,
)
};
(r == 0).then_some(cred.uid)
}
#[cfg(not(target_os = "linux"))]
fn peer_uid(stream: &Stream) -> Option<u32> {
let (mut uid, mut gid) = (0, 0);
let r = unsafe { libc::getpeereid(stream.as_raw_fd(), &mut uid, &mut gid) };
(r == 0).then_some(uid)
}
#[cfg(test)]
mod tests {
use super::*;
fn os(s: &str) -> Option<&OsStr> {
Some(OsStr::new(s))
}
#[test]
fn a_pair_in_this_process_is_its_own_user() {
let (a, b) = Stream::pair().unwrap();
assert!(peer_is_own_user(&a) && peer_is_own_user(&b));
}
#[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!(link_agent_socket(dir, "machine:lap-top.local"), dir.join("agent-link-machine_lap-top.local.sock"));
assert_eq!(link_agent_socket(dir, "machine:a b/c\u{e9}"), dir.join("agent-link-machine_a_b_c_.sock"));
let long = |host: &str| link_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-link-".len() + AGENT_CLIENT_MAX + ".sock".len());
assert!(name.starts_with("agent-link-machine_hhh"), "{name}");
}
#[test]
fn fleet_sockets_are_named_after_the_machine() {
let dir = Path::new("/run/user/1000/devsandbox");
assert_eq!(fleet_socket(dir, "lap.top"), dir.join("fleet-lap.top.sock"));
let long = fleet_socket(dir, &"w".repeat(80));
assert_eq!(long.file_name().unwrap().len(), "fleet-".len() + AGENT_CLIENT_MAX + ".sock".len());
assert_eq!(route_socket(dir, "lap.top"), dir.join("route-lap.top.sock"));
let long = route_socket(dir, &"w".repeat(80));
assert_eq!(long.file_name().unwrap().len(), "route-".len() + AGENT_CLIENT_MAX + ".sock".len());
}
#[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);
}
}