mod copy;
mod create;
mod exec;
mod registry;
mod teardown;
pub use exec::{Exec, ExecOutput, Exit, Stream};
pub use registry::{ContainerInfo, Selector};
#[cfg(feature = "cli")]
pub use copy::{JailSide as CopyJailSide, Side as CopySide, transfer as transfer_between};
use copy::{JailSide, transfer};
#[cfg(feature = "cli")]
pub use teardown::{network_cleanup, unmount_jail_filesystems};
use crate::error::{Error, Result};
use crate::host::{Host, Layout};
use crate::manifest::validate_name;
use crate::rctl::ResourceConfig;
use std::collections::BTreeMap;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Network {
#[default]
None,
Inherit,
Vnet(String),
}
impl Network {
pub fn vnet(network: impl Into<String>) -> Self {
Self::Vnet(network.into())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mount {
host: PathBuf,
jail: PathBuf,
writable: bool,
nosuid: bool,
noexec: bool,
}
impl Mount {
pub fn read_only(host: impl Into<PathBuf>, jail: impl Into<PathBuf>) -> Self {
Self {
host: host.into(),
jail: jail.into(),
writable: false,
nosuid: false,
noexec: false,
}
}
pub fn read_write(host: impl Into<PathBuf>, jail: impl Into<PathBuf>) -> Self {
Self {
writable: true,
nosuid: true,
..Self::read_only(host, jail)
}
}
#[must_use]
pub const fn nosuid(mut self) -> Self {
self.nosuid = true;
self
}
#[must_use]
pub const fn allow_setuid(mut self) -> Self {
self.nosuid = false;
self
}
#[must_use]
pub const fn noexec(mut self) -> Self {
self.noexec = true;
self
}
#[must_use]
pub fn host_path(&self) -> &Path {
&self.host
}
#[must_use]
pub fn jail_path(&self) -> &Path {
&self.jail
}
#[must_use]
pub const fn is_writable(&self) -> bool {
self.writable
}
#[must_use]
pub const fn is_nosuid(&self) -> bool {
self.nosuid
}
#[must_use]
pub const fn is_noexec(&self) -> bool {
self.noexec
}
pub(crate) fn validate_shape(&self) -> Result<()> {
if !self.host.is_absolute() {
return Err(Error::InvalidArgument(format!(
"mount source '{}' must be an absolute path",
self.host.display()
)));
}
let clean = self.jail.components().all(|component| {
matches!(
component,
std::path::Component::RootDir | std::path::Component::Normal(_)
)
});
if !self.jail.is_absolute() || !clean || self.jail == Path::new("/") {
return Err(Error::InvalidArgument(format!(
"mount target '{}' must be an absolute path below / with no '..'",
self.jail.display()
)));
}
Ok(())
}
pub(crate) fn validate(&self) -> Result<()> {
if !self.host.is_absolute() || !self.host.is_dir() {
return Err(Error::InvalidArgument(format!(
"mount source '{}' must be an existing absolute directory",
self.host.display()
)));
}
self.validate_shape()
}
pub(crate) fn options(&self) -> Vec<&'static str> {
let mut options = vec![if self.writable { "rw" } else { "ro" }];
if self.nosuid {
options.push("nosuid");
}
if self.noexec {
options.push("noexec");
}
options
}
}
#[allow(
clippy::redundant_pub_crate,
reason = "bridge lifecycle is a sibling module; keep this helper crate-internal"
)]
pub(super) fn mount_nullfs(root: &Path, mount: &Mount) -> Result<PathBuf> {
mount.validate()?;
let (host, jail) = (&mount.host, &mount.jail);
let canonical_host = host.canonicalize()?;
let canonical_root = root.canonicalize()?;
reject_self_mount(&canonical_host, &canonical_root, host)?;
let target = root.join(jail.strip_prefix("/").unwrap_or(jail));
crate::blueprint::context::reject_symlink_ancestors(root, &target)?;
std::fs::create_dir_all(&target)?;
let canonical_target: PathBuf = target.canonicalize()?;
if !canonical_target.starts_with(&canonical_root) {
return Err(Error::InvalidArgument(format!(
"mount target '{}' escapes the container root",
jail.display()
)));
}
let mut command = std::process::Command::new("/sbin/mount_nullfs");
for option in mount.options() {
command.args(["-o", option]);
}
let output = command
.arg(&canonical_host)
.arg(&canonical_target)
.output()?;
if !output.status.success() {
return Err(Error::JailCreationFailed(format!(
"mount_nullfs {} {}: {}",
canonical_host.display(),
canonical_target.display(),
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(canonical_target)
}
fn reject_self_mount(canonical_host: &Path, canonical_root: &Path, host: &Path) -> Result<()> {
if canonical_root.starts_with(canonical_host) {
return Err(Error::InvalidArgument(format!(
"mount source '{}' contains the container root '{}'",
host.display(),
canonical_root.display()
)));
}
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct Limits {
resources: ResourceConfig,
}
impl Limits {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn memory(mut self, amount: impl Into<String>) -> Self {
self.resources.memory = Some(amount.into());
self
}
#[must_use]
pub fn swap(mut self, amount: impl Into<String>) -> Self {
self.resources.swap = Some(amount.into());
self
}
#[must_use]
pub fn cpu_percent(mut self, percent: u32) -> Self {
self.resources.cpu = Some(percent.to_string());
self
}
#[must_use]
pub const fn max_processes(mut self, count: u32) -> Self {
self.resources.maxproc = Some(count);
self
}
#[must_use]
pub const fn max_threads(mut self, count: u32) -> Self {
self.resources.maxthreads = Some(count);
self
}
#[must_use]
pub const fn open_files(mut self, count: u32) -> Self {
self.resources.openfiles = Some(count);
self
}
#[must_use]
pub fn cpus(mut self, list: impl Into<String>) -> Self {
self.resources.cpuset = Some(list.into());
self
}
#[must_use]
pub fn rule(mut self, rule: impl Into<String>) -> Self {
self.resources.rules.push(rule.into());
self
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.resources.is_empty()
}
pub(crate) const fn resources(&self) -> &ResourceConfig {
&self.resources
}
}
#[derive(Debug, Clone)]
pub struct ContainerSpec {
name: String,
release: String,
hostname: Option<String>,
network: Network,
limits: Limits,
mounts: Vec<Mount>,
labels: BTreeMap<String, String>,
boot: bool,
raw_sockets: bool,
chflags: bool,
nameservers: Vec<IpAddr>,
params: Vec<String>,
}
impl ContainerSpec {
pub fn new(name: impl Into<String>, release: impl Into<String>) -> Self {
Self {
name: name.into(),
release: release.into(),
hostname: None,
network: Network::default(),
limits: Limits::default(),
mounts: Vec::new(),
labels: BTreeMap::new(),
boot: false,
raw_sockets: false,
chflags: false,
nameservers: Vec::new(),
params: Vec::new(),
}
}
#[must_use]
pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
self.hostname = Some(hostname.into());
self
}
#[must_use]
pub fn network(mut self, network: Network) -> Self {
self.network = network;
self
}
#[must_use]
pub fn nameserver(mut self, server: impl Into<IpAddr>) -> Self {
self.nameservers.push(server.into());
self
}
#[must_use]
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub fn mount(mut self, mount: Mount) -> Self {
self.mounts.push(mount);
self
}
#[must_use]
pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.labels.insert(key.into(), value.into());
self
}
#[must_use]
pub const fn boot(mut self) -> Self {
self.boot = true;
self
}
#[must_use]
pub const fn allow_raw_sockets(mut self) -> Self {
self.raw_sockets = true;
self
}
#[must_use]
pub const fn allow_chflags(mut self) -> Self {
self.chflags = true;
self
}
#[must_use]
pub fn jail_param(mut self, param: impl Into<String>) -> Self {
self.params.push(param.into());
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn release(&self) -> &str {
&self.release
}
}
#[derive(Debug)]
pub struct Container {
layout: Arc<Layout>,
name: String,
jid: i32,
root: PathBuf,
dataset: Option<String>,
destroy_on_drop: bool,
}
impl Container {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn jid(&self) -> i32 {
self.jid
}
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
#[must_use]
pub fn dataset(&self) -> Option<&str> {
self.dataset.as_deref()
}
pub fn exec(&self, exec: Exec<'_>) -> Result<ExecOutput> {
Error::require_root("running a command in a container")?;
exec::run(self.jid, exec)
}
pub fn copy_in(&self, host_path: impl AsRef<Path>, jail_path: impl AsRef<str>) -> Result<()> {
Error::require_root("copying into a container")?;
transfer(
©::Side::Host(host_path.as_ref()),
©::Side::Jail(self.jail_side(jail_path.as_ref())),
true,
)
}
pub fn copy_out(&self, jail_path: impl AsRef<str>, host_path: impl AsRef<Path>) -> Result<()> {
Error::require_root("copying out of a container")?;
transfer(
©::Side::Jail(self.jail_side(jail_path.as_ref())),
©::Side::Host(host_path.as_ref()),
true,
)
}
pub fn commit(&self, release: &str) -> Result<crate::Release> {
Error::require_root("committing a container")?;
let zfs = self.layout.zfs().ok_or(Error::ZfsNotEnabled)?;
let dataset = self.dataset.as_deref().ok_or(Error::ZfsNotEnabled)?;
crate::release::commit_dataset(&self.layout, &zfs, dataset, release)
}
pub fn keep(&mut self) -> Result<()> {
registry::disown(&self.layout, &self.name)?;
self.destroy_on_drop = false;
Ok(())
}
pub fn hand_over(&mut self, pid: u32) -> Result<()> {
registry::hand_over(&self.layout, &self.name, pid)?;
self.destroy_on_drop = false;
Ok(())
}
pub fn destroy(mut self) -> Result<()> {
self.destroy_on_drop = false;
teardown::destroy(&self.layout, &self.name)
}
fn jail_side(&self, path: &str) -> JailSide {
JailSide {
jid: Some(self.jid),
root: self.root.clone(),
path: path.to_string(),
}
}
}
impl Drop for Container {
fn drop(&mut self) {
if self.destroy_on_drop {
let _ = teardown::destroy(&self.layout, &self.name);
}
}
}
impl Host {
pub fn create(&self, spec: &ContainerSpec) -> Result<Container> {
create::create(self.layout(), spec)
}
pub fn open(&self, name: &str) -> Result<Container> {
Error::require_root("opening a container")?;
validate_container_name(name)?;
let jid = crate::jail::jail_getid(name).map_err(|_| Error::JailNotRunning(name.into()))?;
let record = registry::load(self.layout(), name);
let root = record
.as_ref()
.map_or_else(|| self.layout().container_root(name), |r| r.root.clone());
Ok(Container {
layout: Arc::clone(self.layout()),
name: name.to_string(),
jid,
root,
dataset: record.and_then(|r| r.dataset),
destroy_on_drop: false,
})
}
pub fn destroy_container(&self, name: &str) -> Result<()> {
teardown::destroy(self.layout(), name)
}
pub fn containers(&self) -> Result<Vec<ContainerInfo>> {
Ok(registry::list(self.layout()))
}
pub fn orphans(&self, selector: &Selector) -> Result<Vec<ContainerInfo>> {
Ok(self
.containers()?
.into_iter()
.filter(|info| info.is_orphan() && selector.matches(info))
.collect())
}
pub fn reap_orphans(&self, selector: &Selector) -> Result<Vec<String>> {
Error::require_root("reaping orphaned containers")?;
let mut reaped = Vec::new();
let mut first_error = None;
for orphan in self.orphans(selector)? {
match self.destroy_container(&orphan.name) {
Ok(()) => reaped.push(orphan.name),
Err(e) => {
first_error.get_or_insert(e);
}
}
}
match first_error {
Some(e) => Err(e),
None => Ok(reaped),
}
}
}
pub fn validate_container_name(name: &str) -> Result<()> {
validate_name("container", name)?;
if name.contains('.') {
return Err(Error::ConfigValidation(format!(
"container name '{name}' must not contain '.' (jail(8) reads it as a child jail)"
)));
}
Ok(())
}
#[cfg(test)]
mod tests;