use std::fs::File;
use std::os::fd::{AsFd, OwnedFd};
use std::os::unix::fs::FileExt;
use rustix::event::{PollFd, PollFlags, poll};
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
use rustix::io::{Errno, FdFlags, fcntl_setfd};
use super::{Channel, frame_file};
const MARKER: &[u8] = b"\0";
pub(super) fn cloexec(fd: &impl AsFd) -> Result<(), Errno> {
fcntl_setfd(fd, FdFlags::CLOEXEC)
}
pub(super) fn nonblocking(fd: &impl AsFd) -> Result<(), Errno> {
let flags = fcntl_getfl(fd)?;
if !flags.contains(OFlags::NONBLOCK) {
fcntl_setfl(fd, flags | OFlags::NONBLOCK)?;
}
Ok(())
}
pub(super) fn wait_to_read(fd: &OwnedFd) -> Result<(), Errno> {
wait(fd, PollFlags::IN)
}
pub(super) fn wait_to_write(fd: &OwnedFd) -> Result<(), Errno> {
wait(fd, PollFlags::OUT)
}
fn wait(fd: &OwnedFd, events: PollFlags) -> Result<(), Errno> {
let mut fds = [PollFd::new(fd, events)];
loop {
match poll(&mut fds, None) {
Err(Errno::INTR) => continue,
result => return result.map(|_| ()),
}
}
}
pub(super) fn encode(socket: &OwnedFd, bytes: &[u8]) -> Result<(File, &'static [u8]), Errno> {
nonblocking(socket)?;
rustix::net::sockopt::set_socket_nosigpipe(socket, true)?;
let file = frame_file(bytes).map_err(|e| Errno::from_io_error(&e).unwrap_or(Errno::IO))?;
Ok((file, MARKER))
}
pub(super) fn decode(bytes: &[u8], fds: Vec<OwnedFd>) -> Result<(Vec<u8>, Vec<OwnedFd>), String> {
if bytes != MARKER {
return Err("a frame came without its marker".into());
}
let mut fds = fds.into_iter();
let file = File::from(fds.next().ok_or("a frame came without its file")?);
for fd in fds.as_slice() {
cloexec(fd).map_err(|e| format!("a frame descriptor: {e}"))?;
}
cloexec(&file).map_err(|e| format!("a frame descriptor: {e}"))?;
let meta = file.metadata().map_err(|e| format!("a frame file: {e}"))?;
if !meta.is_file() {
return Err("a frame came without a regular file".into());
}
let len = usize::try_from(meta.len())
.ok()
.filter(|n| *n <= Channel::FRAME_MAX)
.ok_or_else(|| format!("a frame over {} bytes came inline", Channel::FRAME_MAX))?;
let mut buffer = vec![0; len];
file.read_exact_at(&mut buffer, 0).map_err(|e| format!("a frame file: {e}"))?;
Ok((buffer, fds.collect()))
}