use std::ffi::CStr;
use std::io;
use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::trace;
static DEFAULT_NAMES: AtomicU32 = AtomicU32::new(0);
fn user_name() -> String {
let uid = unsafe { libc::getuid() };
let mut pwd = std::mem::MaybeUninit::<libc::passwd>::uninit();
let mut buf = vec![0 as libc::c_char; 1024];
let mut result = std::ptr::null_mut();
loop {
let rc = unsafe {
libc::getpwuid_r(
uid,
pwd.as_mut_ptr(),
buf.as_mut_ptr(),
buf.len(),
&mut result,
)
};
if rc == libc::ERANGE && buf.len() < 1 << 20 {
buf.resize(buf.len() * 2, 0);
continue;
}
break;
}
if result.is_null() {
return uid.to_string();
}
let name = unsafe { CStr::from_ptr((*result).pw_name) };
name.to_string_lossy().into_owned()
}
fn default_name() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let n = DEFAULT_NAMES.fetch_add(1, Ordering::Relaxed);
let base = format!("{:09}-{secs}", std::process::id());
if n == 0 { base } else { format!("{base}-{n}") }
}
pub(crate) fn socket_path(spec: &str) -> io::Result<PathBuf> {
if spec.is_empty() {
let dir = PathBuf::from(format!("/tmp/omni-{}", user_name()));
if !dir.is_dir() {
std::fs::DirBuilder::new().mode(0o755).create(&dir)?;
}
Ok(dir.join(default_name()))
} else if spec.ends_with('/') {
Ok(Path::new(spec).join(default_name()))
} else {
Ok(PathBuf::from(spec))
}
}
#[derive(Debug)]
pub(crate) struct SocketFile {
path: PathBuf,
dev: u64,
ino: u64,
}
impl Drop for SocketFile {
fn drop(&mut self) {
if let Ok(meta) = std::fs::symlink_metadata(&self.path) {
if meta.dev() == self.dev && meta.ino() == self.ino {
let _ = std::fs::remove_file(&self.path);
}
}
}
}
pub(crate) fn bind(path: &Path) -> io::Result<(UnixListener, SocketFile)> {
if let Ok(meta) = std::fs::symlink_metadata(path) {
if !meta.file_type().is_socket() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("{} exists and is not a socket", path.display()),
));
}
if UnixStream::connect(path).is_ok() {
return Err(io::Error::new(
io::ErrorKind::AddrInUse,
format!("{} is in use", path.display()),
));
}
trace::info!("removing the stale socket {}", path.display());
std::fs::remove_file(path)?;
}
let listener = UnixListener::bind(path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o777))?;
let meta = std::fs::symlink_metadata(path)?;
Ok((
listener,
SocketFile {
path: path.to_owned(),
dev: meta.dev(),
ino: meta.ino(),
},
))
}
pub(crate) fn host() -> &'static str {
static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HOST.get_or_init(|| {
let mut buf = [0u8; 256];
let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) };
if rc != 0 {
return "localhost".into();
}
let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..end]).into_owned()
})
}