use std::io::{self, ErrorKind, Read, Write};
use std::os::fd::AsFd;
use rustix::event::{PollFd, PollFlags};
use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
use super::{Drain, Pump, Slot, CHUNK};
use crate::pipe::{PipeReader, PipeWriter};
use crate::wait;
impl<'a> Pump<'a, PipeWriter, PipeReader> {
pub(super) fn new(
stdin: Option<PipeWriter>,
input: &'a [u8],
stdout: Option<PipeReader>,
stderr: Option<PipeReader>,
) -> Self {
Pump::assemble(
stdin,
input,
stdout,
stderr,
|pipe| {
nonblocking(&pipe)?;
forbid_sigpipe(&pipe)?;
Ok(pipe)
},
|pipe| {
nonblocking(&pipe)?;
Ok(pipe)
},
)
}
pub(super) fn run(&mut self) -> io::Result<()> {
let mut chunk = vec![0u8; CHUNK];
loop {
let mut slots = Vec::with_capacity(3);
let mut fds = Vec::with_capacity(3);
if let Some(feed) = &self.feed {
slots.push(Slot::Stdin);
fds.push(PollFd::new(&feed.pipe, PollFlags::OUT));
}
if let Some(pipe) = &self.stdout.pipe {
slots.push(Slot::Stdout);
fds.push(PollFd::new(pipe, PollFlags::IN));
}
if let Some(pipe) = &self.stderr.pipe {
slots.push(Slot::Stderr);
fds.push(PollFd::new(pipe, PollFlags::IN));
}
if fds.is_empty() {
return Ok(());
}
wait::poll_ready(&mut fds)?;
let ready: Vec<Slot> = slots
.iter()
.zip(&fds)
.filter(|(_, fd)| !fd.revents().is_empty())
.map(|(slot, _)| *slot)
.collect();
drop(fds);
for slot in ready {
match slot {
Slot::Stdin => self.write_some(),
Slot::Stdout => self.stdout.read_some(&mut chunk),
Slot::Stderr => self.stderr.read_some(&mut chunk),
}
}
}
}
fn write_some(&mut self) {
let Some(feed) = &mut self.feed else { return };
match write_without_sigpipe(&mut feed.pipe, feed.rest) {
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
written => self.wrote(written),
}
}
}
impl Drain<PipeReader> {
fn read_some(&mut self, chunk: &mut [u8]) {
let Some(pipe) = &mut self.pipe else { return };
match pipe.read(chunk) {
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted) => {}
read => {
if !self.collected.took(read, chunk) {
self.pipe = None;
}
}
}
}
}
fn nonblocking(pipe: &impl AsFd) -> io::Result<()> {
let flags = fcntl_getfl(pipe)?;
fcntl_setfl(pipe, flags | OFlags::NONBLOCK)?;
Ok(())
}
#[cfg(target_os = "macos")]
fn forbid_sigpipe(pipe: &PipeWriter) -> io::Result<()> {
use std::os::fd::AsRawFd;
let status = unsafe { libc::fcntl(pipe.as_raw_fd(), libc::F_SETNOSIGPIPE, 1 as libc::c_int) };
if status == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(target_os = "macos")]
fn write_without_sigpipe(pipe: &mut PipeWriter, bytes: &[u8]) -> io::Result<usize> {
pipe.write(bytes)
}
#[cfg(not(target_os = "macos"))]
fn forbid_sigpipe(_: &PipeWriter) -> io::Result<()> {
Ok(())
}
#[cfg(not(target_os = "macos"))]
fn write_without_sigpipe(pipe: &mut PipeWriter, bytes: &[u8]) -> io::Result<usize> {
unsafe {
let mut set: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut set);
libc::sigaddset(&mut set, libc::SIGPIPE);
let mut old: libc::sigset_t = std::mem::zeroed();
let blocked = libc::pthread_sigmask(libc::SIG_BLOCK, &set, &mut old);
debug_assert_eq!(blocked, 0, "block SIGPIPE");
let was_pending = sigpipe_pending();
let written = pipe.write(bytes);
if matches!(&written, Err(e) if e.kind() == ErrorKind::BrokenPipe) && !was_pending && sigpipe_pending() {
let mut signo = 0;
let waited = libc::sigwait(&set, &mut signo);
debug_assert_eq!(waited, 0, "consume SIGPIPE");
}
let restored = libc::pthread_sigmask(libc::SIG_SETMASK, &old, std::ptr::null_mut());
debug_assert_eq!(restored, 0, "restore the signal mask");
written
}
}
#[cfg(not(target_os = "macos"))]
fn sigpipe_pending() -> bool {
unsafe {
let mut pending: libc::sigset_t = std::mem::zeroed();
let status = libc::sigpending(&mut pending);
debug_assert_eq!(status, 0, "read the pending signals");
libc::sigismember(&pending, libc::SIGPIPE) == 1
}
}