chiark / gitweb /
cgi-fcgi-interp: new garbage collection approach, spec (more)
[chiark-utils.git] / cprogs / cgi-fcgi-interp.c
index d2681cfc861a068cd5cbe4d8e7003f7c466c23c0..28ec12624dee698beb91219b492ba32a4ce5aeed 100644 (file)
@@ -2,7 +2,31 @@
  * "Interpreter" that you can put in #! like this
  *   #!/usr/bin/cgi-fcgi-interp [<options>] <interpreter>
  *   #!/usr/bin/cgi-fcgi-interp [<options>],<interpreter>
+ */
+/*
+ * cgi-fcgi-interp.[ch] - C helpers common to the whole of chiark-utils
+ *
+ * Copyright 2016 Ian Jackson
+ * Copyright 1982,1986,1993 The Regents of the University of California
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
  *
+ * You should have received a copy of the GNU General Public
+ * License along with this file; if not, consult the Free Software
+ * Foundation's website at www.fsf.org, or the GNU Project website at
+ * www.gnu.org.
+ *
+ * See below for a BSD 3-clause notice regarding timespeccmp.
+ */
+/*
  * The result is a program which looks, when executed via the #!
  * line, like a CGI program.  But the script inside will be executed
  * via <interpreter> in an fcgi context.
  *         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.
@@ -44,7 +76,7 @@
  *   ~/.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
  *  - check for and maybe create <base>
  *  - stat and lstat the <script>
  *  - stat the socket and check its timestamp
- *       if it is too hold, rename it to g<inum> (where
- *       <inum> is in decimal)
- *       and run garbage collection
- *  - run  cgi-fcgi -connect SOCKET SCRIPT
+ *       if it is too old, unlink it
+ *  - dup stderr, mark no cloexec
+ *  - run     cgi-fcgi -connect SOCKET       \
+ *                cgi-fcgi-interp \
+ *                --stage2 <was-stderr> <socket>      \
+ -c<check-interval>            \
+ *               \
+ *                <interp> <script>
+ *
+ * --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 <socket> and
+ *      if inum, mtime have changed
+ *      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 <nettle/sha.h>
 
 #include "myopt.h"
 #define MINHEXHASH 33
 
 static const char *interp, *ident;
-static int numservers, debugmode;
+static int numservers=4, debugmode, stage2;
+static int check_interval=300;
 
 void diee(const char *m) {
   err(127, "error: %s failed", m);
@@ -135,11 +184,14 @@ static const struct cmdinfo cmdinfos[]= {
   { 0, 'g',   1, .sassignto= &ident           },
   { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
   { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
+  { 0, 'c',   1, .call=of_iassign, .iassignto= &check_interval  },
+  { "--stage2",0, 0, .iassignto= &stage2, .arg= 1 },
   { 0 }
 };
 
 static uid_t us;
-static const char *run_base, *command, *socket_path;
+static const char *run_base, *script, *socket_path;
+static struct stat sock_stab;
 
 static bool find_run_base_var_run(void) {
   struct stat stab;
@@ -207,7 +259,7 @@ static void find_socket_path(void) {
   if (!ident) {
     if (maxidentlen < MINHEXHASH)
       errx(127,"base directory `%s'"
-          " leaves only %d characters for command name hash"
+          " leaves only %d characters for id hash"
           " which is too little (<%d)",
           run_base, maxidentlen, MINHEXHASH);
 
@@ -219,7 +271,7 @@ static void find_socket_path(void) {
 
     sha256_init(&sc);
     sha256_update(&sc,strlen(interp)+1,interp);
-    sha256_update(&sc,strlen(command)+1,command);
+    sha256_update(&sc,strlen(script)+1,script);
     sha256_digest(&sc,sizeof(bbuf),bbuf);
 
     for (i=0; i<identlen; i += 2)
@@ -243,10 +295,63 @@ static void find_socket_path(void) {
   socket_path = m_asprintf("%s/g%s",run_base,ident);
 }  
 
+/*
+ * Regarding the macro timespeccmp:
+ *
+ * Copyright (c) 1982, 1986, 1993
+ *      The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 4. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *      @(#)time.h      8.5 (Berkeley) 5/4/95
+ * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
+ */
+#ifndef timespeccmp
+#define timespeccmp(tvp, uvp, cmp)                                      \
+        (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
+            ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :                       \
+            ((tvp)->tv_sec cmp (uvp)->tv_sec))
+#endif /*timespeccmp*/
+
+
+
+static bool stab_isnewer(const struct stat *a, const struct stat *b) {
+#ifdef st_mtime
+  return timespeccmp(&a->st_mtim, &b->st_mtim, >);
+#else
+  return a->st_mtime > &b->st_mtime;
+#endif
+}
+
 static bool check_garbage(void) {
-  struct stat sock_stab, cmd_stab;
+  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))
@@ -254,12 +359,48 @@ static bool check_garbage(void) {
     err(127,"stat socket (%s)",socket_path);
   }
 
-  r = lstat(command, &cmd_stab);
-  if (r) err(127,"lstat command (%s)",command);
+  if (stab_isnewer(&script_stab, &sock_stab))
+    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))
+      return 1;
+  }
 
   return 0;
 }
 
+static void tidy_garbage(void) {
+  /* 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;
+
+  const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
+
+  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);
+    }
+  }
+
+  r = close(lockfd);
+  if (r) errx(127,"close lock (%s)", lock_path);
+}
+
 static void shbang_opts(const char *const **argv_io,
                        const struct cmdinfo *cmdinfos) {
   myopt(argv_io, cmdinfos);
@@ -304,19 +445,24 @@ int main(int argc, const char *const *argv) {
     shbang_opts(&argv, cmdinfos);
   }
 
-  command = *argv++;
-  if (!command) errx(127,"need command argument");
+  script = *argv++;
+  if (!script) errx(127,"need script argument");
   if (*argv) errx(127,"too many arguments");
 
   find_socket_path();
 
-  check_garbage();
+  bool isgarbage = check_garbage();
 
   if (debugmode) {
     printf("socket: %s\n",socket_path);
     printf("interp: %s\n",interp);
-    printf("command: %s\n",command);
+    printf("script: %s\n",script);
+    printf("garbage: %d\n",isgarbage);
+    exit(0);
   }
 
+  if (isgarbage)
+    tidy_garbage();
+
   exit(0);
 }