use anyhow::Error;
use downcast_rs::{impl_downcast, Downcast};
#[cfg(feature = "serde_support")]
use serde_derive::*;
use std::io::Result as IoResult;
#[cfg(windows)]
use std::os::windows::prelude::{AsRawHandle, RawHandle};
#[derive(Debug)]
pub struct ContainedPtyChild {
#[cfg(unix)]
pub(crate) child: std::process::Child,
#[cfg(windows)]
pub(crate) child: win::WinChild,
}
impl ContainedPtyChild {
#[cfg(unix)]
pub(crate) fn new(child: std::process::Child) -> Self {
Self { child }
}
#[cfg(windows)]
pub(crate) fn new(child: win::WinChild) -> Self {
Self { child }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContainedPtySpawnErrorStage {
BeforeSpawn,
Receipt,
Adoption,
Resume,
}
enum FailedChildRecoveryCommand {
Adopt(ContainedPtyChild),
Attempt {
timeout: std::time::Duration,
#[cfg(test)]
fault: FailedChildRecoveryFault,
response: std::sync::mpsc::SyncSender<IoResult<bool>>,
},
}
#[cfg(test)]
#[derive(Clone, Copy)]
enum FailedChildRecoveryFault {
None,
#[cfg(unix)]
KillError,
#[cfg(unix)]
Deadline,
}
struct FailedChildRecovery {
sender: std::sync::mpsc::Sender<FailedChildRecoveryCommand>,
pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl FailedChildRecovery {
fn prepare() -> IoResult<Self> {
let (sender, receiver) = std::sync::mpsc::channel();
let pending = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let worker_pending = std::sync::Arc::clone(&pending);
std::thread::Builder::new()
.name("sysprims-pty-recovery".to_string())
.spawn(move || failed_child_recovery_worker(receiver, worker_pending))?;
Ok(Self { sender, pending })
}
fn attach(&self, child: ContainedPtyChild) {
self.pending
.store(true, std::sync::atomic::Ordering::Release);
if let Err(error) = self.sender.send(FailedChildRecoveryCommand::Adopt(child)) {
let child = match error.0 {
FailedChildRecoveryCommand::Adopt(child) => child,
FailedChildRecoveryCommand::Attempt { .. } => unreachable!(),
};
bounded_local_recovery_or_abort(child);
}
}
fn attempt(&self, timeout: std::time::Duration) -> IoResult<bool> {
self.attempt_inner(
timeout,
#[cfg(test)]
FailedChildRecoveryFault::None,
)
}
fn attempt_inner(
&self,
timeout: std::time::Duration,
#[cfg(test)] fault: FailedChildRecoveryFault,
) -> IoResult<bool> {
if !self.pending.load(std::sync::atomic::Ordering::Acquire) {
return Ok(true);
}
let timeout = timeout.min(std::time::Duration::from_secs(2));
let (response, result) = std::sync::mpsc::sync_channel(1);
self.sender
.send(FailedChildRecoveryCommand::Attempt {
timeout,
#[cfg(test)]
fault,
response,
})
.map_err(|_| {
std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"exact-child recovery owner stopped",
)
})?;
result
.recv_timeout(timeout + std::time::Duration::from_millis(250))
.map_err(|error| {
std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!("exact-child recovery response unavailable: {error}"),
)
})?
}
#[cfg(all(test, unix))]
fn attempt_with_fault(
&self,
timeout: std::time::Duration,
fault: FailedChildRecoveryFault,
) -> IoResult<bool> {
self.attempt_inner(timeout, fault)
}
fn is_pending(&self) -> bool {
self.pending.load(std::sync::atomic::Ordering::Acquire)
}
}
fn failed_child_recovery_worker(
receiver: std::sync::mpsc::Receiver<FailedChildRecoveryCommand>,
pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
) {
let mut child = None;
while let Ok(command) = receiver.recv() {
match command {
FailedChildRecoveryCommand::Adopt(adopted) => {
debug_assert!(child.is_none());
child = Some(adopted);
}
FailedChildRecoveryCommand::Attempt {
timeout,
#[cfg(test)]
fault,
response,
} => {
let result = attempt_failed_child_recovery(
&mut child,
timeout,
#[cfg(test)]
fault,
);
pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
let _ = response.send(result);
}
}
}
while child.is_some() {
let _ = attempt_failed_child_recovery(
&mut child,
std::time::Duration::from_secs(2),
#[cfg(test)]
FailedChildRecoveryFault::None,
);
pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
if child.is_some() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}
fn attempt_failed_child_recovery(
child: &mut Option<ContainedPtyChild>,
timeout: std::time::Duration,
#[cfg(test)] fault: FailedChildRecoveryFault,
) -> IoResult<bool> {
let owned_child = match child.as_mut() {
Some(child) => child,
None => return Ok(true),
};
if Child::try_wait(owned_child)?.is_some() {
child.take();
return Ok(true);
}
#[cfg(test)]
match fault {
#[cfg(unix)]
FailedChildRecoveryFault::KillError => {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"injected exact-child kill failure",
));
}
#[cfg(unix)]
FailedChildRecoveryFault::Deadline => {
std::thread::sleep(timeout.min(std::time::Duration::from_millis(10)));
return Ok(false);
}
FailedChildRecoveryFault::None => {}
}
ChildKiller::kill(owned_child)?;
let timeout = timeout.min(std::time::Duration::from_secs(2));
let deadline = std::time::Instant::now() + timeout;
loop {
match Child::try_wait(owned_child)? {
Some(_) => {
child.take();
return Ok(true);
}
None if std::time::Instant::now() < deadline => {
std::thread::sleep(std::time::Duration::from_millis(10));
}
None => return Ok(false),
}
}
}
fn bounded_local_recovery_or_abort(mut child: ContainedPtyChild) -> ! {
let _ = ChildKiller::kill(&mut child);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
loop {
match Child::try_wait(&mut child) {
Ok(Some(_)) => {
std::process::abort();
}
Ok(None) if std::time::Instant::now() < deadline => {
std::thread::sleep(std::time::Duration::from_millis(10));
}
Ok(None) | Err(_) => std::process::abort(),
}
}
}
pub struct ContainedPtySpawnError {
stage: ContainedPtySpawnErrorStage,
source: Error,
recovery: Option<FailedChildRecovery>,
}
impl ContainedPtySpawnError {
pub(crate) fn before_spawn(source: Error) -> Self {
Self {
stage: ContainedPtySpawnErrorStage::BeforeSpawn,
source,
recovery: None,
}
}
pub(crate) fn after_spawn(
stage: ContainedPtySpawnErrorStage,
source: Error,
child: ContainedPtyChild,
recovery: FailedChildRecovery,
) -> Self {
debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
recovery.attach(child);
let mut error = Self {
stage,
source,
recovery: Some(recovery),
};
let _ = error.recover(std::time::Duration::from_secs(2));
error
}
#[cfg(all(test, unix))]
pub(crate) fn after_spawn_pending_for_test(
stage: ContainedPtySpawnErrorStage,
source: Error,
child: ContainedPtyChild,
recovery: FailedChildRecovery,
) -> Self {
debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
recovery.attach(child);
Self {
stage,
source,
recovery: Some(recovery),
}
}
pub fn stage(&self) -> ContainedPtySpawnErrorStage {
self.stage
}
pub fn recovery_pending(&self) -> bool {
self.recovery
.as_ref()
.is_some_and(FailedChildRecovery::is_pending)
}
pub fn recover(&mut self, timeout: std::time::Duration) -> IoResult<bool> {
match self.recovery.as_mut() {
Some(recovery) => recovery.attempt(timeout),
None => Ok(true),
}
}
}
impl std::fmt::Debug for ContainedPtySpawnError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ContainedPtySpawnError")
.field("stage", &self.stage)
.field("source", &self.source)
.field("recovery_pending", &self.recovery_pending())
.finish()
}
}
impl std::fmt::Display for ContainedPtySpawnError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.fmt(formatter)
}
}
impl std::error::Error for ContainedPtySpawnError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.source.as_ref())
}
}
pub type ContainedPtyGuard = sysprims_timeout::ContainmentGuard<ContainedPtyChild>;
pub mod cmdbuilder;
pub use cmdbuilder::CommandBuilder;
#[cfg(unix)]
pub mod unix;
#[cfg(windows)]
pub mod win;
pub mod serial;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct PtySize {
pub rows: u16,
pub cols: u16,
pub pixel_width: u16,
pub pixel_height: u16,
}
impl Default for PtySize {
fn default() -> Self {
PtySize {
rows: 24,
cols: 80,
pixel_width: 0,
pixel_height: 0,
}
}
}
pub trait MasterPty: Downcast + Send {
fn resize(&self, size: PtySize) -> Result<(), Error>;
fn get_size(&self) -> Result<PtySize, Error>;
fn try_clone_reader(&self) -> Result<Box<dyn std::io::Read + Send>, Error>;
fn take_writer(&self) -> Result<Box<dyn std::io::Write + Send>, Error>;
#[cfg(unix)]
fn process_group_leader(&self) -> Option<libc::pid_t>;
#[cfg(unix)]
fn as_raw_fd(&self) -> Option<unix::RawFd>;
#[cfg(unix)]
fn tty_name(&self) -> Option<std::path::PathBuf>;
#[cfg(unix)]
fn get_termios(&self) -> Option<nix::sys::termios::Termios> {
None
}
}
impl_downcast!(MasterPty);
pub trait Child: std::fmt::Debug + ChildKiller + Downcast + Send {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>>;
fn wait(&mut self) -> IoResult<ExitStatus>;
fn process_id(&self) -> Option<u32>;
#[cfg(windows)]
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle>;
}
impl_downcast!(Child);
pub trait ChildKiller: std::fmt::Debug + Downcast + Send {
fn kill(&mut self) -> IoResult<()>;
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync>;
}
impl_downcast!(ChildKiller);
pub trait SlavePty {
fn spawn_command(&self, cmd: CommandBuilder) -> Result<Box<dyn Child + Send + Sync>, Error>;
fn spawn_contained_command(
&self,
cmd: CommandBuilder,
) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
let _ = cmd;
Err(ContainedPtySpawnError::before_spawn(anyhow::anyhow!(
"spawn-time PTY containment is unavailable for this PTY implementation"
)))
}
}
#[derive(Debug, Clone)]
pub struct ExitStatus {
code: u32,
signal: Option<String>,
}
impl ExitStatus {
pub fn with_exit_code(code: u32) -> Self {
Self { code, signal: None }
}
pub fn with_signal(signal: &str) -> Self {
Self {
code: 1,
signal: Some(signal.to_string()),
}
}
pub fn success(&self) -> bool {
match self.signal {
None => self.code == 0,
Some(_) => false,
}
}
pub fn exit_code(&self) -> u32 {
self.code
}
pub fn signal(&self) -> Option<&str> {
self.signal.as_deref()
}
}
impl From<std::process::ExitStatus> for ExitStatus {
fn from(status: std::process::ExitStatus) -> ExitStatus {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() {
let signame = unsafe { libc::strsignal(signal) };
let signal = if signame.is_null() {
format!("Signal {signal}")
} else {
let signame = unsafe { std::ffi::CStr::from_ptr(signame) };
signame.to_string_lossy().to_string()
};
return ExitStatus {
code: status.code().map(|c| c as u32).unwrap_or(1),
signal: Some(signal),
};
}
}
let code =
status
.code()
.map(|c| c as u32)
.unwrap_or_else(|| if status.success() { 0 } else { 1 });
ExitStatus { code, signal: None }
}
}
impl std::fmt::Display for ExitStatus {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.success() {
write!(fmt, "Success")
} else {
match &self.signal {
Some(sig) => write!(fmt, "Terminated by {sig}"),
None => write!(fmt, "Exited with code {}", self.code),
}
}
}
}
pub struct PtyPair {
pub slave: Box<dyn SlavePty + Send>,
pub master: Box<dyn MasterPty + Send>,
}
pub trait PtySystem: Downcast {
fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair>;
}
impl_downcast!(PtySystem);
impl Child for std::process::Child {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
std::process::Child::try_wait(self).map(|status| status.map(Into::into))
}
fn wait(&mut self) -> IoResult<ExitStatus> {
std::process::Child::wait(self).map(Into::into)
}
fn process_id(&self) -> Option<u32> {
Some(self.id())
}
#[cfg(windows)]
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
Some(std::os::windows::io::AsRawHandle::as_raw_handle(self))
}
}
impl Child for ContainedPtyChild {
fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
#[cfg(unix)]
return std::process::Child::try_wait(&mut self.child).map(|status| status.map(Into::into));
#[cfg(windows)]
return Child::try_wait(&mut self.child);
}
fn wait(&mut self) -> IoResult<ExitStatus> {
#[cfg(unix)]
return std::process::Child::wait(&mut self.child).map(Into::into);
#[cfg(windows)]
return Child::wait(&mut self.child);
}
fn process_id(&self) -> Option<u32> {
#[cfg(unix)]
return Some(self.child.id());
#[cfg(windows)]
return Child::process_id(&self.child);
}
#[cfg(windows)]
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
Child::as_raw_handle(&self.child)
}
}
impl sysprims_timeout::ContainmentChild for ContainedPtyChild {
fn process_id(&self) -> Option<u32> {
Child::process_id(self)
}
fn try_wait(&mut self) -> IoResult<bool> {
Child::try_wait(self).map(|status| status.is_some())
}
#[cfg(windows)]
fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
Child::as_raw_handle(self)
}
}
#[derive(Debug)]
struct ProcessSignaller {
pid: Option<u32>,
#[cfg(windows)]
handle: Option<filedescriptor::OwnedHandle>,
}
#[cfg(windows)]
impl ChildKiller for ProcessSignaller {
fn kill(&mut self) -> IoResult<()> {
if let Some(handle) = &self.handle {
unsafe {
if winapi::um::processthreadsapi::TerminateProcess(handle.as_raw_handle() as _, 127)
== 0
{
return Err(std::io::Error::last_os_error());
}
}
}
Ok(())
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
Box::new(Self {
pid: self.pid,
handle: self.handle.as_ref().and_then(|h| h.try_clone().ok()),
})
}
}
#[cfg(unix)]
impl ChildKiller for ProcessSignaller {
fn kill(&mut self) -> IoResult<()> {
if let Some(pid) = self.pid {
let result = unsafe { libc::kill(pid as i32, libc::SIGHUP) };
if result != 0 {
return Err(std::io::Error::last_os_error());
}
}
Ok(())
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
Box::new(Self { pid: self.pid })
}
}
impl ChildKiller for std::process::Child {
fn kill(&mut self) -> IoResult<()> {
#[cfg(unix)]
{
let result = unsafe { libc::kill(self.id() as i32, libc::SIGHUP) };
if result != 0 {
return Err(std::io::Error::last_os_error());
}
for attempt in 0..5 {
if attempt > 0 {
std::thread::sleep(std::time::Duration::from_millis(50));
}
if let Ok(Some(_)) = self.try_wait() {
return Ok(());
}
}
}
std::process::Child::kill(self)
}
#[cfg(windows)]
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
struct RawDup(RawHandle);
impl AsRawHandle for RawDup {
fn as_raw_handle(&self) -> RawHandle {
self.0
}
}
Box::new(ProcessSignaller {
pid: self.process_id(),
handle: Child::as_raw_handle(self)
.as_ref()
.and_then(|h| filedescriptor::OwnedHandle::dup(&RawDup(*h)).ok()),
})
}
#[cfg(unix)]
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
Box::new(ProcessSignaller {
pid: self.process_id(),
})
}
}
impl ChildKiller for ContainedPtyChild {
fn kill(&mut self) -> IoResult<()> {
ChildKiller::kill(&mut self.child)
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
ChildKiller::clone_killer(&self.child)
}
}
pub fn native_pty_system() -> Box<dyn PtySystem + Send> {
Box::new(NativePtySystem::default())
}
#[cfg(unix)]
pub type NativePtySystem = unix::UnixPtySystem;
#[cfg(windows)]
pub type NativePtySystem = win::conpty::ConPtySystem;