tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

1036 lignes · 34653 octetsBrut · Historique
1//! Running a program (`std/command`, ADR 0085): the driver both back ends
2//! share. The native runtime parks the calling actor on the child's file
3//! descriptors (`louise_rt/src/command.rs`); the interpreter waits on them
4//! with `poll(2)`. Neither ever blocks on the child itself.
5//!
6//! - **No shell.** The program gets exactly the arguments given, and
7//! exactly the environment given: nothing is inherited.
8//! - **`posix_spawn`, not `std::process`.** The runtime blocks SIGTERM,
9//! SIGINT and SIGHUP in every thread (`signals.rs`), and Rust's
10//! `Command` hands the parent's mask down to the child, which would then
11//! ignore the SIGTERM of a timeout. The spawn here empties the child's
12//! mask, resets every disposition to its default and puts the child in
13//! a process group of its own, so a timeout reaches what it started.
14//! - **Descriptors.** The child's three pipes, a pidfd (the child's exit),
15//! and a timerfd (the next deadline), all non-blocking: a caller waits
16//! until one is ready, then calls [`Child::step`] until it is done.
17//! - **Deadlines.** At the timeout the group gets SIGTERM; after the grace
18//! period, SIGKILL. When the child ends, what is left of its group gets
19//! SIGKILL, and the pipes are drained for at most the grace period (a
20//! descendant that left the group may hold them open).
21//! - **No zombies.** Dropping a [`Child`] before it is done (its actor was
22//! killed) kills the group and reaps the child, on a reaper thread if
23//! the child does not die at once. A program that exits kills the groups
24//! still running ([`kill_all`], an `atexit` handler).
25
26use std::ffi::CString;
27use std::fs::{DirBuilder, OpenOptions};
28use std::io::{ErrorKind, Read, Write};
29use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
30use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
31use std::path::{Path, PathBuf};
32use std::sync::mpsc::{Sender, channel};
33use std::sync::{Mutex, OnceLock};
34use std::time::{Duration, Instant};
35
36/// Where the program runs.
37pub enum Dir {
38 /// The caller's working directory.
39 Inherit,
40 /// This directory.
41 In(PathBuf),
42 /// A fresh private directory: `inputs` are written into it first,
43 /// `outputs` are read back (at most `max_file` bytes each) once the
44 /// program ends, then the directory is removed.
45 Scratch {
46 inputs: Vec<(String, Vec<u8>)>,
47 outputs: Vec<String>,
48 max_file: usize,
49 },
50}
51
52/// What to run.
53pub struct Spec {
54 pub program: String,
55 pub args: Vec<String>,
56 pub env: Vec<(String, String)>,
57 pub dir: Dir,
58 pub stdin: Vec<u8>,
59 pub max_stdout: usize,
60 pub max_stderr: usize,
61 pub timeout: Duration,
62 pub grace: Duration,
63}
64
65/// Why a program did not run. [`Failure::code`] numbers them in the order
66/// of `std/command`'s `Error` constructors.
67#[derive(Debug, PartialEq, Eq)]
68pub enum Failure {
69 NotFound(String),
70 Denied(String),
71 BadArgument(String),
72 Failed(String),
73}
74
75impl Failure {
76 pub fn code(&self) -> i64 {
77 match self {
78 Self::NotFound(_) => 0,
79 Self::Denied(_) => 1,
80 Self::BadArgument(_) => 2,
81 Self::Failed(_) => 3,
82 }
83 }
84
85 pub fn message(&self) -> &str {
86 match self {
87 Self::NotFound(m) | Self::Denied(m) | Self::BadArgument(m) | Self::Failed(m) => m,
88 }
89 }
90}
91
92/// How the program ended. [`Exit::kind`] numbers them in the order of
93/// `std/command`'s `Exit` constructors.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum Exit {
96 Exited(i32),
97 Signalled(i32),
98 /// The timeout passed; the last signal the group was sent.
99 TimedOut(i32),
100}
101
102impl Exit {
103 pub fn kind(self) -> i64 {
104 match self {
105 Self::Exited(_) => 0,
106 Self::Signalled(_) => 1,
107 Self::TimedOut(_) => 2,
108 }
109 }
110
111 pub fn value(self) -> i64 {
112 match self {
113 Self::Exited(n) | Self::Signalled(n) | Self::TimedOut(n) => i64::from(n),
114 }
115 }
116}
117
118/// A scratch output, read back. [`Collected::kind`] numbers them in the
119/// order of `std/command`'s `Collected` constructors.
120#[derive(Debug, PartialEq, Eq)]
121pub enum Collected {
122 Found(String, Vec<u8>),
123 TooLarge(String, u64),
124 Absent(String),
125}
126
127impl Collected {
128 pub fn kind(&self) -> i64 {
129 match self {
130 Self::Found(..) => 0,
131 Self::TooLarge(..) => 1,
132 Self::Absent(_) => 2,
133 }
134 }
135}
136
137/// A finished run.
138pub struct Outcome {
139 pub exit: Exit,
140 pub stdout: Vec<u8>,
141 pub stderr: Vec<u8>,
142 pub stdout_cut: bool,
143 pub stderr_cut: bool,
144 pub files: Vec<Collected>,
145}
146
147/// What a [`Child::step`] found.
148pub enum Step {
149 /// Wait for one of [`Child::fds`] to be ready, then step again.
150 Pending,
151 Done(Outcome),
152}
153
154/// Whether a descriptor is waited on for reading or for writing.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum Interest {
157 Read,
158 Write,
159}
160
161/// Check `spec` before anything is created.
162pub fn validate(spec: &Spec) -> Result<(), Failure> {
163 let bad = |m: String| Err(Failure::BadArgument(m));
164 if spec.program.is_empty() {
165 return bad("the program is empty".into());
166 }
167 let texts = std::iter::once(&spec.program)
168 .chain(&spec.args)
169 .chain(spec.env.iter().flat_map(|(k, v)| [k, v]));
170 if let Some(t) = texts.into_iter().find(|t| t.contains('\0')) {
171 return bad(format!("a NUL byte in {t:?}"));
172 }
173 if let Some((k, _)) = spec
174 .env
175 .iter()
176 .find(|(k, _)| k.is_empty() || k.contains('='))
177 {
178 return bad(format!("not an environment variable name: {k:?}"));
179 }
180 if spec.timeout.is_zero() {
181 return bad("the timeout must be positive".into());
182 }
183 match &spec.dir {
184 Dir::In(p) if p.as_os_str().is_empty() => bad("the directory is empty".into()),
185 Dir::Scratch {
186 inputs, outputs, ..
187 } => {
188 let names = inputs.iter().map(|(n, _)| n).chain(outputs);
189 match names.into_iter().find(|n| !plain_name(n)) {
190 Some(n) => bad(format!("not a plain file name: {n:?}")),
191 None => Ok(()),
192 }
193 }
194 _ => Ok(()),
195 }
196}
197
198/// A file name with no directory in it: not empty, no `/`, no NUL, not
199/// `.` or `..`.
200pub fn plain_name(name: &str) -> bool {
201 !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\0'])
202}
203
204/// The file `program` names: itself if it has a `/`, else the first
205/// executable file of that name in the absolute directories of `path`
206/// (the `PATH` the program is given, never the caller's).
207pub fn resolve(program: &str, path: Option<&str>) -> Option<PathBuf> {
208 if program.contains('/') {
209 return Some(PathBuf::from(program));
210 }
211 path?
212 .split(':')
213 .filter(|d| d.starts_with('/'))
214 .map(|d| Path::new(d).join(program))
215 .find(|p| executable(p))
216}
217
218fn executable(p: &Path) -> bool {
219 let Ok(c) = CString::new(p.as_os_str().as_encoded_bytes()) else {
220 return false;
221 };
222 // SAFETY: `c` is a valid C string.
223 p.is_file() && unsafe { libc::access(c.as_ptr(), libc::X_OK) } == 0
224}
225
226/// A running program. Drop it only when done, or to stop it.
227pub struct Child {
228 pid: libc::pid_t,
229 pidfd: OwnedFd,
230 timer: OwnedFd,
231 stdin: Option<OwnedFd>,
232 stdout: Option<OwnedFd>,
233 stderr: Option<OwnedFd>,
234 input: Vec<u8>,
235 written: usize,
236 out: Capture,
237 err: Capture,
238 deadline: Instant,
239 grace: Duration,
240 /// The last signal the timeout sent, and when the next is due.
241 timeout: Option<(i32, Instant)>,
242 /// How the child ended, and until when its pipes are drained.
243 ended: Option<(Exit, Instant)>,
244 scratch: Option<Scratch>,
245}
246
247struct Capture {
248 data: Vec<u8>,
249 max: usize,
250 cut: bool,
251}
252
253struct Scratch {
254 dir: PathBuf,
255 outputs: Vec<String>,
256 max_file: usize,
257}
258
259impl Drop for Scratch {
260 fn drop(&mut self) {
261 // Removing what is left is all that can be done; symlinks are
262 // removed, never followed.
263 let _ = std::fs::remove_dir_all(&self.dir);
264 }
265}
266
267/// Start `spec`'s program (checked by [`validate`]).
268pub fn spawn(spec: Spec) -> Result<Child, Failure> {
269 validate(&spec)?;
270 let path_var = spec
271 .env
272 .iter()
273 .find(|(k, _)| k == "PATH")
274 .map(|(_, v)| v.as_str());
275 let program = resolve(&spec.program, path_var)
276 .ok_or_else(|| Failure::NotFound(format!("{}: not found", spec.program)))?;
277 let (scratch, cwd) = match spec.dir {
278 Dir::Inherit => (None, None),
279 Dir::In(dir) => (None, Some(dir)),
280 Dir::Scratch {
281 inputs,
282 outputs,
283 max_file,
284 } => {
285 let s = scratch(&inputs, outputs, max_file)?;
286 let dir = s.dir.clone();
287 (Some(s), Some(dir))
288 }
289 };
290 let c = |s: &[u8]| CString::new(s).map_err(|e| Failure::BadArgument(e.to_string()));
291 let path = c(program.as_os_str().as_encoded_bytes())?;
292 let argv = std::iter::once(&spec.program)
293 .chain(&spec.args)
294 .map(|a| c(a.as_bytes()))
295 .collect::<Result<Vec<_>, _>>()?;
296 let envp = spec
297 .env
298 .iter()
299 .map(|(k, v)| c(format!("{k}={v}").as_bytes()))
300 .collect::<Result<Vec<_>, _>>()?;
301 let cwd = cwd
302 .map(|d| c(d.as_os_str().as_encoded_bytes()))
303 .transpose()?;
304 let (child_in, stdin) = pipe()?;
305 let (stdout, child_out) = pipe()?;
306 let (stderr, child_err) = pipe()?;
307 let pid = posix_spawn(
308 &path,
309 &argv,
310 &envp,
311 cwd.as_ref(),
312 [&child_in, &child_out, &child_err],
313 )
314 .map_err(|e| failure(&spec.program, e))?;
315 drop((child_in, child_out, child_err));
316 track(pid);
317 let pidfd = match pidfd_open(pid) {
318 Ok(fd) => fd,
319 Err(e) => {
320 // SAFETY: `pid` is our unreaped child: it cannot be reused.
321 unsafe {
322 libc::killpg(pid, libc::SIGKILL);
323 libc::waitpid(pid, std::ptr::null_mut(), 0);
324 }
325 untrack(pid);
326 return Err(Failure::Failed(format!("pidfd_open: {e}")));
327 }
328 };
329 let timer = timerfd().map_err(|e| Failure::Failed(format!("timerfd: {e}")))?;
330 for fd in [&stdin, &stdout, &stderr] {
331 nonblocking(fd).map_err(|e| Failure::Failed(format!("fcntl: {e}")))?;
332 }
333 let now = Instant::now();
334 let child = Child {
335 pid,
336 pidfd,
337 timer,
338 stdin: (!spec.stdin.is_empty()).then_some(stdin),
339 stdout: Some(stdout),
340 stderr: Some(stderr),
341 input: spec.stdin,
342 written: 0,
343 out: Capture::new(spec.max_stdout),
344 err: Capture::new(spec.max_stderr),
345 deadline: now + spec.timeout,
346 grace: spec.grace,
347 timeout: None,
348 ended: None,
349 scratch,
350 };
351 child.arm(child.deadline, now);
352 Ok(child)
353}
354
355impl Child {
356 /// The descriptors to wait on, and for what.
357 pub fn fds(&self) -> Vec<(RawFd, Interest)> {
358 let read = [
359 Some(&self.pidfd),
360 Some(&self.timer),
361 self.stdout.as_ref(),
362 self.stderr.as_ref(),
363 ];
364 read.into_iter()
365 .flatten()
366 .map(|fd| (fd.as_raw_fd(), Interest::Read))
367 .chain(
368 self.stdin
369 .as_ref()
370 .map(|fd| (fd.as_raw_fd(), Interest::Write)),
371 )
372 .collect()
373 }
374
375 /// Do what can be done without waiting: read the pipes, write stdin,
376 /// notice the child's end, send the signals that are due.
377 pub fn step(&mut self) -> Step {
378 let mut tick = [0u8; 8];
379 let _ = read_fd(&self.timer, &mut tick);
380 drain(&mut self.stdout, &mut self.out);
381 drain(&mut self.stderr, &mut self.err);
382 self.feed();
383 let now = Instant::now();
384 if self.ended.is_none() {
385 if let Some(status) = self.reap() {
386 let exit = match self.timeout {
387 Some((signal, _)) => Exit::TimedOut(signal),
388 None => status,
389 };
390 self.ended = Some((exit, now + self.grace));
391 self.stdin = None;
392 drain(&mut self.stdout, &mut self.out);
393 drain(&mut self.stderr, &mut self.err);
394 } else {
395 self.signal_due(now);
396 }
397 }
398 match self.ended {
399 Some((exit, until))
400 if (self.stdout.is_none() && self.stderr.is_none()) || now >= until =>
401 {
402 Step::Done(self.finish(exit))
403 }
404 Some((_, until)) => {
405 self.arm(until, now);
406 Step::Pending
407 }
408 None => Step::Pending,
409 }
410 }
411
412 fn feed(&mut self) {
413 let Some(fd) = &self.stdin else { return };
414 while self.written < self.input.len() {
415 match write_quietly(fd, &self.input[self.written..]) {
416 Ok(n) => self.written += n,
417 Err(e) if e.kind() == ErrorKind::WouldBlock => return,
418 Err(e) if e.kind() == ErrorKind::Interrupted => {}
419 // EPIPE: the program stopped reading; the rest is dropped.
420 Err(_) => break,
421 }
422 }
423 self.stdin = None;
424 }
425
426 /// The timeout's signals: SIGTERM at the deadline, SIGKILL after the
427 /// grace period.
428 fn signal_due(&mut self, now: Instant) {
429 match self.timeout {
430 None if now >= self.deadline => {
431 self.kill_group(libc::SIGTERM);
432 let next = now + self.grace;
433 self.timeout = Some((libc::SIGTERM, next));
434 self.arm(next, now);
435 }
436 Some((libc::SIGTERM, next)) if now >= next => {
437 self.kill_group(libc::SIGKILL);
438 self.timeout = Some((libc::SIGKILL, next));
439 }
440 _ => {}
441 }
442 }
443
444 /// The child's status if it ended, reaped. What is left of its group
445 /// is killed first, while the unreaped child keeps the group's id.
446 fn reap(&mut self) -> Option<Exit> {
447 let mut info = waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT)?;
448 self.kill_group(libc::SIGKILL);
449 if let Some(reaped) = waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG) {
450 info = reaped;
451 }
452 untrack(self.pid);
453 self.pid = 0;
454 Some(info)
455 }
456
457 fn kill_group(&self, signal: i32) {
458 if self.pid > 0 {
459 // SAFETY: an unreaped child's id names its group; failure
460 // (the group is gone) is harmless.
461 unsafe { libc::killpg(self.pid, signal) };
462 }
463 }
464
465 /// Wake the waiter at `at` (at once if it passed).
466 fn arm(&self, at: Instant, now: Instant) {
467 let wait = at
468 .saturating_duration_since(now)
469 .max(Duration::from_millis(1));
470 let spec = libc::itimerspec {
471 it_interval: libc::timespec {
472 tv_sec: 0,
473 tv_nsec: 0,
474 },
475 it_value: libc::timespec {
476 tv_sec: wait.as_secs() as libc::time_t,
477 tv_nsec: wait.subsec_nanos() as libc::c_long,
478 },
479 };
480 // SAFETY: a valid timerfd and spec; a failure only delays a wake.
481 unsafe { libc::timerfd_settime(self.timer.as_raw_fd(), 0, &spec, std::ptr::null_mut()) };
482 }
483
484 fn finish(&mut self, exit: Exit) -> Outcome {
485 self.stdout = None;
486 self.stderr = None;
487 let files = self.scratch.as_ref().map(collect).unwrap_or_default();
488 self.scratch = None;
489 Outcome {
490 exit,
491 stdout: std::mem::take(&mut self.out.data),
492 stderr: std::mem::take(&mut self.err.data),
493 stdout_cut: self.out.cut,
494 stderr_cut: self.err.cut,
495 files,
496 }
497 }
498}
499
500impl Drop for Child {
501 fn drop(&mut self) {
502 if self.pid <= 0 {
503 return;
504 }
505 self.kill_group(libc::SIGKILL);
506 if waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG).is_none() {
507 // Not dead yet (in an uninterruptible wait): reaped elsewhere,
508 // never on the caller's thread.
509 if let Ok(fd) = self.pidfd.try_clone() {
510 reaper().lock().map(|r| r.send(fd)).ok();
511 }
512 }
513 untrack(self.pid);
514 }
515}
516
517impl Capture {
518 fn new(max: usize) -> Self {
519 Self {
520 data: Vec::new(),
521 max,
522 cut: false,
523 }
524 }
525
526 fn take(&mut self, chunk: &[u8]) {
527 let room = self.max.saturating_sub(self.data.len());
528 self.data.extend_from_slice(&chunk[..chunk.len().min(room)]);
529 self.cut |= chunk.len() > room;
530 }
531}
532
533/// Read `fd` until it would block; close it at its end.
534fn drain(fd: &mut Option<OwnedFd>, into: &mut Capture) {
535 let mut buf = [0u8; 64 * 1024];
536 while let Some(f) = fd {
537 match read_fd(f, &mut buf) {
538 Ok(0) => *fd = None,
539 Ok(n) => into.take(&buf[..n]),
540 Err(e) if e.kind() == ErrorKind::WouldBlock => return,
541 Err(e) if e.kind() == ErrorKind::Interrupted => {}
542 Err(_) => *fd = None,
543 }
544 }
545}
546
547fn read_fd(fd: &OwnedFd, buf: &mut [u8]) -> std::io::Result<usize> {
548 // SAFETY: `buf` is valid for its length; `fd` is open.
549 let n = unsafe { libc::read(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
550 if n < 0 {
551 Err(std::io::Error::last_os_error())
552 } else {
553 Ok(n as usize)
554 }
555}
556
557/// Write to a pipe without SIGPIPE: the signal is blocked on this thread
558/// for the write, and one it raised is taken before the mask is restored,
559/// so a program that stopped reading gives `EPIPE`, never the end of ours.
560fn write_quietly(fd: &OwnedFd, data: &[u8]) -> std::io::Result<usize> {
561 // SAFETY: plain libc calls on valid sets, buffer and descriptor.
562 unsafe {
563 let mut pipe: libc::sigset_t = std::mem::zeroed();
564 libc::sigemptyset(&mut pipe);
565 libc::sigaddset(&mut pipe, libc::SIGPIPE);
566 let mut old: libc::sigset_t = std::mem::zeroed();
567 libc::pthread_sigmask(libc::SIG_BLOCK, &pipe, &mut old);
568 let n = libc::write(fd.as_raw_fd(), data.as_ptr().cast(), data.len());
569 let result = if n < 0 {
570 Err(std::io::Error::last_os_error())
571 } else {
572 Ok(n as usize)
573 };
574 if libc::sigismember(&old, libc::SIGPIPE) == 0 {
575 let zero = libc::timespec {
576 tv_sec: 0,
577 tv_nsec: 0,
578 };
579 while libc::sigtimedwait(&pipe, std::ptr::null_mut(), &zero) == libc::SIGPIPE {}
580 libc::pthread_sigmask(libc::SIG_SETMASK, &old, std::ptr::null_mut());
581 }
582 result
583 }
584}
585
586/// The child's status, if it ended (`flags` decides whether it is reaped).
587fn waitid(pidfd: &OwnedFd, flags: libc::c_int) -> Option<Exit> {
588 // SAFETY: a zeroed siginfo is a valid out-parameter; `pidfd` is open.
589 unsafe {
590 let mut info: libc::siginfo_t = std::mem::zeroed();
591 let id = pidfd.as_raw_fd() as libc::id_t;
592 if libc::waitid(libc::P_PIDFD, id, &mut info, flags) != 0 || info.si_pid() == 0 {
593 return None;
594 }
595 Some(match info.si_code {
596 libc::CLD_EXITED => Exit::Exited(info.si_status()),
597 _ => Exit::Signalled(info.si_status()),
598 })
599 }
600}
601
602fn failure(program: &str, errno: i32) -> Failure {
603 let message = format!("{program}: {}", std::io::Error::from_raw_os_error(errno));
604 match errno {
605 libc::ENOENT | libc::ENOTDIR => Failure::NotFound(message),
606 libc::EACCES | libc::EPERM => Failure::Denied(message),
607 libc::E2BIG | libc::ENAMETOOLONG => Failure::BadArgument(message),
608 _ => Failure::Failed(message),
609 }
610}
611
612/// `posix_spawn` with an empty signal mask, default dispositions and a
613/// process group of the child's own; `stdio` become its 0, 1 and 2.
614/// Everything is built before the call: the child runs no Rust.
615fn posix_spawn(
616 path: &CString,
617 argv: &[CString],
618 envp: &[CString],
619 cwd: Option<&CString>,
620 stdio: [&OwnedFd; 3],
621) -> Result<libc::pid_t, i32> {
622 let argv: Vec<*mut libc::c_char> = argv
623 .iter()
624 .map(|a| a.as_ptr().cast_mut())
625 .chain([std::ptr::null_mut()])
626 .collect();
627 let envp: Vec<*mut libc::c_char> = envp
628 .iter()
629 .map(|a| a.as_ptr().cast_mut())
630 .chain([std::ptr::null_mut()])
631 .collect();
632 // SAFETY: the attributes and file actions are initialised before use
633 // and destroyed after; every pointer outlives the call.
634 unsafe {
635 let mut attr: libc::posix_spawnattr_t = std::mem::zeroed();
636 let mut actions: libc::posix_spawn_file_actions_t = std::mem::zeroed();
637 libc::posix_spawnattr_init(&mut attr);
638 libc::posix_spawn_file_actions_init(&mut actions);
639 let mut empty: libc::sigset_t = std::mem::zeroed();
640 libc::sigemptyset(&mut empty);
641 let mut all: libc::sigset_t = std::mem::zeroed();
642 libc::sigfillset(&mut all);
643 libc::posix_spawnattr_setsigmask(&mut attr, &empty);
644 libc::posix_spawnattr_setsigdefault(&mut attr, &all);
645 libc::posix_spawnattr_setpgroup(&mut attr, 0);
646 let flags = libc::POSIX_SPAWN_SETSIGMASK
647 | libc::POSIX_SPAWN_SETSIGDEF
648 | libc::POSIX_SPAWN_SETPGROUP;
649 libc::posix_spawnattr_setflags(&mut attr, flags as libc::c_short);
650 for (fd, target) in stdio.iter().zip(0..) {
651 libc::posix_spawn_file_actions_adddup2(&mut actions, fd.as_raw_fd(), target);
652 }
653 if let Some(dir) = cwd {
654 libc::posix_spawn_file_actions_addchdir_np(&mut actions, dir.as_ptr());
655 }
656 let mut pid: libc::pid_t = 0;
657 let err = libc::posix_spawn(
658 &mut pid,
659 path.as_ptr(),
660 &actions,
661 &attr,
662 argv.as_ptr(),
663 envp.as_ptr(),
664 );
665 libc::posix_spawn_file_actions_destroy(&mut actions);
666 libc::posix_spawnattr_destroy(&mut attr);
667 if err == 0 { Ok(pid) } else { Err(err) }
668 }
669}
670
671/// A pipe, both ends close-on-exec: (read end, write end).
672fn pipe() -> Result<(OwnedFd, OwnedFd), Failure> {
673 let mut fds = [0; 2];
674 // SAFETY: `fds` holds two descriptors; on success both are ours.
675 unsafe {
676 if libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) != 0 {
677 return Err(Failure::Failed(format!(
678 "pipe: {}",
679 std::io::Error::last_os_error()
680 )));
681 }
682 Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])))
683 }
684}
685
686fn pidfd_open(pid: libc::pid_t) -> std::io::Result<OwnedFd> {
687 // SAFETY: a plain syscall; on success the descriptor is ours.
688 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
689 if fd < 0 {
690 Err(std::io::Error::last_os_error())
691 } else {
692 // SAFETY: a fresh descriptor.
693 Ok(unsafe { OwnedFd::from_raw_fd(fd as RawFd) })
694 }
695}
696
697fn timerfd() -> std::io::Result<OwnedFd> {
698 // SAFETY: a plain call; on success the descriptor is ours.
699 let fd = unsafe {
700 libc::timerfd_create(
701 libc::CLOCK_MONOTONIC,
702 libc::TFD_NONBLOCK | libc::TFD_CLOEXEC,
703 )
704 };
705 if fd < 0 {
706 Err(std::io::Error::last_os_error())
707 } else {
708 // SAFETY: a fresh descriptor.
709 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
710 }
711}
712
713fn nonblocking(fd: &OwnedFd) -> std::io::Result<()> {
714 // SAFETY: plain fcntl calls on an open descriptor.
715 unsafe {
716 let flags = libc::fcntl(fd.as_raw_fd(), libc::F_GETFL);
717 if flags < 0 || libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
718 return Err(std::io::Error::last_os_error());
719 }
720 }
721 Ok(())
722}
723
724/// A fresh `0700` directory under the temporary directory, holding
725/// `inputs` (never through a link, never over an existing file).
726fn scratch(
727 inputs: &[(String, Vec<u8>)],
728 outputs: Vec<String>,
729 max_file: usize,
730) -> Result<Scratch, Failure> {
731 let fail = |what: &str, e: std::io::Error| Failure::Failed(format!("scratch {what}: {e}"));
732 let dir = loop {
733 let dir = std::env::temp_dir().join(format!("louise-command-{:016x}", random()));
734 match DirBuilder::new().mode(0o700).create(&dir) {
735 Ok(()) => break dir,
736 Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
737 Err(e) => return Err(fail("directory", e)),
738 }
739 };
740 let s = Scratch {
741 dir,
742 outputs,
743 max_file,
744 };
745 for (name, data) in inputs {
746 OpenOptions::new()
747 .write(true)
748 .create_new(true)
749 .mode(0o600)
750 .custom_flags(libc::O_NOFOLLOW)
751 .open(s.dir.join(name))
752 .and_then(|mut f| f.write_all(data))
753 .map_err(|e| fail(name, e))?;
754 }
755 Ok(s)
756}
757
758/// The outputs the program left: regular files only (never through a
759/// link, never a FIFO that would block), at most `max_file` bytes each.
760fn collect(s: &Scratch) -> Vec<Collected> {
761 s.outputs
762 .iter()
763 .map(|name| {
764 let file = OpenOptions::new()
765 .read(true)
766 .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
767 .open(s.dir.join(name));
768 let Ok(file) = file else {
769 return Collected::Absent(name.clone());
770 };
771 match file.metadata() {
772 Ok(m) if m.is_file() && m.len() > s.max_file as u64 => {
773 Collected::TooLarge(name.clone(), m.len())
774 }
775 Ok(m) if m.is_file() => {
776 let mut data = Vec::new();
777 match file.take(s.max_file as u64 + 1).read_to_end(&mut data) {
778 Ok(n) if n > s.max_file => Collected::TooLarge(name.clone(), n as u64),
779 Ok(_) => Collected::Found(name.clone(), data),
780 Err(_) => Collected::Absent(name.clone()),
781 }
782 }
783 _ => Collected::Absent(name.clone()),
784 }
785 })
786 .collect()
787}
788
789fn random() -> u64 {
790 let mut n = [0u8; 8];
791 // SAFETY: `n` is valid for 8 bytes; a short read leaves zeros, and the
792 // creation loop retries a name that exists.
793 unsafe { libc::getrandom(n.as_mut_ptr().cast(), n.len(), 0) };
794 u64::from_ne_bytes(n) ^ u64::from(std::process::id())
795}
796
797/// The process groups of the children still running.
798static RUNNING: Mutex<Vec<libc::pid_t>> = Mutex::new(Vec::new());
799
800fn track(pid: libc::pid_t) {
801 static AT_EXIT: std::sync::Once = std::sync::Once::new();
802 // SAFETY: `kill_all` is a valid `extern "C"` function for the program's
803 // whole life.
804 AT_EXIT.call_once(|| unsafe {
805 libc::atexit(kill_all);
806 });
807 RUNNING
808 .lock()
809 .unwrap_or_else(std::sync::PoisonError::into_inner)
810 .push(pid);
811}
812
813fn untrack(pid: libc::pid_t) {
814 let mut running = RUNNING
815 .lock()
816 .unwrap_or_else(std::sync::PoisonError::into_inner);
817 running.retain(|p| *p != pid);
818}
819
820/// Kill every group still running: the program is exiting, and what it
821/// started must not outlive it.
822pub extern "C" fn kill_all() {
823 let running = RUNNING
824 .lock()
825 .unwrap_or_else(std::sync::PoisonError::into_inner);
826 for pid in running.iter() {
827 // SAFETY: an unreaped child's id names its group.
828 unsafe { libc::killpg(*pid, libc::SIGKILL) };
829 }
830}
831
832/// The reaper thread's queue: children killed but not dead yet, reaped
833/// with a blocking `waitid` away from any actor's thread.
834fn reaper() -> &'static Mutex<Sender<OwnedFd>> {
835 static REAPER: OnceLock<Mutex<Sender<OwnedFd>>> = OnceLock::new();
836 REAPER.get_or_init(|| {
837 let (tx, rx) = channel::<OwnedFd>();
838 std::thread::Builder::new()
839 .name("louise-reaper".into())
840 .spawn(move || {
841 for pidfd in rx {
842 while waitid(&pidfd, libc::WEXITED).is_none()
843 && std::io::Error::last_os_error().kind() == ErrorKind::Interrupted
844 {
845 }
846 }
847 })
848 .expect("louise: cannot start the reaper thread");
849 Mutex::new(tx)
850 })
851}
852
853#[cfg(test)]
854mod tests {
855 use super::*;
856
857 fn spec(program: &str, args: &[&str]) -> Spec {
858 Spec {
859 program: program.into(),
860 args: args.iter().map(|a| (*a).into()).collect(),
861 env: vec![],
862 dir: Dir::Inherit,
863 stdin: vec![],
864 max_stdout: 1 << 20,
865 max_stderr: 1 << 16,
866 timeout: Duration::from_secs(10),
867 grace: Duration::from_millis(500),
868 }
869 }
870
871 /// Run to the end with `poll(2)`, as the interpreter does.
872 fn run(s: Spec) -> Result<Outcome, Failure> {
873 let mut child = spawn(s)?;
874 loop {
875 if let Step::Done(o) = child.step() {
876 return Ok(o);
877 }
878 let mut fds: Vec<libc::pollfd> = child
879 .fds()
880 .into_iter()
881 .map(|(fd, i)| libc::pollfd {
882 fd,
883 events: if i == Interest::Read {
884 libc::POLLIN
885 } else {
886 libc::POLLOUT
887 },
888 revents: 0,
889 })
890 .collect();
891 // SAFETY: `fds` is valid for its length.
892 unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, -1) };
893 }
894 }
895
896 #[test]
897 fn plain_names() {
898 assert!(plain_name("page.html"));
899 for bad in ["", ".", "..", "a/b", "../x", "/etc/passwd", "a\0b"] {
900 assert!(!plain_name(bad), "{bad:?}");
901 }
902 }
903
904 #[test]
905 fn resolve_uses_only_the_given_path() {
906 assert_eq!(resolve("/bin/sh", None), Some(PathBuf::from("/bin/sh")));
907 assert_eq!(resolve("sh", None), None);
908 assert_eq!(resolve("sh", Some("relative:bin")), None);
909 assert!(resolve("sh", Some("/nowhere:/usr/bin:/bin")).is_some());
910 }
911
912 #[test]
913 fn validate_refuses_nul_bad_names_and_paths() {
914 let mut s = spec("/bin/echo", &["a\0b"]);
915 assert!(matches!(validate(&s), Err(Failure::BadArgument(_))));
916 s = spec("/bin/echo", &[]);
917 s.env = vec![("A=B".into(), "c".into())];
918 assert!(matches!(validate(&s), Err(Failure::BadArgument(_))));
919 s = spec("/bin/echo", &[]);
920 s.dir = Dir::Scratch {
921 inputs: vec![],
922 outputs: vec!["../x".into()],
923 max_file: 1,
924 };
925 assert!(matches!(validate(&s), Err(Failure::BadArgument(_))));
926 }
927
928 #[test]
929 fn arguments_reach_the_program_unchanged() {
930 let o = run(spec(
931 "/usr/bin/printf",
932 &["%s|", "a b", "$HOME", "x;y", "'q'"],
933 ))
934 .unwrap();
935 assert_eq!(o.exit, Exit::Exited(0));
936 assert_eq!(o.stdout, b"a b|$HOME|x;y|'q'|");
937 }
938
939 #[test]
940 fn the_environment_is_exactly_the_one_given() {
941 let mut s = spec("/usr/bin/env", &[]);
942 s.env = vec![("ONLY".into(), "this".into())];
943 assert_eq!(run(s).unwrap().stdout, b"ONLY=this\n");
944 }
945
946 #[test]
947 fn a_timeout_terminates_with_sigterm() {
948 let mut s = spec("/bin/sleep", &["10"]);
949 s.timeout = Duration::from_millis(100);
950 let started = Instant::now();
951 let o = run(s).unwrap();
952 assert_eq!(o.exit, Exit::TimedOut(libc::SIGTERM));
953 assert!(started.elapsed() < Duration::from_millis(450));
954 }
955
956 #[test]
957 fn a_program_that_ignores_sigterm_is_killed_after_the_grace() {
958 let mut s = spec("/bin/sh", &["-c", "trap '' TERM; sleep 10"]);
959 s.timeout = Duration::from_millis(100);
960 s.grace = Duration::from_millis(200);
961 assert_eq!(run(s).unwrap().exit, Exit::TimedOut(libc::SIGKILL));
962 }
963
964 #[test]
965 fn output_past_the_cap_is_cut_and_the_program_still_ends() {
966 let mut s = spec("/usr/bin/head", &["-c", "300000", "/dev/zero"]);
967 s.max_stdout = 1000;
968 let o = run(s).unwrap();
969 assert_eq!(
970 (o.exit, o.stdout.len(), o.stdout_cut),
971 (Exit::Exited(0), 1000, true)
972 );
973 }
974
975 #[test]
976 fn stdin_a_program_does_not_read_is_dropped_quietly() {
977 let mut s = spec("/usr/bin/head", &["-c", "1"]);
978 s.stdin = vec![b'x'; 4 << 20];
979 let o = run(s).unwrap();
980 assert_eq!((o.exit, o.stdout), (Exit::Exited(0), b"x".to_vec()));
981 }
982
983 #[test]
984 fn a_background_descendant_does_not_hold_the_run() {
985 let mut s = spec("/bin/sh", &["-c", "sleep 10 & echo hi"]);
986 s.grace = Duration::from_millis(200);
987 let started = Instant::now();
988 let o = run(s).unwrap();
989 assert_eq!(o.stdout, b"hi\n");
990 assert!(started.elapsed() < Duration::from_secs(2));
991 }
992
993 #[test]
994 fn scratch_inputs_go_in_and_outputs_come_back() {
995 let mut s = spec(
996 "/bin/sh",
997 &[
998 "-c",
999 "cat in > out; head -c 50 /dev/zero > big; ln -s /etc/passwd link",
1000 ],
1001 );
1002 s.dir = Dir::Scratch {
1003 inputs: vec![("in".into(), b"hello".to_vec())],
1004 outputs: vec!["out".into(), "big".into(), "missing".into(), "link".into()],
1005 max_file: 10,
1006 };
1007 let o = run(s).unwrap();
1008 assert_eq!(
1009 o.files,
1010 vec![
1011 Collected::Found("out".into(), b"hello".to_vec()),
1012 Collected::TooLarge("big".into(), 50),
1013 Collected::Absent("missing".into()),
1014 Collected::Absent("link".into()),
1015 ]
1016 );
1017 }
1018
1019 #[test]
1020 fn a_missing_program_is_not_found() {
1021 assert!(matches!(
1022 run(spec("/nowhere/at/all", &[])),
1023 Err(Failure::NotFound(_))
1024 ));
1025 assert!(matches!(run(spec("sh", &[])), Err(Failure::NotFound(_))));
1026 }
1027
1028 #[test]
1029 fn dropping_a_running_child_kills_and_reaps_it() {
1030 let child = spawn(spec("/bin/sleep", &["10"])).unwrap();
1031 let pid = child.pid;
1032 drop(child);
1033 std::thread::sleep(Duration::from_millis(100));
1034 assert!(!Path::new(&format!("/proc/{pid}")).exists());
1035 }
1036}