OXYGENHUB
# 1daca0b6bb8c oxygenflow / crates / flow-init / src / main.rs
14.8 KiB · Rust · last changed Sandbox env, and an image's own environment 1 month ago source blame history raw
e0918b88 Andy McCall 1
//! PID 1 of a job's microVM (docs/m0.md §2). It mounts the read-only
2
//! rootfs and the workspace, runs the job's argv as an unprivileged user
3
//! with exactly the job's environment, frames the output on the serial
4
//! console for the host, and powers off. It never decides anything the
5
//! host has not: the job comes from `/job.json` in the initramfs the host
6
//! built, and the host enforces the time limit.
7
//!
8
//! Frames, one per line on the console: `\x1eO ` stdout, `\x1eE ` stderr,
9
//! `\x1eX <code>` the exit code (128 + signal when killed), `\x1eF <text>`
10
//! a failure of init itself.
11
12
use serde::Deserialize;
13
use std::ffi::CString;
14
use std::io::{Read, Write};
15
use std::os::fd::FromRawFd;
16
use std::sync::{Arc, Mutex};
17
18
#[derive(Deserialize)]
19
struct JobSpec {
20
    argv: Vec<String>,
21
    env: Vec<(String, String)>,
fc10d9e8 Andy McCall ↶ 22
    #[serde(default)]
23
    mounts: Vec<MountSpec>,
eb5c4db6 Andy McCall ↶ 24
    /// `network "loopback"`: bring up `lo` (the guest has no other device).
25
    #[serde(default)]
26
    loopback: bool,
fc10d9e8 Andy McCall ↶ 27
}
28
29
/// An ephemeral mount from the host: a tmpfs of `size_mib`, or the disk at
30
/// `device`, mounted at `target` under the new root.
31
#[derive(serde::Deserialize)]
32
struct MountSpec {
33
    kind: String,
34
    target: String,
35
    size_mib: u32,
36
    #[serde(default)]
37
    device: Option<String>,
e0918b88 Andy McCall 38
}
39
40
const PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
41
42
fn main() {
43
    let console = Arc::new(Mutex::new(std::io::stdout()));
44
    let code = match run(&console) {
45
        Ok(code) => code,
46
        Err(e) => {
47
            frame(&console, b'F', e.as_bytes());
48
            125
49
        }
50
    };
51
    frame(&console, b'X', code.to_string().as_bytes());
52
    unsafe {
53
        libc::sync();
54
        // Firecracker ends the VM when the guest reboots (reboot=k).
55
        libc::reboot(libc::LINUX_REBOOT_CMD_RESTART);
56
    }
57
}
58
59
fn frame(console: &Mutex<std::io::Stdout>, kind: u8, text: &[u8]) {
60
    let mut out = console.lock().unwrap_or_else(|p| p.into_inner());
61
    let mut line = Vec::with_capacity(text.len() + 4);
62
    line.extend_from_slice(&[0x1e, kind, b' ']);
63
    line.extend_from_slice(text);
64
    line.push(b'\n');
65
    let _ = out.write_all(&line);
66
    let _ = out.flush();
67
}
68
69
fn cstr(s: &str) -> Result<CString, String> {
70
    CString::new(s).map_err(|_| format!("{s:?} contains NUL"))
71
}
72
fc10d9e8 Andy McCall ↶ 73
fn chown(path: &str, uid: libc::uid_t, gid: libc::gid_t) -> Result<(), String> {
74
    let p = cstr(path)?;
75
    if unsafe { libc::chown(p.as_ptr(), uid, gid) } != 0 {
76
        return Err(format!("chown {path}: {}", std::io::Error::last_os_error()));
77
    }
78
    Ok(())
79
}
80
81
/// Create `path` and its missing parents, each owned by the job's user.
82
fn make_dirs_owned(path: &str, uid: libc::uid_t, gid: libc::gid_t) -> Result<(), String> {
83
    let mut missing = Vec::new();
84
    let mut p = std::path::Path::new(path);
85
    while !p.exists() {
86
        missing.push(p.to_path_buf());
87
        p = match p.parent() {
88
            Some(parent) => parent,
89
            None => break,
90
        };
91
    }
92
    for d in missing.iter().rev() {
93
        std::fs::create_dir(d).map_err(|e| format!("mkdir {}: {e}", d.display()))?;
94
        chown(&d.to_string_lossy(), uid, gid)?;
eb5c4db6 Andy McCall ↶ 95
    }
96
    Ok(())
97
}
98
99
/// The file `program` names: itself when it holds a `/`, otherwise the first
100
/// executable regular file of that name in `path`'s directories.
101
fn resolve_program(program: &str, path: &str) -> Option<String> {
102
    use std::os::unix::fs::PermissionsExt;
103
    if program.is_empty() {
104
        return None;
105
    }
106
    if program.contains('/') {
107
        return Some(program.to_string());
108
    }
109
    path.split(':')
110
        .filter(|d| !d.is_empty())
111
        .map(|d| format!("{d}/{program}"))
112
        .find(|p| std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0))
113
}
114
a72abeee Andy McCall ↶ 115
/// A job's environment: `PATH` and `HOME=/tmp` by default, then the
116
/// image's own (`/etc/flow/env`, written by `flow rootfs import --env`),
117
/// then the job's (its sandbox's and its own, already merged by the host).
118
/// Later ones win, so a pipeline can always set `PATH`.
119
fn job_env(image: Option<&str>, job: &[(String, String)]) -> std::collections::BTreeMap<String, String> {
120
    let mut env = std::collections::BTreeMap::new();
121
    env.insert("PATH".to_string(), PATH.to_string());
122
    env.insert("HOME".to_string(), "/tmp".to_string());
123
    for line in image.unwrap_or("").lines() {
124
        if let Some((k, v)) = line.split_once('=') {
125
            if !k.is_empty() {
126
                env.insert(k.to_string(), v.to_string());
127
            }
128
        }
129
    }
130
    for (k, v) in job {
131
        env.insert(k.clone(), v.clone());
132
    }
133
    env
134
}
135
c4285535 Andy McCall ↶ 136
/// The links every Linux system has under /dev and devtmpfs does not
137
/// make: `/dev/fd` (bash's process substitution, `<(…)`) and the standard
138
/// streams, all through the job's own /proc.
139
fn dev_links(dev: &str) -> Result<(), String> {
140
    for (name, target) in DEV_LINKS {
141
        let link = format!("{dev}/{name}");
142
        if std::fs::symlink_metadata(&link).is_err() {
143
            std::os::unix::fs::symlink(target, &link).map_err(|e| format!("link {link}: {e}"))?;
144
        }
145
    }
146
    Ok(())
147
}
148
149
const DEV_LINKS: [(&str, &str); 4] =
150
    [("fd", "/proc/self/fd"), ("stdin", "/proc/self/fd/0"), ("stdout", "/proc/self/fd/1"), ("stderr", "/proc/self/fd/2")];
151
eb5c4db6 Andy McCall ↶ 152
/// Set `lo` up; the kernel gives it 127.0.0.1 and ::1 itself.
153
fn loopback_up() -> Result<(), String> {
154
    let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
155
    if fd < 0 {
156
        return Err(format!("socket for lo: {}", std::io::Error::last_os_error()));
157
    }
158
    let mut req: libc::ifreq = unsafe { std::mem::zeroed() };
159
    for (i, b) in b"lo".iter().enumerate() {
160
        req.ifr_name[i] = *b as libc::c_char;
161
    }
162
    let ok = unsafe {
163
        libc::ioctl(fd, libc::SIOCGIFFLAGS, &mut req) == 0 && {
164
            req.ifr_ifru.ifru_flags |= libc::IFF_UP as libc::c_short;
165
            libc::ioctl(fd, libc::SIOCSIFFLAGS, &req) == 0
166
        }
167
    };
168
    let err = std::io::Error::last_os_error();
169
    unsafe { libc::close(fd) };
170
    if !ok {
171
        return Err(format!("bring up lo: {err}"));
fc10d9e8 Andy McCall ↶ 172
    }
173
    Ok(())
174
}
175
e0918b88 Andy McCall 176
fn mount(src: &str, target: &str, fstype: &str, flags: libc::c_ulong, data: &str) -> Result<(), String> {
177
    let (s, t, f, d) = (cstr(src)?, cstr(target)?, cstr(fstype)?, cstr(data)?);
178
    let rc = unsafe { libc::mount(s.as_ptr(), t.as_ptr(), f.as_ptr(), flags, d.as_ptr() as *const libc::c_void) };
179
    if rc != 0 {
180
        return Err(format!("mount {src} on {target}: {}", std::io::Error::last_os_error()));
181
    }
182
    Ok(())
183
}
184
185
fn run(console: &Arc<Mutex<std::io::Stdout>>) -> Result<i32, String> {
186
    let job: JobSpec = serde_json::from_slice(&std::fs::read("/job.json").map_err(|e| format!("read /job.json: {e}"))?)
187
        .map_err(|e| format!("parse /job.json: {e}"))?;
188
    if job.argv.is_empty() {
189
        return Err("empty argv".into());
190
    }
191
    let nosuid = libc::MS_NOSUID | libc::MS_NODEV;
192
    std::fs::create_dir_all("/dev").ok();
193
    mount("devtmpfs", "/dev", "devtmpfs", libc::MS_NOSUID, "")?;
194
    std::fs::create_dir_all("/newroot").map_err(|e| e.to_string())?;
195
    mount("/dev/vda", "/newroot", "ext4", libc::MS_RDONLY | libc::MS_NODEV, "")?;
196
    mount("/dev/vdb", "/newroot/src", "ext4", nosuid, "")?;
197
    mount("tmpfs", "/newroot/tmp", "tmpfs", nosuid, "mode=1777")?;
198
    mount("proc", "/newroot/proc", "proc", nosuid | libc::MS_NOEXEC, "")?;
199
    mount("devtmpfs", "/newroot/dev", "devtmpfs", libc::MS_NOSUID, "")?;
c4285535 Andy McCall ↶ 200
    dev_links("/newroot/dev")?;
e0918b88 Andy McCall 201
    if std::path::Path::new("/newroot/run").is_dir() {
202
        mount("tmpfs", "/newroot/run", "tmpfs", nosuid, "mode=755")?;
203
    }
204
    // The job runs as whoever owns the workspace (the host's builder), never root.
205
    let (uid, gid) = {
206
        let mut st: libc::stat = unsafe { std::mem::zeroed() };
207
        let p = cstr("/newroot/src")?;
208
        if unsafe { libc::stat(p.as_ptr(), &mut st) } != 0 {
209
            return Err("stat /src".into());
210
        }
211
        if st.st_uid == 0 {
212
            (1000, 1000)
213
        } else {
214
            (st.st_uid, st.st_gid)
215
        }
216
    };
fc10d9e8 Andy McCall ↶ 217
    // Ephemeral mounts: mount points are made (and owned by the job's user)
218
    // under the writable /src or /tmp, then each is mounted and given to it.
219
    for m in &job.mounts {
220
        let target = format!("/newroot{}", m.target);
221
        make_dirs_owned(&target, uid, gid)?;
222
        match (m.kind.as_str(), &m.device) {
223
            ("tmpfs", _) => mount("tmpfs", &target, "tmpfs", nosuid, &format!("size={}m,uid={uid},gid={gid},mode=755", m.size_mib))?,
224
            ("disk", Some(dev)) => {
225
                mount(dev, &target, "ext4", nosuid, "")?;
226
                chown(&target, uid, gid)?;
227
            }
228
            (kind, _) => return Err(format!("unknown mount kind {kind}")),
229
        }
230
    }
eb5c4db6 Andy McCall ↶ 231
    if job.loopback {
232
        loopback_up()?;
233
    }
e0918b88 Andy McCall 234
    let root = cstr("/newroot")?;
235
    if unsafe { libc::chroot(root.as_ptr()) } != 0 || std::env::set_current_dir("/src").is_err() {
236
        return Err(format!("enter the rootfs: {}", std::io::Error::last_os_error()));
237
    }
238
239
    let argv: Vec<CString> = job.argv.iter().map(|a| cstr(a)).collect::<Result<_, _>>()?;
eb5c4db6 Andy McCall ↶ 240
    // glibc's execvpe searches the caller's PATH, and PID 1 has none of its
241
    // own, so the program is found here, in the job's PATH, before forking.
a72abeee Andy McCall ↶ 242
    let vars = job_env(std::fs::read_to_string("/etc/flow/env").ok().as_deref(), &job.env);
243
    let path = vars.get("PATH").map(String::as_str).unwrap_or(PATH);
244
    let program = cstr(&resolve_program(&job.argv[0], path).ok_or_else(|| format!("cannot run {:?}: not found in {path}", job.argv[0]))?)?;
245
    let env: Vec<CString> = vars.iter().map(|(k, v)| cstr(&format!("{k}={v}"))).collect::<Result<_, _>>()?;
e0918b88 Andy McCall 246
    let mut out = [0; 2];
247
    let mut err = [0; 2];
248
    if unsafe { libc::pipe2(out.as_mut_ptr(), libc::O_CLOEXEC) } != 0 || unsafe { libc::pipe2(err.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
249
        return Err("pipe".into());
250
    }
251
    let pid = unsafe { libc::fork() };
252
    if pid < 0 {
253
        return Err("fork".into());
254
    }
255
    if pid == 0 {
256
        // Child: no way back to root, then the program itself (execvpe: no shell).
257
        unsafe {
258
            let null = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY);
259
            libc::dup2(null, 0);
260
            libc::dup2(out[1], 1);
261
            libc::dup2(err[1], 2);
262
            libc::setsid();
263
            if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(gid) != 0 || libc::setuid(uid) != 0 {
264
                libc::_exit(126);
265
            }
266
            let mut a: Vec<*const libc::c_char> = argv.iter().map(|c| c.as_ptr()).collect();
267
            a.push(std::ptr::null());
268
            let mut e: Vec<*const libc::c_char> = env.iter().map(|c| c.as_ptr()).collect();
269
            e.push(std::ptr::null());
eb5c4db6 Andy McCall ↶ 270
            libc::execve(program.as_ptr(), a.as_ptr(), e.as_ptr());
e0918b88 Andy McCall 271
            let msg = format!("flow: cannot run {:?}: {}\n", job.argv[0], std::io::Error::last_os_error());
272
            libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len());
273
            libc::_exit(127);
274
        }
275
    }
276
    unsafe {
277
        libc::close(out[1]);
278
        libc::close(err[1]);
279
    }
280
    let readers: Vec<_> = [(out[0], b'O'), (err[0], b'E')]
281
        .into_iter()
282
        .map(|(fd, kind)| {
283
            let console = console.clone();
284
            std::thread::spawn(move || pump(unsafe { std::fs::File::from_raw_fd(fd) }, kind, &console))
285
        })
286
        .collect();
287
    let mut status = 0;
288
    // Reap everything (we are PID 1) until the job itself exits.
289
    loop {
290
        let r = unsafe { libc::waitpid(-1, &mut status, 0) };
291
        if r == pid || r < 0 {
292
            break;
293
        }
294
    }
295
    for r in readers {
296
        let _ = r.join();
297
    }
298
    Ok(if libc::WIFEXITED(status) { libc::WEXITSTATUS(status) } else { 128 + libc::WTERMSIG(status) })
299
}
300
301
/// Frame a stream line by line; a long line is cut at 16 KiB.
302
fn pump(mut f: std::fs::File, kind: u8, console: &Mutex<std::io::Stdout>) {
303
    let mut buf = [0u8; 8192];
304
    let mut line: Vec<u8> = Vec::new();
305
    loop {
306
        let n = match f.read(&mut buf) {
307
            Ok(0) | Err(_) => break,
308
            Ok(n) => n,
309
        };
310
        for &b in &buf[..n] {
311
            if b == b'\n' || line.len() >= 16 * 1024 {
312
                frame(console, kind, &line);
313
                line.clear();
314
                if b == b'\n' {
315
                    continue;
316
                }
317
            }
318
            line.push(b);
319
        }
320
    }
321
    if !line.is_empty() {
322
        frame(console, kind, &line);
eb5c4db6 Andy McCall ↶ 323
    }
324
}
325
326
#[cfg(test)]
327
mod tests {
a72abeee Andy McCall ↶ 328
    use super::{dev_links, job_env, resolve_program};
329
330
    #[test]
331
    fn the_image_environment_sits_under_the_jobs() {
332
        let image = "PATH=/opt/llvm-mos/bin:/usr/bin:/bin\nX16EMU=/opt/x16emu\nnot a line\n";
333
        let env = job_env(Some(image), &[("X16EMU".into(), "/job".into()), ("LANG".into(), "C".into())]);
334
        assert_eq!(env["PATH"], "/opt/llvm-mos/bin:/usr/bin:/bin", "the image's PATH replaces the default");
335
        assert_eq!(env["X16EMU"], "/job", "the job's value wins");
336
        assert_eq!(env["HOME"], "/tmp");
337
        assert_eq!(env["LANG"], "C");
338
        assert_eq!(job_env(None, &[])["PATH"], super::PATH);
339
    }
c4285535 Andy McCall ↶ 340
341
    #[test]
342
    fn dev_gets_the_usual_links_once() {
343
        let dir = std::env::temp_dir().join(format!("flow-init-dev-{}", std::process::id()));
344
        let _ = std::fs::remove_dir_all(&dir);
345
        std::fs::create_dir_all(&dir).unwrap();
346
        let d = dir.to_str().unwrap();
347
        dev_links(d).unwrap();
348
        dev_links(d).unwrap();
349
        assert_eq!(std::fs::read_link(dir.join("fd")).unwrap(), std::path::Path::new("/proc/self/fd"));
350
        assert_eq!(std::fs::read_link(dir.join("stdout")).unwrap(), std::path::Path::new("/proc/self/fd/1"));
351
        // Through the host's /proc, the link works as in a job.
352
        assert!(dir.join("fd").join("0").exists() || !std::path::Path::new("/proc/self/fd/0").exists());
353
        std::fs::remove_dir_all(&dir).unwrap();
354
    }
355
eb5c4db6 Andy McCall ↶ 356
    use std::os::unix::fs::PermissionsExt;
357
358
    #[test]
359
    fn programs_are_found_in_the_jobs_path() {
360
        let dir = std::env::temp_dir().join(format!("flow-init-test-{}", std::process::id()));
361
        let (a, b) = (dir.join("a"), dir.join("b"));
362
        std::fs::create_dir_all(&a).unwrap();
363
        std::fs::create_dir_all(&b).unwrap();
364
        std::fs::write(a.join("tool"), "not executable").unwrap();
365
        std::fs::write(b.join("tool"), "#!/bin/sh\n").unwrap();
366
        std::fs::set_permissions(b.join("tool"), std::fs::Permissions::from_mode(0o755)).unwrap();
367
        std::fs::create_dir_all(a.join("dir")).unwrap();
368
        let path = format!("{}::{}", a.display(), b.display());
369
        assert_eq!(resolve_program("tool", &path), Some(format!("{}/tool", b.display())), "skips a file that is not executable");
370
        assert_eq!(resolve_program("dir", &path), None, "and directories");
371
        assert_eq!(resolve_program("missing", &path), None);
372
        assert_eq!(resolve_program("./x", &path).as_deref(), Some("./x"), "a path is used as given");
373
        assert_eq!(resolve_program("", &path), None);
374
        std::fs::remove_dir_all(&dir).unwrap();
e0918b88 Andy McCall 375
    }
376
}