use crate::containment::{ContainMode, ContainRequest, Containment, Nesting};
use crate::error::Error;
pub(crate) struct Prepared {
#[allow(dead_code)] pub mode: Option<ContainMode>,
#[allow(dead_code)] pub is_root: bool,
#[cfg(target_os = "linux")]
pub cgroup_leaf: Option<crate::containment::cgroup::CgroupLeaf>,
}
#[derive(Debug, Default)]
pub(crate) enum Attached {
#[default]
None,
Delegated,
#[cfg(unix)]
ProcessGroup(i32), #[cfg(target_os = "linux")]
Cgroup(crate::containment::cgroup::CgroupLeaf),
#[cfg(windows)]
JobObject(crate::containment::windows::JobHandle),
TreeWalk(crate::identity::ProcessId),
}
#[cfg(target_os = "linux")]
impl std::fmt::Debug for crate::containment::cgroup::CgroupLeaf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CgroupLeaf").finish_non_exhaustive()
}
}
impl Attached {
pub(crate) fn hard_kill(&self) -> Result<(), crate::error::Error> {
match self {
Attached::None | Attached::Delegated => Ok(()),
#[cfg(unix)]
Attached::ProcessGroup(pgid) => {
crate::containment::unix::kill_group(*pgid).map_err(crate::error::Error::Io)
}
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => {
leaf.hard_kill();
Ok(())
}
#[cfg(windows)]
Attached::JobObject(job) => {
job.hard_kill();
Ok(())
}
Attached::TreeWalk(root) => {
crate::containment::treewalk::hard_kill(*root);
Ok(())
}
}
}
pub(crate) fn terminate(&self, _child_pid: u32) -> Result<(), Error> {
match self {
Attached::None | Attached::Delegated => {
debug_assert!(
self.is_actionable(),
"Attached::terminate on a non-actionable mechanism"
);
Err(crate::error::Error::Unsupported {
op: "terminate on a non-actionable mechanism".into(),
platform: std::env::consts::OS,
detail: "internal invariant: a non-actionable mechanism reached terminate".into(),
})
}
#[cfg(unix)]
Attached::ProcessGroup(pgid) => crate::containment::unix::term_group(*pgid).map_err(Error::Io),
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.terminate().map_err(Error::Io),
#[cfg(windows)]
Attached::JobObject(_) => crate::containment::windows::terminate(_child_pid).map_err(Error::Io),
Attached::TreeWalk(root) => crate::containment::treewalk::terminate(*root),
}
}
pub(crate) fn disarm(&self) {
match self {
Attached::None | Attached::Delegated => {}
#[cfg(unix)]
Attached::ProcessGroup(_) => {} #[cfg(target_os = "linux")]
Attached::Cgroup(_) => {} #[cfg(windows)]
Attached::JobObject(job) => job.disarm(), Attached::TreeWalk(_) => {} }
}
pub(crate) fn is_actionable(&self) -> bool {
match self {
Attached::None | Attached::Delegated => false,
#[cfg(unix)]
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "linux")]
Attached::Cgroup(_) => true,
#[cfg(windows)]
Attached::JobObject(_) => true,
Attached::TreeWalk(_) => true,
}
}
}
pub(crate) fn is_nested(marker_present: bool) -> bool {
marker_present
}
#[cfg(any(unix, windows))]
fn resolve_root_id(pid: u32) -> Result<crate::identity::ProcessId, Error> {
crate::identity::ProcessId::of(pid).ok_or_else(|| Error::Containment {
detail: "tree-walk root vanished before its identity could be read".into(),
})
}
#[cfg(unix)]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum UnixSetup {
Session,
ProcessGroup,
None,
}
#[cfg(unix)]
pub(crate) fn unix_setup_for(mode: Option<ContainMode>) -> UnixSetup {
match mode {
Some(ContainMode::Session) => UnixSetup::Session,
Some(ContainMode::TreeWalk) => UnixSetup::None,
_ => UnixSetup::ProcessGroup,
}
}
#[cfg(windows)]
pub(crate) struct WindowsContain {
pub creation_flags: u32,
pub marker_env: bool,
}
#[cfg(windows)]
pub(crate) fn windows_contain_setup(req: &ContainRequest, is_root: bool) -> WindowsContain {
let Some(mode) = req.mode else {
return WindowsContain {
creation_flags: 0,
marker_env: false,
};
};
let creation_flags = if is_root && !matches!(mode, ContainMode::TreeWalk) {
crate::containment::windows::root_flags()
} else {
crate::containment::windows::group_flags()
};
WindowsContain {
creation_flags,
marker_env: is_root && req.nesting == Nesting::Mark,
}
}
pub(crate) fn prepare(std_cmd: &mut std::process::Command, req: &ContainRequest) -> Prepared {
let mode = req.mode;
if mode.is_none() {
return Prepared {
mode: None,
is_root: false,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
};
}
let marker_present = std::env::var_os(crate::containment::NESTED_ENV).is_some();
let is_root = !is_nested(marker_present);
if is_root && req.nesting == Nesting::Mark {
std_cmd.env(crate::containment::NESTED_ENV, "1");
}
#[cfg(target_os = "linux")]
{
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => {
crate::containment::unix::set_session(std_cmd);
return Prepared {
mode,
is_root,
cgroup_leaf: None, };
}
UnixSetup::None => {
return Prepared {
mode,
is_root,
cgroup_leaf: None,
};
}
UnixSetup::ProcessGroup => {
crate::containment::unix::set_process_group(std_cmd);
}
}
let leaf = crate::containment::cgroup::try_create_leaf();
if let Some(ref l) = leaf {
let procs_fd = l.procs_fd();
unsafe {
use std::os::unix::process::CommandExt;
std_cmd.pre_exec(move || {
let _ = crate::containment::cgroup::place_self_in_cgroup_pre_exec(procs_fd);
Ok(())
});
}
}
return Prepared {
mode,
is_root,
cgroup_leaf: leaf,
};
}
return Prepared {
mode,
is_root,
cgroup_leaf: None,
};
}
#[cfg(all(unix, not(target_os = "linux")))]
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => crate::containment::unix::set_session(std_cmd),
UnixSetup::ProcessGroup => crate::containment::unix::set_process_group(std_cmd),
UnixSetup::None => {} }
}
#[cfg(windows)]
if mode.is_some() {
use std::os::windows::process::CommandExt;
crate::containment::windows::clear_std_handle_inheritance();
let setup = windows_contain_setup(req, is_root);
std_cmd.creation_flags(setup.creation_flags);
}
#[allow(unreachable_code)]
Prepared {
mode,
is_root,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
}
}
pub(crate) fn attach(
pid: u32,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<(Containment, Attached), Error> {
#[cfg(target_os = "linux")]
{
if prepared.mode.is_some() {
if prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
if matches!(prepared.mode, Some(ContainMode::Session)) {
return Ok((Containment::Session, Attached::ProcessGroup(pgid)));
}
if let Some(leaf) = prepared.cgroup_leaf {
if leaf.contains_pid(raw_pid) {
return Ok((Containment::CgroupV2, Attached::Cgroup(leaf)));
}
drop(leaf);
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
}
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
} else {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
if prepared.mode.is_some() {
if prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
let containment = match prepared.mode {
Some(ContainMode::Session) => Containment::Session,
_ => Containment::ProcessGroup,
};
return Ok((containment, Attached::ProcessGroup(pgid)));
} else {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
}
#[cfg(windows)]
{
if prepared.mode.is_some() && prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
match crate::containment::windows::attach_job(proc_handle) {
Ok(Some(job)) => return Ok((Containment::JobObject, Attached::JobObject(job))),
Ok(None) => {
return Ok((Containment::TreeWalk, Attached::TreeWalk(resolve_root_id(pid)?)));
}
Err(e) => return Err(Error::Containment { detail: e.to_string() }),
}
} else if prepared.mode.is_some() {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
let _ = prepared;
Ok((Containment::None, Attached::None))
}
#[cfg(test)]
#[path = "dispatch_tests.rs"]
mod dispatch_tests;