use std::io;
use std::mem;
use std::os::fd::RawFd;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
static DIAGNOSTICS_MUST_NOT_WAIT: AtomicBool = AtomicBool::new(false);
pub fn forbid_waiting_diagnostics() {
DIAGNOSTICS_MUST_NOT_WAIT.store(true, Ordering::Relaxed);
}
pub fn diagnostics_must_not_wait() -> bool {
DIAGNOSTICS_MUST_NOT_WAIT.load(Ordering::Relaxed)
}
pub fn write_without_waiting(fd: RawFd, bytes: &[u8]) {
let bytes = &bytes[..bytes.len().min(libc::PIPE_BUF)];
suppressing_diagnostic_signals(|| {
let Ok(file_type) = file_type(fd) else {
return 0;
};
let written = match file_type {
libc::S_IFREG => {
let iov = libc::iovec {
iov_base: bytes.as_ptr() as *mut libc::c_void,
iov_len: bytes.len(),
};
unsafe { libc::pwritev2(fd, &iov, 1, -1, libc::RWF_NOWAIT) }
}
libc::S_IFSOCK => unsafe {
libc::send(
fd,
bytes.as_ptr().cast(),
bytes.len(),
libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
)
},
libc::S_IFIFO => return write_through_new_description(fd, bytes),
libc::S_IFCHR if unsafe { libc::isatty(fd) } == 1 => {
return write_through_new_description(fd, bytes);
}
_ => return 0,
};
if written < 0 { last_errno() } else { 0 }
});
}
pub fn write_without_waiting_for_a_reader(fd: RawFd, bytes: &[u8]) -> io::Result<usize> {
let mut result = Err(io::Error::other(
"the signal mask for a diagnostic write could not be set",
));
suppressing_diagnostic_signals(|| {
let file_type = match file_type(fd) {
Ok(file_type) => file_type,
Err(errno) => {
result = Err(io::Error::from_raw_os_error(errno));
return 0;
}
};
let written = match file_type {
libc::S_IFSOCK => unsafe {
libc::send(
fd,
bytes.as_ptr().cast(),
bytes.len(),
libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL,
)
},
libc::S_IFIFO | libc::S_IFCHR => {
let path = proc_self_fd_path(fd);
let reopened = unsafe {
libc::open(
path.as_ptr().cast(),
libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC | libc::O_NOCTTY,
)
};
if reopened < 0 {
let errno = match last_errno() {
libc::ENXIO => libc::EPIPE,
errno => errno,
};
result = Err(io::Error::from_raw_os_error(errno));
return 0;
}
let written = unsafe { libc::write(reopened, bytes.as_ptr().cast(), bytes.len()) };
let errno = last_errno();
unsafe { libc::close(reopened) };
if written < 0 {
result = Err(io::Error::from_raw_os_error(errno));
return errno;
}
written
}
_ => unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) },
};
if written < 0 {
let error = io::Error::last_os_error();
let errno = error.raw_os_error().unwrap_or(0);
result = Err(error);
errno
} else {
result = Ok(written as usize);
0
}
});
result
}
fn file_type(fd: RawFd) -> Result<libc::mode_t, i32> {
let mut stat: libc::statx = unsafe { mem::zeroed() };
let inspected = unsafe {
libc::statx(
fd,
c"".as_ptr(),
libc::AT_EMPTY_PATH | libc::AT_STATX_DONT_SYNC,
libc::STATX_TYPE,
&mut stat,
)
} == 0;
let statx_errno = if inspected { libc::EIO } else { last_errno() };
let file_type = libc::mode_t::from(stat.stx_mode) & libc::S_IFMT;
if inspected && stat.stx_mask & libc::STATX_TYPE != 0 && file_type != 0 {
return Ok(file_type);
}
if unsafe { libc::fcntl(fd, libc::F_GETPIPE_SZ) } > 0 {
return Ok(libc::S_IFIFO);
}
let mut socket_type: libc::c_int = 0;
let mut length = mem::size_of::<libc::c_int>() as libc::socklen_t;
let answered = unsafe {
libc::getsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_TYPE,
(&raw mut socket_type).cast(),
&mut length,
)
} == 0;
if answered && socket_type != 0 {
return Ok(libc::S_IFSOCK);
}
Err(statx_errno)
}
pub fn last_errno() -> i32 {
io::Error::last_os_error().raw_os_error().unwrap_or(0)
}
fn write_through_new_description(fd: RawFd, bytes: &[u8]) -> i32 {
let path = proc_self_fd_path(fd);
let reopened = unsafe {
libc::open(
path.as_ptr().cast(),
libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC | libc::O_NOCTTY,
)
};
if reopened < 0 {
return 0;
}
let written = unsafe { libc::write(reopened, bytes.as_ptr().cast(), bytes.len()) };
let errno = if written < 0 { last_errno() } else { 0 };
unsafe { libc::close(reopened) };
errno
}
pub fn proc_self_fd_path(fd: RawFd) -> [u8; 32] {
const PREFIX: &[u8] = b"/proc/self/fd/";
let mut path = [0u8; 32];
path[..PREFIX.len()].copy_from_slice(PREFIX);
let mut digits = [0u8; 10];
let mut count = 0;
let mut rest = fd.unsigned_abs();
loop {
digits[count] = b'0' + (rest % 10) as u8;
count += 1;
rest /= 10;
if rest == 0 {
break;
}
}
for (slot, digit) in path[PREFIX.len()..]
.iter_mut()
.zip(digits[..count].iter().rev())
{
*slot = *digit;
}
path
}
pub fn suppressing_diagnostic_signals(write: impl FnOnce() -> i32) {
unsafe {
let mut blocked: libc::sigset_t = mem::zeroed();
libc::sigemptyset(&mut blocked);
for signal in [libc::SIGPIPE, libc::SIGXFSZ, libc::SIGTTOU] {
libc::sigaddset(&mut blocked, signal);
}
let mut original: libc::sigset_t = mem::zeroed();
if libc::pthread_sigmask(libc::SIG_BLOCK, &blocked, &mut original) != 0 {
return;
}
let mut pending_before: libc::sigset_t = mem::zeroed();
libc::sigemptyset(&mut pending_before);
libc::sigpending(&mut pending_before);
let errno = write();
let generated = match errno {
libc::EPIPE => Some(libc::SIGPIPE),
libc::EFBIG => Some(libc::SIGXFSZ),
_ => None,
};
if let Some(signal) = generated
&& libc::sigismember(&pending_before, signal) == 0
{
let mut consume: libc::sigset_t = mem::zeroed();
libc::sigemptyset(&mut consume);
libc::sigaddset(&mut consume, signal);
let now = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
while libc::sigtimedwait(&consume, std::ptr::null_mut(), &now) < 0
&& last_errno() == libc::EINTR
{}
}
libc::pthread_sigmask(libc::SIG_SETMASK, &original, std::ptr::null_mut());
}
}