import os import shutil import signal import struct import subprocess from contextlib import nullcontext from pathlib import Path from time import monotonic ROOT = Path("/opt/foxdec") DEADLINE = 300 MAX_UPLOAD = 16 * 1024 * 1024 MAX_OUTPUT_FILE = 8 * 1024 * 1024 def read_preview(path, *, tail=False): if not path.is_file(): return "" with path.open("rb") as stream: size = stream.seek(0, os.SEEK_END) stream.seek(max(0, size - 12_000) if tail else 0) preview = stream.read(12_000).decode(errors="replace").strip() if size <= 12_000: return preview return "…\n" + preview if tail else preview + "\n…" class CommandError(RuntimeError): def __init__(self, command, code): super().__init__(f"{Path(command).name} exited with status {code}.") self.code = code def run_command(args, work, log, deadline, *, env=None, stdout=None, limit_output=False): if monotonic() >= deadline: raise TimeoutError("The job reached its time limit.") command = Path(args[0]).name if limit_output: args = ["prlimit", f"--fsize={MAX_OUTPUT_FILE}", "--", *args] with log.open("ab") as diagnostics, (stdout.open("wb") if stdout else nullcontext(diagnostics)) as output: with subprocess.Popen( args, cwd=work, env=env, stdout=output, stderr=diagnostics, stdin=subprocess.DEVNULL, start_new_session=True, ) as process: try: code = process.wait(timeout=max(0, deadline - monotonic())) except subprocess.TimeoutExpired: raise TimeoutError("The job reached its time limit.") from None finally: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass if code: raise CommandError(command, code) def require_outputs(*paths): for path in paths: if not path.is_file() or not path.stat().st_size: raise RuntimeError(f"Expected output was missing or empty: {path.name}.") def stage_upload(source, work, entries): with Path(source).open("rb") as stream: data = stream.read(MAX_UPLOAD + 1) if len(data) > MAX_UPLOAD: raise ValueError("Choose a binary no larger than 16 MiB.") if len(data) < 64 or data[:7] != b"\x7fELF\x02\x01\x01": raise ValueError("Choose a 64-bit little-endian Linux ELF binary.") kind, machine, version, entry = struct.unpack_from("