chiark / gitweb /
cgi-fcgi-interp: new garbage collection approach, wip compile
[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 static int stderr_copy;
195
196 static bool find_run_base_var_run(void) {
197   struct stat stab;
198   char *try;
199   int r;
200
201   try = m_asprintf("%s/%lu", "/var/run/user", us);
202   r = lstat(try, &stab);
203   if (r<0) {
204     if (errno == ENOENT ||
205         errno == ENOTDIR ||
206         errno == EACCES ||
207         errno == EPERM)
208       return 0; /* oh well */
209     diee("stat /var/run/user/UID");
210   }
211   if (!S_ISDIR(stab.st_mode)) {
212     warnx("%s not a directory, falling back to ~\n", try);
213     return 0;
214   }
215   if (stab.st_uid != us) {
216     warnx("%s not owned by uid %lu, falling back to ~\n", try,
217           (unsigned long)us);
218     return 0;
219   }
220   if (stab.st_mode & 0077) {
221     warnx("%s writeable by group or other, falling back to ~\n", try);
222     return 0;
223   }
224   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
225   return 1;
226 }
227
228 static bool find_run_base_home(void) {
229   struct passwd *pw;
230   struct utsname ut;
231   char *dot, *try;
232   int r;
233
234   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
235
236   r = uname(&ut);   if (r) diee("uname(2)");
237   dot = strchr(ut.nodename, '.');
238   if (dot) *dot = 0;
239   if (sizeof(ut.nodename) > 32)
240     ut.nodename[32] = 0;
241
242   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
243   run_base = try;
244   return 1;
245 }
246
247 static void find_socket_path(void) {
248   struct sockaddr_un sun;
249   int r;
250
251   us = getuid();  if (us==(uid_t)-1) diee("getuid");
252
253   find_run_base_var_run() ||
254     find_run_base_home() ||
255     (abort(),0);
256
257   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
258
259   if (!ident) {
260     if (maxidentlen < MINHEXHASH)
261       errx(127,"base directory `%s'"
262            " leaves only %d characters for id hash"
263            " which is too little (<%d)",
264            run_base, maxidentlen, MINHEXHASH);
265
266     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
267     char *hexident = xmalloc(identlen + 2);
268     struct sha256_ctx sc;
269     unsigned char bbuf[32];
270     int i;
271
272     sha256_init(&sc);
273     sha256_update(&sc,strlen(interp)+1,interp);
274     sha256_update(&sc,strlen(script)+1,script);
275     sha256_digest(&sc,sizeof(bbuf),bbuf);
276
277     for (i=0; i<identlen; i += 2)
278       sprintf(hexident+i, "%02x", bbuf[i/2]);
279
280     hexident[identlen] = 0;
281     ident = hexident;
282   }
283
284   if (strlen(ident) > maxidentlen)
285     errx(127, "base directory `%s' plus ident `%s' too long"
286          " (with spare) for socket (max ident %d)\n",
287          run_base, ident, maxidentlen);
288
289   r = mkdir(run_base, 0700);
290   if (r) {
291     if (!(errno == EEXIST))
292       err(127,"mkdir %s",run_base);
293   }
294
295   socket_path = m_asprintf("%s/g%s",run_base,ident);
296 }  
297
298 /*
299  * Regarding the macro timespeccmp:
300  *
301  * Copyright (c) 1982, 1986, 1993
302  *      The Regents of the University of California.  All rights reserved.
303  *
304  * Redistribution and use in source and binary forms, with or without
305  * modification, are permitted provided that the following conditions
306  * are met:
307  * 1. Redistributions of source code must retain the above copyright
308  *    notice, this list of conditions and the following disclaimer.
309  * 2. Redistributions in binary form must reproduce the above copyright
310  *    notice, this list of conditions and the following disclaimer in the
311  *    documentation and/or other materials provided with the distribution.
312  * 4. Neither the name of the University nor the names of its contributors
313  *    may be used to endorse or promote products derived from this software
314  *    without specific prior written permission.
315  *
316  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
317  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
318  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
319  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
320  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
321  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
322  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
323  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
324  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
325  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
326  * SUCH DAMAGE.
327  *
328  *      @(#)time.h      8.5 (Berkeley) 5/4/95
329  * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
330  */
331 #ifndef timespeccmp
332 #define timespeccmp(tvp, uvp, cmp)                                      \
333         (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
334             ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :                       \
335             ((tvp)->tv_sec cmp (uvp)->tv_sec))
336 #endif /*timespeccmp*/
337
338
339
340 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
341 #ifdef st_mtime
342   return timespeccmp(&a->st_mtim, &b->st_mtim, >);
343 #else
344   return a->st_mtime > &b->st_mtime;
345 #endif
346 }
347
348 static bool check_garbage_vs(const struct stat *started) {
349   struct stat script_stab;
350   struct stat sock_stab;
351   int r;
352
353   r = lstat(script, &script_stab);
354   if (r) err(127,"lstat script (%s)",script);
355
356   if (stab_isnewer(&script_stab, &sock_stab))
357     return 1;
358
359   if (S_ISLNK(script_stab.st_mode)) {
360     r = stat(script, &script_stab);
361     if (r) err(127,"stat script (%s0",script);
362
363     if (stab_isnewer(&script_stab, &sock_stab))
364       return 1;
365   }
366
367   return 0;
368 }
369
370 static bool check_garbage(void) {
371   struct stat sock_stab;
372   int r;
373
374   r = lstat(socket_path, &sock_stab);
375   if (r) {
376     if ((errno == ENOENT))
377       return 0; /* well, no garbage then */
378     err(127,"stat socket (%s)",socket_path);
379   }
380
381   return check_garbage_vs(&sock_stab);
382 }
383
384 static void tidy_garbage(void) {
385   /* We lock l<ident> and re-check.  The effect of this is that each
386    * stale socket is removed only once.  So unless multiple updates to
387    * the script happen rapidly, we can't be racing with the cgi-fcgi
388    * (which is recreating the socket */
389   int lockfd = -1;
390   int r;
391
392   const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
393
394   lockfd = open(lock_path, O_CREAT|O_RDWR, 0600);
395   if (lockfd<0) err(127,"create lock (%s)", lock_path);
396
397   r = flock(lockfd, LOCK_EX);
398   if (r) err(127,"lock lock (%s)", lock_path);
399
400   if (check_garbage()) {
401     r = unlink(socket_path);
402     if (r) {
403       if (!(errno == ENOENT))
404         err(127,"remove out-of-date socket (%s)", socket_path);
405     }
406   }
407
408   r = close(lockfd);
409   if (r) errx(127,"close lock (%s)", lock_path);
410 }
411
412 static void make_stderr_copy(void) {
413   stderr_copy = dup(2);
414   if (stderr_copy < 0) err(127,"dup stderr (for copy for stage2)");
415 }
416
417 static void shbang_opts(const char *const **argv_io,
418                         const struct cmdinfo *cmdinfos) {
419   myopt(argv_io, cmdinfos);
420
421   interp = *(*argv_io)++;
422   if (!interp) errx(127,"need interpreter argument");
423 }
424
425 /* stage2 predeclarations */
426 static void record_baseline_time(void);
427 static void become_pgrp(void);
428 static void setup_handlers(void);
429 static void spawn_script(void);
430 static void queue_alarm(void);
431
432 int main(int argc, const char *const *argv) {
433   const char *smashedopt, *us;
434   int r;
435
436   us = argv[0];
437
438   if (argc>=4 && !strcmp(argv[1],"--stage2")) {
439     ++argv;
440     stage2 = 1;
441
442     int stderrfd = atoi(*++argv);
443     r = dup2(stderrfd, 2);
444     assert(r==2);
445
446     r = open("/dev/null",O_WRONLY);
447     if (r<0) err(127,"open /dev/null as stdout");
448     if (r>=3) close(r);
449     else if (r!=1) errx(127,"open /dev/null for stdout gave bad fd %d",r);
450
451     socket_path = *++argv;
452   }
453
454   if (argc>=2 &&
455       (smashedopt = argv[1]) &&
456       smashedopt[0]=='-' &&
457       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
458     /* single argument containg all the options and <interp> */
459     argv += 2; /* eat argv[0] and smashedopt */
460     const char *split_args[MAX_OPTS+1];
461     int split_argc = 0;
462     split_args[split_argc++] = argv[0];
463     for (;;) {
464       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
465       split_args[split_argc++] = smashedopt;
466       if (smashedopt[0] != '-') /* never true on first iteration */
467         break;
468       char *delim = strchr(smashedopt,' ');
469       if (!delim) delim = strchr(smashedopt,',');
470       if (!delim)
471         errx(127,"combined arg lacks <interpreter>");
472       *delim = 0;
473       smashedopt = delim+1;
474     }
475     assert(split_argc <= MAX_OPTS);
476     split_args[split_argc++] = 0;
477
478     const char *const *split_argv = split_args;
479
480     shbang_opts(&split_argv, cmdinfos);
481     /* sets interp */
482     if (!split_argv) errx(127,"combined arg too many non-option arguments");
483   } else {
484     shbang_opts(&argv, cmdinfos);
485   }
486
487   script = *argv++;
488   if (!script) errx(127,"need script argument");
489   if (*argv) errx(127,"too many arguments");
490
491   if (!stage2) {
492     
493     find_socket_path();
494
495     bool isgarbage = check_garbage();
496
497     if (debugmode) {
498       printf("socket: %s\n",socket_path);
499       printf("interp: %s\n",interp);
500       printf("script: %s\n",script);
501       printf("garbage: %d\n",isgarbage);
502       exit(0);
503     }
504
505     if (isgarbage)
506       tidy_garbage();
507
508     make_stderr_copy();
509
510     execlp("cgi-fcgi",
511            "cgi-fcti", "-connect", socket_path,
512            us, "--stage2",
513            m_asprintf("-c%d", check_interval),
514            m_asprintf("%d", stderr_copy), socket_path,
515            interp, script,
516            (char*)0);
517     err(127,"exec cgi-fcgi");
518     
519   } else { /*stage2*/
520
521     record_baseline_time();
522     become_pgrp();
523     setup_handlers();
524     spawn_script();
525     queue_alarm();
526     await_something();
527     abort();
528
529   }
530 }
531
532 /* stage2 */
533
534 /* It is most convenient to handle the recheck timeout, as well as
535  * child death, in signal handlers.  Our signals all block each other,
536  * and the main program has signals blocked except in sigsuspend, so
537  * we don't need to worry about async-signal-safety, or errno. */
538
539 static struct stab baseline_time;
540 static pid_t script_child, stage2_pgrp;
541 static bool out_of_date;
542
543 static void record_baseline_time(void) {
544 #ifdef st_mtime
545   int r = clock_gettime(CLOCK_REALTIME, &baselime_time.st_mtim);
546   if (r) err(127,"(stage2) clock_gettime");
547 #else
548   baseline_time.st_mtime = time(NULL);
549   if (baseline_time.st_mtime == (time_t)-1) err(127,"(stage2) time()");
550 #endif
551 }
552
553 static void become_pgrp(void) {
554   int r;
555
556   stage2_pgrp = getpid();
557
558   r = setpgid(0,0);
559   if (r) err(127,"(stage2) setpgid");
560 }
561
562 static void atexit_handler(void) {
563   int r;
564
565   sighandler_t sigr = signal(SIGTERM,SIG_IGN);
566   if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
567
568   r = killpg(stage2_pgrp,SIGTERM);
569   if (r) warn("(stage) killpg failed");
570 }
571
572 static void alarm_handler(int dummy) {
573   if (out_of_date)
574     /* second timeout */
575     exit(0); /* transfers control to atexit_handler */
576
577   out_of_date = check_garbage_vs(&baseline_time);
578   queue_alarm();
579 }
580
581 static void setup_handlers(void) {
582   struct sigaction sa;
583   int r;
584
585   r = atexit(atexit_handler);
586   if (r) err(127,"(stage2) atexit");
587
588   sigemptyset(&sa.sa_mask);
589   sigaddset(&sa.sa_mask, SIGALRM);
590   sigaddset(&sa.sa_mask, SIGCHLD);
591   sa.sa_flags = 0;
592
593   r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
594   if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
595
596   sa.sa_handler = alarm_handler;
597   r = sigaction(SIGALRM, &sa, 0);
598   if (r) err(127,"(stage2) sigaction SIGALRM");
599
600   sa.sa_flags |= SA_NOCLDSTOP;
601   sa.sa_handler = child_handler;
602   r = sigaction(SIGCHLD, &sa, 0);
603   if (r) err(127,"(stage2) sigaction SIGCHLD");
604 }
605
606 static void spawn_script(void) {
607   script_child = fork();
608   if (script_child == (pid_t)-1) err(127,"(stage2) fork");
609   if (!script_child) {
610     execlp(interp,
611            interp, script, (char*)0);
612     err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
613   }
614 }
615
616 static void queue_alarm(void) {
617   alarm(check_interval);
618 }