chiark / gitweb /
cgi-fcgi-interp: new garbage collection approach, wip implementation
[chiark-utils.git] / cprogs / cgi-fcgi-interp.c
1 /*
2  * "Interpreter" that you can put in #! like this
3  *   #!/usr/bin/cgi-fcgi-interp [<options>] <interpreter>
4  *   #!/usr/bin/cgi-fcgi-interp [<options>],<interpreter>
5  */
6 /*
7  * cgi-fcgi-interp.[ch] - C helpers common to the whole of chiark-utils
8  *
9  * Copyright 2016 Ian Jackson
10  * Copyright 1982,1986,1993 The Regents of the University of California
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public
23  * License along with this file; if not, consult the Free Software
24  * Foundation's website at www.fsf.org, or the GNU Project website at
25  * www.gnu.org.
26  *
27  * See below for a BSD 3-clause notice regarding timespeccmp.
28  */
29 /*
30  * The result is a program which looks, when executed via the #!
31  * line, like a CGI program.  But the script inside will be executed
32  * via <interpreter> in an fcgi context.
33  *
34  * Options:
35  *
36  *  <interpreter>
37  *          The real interpreter to use.  Eg "perl".  Need not
38  *          be an absolute path; will be fed to execvp.
39  *
40  *  -g<ident>
41  *          Use <ident> rather than hex(sha256(<script>))
42  *          as the basename of the leafname of the fcgi rendezvous
43  *          socket.  If <ident> contains only hex digit characters it
44  *          ought to be no more than 32 characters.  <ident> should
45  *          not contain spaces or commas (see below).
46  *
47  *  -M<numservers>
48  *         Start <numservers> instances of the program.  This
49  *         determines the maximum concurrency.  (Note that unlike
50  *         speedy, the specified number of servers is started
51  *         right away.)  The default is 4.
52  *
53  *  -c<interval>
54  *         Stale server check interval, in seconds.  The worker
55  *         process group will get a SIGTERM when it is no longer
56  *         needed to process new requests.  Ideally it would continue
57  *         to serve any existing requests.  The SIGTERM will arrive no
58  *         earlier than <interval> after the last request arrived at
59  *         the containing webserver.  Default is 300.
60  *
61  *  -D
62  *         Debug mode.  Do not actually run program.  Instead, print
63  *         out what we would do.
64  *
65  * <options> and <interpreter> can be put into a single argument
66  * to cgi-fcgi-interp, separated by spaces or commas.  <interpreter>
67  * must come last.
68  *
69  * cgi-fcgi-interp automatically expires old sockets, including
70  * ones where the named script is out of date.
71  */
72
73 /*
74  * Uses one of two directories
75  *   /var/run/user/<UID>/cgi-fcgi-interp/
76  *   ~/.cgi-fcgi-interp/<node>/
77  * and inside there uses these paths
78  *   s<ident>
79  *   l<ident>    used to lock around garbage collection
80  *
81  * If -M<ident> is not specified then an initial substricg of the
82  * lowercase hex of the sha256 of the <script> (ie, our argv[1]) is
83  * used.  The substring is chosen so that the whole path is 10 bytes
84  * shorter than sizeof(sun_path).  But always at least 33 characters.
85  *
86  * <node> is truncated at the first `.' and after the first 32
87  * characters.
88  *
89  * Algorithm:
90  *  - see if /var/run/user exists
91  *       if so, lstat /var/run/user/<UID> and check that
92  *         we own it and it's X700; if not, fail
93  *         if it's ok then <base> is /var/run/user/<UID>
94  *       otherwise, look for and maybe create ~/.cgi-fcgi-interp
95  *         (where ~ is HOME or from getpwuid)
96  *         and then <base> is ~/.cgi-fcgi-interp/<node>
97  *  - calculate pathname (checking <ident> length is OK)
98  *  - check for and maybe create <base>
99  *  - stat and lstat the <script>
100  *  - stat the socket and check its timestamp
101  *       if it is too old, unlink it
102  *  - dup stderr, mark no cloexec
103  *  - run     cgi-fcgi -connect SOCKET       \
104  *                cgi-fcgi-interp \
105  *                --stage2 <was-stderr> <socket>      \
106  -c<check-interval>             \
107  *               \
108  *                <interp> <script>
109  *
110  * --stage2 does this:
111  *  - dup2 <was-stderr> to fd 2
112  *  - open /dev/null and expect fd 1 (and if not, close it)
113  *  - become a new process group
114  *  - lstat <socket> to find its inum, mtime
115  *  - fork/exec <interp> <script>
116  *  - periodically lstat <interp> and <script> and
117  *      if mtime is newer than our start time
118  *      kill process group (at second iteration)
119  */
120
121 #include "common.h"
122
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <errno.h>
127 #include <stdbool.h>
128 #include <assert.h>
129 #include <limits.h>
130
131 #include <sys/types.h>
132 #include <sys/stat.h>
133 #include <sys/utsname.h>
134 #include <sys/socket.h>
135 #include <sys/un.h>
136 #include <sys/file.h>
137 #include <unistd.h>
138 #include <fcntl.h>
139 #include <pwd.h>
140 #include <err.h>
141         
142 #include <nettle/sha.h>
143
144 #include "myopt.h"
145
146 #define die  common_die
147 #define diee common_diee
148
149 #define MINHEXHASH 33
150
151 static const char *interp, *ident;
152 static int numservers=4, debugmode, stage2;
153 static int check_interval=300;
154
155 void diee(const char *m) {
156   err(127, "error: %s failed", m);
157 }
158
159 static void fusagemessage(FILE *f) {
160   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
161 }
162
163 void usagemessage(void) { fusagemessage(stderr); }
164
165 static void of_help(const struct cmdinfo *ci, const char *val) {
166   fusagemessage(stdout);
167   if (ferror(stdout)) diee("write usage message to stdout");
168   exit(0);
169 }
170
171 static void of_iassign(const struct cmdinfo *ci, const char *val) {
172   long v;
173   char *ep;
174   errno= 0; v= strtol(val,&ep,10);
175   if (!*val || *ep || errno || v<INT_MIN || v>INT_MAX)
176     badusage("bad integer argument `%s' for --%s",val,ci->olong);
177   *ci->iassignto = v;
178 }
179
180 #define MAX_OPTS 5
181
182 static const struct cmdinfo cmdinfos[]= {
183   { "help",   0, .call= of_help               },
184   { 0, 'g',   1, .sassignto= &ident           },
185   { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
186   { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
187   { 0, 'c',   1, .call=of_iassign, .iassignto= &check_interval  },
188   { "--stage2",0, 0, .iassignto= &stage2, .arg= 1 },
189   { 0 }
190 };
191
192 static uid_t us;
193 static const char *run_base, *script, *socket_path;
194
195 static bool find_run_base_var_run(void) {
196   struct stat stab;
197   char *try;
198   int r;
199
200   try = m_asprintf("%s/%lu", "/var/run/user", us);
201   r = lstat(try, &stab);
202   if (r<0) {
203     if (errno == ENOENT ||
204         errno == ENOTDIR ||
205         errno == EACCES ||
206         errno == EPERM)
207       return 0; /* oh well */
208     diee("stat /var/run/user/UID");
209   }
210   if (!S_ISDIR(stab.st_mode)) {
211     warnx("%s not a directory, falling back to ~\n", try);
212     return 0;
213   }
214   if (stab.st_uid != us) {
215     warnx("%s not owned by uid %lu, falling back to ~\n", try,
216           (unsigned long)us);
217     return 0;
218   }
219   if (stab.st_mode & 0077) {
220     warnx("%s writeable by group or other, falling back to ~\n", try);
221     return 0;
222   }
223   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
224   return 1;
225 }
226
227 static bool find_run_base_home(void) {
228   struct passwd *pw;
229   struct utsname ut;
230   char *dot, *try;
231   int r;
232
233   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
234
235   r = uname(&ut);   if (r) diee("uname(2)");
236   dot = strchr(ut.nodename, '.');
237   if (dot) *dot = 0;
238   if (sizeof(ut.nodename) > 32)
239     ut.nodename[32] = 0;
240
241   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
242   run_base = try;
243   return 1;
244 }
245
246 static void find_socket_path(void) {
247   struct sockaddr_un sun;
248   int r;
249
250   us = getuid();  if (us==(uid_t)-1) diee("getuid");
251
252   find_run_base_var_run() ||
253     find_run_base_home() ||
254     (abort(),0);
255
256   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
257
258   if (!ident) {
259     if (maxidentlen < MINHEXHASH)
260       errx(127,"base directory `%s'"
261            " leaves only %d characters for id hash"
262            " which is too little (<%d)",
263            run_base, maxidentlen, MINHEXHASH);
264
265     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
266     char *hexident = xmalloc(identlen + 2);
267     struct sha256_ctx sc;
268     unsigned char bbuf[32];
269     int i;
270
271     sha256_init(&sc);
272     sha256_update(&sc,strlen(interp)+1,interp);
273     sha256_update(&sc,strlen(script)+1,script);
274     sha256_digest(&sc,sizeof(bbuf),bbuf);
275
276     for (i=0; i<identlen; i += 2)
277       sprintf(hexident+i, "%02x", bbuf[i/2]);
278
279     hexident[identlen] = 0;
280     ident = hexident;
281   }
282
283   if (strlen(ident) > maxidentlen)
284     errx(127, "base directory `%s' plus ident `%s' too long"
285          " (with spare) for socket (max ident %d)\n",
286          run_base, ident, maxidentlen);
287
288   r = mkdir(run_base, 0700);
289   if (r) {
290     if (!(errno == EEXIST))
291       err(127,"mkdir %s",run_base);
292   }
293
294   socket_path = m_asprintf("%s/g%s",run_base,ident);
295 }  
296
297 /*
298  * Regarding the macro timespeccmp:
299  *
300  * Copyright (c) 1982, 1986, 1993
301  *      The Regents of the University of California.  All rights reserved.
302  *
303  * Redistribution and use in source and binary forms, with or without
304  * modification, are permitted provided that the following conditions
305  * are met:
306  * 1. Redistributions of source code must retain the above copyright
307  *    notice, this list of conditions and the following disclaimer.
308  * 2. Redistributions in binary form must reproduce the above copyright
309  *    notice, this list of conditions and the following disclaimer in the
310  *    documentation and/or other materials provided with the distribution.
311  * 4. Neither the name of the University nor the names of its contributors
312  *    may be used to endorse or promote products derived from this software
313  *    without specific prior written permission.
314  *
315  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
316  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
317  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
318  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
319  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
320  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
321  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
322  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
323  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
324  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
325  * SUCH DAMAGE.
326  *
327  *      @(#)time.h      8.5 (Berkeley) 5/4/95
328  * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
329  */
330 #ifndef timespeccmp
331 #define timespeccmp(tvp, uvp, cmp)                                      \
332         (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
333             ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :                       \
334             ((tvp)->tv_sec cmp (uvp)->tv_sec))
335 #endif /*timespeccmp*/
336
337
338
339 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
340 #ifdef st_mtime
341   return timespeccmp(&a->st_mtim, &b->st_mtim, >);
342 #else
343   return a->st_mtime > &b->st_mtime;
344 #endif
345 }
346
347 static bool check_garbage_vs(const struct stat *started) {
348   struct stat script_stab;
349   struct stat sock_stab;
350   int r;
351
352   r = lstat(script, &script_stab);
353   if (r) err(127,"lstat script (%s)",script);
354
355   if (stab_isnewer(&script_stab, &sock_stab))
356     return 1;
357
358   if (S_ISLNK(script_stab.st_mode)) {
359     r = stat(script, &script_stab);
360     if (r) err(127,"stat script (%s0",script);
361
362     if (stab_isnewer(&script_stab, &sock_stab))
363       return 1;
364   }
365
366   return 0;
367 }
368
369 static bool check_garbage(void) {
370   struct stat sock_stab;
371   int r;
372
373   r = lstat(socket_path, &sock_stab);
374   if (r) {
375     if ((errno == ENOENT))
376       return 0; /* well, no garbage then */
377     err(127,"stat socket (%s)",socket_path);
378   }
379
380   return check_garbage_vs(&sock_stab);
381 }
382
383 static void tidy_garbage(void) {
384   /* We lock l<ident> and re-check.  The effect of this is that each
385    * stale socket is removed only once.  So unless multiple updates to
386    * the script happen rapidly, we can't be racing with the cgi-fcgi
387    * (which is recreating the socket */
388   int lockfd = -1;
389   int r;
390
391   const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
392
393   lockfd = open(lock_path, O_CREAT|O_RDWR, 0600);
394   if (lockfd<0) err(127,"create lock (%s)", lock_path);
395
396   r = flock(lockfd, LOCK_EX);
397   if (r) err(127,"lock lock (%s)", lock_path);
398
399   if (check_garbage()) {
400     r = unlink(socket_path);
401     if (r) {
402       if (!(errno == ENOENT))
403         err(127,"remove out-of-date socket (%s)", socket_path);
404     }
405   }
406
407   r = close(lockfd);
408   if (r) errx(127,"close lock (%s)", lock_path);
409 }
410
411 static void shbang_opts(const char *const **argv_io,
412                         const struct cmdinfo *cmdinfos) {
413   myopt(argv_io, cmdinfos);
414
415   interp = *(*argv_io)++;
416   if (!interp) errx(127,"need interpreter argument");
417 }
418
419 int main(int argc, const char *const *argv) {
420   const char *smashedopt, *us;
421
422   us = argv[0];
423
424   if (argv>=4 && !strcmp(argv[1],"--stage2")) {
425     ++argv;
426     stage2 = 1;
427
428     int stderrfd = atoi(*++argv);
429     r = dup2(stderrfd, 2);
430     assert(r==2);
431
432     r = open("/dev/null",O_WRONLY);
433     if (r<0) err(127,"open /dev/null as stdout");
434     if (r>=3) close(r);
435     else if (r!=) errx(127,"open /dev/null gave bad fd %d",r);
436
437     sock_path = *++argv;
438   }
439
440   if (argc>=2 &&
441       (smashedopt = argv[1]) &&
442       smashedopt[0]=='-' &&
443       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
444     /* single argument containg all the options and <interp> */
445     argv += 2; /* eat argv[0] and smashedopt */
446     const char *split_args[MAX_OPTS+1];
447     int split_argc = 0;
448     split_args[split_argc++] = argv[0];
449     for (;;) {
450       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
451       split_args[split_argc++] = smashedopt;
452       if (smashedopt[0] != '-') /* never true on first iteration */
453         break;
454       char *delim = strchr(smashedopt,' ');
455       if (!delim) delim = strchr(smashedopt,',');
456       if (!delim)
457         errx(127,"combined arg lacks <interpreter>");
458       *delim = 0;
459       smashedopt = delim+1;
460     }
461     assert(split_argc <= MAX_OPTS);
462     split_args[split_argc++] = 0;
463
464     const char *const *split_argv = split_args;
465
466     shbang_opts(&split_argv, cmdinfos);
467     /* sets interp */
468     if (!split_argv) errx(127,"combined arg too many non-option arguments");
469   } else {
470     shbang_opts(&argv, cmdinfos);
471   }
472
473   script = *argv++;
474   if (!script) errx(127,"need script argument");
475   if (*argv) errx(127,"too many arguments");
476
477   if (!stage2) {
478     
479     find_socket_path();
480
481     bool isgarbage = check_garbage();
482
483     if (debugmode) {
484       printf("socket: %s\n",socket_path);
485       printf("interp: %s\n",interp);
486       printf("script: %s\n",script);
487       printf("garbage: %d\n",isgarbage);
488       exit(0);
489     }
490
491     if (isgarbage)
492       tidy_garbage();
493
494     execlp("cgi-fcgi",
495            "cgi-fcti", "-connect", socket_path,
496            us, "--stage2",
497            m_asprintf("-c%d", check_interval),
498            m_asprintf("%d", copy_stderr), socket_path,
499            interp, script,
500            (char*)0);
501     err(127,"exec cgi-fcgi");
502     
503   } else { /*stage2*/
504
505     check_baseline_time();
506     become_pgrp();
507     setup_handlers();
508     spawn_script();
509     queue_alarm();
510     await_something();
511     abort();
512
513   }
514 }
515
516 /* stage2 */
517
518 /* It is most convenient to handle the recheck timeout, as well as
519  * child death, in signal handlers.  Our signals all block each other,
520  * and the main program has signals blocked except in sigsuspend, so
521  * we don't need to worry about async-signal-safety, or errno. */
522
523 static struct stab baseline_time;
524 static pid_t script_child, stage2_pgrp;
525 static bool out_of_date;
526
527 void check_baseline_time(void) {
528 #ifdef st_mtime
529   int r = clock_gettime(CLOCK_REALTIME, &baselime_time.st_mtim);
530   if (r) err(127,"(stage2) clock_gettime");
531 #else
532   baseline_time.st_mtime = time(NULL);
533   if (baseline_time.st_mtime == (time_t)-1) err(127,"(stage2) time()");
534 #endif
535 }
536
537 static void become_pgrp(void) {
538   int r;
539
540   stage2_pgrp = getpid();
541
542   r = setpgid(0,0);
543   if (r) err(127,"(stage2) setpgid");
544 }
545
546 static void setup_handlers(void) {
547   struct sigaction sa;
548   int r;
549
550   r = atexit(atexit_handler);
551   if (r) err(127,"(stage2) atexit");
552
553   sigemptyset(&sa.sa_mask);
554   sigaddset(&sa.sa_mask, SIGALRM);
555   sigaddset(&sa.sa_mask, SIGCHLD);
556   sa.sa_flags = 0;
557
558   r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
559   if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
560
561   sa.sa_handler = alarm_handler;
562   r = sigaction(SIGALRM, &sa, 0);
563   if (r) err(127,"(stage2) sigaction SIGALRM");
564
565   sa.sa_flags |= SA_NOCLDSTOP;
566   sa.sa_handler = child_handler;
567   r = sigaction(SIGCHLD, &sa, 0);
568   if (r) err(127,"(stage2) sigaction SIGCHLD");
569 }
570
571 static void atexit_handler(void) {
572   int r;
573
574   sighandler_t sigr = signal(SIGTERM,SIG_IGN);
575   if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
576
577   r = killpg(stage2_pgrp,SIGTERM);
578   if (r) warn("(stage) killpg failed");
579 }
580
581 static void alarm_handler(int dummy) {
582   if (out_of_date)
583     /* second timeout */
584     exit(0); /* transfers control to atexit_handler */
585
586   out_of_date = check_garbage_vs(&baseline_time);
587   queue_alarm();
588 }
589
590 static void spawn_script(void) {
591   script_child = fork();
592   if (script_child == (pid_t)-1) err(127,"(stage2) fork");
593   if (!script_child) {
594     execlp(interp,
595            interp, script, (char*)0);
596     err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
597   }
598 }
599
600 static void queue_alarm(void) {
601   alarm(check_interval);
602 }