OXYGENHUB
# c4285535b03a oxygenflow / crates / flow-init / src / main.rs
13.3 KiB · Rust · last changed Guest /dev/fd links; jobs are told what they build 1 month ago source blame history raw
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)>,
22
    #[serde(default)]
23
    mounts: Vec<MountSpec>,
24
    /// `network "loopback"`: bring up `lo` (the guest has no other device).
25
    #[serde(default)]
26
    loopback: bool,
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>,
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
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)?;
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
115
/// The links every Linux system has under /dev and devtmpfs does not
116
/// make: `/dev/fd` (bash's process substitution, `<(…)`) and the standard
117
/// streams, all through the job's own /proc.
118
fn dev_links(dev: &str) -> Result<(), String> {
119
    for (name, target) in DEV_LINKS {
120
        let link = format!("{dev}/{name}");
121
        if std::fs::symlink_metadata(&link).is_err() {
122
            std::os::unix::fs::symlink(target, &link).map_err(|e| format!("link {link}: {e}"))?;
123
        }
124
    }
125
    Ok(())
126
}
127
128
const DEV_LINKS: [(&str, &str); 4] =
129
    [("fd", "/proc/self/fd"), ("stdin", "/proc/self/fd/0"), ("stdout", "/proc/self/fd/1"), ("stderr", "/proc/self/fd/2")];
130
131
/// Set `lo` up; the kernel gives it 127.0.0.1 and ::1 itself.
132
fn loopback_up() -> Result<(), String> {
133
    let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
134
    if fd < 0 {
135
        return Err(format!("socket for lo: {}", std::io::Error::last_os_error()));
136
    }
137
    let mut req: libc::ifreq = unsafe { std::mem::zeroed() };
138
    for (i, b) in b"lo".iter().enumerate() {
139
        req.ifr_name[i] = *b as libc::c_char;
140
    }
141
    let ok = unsafe {
142
        libc::ioctl(fd, libc::SIOCGIFFLAGS, &mut req) == 0 && {
143
            req.ifr_ifru.ifru_flags |= libc::IFF_UP as libc::c_short;
144
            libc::ioctl(fd, libc::SIOCSIFFLAGS, &req) == 0
145
        }
146
    };
147
    let err = std::io::Error::last_os_error();
148
    unsafe { libc::close(fd) };
149
    if !ok {
150
        return Err(format!("bring up lo: {err}"));
151
    }
152
    Ok(())
153
}
154
155
fn mount(src: &str, target: &str, fstype: &str, flags: libc::c_ulong, data: &str) -> Result<(), String> {
156
    let (s, t, f, d) = (cstr(src)?, cstr(target)?, cstr(fstype)?, cstr(data)?);
157
    let rc = unsafe { libc::mount(s.as_ptr(), t.as_ptr(), f.as_ptr(), flags, d.as_ptr() as *const libc::c_void) };
158
    if rc != 0 {
159
        return Err(format!("mount {src} on {target}: {}", std::io::Error::last_os_error()));
160
    }
161
    Ok(())
162
}
163
164
fn run(console: &Arc<Mutex<std::io::Stdout>>) -> Result<i32, String> {
165
    let job: JobSpec = serde_json::from_slice(&std::fs::read("/job.json").map_err(|e| format!("read /job.json: {e}"))?)
166
        .map_err(|e| format!("parse /job.json: {e}"))?;
167
    if job.argv.is_empty() {
168
        return Err("empty argv".into());
169
    }
170
    let nosuid = libc::MS_NOSUID | libc::MS_NODEV;
171
    std::fs::create_dir_all("/dev").ok();
172
    mount("devtmpfs", "/dev", "devtmpfs", libc::MS_NOSUID, "")?;
173
    std::fs::create_dir_all("/newroot").map_err(|e| e.to_string())?;
174
    mount("/dev/vda", "/newroot", "ext4", libc::MS_RDONLY | libc::MS_NODEV, "")?;
175
    mount("/dev/vdb", "/newroot/src", "ext4", nosuid, "")?;
176
    mount("tmpfs", "/newroot/tmp", "tmpfs", nosuid, "mode=1777")?;
177
    mount("proc", "/newroot/proc", "proc", nosuid | libc::MS_NOEXEC, "")?;
178
    mount("devtmpfs", "/newroot/dev", "devtmpfs", libc::MS_NOSUID, "")?;
179
    dev_links("/newroot/dev")?;
180
    if std::path::Path::new("/newroot/run").is_dir() {
181
        mount("tmpfs", "/newroot/run", "tmpfs", nosuid, "mode=755")?;
182
    }
183
    // The job runs as whoever owns the workspace (the host's builder), never root.
184
    let (uid, gid) = {
185
        let mut st: libc::stat = unsafe { std::mem::zeroed() };
186
        let p = cstr("/newroot/src")?;
187
        if unsafe { libc::stat(p.as_ptr(), &mut st) } != 0 {
188
            return Err("stat /src".into());
189
        }
190
        if st.st_uid == 0 {
191
            (1000, 1000)
192
        } else {
193
            (st.st_uid, st.st_gid)
194
        }
195
    };
196
    // Ephemeral mounts: mount points are made (and owned by the job's user)
197
    // under the writable /src or /tmp, then each is mounted and given to it.
198
    for m in &job.mounts {
199
        let target = format!("/newroot{}", m.target);
200
        make_dirs_owned(&target, uid, gid)?;
201
        match (m.kind.as_str(), &m.device) {
202
            ("tmpfs", _) => mount("tmpfs", &target, "tmpfs", nosuid, &format!("size={}m,uid={uid},gid={gid},mode=755", m.size_mib))?,
203
            ("disk", Some(dev)) => {
204
                mount(dev, &target, "ext4", nosuid, "")?;
205
                chown(&target, uid, gid)?;
206
            }
207
            (kind, _) => return Err(format!("unknown mount kind {kind}")),
208
        }
209
    }
210
    if job.loopback {
211
        loopback_up()?;
212
    }
213
    let root = cstr("/newroot")?;
214
    if unsafe { libc::chroot(root.as_ptr()) } != 0 || std::env::set_current_dir("/src").is_err() {
215
        return Err(format!("enter the rootfs: {}", std::io::Error::last_os_error()));
216
    }
217
218
    let argv: Vec<CString> = job.argv.iter().map(|a| cstr(a)).collect::<Result<_, _>>()?;
219
    // glibc's execvpe searches the caller's PATH, and PID 1 has none of its
220
    // own, so the program is found here, in the job's PATH, before forking.
221
    let program = cstr(&resolve_program(&job.argv[0], PATH).ok_or_else(|| format!("cannot run {:?}: not found in {PATH}", job.argv[0]))?)?;
222
    let mut env: Vec<CString> = vec![cstr(&format!("PATH={PATH}"))?, cstr("HOME=/tmp")?];
223
    for (k, v) in &job.env {
224
        env.push(cstr(&format!("{k}={v}"))?);
225
    }
226
    let mut out = [0; 2];
227
    let mut err = [0; 2];
228
    if unsafe { libc::pipe2(out.as_mut_ptr(), libc::O_CLOEXEC) } != 0 || unsafe { libc::pipe2(err.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
229
        return Err("pipe".into());
230
    }
231
    let pid = unsafe { libc::fork() };
232
    if pid < 0 {
233
        return Err("fork".into());
234
    }
235
    if pid == 0 {
236
        // Child: no way back to root, then the program itself (execvpe: no shell).
237
        unsafe {
238
            let null = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY);
239
            libc::dup2(null, 0);
240
            libc::dup2(out[1], 1);
241
            libc::dup2(err[1], 2);
242
            libc::setsid();
243
            if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(gid) != 0 || libc::setuid(uid) != 0 {
244
                libc::_exit(126);
245
            }
246
            let mut a: Vec<*const libc::c_char> = argv.iter().map(|c| c.as_ptr()).collect();
247
            a.push(std::ptr::null());
248
            let mut e: Vec<*const libc::c_char> = env.iter().map(|c| c.as_ptr()).collect();
249
            e.push(std::ptr::null());
250
            libc::execve(program.as_ptr(), a.as_ptr(), e.as_ptr());
251
            let msg = format!("flow: cannot run {:?}: {}\n", job.argv[0], std::io::Error::last_os_error());
252
            libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len());
253
            libc::_exit(127);
254
        }
255
    }
256
    unsafe {
257
        libc::close(out[1]);
258
        libc::close(err[1]);
259
    }
260
    let readers: Vec<_> = [(out[0], b'O'), (err[0], b'E')]
261
        .into_iter()
262
        .map(|(fd, kind)| {
263
            let console = console.clone();
264
            std::thread::spawn(move || pump(unsafe { std::fs::File::from_raw_fd(fd) }, kind, &console))
265
        })
266
        .collect();
267
    let mut status = 0;
268
    // Reap everything (we are PID 1) until the job itself exits.
269
    loop {
270
        let r = unsafe { libc::waitpid(-1, &mut status, 0) };
271
        if r == pid || r < 0 {
272
            break;
273
        }
274
    }
275
    for r in readers {
276
        let _ = r.join();
277
    }
278
    Ok(if libc::WIFEXITED(status) { libc::WEXITSTATUS(status) } else { 128 + libc::WTERMSIG(status) })
279
}
280
281
/// Frame a stream line by line; a long line is cut at 16 KiB.
282
fn pump(mut f: std::fs::File, kind: u8, console: &Mutex<std::io::Stdout>) {
283
    let mut buf = [0u8; 8192];
284
    let mut line: Vec<u8> = Vec::new();
285
    loop {
286
        let n = match f.read(&mut buf) {
287
            Ok(0) | Err(_) => break,
288
            Ok(n) => n,
289
        };
290
        for &b in &buf[..n] {
291
            if b == b'\n' || line.len() >= 16 * 1024 {
292
                frame(console, kind, &line);
293
                line.clear();
294
                if b == b'\n' {
295
                    continue;
296
                }
297
            }
298
            line.push(b);
299
        }
300
    }
301
    if !line.is_empty() {
302
        frame(console, kind, &line);
303
    }
304
}
305
306
#[cfg(test)]
307
mod tests {
308
    use super::{dev_links, resolve_program};
309
310
    #[test]
311
    fn dev_gets_the_usual_links_once() {
312
        let dir = std::env::temp_dir().join(format!("flow-init-dev-{}", std::process::id()));
313
        let _ = std::fs::remove_dir_all(&dir);
314
        std::fs::create_dir_all(&dir).unwrap();
315
        let d = dir.to_str().unwrap();
316
        dev_links(d).unwrap();
317
        dev_links(d).unwrap();
318
        assert_eq!(std::fs::read_link(dir.join("fd")).unwrap(), std::path::Path::new("/proc/self/fd"));
319
        assert_eq!(std::fs::read_link(dir.join("stdout")).unwrap(), std::path::Path::new("/proc/self/fd/1"));
320
        // Through the host's /proc, the link works as in a job.
321
        assert!(dir.join("fd").join("0").exists() || !std::path::Path::new("/proc/self/fd/0").exists());
322
        std::fs::remove_dir_all(&dir).unwrap();
323
    }
324
325
    use std::os::unix::fs::PermissionsExt;
326
327
    #[test]
328
    fn programs_are_found_in_the_jobs_path() {
329
        let dir = std::env::temp_dir().join(format!("flow-init-test-{}", std::process::id()));
330
        let (a, b) = (dir.join("a"), dir.join("b"));
331
        std::fs::create_dir_all(&a).unwrap();
332
        std::fs::create_dir_all(&b).unwrap();
333
        std::fs::write(a.join("tool"), "not executable").unwrap();
334
        std::fs::write(b.join("tool"), "#!/bin/sh\n").unwrap();
335
        std::fs::set_permissions(b.join("tool"), std::fs::Permissions::from_mode(0o755)).unwrap();
336
        std::fs::create_dir_all(a.join("dir")).unwrap();
337
        let path = format!("{}::{}", a.display(), b.display());
338
        assert_eq!(resolve_program("tool", &path), Some(format!("{}/tool", b.display())), "skips a file that is not executable");
339
        assert_eq!(resolve_program("dir", &path), None, "and directories");
340
        assert_eq!(resolve_program("missing", &path), None);
341
        assert_eq!(resolve_program("./x", &path).as_deref(), Some("./x"), "a path is used as given");
342
        assert_eq!(resolve_program("", &path), None);
343
        std::fs::remove_dir_all(&dir).unwrap();
344
    }
345
}