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