unix_cred/
ucred.rs

1//! The `ucred` module provides an interface to the `ucred` interface on Linux, the `sockpeecred`
2//! interface on OpenBSD, or the `unpcbid` interface on NetBSD.
3//!
4//! The reason that the interfaces for all three of these are in one module is that they are all
5//! essentially the same interface, with only minor implementation differences (such as the order
6//! of the fields in the C struct, or the name of the socket option used to retrieve them).
7//!
8//! Note: This module is only here for completeness. In most cases, you should use
9//! [`get_peer_ids()`] or [`get_peer_pid_ids()`], which have slightly better cross-platform
10//! support.
11//!
12//! [`get_peer_ids()`]: ../fn.get_peer_ids.html
13//! [`get_peer_pid_ids()`]: ../fn.get_peer_pid_ids.html
14
15use std::io;
16use std::os::unix::net::UnixStream;
17use std::os::unix::prelude::*;
18
19/// Represents the credentials of a Unix socket's peer.
20#[derive(Clone, Debug, Eq, Hash, PartialEq)]
21#[repr(C)]
22pub struct Ucred {
23    /// The peer's PID.
24    #[cfg(any(target_os = "linux", target_os = "netbsd"))]
25    pub pid: libc::pid_t,
26    /// The peer's effective user ID.
27    pub uid: libc::uid_t,
28    /// The peer's effective group ID.
29    pub gid: libc::gid_t,
30    /// The peer's PID.
31    #[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/// Get the credentials of the given socket's peer.
71#[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}