use super::{Jail, JailConfig};
use anyhow::{Context, Result};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitStatus;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, SystemTime};
use tracing::{debug, error, info, warn};
use crate::jail::{canary_owner_alive, get_canary_dir, valid_jail_id};
pub struct ManagedJail<J: Jail> {
jail: J,
canary_dir: PathBuf,
canary_path: PathBuf,
heartbeat_interval: Duration,
orphan_timeout: Duration,
enable_heartbeat: bool,
stop_heartbeat: Arc<AtomicBool>,
heartbeat_handle: Option<JoinHandle<()>>,
}
impl<J: Jail> ManagedJail<J> {
pub fn new(jail: J, config: &JailConfig) -> Result<Self> {
let canary_dir = get_canary_dir();
let canary_path = canary_dir.join(&config.jail_id);
Ok(Self {
jail,
canary_dir,
canary_path,
heartbeat_interval: Duration::from_secs(config.heartbeat_interval_secs),
orphan_timeout: Duration::from_secs(config.orphan_timeout_secs),
enable_heartbeat: config.enable_heartbeat,
stop_heartbeat: Arc::new(AtomicBool::new(false)),
heartbeat_handle: None,
})
}
fn ensure_canary_dir(&self) -> Result<()> {
#[cfg(target_os = "linux")]
if unsafe { libc::geteuid() == 0 } {
crate::jail::ensure_trusted_root_dir(&self.canary_dir)?;
return Ok(());
}
fs::create_dir_all(&self.canary_dir)?;
Ok(())
}
pub fn debug_cleanup_orphans(&self) -> Result<()> {
self.cleanup_orphans()
}
fn cleanup_orphans(&self) -> Result<()> {
debug!("Starting orphan cleanup scan in {:?}", self.canary_dir);
let existed = self.canary_dir.exists();
self.ensure_canary_dir()
.context("Failed to create trusted canary directory")?;
if !existed {
return Ok(());
}
for entry in fs::read_dir(&self.canary_dir)? {
let entry = entry?;
let path = entry.path();
if !path.is_file() {
continue;
}
let metadata = fs::metadata(&path)?;
let modified = metadata
.modified()
.context("Failed to get file modification time")?;
let age = SystemTime::now()
.duration_since(modified)
.unwrap_or(Duration::from_secs(0));
if age > self.orphan_timeout {
let jail_id = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
if !valid_jail_id(jail_id) || canary_owner_alive(&path) {
debug!("Skipping canary for live or invalid jail {}", jail_id);
continue;
}
info!(
"Found orphaned jail '{}' (age: {:?}), cleaning up",
jail_id, age
);
J::cleanup_orphaned(jail_id)
.context(format!("Failed to cleanup orphaned jail '{}'", jail_id))?;
if let Err(e) = fs::remove_file(&path) {
error!("Failed to remove orphaned canary file: {}", e);
}
}
}
Ok(())
}
fn start_heartbeat(&mut self) -> Result<()> {
if !self.enable_heartbeat {
return Ok(());
}
let canary_path = self.canary_path.clone();
let interval = self.heartbeat_interval;
let stop_flag = self.stop_heartbeat.clone();
let handle = thread::spawn(move || {
debug!("Starting heartbeat thread for {:?}", canary_path);
while !stop_flag.load(Ordering::Relaxed) {
if let Err(e) = touch_file_mtime(&canary_path) {
warn!("Failed to touch canary file: {}", e);
}
thread::sleep(interval);
}
debug!("Heartbeat thread stopped for {:?}", canary_path);
});
self.heartbeat_handle = Some(handle);
info!(
"Started lifecycle heartbeat for jail '{}'",
self.jail.jail_id()
);
Ok(())
}
fn stop_heartbeat(&mut self) -> Result<()> {
if !self.enable_heartbeat {
return Ok(());
}
self.stop_heartbeat.store(true, Ordering::Relaxed);
if let Some(handle) = self.heartbeat_handle.take() {
handle
.join()
.map_err(|_| anyhow::anyhow!("Failed to join heartbeat thread"))?;
}
debug!("Stopped heartbeat for jail '{}'", self.jail.jail_id());
Ok(())
}
fn signal_stop_heartbeat(&self) {
if self.enable_heartbeat {
self.stop_heartbeat.store(true, Ordering::Relaxed);
}
}
fn create_canary(&self) -> Result<()> {
self.ensure_canary_dir()
.context("Failed to create trusted canary directory")?;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&self.canary_path)
.context("Failed to create exclusive canary file")?;
file.write_all(std::process::id().to_string().as_bytes())
.context("Failed to write canary owner")?;
debug!("Created canary file for jail '{}'", self.jail.jail_id());
Ok(())
}
fn delete_canary(&self) -> Result<()> {
if self.canary_path.exists() {
fs::remove_file(&self.canary_path).context("Failed to remove canary file")?;
debug!("Deleted canary file for jail '{}'", self.jail.jail_id());
}
Ok(())
}
}
fn touch_file_mtime(path: &PathBuf) -> Result<()> {
if path.exists() {
let metadata = fs::metadata(path)?;
let atime = metadata.accessed().unwrap_or_else(|_| SystemTime::now());
let mtime = SystemTime::now();
filetime::set_file_times(
path,
filetime::FileTime::from_system_time(atime),
filetime::FileTime::from_system_time(mtime),
)?;
}
Ok(())
}
impl<J: Jail> Jail for ManagedJail<J> {
fn setup(&mut self, proxy_port: u16) -> Result<()> {
if self.enable_heartbeat {
self.cleanup_orphans()?;
self.create_canary()?;
}
let setup_result = self.jail.setup(proxy_port);
if setup_result.is_err() && self.enable_heartbeat {
let _ = self.delete_canary();
return setup_result;
}
self.start_heartbeat()?;
Ok(())
}
fn execute(&self, command: &[String], extra_env: &[(String, String)]) -> Result<ExitStatus> {
self.jail.execute(command, extra_env)
}
fn execute_with_timeout(
&self,
command: &[String],
extra_env: &[(String, String)],
timeout: Duration,
) -> Result<ExitStatus> {
self.jail.execute_with_timeout(command, extra_env, timeout)
}
fn cleanup(&self) -> Result<()> {
self.signal_stop_heartbeat();
self.jail.cleanup()?;
if self.enable_heartbeat {
self.delete_canary()?;
}
Ok(())
}
fn jail_id(&self) -> &str {
self.jail.jail_id()
}
fn cleanup_orphaned(jail_id: &str) -> Result<()>
where
Self: Sized,
{
J::cleanup_orphaned(jail_id)
}
}
impl<J: Jail> Drop for ManagedJail<J> {
fn drop(&mut self) {
let _ = self.stop_heartbeat();
let cleanup_result = self.jail.cleanup();
if self.enable_heartbeat && cleanup_result.is_ok() {
let _ = self.delete_canary();
} else if cleanup_result.is_err() {
error!(
"Failed to cleanup jail '{}', leaving canary for orphan cleanup",
self.jail.jail_id()
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canary_creation_never_follows_an_existing_symlink() {
let dir = tempfile::tempdir().unwrap();
let sentinel = dir.path().join("sentinel");
fs::write(&sentinel, "unchanged").unwrap();
let config = JailConfig::new();
let weak = crate::jail::weak::WeakJail::new(config.clone()).unwrap();
let mut jail = ManagedJail::new(weak, &config).unwrap();
jail.enable_heartbeat = false;
jail.canary_dir = dir.path().to_path_buf();
jail.canary_path = dir.path().join("canary");
std::os::unix::fs::symlink(&sentinel, &jail.canary_path).unwrap();
assert!(jail.create_canary().is_err());
assert_eq!(fs::read_to_string(&sentinel).unwrap(), "unchanged");
}
}