Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/kiri-init/src/linux/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap<libc::pid_t, Pr
},
Err(e) => Msg::Error(&e).encode(&mut out),
},
Ok(Msg::StartExec { id }) => match procs.values_mut().find(|p| p.run.id == id && p.run.container.is_none() && p.exited.is_none()) {
Some(p) => match p.run.start_exec() {
Ok(()) => Msg::Ack.encode(&mut out),
Err(e) => Msg::Error(&format!("start exec {id}: {e}")).encode(&mut out),
},
None => Msg::Error(&format!("container {id} is not running")).encode(&mut out),
},
Ok(Msg::StatsQuery { id }) => match netns_pid(procs, id) {
Some(pid) => match super::cgroup::stats(&paths.cgroup.join(id), pid) {
Ok(s) => Msg::ContainerStats(s).encode(&mut out),
Expand Down
41 changes: 41 additions & 0 deletions crates/kiri-init/src/linux/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ pub struct Process {
/// Its start was cancelled while it was filling a volume (see `cancel`):
/// killed as soon as its root is in place.
cancelled: bool,
/// Write end of `Prepared::exec_ready` when started with
/// `run_flags::HOLD_EXEC` so secondary networks can be attached before PID 1 execs.
exec_go: Option<OwnedFd>,
}

/// Where a container's root stands (see [`Process::root`]).
Expand Down Expand Up @@ -233,6 +236,17 @@ impl Process {
pub fn start_failure(&self) -> Option<&str> {
self.ended_before_ready.as_deref()
}

/// Releases a child started with `run_flags::HOLD_EXEC` so it proceeds to exec.
pub fn start_exec(&mut self) -> io::Result<()> {
if let Some(go) = self.exec_go.take() {
// SAFETY: writing one byte to a pipe we own.
if unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 {
return Err(io::Error::last_os_error());
}
}
Ok(())
}
}

/// A child that ended before its root was in place and said nothing.
Expand Down Expand Up @@ -270,6 +284,7 @@ impl Process {
ended_before_ready: None,
filling: false,
cancelled: false,
exec_go: None,
}
}

Expand Down Expand Up @@ -339,6 +354,9 @@ struct Prepared {
/// The child's end of the pipe that says it has been moved into its
/// cgroup. Only a start that fell back to clone(2) waits on it.
cgroup_ready: Option<OwnedFd>,
/// When `run_flags::HOLD_EXEC` is set, the child waits here (after TTY and
/// root setup, before seccomp and exec) until `Msg::StartExec` releases it.
exec_ready: Option<OwnedFd>,
}

/// The parts of [`super::hostopts::HostOpts`] the child applies itself.
Expand Down Expand Up @@ -665,6 +683,13 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// instead of the container's, where its image users don't exist (#311).
let (root_ready, child_root_ready) = sys::pipe().map_err(cleanup)?;
prepared.root_ready = Some(child_root_ready);
let exec_go = if spec.flags & run_flags::HOLD_EXEC != 0 {
let (r, w) = sys::pipe().map_err(cleanup)?;
prepared.exec_ready = Some(r);
Some(w)
} else {
None
};
// The child waits here until the agent has moved it into its cgroup, for
// a start that clone3 could not place there itself. Once `clone3` with
// `CLONE_INTO_CGROUP` is confirmed working in this process, skip making
Expand Down Expand Up @@ -731,6 +756,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
// it (the child exiting early) read as EOF here.
drop(prepared.root_ready.take());
drop(prepared.cgroup_ready.take());
drop(prepared.exec_ready.take());
let child_netns = if flags & libc::CLONE_NEWNET as u64 != 0 {
let f = fs::File::open(format!("/proc/{pid}/ns/net")).ok();
netns = f.as_ref().map_or(0, netns_inode);
Expand Down Expand Up @@ -958,6 +984,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result<P
ended_before_ready: None,
filling: filling.get(),
cancelled: false,
exec_go,
})
}

Expand Down Expand Up @@ -1247,6 +1274,7 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile
ended_before_ready: None,
filling: false,
cancelled: false,
exec_go: None,
})
}

Expand Down Expand Up @@ -1532,6 +1560,7 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname:
host: HostApplied::default(),
root_ready: None,
cgroup_ready: None,
exec_ready: None,
})
}

Expand Down Expand Up @@ -2550,6 +2579,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec<RawFd> {
host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ },
root_ready,
cgroup_ready,
exec_ready,
} = p;
let mut fds = match io {
ChildStdio::Tty { sock } => vec![sock.as_raw_fd()],
Expand All @@ -2563,6 +2593,7 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec<RawFd> {
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.extend(exec_ready.as_ref().map(AsRawFd::as_raw_fd));
fds
}

Expand Down Expand Up @@ -2781,6 +2812,16 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! {
// which is where the user will see why a start failed.
let fail = |what: &str, e: io::Error| -> ! { child_fail(2, what, e) };

if console
&& let Some(ready) = &p.exec_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("network", io::Error::other("the agent could not set up this container's networks"));
}
}

// While still root with every capability: raising a hard limit needs
// CAP_SYS_RESOURCE.
apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e));
Expand Down
11 changes: 11 additions & 0 deletions crates/kiri-proto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,10 @@ pub enum Msg<'a> {
TrimDisk,
/// Guest → host: bytes discarded by `FITRIM`, plus updated `statvfs` usage.
DiskTrimmed { trimmed: u64, in_use: u64, capacity: u64 },
/// Host → guest: release a container started with [`run_flags::HOLD_EXEC`]
/// to exec its program once secondary networks are attached. Answered by
/// `Ack` or `Error`.
StartExec { id: &'a str },
/// Success, for requests with nothing else to say.
Ack,
}
Expand Down Expand Up @@ -509,6 +513,9 @@ pub mod run_flags {
/// `--pid host`: no PID namespace of its own; the container sees the
/// VM's processes (on a Linux host, the host's).
pub const PID_HOST: u32 = 1 << 17;
/// Hold the container's process right before exec until [`super::Msg::StartExec`]
/// releases it, so `spec.extra_networks` are attached before PID 1 runs.
pub const HOLD_EXEC: u32 = 1 << 18;
}

/// A container's network, as `Run` carries it.
Expand Down Expand Up @@ -901,6 +908,7 @@ mod kind {
pub const DISK_USAGE: u16 = 86;
pub const TRIM_DISK: u16 = 87;
pub const DISK_TRIMMED: u16 = 88;
pub const START_EXEC: u16 = 89;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -1312,6 +1320,7 @@ impl Msg<'_> {
put_u64(o, in_use);
put_u64(o, capacity);
}),
Msg::StartExec { id } => frame(out, kind::START_EXEC, |o| put_str(o, id)),
Msg::Listening(lines) => frame(out, kind::LISTENING, |o| {
put_u32(o, lines.count);
o.extend_from_slice(lines.raw);
Expand Down Expand Up @@ -1633,6 +1642,7 @@ pub fn decode(frame: &[u8]) -> Result<Msg<'_>, DecodeError> {
kind::DISK_USAGE => Msg::DiskUsage { in_use: r.u64()?, capacity: r.u64()? },
kind::TRIM_DISK => Msg::TrimDisk,
kind::DISK_TRIMMED => Msg::DiskTrimmed { trimmed: r.u64()?, in_use: r.u64()?, capacity: r.u64()? },
kind::START_EXEC => Msg::StartExec { id: r.str()? },
kind::NET_ATTACH => Msg::NetAttach {
id: r.str()?,
ifname: r.str()?,
Expand Down Expand Up @@ -1739,6 +1749,7 @@ mod tests {
assert_eq!(decode(&buf[..buf.len() - 32]).unwrap(), Msg::Stats(no_memory_words));
assert_eq!(decode(&buf[..buf.len() - 40]).unwrap(), Msg::Stats(Stats { mem_used_kib: 0, ..no_memory_words }));
round(Msg::LayerQuery("sha256:ab"));
round(Msg::StartExec { id: "ctr-123" });
round(Msg::LayerStatus(true));
round(Msg::LayerBegin(LayerBegin { digest: "sha256:ab", media_type: "x+gzip", size: 9 }));
round(Msg::LayerStored(LayerStored { unpacked_bytes: 1, elapsed_ns: 2 }));
Expand Down
94 changes: 89 additions & 5 deletions crates/kiri/src/daemon/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ fn route(req: &Request, engine: &Arc<Engine>, caller: &Caller, w: &mut UnixStrea
("POST", "/networks/create") => return reply(w, network_create(req, engine), 201),
("POST", "/networks/prune") => return reply(w, network_prune(req, engine), 200),
("GET", "/volumes") => return reply(w, volumes(req, engine), 200),
("POST", "/volumes/create") => return reply(w, volume_create(req, engine), 201),
("POST", "/volumes/create") => return reply(w, volume_create(req, engine, caller), 201),
("POST", "/volumes/prune") => return reply(w, volume_prune(req, engine), 200),
_ => {}
}
Expand Down Expand Up @@ -1962,6 +1962,31 @@ fn check_volume_device(options: &std::collections::BTreeMap<String, String>) ->
Ok(())
}

/// Resolves a local bind volume's `device` path for WSL integration or Windows
/// drive-letter paths before passing it to the guest, while keeping the raw
/// `device` option in `volumes.json` for `docker volume inspect`.
fn volume_bind_source(device: &str, wsl: Option<&super::binds::Wsl>, wsl_distro: Option<&str>) -> Result<String, Error> {
match (wsl, wsl_distro) {
(_, Some(d)) => super::binds::distro_source(device, d, wsl),
(Some(w), None) => super::binds::source(device, w),
_ => Ok(device.to_owned()),
}
}

fn validate_volume_options(
options: &std::collections::BTreeMap<String, String>,
wsl: Option<&super::binds::Wsl>,
wsl_distro: Option<&str>,
) -> Result<(), Error> {
check_volume_device(options)?;
let (flags, _) = super::volumes::mount_options(options.get("o").map_or("", String::as_str));
if flags & 4096 != 0 {
let device = options.get("device").map_or("", String::as_str);
volume_bind_source(device, wsl, wsl_distro)?;
}
Ok(())
}

/// Refuses text that would forge a field in the tab-separated mount line the
/// guest parses.
///
Expand Down Expand Up @@ -2183,11 +2208,23 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller:
// must not be reachable this way either: not as a virtiofs
// tag, and not as a bind of /mnt/mac.
check_volume_device(&v.options)?;
let vol_distro = v.wsl_distro.as_deref().or(wsl_distro);
let (opt_flags, _) = super::volumes::mount_options(v.options.get("o").map_or("", String::as_str));
let translated_bind_dev = if opt_flags & 4096 != 0 {
let raw_dev = v.options.get("device").map_or("", String::as_str);
Some(volume_bind_source(raw_dev, super::binds::wsl(), vol_distro)?)
} else {
None
};
let path = super::volumes::guest_path(&name);
let copy = if extra.contains("nocopy") { "create" } else { "create,copyup" };
// A volume with driver options (`type=nfs`, `o=bind` …) is
// mounted at its path by the guest at start, then bound in.
let vol = super::volumes::guest_mount_fields(&v.options, guest_bind_source, resolve_server);
let vol = super::volumes::guest_mount_fields(
&v.options,
|dev| guest_bind_source(translated_bind_dev.as_deref().unwrap_or(dev)),
resolve_server,
);
out.guest.push(format!("{path}\t{dst}\t{}{vol}", flag(copy)));
out.info.push(json!({"Type": "volume", "Name": name, "Source": path, "Destination": dst, "Driver": "local", "Mode": "z", "RW": !ro, "Propagation": ""}));
if anonymous {
Expand Down Expand Up @@ -2258,7 +2295,8 @@ fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller:
d => return Err(Error::BadRequest(format!("Kiri supports only local volumes, not {d}"))),
}
let options = super::volumes::local_options(&driver_opts["Options"]).map_err(Error::BadRequest)?;
engine.volume_ensure_with(src, m["VolumeOptions"]["Labels"].clone(), options)?;
validate_volume_options(&options, wsl, wsl_distro)?;
engine.volume_ensure_with_distro(src, m["VolumeOptions"]["Labels"].clone(), options, wsl_distro.map(str::to_owned))?;
}
add(kind, src, dst, ro, &extra, false, &mut out)?;
}
Expand Down Expand Up @@ -2398,7 +2436,7 @@ fn volume_json(v: &super::volumes::Volume) -> Value {
})
}

fn volume_create(req: &Request, engine: &Engine) -> Result<Value, Error> {
fn volume_create(req: &Request, engine: &Engine, caller: &super::caller::Caller) -> Result<Value, Error> {
let body: Value = serde_json::from_slice(&req.body).unwrap_or(Value::Null);
match body["Driver"].as_str().unwrap_or("local") {
"" | "local" => {}
Expand All @@ -2409,7 +2447,9 @@ fn volume_create(req: &Request, engine: &Engine) -> Result<Value, Error> {
n => n.to_owned(),
};
let options = super::volumes::local_options(&body["DriverOpts"]).map_err(Error::BadRequest)?;
let v = engine.volume_ensure_with(&name, body["Labels"].clone(), options)?;
let wsl_distro = caller.wsl_distro();
validate_volume_options(&options, super::binds::wsl(), wsl_distro)?;
let v = engine.volume_ensure_with_distro(&name, body["Labels"].clone(), options, wsl_distro.map(str::to_owned))?;
Ok(volume_json(&v))
}

Expand Down Expand Up @@ -5151,6 +5191,50 @@ mod tests {
assert_eq!(m.info[1]["Source"], "/run/host-services/ssh-auth.sock");
assert_eq!(m.info[1]["Destination"], "/agent.sock");
assert_eq!(m.info[1]["RW"], false);

// From an integrated WSL distro, `/run/host-services/ssh-auth.sock` stays
// the SSH relay socket and local `o=bind` volumes translate `device` into
// `/mnt/wsl/kiri/roots/<distro>/...` for the guest while keeping `Options.device`
// unchanged in `volume inspect`.
let wsl_caller = Caller::Wsl("Ubuntu".into());
let mw = mounts_for(&body, &engine, &image, &wsl_caller).unwrap();
assert_eq!(mw.guest, [format!("{src}\t/run/host-services/ssh-auth.sock\t"), format!("{src}\t/agent.sock\tro")]);
assert_eq!(mw.info[0]["Source"], "/run/host-services/ssh-auth.sock");
assert_eq!(mw.info[1]["Source"], "/run/host-services/ssh-auth.sock");

let vreq = Request::internal(
"POST",
"/volumes/create",
&[],
serde_json::to_vec(&json!({
"Name": "wsl-shared",
"Driver": "local",
"DriverOpts": {"type": "none", "o": "bind", "device": "/tmp/shared"},
}))
.unwrap(),
);
let vj = volume_create(&vreq, &engine, &wsl_caller).unwrap();
assert_eq!(vj["Options"]["device"], "/tmp/shared");
let vbody = json!({"HostConfig": {"Binds": ["wsl-shared:/shared"]}});
let mv = mounts_for(&vbody, &engine, &image, &Caller::Host).unwrap();
assert_eq!(
mv.guest,
["/var/lib/kiri/volumes/wsl-shared/_data\t/shared\tcreate,copyup\tnone\t/mnt/wsl/kiri/roots/Ubuntu/tmp/shared\t1000\t"]
);

let bad_vreq = Request::internal(
"POST",
"/volumes/create",
&[],
serde_json::to_vec(&json!({
"Name": "wsl-evil",
"Driver": "local",
"DriverOpts": {"type": "none", "o": "bind", "device": "/mnt/wsl/kiri/roots/Debian/etc"},
}))
.unwrap(),
);
assert!(volume_create(&bad_vreq, &engine, &wsl_caller).is_err());

drop(engine);
let _ = std::fs::remove_dir_all(root);
}
Expand Down
30 changes: 28 additions & 2 deletions crates/kiri/src/daemon/binds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result<Strin
}
let distro_root = format!("{roots_dir}/{distro}");
let cleaned = clean(src);
if ENGINE_SOCKS.contains(&cleaned.as_str()) || is_wsl_engine_socket(&cleaned) {
if ENGINE_SOCKS.contains(&cleaned.as_str()) || is_wsl_engine_socket(&cleaned) || cleaned == SSH_AGENT_SOCK {
return Ok(cleaned);
}
if cleaned == distro_root || cleaned.strip_prefix(&distro_root).is_some_and(|r| r.starts_with('/')) {
Expand All @@ -269,7 +269,12 @@ pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result<Strin
return Ok(target);
}
let lex = lexical_clean(src);
if ENGINE_SOCKS.contains(&lex.as_str()) || is_wsl_engine_socket(&lex) {
if ENGINE_SOCKS.contains(&lex.as_str())
|| is_wsl_engine_socket(&lex)
|| lex == SSH_AGENT_SOCK
|| lex == "/sys"
|| lex.starts_with("/sys/")
{
return Ok(lex);
}
let is_internal_wsl = |p: &str| {
Expand Down Expand Up @@ -472,6 +477,7 @@ const VM_ENGINE_SOCK: &str = "/run/host-services/docker.sock";
/// (`DOCKER_HOST=unix://~/.kiri/run/docker.sock`, which Testcontainers
/// mounts into Ryuk).
const ENGINE_SOCKS: &[&str] = &["/var/run/docker.sock", "/run/docker.sock", "/private/var/run/docker.sock"];
const SSH_AGENT_SOCK: &str = "/run/host-services/ssh-auth.sock";

/// Where a path really is: its links followed, and the file it leads to
/// as device and inode, which also matches a hard link or another mount of
Expand Down Expand Up @@ -880,6 +886,26 @@ mod tests {
split_for("/run/docker.sock:/var/run/docker.sock", Some(&w), Some("Ubuntu")).unwrap(),
t("/run/docker.sock", "/var/run/docker.sock", "")
);
assert_eq!(
split_for("/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", Some(&w), Some("Ubuntu")).unwrap(),
t("/run/host-services/ssh-auth.sock", "/run/host-services/ssh-auth.sock", "")
);
assert_eq!(
split_for("/sys/fs/cgroup:/sys/fs/cgroup", Some(&w), Some("Ubuntu")).unwrap(),
t("/sys/fs/cgroup", "/sys/fs/cgroup", "")
);
assert_eq!(
split_for("/sys:/hostsys:ro", Some(&w), Some("Ubuntu")).unwrap(),
t("/sys", "/hostsys", "ro")
);
assert_eq!(
split_for("/sys/fs/./cgroup:/mnt2", Some(&w), Some("Ubuntu")).unwrap(),
t("/sys/fs/cgroup", "/mnt2", "")
);
assert_eq!(
distro_source("/sys/../etc/passwd", "Ubuntu", Some(&w)).unwrap(),
"/mnt/wsl/kiri/roots/Ubuntu/etc/passwd"
);
assert_eq!(
split_for("myvol:/data", Some(&w), Some("Ubuntu")).unwrap(),
t("myvol", "/data", "")
Expand Down
Loading
Loading