> = std::sync::OnceLock::new();
+ if !had_ping
+ && let Some(max) = *SELF_PING_MAX.get_or_init(|| fs::read_to_string("/proc/self/gid_map").ok().map(|m| ping_group_max(&m)))
+ {
+ if max < DEFAULT_PING_MAX
+ && let Some(s) = host.sysctls.iter_mut().find(|s| s.path == "net/ipv4/ping_group_range")
+ {
+ s.value = format!("0 {max}");
+ }
+ }
}
let bridged = !spec.net.bridge.is_empty() && spec.flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0 && prepared.net_join.is_none();
let mut go = None;
@@ -570,10 +665,24 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
e,
}
};
+ if !cloned.into_cgroup {
+ // clone(2) cannot put the child in its cgroup: do it now, before it
+ // mounts anything and its limits have to apply. The child waits on
+ // the pipe until this write is done.
+ fs::write(cgroup.join("cgroup.procs"), pid.to_string())
+ .map_err(|e| kill_child(io::Error::new(e.kind(), format!("cgroup: {e}"))))?;
+ if let Some(go_fd) = &cgroup_go {
+ // SAFETY: one byte to a pipe we own: "you are in your cgroup".
+ if unsafe { libc::write(go_fd.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 {
+ return Err(kill_child(io::Error::last_os_error()));
+ }
+ }
+ }
+ drop(cgroup_go);
// Before `pivot_root`, an exec joining its mount namespace gets the
// agent's `/etc/passwd`, and an image user such as `dev` is unknown
// (#311). So the start waits for the root, briefly (ROOT_READY_WAIT):
@@ -679,15 +810,28 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result
{}
Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))),
- Ok(RootWord::NotYet) if prepared.tty => match root_word(root_ready.as_raw_fd(), None, &mut began_fill) {
- Ok(RootWord::Ready) => {}
- Ok(_) => return Err(kill_child(io::Error::other(NOT_READY))),
- Err(e) => return Err(kill_child(e)),
- },
+ Ok(RootWord::NotYet) if prepared.tty => {
+ let word = if began_fill {
+ root_word(root_ready.as_raw_fd(), None, &mut began_fill)
+ } else {
+ match root_word(root_ready.as_raw_fd(), Some(TTY_READY_WAIT), &mut began_fill) {
+ Ok(RootWord::NotYet) if began_fill => root_word(root_ready.as_raw_fd(), None, &mut began_fill),
+ other => other,
+ }
+ };
+ filling.set(began_fill);
+ match word {
+ Ok(RootWord::Ready) => {}
+ Ok(RootWord::NotYet) => return Err(kill_child(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container root"))),
+ Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))),
+ Err(e) => return Err(kill_child(e)),
+ }
+ }
Ok(RootWord::NotYet) => starting.set(true),
Err(e) => return Err(kill_child(e)),
}
let mut veths = Vec::new();
+ let mut uplinks = Vec::new();
// Names, AAAA records and `--dns` servers to give the DNS server, once
// nothing can fail any more: a failed start must not leave its names
// answering (#325). Nothing is answered before then anyway, since the
@@ -696,7 +840,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
f,
+ None => {
+ opened = std::fs::File::open(format!("/proc/{pid}/ns/net"))?;
+ &opened
}
- Ok(())
- })
+ };
+ net.dns.serve_in(ns, pid, spec.net.bridge)?;
+ // User networks it joins once it runs: their names
+ // answer from its first lookup (#449).
+ for b in net_opts::values(spec.net.opts, net_opts::DNS_BRIDGE) {
+ net.dns.serve_in(ns, pid, b)?;
+ }
+ Ok(())
});
if let Some(e) = in_err {
net.dns.drop_container(pid);
@@ -766,7 +918,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
, paths: &Paths, net: NetCtx<'_>) -> io::Result
io::Result {
+fn plain_upper(base: &Path, writable: bool) -> io::Result {
let marker = base.join(PLAIN_UPPER);
if marker.exists() {
return Ok(true);
@@ -826,8 +980,22 @@ fn plain_upper(base: &Path) -> io::Result {
// written into it since this one looked for the marker.
return Ok(marker.exists());
}
- fs::write(marker, b"")?;
- Ok(true)
+ match fs::write(marker, b"") {
+ Ok(()) => Ok(true),
+ Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => Ok(true),
+ Err(e) => Err(e),
+ }
+}
+
+/// Marks a writable layer that `kiri import` brought in whole as plain
+/// (see `plain_upper`): it holds whole files, whole directories, whiteouts
+/// and opaque marks, and no overlayfs redirects or metadata-only copies
+/// (`copy` strips those attributes). Without the mark its first mount would
+/// find it already written to and keep the kernel's defaults, under which
+/// later writes may redirect directories that `docker diff` and `commit`
+/// can't read.
+pub(super) fn mark_plain_upper(base: &Path) -> io::Result<()> {
+ fs::write(base.join(PLAIN_UPPER), b"")
}
/// The overlayfs features to mount with, whatever the kernel's defaults
@@ -844,16 +1012,55 @@ fn overlay_features(plain: bool) -> &'static str {
if plain { "index=off,redirect_dir=nofollow,metacopy=off" } else { "index=off" }
}
+/// Verifies that a writable container's backing directory and mounted overlay
+/// root are not read-only (`ST_RDONLY` / `emergency_ro`). Linux `overlayfs`
+/// silently falls back to mounting read-only (returning 0 from `mount(2)`)
+/// when `work/work` fails on `EROFS` or `EEXIST` (#768).
+pub(super) fn ensure_writable_rootfs(base: &Path, rootfs: &Path) -> io::Result<()> {
+ let kind = match (sys::detect_readonly_fs(base), sys::detect_readonly_fs(rootfs)) {
+ (Some(a), Some(b)) => Some(a.merge(b)),
+ (Some(a), None) | (None, Some(a)) => Some(a),
+ (None, None) => None,
+ };
+ match kind {
+ Some(k) => Err(sys::readonly_storage_error(k)),
+ None => Ok(()),
+ }
+}
+
+fn map_rofs_error(base: &Path, writable: bool, err: io::Error) -> io::Error {
+ if writable && err.raw_os_error() == Some(libc::EROFS) {
+ let kind = sys::detect_readonly_fs(base).unwrap_or(sys::ReadOnlyKind::ReadOnly);
+ return sys::readonly_storage_error(kind);
+ }
+ err
+}
+
/// Mounts a container's root: its image layers under its writable layer,
/// at `//rootfs`. Returns that path. Only `roots` calls
/// this, which keeps it to one mount per container.
-pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str]) -> io::Result {
+pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writable: bool) -> io::Result {
valid_id(id)?;
let base = paths.containers.join(id);
+ let fresh_base = !base.exists();
+ if !fresh_base
+ && writable
+ && let Some(kind) = sys::detect_readonly_fs(&base)
+ {
+ return Err(sys::readonly_storage_error(kind));
+ }
let (upper, work, rootfs) = (base.join("upper"), base.join("work"), base.join("rootfs"));
- let _ = sys::umount_lazy(&rootfs);
- for d in [&upper, &work, &rootfs] {
- fs::create_dir_all(d)?;
+ if fresh_base {
+ for d in [&upper, &work, &rootfs] {
+ fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?;
+ }
+ } else {
+ let _ = sys::umount_lazy(&rootfs);
+ for d in [&upper, &work, &rootfs] {
+ if !d.is_dir() {
+ fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?;
+ }
+ }
}
// Lower dirs are relative to the agent's working directory (the layer
// store), which keeps the option string short enough for many layers.
@@ -878,11 +1085,39 @@ pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str]) -> io
// fails at exec, as Docker's does, instead of failing to mount.
if lower.is_empty() {
let empty = base.join("empty");
- fs::create_dir_all(&empty)?;
+ if !empty.is_dir() {
+ fs::create_dir_all(&empty).map_err(|e| map_rofs_error(&base, writable, e))?;
+ }
lower.push(empty.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "container folder is not UTF-8"))?.to_owned());
}
- let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain_upper(&base)?));
- sys::mount_overlay(&rootfs, &lower, &rest, 0)?;
+ let plain = if fresh_base {
+ match fs::write(base.join(PLAIN_UPPER), b"") {
+ Ok(()) => true,
+ Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => true,
+ Err(e) => return Err(map_rofs_error(&base, writable, e)),
+ }
+ } else {
+ plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))?
+ };
+ let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain));
+ sys::mount_overlay(&rootfs, &lower, &rest, 0).map_err(|e| map_rofs_error(&base, writable, e))?;
+ if writable {
+ let ro_err = if fresh_base {
+ // `create_dir_all` already verified `base` is writable; one `statvfs`
+ // on `rootfs` catches overlayfs's silent read-only fallback (#768).
+ if sys::is_statvfs_readonly(&rootfs).unwrap_or(false) {
+ ensure_writable_rootfs(&base, &rootfs).err()
+ } else {
+ None
+ }
+ } else {
+ ensure_writable_rootfs(&base, &rootfs).err()
+ };
+ if let Some(e) = ro_err {
+ super::roots::unmount(&rootfs);
+ return Err(e);
+ }
+ }
Ok(rootfs)
}
@@ -908,10 +1143,19 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
let mut prepared = prepare(spec.argv, spec.env, spec.cwd, spec.user, None, spec.flags, spec.caps)?;
// The container's ulimits and groups apply to its execs too, as with runc.
let host = super::hostopts::parse(spec.opts)?;
- prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, nodes: Vec::new() };
+ prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, ..Default::default() };
// An exec runs under its container's profile, not the default.
prepared.profile = profile.to_vec();
let (parent_io, child_io) = stdio(&prepared)?;
+ // The child waits here until the agent has moved it into its cgroup, for
+ // a start that clone3 could not place there itself.
+ let cgroup_go = if sys::clone3_works() {
+ None
+ } else {
+ let (child_cgroup_ready, go_fd) = sys::pipe()?;
+ prepared.cgroup_ready = Some(child_cgroup_ready);
+ Some(go_fd)
+ };
let args = CloneArgs {
flags: CLONE_INTO_CGROUP,
exit_signal: libc::SIGCHLD as u64,
@@ -931,9 +1175,8 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
// no processes. Join the one its init lives in, as runc does.
let init_cgroup;
if cloned.as_ref().is_err_and(|e| e.kind() == io::ErrorKind::ResourceBusy) {
- let rel = fs::read_to_string(format!("/proc/{target_pid}/cgroup")).unwrap_or_default();
- let rel = rel.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim_start_matches('/').to_owned();
- init_cgroup = fs::File::open(std::path::Path::new("/sys/fs/cgroup").join(&rel));
+ let (rel, dir) = proc_cgroup(&paths.cgroup_root, target_pid);
+ init_cgroup = fs::File::open(dir);
match &init_cgroup {
Ok(fd) => {
let retry = CloneArgs { cgroup: fd.as_raw_fd() as u64, ..args };
@@ -943,16 +1186,46 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
Err(e) => cloned = Err(io::Error::new(e.kind(), format!("cgroup {rel}: {e}"))),
}
}
- if let Ok(0) = cloned {
- exec_child(&prepared, &namespaces, &child_io);
+ if let Ok(c) = &cloned
+ && c.pid == 0
+ {
+ exec_child(&prepared, &namespaces, &child_io, !c.into_cgroup);
}
let restored = sys::setns(own_pid_ns.as_raw_fd(), libc::CLONE_NEWPID);
- let pid = cloned?;
- restored?;
+ drop(prepared.cgroup_ready.take());
+ let child = cloned?;
+ let pid = child.pid;
+ if let Err(e) = restored {
+ // SAFETY: killing and reaping the child we just cloned.
+ unsafe {
+ libc::kill(pid, libc::SIGKILL);
+ libc::waitpid(pid, std::ptr::null_mut(), 0);
+ }
+ return Err(e);
+ }
+ if !child.into_cgroup {
+ // clone(2) cannot put the exec in the container's cgroup: do it now,
+ // then let it join the container's namespaces.
+ if let Some(go_fd) = &cgroup_go
+ && let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, go_fd)
+ {
+ // SAFETY: killing and reaping the child we just cloned.
+ unsafe {
+ libc::kill(pid, libc::SIGKILL);
+ libc::waitpid(pid, std::ptr::null_mut(), 0);
+ }
+ return Err(e);
+ }
+ }
+ drop(cgroup_go);
drop(cgroup_fd);
let (stdin, stdout, stderr) = finish_stdio(parent_io, child_io).map_err(|e| {
- // SAFETY: killing the child we just cloned.
- unsafe { libc::kill(pid, libc::SIGKILL) };
+ // SAFETY: killing and reaping the child we just cloned so a failed or
+ // timed-out TTY setup never leaks a stuck or zombie process (#948).
+ unsafe {
+ libc::kill(pid, libc::SIGKILL);
+ libc::waitpid(pid, std::ptr::null_mut(), 0);
+ }
e
})?;
Ok(Process {
@@ -965,6 +1238,7 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
tty: prepared.tty,
dns_entries: Vec::new(),
veths: Vec::new(),
+ uplinks: Vec::new(),
netns: 0,
joins_netns: false,
seccomp: Vec::new(),
@@ -976,6 +1250,38 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
})
}
+/// The cgroup v2 directory (under `cgroup_root`) where `pid` lives, and
+/// its hierarchy-relative path for error messages.
+fn proc_cgroup(cgroup_root: &Path, pid: libc::pid_t) -> (String, PathBuf) {
+ let text = fs::read_to_string(format!("/proc/{pid}/cgroup")).unwrap_or_default();
+ cgroup_of_proc(cgroup_root, &text)
+}
+
+fn cgroup_of_proc(cgroup_root: &Path, proc_cgroup: &str) -> (String, PathBuf) {
+ let rel = proc_cgroup.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim().trim_start_matches('/').to_owned();
+ let dir = if rel.is_empty() { cgroup_root.to_path_buf() } else { cgroup_root.join(&rel) };
+ (rel, dir)
+}
+
+/// Moves a child started with clone(2) into `cgroup`, then lets it go on.
+/// `init_pid`: the container's init, whose cgroup is used when the
+/// container's own cgroup takes no processes (Docker in Docker, BuildKit
+/// move theirs into sub-cgroups), as runc does.
+fn move_child(cgroup: &Path, cgroup_root: &Path, pid: libc::pid_t, init_pid: libc::pid_t, go: &OwnedFd) -> io::Result<()> {
+ if let Err(e) = fs::write(cgroup.join("cgroup.procs"), pid.to_string()) {
+ if e.kind() != io::ErrorKind::ResourceBusy {
+ return Err(e);
+ }
+ let (rel, dir) = proc_cgroup(cgroup_root, init_pid);
+ fs::write(dir.join("cgroup.procs"), pid.to_string()).map_err(|e| io::Error::new(e.kind(), format!("joining cgroup {rel}: {e}")))?;
+ }
+ // SAFETY: one byte to a pipe we own: "you are in your cgroup".
+ if unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(())
+}
+
/// Unmounts a container and, for `--rm`, deletes its writable layer.
/// Runs after the exit has been reported, off the critical path. Execs have
/// nothing to undo.
@@ -992,11 +1298,12 @@ pub fn oom_killed(p: &Process) -> bool {
/// deletes them (see `net::retire`).
pub fn teardown(p: &Process, netns_shared: bool) {
if netns_shared {
- for v in &p.veths {
+ for (_, v) in &p.veths {
let _ = net::detach(v);
}
} else {
- net::retire(&p.veths);
+ let host_veths: Vec = p.veths.iter().map(|(_, v)| v.clone()).collect();
+ net::retire(&host_veths);
}
if let Some(t) = &p.teardown {
undo_now(t, t.remove);
@@ -1029,6 +1336,13 @@ fn undo_now(t: &Teardown, remove_files: bool) {
let _ = fs::remove_dir_all(PathBuf::from("/run/kiri").join(id));
}
remove_cgroup(&t.cgroup);
+ if t.cgroup.exists() {
+ kill_cgroup(&t.cgroup);
+ remove_cgroup(&t.cgroup);
+ }
+ for path in &t.loop_mounts {
+ super::volmount::release_loop(path);
+ }
if remove_files {
super::roots::remove(&t.base);
}
@@ -1091,15 +1405,22 @@ pub fn sweep(paths: &Paths, cgroup: &std::path::Path) {
remove_cgroup(&cg);
}
}
- // Host-side veths are kv<9 characters of the id><4 hex digits>.
+ // Host-side veths are kv<9 characters of the id><4 hex digits> or kx<9>.
let Ok(links) = fs::read_dir("/sys/class/net") else { return };
for link in links.flatten() {
let Ok(name) = link.file_name().into_string() else { continue };
- let ours = name.strip_prefix("kv").and_then(|rest| rest.get(..9)).is_some_and(|p| ids.iter().any(|id| id.starts_with(p)));
+ let ours = name
+ .strip_prefix("kv")
+ .or_else(|| name.strip_prefix("kx"))
+ .and_then(|rest| rest.get(..9))
+ .is_some_and(|p| ids.iter().any(|id| id.starts_with(p)));
if ours {
let _ = net::detach(&name);
}
}
+ // Detach any loopback ext4 image mounted for `kiri-k8s` on a ZFS host so
+ // the filesystem flushes cleanly and no orphan loop mount remains.
+ super::volmount::release_k8s_ext4_if_mounted();
}
/// Kills every process in a cgroup and below it, and waits (briefly) until
@@ -1206,8 +1527,11 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname:
nodev_root: false,
shm_size: 64 << 20,
init: flags & run_flags::INIT != 0,
+ cgroupns_host: false,
+ timer_slack_ns: None,
host: HostApplied::default(),
root_ready: None,
+ cgroup_ready: None,
})
}
@@ -1246,18 +1570,18 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8;
}
}
}
- // On a Linux host there is no loopback redirect; host.docker.internal
- // points at the bridge gateway, like Docker's host-gateway, so it reaches
- // host services on 0.0.0.0 but not ones bound only to 127.0.0.1.
- // A host-network container is on the host already, loopback included,
- // so there the name is the loopback address.
+ // On a plain Linux host there is no loopback redirect; host.docker.internal
+ // points at the bridge gateway (or 127.0.0.1 for `--network host`).
+ // On Windows (WSL 2) when `kiri hostrelay` is active (`192.168.65.254` on
+ // `lo`), host.docker.internal / host.kiri.internal / host-gateway point at
+ // `192.168.65.254` for all networks (default bridge, user networks, and
+ // `--network host`), matching Docker Desktop.
let host_addr = net::ip_str(net::HOST_ADDR);
let host_net = spec.flags & run_flags::NET_HOST != 0;
- let gateway = if host_net { "127.0.0.1".to_owned() } else { net::ip_str(spec.net.gateway) };
- let map_host = super::transport::is_host_process() && (host_net || spec.net.gateway != [0; 4]);
+ let mapped = host_etc_target(super::transport::is_host_process(), net::wsl_host_relay_active(), host_net, spec.net.gateway);
for line in spec.net.extra_hosts.iter() {
- if map_host {
- hosts.push_str(&line.replace(&host_addr, &gateway));
+ if let Some(target) = mapped.as_deref() {
+ hosts.push_str(&line.replace(&host_addr, target));
} else {
hosts.push_str(line);
}
@@ -1274,6 +1598,25 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8;
Ok(out)
}
+/// Target IP replacing `net::HOST_ADDR` in container `/etc/hosts` lines.
+/// Returns `None` in the macOS VM (keep `198.19.248.254`) and for `--network none`
+/// on a plain Linux host.
+fn host_etc_target(host_process: bool, wsl_relay_active: bool, host_net: bool, gateway: [u8; 4]) -> Option {
+ if !host_process {
+ return None;
+ }
+ if wsl_relay_active {
+ return Some(net::ip_str(net::WSL_HOST_ADDR));
+ }
+ if host_net {
+ Some("127.0.0.1".to_owned())
+ } else if gateway != [0; 4] {
+ Some(net::ip_str(gateway))
+ } else {
+ None
+ }
+}
+
/// The container's resolv.conf. On a user-defined network the embedded DNS
/// at 127.0.0.11 is the only nameserver, as with Docker (it forwards to
/// `--dns` servers); elsewhere `--dns` servers replace the VM's.
@@ -1288,6 +1631,58 @@ fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]], relay: bool) -> bool {
embedded_dns_if(spec, || relay || net::local_resolver(upstream))
}
+/// In the VM, a `--network host` container's resolver: the agent's on the
+/// default bridge's gateway, which is one of the VM's own addresses, so the
+/// container reaches it. As the default bridge's containers do, its
+/// lookups then go through the Mac when the Mac's resolver for the VM
+/// network doesn't answer (dns.rs), where asking that resolver directly
+/// would just fail. Not on a Linux host (the container runs in the host's
+/// network namespace and reaches `127.0.0.53` on host loopback directly),
+/// nor with `--dns`. On a fresh VM before any bridged container has
+/// started, `kiri0` is brought up on demand with the default bridge's
+/// gateway and prefix. None, the VM's upstream as before, when the bridge
+/// can't be brought up or the agent can't listen there.
+fn host_network_resolver(spec: &RunSpec<'_>, bridges: &mut net::Bridges, dns: &mut super::dns::Dns) -> Option<[u8; 4]> {
+ if !host_network_uses_agent(spec, dns.relay) {
+ return None;
+ }
+ let gateway = match net::bridge_ipv4(DEFAULT_BRIDGE) {
+ Some(gw) => gw,
+ None => {
+ let (gw, prefix) = host_bridge_addr(spec);
+ if let Err(e) = bridges.ensure(DEFAULT_BRIDGE, Some(gw), prefix, None) {
+ eprintln!("kiri-init: dns: cannot bring up {DEFAULT_BRIDGE} for host-network DNS: {e}");
+ return None;
+ }
+ gw
+ }
+ };
+ dns.serve_or_warn(DEFAULT_BRIDGE, gateway).then_some(gateway)
+}
+
+/// The default bridge, where the agent's resolver answers on the gateway.
+const DEFAULT_BRIDGE: &str = "kiri0";
+const DEFAULT_BRIDGE_GATEWAY: [u8; 4] = [172, 17, 0, 1];
+const DEFAULT_BRIDGE_PREFIX: u8 = 16;
+
+/// Gateway and prefix for bringing up `DEFAULT_BRIDGE` when a `--network host`
+/// container starts before any bridged one: what the daemon sent on `spec.net`
+/// when present, falling back to Docker's default 172.17.0.1/16.
+fn host_bridge_addr(spec: &RunSpec<'_>) -> ([u8; 4], u8) {
+ if spec.net.gateway == [0; 4] {
+ (DEFAULT_BRIDGE_GATEWAY, DEFAULT_BRIDGE_PREFIX)
+ } else {
+ let prefix = if spec.net.prefix == 0 { DEFAULT_BRIDGE_PREFIX } else { spec.net.prefix };
+ (spec.net.gateway, prefix)
+ }
+}
+
+/// Whether a container's lookups go to the agent's resolver on the default
+/// bridge because it shares the VM's own network (see `host_network_resolver`).
+fn host_network_uses_agent(spec: &RunSpec<'_>, relay: bool) -> bool {
+ relay && spec.flags & run_flags::NET_HOST != 0 && net_opts::values(spec.net.opts, net_opts::NAMESERVER).next().is_none()
+}
+
/// `embedded_dns`, with `through_agent` saying whether the default bridge's
/// lookups go through the agent (asked only when it matters).
fn embedded_dns_if(spec: &RunSpec<'_>, through_agent: impl FnOnce() -> bool) -> bool {
@@ -1351,12 +1746,17 @@ fn resolv_conf(spec: &RunSpec<'_>, upstream: &[[u8; 4]], embedded: Option<[u8; 4
for d in servers {
resolv.push_str(&format!("nameserver {d}\n"));
}
- } else if upstream.is_empty() {
- // The VM has no lease yet; a public resolver beats none.
- resolv.push_str("nameserver 1.1.1.1\n");
} else {
- for d in upstream {
+ let host_net = spec.flags & run_flags::NET_HOST != 0;
+ let mut wrote = false;
+ for d in upstream.iter().filter(|d| host_net || d[0] != 127) {
resolv.push_str(&format!("nameserver {}\n", net::ip_str(*d)));
+ wrote = true;
+ }
+ if !wrote {
+ // The VM has no lease yet, or only a loopback stub remained
+ // without an agent listener; a public resolver beats none.
+ resolv.push_str("nameserver 1.1.1.1\n");
}
}
// `--dns-search .` means no search domains.
@@ -1404,7 +1804,7 @@ pub(super) fn use_embedded_dns(id: &str, is_kiri: impl Fn([u8; 4]) -> bool) -> i
}
/// One mount, resolved before clone.
-struct Mount {
+pub(super) struct Mount {
/// A guest path, or None for a tmpfs.
source: Option,
/// Relative to the container root (the child mounts before pivot_root).
@@ -1418,6 +1818,18 @@ struct Mount {
tmpfs_opts: Option,
/// tmpfs mount flags (`noexec`, `nosuid`, `nodev`, `ro`).
tmpfs_flags: libc::c_ulong,
+ /// Loopback ext4 volume mount acquired for this container (released on stop).
+ loop_mount: Option,
+}
+
+impl Mount {
+ pub(super) fn is_tmpfs(&self) -> bool {
+ self.tmpfs_opts.is_some()
+ }
+
+ pub(super) fn is_copy_up(&self) -> bool {
+ self.copy_up
+ }
}
/// `source\ttarget\tflags` entries. Flags: `ro`, `create` (make the source
@@ -1425,52 +1837,101 @@ struct Mount {
/// flags (`noexec`, `exec`, `nosuid`, …; later ones win). A volume with
/// driver options adds `\ttype\tdevice\tflags(hex)\tdata`, and is mounted
/// at its source first.
-fn parse_mounts(list: StrList<'_>) -> io::Result> {
+pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> {
let mut out = Vec::with_capacity(list.len());
- for m in list.iter() {
- let bad = || io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}"));
- // Three fields: source, target, flags. Seven: the same, then a
- // volume's driver options (`type`, `device`, flags, data). Any other
- // count is a separator inside a field — a target alone comes from an
- // image's VOLUME line — and is refused here as well as at the host.
- let f: Vec<&str> = m.split('\t').collect();
- if f.len() != 3 && f.len() != 7 {
- return Err(bad());
- }
- let (src, given_target, words) = (f[0], f[1], f[2]);
- let flags: Vec<&str> = words.split(',').filter(|f| !f.is_empty()).collect();
- if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") {
- return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}")));
- }
- let rel = given_target.trim_start_matches('/');
- let target = CString::new(if rel.is_empty() { "." } else { rel })?;
- let ro = flags.contains(&"ro");
- if flags.contains(&"tmpfs") {
- let opts: Vec<&str> = flags.iter().copied().filter(|f| f.contains('=')).collect();
- let opts = if opts.is_empty() { "mode=1777".to_owned() } else { opts.join(",") };
- let tmpfs_flags = tmpfs_flags(&flags);
- let ro = tmpfs_flags & libc::MS_RDONLY != 0;
- out.push(Mount { source: None, target, ro, dir: true, copy_up: false, tmpfs_opts: Some(CString::new(opts)?), tmpfs_flags });
- continue;
+ let release_acquired = |mounts: &[Mount]| {
+ for m in mounts {
+ if let Some(path) = &m.loop_mount {
+ super::volmount::release_loop(path);
+ }
}
- // A missing source becomes a directory, as Docker does; one that is
- // there already (a file such as /etc/hostname, too) is used as it is.
- if flags.contains(&"create") && fs::symlink_metadata(src).is_err() {
- fs::create_dir_all(src)?;
- }
- if f.len() == 7 && !f[3].is_empty() {
- super::volmount::ensure(src, f[3], f[4], f[5], f[6])?;
- }
- let meta = fs::metadata(src).map_err(|e| io::Error::new(e.kind(), format!("mount source {src}: {e}")))?;
- out.push(Mount {
- source: Some(sys::cstr(src)?),
- target,
- ro,
- dir: meta.is_dir(),
- copy_up: flags.contains(&"copyup"),
- tmpfs_opts: None,
- tmpfs_flags: 0,
- });
+ };
+ let parsed = (|| -> io::Result<()> {
+ for m in list.iter() {
+ let bad = || io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}"));
+ // Three fields: source, target, flags. Seven: the same, then a
+ // volume's driver options (`type`, `device`, flags, data). Any other
+ // count is a separator inside a field — a target alone comes from an
+ // image's VOLUME line — and is refused here as well as at the host.
+ let f: Vec<&str> = m.split('\t').collect();
+ if f.len() != 3 && f.len() != 7 {
+ return Err(bad());
+ }
+ let (src, given_target, words) = (f[0], f[1], f[2]);
+ let flags: Vec<&str> = words.split(',').filter(|f| !f.is_empty()).collect();
+ if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}")));
+ }
+ let rel = given_target.trim_start_matches('/');
+ let target = CString::new(if rel.is_empty() { "." } else { rel })?;
+ let ro = flags.contains(&"ro");
+ if flags.contains(&"tmpfs") {
+ let opts: Vec<&str> = flags.iter().copied().filter(|f| f.contains('=')).collect();
+ let opts = if opts.is_empty() { "mode=1777".to_owned() } else { opts.join(",") };
+ let tmpfs_flags = tmpfs_flags(&flags);
+ let ro = tmpfs_flags & libc::MS_RDONLY != 0;
+ out.push(Mount { source: None, target, ro, dir: true, copy_up: false, tmpfs_opts: Some(CString::new(opts)?), tmpfs_flags, loop_mount: None });
+ continue;
+ }
+ // A missing source becomes a directory, as Docker does; one that is
+ // there already (a file such as /etc/hostname, too) is used as it is.
+ // Never create a directory at /etc/localtime or /etc/timezone (#938).
+ let norm = lexical_normalize(Path::new(src));
+ if norm == Path::new("/etc/localtime") {
+ if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir())
+ || (flags.contains(&"create") && fs::metadata(src).is_err())
+ {
+ super::localtime::ensure_localtime()?;
+ }
+ } else if norm == Path::new("/etc/timezone") {
+ if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir())
+ || (flags.contains(&"create") && fs::metadata(src).is_err())
+ {
+ super::localtime::ensure_timezone()?;
+ }
+ } else if flags.contains(&"create") && fs::symlink_metadata(src).is_err() {
+ fs::create_dir_all(src)?;
+ }
+ let mut loop_mount = None;
+ if f.len() == 7 && !f[3].is_empty() {
+ super::volmount::ensure(src, f[3], f[4], f[5], f[6])?;
+ } else if super::volmount::ensure_k8s_ext4(src)? {
+ loop_mount = Some(src.to_owned());
+ }
+ let meta = match fs::metadata(src) {
+ Ok(meta) => meta,
+ Err(e) => {
+ if let Some(path) = &loop_mount {
+ super::volmount::release_loop(path);
+ }
+ return Err(io::Error::new(e.kind(), format!("mount source {src}: {e}")));
+ }
+ };
+ let source = match sys::cstr(src) {
+ Ok(s) => s,
+ Err(e) => {
+ if let Some(path) = &loop_mount {
+ super::volmount::release_loop(path);
+ }
+ return Err(e);
+ }
+ };
+ out.push(Mount {
+ source: Some(source),
+ target,
+ ro,
+ dir: meta.is_dir(),
+ copy_up: flags.contains(&"copyup"),
+ tmpfs_opts: None,
+ tmpfs_flags: 0,
+ loop_mount,
+ });
+ }
+ Ok(())
+ })();
+ if let Err(e) = parsed {
+ release_acquired(&out);
+ return Err(e);
}
// Parents before what's under them, as Docker sorts mounts: the CLI sends
// `-v` in no set order, and `/app/node_modules` mounted before `/app`
@@ -1487,7 +1948,7 @@ fn depth(target: &CStr) -> usize {
/// A tmpfs's mount flags from its flag words, in order, so `exec` after
/// Docker's default `noexec` wins.
-fn tmpfs_flags(words: &[&str]) -> libc::c_ulong {
+pub(super) fn tmpfs_flags(words: &[&str]) -> libc::c_ulong {
let mut f = 0;
for w in words {
match *w {
@@ -1507,17 +1968,264 @@ fn tmpfs_flags(words: &[&str]) -> libc::c_ulong {
f
}
+const CGROUP_RO_ATTRS: u64 = sys::MOUNT_ATTR_RDONLY | sys::MOUNT_ATTR_NOSUID | sys::MOUNT_ATTR_NODEV | sys::MOUNT_ATTR_NOEXEC;
+const CGROUP_RO_FLAGS: libc::c_ulong = libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC;
+
+/// Normalizes `path` lexically by collapsing `//`, `.`, and `..`.
+fn lexical_normalize(path: &Path) -> PathBuf {
+ use std::path::Component;
+ let mut parts: Vec> = Vec::new();
+ let mut is_abs = false;
+ for c in path.components() {
+ match c {
+ Component::RootDir => {
+ is_abs = true;
+ parts.clear();
+ }
+ Component::CurDir => {}
+ Component::ParentDir => {
+ if matches!(parts.last(), Some(Component::Normal(_))) {
+ parts.pop();
+ } else if !is_abs {
+ parts.push(c);
+ }
+ }
+ Component::Normal(_) | Component::Prefix(_) => parts.push(c),
+ }
+ }
+ let mut out = PathBuf::new();
+ if is_abs {
+ out.push("/");
+ }
+ for p in parts {
+ out.push(p.as_os_str());
+ }
+ out
+}
+
+/// Resolves symlinks via `fs::canonicalize` when `path` exists, falling back
+/// to lexical normalization so `.`, `..`, and `//` are still collapsed.
+fn canonical_path(path: &Path) -> PathBuf {
+ fs::canonicalize(path).unwrap_or_else(|_| lexical_normalize(path))
+}
+
+/// Normalizes a container-relative target path (stripping leading `/`, `.`, and
+/// collapsing `//` and `..` within the container root).
+fn normalize_rel_target(target: &Path) -> PathBuf {
+ use std::path::Component;
+ let mut out = PathBuf::new();
+ for c in target.components() {
+ match c {
+ Component::RootDir | Component::CurDir | Component::Prefix(_) => {}
+ Component::ParentDir => {
+ out.pop();
+ }
+ Component::Normal(n) => out.push(n),
+ }
+ }
+ out
+}
+
+/// Pure path check for whether `(src, target)` is a self-bind of
+/// `/sys/fs/cgroup` onto `/sys/fs/cgroup`.
+fn is_cgroup_self_bind_paths(src: &Path, target: &Path) -> bool {
+ canonical_path(src) == Path::new("/sys/fs/cgroup") && normalize_rel_target(target) == Path::new("sys/fs/cgroup")
+}
+
+/// Whether `src` and `target` (relative to `root`) are a bind of
+/// `/sys/fs/cgroup` onto `/sys/fs/cgroup`, including symlinks on `src` or
+/// inside `root`. `mount_container_filesystems` has already mounted `cgroup2`
+/// there, rooted at the container's cgroup namespace (the host's for
+/// `--cgroupns host`, the container's own cgroup otherwise) and read-only
+/// unless `--privileged`.
+fn is_cgroup_self_bind(root: BorrowedFd<'_>, src: &Path, target: &Path) -> bool {
+ if canonical_path(src) != Path::new("/sys/fs/cgroup") {
+ return false;
+ }
+ if normalize_rel_target(target) == Path::new("sys/fs/cgroup") {
+ return true;
+ }
+ matches!(
+ (inroot::open(root, target, Last::Exists), inroot::open(root, Path::new("sys/fs/cgroup"), Last::Exists)),
+ (Ok(at_t), Ok(at_cg)) if same_dir(&at_t, &at_cg)
+ )
+}
+
+/// Whether canonicalized `src` names the cgroup tree (v1 or v2, or a path
+/// under `/sys/fs/cgroup` such as a hybrid `tmpfs`), which an unprivileged
+/// container may only ever mount read-only.
+fn is_cgroup_source(src: &Path) -> bool {
+ let real = canonical_path(src);
+ real.starts_with("/sys/fs/cgroup") || sys::is_cgroup(&real) || sys::is_cgroup(src)
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct MountInfoEntry {
+ mount_point: PathBuf,
+ fstype: String,
+ options: String,
+}
+
+fn unescape_mount_bytes(raw: &str) -> Vec {
+ let bytes = raw.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'\\'
+ && i + 3 < bytes.len()
+ && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b))
+ {
+ let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0');
+ out.push(val);
+ i += 4;
+ } else {
+ out.push(bytes[i]);
+ i += 1;
+ }
+ }
+ out
+}
+
+/// Parses `/proc/self/mountinfo` keeping only the topmost active mount for each
+/// mountpoint path, ordered parents-first.
+fn parse_mountinfo(mountinfo: &str) -> Vec {
+ use std::os::unix::ffi::OsStringExt;
+ let mut active = std::collections::BTreeMap::::new();
+ for line in mountinfo.lines() {
+ let Some((before, after)) = line.split_once(" - ") else { continue };
+ let mut b = before.split_whitespace();
+ let (Some(_id), Some(_parent), Some(_dev), Some(_root), Some(mp), Some(mopts)) =
+ (b.next(), b.next(), b.next(), b.next(), b.next(), b.next())
+ else {
+ continue;
+ };
+ let Some(fstype) = after.split_whitespace().next() else { continue };
+ let mount_point = PathBuf::from(std::ffi::OsString::from_vec(unescape_mount_bytes(mp)));
+ active.insert(
+ mount_point.clone(),
+ MountInfoEntry { mount_point, fstype: fstype.to_owned(), options: mopts.to_owned() },
+ );
+ }
+ active.into_values().collect()
+}
+
+/// Active mountpoints in `mountinfo` at or beneath `target`.
+fn submounts_under(mountinfo: &str, target: &Path) -> Vec {
+ parse_mountinfo(mountinfo)
+ .into_iter()
+ .filter(|e| e.mount_point == target || e.mount_point.starts_with(target))
+ .collect()
+}
+
+/// Active `cgroup` or `cgroup2` mountpoints in `mountinfo` at or beneath `target`.
+fn cgroup_mounts_under(mountinfo: &str, target: &Path) -> Vec {
+ submounts_under(mountinfo, target)
+ .into_iter()
+ .filter(|e| e.fstype == "cgroup" || e.fstype == "cgroup2")
+ .collect()
+}
+
+/// Translates mountinfo per-mount option words into `mount(2)` flags so locked
+/// flags in a user namespace are preserved during `MS_BIND | MS_REMOUNT`.
+fn mount_opts_flags(opts: &str) -> libc::c_ulong {
+ let mut f = 0 as libc::c_ulong;
+ for w in opts.split(',') {
+ match w {
+ "nosuid" => f |= libc::MS_NOSUID,
+ "nodev" => f |= libc::MS_NODEV,
+ "noexec" => f |= libc::MS_NOEXEC,
+ "noatime" => f |= libc::MS_NOATIME,
+ "nodiratime" => f |= libc::MS_NODIRATIME,
+ "relatime" => f |= libc::MS_RELATIME,
+ "strictatime" => f |= libc::MS_STRICTATIME,
+ _ => {}
+ }
+ }
+ f
+}
+
+fn remount_single(target: &CStr, extra_flags: libc::c_ulong, mountinfo_opts: Option<&str>) -> io::Result<()> {
+ let mut flags = libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | extra_flags;
+ if let Some(opts) = mountinfo_opts {
+ flags |= mount_opts_flags(opts);
+ } else {
+ // SAFETY: `statvfs` is plain zero-initialized data and `target` is NUL-terminated.
+ let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
+ // SAFETY: `target` is valid and `st` is writable.
+ if unsafe { libc::statvfs(target.as_ptr(), &mut st) } == 0 {
+ flags |= (st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC)) as libc::c_ulong;
+ }
+ }
+ sys::mount(c"none", target, c"none", flags, None)
+}
+
+/// Remounts `target` and every submount beneath it read-only using
+/// `mount_setattr(AT_RECURSIVE)`, falling back to `/proc/self/mountinfo` when
+/// `mount_setattr` is unavailable (`ENOSYS`/seccomp) because Linux ignores
+/// `MS_REC` on `MS_BIND | MS_REMOUNT`.
+fn remount_ro_recursive(target: &CStr, attr_set: u64, remount_flags: libc::c_ulong) -> io::Result<()> {
+ if sys::mount_setattr_recursive(target, attr_set).is_ok() {
+ return Ok(());
+ }
+ let target_path = Path::new(std::ffi::OsStr::from_bytes(target.to_bytes()));
+ let real = fs::read_link(target_path).unwrap_or_else(|_| target_path.to_path_buf());
+ let mountinfo = fs::read_to_string("/proc/self/mountinfo")?;
+ let subs = submounts_under(&mountinfo, &real);
+ let mut remounted_target = false;
+ for entry in &subs {
+ if entry.mount_point == real {
+ remounted_target = true;
+ }
+ let mp = sys::cstr(&entry.mount_point)?;
+ remount_single(&mp, remount_flags, Some(&entry.options))?;
+ }
+ if !remounted_target {
+ remount_single(target, remount_flags, None)?;
+ }
+ Ok(())
+}
+
+/// Ensures any cgroup v1/v2 mount exposed at or beneath `t` after a bind mount
+/// in an unprivileged container is strictly read-only (`nosuid,nodev,noexec,ro`).
+fn harden_cgroup_mounts(root: BorrowedFd<'_>, t: &Path) -> io::Result<()> {
+ let at = inroot::open(root, t, Last::Exists)?;
+ let proc_path = at.proc_path();
+ let proc_p = Path::new(std::ffi::OsStr::from_bytes(proc_path.to_bytes()));
+ if sys::is_cgroup(proc_p) {
+ remount_ro_recursive(&proc_path, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?;
+ }
+ let real = fs::read_link(proc_p)?;
+ let mountinfo = fs::read_to_string("/proc/self/mountinfo")?;
+ for entry in cgroup_mounts_under(&mountinfo, &real) {
+ let mp = sys::cstr(&entry.mount_point)?;
+ remount_ro_recursive(&mp, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?;
+ }
+ Ok(())
+}
+
/// Mounts one entry into the container (relative target, before
/// pivot_root), creating the target as a directory or an empty file. The
/// target is looked up inside `root`, so an image's symlink cannot point
/// the mount, the copy-up or the new directory outside the container.
-fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) -> io::Result<()> {
+pub(super) fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount, privileged: bool) -> io::Result<()> {
let t = Path::new(std::ffi::OsStr::from_bytes(m.target.to_bytes()));
if let Some(opts) = &m.tmpfs_opts {
let at = inroot::open(root, t, Last::Dir)?;
return sys::mount(c"tmpfs", &at.proc_path(), c"tmpfs", m.tmpfs_flags, Some(opts));
}
let src = m.source.as_ref().expect("bind mounts have a source");
+ let src_path = Path::new(std::ffi::OsStr::from_bytes(src.to_bytes()));
+ if is_cgroup_self_bind(root, src_path, t) {
+ if !privileged || m.ro {
+ if let Ok(at) = inroot::open(root, Path::new("sys/fs/cgroup"), Last::Exists) {
+ let proc_path = at.proc_path();
+ if sys::is_cgroup(Path::new(std::ffi::OsStr::from_bytes(proc_path.to_bytes()))) {
+ remount_ro_recursive(&proc_path, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?;
+ }
+ }
+ }
+ return Ok(());
+ }
let at = inroot::open(root, t, if m.dir { Last::Dir } else { Last::File })?;
let target = at.proc_path();
if m.dir && m.copy_up {
@@ -1548,7 +2256,6 @@ fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) -
None => None,
};
if let Some(from_path) = from_path {
- let src_path = Path::new(std::ffi::OsStr::from_bytes(src.to_bytes()));
let image_path = Path::new(std::ffi::OsStr::from_bytes(from_path.to_bytes()));
let empty = fs::read_dir(src_path).map(|mut d| d.next().is_none()).unwrap_or(false);
if empty && image_path.is_dir() {
@@ -1557,11 +2264,20 @@ fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) -
}
}
sys::mount(src, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?;
- if m.ro {
+ let cgroup_src = !privileged && is_cgroup_source(src_path);
+ if m.ro || cgroup_src {
// The descriptor is the directory under the new mount; look again
// to reach the mount itself.
let at = inroot::open(root, t, Last::Exists)?;
- sys::mount(c"none", &at.proc_path(), c"none", libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | libc::MS_REC, None)?;
+ let (attrs, flags) = if cgroup_src {
+ (CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)
+ } else {
+ (sys::MOUNT_ATTR_RDONLY, libc::MS_RDONLY)
+ };
+ remount_ro_recursive(&at.proc_path(), attrs, flags)?;
+ }
+ if !privileged {
+ harden_cgroup_mounts(root, t)?;
}
Ok(())
}
@@ -1593,7 +2309,7 @@ fn same_dir(a: &inroot::Found, b: &inroot::Found) -> bool {
/// root) without the mounts on it: the image as it is under any bind.
/// None where the kernel has no open_tree (before Linux 5.2); volumes are
/// then filled from what the path shows, as before.
-fn image_tree() -> Option {
+pub(super) fn image_tree() -> Option {
const OPEN_TREE_CLONE: libc::c_uint = 1;
// SAFETY: a valid NUL-terminated path; the result is a new descriptor or -1.
let fd = unsafe { libc::syscall(libc::SYS_open_tree, libc::AT_FDCWD, c".".as_ptr(), OPEN_TREE_CLONE | libc::O_CLOEXEC as libc::c_uint) };
@@ -1762,6 +2478,29 @@ fn bind_file(root: BorrowedFd<'_>, src: &CStr, target: &CStr) -> io::Result<()>
sys::mount(src, &at.proc_path(), c"none", libc::MS_BIND, None)
}
+/// Docker's `/.dockerenv`: an empty file, 0755, owned by root. Whatever the
+/// image (or an earlier start) has there stays as it is: O_EXCL never
+/// follows a link, so one that points out of the container is not written
+/// through, and a link or directory there does not fail the start.
+fn make_marker(root: BorrowedFd<'_>, readonly_rootfs: bool) -> io::Result<()> {
+ // SAFETY: valid directory fd and NUL-terminated name.
+ let fd = unsafe { libc::openat(root.as_raw_fd(), MARKER.as_ptr(), libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0o755) };
+ if fd >= 0 {
+ // SAFETY: the descriptor opened just above, owned by nothing else;
+ // openat applies the process's umask, so set 0755 explicitly.
+ unsafe {
+ libc::fchmod(fd, 0o755);
+ libc::close(fd);
+ }
+ return Ok(());
+ }
+ match io::Error::last_os_error() {
+ e if e.raw_os_error() == Some(libc::EEXIST) => Ok(()),
+ e if readonly_rootfs && e.raw_os_error() == Some(libc::EROFS) => Ok(()),
+ e => Err(e),
+ }
+}
+
/// Where the child reports a failure before it has execed: the stderr pipe,
/// or the pty socket (the agent reads text there instead of a descriptor).
fn report_fd(io: &ChildStdio) -> RawFd {
@@ -1774,7 +2513,8 @@ fn report_fd(io: &ChildStdio) -> RawFd {
/// The descriptors a container's child, right after its clone, still uses
/// of those it inherited: its standard streams (or terminal socket), which
/// are also where it reports a failure; the network namespace it joins;
-/// the pipes it says "root ready" on and waits for its network on. Every
+/// the pipes it says "root ready" on, waits for its network on, and waits
+/// for its cgroup placement on. Every
/// other descriptor it uses it opens itself, later (its root, the image's
/// tree, its terminal). Standard input, output and error (0, 1, 2) always
/// stay. Every field of `Prepared` is named, so a descriptor added to it
@@ -1804,9 +2544,12 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec {
nodev_root: _,
shm_size: _,
init: _,
+ cgroupns_host: _,
+ timer_slack_ns: _,
// Paths, numbers and names only.
- host: HostApplied { rlimits: _, groups: _, nodes: _ },
+ host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ },
root_ready,
+ cgroup_ready,
} = p;
let mut fds = match io {
ChildStdio::Tty { sock } => vec![sock.as_raw_fd()],
@@ -1819,12 +2562,15 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec {
fds.extend(net_join.as_ref().map(AsRawFd::as_raw_fd));
fds.extend(net_ready.as_ref().map(AsRawFd::as_raw_fd));
fds.extend(root_ready.as_ref().map(AsRawFd::as_raw_fd));
+ fds.extend(cgroup_ready.as_ref().map(AsRawFd::as_raw_fd));
fds
}
/// Runs in the cloned child: PID 1 of the container, in its own namespaces
/// and cgroup. Never returns: it execs or exits 127 with a message.
-fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)]) -> ! {
+/// `fallback`: clone3 was blocked, so clone(2) made this child: it is not
+/// in its cgroup yet and has no cgroup namespace of its own.
+fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)], fallback: bool) -> ! {
// First of all: the clone gave this child a copy of every descriptor
// the agent had open, and filling a new volume can take seconds while
// the agent goes on. Held here, a network's DNS socket keeps its
@@ -1839,6 +2585,22 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[
let err = report_fd(io);
let fail = |what: &str, e: io::Error| -> ! { child_fail(err, what, e) };
+ if fallback {
+ // The agent moves us into the container's cgroup, then unshares a
+ // cgroup namespace rooted there, as clone3 with CLONE_INTO_CGROUP
+ // would have done before we ran anything.
+ if let Some(ready) = &p.cgroup_ready {
+ let mut b = [0u8; 1];
+ // SAFETY: reading one byte into a local buffer from a pipe we own.
+ if unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) } != 1 {
+ fail("cgroup", io::Error::other("the agent could not move this container into its cgroup"));
+ }
+ }
+ if !p.cgroupns_host {
+ sys::unshare(libc::CLONE_NEWCGROUP).unwrap_or_else(|e| fail("cgroup namespace", e));
+ }
+ }
+
// Mount events must not leak back into the agent's namespace.
sys::remount(c"/", libc::MS_REC | libc::MS_PRIVATE).unwrap_or_else(|e| fail("make mounts private", e));
if let Some(ns) = &p.net_join {
@@ -1850,11 +2612,20 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[
}
let root = inroot::open_root(Path::new(".")).unwrap_or_else(|e| fail("enter rootfs", e));
let root = root.as_fd();
- mount_container_filesystems(p.privileged, p.shm_size).unwrap_or_else(|e| fail("mount", e));
+ mount_container_filesystems(p.privileged, p.shm_size, &p.host).unwrap_or_else(|e| fail("mount", e));
+ // Taken before user mounts can cover /dev, as the source for MaskedPaths.
+ let null = (!p.privileged)
+ .then(|| p.host.masked.as_ref().filter(|m| !m.is_empty()))
+ .flatten()
+ .map(|_| dev_null().unwrap_or_else(|e| fail("masked paths", e)));
super::hostopts::make_nodes(root, &p.host.nodes).unwrap_or_else(|e| fail("devices", e));
for (src, target) in &p.etc_files {
bind_file(root, src, target).unwrap_or_else(|e| fail(&target.to_string_lossy(), e));
}
+ // SDKs use Docker's marker to detect container execution when cgroup
+ // namespaces hide the host's cgroup path. Made before changing user or
+ // making the root filesystem read-only.
+ make_marker(root, p.readonly_rootfs).unwrap_or_else(|e| fail("container marker", e));
// The image's tree without the mounts made on it, for filling new
// volumes; closed (and so unmounted) once they are all in place.
let image = if p.mounts.iter().any(|m| m.copy_up) { image_tree() } else { None };
@@ -1868,7 +2639,7 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[
}
}
for m in &p.mounts {
- apply_mount(root, image.as_ref().map(|f| f.as_fd()), m).unwrap_or_else(|e| fail(&format!("mount {}", m.target.to_string_lossy()), e));
+ apply_mount(root, image.as_ref().map(|f| f.as_fd()), m, p.privileged).unwrap_or_else(|e| fail(&format!("mount {}", m.target.to_string_lossy()), e));
}
drop(image);
@@ -1887,6 +2658,8 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[
// before it switches user and before the root goes read-only, so both
// `-u 1000 -w /missing` and `--read-only -w /missing` start (#370).
make_workdir(root, &p.cwd);
+ api_paths(root, p.privileged, p.host.readonly.as_deref().unwrap_or_default(), p.host.masked.as_deref().unwrap_or_default(), null.as_ref())
+ .unwrap_or_else(|e| fail("masked paths", e));
if let Some(flags) = root_remount_flags(p.readonly_rootfs, p.nodev_root) {
// Only the root itself: volumes, tmpfs and /dev stay as they are.
sys::mount(c"none", c"/", c"none", flags, None).unwrap_or_else(|e| fail(if p.readonly_rootfs { "read-only root" } else { "nodev root" }, e));
@@ -1919,8 +2692,19 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[
/// Runs in the cloned child of an exec: joins the container's remaining
/// namespaces (the PID namespace was set before clone), then execs.
-fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio) -> ! {
+/// `fallback`: clone3 was blocked, so it waits until the agent has moved it
+/// into the container's cgroup.
+fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio, fallback: bool) -> ! {
let err = report_fd(io);
+ if fallback
+ && let Some(ready) = &p.cgroup_ready
+ {
+ let mut b = [0u8; 1];
+ // SAFETY: reading one byte into a local buffer from a pipe we own.
+ if unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) } != 1 {
+ child_fail(err, "cgroup", io::Error::other("the agent could not move this exec into its cgroup"));
+ }
+ }
for (fd, kind) in namespaces {
sys::setns(fd.as_raw_fd(), *kind).unwrap_or_else(|e| child_fail(err, "join container", e));
}
@@ -1999,7 +2783,12 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! {
// While still root with every capability: raising a hard limit needs
// CAP_SYS_RESOURCE.
- super::hostopts::set_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e));
+ apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e));
+ if console
+ && let Some(ns) = p.timer_slack_ns
+ {
+ apply_timer_slack(ns);
+ }
for cap in 0..=LAST_CAP {
if !p.privileged && p.caps & (1 << cap) == 0 {
@@ -2102,6 +2891,22 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! {
sys::exec_fail(2, &exe, io::Error::last_os_error(), false)
}
+/// Applies timer slack (`ns`) to the container's PID 1 before `execve`.
+/// Writing `/proc/self/timerslack_ns` updates both `timer_slack_ns` and
+/// `default_timer_slack_ns` in Linux (`fs/proc/base.c`), so the slack survives
+/// `execve` into `/bin/k3s` and coalesces staggered sub-100 ms tickers (#989).
+fn apply_timer_slack(ns: u64) {
+ let _ = apply_timer_slack_to(Path::new("/proc/self/timerslack_ns"), ns);
+ // SAFETY: `PR_SET_TIMERSLACK` takes the slack in nanoseconds as `arg2`.
+ unsafe {
+ libc::prctl(libc::PR_SET_TIMERSLACK, ns as libc::c_ulong, 0, 0, 0);
+ }
+}
+
+fn apply_timer_slack_to(path: &Path, ns: u64) -> io::Result<()> {
+ fs::write(path, ns.to_string())
+}
+
/// How the container's root is remounted once it is `/`, if at all:
/// read-only for `--read-only`, and `nodev` when the device filter could not
/// be attached. Without the filter, a block or character device node that an
@@ -2126,7 +2931,7 @@ fn root_remount_flags(readonly: bool, nodev: bool) -> Option {
/// /dev/pts, /dev/shm, /dev/mqueue and a read-only cgroup view. Relative
/// paths: the current directory is the container root. A privileged
/// container gets the VM's devices and writable /sys and cgroups instead.
-fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()> {
+fn mount_container_filesystems(privileged: bool, shm_size: u64, host: &HostApplied) -> io::Result<()> {
let nosuid_nodev_noexec = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC;
let ro = if privileged { 0 } else { libc::MS_RDONLY };
for d in [c"proc", c"sys", c"dev"] {
@@ -2151,22 +2956,19 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
if privileged {
copy_host_devices(Path::new("/dev"), Path::new("dev"))?;
}
- for (name, major, minor) in [
- (c"dev/null", 1, 3),
- (c"dev/zero", 1, 5),
- (c"dev/full", 1, 7),
- (c"dev/random", 1, 8),
- (c"dev/urandom", 1, 9),
- (c"dev/tty", 5, 0),
+ for (host, name, major, minor) in [
+ (c"/dev/null", c"dev/null", 1, 3),
+ (c"/dev/zero", c"dev/zero", 1, 5),
+ (c"/dev/full", c"dev/full", 1, 7),
+ (c"/dev/random", c"dev/random", 1, 8),
+ (c"/dev/urandom", c"dev/urandom", 1, 9),
+ (c"/dev/tty", c"dev/tty", 5, 0),
] {
- if privileged {
+ if privileged && is_char_dev(name) {
// Copied from the host already.
continue;
}
- sys::mknod(name, libc::S_IFCHR | 0o666, major, minor)?;
- // mknod applies the umask; every user in the container needs these.
- // SAFETY: valid NUL-terminated path.
- unsafe { libc::chmod(name.as_ptr(), 0o666) };
+ make_or_bind_dev(host, name, major, minor)?;
}
// The host's /proc still, before the pivot.
for (target, link) in dev_links(Path::new("/proc/kcore").exists()) {
@@ -2185,12 +2987,127 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()
sys::mount(c"mqueue", c"dev/mqueue", c"mqueue", nosuid_nodev_noexec, None)?;
sys::mkdir(c"sys/fs/cgroup", 0o755);
sys::mount(c"cgroup2", c"sys/fs/cgroup", c"cgroup2", nosuid_nodev_noexec | ro, None)?;
- if !privileged {
+ // An API list replaces Docker's default for that half (see `api_paths`).
+ if !privileged && host.readonly.is_none() {
harden_proc()?;
}
+ if !privileged && host.masked.is_none() {
+ mask_proc();
+ }
Ok(())
}
+/// The default `nofile` soft and hard limit the daemon sends when a run sets
+/// no `--ulimit nofile=...` of its own.
+const DEFAULT_NOFILE: u64 = 1_048_576;
+const DEFAULT_PING_MAX: u64 = 2_147_483_647;
+
+/// The highest group id in the `/proc/self/gid_map` extent that maps 0,
+/// clamped to `2147483647`. In the initial user namespace (`0 0 4294967295`)
+/// this is `2147483647`; in a user namespace (`0 0 65536`) the kernel refuses
+/// any upper bound that is not mapped (`EINVAL` on `ping_group_range`, #597).
+fn ping_group_max(gid_map: &str) -> u64 {
+ for line in gid_map.lines() {
+ let mut f = line.split_whitespace();
+ if let (Some("0"), Some(_outer), Some(count)) = (f.next(), f.next(), f.next())
+ && let Ok(n) = count.parse::()
+ && n > 0
+ {
+ return (n - 1).min(DEFAULT_PING_MAX);
+ }
+ }
+ DEFAULT_PING_MAX
+}
+
+/// Caps the default `nofile` limit (`1048576:1048576`) to `rlim_max` when the
+/// engine's own hard limit is lower (as in a user namespace or a nested
+/// container with a `524288` ceiling, where raising past it is refused). An
+/// explicit `--ulimit nofile=...` is left as given, so a lower value applies
+/// and one above `rlim_max` still fails with the kernel's error.
+fn cap_default_nofile(rlimits: &mut [(u32, u64, u64)], rlim_max: u64) -> bool {
+ let mut capped = false;
+ if rlim_max > 0 && rlim_max < DEFAULT_NOFILE {
+ for (res, soft, hard) in rlimits {
+ if *res == libc::RLIMIT_NOFILE as u32 && *soft == DEFAULT_NOFILE && *hard == DEFAULT_NOFILE {
+ *soft = rlim_max;
+ *hard = rlim_max;
+ capped = true;
+ }
+ }
+ }
+ capped
+}
+
+/// Applies resource limits, falling back to the engine's own hard `nofile`
+/// limit if the default `1048576` is refused with `EPERM` (#597).
+fn apply_rlimits(rlimits: &[(u32, u64, u64)]) -> io::Result<()> {
+ match super::hostopts::set_rlimits(rlimits) {
+ Ok(()) => Ok(()),
+ Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => {
+ let mut rl = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
+ // SAFETY: valid writable rlimit struct.
+ if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rl) } != 0 {
+ return Err(e);
+ }
+ let mut capped = rlimits.to_vec();
+ if !cap_default_nofile(&mut capped, rl.rlim_max) {
+ return Err(e);
+ }
+ super::hostopts::set_rlimits(&capped)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+/// Whether `path` already exists as a character device node (never following a symlink).
+fn is_char_dev(path: &CStr) -> bool {
+ fstat_at(libc::AT_FDCWD, path, libc::AT_SYMLINK_NOFOLLOW)
+ .is_ok_and(|st| st.st_mode & libc::S_IFMT == libc::S_IFCHR)
+}
+
+/// Creates a standard character device node at `target` on the container's
+/// fresh `/dev` tmpfs, or, when `mknod` is refused in a user namespace
+/// (`EPERM`), bind-mounts `host` onto a newly created empty file at `target`,
+/// as runc does (#597).
+fn make_or_bind_dev(host: &CStr, target: &CStr, major: u32, minor: u32) -> io::Result<()> {
+ match sys::mknod(target, libc::S_IFCHR | 0o666, major, minor) {
+ Ok(()) => {
+ // mknod applies the umask; every user in the container needs these.
+ // SAFETY: valid NUL-terminated path.
+ unsafe { libc::chmod(target.as_ptr(), 0o666) };
+ Ok(())
+ }
+ Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => {
+ let (host_fd, target_fd) = prepare_dev_bind(host, target)?;
+ let src = CString::new(format!("/proc/self/fd/{}", host_fd.as_raw_fd())).expect("no NUL");
+ let dst = CString::new(format!("/proc/self/fd/{}", target_fd.as_raw_fd())).expect("no NUL");
+ sys::mount(&src, &dst, c"none", libc::MS_BIND, None)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+/// Verifies that `host` is a real character device (not a symlink or other
+/// file) and creates an empty regular mountpoint file at `target` without
+/// following symlinks or overwriting an existing entry.
+fn prepare_dev_bind(host: &CStr, target: &CStr) -> io::Result<(OwnedFd, OwnedFd)> {
+ let host_fd = open_at(libc::AT_FDCWD, host, libc::O_PATH | libc::O_NOFOLLOW)?;
+ let st = fstat_at(host_fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?;
+ if st.st_mode & libc::S_IFMT != libc::S_IFCHR {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ format!("{} is not a character device", host.to_string_lossy()),
+ ));
+ }
+ let target_fd = open_at_mode(
+ libc::AT_FDCWD,
+ target,
+ libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW,
+ 0o666,
+ )?;
+ Ok((host_fd, target_fd))
+}
+
/// The links runc makes in a container's /dev (relative to its root):
/// /dev/core only when the host has /proc/kcore, as runc checks.
fn dev_links(kcore: bool) -> Vec<(&'static CStr, &'static CStr)> {
@@ -2249,8 +3166,8 @@ fn copy_host_devices(from: &Path, to: &Path) -> io::Result<()> {
Ok(())
}
-/// Makes the dangerous parts of /proc read-only or hides them, as Docker's
-/// default `readonlyPaths` and `maskedPaths` do. The container is real root
+/// Makes the dangerous parts of /proc read-only, as Docker's default
+/// `readonlyPaths` does. The container is real root
/// (no user namespace), and these sysctls and files are not namespaced, so
/// without this a container could set `kernel.core_pattern` or
/// `kernel.modprobe` and run code on the host. Paths are relative to the
@@ -2268,6 +3185,11 @@ fn harden_proc() -> io::Result<()> {
let _ = sys::remount(p, ro as libc::c_ulong);
}
}
+ Ok(())
+}
+
+/// Hides what Docker's default `maskedPaths` does, relative to the container root.
+fn mask_proc() {
// Hide files that leak host memory or kernel addresses, by covering them
// with /dev/null (already created above).
for p in [c"proc/kcore", c"proc/keys", c"proc/latency_stats", c"proc/timer_list", c"proc/timer_stats", c"proc/sched_debug", c"proc/interrupts"] {
@@ -2277,9 +3199,135 @@ fn harden_proc() -> io::Result<()> {
for p in [c"proc/scsi", c"proc/acpi", c"proc/asound", c"sys/firmware", c"sys/devices/virtual/powercap"] {
let _ = sys::mount(c"tmpfs", p, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k"));
}
+}
+
+/// Looks up an existing `path` inside `root` without creating anything,
+/// resolving symlinks and `..` against `root` so neither can leave it.
+/// Returns the descriptor and whether it is a directory, or `None` when a
+/// component is missing, a parent is not a directory, or the path resolves
+/// to `root` itself.
+fn lookup_existing(root: BorrowedFd<'_>, path: &Path) -> io::Result> {
+ use std::collections::VecDeque;
+ use std::ffi::OsString;
+ use std::path::Component;
+
+ let parts = |p: &std::ffi::OsStr| -> VecDeque {
+ Path::new(p)
+ .components()
+ .filter_map(|c| match c {
+ Component::Normal(n) => Some(n.to_owned()),
+ Component::ParentDir => Some(OsString::from("..")),
+ Component::RootDir | Component::CurDir | Component::Prefix(_) => None,
+ })
+ .collect()
+ };
+ let root_st = fstat_at(root.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?;
+ let is_root = |st: &libc::stat| st.st_dev == root_st.st_dev && st.st_ino == root_st.st_ino;
+ let mut todo = parts(path.as_os_str());
+ let mut dirs: Vec = vec![root.try_clone_to_owned()?];
+ let mut links = 0u32;
+ while let Some(name) = todo.pop_front() {
+ if name == ".." {
+ if dirs.len() > 1 {
+ dirs.pop();
+ }
+ continue;
+ }
+ let is_last = todo.is_empty();
+ let dir = dirs.last().expect("root stays").as_raw_fd();
+ let c = CString::new(name.as_os_str().as_bytes()).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
+ let fd = match open_at(dir, &c, libc::O_PATH | libc::O_NOFOLLOW) {
+ Ok(fd) => fd,
+ Err(e) if matches!(e.raw_os_error(), Some(libc::ENOENT | libc::ENOTDIR)) => return Ok(None),
+ Err(e) => return Err(e),
+ };
+ let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?;
+ match st.st_mode & libc::S_IFMT {
+ libc::S_IFLNK => {
+ links += 1;
+ if links > 40 {
+ return Err(io::Error::from_raw_os_error(libc::ELOOP));
+ }
+ let target = read_link_at(fd.as_raw_fd(), c"")?;
+ let bytes = target.as_bytes();
+ if bytes.first() == Some(&b'/') {
+ dirs.truncate(1);
+ }
+ for comp in parts(std::ffi::OsStr::from_bytes(bytes)).into_iter().rev() {
+ todo.push_front(comp);
+ }
+ }
+ libc::S_IFDIR if !is_last => dirs.push(fd),
+ libc::S_IFDIR => return Ok((!is_root(&st)).then_some((fd, true))),
+ _ if is_last => return Ok(Some((fd, false))),
+ _ => return Ok(None),
+ }
+ }
+ let fd = dirs.pop().expect("root stays");
+ let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?;
+ Ok((!is_root(&st)).then_some((fd, true)))
+}
+
+/// The API's own `ReadonlyPaths` and `MaskedPaths`, applied after pivot_root as runc does.
+fn api_paths(root: BorrowedFd<'_>, privileged: bool, readonly: &[CString], masked: &[CString], null: Option<&OwnedFd>) -> io::Result<()> {
+ if privileged {
+ return Ok(());
+ }
+ let proc_fd = |fd: &OwnedFd| CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("no NUL");
+ for p in readonly {
+ let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes()));
+ let Some((fd, _)) = lookup_existing(root, path)? else { continue };
+ let target = proc_fd(&fd);
+ sys::mount(&target, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?;
+ // The first descriptor is under the new bind mount; look again to
+ // reach the mount itself, and keep its nosuid, nodev and noexec flags.
+ let Some((fd, _)) = lookup_existing(root, path)? else { continue };
+ let target = proc_fd(&fd);
+ // SAFETY: statvfs is plain data; all-zero is a valid value.
+ let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
+ // SAFETY: valid NUL-terminated path and a writable struct.
+ if unsafe { libc::statvfs(target.as_ptr(), &mut st) } != 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let keep = st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC);
+ sys::remount(&target, (libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY) as libc::c_ulong | keep)?;
+ }
+ for p in masked {
+ let null = null.ok_or_else(|| io::Error::other("no /dev/null to mask with"))?;
+ let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes()));
+ let Some((fd, is_dir)) = lookup_existing(root, path)? else { continue };
+ let target = proc_fd(&fd);
+ if is_dir {
+ sys::mount(c"tmpfs", &target, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k"))?;
+ } else {
+ let src = proc_fd(null);
+ sys::mount(&src, &target, c"none", libc::MS_BIND, None)?;
+ }
+ }
Ok(())
}
+/// The container's own /dev/null as an O_PATH descriptor, checked to be device 1:3.
+fn dev_null() -> io::Result {
+ // SAFETY: valid NUL-terminated path; the descriptor is owned right away.
+ let fd = unsafe { libc::open(c"dev/null".as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) };
+ if fd < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ // SAFETY: fresh descriptor nothing else owns.
+ let fd = unsafe { OwnedFd::from_raw_fd(fd) };
+ // SAFETY: stat is plain data; all-zero is a valid value.
+ let mut st: libc::stat = unsafe { std::mem::zeroed() };
+ // SAFETY: a descriptor we own and a writable struct.
+ if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
+ return Err(io::Error::last_os_error());
+ }
+ if st.st_mode & libc::S_IFMT != libc::S_IFCHR || st.st_rdev != libc::makedev(1, 3) {
+ return Err(io::Error::other("/dev/null is not the null device"));
+ }
+ Ok(fd)
+}
+
/// `""`, `root`, `1000`, `1000:1000`, `redis`, `redis:redis`: looked up in
/// the container's /etc/passwd and /etc/group when not numeric.
/// The home directory /etc/passwd gives `uid`.
@@ -2646,12 +3694,12 @@ mod tests {
let base = std::env::temp_dir().join(format!("kiri-plain-upper-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("upper")).unwrap();
- assert!(super::plain_upper(&base).unwrap(), "fresh");
+ assert!(super::plain_upper(&base, true).unwrap(), "fresh");
assert!(base.join(super::PLAIN_UPPER).exists());
std::fs::write(base.join("upper/written"), b"x").unwrap();
- assert!(super::plain_upper(&base).unwrap(), "marked, then written to");
+ assert!(super::plain_upper(&base, true).unwrap(), "marked, then written to");
std::fs::remove_file(base.join(super::PLAIN_UPPER)).unwrap();
- assert!(!super::plain_upper(&base).unwrap(), "written before the mark existed");
+ assert!(!super::plain_upper(&base, true).unwrap(), "written before the mark existed");
assert!(!base.join(super::PLAIN_UPPER).exists(), "an old layer is never marked");
assert_eq!(super::overlay_features(true), "index=off,redirect_dir=nofollow,metacopy=off");
assert_eq!(super::overlay_features(false), "index=off");
@@ -3130,9 +4178,55 @@ mod tests {
assert!(super::joined_user_network("", kiri).is_none(), "no file to speak of");
}
+ /// The marker is made empty where the root has none. What is there
+ /// already stays: a file (a restart), a directory, and a link, whose
+ /// target outside the root is neither made nor touched.
+ #[test]
+ fn marker_is_made_once_and_never_through_a_link() {
+ use std::os::fd::AsFd;
+ use std::os::unix::fs::MetadataExt;
+ let base = std::env::temp_dir().join(format!("kiri-marker-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let (plain, linked, linked_existing, dir) = (base.join("plain"), base.join("linked"), base.join("linked-existing"), base.join("dir"));
+ let marker = |root: &std::path::Path| root.join(super::MARKER.to_str().unwrap());
+ let make = |root: &std::path::Path| super::make_marker(super::inroot::open_root(root).unwrap().as_fd(), false);
+ for root in [&plain, &linked, &linked_existing, &dir] {
+ std::fs::create_dir_all(root).unwrap();
+ }
+
+ make(&plain).unwrap();
+ let meta = std::fs::symlink_metadata(marker(&plain)).unwrap();
+ assert!(meta.is_file() && meta.len() == 0);
+ assert_eq!(meta.mode() & 0o7777, 0o755);
+ std::fs::write(marker(&plain), b"kept").unwrap();
+ set_mode(&marker(&plain), 0o640);
+ make(&plain).unwrap();
+ assert_eq!(std::fs::read(marker(&plain)).unwrap(), b"kept");
+ assert_eq!(mode_of(&marker(&plain)), 0o640);
+
+ std::os::unix::fs::symlink(base.join("outside"), marker(&linked)).unwrap();
+ make(&linked).unwrap();
+ assert!(std::fs::symlink_metadata(marker(&linked)).unwrap().file_type().is_symlink());
+ assert!(!base.join("outside").exists(), "made through the link");
+
+ let existing = base.join("existing");
+ std::fs::write(&existing, b"host").unwrap();
+ set_mode(&existing, 0o600);
+ std::os::unix::fs::symlink(&existing, marker(&linked_existing)).unwrap();
+ make(&linked_existing).unwrap();
+ assert!(std::fs::symlink_metadata(marker(&linked_existing)).unwrap().file_type().is_symlink());
+ assert_eq!(std::fs::read(&existing).unwrap(), b"host");
+ assert_eq!(mode_of(&existing), 0o600);
+
+ std::fs::create_dir(marker(&dir)).unwrap();
+ make(&dir).unwrap();
+ assert!(marker(&dir).is_dir());
+ std::fs::remove_dir_all(&base).unwrap();
+ }
+
#[test]
fn mounts_go_parents_first_whatever_order_they_came_in() {
- let m = |t: &str| super::Mount { source: None, target: std::ffi::CString::new(t).unwrap(), ro: false, dir: true, copy_up: false, tmpfs_opts: None, tmpfs_flags: 0 };
+ let m = |t: &str| super::Mount { source: None, target: std::ffi::CString::new(t).unwrap(), ro: false, dir: true, copy_up: false, tmpfs_opts: None, tmpfs_flags: 0, loop_mount: None };
let mut mounts = vec![m("app/node_modules"), m("app"), m("data"), m("app/cache/x"), m(".")];
mounts.sort_by_key(|x| super::depth(&x.target));
let order: Vec<_> = mounts.iter().map(|x| x.target.to_str().unwrap()).collect();
@@ -3166,6 +4260,17 @@ mod tests {
// TEST-NET-3: no machine running the tests has it.
assert!(!super::embedded_dns(&spec, &[[203, 0, 113, 53]], false), "a resolver elsewhere is asked directly");
assert!(!super::embedded_dns(&spec, &[], false), "no resolver: the public fallback, not the agent");
+ // systemd-resolved's 127.0.0.53 stub and Tailscale's 100.100.100.100
+ // live in the host's network namespace: default-bridge containers ask
+ // the agent at the bridge gateway (172.17.0.1), never 127.0.0.53 (#330).
+ for stub in [&[[127, 0, 0, 53]][..], &[[127, 0, 0, 53], [168, 63, 129, 16]][..], &[[100, 100, 100, 100]][..]] {
+ assert!(super::embedded_dns(&spec, stub, false), "{stub:?} goes through the agent");
+ assert_eq!(super::resolv_conf(&spec, stub, Some(super::embedded_address(&spec))), "nameserver 172.17.0.1\n");
+ }
+ // Even if no agent listener could be made, a bridged container strips
+ // 127/8 stubs and keeps non-loopback fallbacks or 1.1.1.1.
+ assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53], [168, 63, 129, 16]], None), "nameserver 168.63.129.16\n");
+ assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53]], None), "nameserver 1.1.1.1\n");
}
#[test]
@@ -3180,7 +4285,17 @@ mod tests {
let gateway = [[192, 168, 64, 1]];
spec_with(0, &[], &|s| assert!(super::embedded_dns(s, &gateway, true), "so a refused gateway can fall back to the host"));
spec_with(0, &["nameserver=8.8.8.8"], &|s| assert!(!super::embedded_dns(s, &gateway, true), "--dns servers are asked directly"));
- spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking keeps the VM's resolv.conf"));
+ spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking has no embedded DNS of its own"));
+ // In the VM a host-network container asks the agent on the default
+ // bridge's gateway, so a refused gateway resolver falls back to the
+ // Mac too (#732); not with --dns, nor on a Linux host (no relay).
+ spec_with(run_flags::NET_HOST, &[], &|s| assert!(super::host_network_uses_agent(s, true)));
+ spec_with(run_flags::NET_HOST, &["nameserver=8.8.8.8"], &|s| assert!(!super::host_network_uses_agent(s, true), "--dns servers are asked directly"));
+ spec_with(run_flags::NET_HOST, &[], &|s| {
+ assert!(!super::host_network_uses_agent(s, false), "a Linux host has its own resolv.conf");
+ assert_eq!(super::resolv_conf(s, &[[127, 0, 0, 53]], None), "nameserver 127.0.0.53\n", "Linux --network host keeps 127.0.0.53 directly");
+ });
+ spec_with(0, &[], &|s| assert!(!super::host_network_uses_agent(s, true), "a bridged container has its own"));
// Named by the bridge's gateway, not 127.0.0.11: builders keep it
// for their steps rather than swapping in 8.8.8.8.
spec_with(0, &[], &|s| assert_eq!(super::embedded_address(s), [172, 17, 0, 1]));
@@ -3189,6 +4304,30 @@ mod tests {
spec_with(run_flags::DNS_GATEWAY, &[], &|s| assert_eq!(super::embedded_address(s), super::super::dns::EMBEDDED));
}
+ #[test]
+ fn host_network_resolver_picks_bridge_gateway_or_default() {
+ let check = |gateway: [u8; 4], prefix: u8, opts: &[&str], f: &mut dyn FnMut(&kiri_proto::RunSpec<'_>)| {
+ let mut buf = Vec::new();
+ let net = Net { bridge: "", ip: [0; 4], prefix, gateway, extra_hosts: &[], dns_names: &[], opts };
+ encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", run_flags::NET_HOST, net, &[], &Limits::default(), 0, &[] as &[&str], &[]);
+ let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
+ f(&spec);
+ };
+ check([172, 18, 0, 1], 24, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 24)));
+ check([0; 4], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 17, 0, 1], 16), "standalone caller falls back to 172.17.0.1/16"));
+ check([172, 18, 0, 1], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 16), "zero prefix falls back to /16"));
+
+ let mut bridges = super::net::Bridges::default();
+ let mut dns = super::super::dns::Dns::default();
+ check([172, 17, 0, 1], 16, &[], &mut |s| {
+ assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "no relay on a Linux host");
+ });
+ dns.relay = true;
+ check([172, 17, 0, 1], 16, &["nameserver=8.8.8.8"], &mut |s| {
+ assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "--dns bypasses agent resolver");
+ });
+ }
+
/// WSL 2: the host's resolver is 10.255.255.254, an address on `lo`.
/// The default bridge's lookups go through the agent, which the
/// container finds at the bridge's gateway, as in the VM: a loopback
@@ -3341,4 +4480,381 @@ mod tests {
let both = super::root_remount_flags(true, true).expect("remounted");
assert_eq!(both & (libc::MS_RDONLY | libc::MS_NODEV), libc::MS_RDONLY | libc::MS_NODEV);
}
+
+ /// `MaskedPaths` and `ReadonlyPaths` targets are looked up inside the
+ /// container's root without creating missing folders: links inside the
+ /// image work, links pointing outside or to `/` (`../..`) never leave
+ /// the root or cover `/` itself, and a path under a file is skipped.
+ #[test]
+ fn lookup_existing_stays_in_root_and_makes_nothing() {
+ use std::os::fd::{AsFd, AsRawFd};
+ use std::os::unix::fs::symlink;
+ use std::path::Path;
+ let (base, root, _vol, outside) = fill_dirs("lookup-existing");
+ std::fs::create_dir_all(root.join("etc")).unwrap();
+ std::fs::create_dir_all(root.join("usr/lib")).unwrap();
+ std::fs::create_dir_all(root.join("var")).unwrap();
+ std::fs::create_dir_all(root.join("custom")).unwrap();
+ std::fs::write(root.join("usr/lib/os-release"), b"alpine").unwrap();
+ std::fs::write(outside.join("secret"), b"host").unwrap();
+ symlink("../usr/lib/os-release", root.join("etc/os-release")).unwrap();
+ symlink(outside.join("secret"), root.join("custom/out")).unwrap();
+ symlink("../../../../../../outside/secret", root.join("custom/rel")).unwrap();
+ symlink("../..", root.join("custom/up")).unwrap();
+ symlink("/custom/loop_b", root.join("custom/loop_a")).unwrap();
+ symlink("/custom/loop_a", root.join("custom/loop_b")).unwrap();
+
+ let r = super::inroot::open_root(&root).unwrap();
+ let (fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/etc/os-release")).unwrap().expect("in-image link");
+ assert!(!is_dir);
+ assert_eq!(std::fs::read(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(), b"alpine");
+ let (_fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/var")).unwrap().expect("directory");
+ assert!(is_dir);
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/nope/sub")).unwrap().is_none());
+ assert!(!root.join("nope").exists(), "missing parent is not created");
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/usr/lib/os-release/sub")).unwrap().is_none(), "parent is a file");
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/out")).unwrap().is_none(), "absolute link stays in root");
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/rel")).unwrap().is_none(), ".. stops at root");
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/up")).unwrap().is_none(), "root itself is not returned");
+ assert!(super::lookup_existing(r.as_fd(), Path::new("/")).unwrap().is_none(), "root itself is not returned");
+ assert_eq!(super::lookup_existing(r.as_fd(), Path::new("/custom/loop_a")).unwrap_err().raw_os_error(), Some(libc::ELOOP));
+ let paths = [std::ffi::CString::new("/etc/os-release").unwrap()];
+ assert!(super::api_paths(r.as_fd(), true, &paths, &paths, None).is_ok(), "privileged skips api_paths");
+ assert!(super::api_paths(r.as_fd(), false, &[], &paths, None).is_err(), "unprivileged applies masked paths");
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ /// When clone3 is blocked (#529), `move_child` writes the child's PID to
+ /// `cgroup.procs` and signals `cgroup_go`; when a container's root cgroup
+ /// refuses processes (`EBUSY`), `cgroup_of_proc` resolves the container
+ /// init's cgroup under `paths.cgroup_root`, including hybrid trees (#277).
+ #[test]
+ fn move_child_places_fallback_child_and_resolves_hybrid_init_cgroup() {
+ use std::os::fd::AsRawFd;
+ use std::path::Path;
+ let dir = std::env::temp_dir().join(format!("kiri-move-child-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("cgroup.procs"), b"").unwrap();
+ let (ready, go) = super::sys::pipe().unwrap();
+ super::move_child(&dir, &dir, 4242, 1, &go).unwrap();
+ assert_eq!(std::fs::read_to_string(dir.join("cgroup.procs")).unwrap(), "4242");
+ let mut b = [0u8; 1];
+ // SAFETY: reading the byte move_child just wrote to the pipe.
+ assert_eq!(unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) }, 1);
+ assert_eq!(&b, b"g");
+ let _ = std::fs::remove_dir_all(&dir);
+
+ let unified = Path::new("/sys/fs/cgroup");
+ assert_eq!(
+ super::cgroup_of_proc(unified, "0::/kiri/c1/init\n"),
+ ("kiri/c1/init".to_owned(), unified.join("kiri/c1/init"))
+ );
+ let hybrid = Path::new("/sys/fs/cgroup/unified");
+ assert_eq!(
+ super::cgroup_of_proc(hybrid, "2:devices:/\n1:name=systemd:/\n0::/kiri/c1/sub\n"),
+ ("kiri/c1/sub".to_owned(), hybrid.join("kiri/c1/sub"))
+ );
+ assert_eq!(
+ super::cgroup_of_proc(hybrid, "1:name=systemd:/\n0::/\n"),
+ (String::new(), hybrid.to_path_buf())
+ );
+ }
+
+ /// In a user namespace or nested container whose hard `nofile` limit is
+ /// below the default `1048576` (#597), only the default `nofile` entry is
+ /// clamped to `rlim_max`; explicit `--ulimit nofile=...` values and other
+ /// resources stay untouched.
+ #[test]
+ fn cap_default_nofile_clamps_only_the_default_nofile_limit() {
+ let nofile = libc::RLIMIT_NOFILE as u32;
+ let nproc = libc::RLIMIT_NPROC as u32;
+ let mut lims = vec![(nproc, 100, 200), (nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)];
+ assert!(super::cap_default_nofile(&mut lims, 524_288));
+ assert_eq!(lims, [(nproc, 100, 200), (nofile, 524_288, 524_288)]);
+
+ let mut high_host = vec![(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)];
+ assert!(!super::cap_default_nofile(&mut high_host, super::DEFAULT_NOFILE));
+ assert!(!super::cap_default_nofile(&mut high_host, 2_097_152));
+ assert!(!super::cap_default_nofile(&mut high_host, 0));
+ assert_eq!(high_host, [(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]);
+
+ let mut explicit = vec![(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)];
+ assert!(!super::cap_default_nofile(&mut explicit, 524_288));
+ assert_eq!(
+ explicit,
+ [(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)]
+ );
+ assert_eq!(super::ping_group_max(" 0 0 4294967295\n"), super::DEFAULT_PING_MAX);
+ assert_eq!(super::ping_group_max(" 0 0 65536\n"), 65_535);
+ assert_eq!(super::ping_group_max(" 0 1000 1\n 1 100000 65536\n"), 0);
+ assert_eq!(super::ping_group_max(""), super::DEFAULT_PING_MAX);
+ }
+
+ /// When `mknod` is refused in a user namespace (#597), `prepare_dev_bind`
+ /// verifies the host source is a real character device (never following a
+ /// symlink) and creates the mountpoint file with `O_CREAT | O_EXCL |
+ /// O_NOFOLLOW` so a symlink or existing file at the target is refused.
+ #[test]
+ fn prepare_dev_bind_verifies_char_device_and_refuses_symlinks() {
+ use std::ffi::CString;
+ use std::os::unix::ffi::OsStrExt;
+ use std::os::unix::fs::symlink;
+
+ let (base, dev, _vol, outside) = fill_dirs("dev-bind");
+ let cstr = |p: &std::path::Path| CString::new(p.as_os_str().as_bytes()).unwrap();
+
+ let target = dev.join("null");
+ let (_h, _t) = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).expect("fresh target with /dev/null");
+ assert!(std::fs::symlink_metadata(&target).unwrap().is_file());
+ assert!(super::is_char_dev(c"/dev/null"));
+ assert!(!super::is_char_dev(&cstr(&target)));
+
+ // Existing file at target is refused with EEXIST.
+ let e = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).unwrap_err();
+ assert_eq!(e.raw_os_error(), Some(libc::EEXIST));
+
+ // Symlink at target (to an existing outside file or dangling) is refused and never followed.
+ let victim = outside.join("victim");
+ std::fs::write(&victim, b"untouched").unwrap();
+ let link_existing = dev.join("zero");
+ symlink(&victim, &link_existing).unwrap();
+ let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_existing)).unwrap_err();
+ assert_eq!(e.raw_os_error(), Some(libc::EEXIST));
+ assert_eq!(std::fs::read(&victim).unwrap(), b"untouched");
+
+ let gone = outside.join("gone");
+ let link_dangling = dev.join("full");
+ symlink(&gone, &link_dangling).unwrap();
+ let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_dangling)).unwrap_err();
+ assert_eq!(e.raw_os_error(), Some(libc::EEXIST));
+ assert!(!gone.exists());
+
+ // Non-character-device host sources (regular file, directory, symlink to /dev/null) are refused before creating target.
+ let fake_chr = outside.join("fake");
+ std::fs::write(&fake_chr, b"").unwrap();
+ let link_chr = outside.join("null-link");
+ symlink("/dev/null", &link_chr).unwrap();
+ assert!(!super::is_char_dev(&cstr(&link_chr)));
+ for bad_src in [&fake_chr, &outside, &link_chr] {
+ let unmade = dev.join("unmade");
+ let e = super::prepare_dev_bind(&cstr(bad_src), &cstr(&unmade)).unwrap_err();
+ assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
+ assert!(!unmade.exists(), "target must not be created when source is invalid");
+ }
+
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn host_etc_target_maps_wsl_host_relay_across_all_network_modes() {
+ // macOS VM keeps 198.19.248.254 unchanged.
+ assert_eq!(super::host_etc_target(false, false, false, [172, 17, 0, 1]), None);
+ assert_eq!(super::host_etc_target(false, true, true, [0; 4]), None);
+ // Plain Linux host uses bridge gateway or 127.0.0.1 for --network host.
+ assert_eq!(super::host_etc_target(true, false, false, [172, 17, 0, 1]).as_deref(), Some("172.17.0.1"));
+ assert_eq!(super::host_etc_target(true, false, true, [0; 4]).as_deref(), Some("127.0.0.1"));
+ assert_eq!(super::host_etc_target(true, false, false, [0; 4]), None);
+ // WSL 2 with active Windows host relay resolves to 192.168.65.254 everywhere.
+ assert_eq!(super::host_etc_target(true, true, false, [172, 17, 0, 1]).as_deref(), Some("192.168.65.254"));
+ assert_eq!(super::host_etc_target(true, true, false, [172, 18, 0, 1]).as_deref(), Some("192.168.65.254"));
+ assert_eq!(super::host_etc_target(true, true, true, [0; 4]).as_deref(), Some("192.168.65.254"));
+ }
+
+ #[test]
+ fn cgroup_self_bind_canonicalization_and_source_checks() {
+ use std::os::fd::AsFd;
+ use std::os::unix::fs::symlink;
+ use std::path::{Path, PathBuf};
+
+ assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("sys/fs/cgroup")));
+ assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup/"), Path::new("/sys/fs/cgroup/")));
+ assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/./cgroup"), Path::new("sys/fs/./cgroup")));
+ assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/x/../cgroup"), Path::new("/sys//fs/cgroup")));
+ assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup/sub"), Path::new("sys/fs/cgroup")));
+ assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("sys/fs/cgroup/sub")));
+ assert!(!super::is_cgroup_self_bind_paths(Path::new("/tmp/cgroup"), Path::new("sys/fs/cgroup")));
+ assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("mnt")));
+
+ assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup")));
+ assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup/kiri")));
+ assert!(super::is_cgroup_source(Path::new("/sys/fs/./cgroup")));
+ assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup/kiri/../other")));
+ assert!(!super::is_cgroup_source(Path::new("/sys/fs/cgroup2")));
+ assert!(!super::is_cgroup_source(Path::new("/sys")));
+ assert!(!super::is_cgroup_source(Path::new("/tmp/cgroup")));
+
+ // Canonicalization resolves symlinks on disk and inside container root.
+ let base = std::env::temp_dir().join(format!("kiri-cg-canon-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&base);
+ let root = base.join("root");
+ std::fs::create_dir_all(root.join("sys/fs/cgroup")).unwrap();
+ std::fs::create_dir_all(root.join("mnt")).unwrap();
+ symlink("/sys/fs/cgroup", root.join("mycg")).unwrap();
+ let real_dir = base.join("real");
+ std::fs::create_dir_all(&real_dir).unwrap();
+ let link_dir = base.join("link");
+ symlink(&real_dir, &link_dir).unwrap();
+ assert_eq!(super::canonical_path(&link_dir), real_dir.canonicalize().unwrap());
+
+ if Path::new("/sys/fs/cgroup").exists() {
+ let sys_cg_link = base.join("cglink");
+ symlink("/sys/fs/cgroup", &sys_cg_link).unwrap();
+ assert!(super::is_cgroup_source(&sys_cg_link));
+ assert!(super::is_cgroup_self_bind_paths(&sys_cg_link, Path::new("sys/fs/cgroup")));
+ }
+
+ let root_fd = super::inroot::open_root(&root).unwrap();
+ if Path::new("/sys/fs/cgroup").canonicalize().is_ok_and(|p| p == Path::new("/sys/fs/cgroup")) {
+ assert!(super::is_cgroup_self_bind(root_fd.as_fd(), Path::new("/sys/fs/cgroup"), Path::new("mycg")));
+ assert!(!super::is_cgroup_self_bind(root_fd.as_fd(), Path::new("/sys/fs/cgroup"), Path::new("mnt")));
+ }
+ assert_eq!(super::normalize_rel_target(Path::new("/sys/fs/./cgroup/")), PathBuf::from("sys/fs/cgroup"));
+ let _ = std::fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn mountinfo_finds_nested_cgroup_submounts_under_parent_bind() {
+ use std::path::{Path, PathBuf};
+
+ let target = Path::new("/var/lib/kiri/containers/c1/rootfs/hostsys");
+ // Pure cgroup v2 parent bind plus a sibling prefix `/hostsystemd` that must not match.
+ let pure_v2 = "\
+28 24 0:26 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw
+101 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsys rw,relatime - sysfs sysfs rw
+102 101 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw
+103 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsystemd rw,relatime - sysfs sysfs rw
+104 103 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsystemd/fs/cgroup rw,relatime - cgroup2 cgroup2 rw
+";
+ let cg_v2: Vec = super::cgroup_mounts_under(pure_v2, target).into_iter().map(|e| e.mount_point).collect();
+ assert_eq!(cg_v2, vec![PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup")]);
+ let all_v2: Vec = super::submounts_under(pure_v2, target).into_iter().map(|e| e.mount_point).collect();
+ assert_eq!(
+ all_v2,
+ vec![
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys"),
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup"),
+ ]
+ );
+
+ // Hybrid WSL 2 parent bind: tmpfs overmounts an earlier cgroup2 at `/hostsys/fs/cgroup`,
+ // with `unified` (cgroup2) and v1 controllers (`memory`, `pids`) beneath it, plus an escaped space mount.
+ let hybrid = "\
+101 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsys rw,relatime - sysfs sysfs rw
+102 101 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,relatime - cgroup2 cgroup2 rw
+103 102 0:31 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755
+104 103 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw
+105 103 0:32 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory
+106 103 0:33 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,pids
+107 103 0:34 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/my\\040cg\\134v1 rw,noatime,nodiratime - cgroup cgroup rw
+";
+ let cg_hybrid: Vec = super::cgroup_mounts_under(hybrid, target).into_iter().map(|e| e.mount_point).collect();
+ assert_eq!(
+ cg_hybrid,
+ vec![
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/memory"),
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/my cg\\v1"),
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/pids"),
+ PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/unified"),
+ ]
+ );
+ let all_hybrid = super::submounts_under(hybrid, target);
+ assert_eq!(all_hybrid.len(), 6);
+ assert_eq!(all_hybrid[1].fstype, "tmpfs");
+
+ let flags = super::mount_opts_flags("rw,nosuid,nodev,noexec,relatime,noatime,nodiratime");
+ assert_eq!(
+ flags,
+ libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RELATIME | libc::MS_NOATIME | libc::MS_NODIRATIME
+ );
+ }
+
+ #[test]
+ fn hostopts_cgroupns_host_is_parsed_cleanly() {
+ let mut buf = Vec::new();
+ let net = Net { bridge: "", ip: [0; 4], prefix: 0, gateway: [0; 4], extra_hosts: &[], dns_names: &[], opts: &[] };
+ encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost", "timerslack\t10000000"], &[]);
+ let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() };
+ let parsed = super::super::hostopts::parse(spec.opts).unwrap();
+ assert!(parsed.cgroupns_host);
+ assert_eq!(parsed.timer_slack_ns, Some(10_000_000));
+ let mut prepared = super::prepare(spec.argv, spec.env, spec.cwd, spec.user, Some(spec.hostname), spec.flags, spec.caps).unwrap();
+ assert!(!prepared.cgroupns_host);
+ assert_eq!(prepared.timer_slack_ns, None);
+ prepared.cgroupns_host = parsed.cgroupns_host;
+ prepared.timer_slack_ns = parsed.timer_slack_ns;
+ assert!(prepared.cgroupns_host);
+ assert_eq!(prepared.timer_slack_ns, Some(10_000_000));
+ let tmp = std::env::temp_dir().join(format!("kiri-timerslack-{}", std::process::id()));
+ super::apply_timer_slack_to(&tmp, 10_000_000).unwrap();
+ assert_eq!(std::fs::read_to_string(&tmp).unwrap(), "10000000");
+ let _ = std::fs::remove_file(&tmp);
+ }
+
+ #[test]
+ fn finish_stdio_times_out_when_tty_child_never_sends_pty_and_reaps_child() {
+ use std::os::fd::AsRawFd;
+ use std::time::{Duration, Instant};
+
+ // 1. Stuck child holding its socket end open: times out promptly instead of blocking forever.
+ let (p_sock, hold_child) = super::sys::socketpair().unwrap();
+ let dup_child = hold_child.try_clone().unwrap();
+ let began = Instant::now();
+ let err = super::finish_stdio_timeout(
+ super::ParentStdio::Tty { sock: p_sock },
+ super::ChildStdio::Tty { sock: dup_child },
+ Duration::from_millis(30),
+ )
+ .unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}");
+ assert!(began.elapsed() < Duration::from_secs(2));
+ drop(hold_child);
+
+ // 2. Child exits without sending an fd: reports premature exit.
+ let (p_sock, c_sock) = super::sys::socketpair().unwrap();
+ let err = super::finish_stdio_timeout(
+ super::ParentStdio::Tty { sock: p_sock },
+ super::ChildStdio::Tty { sock: c_sock },
+ Duration::from_secs(1),
+ )
+ .unwrap_err();
+ assert!(err.to_string().contains("exited before its terminal was ready"), "{err}");
+
+ // 3. Child sends a valid fd: returns non-blocking input + master fds.
+ let (p_sock, c_sock) = super::sys::socketpair().unwrap();
+ let (r_pipe, _w_pipe) = super::sys::pipe().unwrap();
+ super::sys::send_fd(c_sock.as_raw_fd(), r_pipe.as_raw_fd()).unwrap();
+ let (stdin, stdout, stderr) = super::finish_stdio_timeout(
+ super::ParentStdio::Tty { sock: p_sock },
+ super::ChildStdio::Tty { sock: c_sock },
+ Duration::from_secs(1),
+ )
+ .unwrap();
+ assert!(stdin.is_some() && stdout.is_some() && stderr.is_none());
+
+ // 4. Real forked child that pauses before sending pty: timeout + SIGKILL + waitpid leaves no zombie.
+ let (p_sock, c_sock) = super::sys::socketpair().unwrap();
+ // SAFETY: child only calls pause() and _exit(0), both async-signal-safe.
+ let pid = unsafe { libc::fork() };
+ assert!(pid >= 0);
+ if pid == 0 {
+ unsafe {
+ libc::pause();
+ libc::_exit(0);
+ }
+ }
+ let res = super::finish_stdio_timeout(
+ super::ParentStdio::Tty { sock: p_sock },
+ super::ChildStdio::Tty { sock: c_sock },
+ Duration::from_millis(25),
+ );
+ assert_eq!(res.unwrap_err().kind(), std::io::ErrorKind::TimedOut);
+ // SAFETY: killing and reaping the child we just forked.
+ unsafe {
+ assert_eq!(libc::kill(pid, libc::SIGKILL), 0);
+ assert_eq!(libc::waitpid(pid, std::ptr::null_mut(), 0), pid);
+ assert_eq!(libc::kill(pid, 0), -1);
+ assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH));
+ }
+ }
}
diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs
index f96b688f8..a859da474 100644
--- a/crates/kiri-init/src/linux/copy.rs
+++ b/crates/kiri-init/src/linux/copy.rs
@@ -8,17 +8,19 @@
//! child asks for it over a socket pair of its own, so a copy and a start at
//! the same moment share one mount (see `roots`, #227).
+use std::cell::RefCell;
+use std::error::Error as StdError;
use std::fs;
use std::io::{self, BufReader, BufWriter, Read, Write};
-use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
+use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{FileTypeExt, MetadataExt};
+use std::path::{Path, PathBuf};
-use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, copy_flags, copy_op};
-
-use std::cell::RefCell;
-use std::path::PathBuf;
+use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, StrList, copy_flags, copy_op};
-use super::container::Paths;
+use super::container::{self, Paths};
+use super::inroot;
use super::sys;
/// A copy child as the agent sees it: its end of the child's socket pair
@@ -118,7 +120,7 @@ pub fn on_readable(fd: i32, paths: &Paths) -> bool {
let id = lines.next().unwrap_or("");
let layers: Vec<&str> = lines.collect();
let got = match kind {
- "m" => super::roots::acquire(paths, id, &layers),
+ "m" => super::roots::acquire(paths, id, &layers, false),
"h" => super::roots::hold(paths, id),
_ => Err(io::Error::new(io::ErrorKind::InvalidInput, "unknown request")),
};
@@ -189,14 +191,18 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa
let result = match spec.op {
// These read the writable layer itself, next to the image's layers.
copy_op::DIFF | copy_op::COMMIT => layer_job(&mut conn, &spec, paths),
+ // And this one writes it, before the container ever runs.
+ copy_op::UPPER => upper_job(&mut conn, &spec, running, paths, &chan),
_ => {
- if let Err(e) = enter(&spec, running, paths, &chan) {
- return reply_error(&mut conn, &format!("container {}: {e}", spec.id));
- }
+ let mounts = match enter(&spec, running, paths, &chan) {
+ Ok(m) => m,
+ Err(e) => return reply_error(&mut conn, &format!("container {}: {e}", spec.id)),
+ };
+ drop(chan);
match spec.op {
- copy_op::IN => copy_in(&mut conn, &spec),
+ copy_op::IN => copy_in(&mut conn, &spec, &mounts),
copy_op::OUT | copy_op::STAT => copy_out(&mut conn, &spec),
- copy_op::EXPORT => export(&mut conn),
+ copy_op::EXPORT => export(&mut conn, &spec),
op => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unknown copy op {op}"))),
}
}
@@ -207,9 +213,59 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa
}
}
-/// Makes the container's root this process's `/`.
-fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> {
- let root = match running.iter().find(|(id, _)| *id == spec.id) {
+/// A mount active in the container's root view, used by `copy_in` to refuse
+/// writes into read-only mounts and to overwrite bind-mounted files in place.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct MountAccess {
+ target: PathBuf,
+ ro: bool,
+ tmpfs: bool,
+}
+
+/// Normalizes an absolute mount target path (`"/data/"` → `"/data"`, `"/"` stays `"/"`).
+fn clean_mount_target(target: &str) -> String {
+ let parts: Vec<&str> = target.split('/').filter(|c| !c.is_empty() && *c != ".").collect();
+ format!("/{}", parts.join("/"))
+}
+
+/// Pure parsing of `CopySpec::mounts` (no filesystem I/O): validates each line
+/// and sorts parent-first, matching `container::parse_mounts`.
+fn parse_mount_access(list: StrList<'_>) -> io::Result> {
+ let mut out = Vec::with_capacity(list.len());
+ for m in list.iter() {
+ let f: Vec<&str> = m.split('\t').collect();
+ if f.len() != 3 && f.len() != 7 {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}")));
+ }
+ let (given_target, words) = (f[1], f[2]);
+ if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}")));
+ }
+ let flags: Vec<&str> = words.split(',').filter(|w| !w.is_empty()).collect();
+ let tmpfs = flags.contains(&"tmpfs");
+ let ro = if tmpfs { container::tmpfs_flags(&flags) & libc::MS_RDONLY != 0 } else { flags.contains(&"ro") };
+ out.push(MountAccess { target: PathBuf::from(clean_mount_target(given_target)), ro, tmpfs });
+ }
+ out.sort_by_key(|m| m.target.components().count());
+ Ok(out)
+}
+
+/// Resolves each mount's target inside the container chroot so symlinks in
+/// mount target paths (e.g. `/var/run/cfg` → `/run/cfg`) match canonicalized
+/// destination paths.
+fn resolve_mount_targets(access: &mut [MountAccess]) {
+ for m in access {
+ if let Ok(real) = fs::canonicalize(&m.target) {
+ m.target = real;
+ }
+ }
+}
+
+/// Makes the container's root this process's `/`, assembling non-tmpfs volumes
+/// and bind mounts in a private mount namespace when the container is not
+/// running (except for `EXPORT`, which reads only the overlay rootfs).
+fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result> {
+ match running.iter().find(|(id, _)| *id == spec.id) {
// An export is the container's own filesystem, without its mounts:
// the overlay the agent mounted for it.
// It may have stopped since: then the root is mounted for it.
@@ -220,24 +276,70 @@ fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, ch
}
ask(chan, 'm', spec)?;
}
- paths.containers.join(spec.id).join("rootfs")
+ chroot_into(&paths.containers.join(spec.id).join("rootfs"))?;
+ Ok(Vec::new())
}
- // Through /proc the root shows the container's mounts (volumes) too.
- // The copy holds the container's root meanwhile, so a restart can't
- // mount a second one over the same layer while it still writes.
+ // Through /proc the root shows the container's live mounts (including
+ // tmpfs). The copy holds the container's root meanwhile, so a restart
+ // can't mount a second one over the same layer while it still writes.
Some((_, pid)) => {
let _ = ask(chan, 'h', spec);
- std::path::PathBuf::from(format!("/proc/{pid}/root"))
+ let mut access = parse_mount_access(spec.mounts)?;
+ chroot_into(&PathBuf::from(format!("/proc/{pid}/root")))?;
+ resolve_mount_targets(&mut access);
+ Ok(access)
}
None => {
if spec.layers.is_empty() {
return Err(io::Error::new(io::ErrorKind::NotFound, "no such container"));
}
ask(chan, 'm', spec)?;
- paths.containers.join(spec.id).join("rootfs")
+ let rootfs = paths.containers.join(spec.id).join("rootfs");
+ if spec.op == copy_op::EXPORT {
+ chroot_into(&rootfs)?;
+ return Ok(Vec::new());
+ }
+ // A stopped or created container has no live tmpfs mounts.
+ let mut access = parse_mount_access(spec.mounts)?;
+ access.retain(|m| !m.tmpfs);
+ if !access.is_empty() {
+ // Assemble mounts strictly inside this short-lived child's own
+ // mount namespace so nothing ever leaks into the agent's.
+ sys::unshare(libc::CLONE_NEWNS)?;
+ sys::remount(c"/", libc::MS_REC | libc::MS_SLAVE)?;
+ let mut mounts = container::parse_mounts(spec.mounts)?;
+ mounts.retain(|m| !m.is_tmpfs());
+ let rootfs_c = sys::cstr(&rootfs)?;
+ // SAFETY: valid NUL-terminated path.
+ unsafe { sys::check(libc::chdir(rootfs_c.as_ptr()) as _, "chdir")? };
+ let root = inroot::open_root(Path::new("."))?;
+ let image = if mounts.iter().any(container::Mount::is_copy_up) { container::image_tree() } else { None };
+ for m in &mounts {
+ container::apply_mount(root.as_fd(), image.as_ref().map(|f| f.as_fd()), m, false)?;
+ }
+ drop(image);
+ drop(root);
+ if spec.op == copy_op::IN && spec.flags & copy_flags::READONLY_ROOTFS != 0 {
+ // Defense in depth: remount only the rootfs mount read-only
+ // in our private namespace, leaving writable mounts rw.
+ sys::mount(c"none", c".", c"none", libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY, None)?;
+ }
+ // SAFETY: valid NUL-terminated paths.
+ unsafe {
+ sys::check(libc::chroot(c".".as_ptr()) as _, "chroot")?;
+ sys::check(libc::chdir(c"/".as_ptr()) as _, "chdir")?;
+ }
+ } else {
+ chroot_into(&rootfs)?;
+ }
+ resolve_mount_targets(&mut access);
+ Ok(access)
}
- };
- let c = sys::cstr(&root)?;
+ }
+}
+
+fn chroot_into(root: &Path) -> io::Result<()> {
+ let c = sys::cstr(root)?;
// SAFETY: valid NUL-terminated paths.
unsafe {
sys::check(libc::chroot(c.as_ptr()) as _, "chroot")?;
@@ -270,43 +372,143 @@ fn ask(chan: &OwnedFd, kind: char, spec: &CopySpec<'_>) -> io::Result<()> {
}
}
+/// Refuses writes when the innermost mount containing `canonical_path` is
+/// read-only, or when `canonical_path` is outside every mount and the
+/// container has `--read-only`.
+fn check_writable(canonical_path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Result<()> {
+ let innermost = mounts
+ .iter()
+ .filter(|m| canonical_path == m.target || canonical_path.starts_with(&m.target))
+ .max_by_key(|m| m.target.components().count());
+ match innermost {
+ Some(m) if m.ro => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only")),
+ Some(_) => Ok(()),
+ None if readonly_rootfs => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: container rootfs is marked read-only")),
+ None => Ok(()),
+ }
+}
+
+/// Resolves a tar entry's target path under `canonical_dest`, following
+/// existing symlinks in parent components (inside the container chroot) while
+/// keeping the final component unfollowed (since unpacking replaces a final
+/// symlink rather than writing through it).
+fn resolve_entry_target(canonical_dest: &Path, entry_path: &Path) -> PathBuf {
+ let mut parts: Vec<&std::ffi::OsStr> = Vec::new();
+ for c in entry_path.components() {
+ match c {
+ std::path::Component::Normal(p) => parts.push(p),
+ std::path::Component::ParentDir => {
+ parts.pop();
+ }
+ std::path::Component::CurDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
+ }
+ }
+ let Some((last, parents)) = parts.split_last() else {
+ return canonical_dest.to_path_buf();
+ };
+ let mut cur = canonical_dest.to_path_buf();
+ let mut exists = true;
+ for part in parents {
+ cur.push(part);
+ if exists {
+ match fs::canonicalize(&cur) {
+ Ok(real) => cur = real,
+ Err(_) => exists = false,
+ }
+ }
+ }
+ cur.push(last);
+ cur
+}
+
+fn is_erofs(e: &io::Error) -> bool {
+ if e.raw_os_error() == Some(libc::EROFS) {
+ return true;
+ }
+ let mut cur: Option<&(dyn StdError + 'static)> = e.source();
+ while let Some(src) = cur {
+ if src.downcast_ref::().is_some_and(|ioe| ioe.raw_os_error() == Some(libc::EROFS)) {
+ return true;
+ }
+ cur = src.source();
+ }
+ false
+}
+
+fn map_erofs(e: io::Error, path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Error {
+ if !is_erofs(&e) {
+ return e;
+ }
+ match check_writable(path, mounts, readonly_rootfs) {
+ Err(ro) => ro,
+ Ok(()) => io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only"),
+ }
+}
+
+/// Overwrites an existing bind-mounted regular file in place: `unlink(2)` on a
+/// file bind mount fails with `EBUSY`, so `tar::Entry::unpack_in` cannot
+/// replace it by remove-and-recreate.
+fn unpack_mount_file(entry: &mut tar::Entry<'_, R>, target: &Path, owner: Option<(libc::uid_t, libc::gid_t)>) -> io::Result<()> {
+ let c = sys::cstr(target)?;
+ // SAFETY: valid NUL-terminated path; O_NOFOLLOW never follows a symlink,
+ // and O_NONBLOCK avoids blocking if a FIFO was swapped in.
+ let fd = unsafe { libc::open(c.as_ptr(), libc::O_WRONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) };
+ if fd < 0 {
+ return Err(io::Error::last_os_error());
+ }
+ // SAFETY: fresh descriptor owned only here.
+ let mut file = fs::File::from(unsafe { OwnedFd::from_raw_fd(fd) });
+ // SAFETY: plain zeroed stat filled from our own descriptor.
+ let mut st: libc::stat = unsafe { std::mem::zeroed() };
+ sys::check(unsafe { libc::fstat(file.as_raw_fd(), &mut st) } as _, "fstat")?;
+ if st.st_mode & libc::S_IFMT != libc::S_IFREG {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput, "mount target is not a regular file"));
+ }
+ // SAFETY: valid regular-file descriptor we own.
+ sys::check(unsafe { libc::ftruncate(file.as_raw_fd(), 0) } as _, "ftruncate")?;
+ io::copy(entry, &mut file)?;
+ if let Some((uid, gid)) = owner {
+ // SAFETY: valid descriptor we own.
+ sys::check(unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } as _, "fchown")?;
+ } else if let (Ok(uid), Ok(gid)) = (entry.header().uid(), entry.header().gid()) {
+ // SAFETY: valid descriptor we own; best-effort like tar::Archive.
+ unsafe { libc::fchown(file.as_raw_fd(), uid as libc::uid_t, gid as libc::gid_t) };
+ }
+ if let Ok(mode) = entry.header().mode() {
+ // SAFETY: valid descriptor we own.
+ sys::check(unsafe { libc::fchmod(file.as_raw_fd(), (mode & 0o7777) as libc::mode_t) } as _, "fchmod")?;
+ }
+ if let Ok(mtime) = entry.header().mtime() {
+ let times = [
+ libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT },
+ libc::timespec { tv_sec: mtime as _, tv_nsec: 0 },
+ ];
+ // SAFETY: valid descriptor and 2-element timespec array.
+ unsafe { libc::futimens(file.as_raw_fd(), times.as_ptr()) };
+ }
+ Ok(())
+}
+
/// Unpacks the archive that follows into `spec.path`, a directory.
-fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> {
- let dest = std::path::Path::new(spec.path);
+fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>, mounts: &[MountAccess]) -> io::Result<()> {
+ let (path, user) = if spec.flags & copy_flags::KEEP_OWNERS != 0 {
+ spec.path.split_once('\0').unwrap_or((spec.path, ""))
+ } else {
+ (spec.path, "")
+ };
+ let dest = std::path::Path::new(path);
match fs::metadata(dest) {
Ok(m) if m.is_dir() => {}
- Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {}", spec.path))),
- Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id))),
+ Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {path}"))),
+ Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {path} in container {}", spec.id))),
}
+ let canonical_dest = fs::canonicalize(dest)?;
+ let readonly_rootfs = spec.flags & copy_flags::READONLY_ROOTFS != 0;
+ check_writable(&canonical_dest, mounts, readonly_rootfs)?;
+ let owner = if user.is_empty() { None } else { Some(resolve_copy_user_in(std::path::Path::new("/"), user)?) };
let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) };
let mut reader = BufReader::with_capacity(256 * 1024, source);
- {
- let mut archive = tar::Archive::new(&mut reader);
- archive.set_preserve_permissions(true);
- archive.set_preserve_mtime(true);
- archive.set_preserve_ownerships(spec.flags & copy_flags::KEEP_OWNERS != 0);
- archive.set_unpack_xattrs(false);
- archive.set_overwrite(true);
- for entry in archive.entries()? {
- let mut entry = entry?;
- if spec.flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 {
- let target = dest.join(entry.path()?);
- if let Ok(m) = fs::symlink_metadata(&target) {
- if m.is_dir() != entry.header().entry_type().is_dir() {
- return Err(io::Error::new(
- io::ErrorKind::AlreadyExists,
- format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }),
- ));
- }
- }
- }
- let path = entry.path()?.into_owned();
- // `docker cp` and the classic build's context keep a time of 0.
- if entry.unpack_in(dest)? {
- super::layers::keep_zero_time(dest, &path, entry.header())?;
- }
- }
- }
+ unpack_in(&mut reader, dest, &canonical_dest, spec.flags, owner, mounts, readonly_rootfs)?;
// The archive's trailing padding: read it so the host's writes complete.
io::copy(&mut reader, &mut io::sink())?;
drop(reader);
@@ -315,6 +517,140 @@ fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> {
conn.write_all(&out)
}
+/// Moby's `applyTarCopyUserOptions` (`getUIDGID`): resolves a container's
+/// non-empty `Config.User` (`user[:group]`) against its `/etc/passwd` and
+/// `/etc/group` when `copyUIDGID` (`docker cp -a`) is set.
+fn resolve_copy_user_in(root: &std::path::Path, user: &str) -> io::Result<(libc::uid_t, libc::gid_t)> {
+ let (u, g) = user.split_once(':').unwrap_or((user, ""));
+ let (mut uid, mut gid) = (0, 0);
+ if !u.is_empty() {
+ let passwd = fs::read_to_string(root.join("etc/passwd")).unwrap_or_default();
+ if let Ok(id) = u.parse::()
+ && id <= i32::MAX as u32
+ {
+ uid = id;
+ gid = passwd
+ .lines()
+ .find_map(|l| {
+ let mut f = l.split(':');
+ (f.nth(2)?.parse::().ok()? == id).then(|| f.next()?.parse::().ok()).flatten()
+ })
+ .unwrap_or(0);
+ } else {
+ (uid, gid) = passwd
+ .lines()
+ .find_map(|l| {
+ let mut f = l.split(':');
+ if f.next()? != u {
+ return None;
+ }
+ Some((f.nth(1)?.parse::().ok()?, f.next()?.parse::().ok()?))
+ })
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up user {u:?} in container")))?;
+ }
+ }
+ if !g.is_empty() {
+ if let Ok(id) = g.parse::()
+ && id <= i32::MAX as u32
+ {
+ gid = id;
+ } else {
+ let group = fs::read_to_string(root.join("etc/group")).unwrap_or_default();
+ gid = group
+ .lines()
+ .find_map(|l| {
+ let mut f = l.split(':');
+ if f.next()? != g {
+ return None;
+ }
+ f.nth(1)?.parse::().ok()
+ })
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up group {g:?} in container")))?;
+ }
+ }
+ Ok((uid, gid))
+}
+
+fn unpack_in(
+ reader: impl Read,
+ dest: &std::path::Path,
+ canonical_dest: &std::path::Path,
+ flags: u32,
+ owner: Option<(libc::uid_t, libc::gid_t)>,
+ mounts: &[MountAccess],
+ readonly_rootfs: bool,
+) -> io::Result<()> {
+ let mut archive = tar::Archive::new(reader);
+ archive.set_preserve_permissions(true);
+ archive.set_preserve_mtime(true);
+ // Moby's `defaultTarCopyOptions` preserves the archive's header UID/GID
+ // (`ChownOpts == nil`); when `copyUIDGID` (`docker cp -a`) is set on a
+ // container with a non-empty `Config.User`, `applyTarCopyUserOptions`
+ // sets `ChownOpts` (`owner`) to chown every unpacked entry to that user.
+ archive.set_preserve_ownerships(owner.is_none());
+ archive.set_unpack_xattrs(false);
+ archive.set_overwrite(true);
+ for entry in archive.entries()? {
+ let mut entry = entry?;
+ let path = entry.path()?.into_owned();
+ let etype = entry.header().entry_type();
+ let check_path = if !etype.is_pax_global_extensions() && !etype.is_pax_local_extensions() {
+ let resolved = resolve_entry_target(canonical_dest, &path);
+ check_writable(&resolved, mounts, readonly_rootfs)?;
+ Some(resolved)
+ } else {
+ None
+ };
+ if flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 {
+ let target = dest.join(&path);
+ if let Ok(m) = fs::symlink_metadata(&target)
+ && m.is_dir() != etype.is_dir()
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::AlreadyExists,
+ format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }),
+ ));
+ }
+ }
+ if let Some(ref resolved) = check_path
+ && etype.is_file()
+ && mounts.iter().any(|m| m.target == *resolved)
+ && fs::symlink_metadata(resolved).is_ok_and(|m| m.file_type().is_file())
+ {
+ unpack_mount_file(&mut entry, resolved, owner).map_err(|e| map_erofs(e, resolved, mounts, readonly_rootfs))?;
+ continue;
+ }
+ // `docker cp` and the classic build's context keep a time of 0.
+ let target_for_err = check_path.as_deref().unwrap_or(canonical_dest);
+ if entry.unpack_in(dest).map_err(|e| map_erofs(e, target_for_err, mounts, readonly_rootfs))? {
+ if let Some((uid, gid)) = owner
+ && !etype.is_pax_global_extensions()
+ {
+ let mut file_dst = dest.to_path_buf();
+ for part in path.components() {
+ if let std::path::Component::Normal(p) = part {
+ file_dst.push(p);
+ }
+ }
+ if file_dst != dest {
+ let c = sys::cstr(&file_dst)?;
+ // SAFETY: valid NUL-terminated path inside the container chroot.
+ sys::check(unsafe { libc::lchown(c.as_ptr(), uid, gid) } as _, "lchown")?;
+ if !fs::symlink_metadata(&file_dst)?.file_type().is_symlink()
+ && let Ok(mode) = entry.header().mode()
+ && mode & 0o6000 != 0
+ {
+ // SAFETY: valid NUL-terminated non-symlink path.
+ sys::check(unsafe { libc::chmod(c.as_ptr(), (mode & 0o7777) as libc::mode_t) } as _, "chmod")?;
+ }
+ }
+ }
+ super::layers::keep_zero_time(dest, &path, entry.header())?;
+ }
+ }
+ Ok(())
+}
+
/// A `copy_flags::CHUNKED` archive: chunks of `len: u32 LE | bytes`, read
/// as one stream that ends at the empty chunk, with the connection still
/// open for the answer.
@@ -351,15 +687,105 @@ impl Read for Chunks {
}
}
+const PACED_CHUNK: usize = 64 * 1024;
+
+/// A `copy_flags::PACED` writer: sends the archive in `<= 64 KiB` chunks
+/// (`len: u32 LE | bytes`), waiting for a 1-byte credit ack from the host
+/// before sending each chunk, then an empty chunk at the end (#874).
+struct PacedWriter {
+ conn: S,
+ buf: Vec,
+}
+
+impl PacedWriter {
+ fn new(conn: S) -> Self {
+ let mut buf = Vec::with_capacity(4 + PACED_CHUNK);
+ buf.resize(4, 0);
+ Self { conn, buf }
+ }
+
+ fn flush_chunk(&mut self) -> io::Result<()> {
+ let payload = self.buf.len() - 4;
+ if payload == 0 {
+ return Ok(());
+ }
+ let mut ack = [0u8; 1];
+ self.conn.read_exact(&mut ack)?;
+ self.buf[..4].copy_from_slice(&(payload as u32).to_le_bytes());
+ self.conn.write_all(&self.buf)?;
+ self.buf.truncate(4);
+ Ok(())
+ }
+
+ fn finish(mut self) -> io::Result<()> {
+ self.flush_chunk()?;
+ let mut ack = [0u8; 1];
+ self.conn.read_exact(&mut ack)?;
+ self.conn.write_all(&0u32.to_le_bytes())?;
+ Ok(())
+ }
+}
+
+impl Write for PacedWriter {
+ fn write(&mut self, data: &[u8]) -> io::Result {
+ if data.is_empty() {
+ return Ok(0);
+ }
+ if self.buf.len() - 4 == PACED_CHUNK {
+ self.flush_chunk()?;
+ }
+ let room = PACED_CHUNK - (self.buf.len() - 4);
+ let n = data.len().min(room);
+ self.buf.extend_from_slice(&data[..n]);
+ Ok(n)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.flush_chunk()?;
+ self.conn.flush()
+ }
+}
+
+fn stream_tar(conn: &mut fs::File, paced: bool, build: impl FnOnce(&mut tar::Builder<&mut dyn Write>) -> io::Result<()>) -> io::Result<()> {
+ if paced {
+ let mut w = PacedWriter::new(&mut *conn);
+ {
+ let mut b = tar::Builder::new(&mut w as &mut dyn Write);
+ b.follow_symlinks(false);
+ build(&mut b)?;
+ b.finish()?;
+ }
+ w.finish()
+ } else {
+ let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn);
+ {
+ let mut b = tar::Builder::new(&mut w as &mut dyn Write);
+ b.follow_symlinks(false);
+ build(&mut b)?;
+ b.finish()?;
+ }
+ w.flush()
+ }
+}
+
/// Answers with the path's metadata; for `OUT` an archive of it follows.
fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> {
- let path = std::path::Path::new(spec.path);
+ // Docker archives a path with its "." and ".." resolved by name, but
+ // stats it as given.
+ let cleaned;
+ let source = if spec.op == copy_op::OUT && !spec.path.is_empty() {
+ cleaned = archived(spec.path);
+ cleaned.as_str()
+ } else {
+ spec.path
+ };
+ let path = std::path::Path::new(source);
let meta = fs::symlink_metadata(path)
.map_err(|_| io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id)))?;
let link = if meta.file_type().is_symlink() { fs::read_link(path)?.to_string_lossy().into_owned() } else { String::new() };
- let name = path.file_name().map_or_else(|| "/".to_owned(), |n| n.to_string_lossy().into_owned());
+ let name = base(source);
let entry = FsEntry {
- name: &name,
+ name,
mode: meta.mode(),
size: meta.len(),
mtime: meta.mtime(),
@@ -372,20 +798,56 @@ fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> {
if spec.op == copy_op::STAT {
return Ok(());
}
- let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn);
- {
- let mut b = tar::Builder::new(&mut w);
- b.follow_symlinks(false);
- // The root itself archives as its contents under ".".
- let top = if name == "/" { "." } else { name.as_str() };
+ let paced = spec.flags & copy_flags::PACED != 0;
+ stream_tar(conn, paced, |b| {
if meta.is_dir() {
- append_tree(&mut b, path, std::path::Path::new(top))?;
+ append_tree(b, path, std::path::Path::new(name))
} else {
- append_one(&mut b, path, std::path::Path::new(top), &meta)?;
+ append_one(b, path, std::path::Path::new(name), &meta)
+ }
+ })
+}
+
+/// The last component of `path` as Docker names it: "." and ".." are kept,
+/// and the root is "/".
+fn base(path: &str) -> &str {
+ path.trim_end_matches('/').rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or("/")
+}
+
+/// The path an archive is read from: `path` with its dots resolved by name.
+/// Where that names nothing, `path` as given, so that every path found
+/// before is still found: the window follows a start script's relative
+/// link by asking for the link's directory, "..", and the rest, and behind
+/// a linked directory (/bin on many images) only the kernel finds that.
+fn archived(path: &str) -> String {
+ let cleaned = clean(path);
+ if fs::symlink_metadata(&cleaned).is_ok() { cleaned } else { path.to_owned() }
+}
+
+/// `path` from the root, with "." and ".." resolved by name. A final "." (a
+/// directory's contents) and a trailing "/" (a link's directory) are kept.
+fn clean(path: &str) -> String {
+ let mut parts: Vec<&str> = Vec::new();
+ for part in path.split('/') {
+ match part {
+ "" | "." => {}
+ ".." => {
+ parts.pop();
+ }
+ name => parts.push(name),
}
- b.finish()?;
}
- w.flush()
+ let mut cleaned = format!("/{}", parts.join("/"));
+ if base(path) == "." {
+ if !cleaned.ends_with('/') {
+ cleaned.push('/');
+ }
+ cleaned.push('.');
+ }
+ if path.ends_with('/') && !cleaned.ends_with('/') {
+ cleaned.push('/');
+ }
+ cleaned
}
/// Like `append_dir_all`, but sockets (which tar cannot hold) are skipped,
@@ -432,11 +894,16 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st
if ft.is_socket() {
return Ok(());
}
+ // A directory's contents under "./" and the root's under "/" keep those names.
+ let verbatim = name.as_os_str().as_bytes().starts_with(b"./") || name.has_root();
if ft.is_file() {
let mut h = tar::Header::new_gnu();
h.set_metadata(meta);
h.set_mode(mode_bits(meta));
let mut f = fs::File::open(src)?;
+ if verbatim {
+ return append_contents(b, &mut h, name, None, &mut f);
+ }
return b.append_data(&mut h, name, &mut f);
}
if ft.is_dir() || ft.is_symlink() || ft.is_fifo() || ft.is_char_device() || ft.is_block_device() {
@@ -445,18 +912,53 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st
h.set_mode(mode_bits(meta));
h.set_size(0);
if ft.is_symlink() {
- return b.append_link(&mut h, name, fs::read_link(src)?);
+ let link = fs::read_link(src)?;
+ if verbatim {
+ return append_contents(b, &mut h, name, Some(&link), io::empty());
+ }
+ return b.append_link(&mut h, name, link);
}
if ft.is_char_device() || ft.is_block_device() {
let rdev = meta.rdev();
h.set_device_major(libc::major(rdev))?;
h.set_device_minor(libc::minor(rdev))?;
}
+ if verbatim {
+ return append_contents(b, &mut h, name, None, io::empty());
+ }
return b.append_data(&mut h, name, io::empty());
}
Ok(())
}
+/// tar's path setter drops "./" and refuses a leading "/". Docker's client
+/// needs "./" when it rebases a directory-contents archive into a destination
+/// that does not exist, and puts the new name in front of the root's "/".
+/// These paths come from append_tree's "." or "/" plus directory entry names.
+fn append_contents(b: &mut tar::Builder, h: &mut tar::Header, name: &std::path::Path, link: Option<&std::path::Path>, data: impl Read) -> io::Result<()> {
+ fn field(b: &mut tar::Builder, slot: &mut [u8], bytes: &[u8], kind: u8) -> io::Result<()> {
+ if bytes.len() > slot.len() {
+ let mut long = tar::Header::new_gnu();
+ long.set_path("././@LongLink")?;
+ long.set_entry_type(tar::EntryType::new(kind));
+ long.set_mode(0o644);
+ long.set_size(bytes.len() as u64 + 1);
+ long.set_cksum();
+ b.append(&long, bytes.chain(io::repeat(0).take(1)))?;
+ }
+ slot.fill(0);
+ let count = bytes.len().min(slot.len());
+ slot[..count].copy_from_slice(&bytes[..count]);
+ Ok(())
+ }
+ field(b, &mut h.as_old_mut().name, name.as_os_str().as_bytes(), b'L')?;
+ if let Some(link) = link {
+ field(b, &mut h.as_old_mut().linkname, link.as_os_str().as_bytes(), b'K')?;
+ }
+ h.set_cksum();
+ b.append(h, data)
+}
+
fn done(conn: &mut fs::File) -> io::Result<()> {
let mut out = Vec::new();
Msg::CopyDone.encode(&mut out);
@@ -465,20 +967,17 @@ fn done(conn: &mut fs::File) -> io::Result<()> {
/// `docker export`: everything under `/` (the chroot), entries named
/// without a leading slash, as Docker writes them.
-fn export(conn: &mut fs::File) -> io::Result<()> {
+fn export(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> {
done(conn)?;
- let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn);
- {
- let mut b = tar::Builder::new(&mut w);
- b.follow_symlinks(false);
+ let paced = spec.flags & copy_flags::PACED != 0;
+ stream_tar(conn, paced, |b| {
let mut children: Vec<_> = fs::read_dir("/")?.flatten().collect();
children.sort_by_key(|e| e.file_name());
for e in children {
- append_tree(&mut b, &e.path(), std::path::Path::new(&e.file_name()))?;
+ append_tree(b, &e.path(), std::path::Path::new(&e.file_name()))?;
}
- b.finish()?;
- }
- w.flush()
+ Ok(())
+ })
}
/// An overlay whiteout: a 0:0 character device.
@@ -494,6 +993,38 @@ fn is_opaque(path: &std::path::Path) -> bool {
n == 1 && v[0] == b'y'
}
+/// The marker as the agent made it at start: not a change the container
+/// made, so Docker shows it in neither `docker diff` nor a committed layer.
+/// Once the container has written to it or changed its mode or owner, it is
+/// a change like any other.
+fn is_marker(rel: &std::path::Path, m: &fs::Metadata) -> bool {
+ is_marker_attr(rel, m.file_type().is_file(), m.len(), m.mode(), m.uid(), m.gid())
+}
+
+fn is_marker_attr(rel: &std::path::Path, is_file: bool, len: u64, mode: u32, uid: u32, gid: u32) -> bool {
+ rel.as_os_str().as_encoded_bytes() == container::MARKER.to_bytes()
+ && is_file
+ && len == 0
+ && mode & 0o7777 == 0o755
+ && uid == 0
+ && gid == 0
+}
+
+fn in_lower_layers(lowers: &[OwnedFd], rel: &std::path::Path) -> bool {
+ for l in lowers {
+ let Some(rel) = rel.to_str() else { continue };
+ let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue };
+ // SAFETY: fstat into a zeroed stat on a descriptor we own.
+ let mut st: libc::stat = unsafe { std::mem::zeroed() };
+ if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
+ continue;
+ }
+ let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0;
+ return !whiteout;
+ }
+ false
+}
+
/// `docker diff` and `docker commit`, from the writable layer.
fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Result<()> {
if spec.layers.is_empty() {
@@ -513,6 +1044,7 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res
(fd >= 0).then(|| unsafe { OwnedFd::from_raw_fd(fd) })
})
.collect();
+ let in_lower = |rel: &std::path::Path| in_lower_layers(&lowers, rel);
// A running container writes its upper layer while we walk it, and could
// swap a directory for a link to `/` between our look and our read
// (`docker diff`, `commit --pause=false`). Inside a chroot of the layer
@@ -542,6 +1074,9 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res
for e in names.into_iter().rev() {
let r = rel.join(e.file_name());
let Ok(m) = fs::symlink_metadata(e.path()) else { continue };
+ if is_marker(&r, &m) && !in_lower(&r) {
+ continue;
+ }
if m.is_dir() {
stack.push(r.clone());
}
@@ -551,20 +1086,6 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res
entries.sort_by(|a, b| a.0.cmp(&b.0));
done(conn)?;
if spec.op == copy_op::DIFF {
- let in_lower = |rel: &std::path::Path| {
- for l in &lowers {
- let Some(rel) = rel.to_str() else { continue };
- let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue };
- // SAFETY: fstat into a zeroed stat on a descriptor we own.
- let mut st: libc::stat = unsafe { std::mem::zeroed() };
- if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
- continue;
- }
- let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0;
- return !whiteout;
- }
- false
- };
let mut w = BufWriter::new(&mut *conn);
for (rel, m) in &entries {
let kind = if is_whiteout(m) {
@@ -606,6 +1127,114 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res
w.flush()
}
+/// `kiri import`: the writable layer a container had on the engine it came
+/// from, as an OCI layer tar (see `copy_op::UPPER`), becomes its own before
+/// it ever runs. Writing under the upper dir of a mounted overlay is
+/// undefined behaviour to the kernel, so a running container, or one whose
+/// root is mounted for a copy, is refused, as is one that has a writable
+/// layer already.
+fn upper_job(conn: &mut fs::File, spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> {
+ if spec.layers.is_empty() {
+ return reply_error(conn, "no such container");
+ }
+ container::valid_id(spec.id)?;
+ // `h` holds a root only when it is mounted; this child exits soon and
+ // lets it go again.
+ if running.iter().any(|(id, _)| *id == spec.id) || ask(chan, 'h', spec).is_ok() {
+ return reply_error(conn, &format!("container {} is in use: its writable layer can only be brought in before it runs", spec.id));
+ }
+ let base = paths.containers.join(spec.id);
+ if fs::read_dir(base.join("upper")).is_ok_and(|mut d| d.next().is_some()) {
+ return reply_error(conn, &format!("container {} already has a writable layer of its own", spec.id));
+ }
+ let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) };
+ import_upper(BufReader::with_capacity(256 * 1024, source), &base)?;
+ done(conn)
+}
+
+/// Unpacks the layer `reader` holds into ` /upper`. It is unpacked
+/// beside it first and moved in whole, so a copy cut short leaves the
+/// container as it was; overlayfs's own attributes are stripped, and the
+/// layer is marked plain (`container::mark_plain_upper`).
+fn import_upper(mut reader: impl Read, base: &Path) -> io::Result<()> {
+ let upper = base.join("upper");
+ let staging = base.join("upper.import");
+ fs::create_dir_all(base)?;
+ match fs::remove_dir_all(&staging) {
+ Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
+ _ => {}
+ }
+ fs::create_dir(&staging)?;
+ let unpacked = (|| -> io::Result<()> {
+ // The root of the container's filesystem takes this directory's
+ // mode and owner, as with the `upper` a first start makes.
+ fs::set_permissions(&staging, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
+ super::layers::untar(&mut reader, &staging)?;
+ // The archive's trailing padding, so the host's writes complete.
+ io::copy(&mut reader, &mut io::sink())?;
+ strip_overlay_xattrs(&staging)?;
+ // An empty `upper` an earlier copy's mount left goes first.
+ match fs::remove_dir(&upper) {
+ Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
+ _ => {}
+ }
+ fs::rename(&staging, &upper)
+ })();
+ if let Err(e) = unpacked {
+ let _ = fs::remove_dir_all(&staging);
+ return Err(e);
+ }
+ container::mark_plain_upper(base)
+}
+
+/// Removes overlayfs's own attributes (`trusted.overlay.*`: redirects,
+/// metacopy, origin) from everything under `root`, keeping the opaque mark
+/// `layers::untar` sets for `.wh..wh..opq`. An imported layer is whole
+/// files and directories; an attribute an archive carried must not make
+/// the mount look elsewhere for them.
+fn strip_overlay_xattrs(root: &Path) -> io::Result<()> {
+ let mut stack = vec![root.to_path_buf()];
+ while let Some(path) = stack.pop() {
+ let meta = fs::symlink_metadata(&path)?;
+ let c = sys::cstr(&path)?;
+ let mut names = vec![0u8; 4096];
+ let n = loop {
+ // SAFETY: valid NUL-terminated path; fills at most `names.len()` bytes.
+ let n = unsafe { libc::llistxattr(c.as_ptr(), names.as_mut_ptr().cast(), names.len()) };
+ if n >= 0 {
+ break n as usize;
+ }
+ match io::Error::last_os_error() {
+ e if e.raw_os_error() == Some(libc::ERANGE) && names.len() < 1 << 20 => names.resize(names.len() * 4, 0),
+ e if e.raw_os_error() == Some(libc::ENOTSUP) => break 0,
+ e => return Err(e),
+ }
+ };
+ for name in names[..n].split(|b| *b == 0).filter(|name| overlay_own(name)) {
+ let name = std::ffi::CString::new(name).map_err(io::Error::other)?;
+ // SAFETY: valid NUL-terminated path and attribute name.
+ if unsafe { libc::lremovexattr(c.as_ptr(), name.as_ptr()) } != 0 {
+ let e = io::Error::last_os_error();
+ if e.raw_os_error() != Some(libc::ENODATA) {
+ return Err(e);
+ }
+ }
+ }
+ if meta.is_dir() {
+ for e in fs::read_dir(&path)? {
+ stack.push(e?.path());
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Whether an extended attribute is one overlayfs reads in an upper dir,
+/// other than the opaque mark.
+fn overlay_own(name: &[u8]) -> bool {
+ name.starts_with(b"trusted.overlay.") && name != b"trusted.overlay.opaque"
+}
+
fn reply_error(conn: &mut fs::File, msg: &str) -> io::Result<()> {
let mut out = Vec::new();
Msg::Error(msg).encode(&mut out);
@@ -624,6 +1253,184 @@ fn read_frame(conn: &mut impl Read, buf: &mut Vec) -> io::Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn only_overlayfs_own_attributes_but_the_opaque_mark_are_stripped() {
+ assert!(overlay_own(b"trusted.overlay.redirect"));
+ assert!(overlay_own(b"trusted.overlay.metacopy"));
+ assert!(overlay_own(b"trusted.overlay.origin"));
+ assert!(!overlay_own(b"trusted.overlay.opaque"));
+ assert!(!overlay_own(b"security.capability"));
+ assert!(!overlay_own(b"user.overlay.redirect"));
+ assert!(!overlay_own(b"trusted.overlayx"));
+ }
+
+ /// `kiri import` (#410): a writable layer from another engine becomes
+ /// the container's `upper`, whiteouts and opaque marks as overlayfs reads
+ /// them, owners and links kept, overlayfs's own attributes gone, marked
+ /// plain; one cut short leaves nothing behind.
+ #[test]
+ fn an_imported_writable_layer_becomes_the_upper_dir_whole() {
+ // SAFETY: a plain getter.
+ if unsafe { libc::geteuid() } != 0 {
+ eprintln!("skipped: needs root for owners, whiteouts and trusted attributes");
+ return;
+ }
+ let base = std::env::temp_dir().join(format!("kiri-import-upper-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&base);
+ let layer = |cut: bool| {
+ let mut b = tar::Builder::new(Vec::new());
+ let h = |kind: tar::EntryType, size: u64, mode: u32, owner: u64| {
+ let mut h = tar::Header::new_ustar();
+ h.set_entry_type(kind);
+ h.set_size(size);
+ h.set_mode(mode);
+ h.set_uid(owner);
+ h.set_gid(owner);
+ h.set_mtime(1_700_000_000);
+ h
+ };
+ b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750, 1000), "added/", io::empty()).unwrap();
+ b.append_pax_extensions([("SCHILY.xattr.trusted.overlay.redirect", &b"/elsewhere"[..])]).unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 5, 0o640, 1000), "added/file", &b"hello"[..]).unwrap();
+ b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777, 0), "link", "added/file").unwrap();
+ b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "etc/", io::empty()).unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "etc/.wh.gone", io::empty()).unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 4, 0o644, 0), "etc/motd", &b"new\n"[..]).unwrap();
+ b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "again/", io::empty()).unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "again/.wh..wh..opq", io::empty()).unwrap();
+ let mut bytes = b.into_inner().unwrap();
+ if cut {
+ // Inside the first file's body.
+ bytes.truncate(512 * 4 + 2);
+ }
+ bytes
+ };
+
+ // Cut short: an error, and neither `upper` nor its staging is left.
+ assert!(import_upper(&layer(true)[..], &base).is_err());
+ assert!(!base.join("upper").exists() && !base.join("upper.import").exists() && !base.join(super::container::PLAIN_UPPER).exists());
+
+ // An empty `upper` (an earlier copy's mount made it) is taken over.
+ fs::create_dir_all(base.join("upper")).unwrap();
+ import_upper(&layer(false)[..], &base).unwrap();
+ let upper = base.join("upper");
+ let meta = |p: &str| fs::symlink_metadata(upper.join(p)).unwrap();
+ assert!(!base.join("upper.import").exists());
+ assert!(base.join(super::container::PLAIN_UPPER).exists(), "marked plain");
+ assert_eq!(meta("").mode() & 0o7777, 0o755);
+ let added = meta("added");
+ assert_eq!((added.uid(), added.gid(), added.mode() & 0o7777, added.mtime()), (1000, 1000, 0o750, 1_700_000_000));
+ let file = meta("added/file");
+ assert_eq!((file.uid(), file.gid(), file.mode() & 0o7777), (1000, 1000, 0o640));
+ assert_eq!(fs::read(upper.join("added/file")).unwrap(), b"hello");
+ assert_eq!(fs::read_link(upper.join("link")).unwrap(), Path::new("added/file"));
+ assert_eq!(fs::read(upper.join("etc/motd")).unwrap(), b"new\n");
+ assert!(is_whiteout(&meta("etc/gone")), "a 0:0 character device");
+ assert!(!upper.join("etc/.wh.gone").exists());
+ assert!(is_opaque(&upper.join("again")));
+ assert!(!upper.join("again/.wh..wh..opq").exists());
+ let c = sys::cstr(upper.join("added/file")).unwrap();
+ // SAFETY: valid path and name; a size query.
+ let redirect = unsafe { libc::lgetxattr(c.as_ptr(), c"trusted.overlay.redirect".as_ptr(), std::ptr::null_mut(), 0) };
+ assert!(redirect < 0, "overlayfs's own attribute stripped");
+
+ let _ = fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn contents_keep_dot_prefix_and_long_names() {
+ for length in [4, 98, 99, 100, 101, 255] {
+ let name = format!("./{}", "a".repeat(length));
+ let link = "../".to_owned() + &"b".repeat(length);
+ let mut bytes = Vec::new();
+ {
+ let mut archive = tar::Builder::new(&mut bytes);
+ let mut header = tar::Header::new_gnu();
+ header.set_entry_type(tar::EntryType::Symlink);
+ header.set_size(0);
+ append_contents(&mut archive, &mut header, std::path::Path::new(&name), Some(std::path::Path::new(&link)), io::empty()).unwrap();
+ archive.finish().unwrap();
+ }
+ let mut archive = tar::Archive::new(bytes.as_slice());
+ let mut entries = archive.entries().unwrap();
+ let entry = entries.next().unwrap().unwrap();
+ assert_eq!(entry.path_bytes().as_ref(), name.as_bytes());
+ assert_eq!(entry.link_name_bytes().unwrap().as_ref(), link.as_bytes());
+ assert!(entries.next().is_none());
+ }
+ }
+
+ #[test]
+ fn archived_paths_resolve_dots_by_name_and_stats_keep_them() {
+ for (path, cleaned, name) in [
+ ("/t/dir", "/t/dir", "dir"),
+ ("/t/dir/", "/t/dir/", "dir"),
+ ("/t/dir/.", "/t/dir/.", "."),
+ ("/t/dir/./", "/t/dir/./", "."),
+ ("/t/dir//.", "/t/dir/.", "."),
+ ("/t/dir/sub/..", "/t/dir", "dir"),
+ ("/t/dir/sub/../", "/t/dir/", "dir"),
+ ("/t/dir/sub/../.", "/t/dir/.", "."),
+ ("/t/link/../dir", "/t/dir", "dir"),
+ ("t/dir/..", "/t", "t"),
+ ("../../t/dir/.", "/t/dir/.", "."),
+ ("/", "/", "/"),
+ ("//", "/", "/"),
+ ("/.", "/.", "."),
+ ("/..", "/", "/"),
+ ("/etc/..", "/", "/"),
+ ("/etc/../.", "/.", "."),
+ (".", "/.", "."),
+ ("..", "/", "/"),
+ ] {
+ assert_eq!(clean(path), cleaned, "{path}");
+ assert_eq!(base(cleaned), name, "{path}");
+ }
+ for (path, name) in [("/t/dir/sub/..", ".."), ("/t/dir/sub/../", ".."), ("/t/dir/.", "."), ("/t/dir/", "dir"), ("/", "/"), ("//", "/"), ("/..", "..")] {
+ assert_eq!(base(path), name, "{path}");
+ }
+ }
+
+ #[test]
+ fn a_path_only_the_kernel_finds_is_archived_as_given() {
+ let dir = std::env::temp_dir().join(format!("kiri-archived-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(dir.join("usr/bin")).unwrap();
+ fs::create_dir_all(dir.join("usr/share")).unwrap();
+ fs::create_dir_all(dir.join("share")).unwrap();
+ fs::write(dir.join("usr/share/start.sh"), "").unwrap();
+ fs::write(dir.join("usr/share/both"), "").unwrap();
+ fs::write(dir.join("share/both"), "").unwrap();
+ std::os::unix::fs::symlink("usr/bin", dir.join("bin")).unwrap();
+ let at = |rest: &str| format!("{}/{rest}", dir.display());
+ // By name this is share/start.sh, which is not there: the kernel's stays.
+ assert_eq!(archived(&at("bin/../share/start.sh")), at("bin/../share/start.sh"));
+ // Where the path by name is there, it is the one, as in Docker.
+ assert_eq!(archived(&at("bin/../share/both")), at("share/both"));
+ assert_eq!(archived(&at("usr/bin/..")), at("usr"));
+ // Nothing either way: the path as given, for the error to name.
+ assert_eq!(archived(&at("bin/../none")), at("bin/../none"));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn root_and_contents_entries_keep_their_prefix() {
+ let root = std::path::Path::new("/");
+ let meta = fs::symlink_metadata(root).unwrap();
+ let names = ["/", "/etc", ".", "./etc", "etc"];
+ let mut bytes = Vec::new();
+ {
+ let mut archive = tar::Builder::new(&mut bytes);
+ for name in names {
+ append_one(&mut archive, root, std::path::Path::new(name), &meta).unwrap();
+ }
+ archive.finish().unwrap();
+ }
+ let mut archive = tar::Archive::new(bytes.as_slice());
+ let got: Vec<_> = archive.entries().unwrap().map(|entry| String::from_utf8(entry.unwrap().path_bytes().into_owned()).unwrap()).collect();
+ assert_eq!(got, names);
+ }
+
#[test]
fn chunks_end_at_the_empty_chunk_and_leave_the_rest() {
let wire = [&3u32.to_le_bytes()[..], b"abc", &2u32.to_le_bytes(), b"de", &0u32.to_le_bytes(), b"after"].concat();
@@ -640,4 +1447,310 @@ mod tests {
let err = Chunks::new(&wire[..]).read_to_end(&mut Vec::new()).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
}
+
+ #[test]
+ fn unpack_in_keeps_owners_and_does_not_chown_symlink_targets() {
+ // SAFETY: a plain getter.
+ if unsafe { libc::geteuid() } != 0 {
+ eprintln!("skipped: needs root to keep owners");
+ return;
+ }
+ let dest = std::env::temp_dir().join(format!("kiri-copy-owners-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dest);
+ fs::create_dir_all(&dest).unwrap();
+ fs::write(dest.join("target"), b"stay").unwrap();
+ std::os::unix::fs::symlink("target", dest.join("replaced")).unwrap();
+
+ let mut b = tar::Builder::new(Vec::new());
+ let h = |kind: tar::EntryType, size: u64, mode: u32| {
+ let mut h = tar::Header::new_gnu();
+ h.set_entry_type(kind);
+ h.set_size(size);
+ h.set_mode(mode);
+ h.set_uid(1234);
+ h.set_gid(1235);
+ h.set_mtime(1_700_000_000);
+ h.set_cksum();
+ h
+ };
+ b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750), "dir", &[][..]).unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 3, 0o600), "dir/owned.pem", &b"key"[..]).unwrap();
+ b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777), "link", "target").unwrap();
+ b.append_data(&mut h(tar::EntryType::Regular, 3, 0o640), "replaced", &b"new"[..]).unwrap();
+ let bytes = b.into_inner().unwrap();
+
+ unpack_in(&bytes[..], &dest, &dest, 0, None, &[], false).unwrap();
+
+ let meta = |p: &str| fs::symlink_metadata(dest.join(p)).unwrap();
+ let dir = meta("dir");
+ assert_eq!((dir.uid(), dir.gid(), dir.mode() & 0o777), (1234, 1235, 0o750));
+ let pem = meta("dir/owned.pem");
+ assert_eq!((pem.uid(), pem.gid(), pem.mode() & 0o777), (1234, 1235, 0o600));
+ assert_eq!(fs::read(dest.join("dir/owned.pem")).unwrap(), b"key");
+ let link = meta("link");
+ assert!(link.file_type().is_symlink());
+ assert_eq!((link.uid(), link.gid()), (1234, 1235));
+ let replaced = meta("replaced");
+ assert!(replaced.file_type().is_file());
+ assert_eq!((replaced.uid(), replaced.gid(), replaced.mode() & 0o777), (1234, 1235, 0o640));
+ assert_eq!(fs::read(dest.join("replaced")).unwrap(), b"new");
+ let target = meta("target");
+ assert_eq!((target.uid(), target.gid()), (0, 0));
+ assert_eq!(fs::read(dest.join("target")).unwrap(), b"stay");
+
+ unpack_in(&bytes[..], &dest, &dest, 0, Some((2375, 2376)), &[], false).unwrap();
+ assert_eq!((meta("dir").uid(), meta("dir").gid()), (2375, 2376));
+ assert_eq!((meta("dir/owned.pem").uid(), meta("dir/owned.pem").gid(), meta("dir/owned.pem").mode() & 0o777), (2375, 2376, 0o600));
+ assert_eq!((meta("link").uid(), meta("link").gid()), (2375, 2376));
+ assert_eq!((meta("target").uid(), meta("target").gid()), (0, 0));
+
+ let _ = fs::remove_dir_all(&dest);
+ }
+
+ #[test]
+ fn resolve_copy_user_matches_moby_get_uid_gid() {
+ let root = std::env::temp_dir().join(format!("kiri-copy-user-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&root);
+ fs::create_dir_all(root.join("etc")).unwrap();
+ fs::write(root.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\ntestuser:x:2375:2376::/home/testuser:/bin/sh\n").unwrap();
+ fs::write(root.join("etc/group"), "root:x:0:\ntestgroup:x:2376:\n").unwrap();
+
+ for (spec, want) in [
+ ("7777:", (7777, 0)),
+ (":7777", (0, 7777)),
+ ("2375", (2375, 2376)),
+ ("7777", (7777, 0)),
+ ("2375:2376", (2375, 2376)),
+ ("testuser:testgroup", (2375, 2376)),
+ ("testuser", (2375, 2376)),
+ ("testuser:7777", (2375, 7777)),
+ ("7777:testgroup", (7777, 2376)),
+ ] {
+ assert_eq!(resolve_copy_user_in(&root, spec).unwrap(), want, "{spec}");
+ }
+ assert!(resolve_copy_user_in(&root, "nosuchuser").is_err());
+ assert!(resolve_copy_user_in(&root, "testuser:nosuchgroup").is_err());
+
+ let _ = fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn only_an_untouched_root_marker_is_skipped_by_diff_and_commit() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let p = std::path::Path::new;
+ assert!(is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0));
+ assert!(!is_marker_attr(p("sub/.dockerenv"), true, 0, 0o100755, 0, 0));
+ assert!(!is_marker_attr(p("added"), true, 0, 0o100755, 0, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), false, 0, 0o120755, 0, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 2, 0o100755, 0, 0));
+ // `chmod 600 /.dockerenv`, `rm && touch` (0644), or special mode bits.
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100600, 0, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100644, 0, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o101755, 0, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o104755, 0, 0));
+ // `chown 1000:1000 /.dockerenv` (or uid-only / gid-only changes).
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 0));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 1000));
+ assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 1000));
+
+ let base = std::env::temp_dir().join(format!("kiri-copy-marker-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&base);
+ fs::create_dir_all(base.join("sub")).unwrap();
+ let meta = |rel: &str| fs::symlink_metadata(base.join(rel)).unwrap();
+
+ fs::write(base.join(".dockerenv"), b"").unwrap();
+ fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap();
+ let m = meta(".dockerenv");
+ assert_eq!(is_marker(p(".dockerenv"), &m), m.uid() == 0 && m.gid() == 0);
+ assert!(!is_marker(p("sub/.dockerenv"), &m));
+ assert!(!is_marker(p("added"), &m));
+
+ fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o600)).unwrap();
+ assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv")));
+
+ fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap();
+ fs::write(base.join(".dockerenv"), b"hi").unwrap();
+ assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv")));
+
+ fs::remove_file(base.join(".dockerenv")).unwrap();
+ std::os::unix::fs::symlink("/outside", base.join(".dockerenv")).unwrap();
+ assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv")));
+
+ fs::remove_file(base.join(".dockerenv")).unwrap();
+ fs::create_dir(base.join(".dockerenv")).unwrap();
+ assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv")));
+
+ // Truncating an image-provided `/.dockerenv` to 0 bytes leaves an empty
+ // `0755 0:0` file in `upper`, which must not be skipped when a lower
+ // layer already has `/.dockerenv`.
+ let lower_clean = base.join("lower-clean");
+ let lower_image = base.join("lower-image");
+ fs::create_dir_all(&lower_clean).unwrap();
+ fs::create_dir_all(&lower_image).unwrap();
+ fs::write(lower_image.join(".dockerenv"), b"from-image\n").unwrap();
+ let open_dir = |dir: &std::path::Path| {
+ let c = sys::cstr(dir).unwrap();
+ // SAFETY: plain open of a temp directory we just created.
+ let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) };
+ assert!(fd >= 0);
+ // SAFETY: fresh descriptor.
+ unsafe { OwnedFd::from_raw_fd(fd) }
+ };
+ let clean_lowers = [open_dir(&lower_clean)];
+ let image_lowers = [open_dir(&lower_image)];
+ assert!(!in_lower_layers(&clean_lowers, p(".dockerenv")));
+ assert!(in_lower_layers(&image_lowers, p(".dockerenv")));
+ let skip = |lowers: &[OwnedFd]| is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0) && !in_lower_layers(lowers, p(".dockerenv"));
+ assert!(skip(&clean_lowers));
+ assert!(!skip(&image_lowers));
+
+ let _ = fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn parse_mount_access_sorts_parents_first_and_tracks_ro_and_tmpfs() {
+ let mut buf = Vec::new();
+ kiri_proto::encode_copy(
+ &mut buf,
+ copy_op::IN,
+ "c1",
+ "/",
+ 0,
+ &["sha256:a"],
+ &[
+ "/v/sub\t/app/sub/\tro",
+ "/v/app\t/app\tcreate,copyup",
+ "tmpfs\t/tmp\ttmpfs,noexec,ro",
+ "tmpfs\t/run\ttmpfs,ro,rw",
+ ],
+ );
+ let Msg::Copy(spec) = kiri_proto::decode(&buf).unwrap() else { panic!() };
+ let got = parse_mount_access(spec.mounts).unwrap();
+ assert_eq!(
+ got,
+ [
+ MountAccess { target: PathBuf::from("/app"), ro: false, tmpfs: false },
+ MountAccess { target: PathBuf::from("/tmp"), ro: true, tmpfs: true },
+ MountAccess { target: PathBuf::from("/run"), ro: false, tmpfs: true },
+ MountAccess { target: PathBuf::from("/app/sub"), ro: true, tmpfs: false },
+ ]
+ );
+ let mut bad = Vec::new();
+ kiri_proto::encode_copy(&mut bad, copy_op::IN, "c1", "/", 0, &[], &["/src\t../escape\tro"]);
+ let Msg::Copy(bad_spec) = kiri_proto::decode(&bad).unwrap() else { panic!() };
+ assert!(parse_mount_access(bad_spec.mounts).is_err());
+ }
+
+ #[test]
+ fn check_writable_enforces_innermost_mount_and_readonly_rootfs() {
+ let m = |target: &str, ro: bool| MountAccess { target: PathBuf::from(target), ro, tmpfs: false };
+ let mounts = [m("/app", false), m("/app/ro", true), m("/app/ro/rw", false), m("/ro", true)];
+ let err = |p: &str, ro_root: bool| check_writable(Path::new(p), &mounts, ro_root).unwrap_err().to_string();
+
+ assert_eq!(err("/ro", false), "forbidden: mounted volume is marked read-only");
+ assert_eq!(err("/ro/sub/f", false), "forbidden: mounted volume is marked read-only");
+ assert_eq!(err("/app/ro", false), "forbidden: mounted volume is marked read-only");
+ assert_eq!(err("/app/ro/file", false), "forbidden: mounted volume is marked read-only");
+ // Component boundary: `/app/ro2` is under `/app` (rw), not `/app/ro`.
+ assert!(check_writable(Path::new("/app/ro2/file"), &mounts, true).is_ok());
+ // Writable nested mount inside a read-only mount succeeds.
+ assert!(check_writable(Path::new("/app/ro/rw"), &mounts, true).is_ok());
+ assert!(check_writable(Path::new("/app/ro/rw/x"), &mounts, true).is_ok());
+ // Path outside every mount: refused iff `--read-only`.
+ assert!(check_writable(Path::new("/etc"), &mounts, false).is_ok());
+ assert_eq!(err("/etc", true), "forbidden: container rootfs is marked read-only");
+ // Writable mount on a `--read-only` rootfs succeeds.
+ assert!(check_writable(Path::new("/app/file"), &mounts, true).is_ok());
+ // `:ro` mount on a `--read-only` rootfs reports the mounted volume error.
+ assert_eq!(err("/ro/x", true), "forbidden: mounted volume is marked read-only");
+ }
+
+ #[test]
+ fn unpack_in_refuses_ro_mounts_and_overwrites_file_mounts_in_place() {
+ let base = std::env::temp_dir().join(format!("kiri-copy-ro-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&base);
+ let root = base.join("root");
+ fs::create_dir_all(root.join("ro")).unwrap();
+ fs::create_dir_all(root.join("rw")).unwrap();
+ fs::create_dir_all(root.join("etc")).unwrap();
+ fs::write(root.join("etc/app.conf"), b"old").unwrap();
+ fs::write(root.join("etc/ro.conf"), b"stay").unwrap();
+ std::os::unix::fs::symlink(root.join("etc"), root.join("rw/to_etc")).unwrap();
+ let canonical_root = fs::canonicalize(&root).unwrap();
+ let mounts = [
+ MountAccess { target: canonical_root.join("ro"), ro: true, tmpfs: false },
+ MountAccess { target: canonical_root.join("rw"), ro: false, tmpfs: false },
+ MountAccess { target: canonical_root.join("etc/app.conf"), ro: false, tmpfs: false },
+ MountAccess { target: canonical_root.join("etc/ro.conf"), ro: true, tmpfs: false },
+ ];
+ let tar_file = |name: &str, data: &[u8]| {
+ let mut b = tar::Builder::new(Vec::new());
+ let mut h = tar::Header::new_gnu();
+ h.set_entry_type(tar::EntryType::Regular);
+ h.set_size(data.len() as u64);
+ h.set_mode(0o640);
+ h.set_mtime(0);
+ h.set_cksum();
+ b.append_data(&mut h, name, data).unwrap();
+ b.into_inner().unwrap()
+ };
+
+ // Entry targeting a `:ro` file bind mount is refused before writing.
+ let bytes = tar_file("ro.conf", b"pwn");
+ let err = unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap_err();
+ assert_eq!(err.to_string(), "forbidden: mounted volume is marked read-only");
+ assert_eq!(fs::read(canonical_root.join("etc/ro.conf")).unwrap(), b"stay");
+
+ // Entry escaping a `:rw` volume through a symlink to a `--read-only` rootfs is refused.
+ let bytes = tar_file("to_etc/pwn", b"bad");
+ let err = unpack_in(&bytes[..], &canonical_root.join("rw"), &canonical_root.join("rw"), 0, None, &mounts, true).unwrap_err();
+ assert_eq!(err.to_string(), "forbidden: container rootfs is marked read-only");
+ assert!(!canonical_root.join("etc/pwn").exists());
+
+ // Entry targeting a `:rw` file bind mount overwrites in place (keeping inode and zero mtime).
+ let before_ino = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap().ino();
+ let bytes = tar_file("app.conf", b"updated");
+ unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap();
+ let after = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap();
+ assert_eq!(after.ino(), before_ino, "file bind mount must be overwritten in place, not unlinked");
+ assert_eq!(fs::read(canonical_root.join("etc/app.conf")).unwrap(), b"updated");
+ assert_eq!(after.mtime(), 0);
+ assert_eq!(after.mode() & 0o777, 0o640);
+
+ let _ = fs::remove_dir_all(&base);
+ }
+
+ #[test]
+ fn paced_writer_waits_for_credit_and_bounds_chunks_to_64kib() {
+ use std::os::unix::net::UnixStream;
+ let (mut host, guest) = UnixStream::pair().unwrap();
+ let data = vec![0x5a_u8; PACED_CHUNK + 1234];
+ let expected = data.clone();
+ let t = std::thread::spawn(move || {
+ let mut w = PacedWriter::new(guest);
+ w.write_all(&data).unwrap();
+ w.finish().unwrap();
+ });
+
+ let mut received = Vec::new();
+ let mut sizes = Vec::new();
+ loop {
+ host.write_all(&[1]).unwrap();
+ let mut hdr = [0u8; 4];
+ host.read_exact(&mut hdr).unwrap();
+ let len = u32::from_le_bytes(hdr) as usize;
+ if len == 0 {
+ break;
+ }
+ assert!(len <= PACED_CHUNK, "chunk {len} exceeded {PACED_CHUNK}");
+ sizes.push(len);
+ let mut chunk = vec![0u8; len];
+ host.read_exact(&mut chunk).unwrap();
+ received.extend_from_slice(&chunk);
+ }
+ t.join().unwrap();
+ assert_eq!(sizes, vec![PACED_CHUNK, 1234]);
+ assert_eq!(received, expected);
+ }
}
diff --git a/crates/kiri-init/src/linux/disk.rs b/crates/kiri-init/src/linux/disk.rs
new file mode 100644
index 000000000..cca7d15d1
--- /dev/null
+++ b/crates/kiri-init/src/linux/disk.rs
@@ -0,0 +1,126 @@
+//! Expand the mounted ext4 filesystem to the backing device's capacity.
+
+use std::fs::File;
+use std::io::{self, Read, Seek, SeekFrom};
+use std::os::fd::AsRawFd;
+use std::path::Path;
+
+const EXT4_SUPER_OFFSET: u64 = 1024;
+const EXT4_SUPER_LEN: usize = 1024;
+const EXT4_SUPER_MAGIC: u16 = 0xEF53;
+const EXT4_FEATURE_INCOMPAT_64BIT: u32 = 0x80;
+
+// EXT4_IOC_RESIZE_FS = _IOW('f', 16, __u64), on both guest architectures.
+const EXT4_IOC_RESIZE_FS: libc::Ioctl = 0x4008_6610_u32 as libc::Ioctl;
+
+/// Parses the ext4 superblock's total block count (including metadata).
+/// Returns `InvalidData` if the superblock magic does not match ext4.
+fn superblock_blocks(sb: &[u8; EXT4_SUPER_LEN]) -> io::Result {
+ let magic = u16::from_le_bytes([sb[0x38], sb[0x39]]);
+ if magic != EXT4_SUPER_MAGIC {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ format!("unexpected ext4 superblock magic 0x{magic:04x}"),
+ ));
+ }
+ let word = |offset: usize| u32::from_le_bytes(sb[offset..offset + 4].try_into().unwrap());
+ let mut blocks = u64::from(word(0x04));
+ if word(0x60) & EXT4_FEATURE_INCOMPAT_64BIT != 0 {
+ blocks |= u64::from(word(0x150)) << 32;
+ }
+ Ok(blocks)
+}
+
+pub fn grow() -> io::Result<()> {
+ grow_device(Path::new("/dev/vda"), Path::new(super::DATA))
+}
+
+pub(crate) fn grow_device(device: &Path, mountpoint: &Path) -> io::Result<()> {
+ let mut disk = File::open(device)?;
+ let bytes = disk.seek(SeekFrom::End(0))?;
+ // The data disk has already mounted as ext4. Read its total block
+ // count, including metadata (statfs excludes metadata from f_blocks).
+ disk.seek(SeekFrom::Start(EXT4_SUPER_OFFSET))?;
+ let mut sb = [0u8; EXT4_SUPER_LEN];
+ disk.read_exact(&mut sb)?;
+ let current = superblock_blocks(&sb)?;
+ let fs = File::open(mountpoint)?;
+ // SAFETY: statfs is plain data; fstatfs writes it before it is read.
+ let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
+ // SAFETY: fs is open and stat is valid writable storage.
+ super::sys::check(
+ unsafe { libc::fstatfs(fs.as_raw_fd(), &mut stat) } as _,
+ "data disk statfs",
+ )?;
+ let block_size = stat.f_bsize as u64;
+ if block_size == 0 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "invalid ext4 block size",
+ ));
+ }
+ let blocks = bytes / block_size;
+ if blocks <= current {
+ return Ok(());
+ }
+ // SAFETY: fs is the mounted ext4 directory and blocks is a valid u64.
+ super::sys::check(
+ unsafe { libc::ioctl(fs.as_raw_fd(), EXT4_IOC_RESIZE_FS, &blocks) } as _,
+ "grow ext4 data disk",
+ )?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fake_superblock(lo: u32, hi: u32, is_64bit: bool) -> [u8; EXT4_SUPER_LEN] {
+ let mut sb = [0u8; EXT4_SUPER_LEN];
+ sb[0x38..0x3a].copy_from_slice(&EXT4_SUPER_MAGIC.to_le_bytes());
+ sb[0x04..0x08].copy_from_slice(&lo.to_le_bytes());
+ let incompat: u32 = if is_64bit {
+ EXT4_FEATURE_INCOMPAT_64BIT
+ } else {
+ 0
+ };
+ sb[0x60..0x64].copy_from_slice(&incompat.to_le_bytes());
+ sb[0x150..0x154].copy_from_slice(&hi.to_le_bytes());
+ sb
+ }
+
+ #[test]
+ fn superblock_reads_32bit_and_64bit_block_counts() {
+ let sb32 = fake_superblock(16_777_216, 99, false);
+ assert_eq!(superblock_blocks(&sb32).unwrap(), 16_777_216);
+
+ let sb64 = fake_superblock(0x0000_0001, 0x0000_0002, true);
+ assert_eq!(superblock_blocks(&sb64).unwrap(), (2u64 << 32) | 1);
+ }
+
+ #[test]
+ fn superblock_rejects_bad_magic() {
+ let sb = [0u8; EXT4_SUPER_LEN];
+ assert_eq!(
+ superblock_blocks(&sb).unwrap_err().kind(),
+ io::ErrorKind::InvalidData
+ );
+ }
+
+ /// Real online ext4 resize check when driven on a Linux host with a
+ /// mounted loop device (`KIRI_TEST_EXT4_DEV` + `KIRI_TEST_EXT4_MOUNT`).
+ #[test]
+ fn grows_mounted_ext4_online_when_configured() {
+ let (Ok(dev), Ok(mnt)) = (
+ std::env::var("KIRI_TEST_EXT4_DEV"),
+ std::env::var("KIRI_TEST_EXT4_MOUNT"),
+ ) else {
+ return;
+ };
+ let dev = Path::new(&dev);
+ let mnt = Path::new(&mnt);
+ grow_device(dev, mnt).expect("first online ext4 resize must succeed");
+ // Calling grow again when already at full capacity must be a no-op.
+ grow_device(dev, mnt).expect("second online ext4 resize must be idempotent");
+ }
+}
diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs
index 3ca8b5b0b..1049138d6 100644
--- a/crates/kiri-init/src/linux/dns.rs
+++ b/crates/kiri-init/src/linux/dns.rs
@@ -74,12 +74,25 @@ const OWN_DEADLINE: Duration = Duration::from_secs(4 * MAX_OWN_SERVERS as u64);
/// than `MAX_PER_CLIENT`. One more is answered SERVFAIL at once.
const MAX_OWN_PER_CLIENT: usize = 16;
const _: () = assert!(MAX_OWN_PER_CLIENT < MAX_PER_CLIENT);
-/// Largest reply the host relay may send (a DNS over TCP frame's limit).
+/// Largest reply the host relay or a TCP upstream may send (a DNS over TCP frame's limit).
const MAX_RELAYED: usize = 2 + 65_535;
+/// Concurrent TCP DNS client connections accepted across all listeners.
+const MAX_TCP_CLIENTS: usize = 64;
+/// Maximum queued reply bytes for one TCP DNS client before it is dropped.
+const MAX_TCP_SEND: usize = 65_536;
/// Docker's embedded DNS address, inside each container.
pub const EMBEDDED: [u8; 4] = [127, 0, 0, 11];
+/// Who owns a forwarded DNS query (`Pending`) or `--dns` upstream list.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+enum ClientKey {
+ /// A container queried a bridge's gateway from this source IP.
+ Ip([u8; 4]),
+ /// A container queried 127.0.0.11 in its own network namespace (PID 1).
+ Container(i32),
+}
+
struct Server {
/// Its own number, never reused: what a forwarded query names it by.
id: u64,
@@ -87,9 +100,20 @@ struct Server {
/// network of the container it is in.
bridges: Vec,
sock: OwnedFd,
- /// In a container's namespace: (its PID, the address its `--dns`
- /// servers are kept under). Every query there comes from 127.0.0.1.
- container: Option<(i32, [u8; 4])>,
+ /// PID of the container whose namespace this 127.0.0.11 server is in;
+ /// every query there comes from 127.0.0.1.
+ container: Option,
+}
+
+struct TcpClient {
+ id: u64,
+ server: u64,
+ key: ClientKey,
+ sock: OwnedFd,
+ recv: Vec,
+ send: Vec,
+ eof: bool,
+ started: Instant,
}
struct Pending {
@@ -101,11 +125,13 @@ struct Pending {
sock: OwnedFd,
/// The ID it went out with.
our: u16,
- /// Who asked, for `MAX_PER_CLIENT`: the container's address.
- key: [u8; 4],
+ /// Who asked, for `MAX_PER_CLIENT`.
+ key: ClientKey,
/// The server the query came in on (`Server::id`).
server: u64,
client: libc::sockaddr_in,
+ /// `Some(TcpClient::id)` when the client asked over TCP; `None` for UDP.
+ tcp_client: Option,
id: u16,
question: Vec,
/// When it was asked of the server it is with now.
@@ -115,13 +141,20 @@ struct Pending {
/// The query as sent (with `our` ID), to send again.
query: Vec,
/// With the container's own `--dns` servers (kept under `key`): the
- /// position of the one it is with. None for the VM's resolver.
+ /// position of the one it is with. None for the VM's / host's resolver.
own: Option,
+ /// Host/VM upstream servers and the index currently asked when `own` is None.
+ upstreams: Vec<[u8; 4]>,
+ upstream_at: usize,
/// It may still go through the host: in the VM, asked of the VM's own
/// resolver (not `--dns` servers), and not tried there yet.
may_relay: bool,
/// Sent through the host: the reply's bytes so far, `u16 len | reply`.
relayed: Option>,
+ /// Sent over TCP to an upstream server: remaining request bytes to write,
+ /// while `tcp_recv` collects the `u16 len | reply` answer.
+ tcp_send: Option>,
+ tcp_recv: Vec,
}
/// One name's IPv6 addresses, each with its container's IPv4 address.
@@ -130,20 +163,36 @@ type Owned6 = Vec<([u8; 4], [u8; 16])>;
#[derive(Default)]
pub struct Dns {
servers: Vec,
+ /// `(Server::id, listener)` for DNS over TCP on gateways and `127.0.0.11`.
+ tcp_servers: Vec<(u64, OwnedFd)>,
+ tcp_clients: Vec,
/// bridge → name (lowercase) → addresses.
names: HashMap>>,
/// bridge → name → (the container's IPv4 address there, its IPv6 one):
/// the IPv4 address is what `unregister` names the container by.
names6: HashMap>,
+ /// Bridges with IPv6 enabled: external `AAAA` queries on a server whose
+ /// bridges are all IPv4-only are answered `NODATA` locally (matching
+ /// Docker's libnetwork) instead of returning unreachable global IPv6
+ /// addresses (#932).
+ ipv6_bridges: std::collections::HashSet,
/// bridge → its Docker network's name: the order a container's server
/// searches its networks in.
networks: HashMap,
- /// Container address → its `--dns` servers, used instead of the VM's.
+ /// Container address → its `--dns` servers, used on a gateway listener.
clients: HashMap<[u8; 4], Vec<[u8; 4]>>,
+ /// Container PID → its `--dns` servers, used on 127.0.0.11 so custom
+ /// resolvers survive disconnecting and reconnecting even the first network.
+ container_upstreams: HashMap