use crate::blueprint::context::{BuildContext, reject_symlink_ancestors};
use crate::blueprint::instructions::{CopySpec, Instruction, Jailfile};
use crate::error::{Error, Result};
use crate::jail::jexec::chroot_exec;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
pub struct LayerCache {
pub zfs: crate::zfs::ZfsManager,
pub jail: String,
pub seed: String,
}
pub struct TemplateExecutor {
context: BuildContext,
dry_run: bool,
layer_cache: Option<LayerCache>,
}
impl TemplateExecutor {
pub const fn new(context: BuildContext) -> Self {
Self {
context,
dry_run: false,
layer_cache: None,
}
}
pub const fn dry_run(mut self, dry_run: bool) -> Self {
self.dry_run = dry_run;
self
}
pub fn layer_cache(mut self, cache: Option<LayerCache>) -> Self {
self.layer_cache = cache;
self
}
fn instruction_key(&self, prev: &str, instruction: &Instruction) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(prev.as_bytes());
hasher.update(format!("{instruction:?}").as_bytes());
if let Instruction::Copy(spec) = instruction
&& let Ok(src_path) = self.context.resolve_source(&spec.src)
{
hash_path_contents(&mut hasher, &src_path);
}
hex_digest(hasher)
}
const fn is_layer_boundary(instruction: &Instruction) -> bool {
matches!(instruction, Instruction::Run(_) | Instruction::Copy(_))
}
pub fn execute(&mut self, jailfile: &Jailfile) -> Result<()> {
self.context.log(format_args!(
"Building jail '{}' from {:?}",
self.context.jail_name(),
jailfile.from
));
for arg in &jailfile.args {
if self.context.get_arg(&arg.name).is_none()
&& let Some(default) = &arg.default
{
self.context.set_arg(&arg.name, default);
}
}
let mut resume_from = 0usize;
let mut keys: Vec<String> = Vec::new();
if let Some(cache) = &self.layer_cache {
let mut hash = cache.seed.clone();
let mut last_cached: Option<(usize, String)> = None;
let mut chain_intact = true;
for (index, instruction) in jailfile.instructions.iter().enumerate() {
hash = self.instruction_key(&hash, instruction);
keys.push(hash.clone());
if chain_intact && Self::is_layer_boundary(instruction) {
let layer = crate::zfs::ZfsManager::layer_snapshot_name(index, &hash[..12]);
if cache.zfs.has_layer(&cache.jail, &layer) {
last_cached = Some((index, layer));
} else {
chain_intact = false;
}
}
}
if let Some((index, layer)) = last_cached {
if !self.dry_run {
cache.zfs.rollback_to_layer(&cache.jail, &layer)?;
}
println!("CACHED steps 1-{} (layer {})", index + 1, layer);
resume_from = index + 1;
}
}
for (index, instruction) in jailfile.instructions.iter().enumerate() {
if index < resume_from {
if !Self::is_layer_boundary(instruction) {
self.execute_instruction(instruction)?;
}
continue;
}
self.execute_instruction(instruction)?;
if !self.dry_run
&& Self::is_layer_boundary(instruction)
&& let Some(cache) = &self.layer_cache
{
let layer = crate::zfs::ZfsManager::layer_snapshot_name(index, &keys[index][..12]);
if let Err(e) = cache.zfs.create_layer(&cache.jail, &layer) {
eprintln!("Warning: failed to snapshot build layer: {e}");
}
}
}
self.context.log(format_args!(
"Build complete for '{}'",
self.context.jail_name()
));
Ok(())
}
fn execute_instruction(&mut self, instruction: &Instruction) -> Result<()> {
match instruction {
Instruction::From(release) => {
self.context.log(format_args!("FROM {release}"));
}
Instruction::Arg(arg) => {
self.context.log(format_args!(
"ARG {}{}",
arg.name,
arg.default
.as_ref()
.map(|d| format!("={d}"))
.unwrap_or_default()
));
}
Instruction::Env(name, value) => {
let value = self.context.substitute(value);
self.context.log(format_args!("ENV {name}={value}"));
self.context.set_env(name, &value);
}
Instruction::Run(command) => {
let command = self.context.substitute(command);
self.context.log(format_args!("RUN {command}"));
if !self.dry_run {
self.execute_run(&command)?;
}
}
Instruction::Copy(spec) => {
self.context
.log(format_args!("COPY {} -> {}", spec.src, spec.dest));
if !self.dry_run {
self.execute_copy(spec)?;
}
}
Instruction::Workdir(path) => {
let path = self.context.substitute(path);
self.context.log(format_args!("WORKDIR {path}"));
self.context.set_workdir(&path);
if !self.dry_run {
self.make_jail_dir(&path, "WORKDIR")?;
}
}
Instruction::Expose(port) => {
self.context
.log(format_args!("EXPOSE {}/{}", port.port, port.protocol));
}
Instruction::Cmd(cmd) => {
let cmd = self.context.substitute(cmd);
self.context.log(format_args!("CMD {cmd}"));
}
Instruction::Entrypoint(cmd) => {
let cmd = self.context.substitute(cmd);
self.context.log(format_args!("ENTRYPOINT {cmd}"));
}
Instruction::User(user) => {
let user = self.context.substitute(user);
self.context.log(format_args!("USER {user}"));
}
Instruction::Label(key, value) => {
let value = self.context.substitute(value);
self.context.log(format_args!("LABEL {key}={value}"));
}
Instruction::Volume(path) => {
let path = self.context.substitute(path);
self.context.log(format_args!("VOLUME {path}"));
if !self.dry_run {
self.make_jail_dir(&path, "VOLUME")?;
}
}
Instruction::Stop(_) | Instruction::Comment(_) => {}
}
Ok(())
}
fn execute_run(&self, command: &str) -> Result<()> {
let target_path = self.context.target_path();
let dev_path = target_path.join("dev");
let resolv_path = target_path.join("etc/resolv.conf");
reject_symlink_ancestors(target_path, &resolv_path)?;
if !resolv_path.exists()
&& let Ok(content) = fs::read("/etc/resolv.conf")
{
if let Some(parent) = resolv_path.parent() {
let _ = fs::create_dir_all(parent); }
if let Ok(mut f) = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&resolv_path)
{
use std::io::Write;
let _ = f.write_all(&content); }
}
reject_symlink_ancestors(target_path, &dev_path)?;
let target_str = target_path.to_str().ok_or_else(|| Error::BuildFailed {
step: "RUN".to_string(),
message: format!("Non-UTF-8 build root: {}", target_path.display()),
})?;
let need_devfs = !dev_path.join("null").exists();
if need_devfs {
std::fs::create_dir_all(&dev_path).ok();
if let Err(e) = crate::sys::mount_devfs(&dev_path) {
eprintln!("Warning: {e}");
}
}
let env_vars: Vec<(String, String)> = self
.context
.env()
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let result = chroot_exec(target_str, command, &env_vars);
if need_devfs {
crate::sys::unmount_quiet(&dev_path);
}
let (exit_code, stdout, stderr) = result.map_err(|e| Error::BuildFailed {
step: "RUN".to_string(),
message: format!("Failed to execute chroot: {e}"),
})?;
if exit_code != 0 {
let stderr_str = String::from_utf8_lossy(&stderr);
return Err(Error::BuildFailed {
step: "RUN".to_string(),
message: format!("Command failed with exit code {exit_code}: {stderr_str}"),
});
}
if self.context.is_verbose() {
let stdout_str = String::from_utf8_lossy(&stdout);
if !stdout_str.is_empty() {
for line in stdout_str.lines() {
println!(" {line}");
}
}
}
Ok(())
}
fn jail_dest(&self, dest: &str, step: &str) -> Result<PathBuf> {
let root = self.context.target_path();
if !root.is_dir() {
return Err(Error::BuildFailed {
step: step.to_string(),
message: format!("Jail root '{}' does not exist", root.display()),
});
}
self.context.resolve_dest(dest)
}
fn make_jail_dir(&self, path: &str, step: &str) -> Result<()> {
let full_path = self.jail_dest(path, step)?;
if !full_path.exists() {
fs::create_dir_all(&full_path).map_err(|e| Error::BuildFailed {
step: step.to_string(),
message: format!("Failed to create {}: {}", full_path.display(), e),
})?;
}
Ok(())
}
fn execute_copy(&self, spec: &CopySpec) -> Result<()> {
let src = self.context.substitute(&spec.src);
let dest = self.context.substitute(&spec.dest);
let src_path = self.context.resolve_source(&src)?;
let dest_path = self.jail_dest(&dest, "COPY")?;
if !src_path.exists() {
return Err(Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Source not found: {}", src_path.display()),
});
}
let canonical_src = src_path.canonicalize().map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Failed to canonicalize source '{}': {}",
src_path.display(),
e
),
})?;
let canonical_context =
self.context
.context_dir()
.canonicalize()
.map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Failed to canonicalize context dir '{}': {}",
self.context.context_dir().display(),
e
),
})?;
if !canonical_src.starts_with(&canonical_context) {
return Err(Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Source '{}' resolves to '{}' which is outside the build context '{}'",
src_path.display(),
canonical_src.display(),
canonical_context.display()
),
});
}
if let Some(parent) = dest_path.parent()
&& !parent.exists()
{
create_copy_dir(parent)?;
}
if canonical_src.is_dir() {
copy_dir_recursive(&canonical_src, &dest_path)?;
} else {
let final_dest = if dest.ends_with('/') {
dest_path.join(canonical_src.file_name().unwrap_or_default())
} else {
dest_path
};
if let Ok(meta) = fs::symlink_metadata(&final_dest)
&& meta.file_type().is_symlink()
{
return Err(Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Destination {} is a symlink, refusing to overwrite",
final_dest.display()
),
});
}
copy_file(&canonical_src, &final_dest)?;
if let Some(mode) = spec.mode {
let safe_mode = mode & 0o1777; let permissions = fs::Permissions::from_mode(safe_mode);
fs::set_permissions(&final_dest, permissions).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Failed to set permissions on {}: {}",
final_dest.display(),
e
),
})?;
}
if spec.mode.is_none() {
strip_setid_bits(&final_dest)?;
}
if let Some(owner) = &spec.owner {
set_owner(self.context.target_path(), &final_dest, owner)?;
}
}
Ok(())
}
}
#[cfg(test)]
impl TemplateExecutor {
pub fn context(&self) -> &BuildContext {
&self.context
}
pub fn context_mut(&mut self) -> &mut BuildContext {
&mut self.context
}
}
fn strip_setid_bits(path: &Path) -> Result<()> {
let mode = fs::metadata(path)
.map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to stat {}: {e}", path.display()),
})?
.permissions()
.mode();
if mode & 0o6000 != 0 {
fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o1777)).map_err(|e| {
Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to strip setuid/setgid from {}: {e}", path.display()),
}
})?;
}
Ok(())
}
fn copy_file(src: &Path, dest: &Path) -> Result<()> {
fs::copy(src, dest)
.map(drop)
.map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Failed to copy {} to {}: {e}",
src.display(),
dest.display()
),
})
}
fn create_copy_dir(dir: &Path) -> Result<()> {
fs::create_dir_all(dir).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to create directory {}: {e}", dir.display()),
})
}
fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> {
if !dest.exists() {
create_copy_dir(dest)?;
}
for entry in fs::read_dir(src).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to read directory {}: {}", src.display(), e),
})? {
let entry = entry.map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to read directory entry: {e}"),
})?;
let src_path = entry.path();
let dest_path = dest.join(entry.file_name());
let metadata = fs::symlink_metadata(&src_path).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to read metadata for {}: {}", src_path.display(), e),
})?;
if metadata.file_type().is_symlink() {
eprintln!(
"Warning: skipping symlink '{}' during recursive copy",
src_path.display()
);
continue;
}
if metadata.is_dir() {
if dest_path.exists()
&& let Ok(dest_meta) = fs::symlink_metadata(&dest_path)
&& dest_meta.file_type().is_symlink()
{
return Err(Error::BuildFailed {
step: "COPY".to_string(),
message: format!(
"Destination directory '{}' is a symlink, refusing to recurse",
dest_path.display()
),
});
}
copy_dir_recursive(&src_path, &dest_path)?;
} else {
if let Ok(dest_meta) = fs::symlink_metadata(&dest_path)
&& dest_meta.file_type().is_symlink()
{
eprintln!(
"Warning: skipping copy to '{}' because destination is a symlink",
dest_path.display()
);
continue;
}
copy_file(&src_path, &dest_path)?;
strip_setid_bits(&dest_path)?;
}
}
Ok(())
}
fn set_owner(root: &Path, path: &Path, owner: &str) -> Result<()> {
let (uid, gid) = resolve_owner(root, owner)?;
std::os::unix::fs::chown(path, uid, gid).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to chown {} to {owner}: {e}", path.display()),
})
}
fn resolve_owner(root: &Path, owner: &str) -> Result<(Option<u32>, Option<u32>)> {
let (user, group) = owner.split_once(':').unwrap_or((owner, ""));
let uid = (!user.is_empty())
.then(|| lookup_id(root, "etc/passwd", user, "user"))
.transpose()?;
let gid = (!group.is_empty())
.then(|| lookup_id(root, "etc/group", group, "group"))
.transpose()?;
Ok((uid, gid))
}
fn lookup_id(root: &Path, file: &str, name: &str, what: &str) -> Result<u32> {
if let Ok(id) = name.parse::<u32>() {
return Ok(id);
}
let table = fs::read_to_string(root.join(file)).map_err(|e| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("Failed to read the jail's {file}: {e}"),
})?;
table
.lines()
.filter(|line| !line.starts_with('#'))
.find_map(|line| {
let mut fields = line.split(':');
(fields.next() == Some(name))
.then(|| fields.nth(1)?.parse().ok())
.flatten()
})
.ok_or_else(|| Error::BuildFailed {
step: "COPY".to_string(),
message: format!("No {what} '{name}' in the jail's {file}"),
})
}
fn hex_digest(hasher: sha2::Sha256) -> String {
use sha2::Digest;
hex::encode(hasher.finalize())
}
fn hash_path_contents(hasher: &mut sha2::Sha256, path: &Path) {
use sha2::Digest;
if path.is_file() {
if let Ok(bytes) = fs::read(path) {
hasher.update(&bytes);
}
} else if path.is_dir()
&& let Ok(entries) = fs::read_dir(path)
{
let mut paths: Vec<_> = entries.flatten().map(|e| e.path()).collect();
paths.sort();
for child in paths {
hasher.update(child.to_string_lossy().as_bytes());
hash_path_contents(hasher, &child);
}
}
}
#[cfg(test)]
mod tests;