use std::ffi::{OsStr, OsString};
use std::io;
use std::os::fd::OwnedFd;
use std::path::PathBuf;
use super::fork_exec::{self, Failure, Program, Progress, SpawnError, Spawned, Status, StepFailure};
use super::in_child::{InChild, Step, StepError};
use super::policy::SpawnPolicy;
use super::{held_teardown, Diagnosis, Invocation, SpawnFailure, SpawnLockGuard};
use crate::child::drop_teardown::Torn;
use crate::child::owned::teardown::{Disposition, Past};
use crate::child::owned::OwnedChild;
use crate::containment::cgroup::{CgroupLeaf, PlacementReport};
use crate::elevation::front::TrackedKind;
use crate::error::Error;
use crate::identity::SpawnKernel;
use crate::os_process::linux::fork::{fork_with_pidfd, CloneKind, ForkFn, NewChild};
const KIND_STEP: u8 = 1;
const KIND_PLACEMENT: u8 = 2;
const STEP_EXIT: i32 = 126;
pub(super) struct Started {
pub(super) pid: u32,
pub(super) owned: OwnedChild,
}
pub(super) struct OnFailure<'a> {
pub(super) policy: SpawnPolicy,
pub(super) tracked: TrackedKind,
pub(super) placement: Option<&'a mut CgroupLeaf>,
pub(super) refusing_placement: bool,
}
pub(super) fn program(
invocation: &Invocation,
later: &[PathBuf],
env: Vec<(OsString, OsString)>,
) -> Result<Program, Error> {
let argv0 = invocation.arg0.as_deref().unwrap_or(invocation.program.as_os_str());
let argv: Vec<&OsStr> = std::iter::once(argv0)
.chain(invocation.args.iter().map(OsString::as_os_str))
.collect();
let paths: Vec<&OsStr> = std::iter::once(invocation.program.as_os_str())
.chain(later.iter().map(|p| p.as_os_str()))
.collect();
Program::new(&paths, &argv, env.into_iter()).map_err(|_| {
Error::Io(io::Error::new(
io::ErrorKind::InvalidInput,
"nul byte found in provided data",
))
})
}
pub(super) fn start(
program: &Program,
steps: &mut InChild,
kernel: SpawnKernel,
on_failure: OnFailure<'_>,
lock: &SpawnLockGuard,
) -> Result<Started, SpawnFailure> {
start_via(fork_with_pidfd, program, steps, kernel, on_failure, lock)
}
pub(super) fn start_via(
fork: ForkFn,
program: &Program,
steps: &mut InChild,
kernel: SpawnKernel,
on_failure: OnFailure<'_>,
_lock: &SpawnLockGuard,
) -> Result<Started, SpawnFailure> {
let keep_off = steps.mapped_fds();
let spawned = unsafe {
fork_exec::spawn(
CloneKind::Vfork,
fork,
program,
&keep_off,
&mut |reporter| steps.run(reporter).map_err(step_failure),
STEP_EXIT,
)
};
match spawned {
Ok(Spawned { child, status }) => conclude(child, status, kernel, on_failure),
Err(error) => Err(SpawnFailure::NotStarted(not_spawned(error))),
}
}
fn step_failure(failed: StepError) -> StepFailure {
StepFailure {
kind: match failed.step {
Step::Placement => KIND_PLACEMENT,
_ => KIND_STEP,
},
value: failed.error.raw_os_error().unwrap_or(libc::EINVAL) as u16,
}
}
fn not_spawned(error: SpawnError) -> Error {
match error {
SpawnError::Unsupported(refusal) => Error::Unsupported {
op: "spawn".into(),
platform: "linux",
detail: format!(
"cosca requires a clone that returns the child's pidfd (clone3, or clone with CLONE_PIDFD; \
Linux \u{2265} 5.3), refused here: clone answered {} (kernel {})",
refusal.name(),
kernel_release()
),
source: Some(std::sync::Arc::new(Error::Io(io::Error::from_raw_os_error(
refusal.errno(),
)))),
},
SpawnError::Fork(errno) | SpawnError::Pipe(errno) => Error::Io(io::Error::from_raw_os_error(errno)),
}
}
fn kernel_release() -> String {
unsafe {
let mut name: libc::utsname = std::mem::zeroed();
if libc::uname(&mut name) != 0 {
return "unknown".into();
}
std::ffi::CStr::from_ptr(name.release.as_ptr())
.to_string_lossy()
.into_owned()
}
}
fn failed(pid: u32, failure: Failure) -> Error {
let errno = match failure {
Failure::Exec(errno) => errno,
Failure::Step(StepFailure { kind: KIND_STEP, value }) => i32::from(value),
Failure::Step(StepFailure {
kind: KIND_PLACEMENT,
value,
}) => {
return Error::Containment {
detail: format!(
"the spawned child ({}) died before exec in its cgroup placement step: the program never ran",
super::named(Some(pid))
),
source: Some(Error::io_cause(io::Error::from_raw_os_error(i32::from(value)))),
};
}
Failure::Step(other) => {
debug_assert!(
false,
"a step failure of kind {} is not one this spawn reports",
other.kind
);
libc::EIO
}
};
Error::Io(io::Error::from_raw_os_error(errno))
}
fn died_before_exec(pid: u32) -> Error {
Error::Io(io::Error::other(format!(
"the spawned child ({}) died before exec: the program never ran",
super::named(Some(pid))
)))
}
fn read_records(status: &mut Status, leaf: Option<&mut CgroupLeaf>) -> (io::Result<Progress>, Option<PlacementReport>) {
let progress = status.progress();
let reported = status.reported().map(PlacementReport::of_record);
let report = match (&progress, reported) {
(_, Some(report)) => Some(report),
(Err(e), None) => Some(PlacementReport::Unknown(e.raw_os_error().unwrap_or(libc::EIO))),
(Ok(progress), None) => {
debug_assert!(
leaf.is_none() || !matches!(progress, Progress::Ready | Progress::Ended { ready: true }),
"a child with a cgroup leaf reached its execve with no placement report"
);
None
}
};
if let (Some(leaf), Some(report)) = (leaf, report) {
leaf.record_placement(report);
}
(progress, report)
}
fn conclude(
child: NewChild,
mut status: Status,
kernel: SpawnKernel,
mut on_failure: OnFailure<'_>,
) -> Result<Started, SpawnFailure> {
let pid = child.pid.unsigned_abs();
let pidfd = match crate::above_stdio::above_stdio_keeping(child.pidfd) {
Ok(pidfd) => pidfd,
Err((e, pidfd)) => {
_ = read_records(&mut status, on_failure.placement.as_deref_mut());
return Err(unmovable(pid, pidfd, e, kernel, on_failure));
}
};
let (progress, report) = read_records(&mut status, on_failure.placement.as_deref_mut());
let refused = on_failure.refusing_placement && matches!(report, Some(PlacementReport::WriteFailed(_)));
let did_not_start = if refused {
None
} else {
match progress {
Ok(Progress::Failed(failure)) => Some(failed(pid, failure)),
progress => match progress.and_then(|_| status.could_have_started()) {
Ok(true) => None,
Ok(false) => Some(died_before_exec(pid)),
Err(e) => {
log::warn!(
"{}: its status channel is unreadable ({}); taken to have started",
super::named(Some(pid)),
crate::error::Report(&e)
);
None
}
},
}
};
let owned = OwnedChild::over_pidfd(kernel, Some(pid), pidfd, on_failure.tracked);
match did_not_start {
Some(cause) => {
let torn = held_teardown::tear_down_unexecuted(
owned,
None,
Past::Unexecuted,
on_failure.policy,
&mut Diagnosis::default(),
);
Err(SpawnFailure::NotStartedWithChild { cause, fate: torn.fate })
}
None => Ok(Started { pid, owned }),
}
}
fn unmovable(pid: u32, pidfd: OwnedFd, e: io::Error, kernel: SpawnKernel, on_failure: OnFailure<'_>) -> SpawnFailure {
let owned = OwnedChild::over_pidfd(kernel, Some(pid), pidfd, on_failure.tracked);
let how = held_teardown::HeldTeardown {
id: None,
reach: None,
disposition: Disposition::HandBack,
policy: on_failure.policy,
};
let (detail, torn) = held_teardown::tear_down_held(owned, how, &mut Diagnosis::default());
let Torn {
fate,
unreaped,
cleanup,
} = torn;
SpawnFailure::started(
Error::Io(crate::error::io_context("moving the child's pidfd above stdio", e)),
fate,
unreaped,
)
.with_detail(detail)
.with_cleanup(cleanup)
}
#[cfg(test)]
#[path = "fork_spawn_tests.rs"]
mod fork_spawn_tests;
#[cfg(test)]
#[path = "fork_spawn/lookup_tests.rs"]
mod lookup_tests;
#[cfg(all(test, feature = "tokio"))]
#[path = "fork_spawn/slow_teardown_tests.rs"]
mod slow_teardown_tests;