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