| 1 | use std::ffi::CString; |
| 2 | |
| 3 | use libcontainer::workload::default::DefaultExecutor; |
| 4 | use libcontainer::workload::{Executor, ExecutorError, ExecutorValidationError}; |
| 5 | use nix::unistd; |
| 6 | use oci_spec::runtime::Spec; |
| 7 | use seccompiler::BpfProgram; |
| 8 | |
| 9 | #[derive(Clone)] |
| 10 | pub struct FilteredExecutor { |
| 11 | filter: BpfProgram, |
| 12 | } |
| 13 | |
| 14 | impl FilteredExecutor { |
| 15 | pub fn new(filter: BpfProgram) -> Self { |
| 16 | Self { filter } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | impl Executor for FilteredExecutor { |
| 21 | fn exec(&self, spec: &Spec) -> Result<(), ExecutorError> { |
| 22 | seccompiler::apply_filter(&self.filter) |
| 23 | .map_err(|e| ExecutorError::Other(format!("cannot install seccomp filter: {e}")))?; |
| 24 | exec_process(spec) |
| 25 | } |
| 26 | |
| 27 | fn validate(&self, spec: &Spec) -> Result<(), ExecutorValidationError> { |
| 28 | DefaultExecutor {}.validate(spec) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn exec_process(spec: &Spec) -> Result<(), ExecutorError> { |
| 33 | let args = spec |
| 34 | .process() |
| 35 | .as_ref() |
| 36 | .and_then(|p| p.args().as_ref()) |
| 37 | .ok_or(ExecutorError::InvalidArg)?; |
| 38 | let path = args.first().ok_or(ExecutorError::InvalidArg)?; |
| 39 | let path = CString::new(path.as_bytes()).map_err(|_| ExecutorError::InvalidArg)?; |
| 40 | let argv = args |
| 41 | .iter() |
| 42 | .map(|s| CString::new(s.as_bytes()).map_err(|_| ExecutorError::InvalidArg)) |
| 43 | .collect::<Result<Vec<CString>, ExecutorError>>()?; |
| 44 | let err = unistd::execvp(&path, &argv).unwrap_err(); |
| 45 | Err(ExecutorError::Other(format!( |
| 46 | "cannot exec {}: {err}", |
| 47 | path.to_string_lossy() |
| 48 | ))) |
| 49 | } |