diff --git a/pkgs/id/src/directory_mail.rs b/pkgs/id/src/directory_mail.rs index 9eb8ade993..708c03ed35 100644 --- a/pkgs/id/src/directory_mail.rs +++ b/pkgs/id/src/directory_mail.rs @@ -11,7 +11,8 @@ use std::io::{BufRead, BufReader, Write as _}; use std::net::{SocketAddr, TcpStream}; use std::path::PathBuf; use std::process::{Command, Stdio}; -use std::time::Duration; +use std::thread; +use std::time::{Duration, Instant}; use anyhow::{Context as _, Result, bail, ensure}; use rand::RngExt as _; @@ -36,7 +37,7 @@ pub trait MailSink: Debug + Send + Sync { /// # Errors /// /// Fails if the message could not be written or the program did not - /// finish successfully. + /// finish successfully before its deadline. fn send(&self, mail: &Mail) -> Result<()>; } @@ -76,6 +77,24 @@ impl MailSink for OutboxSink { } } +/// Terminate a timed-out mail command. On Unix the child was spawned as a +/// process-group leader, so SIGKILL the whole group to take any wrapper +/// script's descendants with it; fall back to killing just the child when +/// the group signal fails (e.g. the group is already gone). +fn kill_child_tree(child: &mut std::process::Child) -> std::io::Result<()> { + #[cfg(unix)] + { + #[allow(clippy::cast_possible_wrap)] + let pgid = child.id() as libc::pid_t; + // SAFETY: killpg only delivers a signal; the pgid is our own child's + // pid, and no memory is accessed. + if unsafe { libc::killpg(pgid, libc::SIGKILL) } == 0 { + return Ok(()); + } + } + child.kill() +} + /// Runs a program once per message, with the message in environment /// variables. No shell is involved, so an address cannot inject a command. #[derive(Clone, Debug)] @@ -90,21 +109,61 @@ impl CommandSink { pub const fn new(program: PathBuf, args: Vec) -> Self { Self { program, args } } -} -impl MailSink for CommandSink { - fn send(&self, mail: &Mail) -> Result<()> { - let mut child = Command::new(&self.program) + fn send_with_timeout(&self, mail: &Mail, timeout: Duration) -> Result<()> { + let mut command = Command::new(&self.program); + command .args(&self.args) .env("ID_MAIL_TO", &mail.to) .env("ID_MAIL_SUBJECT", &mail.subject) .env("ID_MAIL_BODY", &mail.body) .stdin(Stdio::null()) .stdout(Stdio::null()) - .stderr(Stdio::null()) + .stderr(Stdio::null()); + // The child leads its own process group so a timeout can terminate + // the whole tree: a wrapper script's descendants (e.g. a stalled + // curl in the shipped cloudflare-mail.sh) must not outlive the + // failure this function reports. + #[cfg(unix)] + { + use std::os::unix::process::CommandExt as _; + command.process_group(0); + } + let mut child = command .spawn() .with_context(|| format!("run {}", self.program.display()))?; - let status = child.wait().context("wait for mail program")?; + let started = Instant::now(); + let status = loop { + // An observed exit always wins: a command that finished before + // the deadline is a success even if the finish is only seen on + // the first poll after the deadline has passed. + if let Some(status) = child.try_wait().context("wait for mail program")? { + break status; + } + + if started.elapsed() >= timeout { + if let Err(kill_error) = kill_child_tree(&mut child) { + let reaper = thread::Builder::new() + .name("id-mail-reaper".to_owned()) + .spawn(move || { + let _ = child.wait(); + }); + if let Err(reaper_error) = reaper { + bail!( + "mail program timed out after {timeout:?}; failed to kill child: {kill_error}; failed to start reaper: {reaper_error}" + ); + } + bail!( + "mail program timed out after {timeout:?}; failed to kill child: {kill_error}; reaping in background" + ); + } + child.wait().context("reap timed-out mail program")?; + bail!("mail program timed out after {timeout:?}"); + } + + let remaining = timeout.saturating_sub(started.elapsed()); + thread::sleep(Duration::from_millis(10).min(remaining)); + }; if !status.success() { bail!("mail program exited with {status}"); } @@ -112,6 +171,16 @@ impl MailSink for CommandSink { } } +// Keep the configurable program on the same 10-second failure budget as the +// loopback SMTP sink; its child must not pin a directory request indefinitely. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(10); + +impl MailSink for CommandSink { + fn send(&self, mail: &Mail) -> Result<()> { + self.send_with_timeout(mail, COMMAND_TIMEOUT) + } +} + const RELAY_TIMEOUT: Duration = Duration::from_secs(10); /// Hands mail to an SMTP relay on this machine, with plain SMTP and no login. @@ -321,11 +390,99 @@ mod tests { assert!(sink.send(&sample()).is_err()); } + #[test] + fn a_command_that_exceeds_its_deadline_is_killed_and_reaped() { + let sink = CommandSink::new( + PathBuf::from("/bin/sh"), + vec!["-c".to_owned(), "exec sleep 30".to_owned()], + ); + let started = Instant::now(); + let error = sink + .send_with_timeout(&sample(), Duration::from_millis(50)) + .unwrap_err(); + assert!(error.to_string().contains("mail program timed out")); + assert!( + started.elapsed() < Duration::from_secs(5), + "timed-out command took {:?}", + started.elapsed() + ); + } + + #[cfg(unix)] + #[test] + fn a_timed_out_wrapper_script_takes_its_descendants_with_it() { + // The shipped mail program is a wrapper script (cloudflare-mail.sh) + // that waits on descendants such as curl. Killing only the wrapper + // on timeout would leave them running after the failure is reported, + // so the sink spawns the command as a process-group leader and + // SIGKILLs the whole group. + let dir = scratch("wrapper"); + let pid_file = dir.join("child.pid"); + let script = format!("sleep 30 & echo $! > {}; wait", pid_file.display()); + let sink = CommandSink::new(PathBuf::from("/bin/sh"), vec!["-c".to_owned(), script]); + let started = Instant::now(); + let error = sink + .send_with_timeout(&sample(), Duration::from_millis(500)) + .unwrap_err(); + assert!(error.to_string().contains("mail program timed out")); + assert!( + started.elapsed() < Duration::from_secs(5), + "timed-out wrapper took {:?}", + started.elapsed() + ); + let child_pid: i32 = std::fs::read_to_string(&pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + // The descendant may take a moment to be reaped after SIGKILL. + let running = |pid: i32| { + // SAFETY: signal 0 only probes for the process's existence. + if unsafe { libc::kill(pid, 0) } != 0 { + return false; + } + // A zombie is terminated, not running — but it still answers + // signal 0, and in a container whose PID 1 does not reap + // orphans it would look alive forever. Linux exposes the + // state in /proc; other hosts' init reaps orphans promptly. + #[cfg(target_os = "linux")] + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) + && let Some(state) = stat + .rsplit(')') + .next() + .and_then(|rest| rest.trim_start().chars().next()) + && state == 'Z' + { + return false; + } + true + }; + let deadline = Instant::now() + Duration::from_secs(2); + while running(child_pid) { + assert!( + Instant::now() < deadline, + "descendant {child_pid} survived the wrapper's timeout kill" + ); + thread::sleep(Duration::from_millis(20)); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_slow_finite_command_completes_before_its_deadline() { + let sink = CommandSink::new( + PathBuf::from("/bin/sh"), + vec!["-c".to_owned(), "exec sleep 0.05".to_owned()], + ); + sink.send_with_timeout(&sample(), Duration::from_secs(2)) + .unwrap(); + } + /// A relay that records every line it is sent, refusing the recipient if asked. fn fake_relay(refuse_recipient: bool) -> (SocketAddr, JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); - let handle = std::thread::spawn(move || { + let handle = thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut writer = stream;