#![allow(unsafe_code)]
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
#[cfg(target_os = "macos")]
fn peer_pid(s: &UnixStream) -> Option<libc::pid_t> {
let mut pid: libc::pid_t = 0;
let mut len = std::mem::size_of::<libc::pid_t>() as libc::socklen_t;
let rc = unsafe {
libc::getsockopt(
s.as_raw_fd(),
libc::SOL_LOCAL,
libc::LOCAL_PEERPID,
&mut pid as *mut _ as *mut libc::c_void,
&mut len,
)
};
(rc == 0).then_some(pid)
}
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn sandbox_check(pid: libc::pid_t, operation: *const libc::c_char, kind: i32, ...) -> i32;
}
#[cfg(target_os = "macos")]
pub fn peer_in_sandbox(s: &UnixStream) -> bool {
let Some(pid) = peer_pid(s) else {
return false;
};
let mut path = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];
unsafe {
sandbox_check(pid, std::ptr::null(), 0) == 1
&& libc::proc_pidpath(pid, path.as_mut_ptr().cast(), path.len() as u32) > 0
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn peer_in_sandbox(_: &UnixStream) -> bool {
false
}