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>
7 * cgi-fcgi-interp.[ch] - C helpers common to the whole of chiark-utils
9 * Copyright 2016 Ian Jackson
10 * Copyright 1982,1986,1993 The Regents of the University of California
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.
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.
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
27 * See below for a BSD 3-clause notice regarding timespeccmp.
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.
37 * The real interpreter to use. Eg "perl". Need not
38 * be an absolute path; will be fed to execvp.
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).
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.
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.
62 * Debug mode. Do not actually run program. Instead, print
63 * out what we would do.
65 * <options> and <interpreter> can be put into a single argument
66 * to cgi-fcgi-interp, separated by spaces or commas. <interpreter>
69 * cgi-fcgi-interp automatically expires old sockets, including
70 * ones where the named script is out of date.
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
78 * l<ident> used to lock around garbage collection
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.
85 * <node> is truncated at the first `.' and after the first 32
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>
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)
126 #include <sys/types.h>
127 #include <sys/stat.h>
128 #include <sys/utsname.h>
129 #include <sys/socket.h>
131 #include <sys/file.h>
138 #include <sys/wait.h>
140 #include <nettle/sha.h>
144 #define die common_die
145 #define diee common_diee
147 #define MINHEXHASH 33
148 #define STAGE2_VAR "CHIARKUTILS_CGIFCGIINTERP_STAGE2"
150 static const char *interp, *ident;
151 static int numservers=4, debugmode;
152 static int check_interval=300;
156 void diee(const char *m) {
157 err(127, "error: %s failed", m);
160 static void fusagemessage(FILE *f) {
161 fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
164 void usagemessage(void) { fusagemessage(stderr); }
166 static void of_help(const struct cmdinfo *ci, const char *val) {
167 fusagemessage(stdout);
168 if (ferror(stdout)) diee("write usage message to stdout");
172 static void of_iassign(const struct cmdinfo *ci, const char *val) {
175 errno= 0; v= strtol(val,&ep,10);
176 if (!*val || *ep || errno || v<INT_MIN || v>INT_MAX)
177 badusage("bad integer argument `%s' for --%s",val,ci->olong);
183 static const struct cmdinfo cmdinfos[]= {
184 { "help", 0, .call= of_help },
185 { 0, 'g', 1, .sassignto= &ident },
186 { 0, 'M', 1, .call=of_iassign, .iassignto= &numservers },
187 { 0, 'D', 0, .iassignto= &debugmode, .arg= 1 },
188 { 0, 'c', 1, .call=of_iassign, .iassignto= &check_interval },
193 static const char *run_base, *script, *socket_path;
194 static const char *run_base_mkdir_p;
195 static int stderr_copy;
197 static bool find_run_base_var_run(void) {
202 try = m_asprintf("%s/%lu", "/var/run/user", us);
203 r = lstat(try, &stab);
205 if (errno == ENOENT ||
209 return 0; /* oh well */
210 diee("stat /var/run/user/UID");
212 if (!S_ISDIR(stab.st_mode)) {
213 warnx("%s not a directory, falling back to ~\n", try);
216 if (stab.st_uid != us) {
217 warnx("%s not owned by uid %lu, falling back to ~\n", try,
221 if (stab.st_mode & 0077) {
222 warnx("%s writeable by group or other, falling back to ~\n", try);
225 run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
229 static bool find_run_base_home(void) {
235 pw = getpwuid(us); if (!pw) diee("getpwent(uid)");
237 r = uname(&ut); if (r) diee("uname(2)");
238 dot = strchr(ut.nodename, '.');
240 if (sizeof(ut.nodename) > 32)
243 run_base_mkdir_p = m_asprintf("%s/%s", pw->pw_dir, ".cgi-fcgi-interp");
244 try = m_asprintf("%/%s", run_base_mkdir_p, ut.nodename);
249 static void find_socket_path(void) {
250 struct sockaddr_un sun;
253 us = getuid(); if (us==(uid_t)-1) diee("getuid");
255 find_run_base_var_run() ||
256 find_run_base_home() ||
259 int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
262 if (maxidentlen < MINHEXHASH)
263 errx(127,"base directory `%s'"
264 " leaves only %d characters for id hash"
265 " which is too little (<%d)",
266 run_base, maxidentlen, MINHEXHASH);
268 int identlen = maxidentlen > 64 ? 64 : maxidentlen;
269 char *hexident = xmalloc(identlen + 2);
270 struct sha256_ctx sc;
271 unsigned char bbuf[32];
275 sha256_update(&sc,strlen(interp)+1,interp);
276 sha256_update(&sc,strlen(script)+1,script);
277 sha256_digest(&sc,sizeof(bbuf),bbuf);
279 for (i=0; i<identlen; i += 2)
280 sprintf(hexident+i, "%02x", bbuf[i/2]);
282 hexident[identlen] = 0;
286 if (strlen(ident) > maxidentlen)
287 errx(127, "base directory `%s' plus ident `%s' too long"
288 " (with spare) for socket (max ident %d)\n",
289 run_base, ident, maxidentlen);
291 r = mkdir(run_base, 0700);
292 if (r && errno==ENOENT && run_base_mkdir_p) {
293 r = mkdir(run_base_mkdir_p, 0700);
294 if (r) err(127,"mkdir %s (since %s was ENOENT)",run_base_mkdir_p,run_base);
295 r = mkdir(run_base, 0700);
298 if (!(errno == EEXIST))
299 err(127,"mkdir %s",run_base);
302 socket_path = m_asprintf("%s/s%s",run_base,ident);
306 * Regarding the macro timespeccmp:
308 * Copyright (c) 1982, 1986, 1993
309 * The Regents of the University of California. All rights reserved.
311 * Redistribution and use in source and binary forms, with or without
312 * modification, are permitted provided that the following conditions
314 * 1. Redistributions of source code must retain the above copyright
315 * notice, this list of conditions and the following disclaimer.
316 * 2. Redistributions in binary form must reproduce the above copyright
317 * notice, this list of conditions and the following disclaimer in the
318 * documentation and/or other materials provided with the distribution.
319 * 4. Neither the name of the University nor the names of its contributors
320 * may be used to endorse or promote products derived from this software
321 * without specific prior written permission.
323 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
324 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
325 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
326 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
327 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
328 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
329 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
330 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
331 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
332 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
335 * @(#)time.h 8.5 (Berkeley) 5/4/95
336 * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
339 #define timespeccmp(tvp, uvp, cmp) \
340 (((tvp)->tv_sec == (uvp)->tv_sec) ? \
341 ((tvp)->tv_nsec cmp (uvp)->tv_nsec) : \
342 ((tvp)->tv_sec cmp (uvp)->tv_sec))
343 #endif /*timespeccmp*/
349 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
351 fprintf(stderr,"stab_isnewer mtim %lu.%06lu %lu.06%lu\n",
352 (unsigned long)a->st_mtim.tv_sec,
353 (unsigned long)a->st_mtim.tv_nsec,
354 (unsigned long)b->st_mtim.tv_sec,
355 (unsigned long)b->st_mtim.tv_nsec);
356 return timespeccmp(&a->st_mtim, &b->st_mtim, >);
359 static void stab_mtimenow(struct stat *out) {
360 int r = clock_gettime(CLOCK_REALTIME, &out->st_mtim);
361 if (r) err(127,"(stage2) clock_gettime");
363 fprintf(stderr,"stab_mtimenow mtim %lu.%06lu\n",
364 (unsigned long)out->st_mtim.tv_sec,
365 (unsigned long)out->st_mtim.tv_nsec);
368 #else /* !defined(st_mtime) */
370 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
372 fprintf(stderr,"stab_isnewer mtime %lu %lu\n",
373 (unsigned long)a->st_mtime,
374 (unsigned long)b->st_mtime);
375 return a->st_mtime > &b->st_mtime;
378 static void stab_mtimenow(struct stat *out) {
379 out->st_mtime = time(NULL);
380 if (baseline_time.st_mtime == (time_t)-1) err(127,"(stage2) time()");
382 fprintf(stderr,"stab_mtimenow mtime %lu\n",
383 (unsigned long)out->st_mtime);
386 #endif /* !defined(st_mtime) */
388 static bool check_garbage_vs(const struct stat *started) {
389 struct stat script_stab;
392 r = lstat(script, &script_stab);
393 if (r) err(127,"lstat script (%s)",script);
395 if (stab_isnewer(&script_stab, started))
398 if (S_ISLNK(script_stab.st_mode)) {
399 r = stat(script, &script_stab);
400 if (r) err(127,"stat script (%s0",script);
402 if (stab_isnewer(&script_stab, started))
409 static bool check_garbage(void) {
410 struct stat sock_stab;
413 r = lstat(socket_path, &sock_stab);
415 if ((errno == ENOENT))
416 return 0; /* well, no garbage then */
417 err(127,"stat socket (%s)",socket_path);
420 return check_garbage_vs(&sock_stab);
423 static void tidy_garbage(void) {
424 /* We lock l<ident> and re-check. The effect of this is that each
425 * stale socket is removed only once. So unless multiple updates to
426 * the script happen rapidly, we can't be racing with the cgi-fcgi
427 * (which is recreating the socket */
431 const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
433 lockfd = open(lock_path, O_CREAT|O_RDWR, 0600);
434 if (lockfd<0) err(127,"create lock (%s)", lock_path);
436 r = flock(lockfd, LOCK_EX);
437 if (r) err(127,"lock lock (%s)", lock_path);
439 if (check_garbage()) {
440 r = unlink(socket_path);
442 if (!(errno == ENOENT))
443 err(127,"remove out-of-date socket (%s)", socket_path);
448 if (r) errx(127,"close lock (%s)", lock_path);
451 static void make_stderr_copy(void) {
452 stderr_copy = dup(2);
453 if (stderr_copy < 0) err(127,"dup stderr (for copy for stage2)");
456 static void prep_stage2(void) {
459 const char *stage2_val = m_asprintf("%d", stderr_copy);
460 r = setenv(STAGE2_VAR, stage2_val, 1);
461 if (r) err(127,"set %s (to announce to stage2)", STAGE2_VAR);
464 static void shbang_opts(const char *const **argv_io,
465 const struct cmdinfo *cmdinfos) {
466 myopt(argv_io, cmdinfos);
468 interp = *(*argv_io)++;
469 if (!interp) errx(127,"need interpreter argument");
472 /* stage2 predeclarations */
473 static void record_baseline_time(void);
474 static void become_pgrp(void);
475 static void setup_handlers(void);
476 static void spawn_script(void);
477 static void queue_alarm(void);
478 static void await_something(void);
480 int main(int argc, const char *const *argv) {
481 const char *smashedopt;
484 stage2 = getenv(STAGE2_VAR);
486 int stderrfd = atoi(stage2);
489 r = dup2(stderrfd, 2);
492 r = open("/dev/null",O_WRONLY);
493 if (r<0) err(127,"open /dev/null as stdout");
495 else if (r!=1) errx(127,"open /dev/null for stdout gave bad fd %d",r);
499 (smashedopt = argv[1]) &&
500 smashedopt[0]=='-' &&
501 (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
502 /* single argument containg all the options and <interp> */
503 argv += 2; /* eat argv[0] and smashedopt */
504 const char *split_args[MAX_OPTS+1];
506 split_args[split_argc++] = argv[0];
508 if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
509 split_args[split_argc++] = smashedopt;
510 if (smashedopt[0] != '-') /* never true on first iteration */
512 char *delim = strchr(smashedopt,' ');
513 if (!delim) delim = strchr(smashedopt,',');
515 errx(127,"combined arg lacks <interpreter>");
517 smashedopt = delim+1;
519 assert(split_argc <= MAX_OPTS);
520 split_args[split_argc++] = 0;
522 const char *const *split_argv = split_args;
524 shbang_opts(&split_argv, cmdinfos);
526 if (!split_argv) errx(127,"combined arg too many non-option arguments");
528 shbang_opts(&argv, cmdinfos);
532 if (!script) errx(127,"need script argument");
533 if (*argv) errx(127,"too many arguments");
539 bool isgarbage = check_garbage();
542 printf("socket: %s\n",socket_path);
543 printf("interp: %s\n",interp);
544 printf("script: %s\n",script);
545 printf("garbage: %d\n",isgarbage);
556 "cgi-fcgi", "-connect", socket_path,
558 m_asprintf("%d", numservers),
560 err(127,"exec cgi-fcgi");
564 record_baseline_time();
577 /* It is most convenient to handle the recheck timeout, as well as
578 * child death, in signal handlers. Our signals all block each other,
579 * and the main program has signals blocked except in sigsuspend, so
580 * we don't need to worry about async-signal-safety, or errno. */
582 static struct stat baseline_time;
583 static pid_t script_child, stage2_pgrp;
584 static bool out_of_date;
586 static void record_baseline_time(void) {
587 stab_mtimenow(&baseline_time);
590 static void become_pgrp(void) {
593 stage2_pgrp = getpid();
596 if (r) err(127,"(stage2) setpgid");
599 static void atexit_handler(void) {
602 sighandler_t sigr = signal(SIGTERM,SIG_IGN);
603 if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
605 r = killpg(stage2_pgrp,SIGTERM);
606 if (r) warn("(stage) killpg failed");
609 static void alarm_handler(int dummy) {
612 exit(0); /* transfers control to atexit_handler */
614 out_of_date = check_garbage_vs(&baseline_time);
618 static void child_handler(int dummy) {
621 pid_t got = waitpid(-1, &status, WNOHANG);
622 if (got == (pid_t)-1) err(127,"(stage2) waitpid");
623 if (got != script_child) {
624 warn("(stage2) waitpid got status %d for unknown child [%lu]",
625 status, (unsigned long)got);
628 if (WIFEXITED(status)) {
629 int v = WEXITSTATUS(status);
630 if (v) warn("program failed with error exit status %d", v);
632 } else if (WIFSIGNALED(status)) {
633 int s = WTERMSIG(status);
634 err(status & 0xff, "program died due to fatal signal %s%s",
635 strsignal(s), WCOREDUMP(status) ? " (core dumped" : "");
637 err(127, "program failed with crazy wait status %#x", status);
643 static void setup_handlers(void) {
647 r = atexit(atexit_handler);
648 if (r) err(127,"(stage2) atexit");
650 sigemptyset(&sa.sa_mask);
651 sigaddset(&sa.sa_mask, SIGALRM);
652 sigaddset(&sa.sa_mask, SIGCHLD);
655 r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
656 if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
658 sa.sa_handler = alarm_handler;
659 r = sigaction(SIGALRM, &sa, 0);
660 if (r) err(127,"(stage2) sigaction SIGALRM");
662 sa.sa_flags |= SA_NOCLDSTOP;
663 sa.sa_handler = child_handler;
664 r = sigaction(SIGCHLD, &sa, 0);
665 if (r) err(127,"(stage2) sigaction SIGCHLD");
668 static void spawn_script(void) {
669 script_child = fork();
670 if (script_child == (pid_t)-1) err(127,"(stage2) fork");
673 interp, script, (char*)0);
674 err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
678 static void queue_alarm(void) {
679 alarm(check_interval);
682 static void await_something(void) {
688 r = sigsuspend(&mask);
690 if (errno != EINTR) err(127,"(stage2) sigsuspend");