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