chiark / gitweb /
prefork: Provide PREFORK_CMDINFOS
[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  *
5  * Usages:
6  *   cgi-fcgi-interp  [<option> ..] <interpreter>  <script> [<ignored> ...]
7  *   cgi-fcgi-interp  [<option>,..],<interpreter>  <script> [<ignored> ...]
8  *   cgi-fcgi-interp '[<option> ..] <interpreter>' <script> [<ignored> ...]
9  */
10 /*
11  * cgi-fcgi-interp.[ch] - Convenience wrapper for cgi-fcgi
12  *
13  * Copyright 2016 Ian Jackson
14  * Copyright 1982,1986,1993 The Regents of the University of California
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public
27  * License along with this file; if not, consult the Free Software
28  * Foundation's website at www.fsf.org, or the GNU Project website at
29  * www.gnu.org.
30  *
31  * See below for a BSD 3-clause notice regarding timespeccmp.
32  */
33 /*
34  * The result is a program which looks, when executed via the #!
35  * line, like a CGI program.  But the script inside will be executed
36  * via <interpreter> in an fcgi context.
37  *
38  * Options:
39  *
40  *  <interpreter>
41  *          The real interpreter to use.  Eg "perl".  Need not
42  *          be an absolute path; will be fed to execvp.
43  *
44  *  -G<ident-info>
45  *          Add <ident-info> to the unique identifying information for
46  *          this fcgi program.  May be repeated; order is significant.
47  *
48  *  -E<ident-info-env-var>
49  *          Look <ident-info-env-var> up in the environment and add
50  *          <ident-info-env-var>=<value> as if specified with -G.  If
51  *          the variable is unset in the environment, it is as if
52  *          -G<ident-info-env-var> was specified.
53  *
54  *  -g<ident>
55  *          Use <ident> rather than hex(sha256(<interp>\0<script>\0))
56  *          as the basename of the leafname of the fcgi rendezvous
57  *          socket.  If <ident> contains only hex digit characters it
58  *          ought to be no more than 32 characters.  <ident> should
59  *          not contain spaces or commas (see below).
60  *
61  *  -M<numservers>
62  *         Start <numservers> instances of the program.  This
63  *         determines the maximum concurrency.  (Note that unlike
64  *         speedy, the specified number of servers is started
65  *         right away.)  The default is 4.
66  *
67  *  -c<interval>
68  *         Stale server check interval, in seconds.  The worker
69  *         process group will get a SIGTERM when it is no longer
70  *         needed to process new requests.  Ideally it would continue
71  *         to serve any existing requests.  The SIGTERM will arrive no
72  *         earlier than <interval> after the last request arrived at
73  *         the containing webserver.  Default is 300.
74  *
75  *  -D
76  *         Debug mode.  Do not actually run program.  Instead, print
77  *         out what we would do.
78  *
79  * <options> and <interpreter> can be put into a single argument
80  * to cgi-fcgi-interp, separated by spaces or commas.  <interpreter>
81  * must come last.
82  *
83  * cgi-fcgi-interp automatically expires old sockets, including
84  * ones where the named script is out of date.
85  */
86 /*
87  * Uses one of two directories
88  *   /var/run/user/<UID>/cgi-fcgi-interp/
89  *   ~/.cgi-fcgi-interp/<node>/
90  * and inside there uses these paths
91  *   s<ident>
92  *   l<ident>    used to lock around garbage collection
93  *
94  * If -M<ident> is not specified then an initial substring of the
95  * lowercase hex of the sha256 of <interp>\0<script>\0 is
96  * used.  The substring is chosen so that the whole path is 10 bytes
97  * shorter than sizeof(sun_path).  But always at least 33 characters.
98  *
99  * <node> is truncated at the first `.' and after the first 32
100  * characters.
101  *
102  * Algorithm:
103  *  - see if /var/run/user exists
104  *       if so, lstat /var/run/user/<UID> and check that
105  *         we own it and it's X700; if not, fail
106  *         if it's ok then <base> is /var/run/user/<UID>
107  *       otherwise, look for and maybe create ~/.cgi-fcgi-interp
108  *         (where ~ is HOME or from getpwuid)
109  *         and then <base> is ~/.cgi-fcgi-interp/<node>
110  *  - calculate pathname (checking <ident> length is OK)
111  *  - check for and maybe create <base>
112  *  - stat and lstat the <script>
113  *  - stat the socket and check its timestamp
114  *       if it is too old, unlink it
115  *  - dup stderr, mark no cloexec
116  *  - set CHIARKUTILS_CGIFCGIINTERP_STAGE2=<stderr-copy-fd>
117  *  - run     cgi-fcgi -connect SOCKET <script>
118  *
119  * When CHIARKUTILS_CGIFCGIINTERP_STAGE2 is set, --stage2 does this:
120  *  - dup2 <was-stderr> to fd 2
121  *  - open /dev/null and expect fd 1 (and if not, close it)
122  *  - become a new process group
123  *  - lstat <socket> to find its inum, mtime
124  *  - fork/exec <interp> <script>
125  *  - periodically lstat <interp> and <script> and
126  *      if mtime is newer than our start time
127  *      kill process group (at second iteration)
128  */
129
130 #include "prefork.h"
131
132 #define STAGE2_VAR "CHIARKUTILS_CGIFCGIINTERP_STAGE2"
133
134 static const char *stage2;
135
136 const char our_name[] = "cgi-fcgi-interp";
137
138 static int numservers=4, debugmode;
139 static int check_interval=300;
140
141 const struct cmdinfo cmdinfos[]= {
142   PREFORK_CMDINFOS
143   { 0, 'M',   1, .call=of_iassign,  .iassignto= &numservers            },
144   { 0, 'D',   0,                    .iassignto= &debugmode,    .arg= 1 },
145   { 0, 'c',   1, .call=of_iassign,  .iassignto= &check_interval        },
146   { 0 }
147 };
148
149 void fusagemessage(FILE *f) {
150   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
151 }
152
153 static int stderr_copy;
154
155 static void make_stderr_copy(void) {
156   stderr_copy = dup(2);
157   if (stderr_copy < 0) diee("dup stderr (for copy for stage2)");
158 }
159
160 static void prep_stage2(void) {
161   int r;
162   
163   const char *stage2_val = m_asprintf("%d", stderr_copy);
164   r = setenv(STAGE2_VAR, stage2_val, 1);
165   if (r) diee("set %s (to announce to stage2)", STAGE2_VAR);
166 }
167
168 #ifdef st_mtime
169
170 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
171   if (debugmode)
172     fprintf(stderr,"stab_isnewer mtim %lu.%06lu %lu.06%lu\n",
173             (unsigned long)a->st_mtim.tv_sec,
174             (unsigned long)a->st_mtim.tv_nsec,
175             (unsigned long)b->st_mtim.tv_sec,
176             (unsigned long)b->st_mtim.tv_nsec);
177   return timespeccmp(&a->st_mtim, &b->st_mtim, >);
178 }
179
180 static void stab_mtimenow(struct stat *out) {
181   int r = clock_gettime(CLOCK_REALTIME, &out->st_mtim);
182   if (r) diee("(stage2) clock_gettime");
183   if (debugmode)
184     fprintf(stderr,"stab_mtimenow mtim %lu.%06lu\n",
185             (unsigned long)out->st_mtim.tv_sec,
186             (unsigned long)out->st_mtim.tv_nsec);
187 }
188
189 #else /* !defined(st_mtime) */
190
191 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
192   if (debugmode)
193     fprintf(stderr,"stab_isnewer mtime %lu %lu\n",
194             (unsigned long)a->st_mtime,
195             (unsigned long)b->st_mtime);
196   return a->st_mtime > b->st_mtime;
197 }
198
199 static void stab_mtimenow(struct stat *out) {
200   out->st_mtime = time(NULL);
201   if (out->st_mtime == (time_t)-1) diee("(stage2) time()");
202   if (debugmode)
203     fprintf(stderr,"stab_mtimenow mtime %lu\n",
204             (unsigned long)out->st_mtime);
205 }
206
207 #endif /* !defined(st_mtime) */
208
209 static bool check_garbage_vs(const struct stat *started) {
210   struct stat script_stab;
211   int r;
212
213   r = lstat(script, &script_stab);
214   if (r) diee("lstat script (%s)",script);
215
216   if (stab_isnewer(&script_stab, started))
217     return 1;
218
219   if (S_ISLNK(script_stab.st_mode)) {
220     r = stat(script, &script_stab);
221     if (r) diee("stat script (%s0",script);
222
223     if (stab_isnewer(&script_stab, started))
224       return 1;
225   }
226
227   return 0;
228 }
229
230 static bool check_garbage(void) {
231   struct stat sock_stab;
232   int r;
233
234   r = lstat(socket_path, &sock_stab);
235   if (r) {
236     if ((errno == ENOENT))
237       return 0; /* well, no garbage then */
238     diee("stat socket (%s)",socket_path);
239   }
240
241   return check_garbage_vs(&sock_stab);
242 }
243
244 static void tidy_garbage(void) {
245   /* We lock l<ident> and re-check.  The effect of this is that each
246    * stale socket is removed only once.  So unless multiple updates to
247    * the script happen rapidly, we can't be racing with the cgi-fcgi
248    * (which is recreating the socket */
249   int lockfd = -1;
250   int r;
251
252   lockfd = acquire_lock();
253
254   if (check_garbage()) {
255     r = unlink(socket_path);
256     if (r) {
257       if (!(errno == ENOENT))
258         diee("remove out-of-date socket (%s)", socket_path);
259     }
260   }
261
262   r = close(lockfd);
263   if (r) diee("close lock (%s)", lock_path);
264 }
265
266 /* stage2 predeclarations */
267 static void record_baseline_time(void);
268 static void become_pgrp(void);
269 static void setup_handlers(void);
270 static void spawn_script(void);
271 static void queue_alarm(void);
272 static void start_logging(void);
273 static void await_something(void);
274
275 int main(int unused_argc, const char *const *argv) {
276   int r;
277
278   stage2 = getenv(STAGE2_VAR);
279   if (stage2) {
280     int stderrfd = atoi(stage2);
281     assert(stderrfd>2);
282
283     r = dup2(stderrfd, 2);
284     assert(r==2);
285
286     r = open("/dev/null",O_WRONLY);
287     if (r<0) diee("open /dev/null as stdout");
288     if (r>=3) close(r);
289     else if (r!=1) die("open /dev/null for stdout gave bad fd %d",r);
290
291     r = close(stderrfd);
292     if (r) diee("close saved stderr fd");
293   }
294
295   process_opts(&argv);
296   if (!script) badusage("need script argument");
297
298   if (!stage2) {
299     
300     find_socket_path();
301
302     bool isgarbage = check_garbage();
303
304     if (debugmode) {
305       printf("socket: %s\n",socket_path);
306       printf("interp: %s\n",interp);
307       printf("script: %s\n",script);
308       printf("garbage: %d\n",isgarbage);
309       exit(0);
310     }
311
312     if (isgarbage)
313       tidy_garbage();
314
315     make_stderr_copy();
316     prep_stage2();
317
318     execlp("cgi-fcgi",
319            "cgi-fcgi", "-connect", socket_path,
320            script,
321            m_asprintf("%d", numservers),
322            (char*)0);
323     diee("exec cgi-fcgi");
324     
325   } else { /*stage2*/
326
327     record_baseline_time();
328     become_pgrp();
329     setup_handlers();
330     spawn_script();
331     queue_alarm();
332     start_logging();
333     await_something();
334     abort();
335
336   }
337 }
338
339 /* stage2 */
340
341 /* It is most convenient to handle the recheck timeout, as well as
342  * child death, in signal handlers.  Our signals all block each other,
343  * and the main program has signals blocked except in sigsuspend, so
344  * we don't need to worry about async-signal-safety, or errno. */
345
346 static struct stat baseline_time;
347 static pid_t script_child, stage2_pgrp;
348 static bool out_of_date;
349 static int errpipe;
350
351 static void record_baseline_time(void) {
352   stab_mtimenow(&baseline_time);
353 }
354
355 static void become_pgrp(void) {
356   int r;
357
358   stage2_pgrp = getpid();
359
360   r = setpgid(0,0);
361   if (r) diee("(stage2) setpgid");
362 }
363
364 static void atexit_handler(void) {
365   int r;
366
367   sighandler_t sigr = signal(SIGTERM,SIG_IGN);
368   if (sigr == SIG_ERR) warninge("(stage2) signal(SIGTERM,SIG_IGN)");
369
370   r = killpg(stage2_pgrp,SIGTERM);
371   if (r) warninge("(stage) killpg failed");
372 }
373
374 static void alarm_handler(int dummy) {
375   if (out_of_date)
376     /* second timeout */
377     exit(0); /* transfers control to atexit_handler */
378
379   out_of_date = check_garbage_vs(&baseline_time);
380   queue_alarm();
381 }
382
383 static void child_handler(int dummy) {
384   for (;;) {
385     int status;
386     pid_t got = waitpid(-1, &status, WNOHANG);
387     if (got == (pid_t)-1) diee("(stage2) waitpid");
388     if (got != script_child) {
389       warning("(stage2) waitpid got status %d for unknown child [%lu]",
390               status, (unsigned long)got);
391       continue;
392     }
393     if (WIFEXITED(status)) {
394       int v = WEXITSTATUS(status);
395       if (v) warning("program failed with error exit status %d", v);
396       exit(status);
397     } else if (WIFSIGNALED(status)) {
398       int s = WTERMSIG(status);
399       warning("program died due to fatal signal %s%s",
400               strsignal(s), WCOREDUMP(status) ? " (core dumped" : "");
401       assert(status & 0xff);
402       exit(status & 0xff);
403     } else {
404       die("program failed with crazy wait status %#x", status);
405     }
406   }
407   exit(127);
408 }
409
410 static void setup_handlers(void) {
411   struct sigaction sa;
412   int r;
413
414   r = atexit(atexit_handler);
415   if (r) diee("(stage2) atexit");
416
417   sigemptyset(&sa.sa_mask);
418   sigaddset(&sa.sa_mask, SIGALRM);
419   sigaddset(&sa.sa_mask, SIGCHLD);
420   sa.sa_flags = 0;
421
422   r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
423   if (r) diee("(stage2) sigprocmask(SIG_BLOCK,)");
424
425   sa.sa_handler = alarm_handler;
426   r = sigaction(SIGALRM, &sa, 0);
427   if (r) diee("(stage2) sigaction SIGALRM");
428
429   sa.sa_flags |= SA_NOCLDSTOP;
430   sa.sa_handler = child_handler;
431   r = sigaction(SIGCHLD, &sa, 0);
432   if (r) diee("(stage2) sigaction SIGCHLD");
433 }
434
435 static void spawn_script(void) {
436   int r;
437   int errpipes[2];
438
439   r = pipe(errpipes);
440   if (r) diee("(stage2) pipe");
441
442   script_child = fork();
443   if (script_child == (pid_t)-1) diee("(stage2) fork");
444   if (!script_child) {
445     r = close(errpipes[0]);
446     if (r) diee("(stage2 child) close errpipes[0]");
447
448     r = dup2(errpipes[1], 2);
449     if (r != 2) diee("(stage2 child) dup2 stderr");
450
451     execlp(interp,
452            interp, script, (char*)0);
453     diee("(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
454   }
455
456   r = close(errpipes[1]);
457   if (r) diee("(stage2) close errpipes[1]");
458
459   errpipe = errpipes[0];
460   r = fcntl(errpipe, F_SETFL, O_NONBLOCK);
461   if (r) diee("(stage2) set errpipe nonblocking");
462 }
463
464 static void queue_alarm(void) {
465   alarm(check_interval);
466 }
467
468 static void start_logging(void) {
469   int r;
470
471   openlog(script, LOG_NOWAIT|LOG_PID, LOG_USER);
472   logging = 1;
473   r = dup2(1,2);
474   if (r!=2) diee("dup2 stdout to stderr");
475 }
476
477 static void errpipe_readable(void) {
478   static char buf[1024];
479   static int pending;
480
481   /* %: does not contain newlines
482    * _: empty (garbage)
483    */ 
484
485   /*           %%%%%%%%%%%__________________ */
486   /*                      ^ pending          */
487
488   for (;;) {
489     int avail = sizeof(buf) - pending;
490     ssize_t got = read(errpipe, buf+pending, avail);
491     if (got==-1) {
492       if (errno==EINTR) continue;
493       else if (errno==EWOULDBLOCK || errno==EAGAIN) return;
494       else diee("(stage2) errpipe read");
495       got = 0;
496     } else if (got==0) {
497       warning("program closed its stderr fd");
498       errpipe = -1;
499       return;
500     }
501     int scanned = pending;
502     pending += got;
503     int eaten = 0;
504     for (;;) {
505       const char *newline = memchr(buf+scanned, '\n', pending-scanned);
506       int printupto, eat;
507       if (newline) {
508         printupto = newline-buf;
509         eat = printupto + 1;
510       } else if (!eaten && pending==sizeof(buf)) { /* overflow */
511         printupto = pending;
512         eat = printupto;
513       } else {
514         break;
515       }
516       syslog(LOG_ERR,"stderr: %.*s", printupto-eaten, buf+eaten);
517       eaten += eat;
518       scanned = eaten;
519     }
520     pending -= eaten;
521     memmove(buf, buf+eaten, pending);
522   }
523 }     
524
525 static void await_something(void) {
526   int r;
527   sigset_t mask;
528   sigemptyset(&mask);
529
530   for (;;) {
531     fd_set rfds;
532     FD_ZERO(&rfds);
533     if (errpipe >= 0)
534       FD_SET(errpipe, &rfds);
535     r = pselect(errpipe+1, &rfds,0,0, 0, &mask);
536     if (r==-1) {
537       if (errno != EINTR) diee("(stage2) sigsuspend");
538       continue;
539     }
540     assert(r>0);
541     assert(FD_ISSET(errpipe, &rfds));
542     errpipe_readable();
543   }
544 }