OXYGENHUB
# 4cf0c99a1486 oxygenflow / crates / flow-init / src / main.rs
10.9 KiB · Rust · last changed The syscall tier: jobs without KVM 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
mod job;
19
use job::{dev_links, job_env, loopback_up, resolve_program, PATH};
20
21
#[derive(Deserialize)]
22
struct JobSpec {
23
    argv: Vec<String>,
24
    env: Vec<(String, String)>,
25
    #[serde(default)]
26
    mounts: Vec<MountSpec>,
27
    /// `network "loopback"`: bring up `lo` (the guest has no other device).
28
    #[serde(default)]
29
    loopback: bool,
30
    /// Secrets to write before the job starts (spec §9): each at `path`
31
    /// under `/run/secrets`, 0400 and the job's user's, on a tmpfs.
32
    #[serde(default)]
33
    secrets: Vec<SecretSpec>,
34
}
35
36
#[derive(serde::Deserialize)]
37
struct SecretSpec {
38
    path: String,
39
    value: String,
40
}
41
42
/// An ephemeral mount from the host: a tmpfs of `size_mib`, or the disk at
43
/// `device`, mounted at `target` under the new root.
44
#[derive(serde::Deserialize)]
45
struct MountSpec {
46
    kind: String,
47
    target: String,
48
    size_mib: u32,
49
    #[serde(default)]
50
    device: Option<String>,
51
}
52
53
fn main() {
54
    let console = Arc::new(Mutex::new(std::io::stdout()));
55
    let code = match run(&console) {
56
        Ok(code) => code,
57
        Err(e) => {
58
            frame(&console, b'F', e.as_bytes());
59
            125
60
        }
61
    };
62
    frame(&console, b'X', code.to_string().as_bytes());
63
    unsafe {
64
        libc::sync();
65
        // Firecracker ends the VM when the guest reboots (reboot=k).
66
        libc::reboot(libc::LINUX_REBOOT_CMD_RESTART);
67
    }
68
}
69
70
fn frame(console: &Mutex<std::io::Stdout>, kind: u8, text: &[u8]) {
71
    let mut out = console.lock().unwrap_or_else(|p| p.into_inner());
72
    let mut line = Vec::with_capacity(text.len() + 4);
73
    line.extend_from_slice(&[0x1e, kind, b' ']);
74
    line.extend_from_slice(text);
75
    line.push(b'\n');
76
    let _ = out.write_all(&line);
77
    let _ = out.flush();
78
}
79
80
fn cstr(s: &str) -> Result<CString, String> {
81
    CString::new(s).map_err(|_| format!("{s:?} contains NUL"))
82
}
83
84
fn chown(path: &str, uid: libc::uid_t, gid: libc::gid_t) -> Result<(), String> {
85
    let p = cstr(path)?;
86
    if unsafe { libc::chown(p.as_ptr(), uid, gid) } != 0 {
87
        return Err(format!("chown {path}: {}", std::io::Error::last_os_error()));
88
    }
89
    Ok(())
90
}
91
92
/// Create `path` and its missing parents, each owned by the job's user.
93
fn make_dirs_owned(path: &str, uid: libc::uid_t, gid: libc::gid_t) -> Result<(), String> {
94
    let mut missing = Vec::new();
95
    let mut p = std::path::Path::new(path);
96
    while !p.exists() {
97
        missing.push(p.to_path_buf());
98
        p = match p.parent() {
99
            Some(parent) => parent,
100
            None => break,
101
        };
102
    }
103
    for d in missing.iter().rev() {
104
        std::fs::create_dir(d).map_err(|e| format!("mkdir {}: {e}", d.display()))?;
105
        chown(&d.to_string_lossy(), uid, gid)?;
106
    }
107
    Ok(())
108
}
109
110
fn mount(src: &str, target: &str, fstype: &str, flags: libc::c_ulong, data: &str) -> Result<(), String> {
111
    let (s, t, f, d) = (cstr(src)?, cstr(target)?, cstr(fstype)?, cstr(data)?);
112
    let rc = unsafe { libc::mount(s.as_ptr(), t.as_ptr(), f.as_ptr(), flags, d.as_ptr() as *const libc::c_void) };
113
    if rc != 0 {
114
        return Err(format!("mount {src} on {target}: {}", std::io::Error::last_os_error()));
115
    }
116
    Ok(())
117
}
118
119
fn run(console: &Arc<Mutex<std::io::Stdout>>) -> Result<i32, String> {
120
    let job: JobSpec = serde_json::from_slice(&std::fs::read("/job.json").map_err(|e| format!("read /job.json: {e}"))?)
121
        .map_err(|e| format!("parse /job.json: {e}"))?;
122
    if job.argv.is_empty() {
123
        return Err("empty argv".into());
124
    }
125
    let nosuid = libc::MS_NOSUID | libc::MS_NODEV;
126
    std::fs::create_dir_all("/dev").ok();
127
    mount("devtmpfs", "/dev", "devtmpfs", libc::MS_NOSUID, "")?;
128
    std::fs::create_dir_all("/newroot").map_err(|e| e.to_string())?;
129
    mount("/dev/vda", "/newroot", "ext4", libc::MS_RDONLY | libc::MS_NODEV, "")?;
130
    mount("/dev/vdb", "/newroot/src", "ext4", nosuid, "")?;
131
    mount("tmpfs", "/newroot/tmp", "tmpfs", nosuid, "mode=1777")?;
132
    mount("proc", "/newroot/proc", "proc", nosuid | libc::MS_NOEXEC, "")?;
133
    mount("devtmpfs", "/newroot/dev", "devtmpfs", libc::MS_NOSUID, "")?;
134
    dev_links("/newroot/dev")?;
135
    if std::path::Path::new("/newroot/run").is_dir() {
136
        mount("tmpfs", "/newroot/run", "tmpfs", nosuid, "mode=755")?;
137
    }
138
    // The job runs as whoever owns the workspace (the host's builder), never root.
139
    let (uid, gid) = {
140
        let mut st: libc::stat = unsafe { std::mem::zeroed() };
141
        let p = cstr("/newroot/src")?;
142
        if unsafe { libc::stat(p.as_ptr(), &mut st) } != 0 {
143
            return Err("stat /src".into());
144
        }
145
        if st.st_uid == 0 {
146
            (1000, 1000)
147
        } else {
148
            (st.st_uid, st.st_gid)
149
        }
150
    };
151
    // Ephemeral mounts: mount points are made (and owned by the job's user)
152
    // under the writable /src or /tmp, then each is mounted and given to it.
153
    for m in &job.mounts {
154
        let target = format!("/newroot{}", m.target);
155
        make_dirs_owned(&target, uid, gid)?;
156
        match (m.kind.as_str(), &m.device) {
157
            ("tmpfs", _) => mount("tmpfs", &target, "tmpfs", nosuid, &format!("size={}m,uid={uid},gid={gid},mode=755", m.size_mib))?,
158
            ("disk", Some(dev)) => {
159
                mount(dev, &target, "ext4", nosuid, "")?;
160
                chown(&target, uid, gid)?;
161
            }
162
            (kind, _) => return Err(format!("unknown mount kind {kind}")),
163
        }
164
    }
165
    // Secrets: an in-memory mount of their own, only the job's user's,
166
    // each file 0400; the job file they came from is outside the new root.
167
    if !job.secrets.is_empty() {
168
        if !std::path::Path::new("/newroot/run").is_dir() {
169
            return Err("the image has no /run, where secrets are mounted".into());
170
        }
171
        let dir = "/newroot/run/secrets";
172
        std::fs::create_dir_all(dir).map_err(|e| format!("mkdir {dir}: {e}"))?;
173
        mount("tmpfs", dir, "tmpfs", nosuid | libc::MS_NOEXEC, &format!("size=1m,uid={uid},gid={gid},mode=700"))?;
174
        for s in &job.secrets {
175
            let Some(rel) = s.path.strip_prefix("/run/secrets/") else {
176
                return Err(format!("secret path {:?} is not under /run/secrets/", s.path));
177
            };
178
            let full = format!("{dir}/{rel}");
179
            if let Some(parent) = std::path::Path::new(&full).parent().and_then(|p| p.to_str()) {
180
                make_dirs_owned(parent, uid, gid)?;
181
            }
182
            std::fs::write(&full, s.value.as_bytes()).map_err(|e| format!("write {}: {e}", s.path))?;
183
            chown(&full, uid, gid)?;
184
            std::fs::set_permissions(&full, std::os::unix::fs::PermissionsExt::from_mode(0o400))
185
                .map_err(|e| format!("chmod {}: {e}", s.path))?;
186
        }
187
    }
188
    if job.loopback {
189
        loopback_up()?;
190
    }
191
    let root = cstr("/newroot")?;
192
    if unsafe { libc::chroot(root.as_ptr()) } != 0 || std::env::set_current_dir("/src").is_err() {
193
        return Err(format!("enter the rootfs: {}", std::io::Error::last_os_error()));
194
    }
195
196
    let argv: Vec<CString> = job.argv.iter().map(|a| cstr(a)).collect::<Result<_, _>>()?;
197
    // glibc's execvpe searches the caller's PATH, and PID 1 has none of its
198
    // own, so the program is found here, in the job's PATH, before forking.
199
    let vars = job_env(std::fs::read_to_string("/etc/flow/env").ok().as_deref(), &job.env);
200
    let path = vars.get("PATH").map(String::as_str).unwrap_or(PATH);
201
    let program = cstr(&resolve_program(&job.argv[0], path).ok_or_else(|| format!("cannot run {:?}: not found in {path}", job.argv[0]))?)?;
202
    let env: Vec<CString> = vars.iter().map(|(k, v)| cstr(&format!("{k}={v}"))).collect::<Result<_, _>>()?;
203
    let mut out = [0; 2];
204
    let mut err = [0; 2];
205
    if unsafe { libc::pipe2(out.as_mut_ptr(), libc::O_CLOEXEC) } != 0 || unsafe { libc::pipe2(err.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
206
        return Err("pipe".into());
207
    }
208
    let pid = unsafe { libc::fork() };
209
    if pid < 0 {
210
        return Err("fork".into());
211
    }
212
    if pid == 0 {
213
        // Child: no way back to root, then the program itself (execvpe: no shell).
214
        unsafe {
215
            let null = libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY);
216
            libc::dup2(null, 0);
217
            libc::dup2(out[1], 1);
218
            libc::dup2(err[1], 2);
219
            libc::setsid();
220
            if libc::setgroups(0, std::ptr::null()) != 0 || libc::setgid(gid) != 0 || libc::setuid(uid) != 0 {
221
                libc::_exit(126);
222
            }
223
            let mut a: Vec<*const libc::c_char> = argv.iter().map(|c| c.as_ptr()).collect();
224
            a.push(std::ptr::null());
225
            let mut e: Vec<*const libc::c_char> = env.iter().map(|c| c.as_ptr()).collect();
226
            e.push(std::ptr::null());
227
            libc::execve(program.as_ptr(), a.as_ptr(), e.as_ptr());
228
            let msg = format!("flow: cannot run {:?}: {}\n", job.argv[0], std::io::Error::last_os_error());
229
            libc::write(2, msg.as_ptr() as *const libc::c_void, msg.len());
230
            libc::_exit(127);
231
        }
232
    }
233
    unsafe {
234
        libc::close(out[1]);
235
        libc::close(err[1]);
236
    }
237
    let readers: Vec<_> = [(out[0], b'O'), (err[0], b'E')]
238
        .into_iter()
239
        .map(|(fd, kind)| {
240
            let console = console.clone();
241
            std::thread::spawn(move || pump(unsafe { std::fs::File::from_raw_fd(fd) }, kind, &console))
242
        })
243
        .collect();
244
    let mut status = 0;
245
    // Reap everything (we are PID 1) until the job itself exits.
246
    loop {
247
        let r = unsafe { libc::waitpid(-1, &mut status, 0) };
248
        if r == pid || r < 0 {
249
            break;
250
        }
251
    }
252
    for r in readers {
253
        let _ = r.join();
254
    }
255
    Ok(if libc::WIFEXITED(status) { libc::WEXITSTATUS(status) } else { 128 + libc::WTERMSIG(status) })
256
}
257
258
/// Frame a stream line by line; a long line is cut at 16 KiB.
259
fn pump(mut f: std::fs::File, kind: u8, console: &Mutex<std::io::Stdout>) {
260
    let mut buf = [0u8; 8192];
261
    let mut line: Vec<u8> = Vec::new();
262
    loop {
263
        let n = match f.read(&mut buf) {
264
            Ok(0) | Err(_) => break,
265
            Ok(n) => n,
266
        };
267
        for &b in &buf[..n] {
268
            if b == b'\n' || line.len() >= 16 * 1024 {
269
                frame(console, kind, &line);
270
                line.clear();
271
                if b == b'\n' {
272
                    continue;
273
                }
274
            }
275
            line.push(b);
276
        }
277
    }
278
    if !line.is_empty() {
279
        frame(console, kind, &line);
280
    }
281
}