File-backed stdio avoids pipe deadlocks. Poll both deadline and output size; never execute a shell or accept arguments embedded in a manifest.
(checker: &Path, input: &[u8], timeout: Duration)
| 365 | /// File-backed stdio avoids pipe deadlocks. Poll both deadline and output size; |
| 366 | /// never execute a shell or accept arguments embedded in a manifest. |
| 367 | pub fn invoke_checker(checker: &Path, input: &[u8], timeout: Duration) -> Result<Vec<u8>, String> { |
| 368 | if input.len() as u64 > MANIFEST_LIMIT { |
| 369 | return Err("checker_input_limit_exceeded".into()); |
| 370 | } |
| 371 | let run = || -> std::io::Result<Vec<u8>> { |
| 372 | let mut stdin = tempfile::tempfile()?; |
| 373 | stdin.write_all(input)?; |
| 374 | stdin.seek(SeekFrom::Start(0))?; |
| 375 | let mut stdout = tempfile::tempfile()?; |
| 376 | let stderr = tempfile::tempfile()?; |
| 377 | let mut child = Command::new(checker) |
| 378 | .stdin(Stdio::from(stdin)) |
| 379 | .stdout(Stdio::from(stdout.try_clone()?)) |
| 380 | .stderr(Stdio::from(stderr.try_clone()?)) |
| 381 | .spawn()?; |
| 382 | let start = Instant::now(); |
| 383 | loop { |
| 384 | if start.elapsed() >= timeout |
| 385 | || stdout.metadata()?.len() > MANIFEST_LIMIT |
| 386 | || stderr.metadata()?.len() > MANIFEST_LIMIT |
| 387 | { |
| 388 | let _ = child.kill(); |
| 389 | let _ = child.wait(); |
| 390 | return Err(std::io::Error::other( |
| 391 | "checker timeout or output limit exceeded", |
| 392 | )); |
| 393 | } |
| 394 | if let Some(status) = child.try_wait()? { |
| 395 | if !status.success() { |
| 396 | return Err(std::io::Error::other("checker exited unsuccessfully")); |
| 397 | } |
| 398 | break; |
| 399 | } |
| 400 | std::thread::sleep(Duration::from_millis(10)); |
| 401 | } |
| 402 | stdout.seek(SeekFrom::Start(0))?; |
| 403 | let mut output = Vec::new(); |
| 404 | stdout.take(MANIFEST_LIMIT + 1).read_to_end(&mut output)?; |
| 405 | if output.len() as u64 > MANIFEST_LIMIT { |
| 406 | return Err(std::io::Error::other("checker output limit exceeded")); |
| 407 | } |
| 408 | Ok(output) |
| 409 | }; |
| 410 | run().map_err(|error| format!("checker_unavailable: {error}")) |
| 411 | } |
| 412 | |
| 413 | #[cfg(test)] |
| 414 | mod tests { |