Rewrite init script in rust and fix non-shell CMDs
CI / build (push) Successful in 14s

This commit is contained in:
2026-09-11 14:40:10 +02:00
parent 3a99da196d
commit d7613a4987
10 changed files with 603 additions and 189 deletions
+429
View File
@@ -0,0 +1,429 @@
//! slim universal init.
//!
//! Injected by `slim build` at /slim/init and invoked via init=/slim/init.
//! Sets up devices, filesystems, networking, and 9p shares, then execs the
//! container's CMD/ENTRYPOINT (or a runtime override) with execvp so the
//! command becomes PID 1 directly.
use base64::Engine;
use nix::mount::{MsFlags, mount};
use nix::sys::reboot::{RebootMode, reboot};
use nix::sys::stat::{Mode, SFlag, makedev, mknod};
use nix::sys::wait::waitpid;
use nix::unistd::{ForkResult, Gid, Uid, User, execvp, fork, setgid, setuid};
use std::env;
use std::ffi::CString;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
fn warn(msg: &str) {
eprintln!("slim-init: {msg}");
}
/// Run a fallible operation, logging on error.
fn try_io<F, T>(label: &str, f: F)
where
F: FnOnce() -> std::io::Result<T>,
{
if let Err(e) = f() {
warn(&format!("{label}: {e}"));
}
}
/// Run a command, logging on error or non-zero exit.
fn try_cmd(label: &str, cmd: &mut Command) {
match cmd.status() {
Ok(status) => {
if !status.success() {
warn(&format!("{label}: exited with {status}"));
}
}
Err(e) => warn(&format!("{label}: {e}")),
}
}
/// The kernel passes a minimal environment to init. Set a default PATH
/// so that `ip` and other tools can be found by name.
fn ensure_path() {
if env::var("PATH").is_err() {
// SAFETY: we are single-threaded before fork/exec.
unsafe {
env::set_var(
"PATH",
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
);
}
}
}
fn find_in_path(prog: &str) -> Option<String> {
let path = env::var("PATH").ok()?;
for dir in path.split(':') {
let candidate = format!("{dir}/{prog}");
if Path::new(&candidate).exists() {
return Some(candidate);
}
}
None
}
fn try_mount(
source: Option<&str>,
target: &str,
fstype: Option<&str>,
flags: MsFlags,
data: Option<&str>,
) {
if let Err(e) = mount(source, target, fstype, flags, data) {
warn(&format!("mount {target}: {e}"));
}
}
fn setup_filesystems() {
if !Path::new("/dev/console").exists() {
try_io("mknod /dev/console", || {
mknod(
"/dev/console",
SFlag::S_IFCHR,
Mode::S_IRUSR | Mode::S_IWUSR,
makedev(5, 1),
)
.map_err(std::io::Error::from)
});
}
let dirs = [
"/proc",
"/sys",
"/dev/pts",
"/dev/shm",
"/run",
"/tmp",
"/sys/fs/cgroup",
];
for d in &dirs {
try_io(&format!("mkdir {d}"), || fs::create_dir_all(d));
}
try_mount(Some("proc"), "/proc", Some("proc"), MsFlags::empty(), None);
try_mount(Some("sysfs"), "/sys", Some("sysfs"), MsFlags::empty(), None);
try_mount(
Some("devpts"),
"/dev/pts",
Some("devpts"),
MsFlags::empty(),
None,
);
try_mount(
Some("tmpfs"),
"/dev/shm",
Some("tmpfs"),
MsFlags::empty(),
None,
);
try_mount(
Some("tmpfs"),
"/run",
Some("tmpfs"),
MsFlags::empty(),
Some("mode=755"),
);
try_mount(
Some("tmpfs"),
"/tmp",
Some("tmpfs"),
MsFlags::empty(),
Some("mode=1777"),
);
// cgroup2
try_mount(
Some("cgroup2"),
"/sys/fs/cgroup",
Some("cgroup2"),
MsFlags::empty(),
None,
);
if let Ok(controllers) = fs::read_to_string("/sys/fs/cgroup/cgroup.controllers") {
for c in controllers.split_whitespace() {
try_io("write cgroup.subtree_control", || {
fs::write("/sys/fs/cgroup/cgroup.subtree_control", format!("+{c}"))
});
}
}
}
fn setup_rootless_prereqs() {
// make-rshared /
if let Err(e) =
mount::<str, str, str, str>(None, "/", None, MsFlags::MS_REC | MsFlags::MS_SHARED, None)
{
warn(&format!("make-rshared /: {e}"));
}
// chmod u+s newuidmap newgidmap
for bin in &["/usr/bin/newuidmap", "/usr/bin/newgidmap"] {
match fs::metadata(bin) {
Ok(meta) => {
let mut perms = meta.permissions();
perms.set_mode(perms.mode() | 0o4000);
try_io(&format!("chmod u+s {bin}"), || {
fs::set_permissions(bin, perms)
});
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => warn(&format!("stat {bin}: {e}")),
}
}
}
fn setup_timezone() {
try_io("symlink timezone", || {
std::os::unix::fs::symlink("/usr/share/zoneinfo/Europe/Stockholm", "/etc/localtime")
});
}
fn setup_networking() {
let ip = find_in_path("ip").unwrap_or_else(|| "/sbin/ip".to_string());
try_cmd(
"ip link set lo up",
Command::new(&ip).args(["link", "set", "lo", "up"]),
);
try_cmd(
"ip link set eth0 up",
Command::new(&ip).args(["link", "set", "eth0", "up"]),
);
try_cmd(
"ip addr add 10.0.2.15/24 dev eth0",
Command::new(&ip).args(["addr", "add", "10.0.2.15/24", "dev", "eth0"]),
);
try_cmd(
"ip route add default via 10.0.2.2",
Command::new(&ip).args(["route", "add", "default", "via", "10.0.2.2"]),
);
try_io("write /etc/resolv.conf", || {
fs::write("/etc/resolv.conf", "nameserver 10.0.2.3\n")
});
}
fn setup_9p_shares(workdir: &str) {
let cmdline = match fs::read_to_string("/proc/cmdline") {
Ok(c) => c,
Err(e) => {
warn(&format!("read /proc/cmdline: {e}"));
return;
}
};
let b64 = base64::engine::general_purpose::STANDARD;
for tok in cmdline.split_whitespace() {
if let Some(rest) = tok.strip_prefix("slim.mount=") {
let Some((tag, dest_b64)) = rest.split_once(':') else {
continue;
};
let dest = match b64.decode(dest_b64) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(s) => s,
Err(e) => {
warn(&format!("9p: invalid UTF-8 in guest path: {e}"));
continue;
}
},
Err(e) => {
warn(&format!("9p: base64 decode failed: {e}"));
continue;
}
};
// Resolve relative guest paths against WORKINGDIR
let dest = if dest.starts_with('/') {
dest
} else {
format!("{}/{}", workdir, dest)
};
try_io(&format!("mkdir {dest}"), || fs::create_dir_all(&dest));
try_mount(
Some(tag),
&dest,
Some("9p"),
MsFlags::empty(),
Some("trans=virtio,version=9p2000.L"),
);
}
}
}
fn read_file_opt(path: &str) -> Option<String> {
fs::read_to_string(path)
.ok()
.filter(|s| !s.trim().is_empty())
}
fn split_null_delimited(data: &[u8]) -> Vec<String> {
data.split(|&b| b == 0)
.filter(|s| !s.is_empty())
.map(|s| String::from_utf8_lossy(s).into_owned())
.collect()
}
fn read_argv() -> Vec<String> {
// Check for runtime override: slim.cmd=<base64(null-delimited argv)>
let b64 = base64::engine::general_purpose::STANDARD;
if let Ok(cmdline) = fs::read_to_string("/proc/cmdline") {
for tok in cmdline.split_whitespace() {
if let Some(rest) = tok.strip_prefix("slim.cmd=")
&& let Ok(decoded) = b64.decode(rest)
{
let argv = split_null_delimited(&decoded);
if !argv.is_empty() {
return argv;
}
}
}
}
// Fall back to build-time argv from /slim/exec
match fs::read("/slim/exec") {
Ok(data) => {
let argv = split_null_delimited(&data);
if !argv.is_empty() {
return argv;
}
}
Err(e) => warn(&format!("read /slim/exec: {e}")),
}
warn("no command found, falling back to /bin/sh");
vec!["/bin/sh".to_string()]
}
fn apply_env() {
if let Ok(data) = fs::read("/slim/env") {
for entry in split_null_delimited(&data) {
if let Some((key, val)) = entry.split_once('=') {
// SAFETY: we are single-threaded before fork/exec.
unsafe { env::set_var(key, val) };
}
}
}
}
fn apply_workdir() {
if let Some(dir) = read_file_opt("/slim/workdir") {
try_io("set working directory", || env::set_current_dir(&dir));
}
}
struct UserSpec {
uid: Uid,
gid: Gid,
}
fn resolve_user(spec: &str) -> Option<UserSpec> {
let (user_part, gid_part) = match spec.split_once(':') {
Some((u, g)) => (u, Some(g)),
None => (spec, None),
};
let (uid, default_gid) = if let Ok(numeric) = user_part.parse::<u32>() {
let user = User::from_uid(Uid::from_raw(numeric)).ok().flatten();
let gid = user
.as_ref()
.map(|u| u.gid)
.unwrap_or(Gid::from_raw(numeric));
(Uid::from_raw(numeric), gid)
} else {
let user = User::from_name(user_part).ok().flatten()?;
(user.uid, user.gid)
};
let gid = match gid_part {
Some(g) => match g.parse::<u32>() {
Ok(n) => Gid::from_raw(n),
Err(_) => default_gid,
},
None => default_gid,
};
Some(UserSpec { uid, gid })
}
fn exec_command(argv: &[String], user: Option<UserSpec>) -> ! {
let cstrings: Vec<CString> = argv
.iter()
.map(|s| CString::new(s.as_str()).unwrap_or_default())
.collect();
let c_prog = cstrings[0].clone();
let c_refs: Vec<&CString> = cstrings.iter().collect();
match user {
None => {
// No privilege drop: exec directly, PID 1 becomes the command.
let Err(e) = execvp(&c_prog, &c_refs);
warn(&format!("execvp {}: {e}", argv[0]));
let _ = reboot(RebootMode::RB_POWER_OFF);
std::process::exit(1);
}
Some(user) => {
// Drop privileges in a child so PID 1 (root) can poweroff afterwards.
match unsafe { fork() } {
Ok(ForkResult::Child) => {
// setgid before setuid to avoid losing privileges
if let Err(e) = setgid(user.gid) {
warn(&format!("setgid: {e}"));
}
if let Err(e) = setuid(user.uid) {
warn(&format!("setuid: {e}"));
}
let Err(e) = execvp(&c_prog, &c_refs);
warn(&format!("execvp {}: {e}", argv[0]));
std::process::exit(127);
}
Ok(ForkResult::Parent { child }) => {
let _ = waitpid(child, None);
let _ = reboot(RebootMode::RB_POWER_OFF);
std::process::exit(0);
}
Err(e) => {
warn(&format!("fork: {e}"));
let _ = reboot(RebootMode::RB_POWER_OFF);
std::process::exit(1);
}
}
}
}
}
fn main() {
ensure_path();
// === Devices & special filesystems ===
setup_filesystems();
// === Rootless container prerequisites (best-effort) ===
setup_rootless_prereqs();
// === Timezone ===
setup_timezone();
// === Networking ===
setup_networking();
// === 9p shares ===
let workdir = read_file_opt("/slim/workdir").unwrap_or_default();
setup_9p_shares(&workdir);
// === Environment & working directory ===
apply_env();
apply_workdir();
// === Resolve user for privilege drop ===
let user = read_file_opt("/slim/user").and_then(|spec| resolve_user(&spec));
// === Execute the configured command ===
let argv = read_argv();
exec_command(&argv, user);
}