chiark / gitweb /
cgi-fcgi-interp: Provide -E option.
[chiark-utils.git] / cprogs / cgi-fcgi-interp.c
index 752db40897652a9955cc0757a48860298b726fdc..6b0585b54f4a9b46e0464d80458c28f4f88b28c7 100644 (file)
  *          The real interpreter to use.  Eg "perl".  Need not
  *          be an absolute path; will be fed to execvp.
  *
+ *  -G<ident-info>
+ *          Add <ident-info> to the unique identifying information for
+ *          this fcgi program.  May be repeated; order is significant.
+ *
+ *  -E<ident-info-env-var>
+ *          Look <ident-info-env-var> up in the environment and add
+ *          <ident-info-env-var>=<value> as if specified with -G.  If
+ *          the variable is unset in the environment, it is as if
+ *          -G<ident-info-env-var> was specified.
+ *
  *  -g<ident>
- *          Use <ident> rather than hex(sha256(<script>))
+ *          Use <ident> rather than hex(sha256(<interp>\0<script>\0))
  *          as the basename of the leafname of the fcgi rendezvous
  *          socket.  If <ident> contains only hex digit characters it
  *          ought to be no more than 32 characters.  <ident> should
  *         speedy, the specified number of servers is started
  *         right away.)  The default is 4.
  *
+ *  -c<interval>
+ *         Stale server check interval, in seconds.  The worker
+ *         process group will get a SIGTERM when it is no longer
+ *         needed to process new requests.  Ideally it would continue
+ *         to serve any existing requests.  The SIGTERM will arrive no
+ *         earlier than <interval> after the last request arrived at
+ *         the containing webserver.  Default is 300.
+ *
  *  -D
  *         Debug mode.  Do not actually run program.  Instead, print
  *         out what we would do.
  * cgi-fcgi-interp automatically expires old sockets, including
  * ones where the named script is out of date.
  */
-
 /*
  * Uses one of two directories
  *   /var/run/user/<UID>/cgi-fcgi-interp/
  *   ~/.cgi-fcgi-interp/<node>/
  * and inside there uses these paths
  *   s<ident>
- *   g<inum>
+ *   l<ident>    used to lock around garbage collection
  *
- * If -M<ident> is not specified then an initial substricg of the
- * lowercase hex of the sha256 of the <script> (ie, our argv[1]) is
+ * If -M<ident> is not specified then an initial substring of the
+ * lowercase hex of the sha256 of <interp>\0<script>\0 is
  * used.  The substring is chosen so that the whole path is 10 bytes
  * shorter than sizeof(sun_path).  But always at least 33 characters.
  *
  *  - check for and maybe create <base>
  *  - stat and lstat the <script>
  *  - stat the socket and check its timestamp
- *       if it is too old, rename it to g<inum>.<pid> (where
- *       <inum> and <pid> are in decimal)
- *       and run garbage collection
- *  - run  cgi-fcgi -connect SOCKET SCRIPT
+ *       if it is too old, unlink it
+ *  - dup stderr, mark no cloexec
+ *  - set CHIARKUTILS_CGIFCGIINTERP_STAGE2=<stderr-copy-fd>
+ *  - run     cgi-fcgi -connect SOCKET <script>
+ *
+ * When CHIARKUTILS_CGIFCGIINTERP_STAGE2 is set, --stage2 does this:
+ *  - dup2 <was-stderr> to fd 2
+ *  - open /dev/null and expect fd 1 (and if not, close it)
+ *  - become a new process group
+ *  - lstat <socket> to find its inum, mtime
+ *  - fork/exec <interp> <script>
+ *  - periodically lstat <interp> and <script> and
+ *      if mtime is newer than our start time
+ *      kill process group (at second iteration)
  */
 
 #include "common.h"
 #include <sys/utsname.h>
 #include <sys/socket.h>
 #include <sys/un.h>
+#include <sys/file.h>
 #include <unistd.h>
+#include <fcntl.h>
 #include <pwd.h>
 #include <err.h>
-
+#include <time.h>
+#include <signal.h>
+#include <sys/wait.h>
+       
 #include <nettle/sha.h>
 
 #include "myopt.h"
 #define diee common_diee
 
 #define MINHEXHASH 33
+#define STAGE2_VAR "CHIARKUTILS_CGIFCGIINTERP_STAGE2"
 
 static const char *interp, *ident;
-static int numservers, debugmode;
+static int numservers=4, debugmode;
+static int check_interval=300;
+
+static struct sha256_ctx identsc;
+
+const char *stage2;
 
 void diee(const char *m) {
   err(127, "error: %s failed", m);
@@ -152,19 +190,39 @@ static void of_iassign(const struct cmdinfo *ci, const char *val) {
   *ci->iassignto = v;
 }
 
+static void ident_addstring(const struct cmdinfo *ci, const char *string) {
+  /* ci may be 0 and is provided so this can be .call */
+  sha256_update(&identsc,strlen(string)+1,string);
+}
+
+static void off_ident_addenv(const struct cmdinfo *ci, const char *name) {
+  const char *val = getenv(name);
+  if (val) {
+    sha256_update(&identsc,strlen(name),name); /* no nul */
+    sha256_update(&identsc,1,"=");
+    ident_addstring(0,val);
+  } else {
+    ident_addstring(0,name);
+  }
+}
+
 #define MAX_OPTS 5
 
 static const struct cmdinfo cmdinfos[]= {
-  { "help",   0, .call= of_help               },
-  { 0, 'g',   1, .sassignto= &ident           },
-  { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
-  { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
+  { "help",   0, .call=of_help                                         },
+  { 0, 'g',   1,                    .sassignto= &ident                 },
+  { 0, 'G',   1, .call= ident_addstring                                },
+  { 0, 'E',   1, .call= off_ident_addenv                               },
+  { 0, 'M',   1, .call=of_iassign,  .iassignto= &numservers            },
+  { 0, 'D',   0,                    .iassignto= &debugmode,    .arg= 1 },
+  { 0, 'c',   1, .call=of_iassign,  .iassignto= &check_interval        },
   { 0 }
 };
 
 static uid_t us;
 static const char *run_base, *script, *socket_path;
-static struct stat sock_stab;
+static const char *run_base_mkdir_p;
+static int stderr_copy;
 
 static bool find_run_base_var_run(void) {
   struct stat stab;
@@ -212,7 +270,8 @@ static bool find_run_base_home(void) {
   if (sizeof(ut.nodename) > 32)
     ut.nodename[32] = 0;
 
-  try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
+  run_base_mkdir_p = m_asprintf("%s/%s", pw->pw_dir, ".cgi-fcgi-interp");
+  try = m_asprintf("%/%s", run_base_mkdir_p, ut.nodename);
   run_base = try;
   return 1;
 }
@@ -238,14 +297,12 @@ static void find_socket_path(void) {
 
     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
     char *hexident = xmalloc(identlen + 2);
-    struct sha256_ctx sc;
     unsigned char bbuf[32];
     int i;
 
-    sha256_init(&sc);
-    sha256_update(&sc,strlen(interp)+1,interp);
-    sha256_update(&sc,strlen(script)+1,script);
-    sha256_digest(&sc,sizeof(bbuf),bbuf);
+    ident_addstring(0,interp);
+    ident_addstring(0,script);
+    sha256_digest(&identsc,sizeof(bbuf),bbuf);
 
     for (i=0; i<identlen; i += 2)
       sprintf(hexident+i, "%02x", bbuf[i/2]);
@@ -260,12 +317,17 @@ static void find_socket_path(void) {
         run_base, ident, maxidentlen);
 
   r = mkdir(run_base, 0700);
+  if (r && errno==ENOENT && run_base_mkdir_p) {
+    r = mkdir(run_base_mkdir_p, 0700);
+    if (r) err(127,"mkdir %s (since %s was ENOENT)",run_base_mkdir_p,run_base);
+    r = mkdir(run_base, 0700);
+  }
   if (r) {
     if (!(errno == EEXIST))
       err(127,"mkdir %s",run_base);
   }
 
-  socket_path = m_asprintf("%s/g%s",run_base,ident);
+  socket_path = m_asprintf("%s/s%s",run_base,ident);
 }  
 
 /*
@@ -310,99 +372,121 @@ static void find_socket_path(void) {
 
 
 
-static bool stab_isnewer(const struct stat *a, const struct stat *b) {
 #ifdef st_mtime
+
+static bool stab_isnewer(const struct stat *a, const struct stat *b) {
+  if (debugmode)
+    fprintf(stderr,"stab_isnewer mtim %lu.%06lu %lu.06%lu\n",
+           (unsigned long)a->st_mtim.tv_sec,
+           (unsigned long)a->st_mtim.tv_nsec,
+           (unsigned long)b->st_mtim.tv_sec,
+           (unsigned long)b->st_mtim.tv_nsec);
   return timespeccmp(&a->st_mtim, &b->st_mtim, >);
-#else
+}
+
+static void stab_mtimenow(struct stat *out) {
+  int r = clock_gettime(CLOCK_REALTIME, &out->st_mtim);
+  if (r) err(127,"(stage2) clock_gettime");
+  if (debugmode)
+    fprintf(stderr,"stab_mtimenow mtim %lu.%06lu\n",
+           (unsigned long)out->st_mtim.tv_sec,
+           (unsigned long)out->st_mtim.tv_nsec);
+}
+
+#else /* !defined(st_mtime) */
+
+static bool stab_isnewer(const struct stat *a, const struct stat *b) {
+  if (debugmode)
+    fprintf(stderr,"stab_isnewer mtime %lu %lu\n",
+           (unsigned long)a->st_mtime,
+           (unsigned long)b->st_mtime);
   return a->st_mtime > &b->st_mtime;
-#endif
 }
 
-static bool check_garbage(void) {
+static void stab_mtimenow(struct stat *out) {
+  out->st_mtime = time(NULL);
+  if (baseline_time.st_mtime == (time_t)-1) err(127,"(stage2) time()");
+  if (debugmode)
+    fprintf(stderr,"stab_mtimenow mtime %lu\n",
+           (unsigned long)out->st_mtime);
+}
+
+#endif /* !defined(st_mtime) */
+
+static bool check_garbage_vs(const struct stat *started) {
   struct stat script_stab;
   int r;
 
   r = lstat(script, &script_stab);
   if (r) err(127,"lstat script (%s)",script);
 
-  r = lstat(socket_path, &sock_stab);
-  if (r) {
-    if ((errno == ENOENT))
-      return 0; /* well, no garbage then */
-    err(127,"stat socket (%s)",socket_path);
-  }
-
-  if (stab_isnewer(&script_stab, &sock_stab))
+  if (stab_isnewer(&script_stab, started))
     return 1;
 
   if (S_ISLNK(script_stab.st_mode)) {
     r = stat(script, &script_stab);
     if (r) err(127,"stat script (%s0",script);
 
-    if (stab_isnewer(&script_stab, &sock_stab))
+    if (stab_isnewer(&script_stab, started))
       return 1;
   }
 
   return 0;
 }
 
-static void tidy_1_garbage(const char *leaf) {
+static bool check_garbage(void) {
+  struct stat sock_stab;
   int r;
-  struct sockaddr_un sun;
-
-  int fd = -1;
-
-  memset(&sun,0,sizeof(sun));
-  sun.sun_family = AF_UNIX;
-  r = snprintf(sun.sun_path, sizeof(sun.sun_path), "%s/%s", run_base, leaf);
-  if (r >= sizeof(sun_path))
-    goto cannot;
-
-  fd = socket(AF_UNIX, SOCK_STREAM, 0);
-  if (fd<0) err("create socket for tidying garbage");
-
-  r = fcntl(fd, F_SETFL, O_NONBLOCK);
-  if (r<0) err("set garbage socket nonblocking");
 
-  r = connect(fd, &sun, sizeof(sun));
+  r = lstat(socket_path, &sock_stab);
   if (r) {
-    if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
-      goto cannot;
-    if (errno != EINPROGRESS)
-      err("connect to garbage socket (%s)", sun.sun_path);
-    /* well, EINPROGRESS, let's just carry on and hope write works */
+    if ((errno == ENOENT))
+      return 0; /* well, no garbage then */
+    err(127,"stat socket (%s)",socket_path);
   }
 
-  r = write(
-       
+  return check_garbage_vs(&sock_stab);
+}
 
 static void tidy_garbage(void) {
-  const char *this_garbage =
-    m_asprintf("%s/g%lu.%lu", run_base,
-              (unsigned long)sock_stab.st_ino,
-              (unsigned long)getpid());
+  /* We lock l<ident> and re-check.  The effect of this is that each
+   * stale socket is removed only once.  So unless multiple updates to
+   * the script happen rapidly, we can't be racing with the cgi-fcgi
+   * (which is recreating the socket */
+  int lockfd = -1;
+  int r;
 
-  r = rename(socket_path, this_garbage);
-  if (r) {
-    if (!(errno == ENOENT))
-      err("rename socket from old runner (from %s to %s)",
-         socket_path, this_garbage);
-  }
+  const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
 
-  DIR *d = opendir(run_base);
-  if (!d) err("open run directory (%d) to clean up garbage", run_base);
-  struct dirent *de;
-  while ((errno = 0, de = readdir(d))) {
-    if (de->d_name[0] != 'g')
-      continue;
-    tidy_1_garbage(de->d_name);
+  lockfd = open(lock_path, O_CREAT|O_RDWR, 0600);
+  if (lockfd<0) err(127,"create lock (%s)", lock_path);
+
+  r = flock(lockfd, LOCK_EX);
+  if (r) err(127,"lock lock (%s)", lock_path);
+
+  if (check_garbage()) {
+    r = unlink(socket_path);
+    if (r) {
+      if (!(errno == ENOENT))
+       err(127,"remove out-of-date socket (%s)", socket_path);
+    }
   }
-  if (errno) err("read run directory (%d) to clean up garbage", run_base);
-  /* 
-  (void)r;
-  if (r) {
 
-  printf("this_garb: %s\n", this_garbage);
+  r = close(lockfd);
+  if (r) errx(127,"close lock (%s)", lock_path);
+}
+
+static void make_stderr_copy(void) {
+  stderr_copy = dup(2);
+  if (stderr_copy < 0) err(127,"dup stderr (for copy for stage2)");
+}
+
+static void prep_stage2(void) {
+  int r;
+  
+  const char *stage2_val = m_asprintf("%d", stderr_copy);
+  r = setenv(STAGE2_VAR, stage2_val, 1);
+  if (r) err(127,"set %s (to announce to stage2)", STAGE2_VAR);
 }
 
 static void shbang_opts(const char *const **argv_io,
@@ -413,8 +497,33 @@ static void shbang_opts(const char *const **argv_io,
   if (!interp) errx(127,"need interpreter argument");
 }
 
+/* stage2 predeclarations */
+static void record_baseline_time(void);
+static void become_pgrp(void);
+static void setup_handlers(void);
+static void spawn_script(void);
+static void queue_alarm(void);
+static void await_something(void);
+
 int main(int argc, const char *const *argv) {
   const char *smashedopt;
+  int r;
+
+  stage2 = getenv(STAGE2_VAR);
+  if (stage2) {
+    int stderrfd = atoi(stage2);
+    assert(stderrfd>2);
+
+    r = dup2(stderrfd, 2);
+    assert(r==2);
+
+    r = open("/dev/null",O_WRONLY);
+    if (r<0) err(127,"open /dev/null as stdout");
+    if (r>=3) close(r);
+    else if (r!=1) errx(127,"open /dev/null for stdout gave bad fd %d",r);
+  }
+
+  sha256_init(&identsc);
 
   if (argc>=2 &&
       (smashedopt = argv[1]) &&
@@ -453,20 +562,161 @@ int main(int argc, const char *const *argv) {
   if (!script) errx(127,"need script argument");
   if (*argv) errx(127,"too many arguments");
 
-  find_socket_path();
+  if (!stage2) {
+    
+    find_socket_path();
+
+    bool isgarbage = check_garbage();
+
+    if (debugmode) {
+      printf("socket: %s\n",socket_path);
+      printf("interp: %s\n",interp);
+      printf("script: %s\n",script);
+      printf("garbage: %d\n",isgarbage);
+      exit(0);
+    }
 
-  bool havegarbage = check_garbage();
+    if (isgarbage)
+      tidy_garbage();
+
+    make_stderr_copy();
+    prep_stage2();
+
+    execlp("cgi-fcgi",
+          "cgi-fcgi", "-connect", socket_path,
+          script,
+          m_asprintf("%d", numservers),
+          (char*)0);
+    err(127,"exec cgi-fcgi");
+    
+  } else { /*stage2*/
+
+    record_baseline_time();
+    become_pgrp();
+    setup_handlers();
+    spawn_script();
+    queue_alarm();
+    await_something();
+    abort();
 
-  if (debugmode) {
-    printf("socket: %s\n",socket_path);
-    printf("interp: %s\n",interp);
-    printf("script: %s\n",script);
-    printf("garbage: %d\n",havegarbage);
-    exit(0);
   }
+}
 
-  if (havegarbage)
-    tidy_garbage();
+/* stage2 */
 
-  exit(0);
+/* It is most convenient to handle the recheck timeout, as well as
+ * child death, in signal handlers.  Our signals all block each other,
+ * and the main program has signals blocked except in sigsuspend, so
+ * we don't need to worry about async-signal-safety, or errno. */
+
+static struct stat baseline_time;
+static pid_t script_child, stage2_pgrp;
+static bool out_of_date;
+
+static void record_baseline_time(void) {
+  stab_mtimenow(&baseline_time);
+}
+
+static void become_pgrp(void) {
+  int r;
+
+  stage2_pgrp = getpid();
+
+  r = setpgid(0,0);
+  if (r) err(127,"(stage2) setpgid");
+}
+
+static void atexit_handler(void) {
+  int r;
+
+  sighandler_t sigr = signal(SIGTERM,SIG_IGN);
+  if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
+
+  r = killpg(stage2_pgrp,SIGTERM);
+  if (r) warn("(stage) killpg failed");
+}
+
+static void alarm_handler(int dummy) {
+  if (out_of_date)
+    /* second timeout */
+    exit(0); /* transfers control to atexit_handler */
+
+  out_of_date = check_garbage_vs(&baseline_time);
+  queue_alarm();
+}
+
+static void child_handler(int dummy) {
+  for (;;) {
+    int status;
+    pid_t got = waitpid(-1, &status, WNOHANG);
+    if (got == (pid_t)-1) err(127,"(stage2) waitpid");
+    if (got != script_child) {
+      warn("(stage2) waitpid got status %d for unknown child [%lu]",
+          status, (unsigned long)got);
+      continue;
+    }
+    if (WIFEXITED(status)) {
+      int v = WEXITSTATUS(status);
+      if (v) warn("program failed with error exit status %d", v);
+      exit(status);
+    } else if (WIFSIGNALED(status)) {
+      int s = WTERMSIG(status);
+      err(status & 0xff, "program died due to fatal signal %s%s",
+         strsignal(s), WCOREDUMP(status) ? " (core dumped" : "");
+    } else {
+      err(127, "program failed with crazy wait status %#x", status);
+    }
+  }
+  exit(127);
+}
+
+static void setup_handlers(void) {
+  struct sigaction sa;
+  int r;
+
+  r = atexit(atexit_handler);
+  if (r) err(127,"(stage2) atexit");
+
+  sigemptyset(&sa.sa_mask);
+  sigaddset(&sa.sa_mask, SIGALRM);
+  sigaddset(&sa.sa_mask, SIGCHLD);
+  sa.sa_flags = 0;
+
+  r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
+  if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
+
+  sa.sa_handler = alarm_handler;
+  r = sigaction(SIGALRM, &sa, 0);
+  if (r) err(127,"(stage2) sigaction SIGALRM");
+
+  sa.sa_flags |= SA_NOCLDSTOP;
+  sa.sa_handler = child_handler;
+  r = sigaction(SIGCHLD, &sa, 0);
+  if (r) err(127,"(stage2) sigaction SIGCHLD");
+}
+
+static void spawn_script(void) {
+  script_child = fork();
+  if (script_child == (pid_t)-1) err(127,"(stage2) fork");
+  if (!script_child) {
+    execlp(interp,
+          interp, script, (char*)0);
+    err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
+  }
+}
+
+static void queue_alarm(void) {
+  alarm(check_interval);
+}
+
+static void await_something(void) {
+  int r;
+  sigset_t mask;
+  sigemptyset(&mask);
+
+  for (;;) {
+    r = sigsuspend(&mask);
+    assert(r==-1);
+    if (errno != EINTR) err(127,"(stage2) sigsuspend");
+  }
 }