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