chiark / gitweb /
prefork-interp: New protocol: C: Do not env-pass saves
[chiark-utils.git] / cprogs / prefork-interp.c
index de63b42bf93445ab70897507a4755e560bb19eb7..11f53d0d1c9eb23c97b7bfea502e90189dac2c91 100644 (file)
@@ -6,6 +6,12 @@
  *   prefork-interp  [<option> ..] <interpreter>  [<script> [<args> ...]]
  *   prefork-interp  [<option>,..],<interpreter>   <script> [<args> ...]
  *   prefork-interp '[<option> ..] <interpreter>'  <script> [<args> ...]
+ *
+ * Options must specify argument laundering mode.
+ * Currently the only mode supported is:
+ *   -U    unlaundered: setup and executor both get all arguments and env vars
+ *         ident covers only env vars specified  with -E
+ *         ident covers only arguments interpreter and (if present) script
  */
 /*
  * Process structure:
  *                               makes new listening socket
  *                               makes first-instance socketpair
  *                            forks setup (script, sock fds indicated in env)
- *                            fd0, fd1, fd2: from-outer-caller
+ *                            fd0, fd1, fd2: from-outer
  *                            other fd: call(client-end)(fake)
  *                            reaps setup (and reports error)
  *                            (implicitly releases lock)
  *
  *     setup (pre-exec)       fd0: null,
- *                            fd[12: fd2-from-outer-caller
+ *                            fd[12]: fd2-from-outer
  *                            env fds: listener, call(server-end)(fake)
- *                            env fds: orig-fd[01]
  *                            close fd: lockfile
+ *                            possibly clean env, argv
  *
  *     setup (script)         runs initialisation parts of the script
  *                            at prefork establishment point:
  *                            forks for server
  *                [2]         exits
  *
#        server (pm) [1]     [fd0: null],
- *                            [fd[12: fd2-from-outer-caller]
- *                            right away, forks one fa-monitor
*        server (pm) [1]     [fd0: null],
+ *                            [fd[12]: fd2-from-outer]
+ *                            right away, forks init monitor
  *                    [2]     closes outer caller fds and call(fake)
  *        [server (pm)]       fd[012]: null
  *                            other fds: listener, syslog
  *                            runs in loop accepting and forking,
- *                            reaping and limiting children (incl fa-monitor)
+ *                            reaping and limiting children (incl init monitor)
  *                            reports failures of monitors to syslog
  *                            
- *         f-a monitor        forks executor
- *                            closes fd: listener
- *                            [fd[12: fd2-from-outer-caller]
- *                            [other fds: call(server-end)(fake), syslog]
- *                            runs as monitor, below
- *
- *
  *  [client (C wrapper)]      if client connect succeeds:
  *                            now fd: call(client-end)
  *                               sends message with: cmdline, env
  *                               sends fds
  *
- *        [server (script)]   accepts, forks monitor
+ *        [server (script)]   accepts, forks subseq monitor
  *
- *          monitor [1]       [fd[012]: null]
- *                            other fds: syslog, call(server-end)
+ *          monitor [1]       [fd0: null]
+ *           (init            [fd[12]: init: fd2-from-outer; subseq: null]
+ *             or             errors: init: fd2; subseq: syslog
+ *            subseq)         other fds: syslog, call(server-end)
  *                            sends ack byte
  *                            receives args, env, fds
  *                            forks executor
  *
  *            executor        sorts out fds:
- *                            fd0, fd1, fd2: from-outer-caller
+ *                            fd0, fd1, fd2: from-outer
  *                            close fds: call(server-end)
  *                            retained fds: syslog
  *
  *                            exits normally
  *
  *          [monitor]         [fd[012]: null]
- *                            [other fds: call(server-end), syslog]
+ *                            [fd[12]: init: fd2-from-outer; subseq: null]
+ *                            [errors: init: fd2; subseq: syslog]
  *                            reaps executor
  *                            reports status via socket
  *
- *    [client (C wrapper)]    [fd0, fd1, fd2: from-outer-caller]
+ *    [client (C wrapper)]    [fd0, fd1, fd2: from-outer]
  *                            [other fd: call(client-end)]
  *                            receives status, exits appropriately
  *                            (if was bad signal, reports to stderr, exits 127)
 
 #include "prefork.h"
 
-struct sockaddr_un sun;
+const char our_name[] = "prefork-interp";
+
+struct sockaddr_un sockaddr_sun;
 
 #define ACK_BYTE '\n'
 
-static struct sockaddr_unix socket_sun;
 static const char *const *executor_argv;
 
+void fusagemessage(FILE *f) {
+  fprintf(f, "usage: #!/usr/bin/prefork-interp [<options>]\n");
+}
+
+static int laundering;
+
+const struct cmdinfo cmdinfos[]= {
+  PREFORK_CMDINFOS
+  { 0, 'U',   0,                    .iassignto= &laundering,    .arg= 'U' },
+  { 0 }
+};
+
+void ident_addinit(void) {
+  char ident_magic[1] = { 0 };
+  sha256_update(&identsc, sizeof(ident_magic), ident_magic);
+}
+
 static void propagate_exit_status(int status, const char *what) {
   int r;
 
@@ -130,11 +150,11 @@ static void propagate_exit_status(int status, const char *what) {
          signame);
     }
 
-    die("setup failed due to signal %d %s%s", sig, signame,
+    die("%s failed due to signal %d %s%s", what, sig, signame,
        WCOREDUMP(status) ? " (core dumped)" : "");
   }
 
-  die("setup failed with weird wait status %d 0x%x", status, status);
+  die("%s failed with weird wait status %d 0x%x", what, status, status);
 }
 
 static __attribute((noreturn)) void die_data_overflow(void) {
@@ -181,7 +201,9 @@ static void prepare_message(size_t *len, char **buf) {
     prepare_string(len, buf, s);
 }
 
-static void send_fd(int via_fd, int payload_fd) {
+static void send_fd(FILE *call_sock, int payload_fd) {
+  int via_fd = fileno(call_sock);
+
   union {
     struct cmsghdr align;
     char buf[CMSG_SPACE(sizeof(payload_fd))];
@@ -222,12 +244,12 @@ static void send_fd(int via_fd, int payload_fd) {
   }
 }
 
-static void send_request(int call_fd) {
+static void send_request(FILE *call_sock) {
   // Sending these first makes it easier for the script to
   // use buffered IO for the message.
-  send_fd(call_fd, 0);
-  send_fd(call_fd, 1);
-  send_fd(call_fd, 2);
+  send_fd(call_sock, 0);
+  send_fd(call_sock, 1);
+  send_fd(call_sock, 2);
 
   size_t len = 4;
   prepare_message(&len, 0);
@@ -238,57 +260,71 @@ static void send_request(int call_fd) {
   prepare_message(0, &p);
   assert(p == m + len);
 
-  p = m;
-  while (len) {
-    ssize_t r = write(call_fd, p, len);
-    if (r==-1) {
-      if (errno == EINTR) continue;
-      diee("write request");
-    }
-    assert(r <= len);
-    assert(r > 0);
-    len -= r;
-    p += r;
+  ssize_t sr = fwrite(p, len, 1, call_sock);
+  if (sr != 1) diee("write request");
+}
+
+static FILE *call_sock_from_fd(int fd) {
+  int r;
+
+  FILE *call_sock = fdopen(fd, "r+");
+  if (!call_sock) diee("fdopen socket");
+
+  r = setvbuf(call_sock, 0, _IONBF, 0);
+  if (r) die("setvbuf socket");
+
+  return call_sock;
+}
+
+static bool was_eof(FILE *call_sock) {
+  return feof(call_sock) || errno==ECONNRESET;
+}
+
+// Does protocol exchange.  Returns 0 if OK, error msg if peer was garbage.
+static const char *protocol_exchange(FILE *call_sock) {
+  char ack;
+  size_t sr = fread(&ack, sizeof(ack), 1, call_sock);
+  if (sr != 1) {
+    if (was_eof(call_sock)) return "initial monitor process quit";
+    diee("read() ack byte");
   }
+  if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
+
+  // We're committed now, send the request (or bail out)
+  send_request(call_sock);
+
+  return 0;
 }
 
-// Returns: call(client-end) fd, or -1 to mean "is garbage"
+// Returns: call(client-end), or 0 to mean "is garbage"
 // find_socket_path must have been called
-static int connect_existing(void) {
+static FILE *connect_existing(void) {
   int r;
   int fd = -1;
+  FILE *call_sock = 0;
 
   fd = socket(AF_UNIX, SOCK_STREAM, 0);
   if (fd==-1) diee("socket() for client");
 
-  socklen_t salen = sizeof(sun);
-  r = connect(fd, (const struct sockaddr*)&socket_sun, salen);
+  socklen_t salen = sizeof(sockaddr_sun);
+  r = connect(fd, (const struct sockaddr*)&sockaddr_sun, salen);
   if (r==-1) {
     if (errno==ECONNREFUSED || errno==ENOENT) goto x_garbage;
     diee("connect() %s", socket_path);
   }
 
-  for (;;) {
-    char ack;
-    size_t sr = read(fd, &ack, 1);
-    if (sr == -1) {
-      if (errno==ECONNRESET) goto x_garbage;
-      if (errno==EINTR) continue;
-      diee("read() ack byte");
-    }
-    if (sr == 0) { goto x_garbage; }
-    if (ack != '\n') die("got ack byte 0x%02x, not '\n'", ack);
-    break;
-  }
+  call_sock = call_sock_from_fd(fd);
+  fd = -1;
 
-  // We're committed now, send the request (or bail out)
-  send_request(fd);
+  if (protocol_exchange(call_sock))
+    goto x_garbage;
 
-  return fd;
+  return call_sock;
 
  x_garbage:
+  if (call_sock) fclose(call_sock);
   if (fd >= 0) close(fd);
-  return -1;
+  return 0;
 }
 
 static __attribute__((noreturn))
@@ -296,34 +332,32 @@ void become_setup(int sfd, int fake_pair[2]) {
   close(fake_pair[0]);
   int call_fd = fake_pair[1];
 
-  int fd0_save = dup(0);  if (fd0_save < 0) diee("dup stdin");
-  int fd1_save = dup(1);  if (fd1_save < 0) diee("dup stdin");
-
   int null_0 = open("/dev/null", O_RDONLY);  if (null_0 < 0) diee("open null");
   if (dup2(null_0, 0)) diee("dup2 /dev/null onto stdin");
   if (dup2(2, 1) != 1) die("dup2 stderr onto stdout");
 
-  putenv(m_asprintf("PREFORK_INTERP=%d,%d,%d,%d,%s",
-                   sfd, call_fd, fd0_save, fd1_save, socket_path));
+  putenv(m_asprintf("PREFORK_INTERP=%d,%d,%s",
+                   sfd, call_fd, socket_path));
 
   execvp(executor_argv[0], (char**)executor_argv);
   diee("execute %s", executor_argv[0]);
 }
 
-static int connect_or_spawn(void) {
+static FILE *connect_or_spawn(void) {
   int r;
 
-  int fd = connect_existing();
-  if (fd >= 0) return fd;
+  FILE *call_sock = connect_existing();
+  if (call_sock) return call_sock;
 
   int lockfd = acquire_lock();
-  fd = connect_existing();
-  if (fd >= 0) { close(lockfd); return fd; }
+  call_sock = connect_existing();
+  if (call_sock) { close(lockfd); return call_sock; }
 
   // We must start a fresh one, and we hold the lock
 
   r = unlink(socket_path);
-  if (r<0) diee("failed to remove stale socket %s", socket_path);
+  if (r<0 && errno!=ENOENT)
+    diee("failed to remove stale socket %s", socket_path);
 
   int fake_pair[2];
   r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
@@ -332,8 +366,8 @@ static int connect_or_spawn(void) {
   int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
   if (sfd<0) diee("socket() for new listener");
 
-  socklen_t salen = sizeof(sun);
-  r= bind(sfd, (const struct sockaddr*)&socket_sun, salen);
+  socklen_t salen = sizeof(sockaddr_sun);
+  r= bind(sfd, (const struct sockaddr*)&sockaddr_sun, salen);
   if (r<0) diee("bind() on new listener");
 
   // We never want callers to get ECONNREFUSED.  But:
@@ -349,18 +383,27 @@ static int connect_or_spawn(void) {
   close(fake_pair[1]);
   close(sfd);
 
+  call_sock = call_sock_from_fd(fake_pair[0]);
+  const char *emsg = protocol_exchange(call_sock);
+  if (emsg) die("setup failed: %s", emsg);
+
   int status;
   pid_t got = waitpid(setup_pid, &status, 0);
   if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
   if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
                             (long)setup_pid, (long)got);
-  if (status != 0) propagate_exit_status(status, "invocation");
+  if (status != 0) propagate_exit_status(status, "setup");
 
   close(lockfd);
-  return fake_pair[0];
+  return call_sock;
 }
 
 static void make_executor_argv(const char *const *argv) {
+  switch (laundering) {
+  case 'U': break;
+  default: die("need -U (specifying unlaundered argument handling)");
+  }
+
   const char *arg;
   #define EACH_NEW_ARG(EACH) {                 \
     arg = interp; { EACH }                     \
@@ -391,10 +434,22 @@ int main(int argc_unused, const char *const *argv) {
   make_executor_argv(argv);
 
   find_socket_path();
-  FILLZERO(sun);
-  sun.sun_family = AF_UNIX;
-  assert(strlen(socket_path) <= sizeof(sun.sun_path));
-  strncpy(sun.sun_path, socket_path, sizeof(sun.sun_path));
+  FILLZERO(sockaddr_sun);
+  sockaddr_sun.sun_family = AF_UNIX;
+  assert(strlen(socket_path) <= sizeof(sockaddr_sun.sun_path));
+  strncpy(sockaddr_sun.sun_path, socket_path, sizeof(sockaddr_sun.sun_path));
+
+  FILE *call_sock = connect_or_spawn();
+  uint32_t status;
+  ssize_t sr = fread(&status, sizeof(status), 1, call_sock);
+  if (sr != 1) {
+    if (was_eof(call_sock)) die("per-call server monitor process quit");
+    diee("read status from call socket");
+  }
+
+  status = ntohl(status);
+  if (status > INT_MAX) die("status 0x%lx does not fit in an int",
+                           (unsigned long)status);
 
-  int call_fd = connect_or_spawn();
+  propagate_exit_status(status, "invocation");
 }