pub(crate) fn open_pty_pair() -> Option<(std::fs::File, std::fs::File)> {
use std::fs::File;
use std::os::fd::FromRawFd;
use std::sync::Mutex;
static PTSNAME: Mutex<()> = Mutex::new(());
let _guard = PTSNAME.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
let master = libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY);
if master < 0 {
return None;
}
if libc::grantpt(master) != 0 || libc::unlockpt(master) != 0 {
libc::close(master);
return None;
}
let name = libc::ptsname(master);
if name.is_null() {
libc::close(master);
return None;
}
let slave = libc::open(name, libc::O_RDWR | libc::O_NOCTTY);
if slave < 0 {
libc::close(master);
return None;
}
let mut probe: libc::termios = std::mem::zeroed();
if libc::tcgetattr(slave, &mut probe) != 0 {
libc::close(slave);
libc::close(master);
return None;
}
Some((File::from_raw_fd(master), File::from_raw_fd(slave)))
}
}
pub(crate) fn drain(f: &dyn std::os::fd::AsFd) -> Vec<u8> {
use std::os::fd::AsRawFd;
let fd = f.as_fd().as_raw_fd();
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
return Vec::new();
}
}
let mut out = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let n = unsafe { libc::read(fd, chunk.as_mut_ptr().cast(), chunk.len()) };
if n <= 0 {
return out;
}
out.extend_from_slice(&chunk[..n as usize]);
}
}
pub(crate) struct ScriptedFd<'a> {
fds: Vec<std::os::fd::BorrowedFd<'a>>,
borrows: std::cell::Cell<usize>,
}
impl<'a> ScriptedFd<'a> {
pub(crate) fn new(fds: &[&'a dyn std::os::fd::AsFd]) -> Self {
assert!(!fds.is_empty(), "a scripted descriptor needs a script");
Self {
fds: fds.iter().map(|f| f.as_fd()).collect(),
borrows: std::cell::Cell::new(0),
}
}
}
impl std::os::fd::AsFd for ScriptedFd<'_> {
fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
let n = self.borrows.get();
self.borrows.set(n + 1);
self.fds[n.min(self.fds.len() - 1)]
}
}
pub(crate) fn attrs(f: &dyn std::os::fd::AsFd) -> libc::termios {
use std::os::fd::AsRawFd;
let mut t: libc::termios = unsafe { std::mem::zeroed() };
assert_eq!(
unsafe { libc::tcgetattr(f.as_fd().as_raw_fd(), &mut t) },
0,
"tcgetattr failed: {}",
std::io::Error::last_os_error()
);
t
}
pub(crate) fn opost(f: &dyn std::os::fd::AsFd) -> bool {
attrs(f).c_oflag & libc::OPOST != 0
}
pub(crate) fn prime(f: &dyn std::os::fd::AsFd, opost: bool) {
use std::os::fd::AsRawFd;
let mut t = attrs(f);
if opost {
t.c_oflag |= libc::OPOST;
} else {
t.c_oflag &= !libc::OPOST;
}
t.c_cc[libc::VMIN] = 4;
t.c_cc[libc::VTIME] = 7;
assert_eq!(
unsafe { libc::tcsetattr(f.as_fd().as_raw_fd(), libc::TCSANOW, &t) },
0,
"tcsetattr failed: {}",
std::io::Error::last_os_error()
);
}