package runner import ( "context" "errors" "fmt" "io" "os" "os/exec" "strings" "syscall" "time" "unicode/utf8" ) // Limits on the submitted program, per test. The container adds its own // (memory, CPUs, pids) on top; these are what make one test fail on its own // instead of taking the service down with it. const ( // memoryKB is RLIMIT_AS, the usual judge limit. It is address space, not // resident memory, so it also covers a vector that is reserved and never // touched. python3 starts in about 30 MB of it. memoryKB = 512 << 10 // fileBlocks is RLIMIT_FSIZE in the shell's 512-byte blocks (64 MB). It // stops a runaway program filling the tmpfs; stdout and stderr go to // files, so it caps them too. fileBlocks = 64 << 20 / 512 // compileMemoryKB is the build's address space. cc1plus needs around // 300 MB for at -O2; this leaves room for heavier // templates while still stopping a template bomb before the container's // OOM killer picks a victim. compileMemoryKB = 1 << 20 compileTimeout = 30 * time.Second lintTimeout = 20 * time.Second // requestBudget bounds a whole request, waiting for a slot included, // so the site's client (90s) always gets the service's answer. requestBudget = 60 * time.Second // compareCap is how much output is read back for comparing. A request // is at most 2 MB, so no expected output is longer: anything past this // is a wrong answer whatever it holds. compareCap = 4 << 20 ) // limits are the rlimits one process runs under; zero leaves one unset. type limits struct { cpuSec int memoryKB int fileBlocks int } // testLimits are a test's: the CPU limit rounded up to whole seconds (the // rlimit's unit) plus one, so the kernel only steps in for a program well // past the limit. The verdict itself compares the measured CPU time with // the exact limit. func testLimits(timeLimit time.Duration) limits { sec := int((timeLimit + time.Second - 1) / time.Second) return limits{cpuSec: sec + 1, memoryKB: memoryKB, fileBlocks: fileBlocks} } // wallLimit is the clock time a test may take. It is well above the CPU // limit, because a loaded machine stretches wall time; it is what catches // a program that sleeps instead of computing. func wallLimit(timeLimit time.Duration) time.Duration { return 2*timeLimit + time.Second } // script sets the rlimits and execs the program. The limits are set by a // shell rather than from Go because Go cannot set them on a child between // fork and exec without cgo, and setting them on the running child (prlimit // after Start) races with the program's first instructions. exec keeps the // shell out of the picture: the program is the process Go waits for, so // its exit status and rusage are the program's own. // // RLIMIT_NPROC is not set: it counts every process of the uid, which here // includes this server's own threads and every other run in flight, so any // value tight enough to stop a fork bomb would also fail unrelated runs. // The container's pids_limit bounds that instead: the process-group kill // below ends a fork bomb, and the image's init (tini) reaps what it leaves, // which this server, as PID 1, would not. The stack limit is raised to the memory // limit, as judges do for deep recursion; it is the one limit allowed to // fail, since some hosts cap the hard stack limit lower. func (l limits) script() string { var b strings.Builder // dash, bash-as-sh and busybox ash all take one resource per ulimit. var set []string if l.cpuSec > 0 { set = append(set, fmt.Sprintf("ulimit -t %d", l.cpuSec)) } if l.memoryKB > 0 { set = append(set, fmt.Sprintf("ulimit -v %d", l.memoryKB)) } if l.fileBlocks > 0 { set = append(set, fmt.Sprintf("ulimit -f %d", l.fileBlocks)) } if len(set) > 0 { b.WriteString(strings.Join(set, " && ")) b.WriteString(" || exit 126; ") } if l.memoryKB > 0 { fmt.Fprintf(&b, "ulimit -s %d 2>/dev/null; ", l.memoryKB) } b.WriteString(`exec "$@"`) return b.String() } // proc is one process to run. type proc struct { dir string args []string // stdin is a file to read from; empty means /dev/null. stdin string // stdout and stderr are files to write to; they may be the same. stdout, stderr string limits limits wall time.Duration } // outcome is how a proc ended. type outcome struct { state *os.ProcessState // nil when it never started err error // why it never started wall time.Duration cpu time.Duration // timedOut is set when the proc's own wall limit killed it; stopped // when the caller's context did (the request's budget, or the client // going away). timedOut, stopped bool } func (o outcome) signal() (syscall.Signal, bool) { if o.state == nil { return 0, false } ws, ok := o.state.Sys().(syscall.WaitStatus) if !ok || !ws.Signaled() { return 0, false } return ws.Signal(), true } // exitCode is the exit status, or 128+signal as a shell reports a killed // program, or -1 when it never ran. func (o outcome) exitCode() int { if sig, ok := o.signal(); ok { return 128 + int(sig) } if o.state == nil { return -1 } return o.state.ExitCode() } // run runs p to completion, or until its wall limit or ctx ends it. The // process gets its own process group, and the whole group is killed both // on timeout and after it exits, so nothing it started outlives the test. func (p proc) run(ctx context.Context) outcome { tctx, cancel := context.WithTimeout(ctx, p.wall) defer cancel() args := p.args if p.limits != (limits{}) { args = append([]string{"sh", "-c", p.limits.script(), "sh"}, args...) } cmd := exec.CommandContext(tctx, args[0], args[1:]...) cmd.Dir = p.dir cmd.Env = childEnv(p.dir) cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } files, err := p.open(cmd) defer func() { for _, f := range files { f.Close() } }() if err != nil { return outcome{err: err} } start := time.Now() err = cmd.Start() if err != nil { return outcome{err: err} } cmd.Wait() // the status is read from ProcessState below o := outcome{state: cmd.ProcessState, wall: time.Since(start)} // The group outlives its leader only if the program left children // behind; the pgid cannot be reused while they exist. syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) o.cpu = o.state.UserTime() + o.state.SystemTime() if ctx.Err() != nil { o.stopped = true } else if errors.Is(tctx.Err(), context.DeadlineExceeded) { o.timedOut = true } return o } // open attaches p's files to cmd. Files rather than pipes: the program's // output then counts against RLIMIT_FSIZE, and Wait never waits on a pipe // held open by something the program left running. func (p proc) open(cmd *exec.Cmd) ([]*os.File, error) { var files []*os.File if p.stdin != "" { f, err := os.Open(p.stdin) if err != nil { return files, err } files = append(files, f) cmd.Stdin = f } out, err := os.Create(p.stdout) if err != nil { return files, err } files = append(files, out) cmd.Stdout = out cmd.Stderr = out if p.stderr != p.stdout { e, err := os.Create(p.stderr) if err != nil { return files, err } files = append(files, e) cmd.Stderr = e } return files, nil } // childEnv is the whole environment a child sees: none of the server's. // LC_ALL=C keeps compiler messages in ASCII quotes, which the lint parsers // expect; python3 still switches itself to UTF-8 under it (PEP 538). func childEnv(dir string) []string { path := os.Getenv("PATH") if path == "" { path = "/usr/local/bin:/usr/bin:/bin" } return []string{ "PATH=" + path, "HOME=" + dir, "TMPDIR=" + os.TempDir(), "LC_ALL=C", "PYTHONDONTWRITEBYTECODE=1", } } // readCapped reads at most limit bytes of the file at path, and whether // there was more. A missing file reads as empty. func readCapped(path string, limit int) (string, bool) { f, err := os.Open(path) if err != nil { return "", false } defer f.Close() data, _ := io.ReadAll(io.LimitReader(f, int64(limit)+1)) if len(data) > limit { return string(data[:limit]), true } return string(data), false } // capText cuts s to at most limit bytes without splitting a UTF-8 // character, so the JSON carries no replacement characters for a cut. func capText(s string, limit int) (string, bool) { if len(s) <= limit { return s, false } s = s[:limit] for i := 0; i < utf8.UTFMax && len(s) > 0; i++ { r, size := utf8.DecodeLastRuneInString(s) if r != utf8.RuneError || size != 1 { break } s = s[:len(s)-1] } return s, true }