use std::io;
use crate::elevation::shim::fork_guard::Origin;
use crate::elevation::shim::protocol::{decode_frame, Frame, FrameError, NotExecuted, Refusal};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AcceptorFailure {
Errno(i32),
Panicked,
}
impl std::fmt::Display for AcceptorFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AcceptorFailure::Errno(errno) => write!(f, "{}", io::Error::from_raw_os_error(*errno)),
AcceptorFailure::Panicked => f.write_str("it panicked"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NotStartedCause {
Withheld,
AcceptorFailed(AcceptorFailure),
NotExecuted(NotExecuted),
ShimRefused(Refusal),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NotStarted {
pub(crate) shim_connected: bool,
pub(crate) cause: NotStartedCause,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LinkOutcome {
Exited(i32),
NotStarted(NotStarted),
SupervisionLost(i32),
StatusLost,
ShimLost,
}
impl LinkOutcome {
pub(crate) fn program_is_gone(&self) -> bool {
!matches!(self, LinkOutcome::ShimLost)
}
}
pub(super) fn classify(bytes: &[u8], eof: bool) -> Option<LinkOutcome> {
match decode_frame(bytes) {
Ok(Frame::Hello) => Some(LinkOutcome::ShimLost),
Ok(Frame::Status(ws)) => Some(LinkOutcome::Exited(ws)),
Ok(Frame::Lost(ws)) => Some(LinkOutcome::SupervisionLost(ws)),
Ok(Frame::StatusLost) => Some(LinkOutcome::StatusLost),
Ok(Frame::NotExecuted(n)) => Some(LinkOutcome::NotStarted(NotStarted {
shim_connected: true,
cause: NotStartedCause::NotExecuted(n),
})),
Ok(Frame::Refused(r)) => Some(LinkOutcome::NotStarted(NotStarted {
shim_connected: true,
cause: NotStartedCause::ShimRefused(r),
})),
Err(FrameError::Garbled) => Some(LinkOutcome::ShimLost),
Err(FrameError::Truncated) => eof.then_some(LinkOutcome::ShimLost),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillOutcome {
Delivered,
AlreadyEnded,
RefusedStart,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum WaitError {
#[error(transparent)]
NotOwner(#[from] NotOwner),
#[error("waiting for the shim")]
Poll(#[source] io::Error),
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum KillError {
#[error("the shim is lost")]
ShimLost,
#[error("the shim's socket would block")]
Unkillable,
#[error(transparent)]
NotOwner(#[from] NotOwner),
#[error("sending to the shim")]
Io(#[source] io::Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("a fork copy of the link cannot control it")]
pub(crate) struct NotOwner;
pub(super) fn owner_check(origin: Origin) -> Result<(), NotOwner> {
if origin == Origin::Original {
Ok(())
} else {
Err(NotOwner)
}
}