1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use std::path::{Path, PathBuf};
use backtrace::Backtrace;
use nix::fcntl::OFlag;
use nix::sched::{clone, CloneFlags};
use nix::sys::signal::Signal;
use nix::sys::wait::waitpid;
use nix::unistd::{execv, mkdir, Pid};
use tempfile::{tempdir, TempDir};
mod command;
use command::DiskWritePolicy;
pub use self::command::Command;
pub use nix::sys::wait::WaitStatus;
struct AutoCloseFd {
fd: i32,
}
impl Drop for AutoCloseFd {
fn drop(&mut self) {
use nix::unistd::close;
let _ = close(self.fd);
}
}
fn setup_rootfs(path: &Path) {
use nix::fcntl::open;
use nix::mount::{mount, umount2, MntFlags, MsFlags};
use nix::sys::stat::Mode;
use nix::unistd::{fchdir, pivot_root};
let none: Option<&str> = None;
let oflag = OFlag::O_DIRECTORY | OFlag::O_RDONLY;
let mode = Mode::empty();
AutoCloseFd {
fd: open("/", oflag, mode).expect("Could not open old root directory"),
};
let newroot = AutoCloseFd {
fd: open(path, oflag, mode).expect("Could not open new root directory"),
};
mount(none, "/", none, MsFlags::MS_PRIVATE, none)
.expect("Could not remount old root directory as private");
mount(none, path, none, MsFlags::MS_PRIVATE, none)
.expect("Could not remount new root directory as private");
fchdir(newroot.fd).expect("Chould not change to new root directory");
pivot_root(".", ".").expect("pivot_root failed");
let _ = mkdir("/proc", Mode::from_bits(0o700).unwrap());
mount(none, "/proc", Some("proc"), MsFlags::empty(), none).expect("Could not mount proc");
let _ = mkdir("/sys", Mode::from_bits(0o700).unwrap());
mount(none, "/sys", Some("sysfs"), MsFlags::empty(), none).expect("Could not mount sysfs");
umount2("/", MntFlags::MNT_DETACH).expect("Could not detach from old root directory");
}
fn overlayfs_escape_path<P: Into<String>>(path: P) -> String {
path.into()
.replace("\\", "\\\\")
.replace(":", "\\:")
.replace(",", "\\,")
}
fn create_overlayfs(mountpoint: &Path, workdir: &Path, layers: &[PathBuf], writedir: &Path) {
use nix::mount::{mount, MsFlags};
let mut options = format!(
"workdir={}",
overlayfs_escape_path(workdir.to_str().expect("TODO: utf8 error"))
);
options.push_str(&format!(
",lowerdir={}",
layers
.iter()
.map(|p| overlayfs_escape_path(p.to_str().expect("TODO: utf8 error")))
.collect::<Vec<_>>()
.join(":")
));
options.push_str(&format!(
",upperdir={}",
overlayfs_escape_path(writedir.to_str().expect("TODO: utf8 error"))
));
mount(
Some("overlay"),
mountpoint,
Some("overlay"),
MsFlags::empty(),
Some(options.as_str()),
)
.expect("overlayfs mount");
}
#[allow(dead_code)]
struct HeldResources {
tmp: TempDir,
}
impl Drop for HeldResources {
fn drop(&mut self) {
let mountpoint = self.tmp.path().join("mount");
nix::mount::umount(&mountpoint).expect("Failed to umount mountpoint");
}
}
pub struct Process {
id: Pid,
status: Option<WaitStatus>,
#[allow(dead_code)]
resources: HeldResources,
}
impl Process {
pub fn spawn(command: Command) -> nix::Result<Process> {
let tmp = tempdir().expect("tempdir creation failed");
let mountpoint = tmp.path().join("mount");
let workdir = tmp.path().join("work");
let writedir = match command.disk_write {
DiskWritePolicy::TempDir => {
let d = tmp.path().join("write");
std::fs::create_dir(&d).expect("Creating temp writedir failed");
d
}
DiskWritePolicy::WriteDir(d) => d,
};
std::fs::create_dir(&mountpoint).expect("Creating temp mountpoint failed");
std::fs::create_dir(&workdir).expect("Creating temp workdir failed");
create_overlayfs(&mountpoint, &workdir, &command.layers, &writedir);
let old_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|panic_info| {
let bt = Backtrace::new();
println!("BUG: panic in pre-exec environment!");
println!("{}", panic_info);
println!("\nBacktrace:\n{:?}", bt);
std::process::exit(1);
}));
let path = command.path;
let args = command.args;
let mut stack = [0; 4096];
let id = clone(
Box::new(move || {
setup_rootfs(&mountpoint);
execv(path.as_c_str(), &args).expect("execv failed");
unreachable!();
}),
&mut stack,
CloneFlags::CLONE_VFORK
| CloneFlags::CLONE_NEWNS
| CloneFlags::CLONE_NEWPID
| CloneFlags::CLONE_NEWNET,
Some(Signal::SIGCHLD as i32),
)
.expect("Clone failed");
std::panic::set_hook(old_hook);
Ok(Process {
id,
status: None,
resources: HeldResources { tmp },
})
}
pub fn wait(&mut self) -> nix::Result<WaitStatus> {
if let Some(old_status) = self.status {
Ok(old_status)
} else {
let status = waitpid(self.id, None)?;
self.status = Some(status);
Ok(status)
}
}
pub fn signal(&mut self, signal: Signal) -> nix::Result<()> {
use nix::sys::signal::kill;
if self.status.is_some() {
panic!("Attempting to send a signal to a known-dead process");
}
kill(self.id, signal)
}
}
impl Drop for Process {
fn drop(&mut self) {
if self.status.is_none() {
panic!("Dropping a running process");
}
}
}