use std::io;
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use super::*;
#[cfg(target_os = "linux")]
pub(super) const REPORT_PLACED: i32 = -1;
#[cfg(target_os = "linux")]
const MESSAGE_LEN: usize = 16;
#[cfg(target_os = "linux")]
const HANDLE_NONE: u64 = 0;
#[cfg(target_os = "linux")]
const HANDLE_PIDFD: u64 = 1;
#[cfg(target_os = "linux")]
const HANDLE_PROC_DIR: u64 = 2;
#[cfg(target_os = "linux")]
pub(super) const TAG_INTENT: i32 = 1;
#[cfg(target_os = "linux")]
const TAG_REPORT: i32 = 2;
#[cfg(target_os = "linux")]
const PROCEED: u8 = b'P';
#[cfg(target_os = "linux")]
pub(crate) struct ReportChannel {
pub(super) read: OwnedFd,
pub(super) write: Option<OwnedFd>,
received: Received,
}
#[cfg(target_os = "linux")]
#[derive(Debug, Default)]
pub(crate) struct Received {
pub(crate) report: Option<PlacementReport>,
pub(crate) pid: Option<u32>,
pub(crate) pidfd: Option<OwnedFd>,
pub(crate) proc_dir: Option<OwnedFd>,
}
#[cfg(target_os = "linux")]
impl Received {
pub(crate) fn placement(&self) -> PlacementReport {
self.report.unwrap_or(PlacementReport::NotReported)
}
}
#[cfg(target_os = "linux")]
impl ReportChannel {
pub(crate) fn new() -> io::Result<ReportChannel> {
use rustix::net::{socketpair, AddressFamily, SocketFlags, SocketType};
#[cfg(test)]
if fault::take_force_report_channel_failure() {
return Err(io::Error::from_raw_os_error(libc::EMFILE));
}
let (read, write) = socketpair(AddressFamily::UNIX, SocketType::SEQPACKET, SocketFlags::CLOEXEC, None)?;
Ok(ReportChannel {
read: crate::above_stdio::above_stdio(read)?,
write: Some(crate::above_stdio::above_stdio(write)?),
received: Received::default(),
})
}
#[cfg(test)]
pub(crate) fn dup_child_end_for_test(&self) -> std::os::fd::OwnedFd {
self.write
.as_ref()
.expect("the child's end is open until the wait")
.try_clone()
.expect("dup the child's end")
}
pub(crate) fn slot(&self) -> ReportSlot {
ReportSlot {
fd: self
.write
.as_ref()
.expect("the child's end is open until the wait")
.as_raw_fd(),
parent_fd: self.read.as_raw_fd(),
}
}
pub(crate) fn wait(&mut self, pidfd: std::os::fd::BorrowedFd<'_>) -> PlacementReport {
use rustix::event::{poll, PollFd, PollFlags};
self.write = None;
#[cfg(test)]
fault::notify_wait_entry(std::os::fd::AsRawFd::as_raw_fd(&pidfd));
loop {
let closed = self.drain();
if let Some(report) = self.received.report {
return report;
}
if closed {
return PlacementReport::NotReported;
}
let mut fds = [
PollFd::new(&self.read, PollFlags::IN),
PollFd::new(&pidfd, PollFlags::IN),
];
#[cfg(test)]
fault::notify_wait_polling();
loop {
match poll(&mut fds, None) {
Ok(_) => break,
Err(rustix::io::Errno::INTR | rustix::io::Errno::NOMEM) => continue,
Err(e) => panic!("poll on the placement report channel failed: {e}"),
}
}
if !fds[1].revents().is_empty() {
self.drain();
return self.received.placement();
}
}
}
fn drain(&mut self) -> bool {
use std::mem::MaybeUninit;
use rustix::net::{recvmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
loop {
let mut message = [0u8; MESSAGE_LEN];
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut control = RecvAncillaryBuffer::new(&mut space);
let received = recvmsg(
&self.read,
&mut [std::io::IoSliceMut::new(&mut message)],
&mut control,
RecvFlags::DONTWAIT | RecvFlags::CMSG_CLOEXEC,
);
let bytes = match received {
Ok(received) => received.bytes,
Err(rustix::io::Errno::INTR | rustix::io::Errno::NOMEM) => continue,
Err(rustix::io::Errno::AGAIN) => return false,
Err(e) => panic!("recvmsg on the placement report channel failed: {e}"),
};
if bytes == 0 {
return true;
}
debug_assert_eq!(bytes, message.len(), "a message is two i32s and a u64");
let tag = i32::from_ne_bytes(message[..4].try_into().expect("four bytes"));
let value = i32::from_ne_bytes(message[4..8].try_into().expect("four bytes"));
let handle = u64::from_ne_bytes(message[8..].try_into().expect("eight bytes"));
let mut pidfd = None;
for ancillary in control.drain() {
if let RecvAncillaryMessage::ScmRights(fds) = ancillary {
for fd in fds {
pidfd.get_or_insert(fd);
}
}
}
match tag {
TAG_INTENT => {
self.received.pid = u32::try_from(value).ok();
match handle {
HANDLE_PIDFD => self.received.pidfd = pidfd,
HANDLE_PROC_DIR => self.received.proc_dir = pidfd,
_ => {}
}
}
TAG_REPORT => {
self.received.report.get_or_insert(match value {
REPORT_PLACED => PlacementReport::Placed,
errno => {
debug_assert!(errno > 0, "a failed write reports its positive errno, got {errno}");
PlacementReport::WriteFailed(errno)
}
});
}
tag => debug_assert!(false, "unknown placement message tag {tag}"),
}
}
}
pub(super) fn proceed(mut self) {
self.drain();
_ = rustix::net::send(
&self.read,
&[PROCEED],
rustix::net::SendFlags::NOSIGNAL | rustix::net::SendFlags::DONTWAIT,
);
}
pub(super) fn shut(mut self) -> Received {
self.write = None;
rustix::net::shutdown(&self.read, rustix::net::Shutdown::Read)
.expect("shut the placement report channel for reading");
self.drain();
#[cfg(test)]
fault::run_after_shut_read();
self.received
}
}
#[cfg(all(target_os = "linux", test))]
impl ReportChannel {
pub(crate) fn report_for_test(mut self) -> PlacementReport {
self.write = None;
self.drain();
self.received.placement()
}
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Delivery {
Queued,
Decided,
Abandoned,
}
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
pub(crate) struct ReportSlot {
pub(super) fd: RawFd,
pub(super) parent_fd: RawFd,
}
#[cfg(target_os = "linux")]
impl ReportSlot {
pub(super) unsafe fn send_intent(self) -> io::Result<Delivery> {
let pid = rustix::process::getpid();
#[cfg(test)]
let (pidfd_denied, proc_denied) = (
fault::take_force_child_pidfd_failure(),
fault::take_force_child_proc_dir_failure(),
);
#[cfg(not(test))]
let (pidfd_denied, proc_denied) = (false, false);
let pidfd = if pidfd_denied {
-1
} else {
rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty())
.map_or(-1, std::os::fd::IntoRawFd::into_raw_fd)
};
let (handle, kind) = if pidfd >= 0 {
(pidfd, HANDLE_PIDFD)
} else {
let dir = if proc_denied {
-1
} else {
unsafe {
libc::open(
c"/proc/self".as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
)
}
};
(dir, if dir >= 0 { HANDLE_PROC_DIR } else { HANDLE_NONE })
};
let sent = unsafe { self.send(TAG_INTENT, pid.as_raw_nonzero().get(), kind, handle) };
if handle >= 0 {
unsafe { libc::close(handle) };
}
sent
}
pub(crate) unsafe fn close_parents_end(self) {
unsafe { libc::close(self.parent_fd) };
}
pub(super) unsafe fn send_report(self, value: i32) -> io::Result<Delivery> {
unsafe { self.send(TAG_REPORT, value, 0, -1) }
}
pub(super) unsafe fn send(self, tag: i32, value: i32, handle: u64, pidfd: RawFd) -> io::Result<Delivery> {
#[repr(C, align(8))]
struct Control([u8; 64]);
let mut message = [0u8; MESSAGE_LEN];
message[..4].copy_from_slice(&tag.to_ne_bytes());
message[4..8].copy_from_slice(&value.to_ne_bytes());
message[8..].copy_from_slice(&handle.to_ne_bytes());
let mut iov = libc::iovec {
iov_base: message.as_mut_ptr().cast(),
iov_len: message.len(),
};
let mut control = Control([0; 64]);
let mut header: libc::msghdr = unsafe { std::mem::zeroed() };
header.msg_iov = &mut iov;
header.msg_iovlen = 1;
if pidfd >= 0 {
let fd_len = std::mem::size_of::<RawFd>() as libc::c_uint;
header.msg_control = control.0.as_mut_ptr().cast();
let space = unsafe { libc::CMSG_SPACE(fd_len) } as usize;
debug_assert!(
space <= control.0.len(),
"one descriptor's control message fits `control`, needs {space}"
);
header.msg_controllen = space as _;
unsafe {
let cmsg = libc::CMSG_FIRSTHDR(&header);
debug_assert!(!cmsg.is_null(), "`msg_controllen` leaves room for one header");
(*cmsg).cmsg_level = libc::SOL_SOCKET;
(*cmsg).cmsg_type = libc::SCM_RIGHTS;
(*cmsg).cmsg_len = libc::CMSG_LEN(fd_len) as _;
std::ptr::write_unaligned(libc::CMSG_DATA(cmsg).cast::<RawFd>(), pidfd);
}
}
loop {
let sent = unsafe { libc::sendmsg(self.fd, &header, libc::MSG_NOSIGNAL) };
if sent == message.len() as isize {
return Ok(Delivery::Queued);
}
let errno = unsafe { *libc::__errno_location() };
return match (sent, errno) {
(-1, libc::EINTR) => continue,
(-1, libc::EPIPE | libc::ECONNRESET) => Ok(if unsafe { self.proceed_queued() } {
Delivery::Decided
} else {
Delivery::Abandoned
}),
(-1, errno) => Err(io::Error::from_raw_os_error(errno)),
_ => Err(io::Error::from_raw_os_error(libc::EMSGSIZE)),
};
}
}
unsafe fn proceed_queued(self) -> bool {
let mut byte = 0u8;
loop {
let got = unsafe { libc::recv(self.fd, (&raw mut byte).cast(), 1, libc::MSG_DONTWAIT) };
if got == -1 && unsafe { *libc::__errno_location() } == libc::EINTR {
continue;
}
return got == 1 && byte == PROCEED;
}
}
}
#[cfg(all(target_os = "linux", test))]
impl ReportSlot {
pub(crate) unsafe fn report_placed_for_test(self) {
let sent = unsafe { self.send_report(REPORT_PLACED) }.expect("send the report");
assert_eq!(sent, Delivery::Queued, "the parent must still be listening");
}
}
#[cfg(test)]
#[path = "channel_tests.rs"]
mod channel_tests;