use std::io;
#[cfg(unix)]
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::Path;
pub use datagram::Datagram;
pub use descriptor::Descriptor;
#[cfg(windows)]
pub mod account;
pub mod datagram;
pub mod descriptor;
#[cfg(feature = "tokio")]
pub mod tokio;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::{Listener, MAX_PATH, SocketAddr, Stream, link};
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const MAX_PATH: usize = 107;
#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
pub const MAX_PATH: usize = 103;
#[cfg(not(any(unix, windows)))]
pub const MAX_PATH: usize = 0;
#[cfg(unix)]
pub type Listener = UnixListener;
#[cfg(unix)]
pub type Stream = UnixStream;
#[cfg(unix)]
pub use std::os::unix::net::SocketAddr;
#[cfg(not(any(unix, windows)))]
pub struct Listener(std::convert::Infallible);
#[cfg(not(any(unix, windows)))]
pub struct Stream(std::convert::Infallible);
pub fn bind(path: &Path) -> io::Result<Listener> {
#[cfg(unix)]
{
reach(path, |short| UnixListener::bind(short))
}
#[cfg(windows)]
{
windows::bind(path)
}
#[cfg(not(any(unix, windows)))]
{
Err(no_socket(path))
}
}
pub fn connect(path: &Path) -> io::Result<Stream> {
#[cfg(unix)]
{
reach(path, |short| UnixStream::connect(short))
}
#[cfg(windows)]
{
windows::connect(path)
}
#[cfg(not(any(unix, windows)))]
{
Err(no_socket(path))
}
}
pub fn pair() -> io::Result<(Stream, Stream)> {
#[cfg(unix)]
{
UnixStream::pair()
}
#[cfg(windows)]
{
link::pair()
}
#[cfg(not(any(unix, windows)))]
{
Err(io::Error::new(
io::ErrorKind::Unsupported,
"a page has no local socket",
))
}
}
#[must_use]
pub fn is_bound(path: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt as _;
std::fs::symlink_metadata(path).is_ok_and(|found| found.file_type().is_socket())
}
#[cfg(windows)]
{
windows::is_bound(path)
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
false
}
}
pub fn peek(stream: &Stream, buffer: &mut [u8], within: std::time::Duration) -> io::Result<usize> {
#[cfg(unix)]
{
use std::os::fd::AsRawFd as _;
stream.set_read_timeout(Some(within))?;
let read = unsafe {
libc::recv(
stream.as_raw_fd(),
buffer.as_mut_ptr().cast(),
buffer.len(),
libc::MSG_PEEK,
)
};
let error = io::Error::last_os_error();
stream.set_read_timeout(None)?;
match usize::try_from(read) {
Ok(read) => Ok(read),
Err(_)
if matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
) =>
{
Ok(0)
}
Err(_) => Err(error),
}
}
#[cfg(windows)]
{
windows::peek(stream, buffer, within)
}
#[cfg(not(any(unix, windows)))]
{
let _ = (stream, buffer, within);
Ok(0)
}
}
#[must_use]
pub fn connected(stream: &Stream) -> bool {
#[cfg(unix)]
{
use std::os::fd::AsRawFd as _;
let mut byte = 0_u8;
let read = unsafe {
libc::recv(
stream.as_raw_fd(),
(&raw mut byte).cast(),
1,
libc::MSG_PEEK | libc::MSG_DONTWAIT,
)
};
match read {
0 => false,
read if read > 0 => true,
_ => matches!(
io::Error::last_os_error().kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
),
}
}
#[cfg(windows)]
{
windows::connected(stream)
}
#[cfg(not(any(unix, windows)))]
{
let _ = stream;
false
}
}
#[cfg(not(any(unix, windows)))]
fn no_socket(_path: &Path) -> io::Error {
io::Error::new(io::ErrorKind::Unsupported, "a page has no local socket")
}
#[cfg(unix)]
fn reach<T>(path: &Path, act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
if path.as_os_str().len() <= MAX_PATH {
return act(path);
}
through_directory(path, act)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn through_directory<T>(path: &Path, act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
use std::os::fd::AsRawFd as _;
let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
return Err(too_long(path));
};
let parent = if parent.as_os_str().is_empty() {
Path::new(".")
} else {
parent
};
let directory = std::fs::File::open(parent).map_err(|error| {
let kind = error.kind();
io::Error::new(kind, format!("{}: {error}", parent.display()))
})?;
let short = Path::new("/proc/self/fd")
.join(directory.as_raw_fd().to_string())
.join(name);
if short.as_os_str().len() > MAX_PATH {
return Err(too_long(path));
}
act(&short)
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
fn through_directory<T>(path: &Path, _act: impl FnOnce(&Path) -> io::Result<T>) -> io::Result<T> {
Err(too_long(path))
}
#[cfg(unix)]
fn too_long(path: &Path) -> io::Error {
io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"{}: a socket's name must be at most {MAX_PATH} bytes",
path.display()
),
)
}
#[cfg(test)]
#[expect(
clippy::mixed_attributes_style,
reason = "the module is a test module, whose panics the lint rules exempt, that binds a Unix socket"
)]
mod tests {
#![cfg(unix)]
use super::*;
use std::io::{Read as _, Write as _};
fn deep() -> (tempfile::TempDir, std::path::PathBuf) {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("a".repeat(60)).join("b".repeat(60));
std::fs::create_dir_all(&dir).unwrap();
(root, dir)
}
tilo_test_env::scenario! {
fn a_socket_binds_and_connects_however_deep_its_directory;
phase a_socket_in_a_deep_directory_binds_and_answers;
{
let (_root, dir) = deep();
let path = dir.join("files.sock");
assert!(path.as_os_str().len() > MAX_PATH);
let listener = bind(&path).unwrap();
assert!(path.exists(), "the socket is named where it was asked for");
let mut client = connect(&path).unwrap();
client.write_all(b"hi").unwrap();
let (mut served, _) = listener.accept().unwrap();
let mut got = [0; 2];
served.read_exact(&mut got).unwrap();
assert_eq!(&got, b"hi");
}
phase nothing_bound_in_a_deep_directory_is_not_found;
{
let (_root, dir) = deep();
let error = connect(&dir.join("files.sock")).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound);
}
phase a_short_path_is_used_as_it_is;
{
let root = tempfile::tempdir().unwrap();
let path = root.path().join("s");
let listener = bind(&path).unwrap();
assert_eq!(
listener.local_addr().unwrap().as_pathname(),
Some(path.as_path())
);
connect(&path).unwrap();
}
}
}