Skip to content
pi-c Documentation
Login

Documentation

/* Bounded command runner shared by the S0 shell drivers.
 *
 *   run-bounded SECONDS -- COMMAND [ARG...]
 *
 * Runs COMMAND in its own process group and enforces a wall-clock limit. The
 * owned group is SIGKILLed on timeout, on SIGINT/SIGTERM/SIGHUP, and after a
 * normal exit. See the explicit limits below. The wait is a blocking
 * waitpid interrupted by SIGALRM: no polling interval is added to the child's
 * runtime.
 *
 * Exit codes: the child's own status on success, 124 on timeout, 125 on spawn
 * failure, 126 on usage error, 128+signal when interrupted.
 *
 * Limits, stated plainly: this is a local process supervisor. It is not the
 * independent host-side cleanup facility that remote qualification requires,
 * and it cannot promise reaping after it is itself SIGKILLed or the host
 * reboots. On SIGINT/SIGTERM/SIGHUP it kills the child group before exiting,
 * but a descendant that has already left the group (e.g. via setsid) is out of
 * its scope. Callers that need recovery across a supervisor kill must give the
 * child its own deadline.
 */
#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#define MAX_SECONDS 610L

/* Test-only seam: widens the fork -> registration window so a regression test
 * can deliver a termination signal deterministically inside it. The seam
 * writes a marker first, so the test signals only once the helper is provably
 * inside the window. */
#ifndef RUN_BOUNDED_TEST_FORK_DELAY_MS
#define RUN_BOUNDED_TEST_FORK_DELAY_MS 0
#endif
#ifndef RUN_BOUNDED_TEST_WINDOW_MARKER
#define RUN_BOUNDED_TEST_WINDOW_MARKER ""
#endif

static volatile sig_atomic_t active_child = 0;
static volatile sig_atomic_t deadline_fired = 0;
static sigset_t block_mask;
static sigset_t old_mask;

static void handle_deadline(int sig) {
  (void)sig;
  deadline_fired = 1;
}

static void handle_terminate(int sig) {
  pid_t child = (pid_t)active_child;
  if (child > 0) {
    (void)kill(-child, SIGKILL);
  }
  _exit(128 + sig);
}

static int install_handlers(void) {
  static const int terminating[] = {SIGINT, SIGTERM, SIGHUP};
  struct sigaction action;
  size_t index;

  memset(&action, 0, sizeof(action));
  action.sa_handler = handle_terminate;
  sigemptyset(&action.sa_mask);
  action.sa_flags = SA_RESTART;
  for (index = 0; index < sizeof(terminating) / sizeof(terminating[0]);
       index++) {
    if (sigaction(terminating[index], &action, NULL) != 0) {
      return 0;
    }
  }
  /* No SA_RESTART: the alarm must interrupt the blocking waitpid. */
  memset(&action, 0, sizeof(action));
  action.sa_handler = handle_deadline;
  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  if (sigaction(SIGALRM, &action, NULL) != 0) {
    return 0;
  }
  /* Held across fork and child registration so a signal in that window is
   * delivered only after active_child is set; otherwise the child is orphaned
   * with no one left to kill its group. */
  sigemptyset(&block_mask);
  sigaddset(&block_mask, SIGINT);
  sigaddset(&block_mask, SIGTERM);
  sigaddset(&block_mask, SIGHUP);
  sigaddset(&block_mask, SIGALRM);
  return 1;
}

static int parse_seconds(const char *text, long *out) {
  char *end = NULL;
  long value;
  if (!text || *text < '0' || *text > '9') {
    return 0;
  }
  errno = 0;
  value = strtol(text, &end, 10);
  if (errno != 0 || !end || *end != '\0' || value < 1 ||
      value > MAX_SECONDS) {
    return 0;
  }
  *out = value;
  return 1;
}

int main(int argc, char **argv) {
  struct itimerval deadline;
  long seconds = 0;
  pid_t pid;
  int status = 0;

  if (argc < 4 || strcmp(argv[2], "--") != 0 || !parse_seconds(argv[1], &seconds)) {
    fprintf(stderr,
            "usage: %s SECONDS -- COMMAND [ARG...]  (SECONDS 1..%ld)\n",
            argv[0], MAX_SECONDS);
    return 126;
  }
  if (!install_handlers()) {
    fprintf(stderr, "run-bounded: cannot install signal handlers\n");
    return 125;
  }

  if (sigprocmask(SIG_BLOCK, &block_mask, &old_mask) != 0) {
    fprintf(stderr, "run-bounded: cannot block signals for fork\n");
    return 125;
  }
  pid = fork();
  if (pid < 0) {
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    fprintf(stderr, "run-bounded: fork failed\n");
    return 125;
  }
  if (pid == 0) {
    /* Own process group: descendants are reaped with the leader. The child
     * restores the parent's original mask before exec. */
    if (setpgid(0, 0) != 0) {
      _exit(125);
    }
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    execvp(argv[3], &argv[3]);
    _exit(127);
  }
  if (setpgid(pid, pid) != 0 && errno != EACCES && errno != ESRCH) {
    (void)kill(pid, SIGKILL);
    (void)waitpid(pid, &status, 0);
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    fprintf(stderr, "run-bounded: cannot isolate the child's process group\n");
    return 125;
  }
#if RUN_BOUNDED_TEST_FORK_DELAY_MS > 0
  {
    /* Parent only, after the child group exists and before registration. */
    /* tv_nsec must stay below one second even for multi-second test windows. */
    struct timespec widen = {RUN_BOUNDED_TEST_FORK_DELAY_MS / 1000,
                            (RUN_BOUNDED_TEST_FORK_DELAY_MS % 1000) * 1000000L};
    if (RUN_BOUNDED_TEST_WINDOW_MARKER[0] != '\0') {
      FILE *marker = fopen(RUN_BOUNDED_TEST_WINDOW_MARKER, "w");
      if (marker != NULL) {
        fputs("in-window\n", marker);
        fclose(marker);
      }
    }
    (void)nanosleep(&widen, NULL);
  }
#endif
  active_child = (sig_atomic_t)pid;

  memset(&deadline, 0, sizeof(deadline));
  deadline.it_value.tv_sec = (time_t)seconds;
  if (setitimer(ITIMER_REAL, &deadline, NULL) != 0) {
    (void)kill(-pid, SIGKILL);
    (void)waitpid(pid, &status, 0);
    active_child = 0;
    (void)sigprocmask(SIG_SETMASK, &old_mask, NULL);
    fprintf(stderr, "run-bounded: cannot arm the deadline\n");
    return 125;
  }
  /* Registration is complete; release any signal that arrived meanwhile. */
  if (sigprocmask(SIG_SETMASK, &old_mask, NULL) != 0) {
    (void)kill(-pid, SIGKILL);
    (void)waitpid(pid, &status, 0);
    active_child = 0;
    fprintf(stderr, "run-bounded: cannot restore the signal mask\n");
    return 125;
  }

  for (;;) {
    pid_t waited = waitpid(pid, &status, 0);
    if (waited == pid) {
      break;
    }
    if (waited < 0 && errno == EINTR) {
      if (deadline_fired) {
        (void)kill(-pid, SIGKILL);
        while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
          /* reap the leader before returning */
        }
        active_child = 0;
        (void)kill(-pid, SIGKILL);
        fprintf(stderr, "run-bounded: deadline %lds exceeded\n", seconds);
        return 124;
      }
      continue;
    }
    if (waited < 0) {
      break;
    }
  }

  {
    struct itimerval cancel;
    memset(&cancel, 0, sizeof(cancel));
    (void)setitimer(ITIMER_REAL, &cancel, NULL);
  }
  active_child = 0;
  (void)kill(-pid, SIGKILL); /* descendants must not outlive the leader */

  if (WIFEXITED(status)) {
    return WEXITSTATUS(status);
  }
  if (WIFSIGNALED(status)) {
    return 128 + WTERMSIG(status);
  }
  return 125;
}