1use std::io;
16use std::os::unix::net::UnixStream;
17use std::os::unix::prelude::*;
18
19#[derive(Clone, Debug, Eq, Hash, PartialEq)]
21#[repr(C)]
22pub struct Ucred {
23 #[cfg(any(target_os = "linux", target_os = "netbsd"))]
25 pub pid: libc::pid_t,
26 pub uid: libc::uid_t,
28 pub gid: libc::gid_t,
30 #[cfg(target_os = "openbsd")]
32 pub pid: libc::pid_t,
33}
34
35#[cfg(target_os = "netbsd")]
36const PEERCRED_LEVEL: libc::c_int = 0;
37#[cfg(not(target_os = "netbsd"))]
38const PEERCRED_LEVEL: libc::c_int = libc::SOL_SOCKET;
39
40#[cfg(target_os = "netbsd")]
41const SO_PEERCRED: libc::c_int = crate::constants::LOCAL_PEEREID;
42#[cfg(not(target_os = "netbsd"))]
43const SO_PEERCRED: libc::c_int = libc::SO_PEERCRED;
44
45pub(crate) unsafe fn get_ucred_raw(sockfd: RawFd) -> io::Result<Ucred> {
46 let mut ucred = Ucred {
47 pid: 0,
48 uid: 0,
49 gid: 0,
50 };
51
52 let len = crate::util::getsockopt_raw(
53 sockfd,
54 PEERCRED_LEVEL,
55 SO_PEERCRED,
56 std::slice::from_mut(&mut ucred),
57 )?;
58
59 if len != std::mem::size_of::<Ucred>()
60 || ucred.pid == 0
61 || ucred.uid == libc::uid_t::MAX
62 || ucred.gid == libc::gid_t::MAX
63 {
64 return Err(io::Error::from_raw_os_error(libc::EINVAL));
65 }
66
67 Ok(ucred)
68}
69
70#[inline]
72pub fn get_ucred(sock: &UnixStream) -> io::Result<Ucred> {
73 unsafe { get_ucred_raw(sock.as_raw_fd()) }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 use std::os::unix::net::UnixDatagram;
81
82 #[test]
83 fn test_get_ucred() {
84 let uid = unsafe { libc::getuid() };
85 let gid = unsafe { libc::getgid() };
86 let pid = unsafe { libc::getpid() };
87
88 let (a, b) = UnixStream::pair().unwrap();
89
90 let acred = get_ucred(&a).unwrap();
91 assert_eq!(acred.uid, uid);
92 assert_eq!(acred.gid, gid);
93 assert_eq!(acred.pid, pid);
94
95 let bcred = get_ucred(&b).unwrap();
96 assert_eq!(bcred.uid, uid);
97 assert_eq!(bcred.gid, gid);
98 assert_eq!(bcred.pid, pid);
99 }
100
101 #[test]
102 fn test_get_ucred_error() {
103 let dir = tempfile::tempdir().unwrap();
104
105 let sock = UnixDatagram::bind(dir.path().join("sock")).unwrap();
106
107 let eno = get_ucred(unsafe { &UnixStream::from_raw_fd(sock.as_raw_fd()) })
108 .unwrap_err()
109 .raw_os_error()
110 .unwrap();
111
112 assert!([libc::EINVAL, libc::ENOTCONN].contains(&eno));
113 }
114}