Skip to content

Commit 8ca6e20

Browse files
committed
unistd: Add getpeereid(3)
Closes #1339.
1 parent a848ab5 commit 8ca6e20

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
77
### Added
88
- Added `mremap` (#[1306](https://github.com/nix-rust/nix/pull/1306))
99

10+
- Added `getpeereid` (#[1342](https://github.com/nix-rust/nix/pull/1342))
11+
### Changed
1012
### Fixed
1113
### Changed
1214

src/unistd.rs

+20
Original file line numberDiff line numberDiff line change
@@ -2785,3 +2785,23 @@ pub fn ttyname(fd: RawFd) -> Result<PathBuf> {
27852785
buf.truncate(nul);
27862786
Ok(OsString::from_vec(buf).into())
27872787
}
2788+
2789+
/// Get the effective user ID and group ID associated with a Unix domain socket.
2790+
///
2791+
/// See also [getpeereid(3)](https://www.freebsd.org/cgi/man.cgi?query=getpeereid)
2792+
#[cfg(any(
2793+
target_os = "macos",
2794+
target_os = "ios",
2795+
target_os = "freebsd",
2796+
target_os = "openbsd",
2797+
target_os = "netbsd",
2798+
target_os = "dragonfly",
2799+
))]
2800+
pub fn getpeereid(fd: RawFd) -> Result<(Uid, Gid)> {
2801+
let mut uid = 1;
2802+
let mut gid = 1;
2803+
2804+
let ret = unsafe { libc::getpeereid(fd, &mut uid, &mut gid) };
2805+
2806+
Errno::result(ret).map(|_| (Uid(uid), Gid(gid)))
2807+
}

test/test_unistd.rs

+39
Original file line numberDiff line numberDiff line change
@@ -1066,3 +1066,42 @@ fn test_ttyname_invalid_fd() {
10661066
fn test_ttyname_invalid_fd() {
10671067
assert_eq!(ttyname(-1), Err(Error::Sys(Errno::ENOTTY)));
10681068
}
1069+
1070+
#[test]
1071+
#[cfg(any(
1072+
target_os = "macos",
1073+
target_os = "ios",
1074+
target_os = "freebsd",
1075+
target_os = "openbsd",
1076+
target_os = "netbsd",
1077+
target_os = "dragonfly",
1078+
))]
1079+
fn test_getpeereid() {
1080+
use std::os::unix::net::UnixStream;
1081+
let (sock_a, sock_b) = UnixStream::pair().unwrap();
1082+
1083+
let (uid_a, gid_a) = getpeereid(sock_a.as_raw_fd()).unwrap();
1084+
let (uid_b, gid_b) = getpeereid(sock_b.as_raw_fd()).unwrap();
1085+
1086+
let uid = geteuid();
1087+
let gid = getegid();
1088+
1089+
assert_eq!(uid, uid_a);
1090+
assert_eq!(gid, gid_a);
1091+
assert_eq!(uid_a, uid_b);
1092+
assert_eq!(gid_a, gid_b);
1093+
}
1094+
1095+
#[test]
1096+
#[cfg(any(
1097+
target_os = "macos",
1098+
target_os = "ios",
1099+
target_os = "freebsd",
1100+
target_os = "openbsd",
1101+
target_os = "netbsd",
1102+
target_os = "dragonfly",
1103+
))]
1104+
fn test_getpeereid_invalid_fd() {
1105+
// getpeereid is not POSIX, so error codes are inconsistent between different Unices.
1106+
assert!(getpeereid(-1).is_err());
1107+
}

0 commit comments

Comments
 (0)