diff options
Diffstat (limited to 'library/std/src/sys/unix/ext/ucred.rs')
| -rw-r--r-- | library/std/src/sys/unix/ext/ucred.rs | 51 |
1 files changed, 47 insertions, 4 deletions
diff --git a/library/std/src/sys/unix/ext/ucred.rs b/library/std/src/sys/unix/ext/ucred.rs index ed7516c7f28..e2aeb39f995 100644 --- a/library/std/src/sys/unix/ext/ucred.rs +++ b/library/std/src/sys/unix/ext/ucred.rs @@ -31,12 +31,16 @@ pub use self::impl_linux::peer_cred; #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", target_os = "openbsd" ))] pub use self::impl_bsd::peer_cred; +#[cfg(any( + target_os = "macos", + target_os = "ios", +))] +pub use self::impl_mac::peer_cred; + #[cfg(any(target_os = "linux", target_os = "android"))] pub mod impl_linux { use super::UCred; @@ -75,8 +79,6 @@ pub mod impl_linux { #[cfg(any( target_os = "dragonfly", - target_os = "macos", - target_os = "ios", target_os = "freebsd", target_os = "openbsd" ))] @@ -95,3 +97,44 @@ pub mod impl_bsd { } } } + +#[cfg(any( + target_os = "macos", + target_os = "ios", +))] +pub mod impl_mac { + use super::UCred; + use crate::{io, mem}; + use crate::os::unix::io::AsRawFd; + use crate::os::unix::net::UnixStream; + use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, SOL_LOCAL, LOCAL_PEERPID}; + + pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> { + let mut cred = UCred { uid: 1, gid: 1, pid: None }; + unsafe { + let ret = getpeereid(socket.as_raw_fd(), &mut cred.uid, &mut cred.gid); + + if ret != 0 { + return Err(io::Error::last_os_error()); + } + + let mut pid: pid_t = 1; + let mut pid_size = mem::size_of::<pid_t>() as socklen_t; + + let ret = getsockopt( + socket.as_raw_fd(), + SOL_LOCAL, + LOCAL_PEERPID, + &mut pid as *mut pid_t as *mut c_void, + &mut pid_size + ); + + if ret == 0 && pid_size as usize == mem::size_of::<pid_t>() { + cred.pid = Some(pid); + Ok(cred) + } else { + Err(io::Error::last_os_error()) + } + } + } +} |
