use crate::error::{Error, Result};
use crate::jail::jexec::jexec_with_timeout;
use crate::proc::{Outcome, run_supervised};
use crate::strings::replace_in_place;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum HookPhase {
PreCreate,
PostCreate,
PreStart,
PostStart,
PreStop,
PostStop,
PreEva,
PostEva,
}
impl HookPhase {
pub const fn requires_running_jail(self) -> bool {
matches!(
self,
Self::PostStart | Self::PreStop | Self::PreEva | Self::PostEva
)
}
}
impl std::fmt::Display for HookPhase {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::PreCreate => "pre_create",
Self::PostCreate => "post_create",
Self::PreStart => "pre_start",
Self::PostStart => "post_start",
Self::PreStop => "pre_stop",
Self::PostStop => "post_stop",
Self::PreEva => "pre_eva",
Self::PostEva => "post_eva",
};
write!(f, "{s}")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum HookTarget {
#[default]
Host,
Jail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum OnFailure {
#[default]
Abort,
Continue,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Hook {
pub phase: HookPhase,
#[serde(default)]
pub target: HookTarget,
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(default = "default_timeout")]
pub timeout: u64,
#[serde(default)]
pub on_failure: OnFailure,
pub description: Option<String>,
}
const fn default_timeout() -> u64 {
30
}
#[cfg(test)]
impl Hook {
pub fn new(phase: HookPhase, command: String) -> Self {
Self {
phase,
target: HookTarget::Host,
command,
args: Vec::new(),
timeout: default_timeout(),
on_failure: OnFailure::Abort,
description: None,
}
}
pub fn with_target(mut self, target: HookTarget) -> Self {
self.target = target;
self
}
pub fn with_args(mut self, args: Vec<String>) -> Self {
self.args = args;
self
}
pub fn with_timeout(mut self, timeout: u64) -> Self {
self.timeout = timeout;
self
}
pub fn with_on_failure(mut self, on_failure: OnFailure) -> Self {
self.on_failure = on_failure;
self
}
}
#[derive(Debug, Clone, Default)]
pub struct HookContext {
pub jail_name: String,
pub jail_path: String,
pub jail_ip: Option<String>,
pub jid: Option<i32>,
pub extra: HashMap<String, String>,
}
impl HookContext {
pub fn new(jail_name: &str, jail_path: &Path) -> Self {
Self {
jail_name: jail_name.to_string(),
jail_path: jail_path.display().to_string(),
jail_ip: None,
jid: None,
extra: HashMap::new(),
}
}
pub fn with_ip(mut self, ip: String) -> Self {
self.jail_ip = Some(ip);
self
}
pub const fn with_jid(mut self, jid: i32) -> Self {
self.jid = Some(jid);
self
}
#[cfg(test)]
pub fn with_var(mut self, name: &str, value: &str) -> Self {
self.extra.insert(name.to_string(), value.to_string());
self
}
#[allow(clippy::literal_string_with_formatting_args)] pub fn substitute(&self, input: &str) -> String {
if !input.contains('$') {
return input.to_string();
}
let mut result = input.to_string();
replace_in_place(&mut result, "${jail_name}", &self.jail_name);
replace_in_place(&mut result, "${jail_path}", &self.jail_path);
replace_in_place(
&mut result,
"${jail_ip}",
self.jail_ip.as_deref().unwrap_or(""),
);
if result.contains("${jid}") {
match self.jid {
Some(jid) => result = result.replace("${jid}", &jid.to_string()),
None => result = result.replace("${jid}", ""),
}
}
let mut needle = String::new();
for (name, value) in &self.extra {
needle.clear();
needle.push_str("${");
needle.push_str(name);
needle.push('}');
replace_in_place(&mut result, &needle, value);
}
result
}
}
#[derive(Debug)]
pub struct HookResult {
pub success: bool,
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
}
impl HookResult {
pub fn summary(&self) -> String {
let status = if self.success { "success" } else { "failed" };
let code = self
.exit_code
.map(|c| format!(" (exit {c})"))
.unwrap_or_default();
format!("{status}{code}")
}
pub fn output(&self) -> String {
if self.stdout.is_empty() {
self.stderr.clone()
} else if self.stderr.is_empty() {
self.stdout.clone()
} else {
format!("{}\n{}", self.stdout, self.stderr)
}
}
}
pub struct HookRunner {
hooks: Vec<Hook>,
verbose: bool,
}
impl HookRunner {
pub const fn new(hooks: Vec<Hook>) -> Self {
Self {
hooks,
verbose: false,
}
}
pub const fn verbose(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}
pub fn execute_phase(&self, phase: HookPhase, context: &HookContext) -> Result<()> {
let phase_hooks = filter_by_phase(&self.hooks, phase);
if phase_hooks.is_empty() {
return Ok(());
}
if phase.requires_running_jail() && context.jid.is_none() {
return Err(Error::HookFailed {
phase: phase.to_string(),
command: phase_hooks[0].command.clone(),
message: format!(
"Phase {} needs a running jail but no JID was supplied for '{}'",
phase, context.jail_name
),
});
}
if self.verbose {
println!("Executing {} hooks for phase {}", phase_hooks.len(), phase);
}
for hook in phase_hooks {
let result = self.execute_hook(hook, context)?;
let desc = hook.description.as_deref().unwrap_or(&hook.command);
if self.verbose {
println!(" {} -> {}", desc, result.summary());
let output = result.output();
if !output.trim().is_empty() {
println!("{}", output.trim_end());
}
}
if !result.success {
let msg = format!(
"Hook '{}' {} at phase {}: {}",
desc,
result.summary(),
phase,
result.output().trim_end()
);
match hook.on_failure {
OnFailure::Abort => {
return Err(Error::HookFailed {
phase: phase.to_string(),
command: hook.command.clone(),
message: format!(
"{}: {}",
result.summary(),
result.output().trim_end()
),
});
}
OnFailure::Continue => {
eprintln!("Warning: {msg}");
}
}
}
}
Ok(())
}
fn execute_hook(&self, hook: &Hook, context: &HookContext) -> Result<HookResult> {
let command = context.substitute(&hook.command);
let args: Vec<String> = hook.args.iter().map(|a| context.substitute(a)).collect();
if self.verbose {
let desc = hook.description.as_deref().unwrap_or(&command);
println!(" Running: {} ({:?})", desc, hook.target);
}
match hook.target {
HookTarget::Host => Self::execute_on_host(&command, &args, hook.timeout),
HookTarget::Jail => {
let jid = context.jid.ok_or_else(|| Error::HookFailed {
phase: hook.phase.to_string(),
command: command.clone(),
message: "Cannot execute jail hook: jail is not running".to_string(),
})?;
Self::execute_in_jail(jid, &command, &args, hook.timeout)
}
}
}
fn execute_on_host(command: &str, args: &[String], timeout_secs: u64) -> Result<HookResult> {
let mut cmd = Command::new(command);
cmd.args(args);
let failed = |message: String| Error::HookFailed {
phase: String::new(),
command: command.to_string(),
message,
};
match run_supervised(&mut cmd, Duration::from_secs(timeout_secs))
.map_err(|e| failed(e.to_string()))?
{
Outcome::Exited(out) => Ok(HookResult {
success: out.success,
exit_code: out.exit_code,
stdout: out.stdout,
stderr: out.stderr,
}),
Outcome::TimedOut => Err(Error::HookTimeout(timeout_secs)),
}
}
fn execute_in_jail(
jid: i32,
command: &str,
args: &[String],
timeout_secs: u64,
) -> Result<HookResult> {
let mut cmd_parts: Vec<&str> = vec![command];
for arg in args {
cmd_parts.push(arg);
}
match jexec_with_timeout(jid, &cmd_parts, timeout_secs) {
Ok((exit_code, stdout, stderr)) => Ok(HookResult {
success: exit_code == 0,
exit_code: Some(exit_code),
stdout,
stderr,
}),
Err(Error::JailTimeout(secs)) => Err(Error::HookTimeout(secs)),
Err(e) => Err(Error::HookFailed {
phase: String::new(),
command: command.to_string(),
message: e.to_string(),
}),
}
}
}
pub fn filter_by_phase(hooks: &[Hook], phase: HookPhase) -> Vec<&Hook> {
hooks.iter().filter(|h| h.phase == phase).collect()
}
#[cfg(test)]
mod tests;