use core::fmt;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::net::UnixDatagram;
use std::path::Path;
pub const NOTIFY_SOCKET_ENV: &str = "NOTIFY_SOCKET";
const READY: &[u8] = b"READY=1\n";
const ABSTRACT_PREFIX: u8 = b'@';
pub fn notify_ready() -> Result<bool, NotifyError> {
match std::env::var_os(NOTIFY_SOCKET_ENV) {
Some(target) => notify(&target).map(|()| true),
None => Ok(false),
}
}
pub fn notify(target: &OsStr) -> Result<(), NotifyError> {
match target.as_bytes().strip_prefix(&[ABSTRACT_PREFIX]) {
Some(name) => send_to_abstract(name),
None => {
let socket = UnixDatagram::unbound()?;
socket.send_to(READY, Path::new(target))?;
Ok(())
}
}
}
#[cfg(target_os = "linux")]
fn send_to_abstract(name: &[u8]) -> Result<(), NotifyError> {
use std::os::linux::net::SocketAddrExt;
use std::os::unix::net::SocketAddr;
let addr = SocketAddr::from_abstract_name(name)?;
let socket = UnixDatagram::unbound()?;
socket.send_to_addr(READY, &addr)?;
Ok(())
}
#[cfg(not(target_os = "linux"))]
fn send_to_abstract(_name: &[u8]) -> Result<(), NotifyError> {
Err(NotifyError::Unsupported)
}
#[non_exhaustive]
#[derive(Debug)]
pub enum NotifyError {
Unsupported,
Io(std::io::Error),
}
impl fmt::Display for NotifyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unsupported => write!(
f,
"an `@` address names the abstract socket namespace, which this platform has none of"
),
Self::Io(err) => write!(f, "readiness could not be reported: {err}"),
}
}
}
impl core::error::Error for NotifyError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Unsupported => None,
Self::Io(err) => Some(err),
}
}
}
impl From<std::io::Error> for NotifyError {
fn from(source: std::io::Error) -> Self {
Self::Io(source)
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::time::Duration;
#[test]
fn ready_reaches_a_listening_socket_verbatim() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("notify.sock");
let listener = UnixDatagram::bind(&path).unwrap();
listener
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
notify(path.as_os_str()).unwrap();
let mut buf = [0u8; 64];
let read = listener.recv(&mut buf).unwrap();
assert_eq!(&buf[..read], b"READY=1\n");
}
#[test]
fn an_address_nothing_is_listening_on_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nobody-here.sock");
assert!(notify(path.as_os_str()).is_err());
}
#[cfg(target_os = "linux")]
#[test]
fn an_abstract_address_reaches_the_abstract_namespace() {
use std::os::linux::net::SocketAddrExt;
use std::os::unix::net::SocketAddr;
let name = format!("shep-notify-{}", std::process::id());
let addr = SocketAddr::from_abstract_name(name.as_bytes()).unwrap();
let listener = UnixDatagram::bind_addr(&addr).unwrap();
listener
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut target = std::ffi::OsString::from("@");
target.push(&name);
notify(&target).unwrap();
let mut buf = [0u8; 64];
let read = listener.recv(&mut buf).unwrap();
assert_eq!(&buf[..read], b"READY=1\n");
}
#[cfg(not(target_os = "linux"))]
#[test]
fn an_abstract_address_is_refused_where_there_is_no_such_namespace() {
let sent = notify(std::ffi::OsStr::new("@shep-notify-nowhere"));
assert!(
matches!(sent, Err(NotifyError::Unsupported)),
"there is no abstract namespace on this platform: {sent:?}"
);
}
#[test]
fn an_unset_notify_socket_reports_nothing_and_is_not_an_error() {
if std::env::var_os(NOTIFY_SOCKET_ENV).is_some() {
return;
}
assert!(
!notify_ready().unwrap(),
"an unset $NOTIFY_SOCKET reports that nothing was told, not that something was"
);
}
}