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;
154 static struct sha256_ctx identsc;
158 void diee(const char *m) {
159 err(127, "error: %s failed", m);
162 static void fusagemessage(FILE *f) {
163 fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
166 void usagemessage(void) { fusagemessage(stderr); }
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");
174 static void of_iassign(const struct cmdinfo *ci, const char *val) {
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);
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);
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 },
200 static const char *run_base, *script, *socket_path;
201 static const char *run_base_mkdir_p;
202 static int stderr_copy;
204 static bool find_run_base_var_run(void) {
209 try = m_asprintf("%s/%lu", "/var/run/user", us);
210 r = lstat(try, &stab);
212 if (errno == ENOENT ||
216 return 0; /* oh well */
217 diee("stat /var/run/user/UID");
219 if (!S_ISDIR(stab.st_mode)) {
220 warnx("%s not a directory, falling back to ~\n", try);
223 if (stab.st_uid != us) {
224 warnx("%s not owned by uid %lu, falling back to ~\n", try,
228 if (stab.st_mode & 0077) {
229 warnx("%s writeable by group or other, falling back to ~\n", try);
232 run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
236 static bool find_run_base_home(void) {
242 pw = getpwuid(us); if (!pw) diee("getpwent(uid)");
244 r = uname(&ut); if (r) diee("uname(2)");
245 dot = strchr(ut.nodename, '.');
247 if (sizeof(ut.nodename) > 32)
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);
256 static void find_socket_path(void) {
257 struct sockaddr_un sun;
260 us = getuid(); if (us==(uid_t)-1) diee("getuid");
262 find_run_base_var_run() ||
263 find_run_base_home() ||
266 int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
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);
275 int identlen = maxidentlen > 64 ? 64 : maxidentlen;
276 char *hexident = xmalloc(identlen + 2);
277 unsigned char bbuf[32];
280 ident_addstring(0,interp);
281 ident_addstring(0,script);
282 sha256_digest(&identsc,sizeof(bbuf),bbuf);
284 for (i=0; i<identlen; i += 2)
285 sprintf(hexident+i, "%02x", bbuf[i/2]);
287 hexident[identlen] = 0;
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);
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);
303 if (!(errno == EEXIST))
304 err(127,"mkdir %s",run_base);
307 socket_path = m_asprintf("%s/s%s",run_base,ident);
311 * Regarding the macro timespeccmp:
313 * Copyright (c) 1982, 1986, 1993
314 * The Regents of the University of California. All rights reserved.
316 * Redistribution and use in source and binary forms, with or without
317 * modification, are permitted provided that the following conditions
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.
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
340 * @(#)time.h 8.5 (Berkeley) 5/4/95
341 * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
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*/
354 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
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, >);
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");
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);
373 #else /* !defined(st_mtime) */
375 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
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;
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()");
387 fprintf(stderr,"stab_mtimenow mtime %lu\n",
388 (unsigned long)out->st_mtime);
391 #endif /* !defined(st_mtime) */
393 static bool check_garbage_vs(const struct stat *started) {
394 struct stat script_stab;
397 r = lstat(script, &script_stab);
398 if (r) err(127,"lstat script (%s)",script);
400 if (stab_isnewer(&script_stab, started))
403 if (S_ISLNK(script_stab.st_mode)) {
404 r = stat(script, &script_stab);
405 if (r) err(127,"stat script (%s0",script);
407 if (stab_isnewer(&script_stab, started))
414 static bool check_garbage(void) {
415 struct stat sock_stab;
418 r = lstat(socket_path, &sock_stab);
420 if ((errno == ENOENT))
421 return 0; /* well, no garbage then */
422 err(127,"stat socket (%s)",socket_path);
425 return check_garbage_vs(&sock_stab);
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 */
436 const char *lock_path = m_asprintf("%s/l%s",run_base,ident);
438 lockfd = open(lock_path, O_CREAT|O_RDWR, 0600);
439 if (lockfd<0) err(127,"create lock (%s)", lock_path);
441 r = flock(lockfd, LOCK_EX);
442 if (r) err(127,"lock lock (%s)", lock_path);
444 if (check_garbage()) {
445 r = unlink(socket_path);
447 if (!(errno == ENOENT))
448 err(127,"remove out-of-date socket (%s)", socket_path);
453 if (r) errx(127,"close lock (%s)", lock_path);
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)");
461 static void prep_stage2(void) {
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);
469 static void shbang_opts(const char *const **argv_io,
470 const struct cmdinfo *cmdinfos) {
471 myopt(argv_io, cmdinfos);
473 interp = *(*argv_io)++;
474 if (!interp) errx(127,"need interpreter argument");
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);
485 int main(int argc, const char *const *argv) {
486 const char *smashedopt;
489 stage2 = getenv(STAGE2_VAR);
491 int stderrfd = atoi(stage2);
494 r = dup2(stderrfd, 2);
497 r = open("/dev/null",O_WRONLY);
498 if (r<0) err(127,"open /dev/null as stdout");
500 else if (r!=1) errx(127,"open /dev/null for stdout gave bad fd %d",r);
503 sha256_init(&identsc);
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];
513 split_args[split_argc++] = argv[0];
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 */
519 char *delim = strchr(smashedopt,' ');
520 if (!delim) delim = strchr(smashedopt,',');
522 errx(127,"combined arg lacks <interpreter>");
524 smashedopt = delim+1;
526 assert(split_argc <= MAX_OPTS);
527 split_args[split_argc++] = 0;
529 const char *const *split_argv = split_args;
531 shbang_opts(&split_argv, cmdinfos);
533 if (!split_argv) errx(127,"combined arg too many non-option arguments");
535 shbang_opts(&argv, cmdinfos);
539 if (!script) errx(127,"need script argument");
540 if (*argv) errx(127,"too many arguments");
546 bool isgarbage = check_garbage();
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);
563 "cgi-fcgi", "-connect", socket_path,
565 m_asprintf("%d", numservers),
567 err(127,"exec cgi-fcgi");
571 record_baseline_time();
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. */
589 static struct stat baseline_time;
590 static pid_t script_child, stage2_pgrp;
591 static bool out_of_date;
593 static void record_baseline_time(void) {
594 stab_mtimenow(&baseline_time);
597 static void become_pgrp(void) {
600 stage2_pgrp = getpid();
603 if (r) err(127,"(stage2) setpgid");
606 static void atexit_handler(void) {
609 sighandler_t sigr = signal(SIGTERM,SIG_IGN);
610 if (sigr == SIG_ERR) warn("(stage2) signal(SIGTERM,SIG_IGN)");
612 r = killpg(stage2_pgrp,SIGTERM);
613 if (r) warn("(stage) killpg failed");
616 static void alarm_handler(int dummy) {
619 exit(0); /* transfers control to atexit_handler */
621 out_of_date = check_garbage_vs(&baseline_time);
625 static void child_handler(int dummy) {
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);
635 if (WIFEXITED(status)) {
636 int v = WEXITSTATUS(status);
637 if (v) warn("program failed with error exit status %d", v);
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" : "");
644 err(127, "program failed with crazy wait status %#x", status);
650 static void setup_handlers(void) {
654 r = atexit(atexit_handler);
655 if (r) err(127,"(stage2) atexit");
657 sigemptyset(&sa.sa_mask);
658 sigaddset(&sa.sa_mask, SIGALRM);
659 sigaddset(&sa.sa_mask, SIGCHLD);
662 r = sigprocmask(SIG_BLOCK, &sa.sa_mask, 0);
663 if (r) err(127,"(stage2) sigprocmask(SIG_BLOCK,)");
665 sa.sa_handler = alarm_handler;
666 r = sigaction(SIGALRM, &sa, 0);
667 if (r) err(127,"(stage2) sigaction SIGALRM");
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");
675 static void spawn_script(void) {
676 script_child = fork();
677 if (script_child == (pid_t)-1) err(127,"(stage2) fork");
680 interp, script, (char*)0);
681 err(127,"(stage2) exec interpreter (`%s', for `%s')\n",interp,script);
685 static void queue_alarm(void) {
686 alarm(check_interval);
689 static void await_something(void) {
695 r = sigsuspend(&mask);
697 if (errno != EINTR) err(127,"(stage2) sigsuspend");