#[cfg(unix)]
use std::os::fd::{AsFd, BorrowedFd};
use std::{
future::Future,
io::{self, IoSlice},
};
#[cfg(unix)]
use rustix::net::{
RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, SendAncillaryBuffer,
SendAncillaryMessage, recvmsg, sendmsg,
};
#[cfg(unix)]
use super::SEND_FLAGS;
use super::SocketOps;
#[cfg(unix)]
use crate::utils::FDS_MAX;
use crate::{
connection::socket::RecvmsgResult,
fdo::ConnectionCredentials,
runtime::{IoSource, Runtime},
};
#[derive(Debug)]
pub(crate) struct UnixOps;
impl SocketOps for UnixOps {
#[cfg(unix)]
fn recv(&self, source: &IoSource, buffer: &mut [u8]) -> RecvmsgResult {
fd_recvmsg(source.as_fd(), buffer)
}
#[cfg(windows)]
fn recv(&self, source: &IoSource, buffer: &mut [u8]) -> RecvmsgResult {
super::recv(source, buffer)
}
#[cfg(unix)]
fn send(
&self,
source: &IoSource,
buffers: &[IoSlice<'_>],
fds: &[BorrowedFd<'_>],
) -> io::Result<usize> {
fd_sendmsg(source.as_fd(), buffers, fds)
}
#[cfg(windows)]
fn send(&self, source: &IoSource, buffers: &[IoSlice<'_>]) -> io::Result<usize> {
super::send(source, buffers)
}
fn can_pass_unix_fd(&self) -> bool {
cfg!(unix)
}
#[cfg(unix)]
fn peer_credentials(
&self,
source: &IoSource,
runtime: &Runtime,
) -> impl Future<Output = io::Result<ConnectionCredentials>> + Send {
peer_credentials(source.as_fd(), Some(runtime))
}
#[cfg(windows)]
fn peer_credentials(
&self,
source: &IoSource,
runtime: &Runtime,
) -> impl Future<Output = io::Result<ConnectionCredentials>> + Send {
peer_credentials(source, runtime)
}
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
fn sends_credentials_byte(&self) -> bool {
true
}
}
#[cfg(all(unix, any(feature = "default-rt", feature = "tokio")))]
pub(crate) fn unix_socket_address(
path: &std::path::Path,
) -> io::Result<std::os::unix::net::SocketAddr> {
use std::os::unix::net::SocketAddr;
#[cfg(any(target_os = "android", target_os = "linux"))]
{
#[cfg(target_os = "android")]
use std::os::android::net::SocketAddrExt;
#[cfg(target_os = "linux")]
use std::os::linux::net::SocketAddrExt;
use std::os::unix::ffi::OsStrExt;
if let Some(name) = path.as_os_str().as_bytes().strip_prefix(b"\0") {
return SocketAddr::from_abstract_name(name);
}
}
SocketAddr::from_pathname(path)
}
#[cfg(unix)]
pub(crate) async fn peer_credentials(
fd: BorrowedFd<'_>,
runtime: Option<&Runtime>,
) -> io::Result<ConnectionCredentials> {
let (credentials, lookup) = socket_credentials(fd)?;
Ok(lookup.complete(credentials, runtime).await)
}
#[cfg(windows)]
async fn peer_credentials(
source: &IoSource,
runtime: &Runtime,
) -> io::Result<ConnectionCredentials> {
let source = source.clone();
runtime
.spawn_blocking(move || credentials_from_socket(&source))
.await
}
#[cfg(windows)]
fn credentials_from_socket(
socket: &impl std::os::windows::io::AsRawSocket,
) -> io::Result<ConnectionCredentials> {
use crate::win32::{ProcessToken, unix_stream_get_peer_pid};
let pid = unix_stream_get_peer_pid(socket)? as _;
let sid = ProcessToken::open(if pid != 0 { Some(pid as _) } else { None })
.and_then(|process_token| process_token.sid())?;
Ok(ConnectionCredentials::default()
.set_process_id(pid)
.set_windows_sid(sid))
}
#[cfg(unix)]
fn fd_recvmsg(fd: BorrowedFd<'_>, buffer: &mut [u8]) -> RecvmsgResult {
use std::{io::IoSliceMut, mem::MaybeUninit};
let mut iov = [IoSliceMut::new(buffer)];
let mut cmsg_buffer = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(FDS_MAX))];
let mut ancillary = RecvAncillaryBuffer::new(&mut cmsg_buffer);
let msg = match recvmsg(fd, &mut iov, &mut ancillary, RecvFlags::empty()) {
#[cfg(any(target_os = "linux", target_os = "android"))]
Err(e) if e == rustix::io::Errno::CONNRESET => return Ok((0, vec![])),
msg => msg?,
};
let mut fds = vec![];
for msg in ancillary.drain() {
match msg {
RecvAncillaryMessage::ScmRights(iter) => {
fds.extend(iter);
}
#[cfg(any(target_os = "linux", target_os = "android"))]
RecvAncillaryMessage::ScmCredentials(_) => {
continue;
}
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected CMSG kind",
));
}
}
}
Ok((msg.bytes, fds))
}
#[cfg(unix)]
fn fd_sendmsg(
fd: BorrowedFd<'_>,
buffers: &[IoSlice<'_>],
fds: &[BorrowedFd<'_>],
) -> io::Result<usize> {
use std::mem::MaybeUninit;
let mut cmsg_buffer = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(FDS_MAX))];
let mut ancillary = SendAncillaryBuffer::new(&mut cmsg_buffer);
if !fds.is_empty() && !ancillary.push(SendAncillaryMessage::ScmRights(fds)) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"too many file descriptors",
));
}
let sent = sendmsg(fd, buffers, &mut ancillary, SEND_FLAGS)?;
if sent == 0 {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"failed to write to buffer",
));
}
Ok(sent)
}
#[cfg(unix)]
fn socket_credentials(fd: BorrowedFd<'_>) -> io::Result<(ConnectionCredentials, GroupLookup)> {
let mut creds = ConnectionCredentials::default();
#[cfg(any(target_os = "android", target_os = "linux"))]
let nss;
#[cfg(any(target_os = "android", target_os = "linux"))]
{
let ucred = peer_ucred(fd)?;
let (uid, gid) = (ucred.uid, ucred.gid);
creds = creds.set_unix_user_id(uid);
if let Some(pid) = u32::try_from(ucred.pid).ok().filter(|&pid| pid != 0) {
creds = creds.set_process_id(pid);
}
#[cfg(target_os = "linux")]
{
use libc::{c_int, socklen_t};
use std::{
mem::{MaybeUninit, size_of},
os::fd::{AsRawFd, FromRawFd, OwnedFd},
};
let mut pidfd = MaybeUninit::<c_int>::zeroed();
let mut len = size_of::<c_int>() as socklen_t;
let ret = unsafe {
libc::getsockopt(
fd.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERPIDFD,
pidfd.as_mut_ptr().cast(),
&mut len,
)
};
if ret == 0 {
let pidfd = unsafe { pidfd.assume_init() };
creds = creds.set_process_fd(unsafe { OwnedFd::from_raw_fd(pidfd).into() });
} else if ret < 0 {
let err = io::Error::last_os_error();
if !matches!(
err.raw_os_error(),
Some(libc::ENOPROTOOPT | libc::ENODATA | libc::EINVAL | libc::ESRCH)
) {
return Err(err);
}
}
}
#[cfg(target_os = "linux")]
match peer_groups(fd, gid)? {
Some(groups) => {
for group in groups {
creds = creds.add_unix_group_id(group);
}
nss = None;
}
None => nss = Some((uid, gid)),
}
#[cfg(target_os = "android")]
{
nss = Some((uid, gid));
}
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd"
))]
{
use std::os::fd::AsRawFd;
let mut uid: libc::uid_t = 0;
let mut gid: libc::gid_t = 0;
let ret = unsafe { libc::getpeereid(fd.as_raw_fd(), &mut uid, &mut gid) };
if ret != 0 {
return Err(io::Error::last_os_error());
}
creds = creds.set_unix_user_id(uid);
}
Ok((
creds,
GroupLookup {
#[cfg(any(target_os = "android", target_os = "linux"))]
nss,
},
))
}
#[cfg(any(target_os = "android", target_os = "linux"))]
fn peer_ucred(fd: BorrowedFd<'_>) -> io::Result<libc::ucred> {
use std::os::fd::AsRawFd;
let mut ucred = libc::ucred {
pid: 0,
uid: 0,
gid: 0,
};
let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
let ret = unsafe {
libc::getsockopt(
fd.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERCRED,
std::ptr::from_mut(&mut ucred).cast(),
&mut len,
)
};
if ret < 0 {
return Err(io::Error::last_os_error());
}
Ok(ucred)
}
#[cfg(unix)]
#[derive(Debug)]
struct GroupLookup {
#[cfg(any(target_os = "android", target_os = "linux"))]
nss: Option<(libc::uid_t, libc::gid_t)>,
}
#[cfg(unix)]
impl GroupLookup {
#[cfg(any(target_os = "android", target_os = "linux"))]
async fn complete(
self,
mut credentials: ConnectionCredentials,
runtime: Option<&Runtime>,
) -> ConnectionCredentials {
let Some((uid, gid)) = self.nss else {
return credentials;
};
let lookup = move || Self::groups(uid, gid);
let groups = match runtime {
Some(runtime) => runtime.spawn_blocking(lookup).await,
None => unblock(lookup).await,
};
for group in groups {
credentials = credentials.add_unix_group_id(group);
}
credentials
}
#[cfg(not(any(target_os = "android", target_os = "linux")))]
async fn complete(
self,
credentials: ConnectionCredentials,
_runtime: Option<&Runtime>,
) -> ConnectionCredentials {
credentials
}
#[cfg(any(target_os = "android", target_os = "linux"))]
fn groups(uid: libc::uid_t, gid: libc::gid_t) -> Vec<u32> {
use crate::log::debug;
let mut passwd: libc::passwd = unsafe { std::mem::zeroed() };
let mut buf = vec![0u8; 16384];
let mut result: *mut libc::passwd = std::ptr::null_mut();
unsafe {
libc::getpwuid_r(
uid,
&mut passwd,
buf.as_mut_ptr() as *mut libc::c_char,
buf.len(),
&mut result,
);
}
if result.is_null() {
return vec![];
}
let username = unsafe { std::ffi::CStr::from_ptr((*result).pw_name) };
let mut groups = vec![0u32; INITIAL_GROUPS];
loop {
let mut ngroups = libc::c_int::try_from(groups.len()).unwrap_or(libc::c_int::MAX);
let found = unsafe {
libc::getgrouplist(
username.as_ptr(),
gid,
groups.as_mut_ptr() as *mut libc::gid_t,
&mut ngroups,
)
};
let ngroups = usize::try_from(ngroups).unwrap_or(0);
if found >= 0 {
groups.truncate(ngroups);
break;
}
if ngroups <= groups.len() {
debug!("Group lookup failed for user {:?}", username);
return vec![];
}
groups.resize(ngroups, 0);
}
groups.sort();
groups.dedup();
groups
}
}
#[cfg(any(target_os = "android", target_os = "linux"))]
async fn unblock<T>(work: impl FnOnce() -> T + Send + 'static) -> T
where
T: Send + 'static,
{
#[cfg(feature = "tokio")]
if let Some(runtime) = crate::runtime::Tokio::current() {
return crate::runtime::traits::Runtime::spawn_blocking(&runtime, work).await;
}
zruntime::unblock(work).await
}
#[cfg(target_os = "linux")]
fn peer_groups(fd: BorrowedFd<'_>, gid: libc::gid_t) -> io::Result<Option<Vec<u32>>> {
use std::{mem::size_of, os::fd::AsRawFd};
let mut groups: Vec<libc::gid_t> = vec![0; INITIAL_GROUPS];
loop {
let room = groups.len() * size_of::<libc::gid_t>();
let mut len = libc::socklen_t::try_from(room).unwrap_or(libc::socklen_t::MAX);
let ret = unsafe {
libc::getsockopt(
fd.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERGROUPS,
groups.as_mut_ptr().cast(),
&mut len,
)
};
let len = usize::try_from(len).unwrap_or(usize::MAX);
if ret == 0 {
groups.truncate(len / size_of::<libc::gid_t>());
break;
}
let err = io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::ERANGE) if len > room => {
groups.resize(len.div_ceil(size_of::<libc::gid_t>()), 0);
}
Some(libc::ENOPROTOOPT | libc::ENODATA) => return Ok(None),
_ => return Err(err),
}
}
groups.push(gid);
groups.sort_unstable();
groups.dedup();
Ok(Some(groups))
}
#[cfg(any(target_os = "android", target_os = "linux"))]
const INITIAL_GROUPS: usize = 64;
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
pub(super) fn send_credentials_byte(fd: std::os::fd::RawFd) -> io::Result<usize> {
use std::mem::MaybeUninit;
let mut iov = libc::iovec {
iov_base: c"".as_ptr() as *mut libc::c_void,
iov_len: 1,
};
let mut msg: libc::msghdr = unsafe { MaybeUninit::zeroed().assume_init() };
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1;
let cmsg_space = unsafe { libc::CMSG_SPACE(0) as usize };
let mut cmsg_buf = vec![0u8; cmsg_space];
msg.msg_control = cmsg_buf.as_mut_ptr() as *mut libc::c_void;
msg.msg_controllen = cmsg_space as _;
let cmsg = unsafe { libc::CMSG_FIRSTHDR(&msg) };
if !cmsg.is_null() {
unsafe {
(*cmsg).cmsg_level = libc::SOL_SOCKET;
(*cmsg).cmsg_type = libc::SCM_CREDS;
(*cmsg).cmsg_len = libc::CMSG_LEN(0) as _;
}
}
let ret = unsafe { libc::sendmsg(fd, &msg, 0) };
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(ret as usize)
}
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
use std::os::{fd::AsFd, unix::net::UnixStream};
use rustix::process::{getegid, geteuid, getgroups};
use super::GroupLookup;
#[cfg(feature = "bus-impl")]
use crate::Error;
use crate::{block_on, fdo::ConnectionCredentials};
#[test]
fn credentials_of_a_peer() {
let (socket, _peer) = UnixStream::pair().unwrap();
let (credentials, lookup) = super::socket_credentials(socket.as_fd()).unwrap();
assert_ours(&credentials);
assert!(lookup.nss.is_none());
}
#[test]
fn groups_are_looked_up_with_no_connection() {
let (uid, gid) = (geteuid().as_raw(), getegid().as_raw());
let lookup = GroupLookup {
nss: Some((uid, gid)),
};
let credentials = block_on(lookup.complete(ConnectionCredentials::default(), None));
let groups = credentials.unix_group_ids().cloned().unwrap_or_default();
assert_eq!(groups, GroupLookup::groups(uid, gid));
}
#[cfg(feature = "bus-impl")]
#[test]
fn credentials_of_the_peer_of_a_socket_of_its_own() {
let (socket, _peer) = UnixStream::pair().unwrap();
let credentials = block_on(ConnectionCredentials::of_peer(&socket)).unwrap();
assert_ours(&credentials);
}
#[cfg(feature = "bus-impl")]
#[test]
fn a_descriptor_that_is_no_socket_has_no_credentials() {
let (read, _write) = std::io::pipe().unwrap();
let credentials = block_on(ConnectionCredentials::of_peer(&read));
let Err(Error::InputOutput(e)) = &credentials else {
panic!("a pipe has credentials: {credentials:?}");
};
assert_eq!(e.raw_os_error(), Some(libc::ENOTSOCK), "{e}");
}
fn assert_ours(credentials: &ConnectionCredentials) {
assert_eq!(credentials.unix_user_id(), Some(geteuid().as_raw()));
assert_eq!(credentials.process_id(), Some(std::process::id()));
let mut groups: Vec<_> = getgroups()
.unwrap()
.into_iter()
.map(|group| group.as_raw())
.chain([getegid().as_raw()])
.collect();
groups.sort_unstable();
groups.dedup();
assert_eq!(credentials.unix_group_ids(), Some(&groups));
}
}