chiark / gitweb /
602ffa62d274a8165a95b3ee65dfed0a911c478b
[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(<script>))
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 /*
74  * Uses one of two directories
75  *   /var/run/user/<UID>/cgi-fcgi-interp/
76  *   ~/.cgi-fcgi-interp/<node>/
77  * and inside there uses these paths
78  *   s<ident>
79  *   l<ident>    used to lock around garbage collection
80  *
81  * If -M<ident> is not specified then an initial substricg of the
82  * lowercase hex of the sha256 of the <script> (ie, our argv[1]) is
83  * used.  The substring is chosen so that the whole path is 10 bytes
84  * shorter than sizeof(sun_path).  But always at least 33 characters.
85  *
86  * <node> is truncated at the first `.' and after the first 32
87  * characters.
88  *
89  * Algorithm:
90  *  - see if /var/run/user exists
91  *       if so, lstat /var/run/user/<UID> and check that
92  *         we own it and it's X700; if not, fail
93  *         if it's ok then <base> is /var/run/user/<UID>
94  *       otherwise, look for and maybe create ~/.cgi-fcgi-interp
95  *         (where ~ is HOME or from getpwuid)
96  *         and then <base> is ~/.cgi-fcgi-interp/<node>
97  *  - calculate pathname (checking <ident> length is OK)
98  *  - check for and maybe create <base>
99  *  - stat and lstat the <script>
100  *  - stat the socket and check its timestamp
101  *       if it is too old, unlink it
102  *  - dup2 stderr, mark no cloexec
103  *  - run     cgi-fcgi -connect SOCKET \
104  *                cgi-fcgi-interp -c<check-interval> \
105  *                --stage2 <was-stderr> <socket> \
106  *                <interp> <script>
107  *
108  * --stage2 does this:
109  *  - dup2 <was-stderr> to fd 2
110  *  - open /dev/null and expect fd 1 (and if not, close it)
111  *  - become a new process group
112  *  - lstat <socket> to find its inum, mtime
113  *  - fork/exec <interp> <script>
114  *  - periodically lstat <socket> and
115  *      if inum, mtime have changed
116  *      kill process group (at second iteration)
117  */
118
119 #include "common.h"
120
121 #include <stdio.h>
122 #include <stdlib.h>
123 #include <string.h>
124 #include <errno.h>
125 #include <stdbool.h>
126 #include <assert.h>
127 #include <limits.h>
128
129 #include <sys/types.h>
130 #include <sys/stat.h>
131 #include <sys/utsname.h>
132 #include <sys/socket.h>
133 #include <sys/un.h>
134 #include <unistd.h>
135 #include <pwd.h>
136 #include <err.h>
137
138 #include <nettle/sha.h>
139
140 #include "myopt.h"
141
142 #define die  common_die
143 #define diee common_diee
144
145 #define MINHEXHASH 33
146
147 static const char *interp, *ident;
148 static int numservers, debugmode;
149
150 void diee(const char *m) {
151   err(127, "error: %s failed", m);
152 }
153
154 static void fusagemessage(FILE *f) {
155   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
156 }
157
158 void usagemessage(void) { fusagemessage(stderr); }
159
160 static void of_help(const struct cmdinfo *ci, const char *val) {
161   fusagemessage(stdout);
162   if (ferror(stdout)) diee("write usage message to stdout");
163   exit(0);
164 }
165
166 static void of_iassign(const struct cmdinfo *ci, const char *val) {
167   long v;
168   char *ep;
169   errno= 0; v= strtol(val,&ep,10);
170   if (!*val || *ep || errno || v<INT_MIN || v>INT_MAX)
171     badusage("bad integer argument `%s' for --%s",val,ci->olong);
172   *ci->iassignto = v;
173 }
174
175 #define MAX_OPTS 5
176
177 static const struct cmdinfo cmdinfos[]= {
178   { "help",   0, .call= of_help               },
179   { 0, 'g',   1, .sassignto= &ident           },
180   { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
181   { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
182   { 0 }
183 };
184
185 static uid_t us;
186 static const char *run_base, *script, *socket_path;
187 static struct stat sock_stab;
188
189 static bool find_run_base_var_run(void) {
190   struct stat stab;
191   char *try;
192   int r;
193
194   try = m_asprintf("%s/%lu", "/var/run/user", us);
195   r = lstat(try, &stab);
196   if (r<0) {
197     if (errno == ENOENT ||
198         errno == ENOTDIR ||
199         errno == EACCES ||
200         errno == EPERM)
201       return 0; /* oh well */
202     diee("stat /var/run/user/UID");
203   }
204   if (!S_ISDIR(stab.st_mode)) {
205     warnx("%s not a directory, falling back to ~\n", try);
206     return 0;
207   }
208   if (stab.st_uid != us) {
209     warnx("%s not owned by uid %lu, falling back to ~\n", try,
210           (unsigned long)us);
211     return 0;
212   }
213   if (stab.st_mode & 0077) {
214     warnx("%s writeable by group or other, falling back to ~\n", try);
215     return 0;
216   }
217   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
218   return 1;
219 }
220
221 static bool find_run_base_home(void) {
222   struct passwd *pw;
223   struct utsname ut;
224   char *dot, *try;
225   int r;
226
227   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
228
229   r = uname(&ut);   if (r) diee("uname(2)");
230   dot = strchr(ut.nodename, '.');
231   if (dot) *dot = 0;
232   if (sizeof(ut.nodename) > 32)
233     ut.nodename[32] = 0;
234
235   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
236   run_base = try;
237   return 1;
238 }
239
240 static void find_socket_path(void) {
241   struct sockaddr_un sun;
242   int r;
243
244   us = getuid();  if (us==(uid_t)-1) diee("getuid");
245
246   find_run_base_var_run() ||
247     find_run_base_home() ||
248     (abort(),0);
249
250   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
251
252   if (!ident) {
253     if (maxidentlen < MINHEXHASH)
254       errx(127,"base directory `%s'"
255            " leaves only %d characters for id hash"
256            " which is too little (<%d)",
257            run_base, maxidentlen, MINHEXHASH);
258
259     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
260     char *hexident = xmalloc(identlen + 2);
261     struct sha256_ctx sc;
262     unsigned char bbuf[32];
263     int i;
264
265     sha256_init(&sc);
266     sha256_update(&sc,strlen(interp)+1,interp);
267     sha256_update(&sc,strlen(script)+1,script);
268     sha256_digest(&sc,sizeof(bbuf),bbuf);
269
270     for (i=0; i<identlen; i += 2)
271       sprintf(hexident+i, "%02x", bbuf[i/2]);
272
273     hexident[identlen] = 0;
274     ident = hexident;
275   }
276
277   if (strlen(ident) > maxidentlen)
278     errx(127, "base directory `%s' plus ident `%s' too long"
279          " (with spare) for socket (max ident %d)\n",
280          run_base, ident, maxidentlen);
281
282   r = mkdir(run_base, 0700);
283   if (r) {
284     if (!(errno == EEXIST))
285       err(127,"mkdir %s",run_base);
286   }
287
288   socket_path = m_asprintf("%s/g%s",run_base,ident);
289 }  
290
291 /*
292  * Regarding the macro timespeccmp:
293  *
294  * Copyright (c) 1982, 1986, 1993
295  *      The Regents of the University of California.  All rights reserved.
296  *
297  * Redistribution and use in source and binary forms, with or without
298  * modification, are permitted provided that the following conditions
299  * are met:
300  * 1. Redistributions of source code must retain the above copyright
301  *    notice, this list of conditions and the following disclaimer.
302  * 2. Redistributions in binary form must reproduce the above copyright
303  *    notice, this list of conditions and the following disclaimer in the
304  *    documentation and/or other materials provided with the distribution.
305  * 4. Neither the name of the University nor the names of its contributors
306  *    may be used to endorse or promote products derived from this software
307  *    without specific prior written permission.
308  *
309  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
310  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
311  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
312  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
313  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
314  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
315  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
316  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
317  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
318  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
319  * SUCH DAMAGE.
320  *
321  *      @(#)time.h      8.5 (Berkeley) 5/4/95
322  * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
323  */
324 #ifndef timespeccmp
325 #define timespeccmp(tvp, uvp, cmp)                                      \
326         (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
327             ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :                       \
328             ((tvp)->tv_sec cmp (uvp)->tv_sec))
329 #endif /*timespeccmp*/
330
331
332
333 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
334 #ifdef st_mtime
335   return timespeccmp(&a->st_mtim, &b->st_mtim, >);
336 #else
337   return a->st_mtime > &b->st_mtime;
338 #endif
339 }
340
341 static bool check_garbage(void) {
342   struct stat script_stab;
343   int r;
344
345   r = lstat(script, &script_stab);
346   if (r) err(127,"lstat script (%s)",script);
347
348   r = lstat(socket_path, &sock_stab);
349   if (r) {
350     if ((errno == ENOENT))
351       return 0; /* well, no garbage then */
352     err(127,"stat socket (%s)",socket_path);
353   }
354
355   if (stab_isnewer(&script_stab, &sock_stab))
356     return 1;
357
358   if (S_ISLNK(script_stab.st_mode)) {
359     r = stat(script, &script_stab);
360     if (r) err(127,"stat script (%s0",script);
361
362     if (stab_isnewer(&script_stab, &sock_stab))
363       return 1;
364   }
365
366   return 0;
367 }
368
369 static void tidy_1_garbage(const char *leaf) {
370   int r;
371   struct sockaddr_un sun;
372
373   int fd = -1;
374
375   memset(&sun,0,sizeof(sun));
376   sun.sun_family = AF_UNIX;
377   r = snprintf(sun.sun_path, sizeof(sun.sun_path), "%s/%s", run_base, leaf);
378   if (r >= sizeof(sun_path))
379     goto cannot;
380
381   fd = socket(AF_UNIX, SOCK_STREAM, 0);
382   if (fd<0) err("create socket for tidying garbage");
383
384   r = fcntl(fd, F_SETFL, O_NONBLOCK);
385   if (r<0) err("set garbage socket nonblocking");
386
387   r = connect(fd, &sun, sizeof(sun));
388   if (r) {
389     if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
390       goto cannot;
391     if (errno != EINPROGRESS)
392       err("connect to garbage socket (%s)", sun.sun_path);
393     /* well, EINPROGRESS, let's just carry on and hope write works */
394   }
395
396   r = write(
397         
398
399 static void tidy_garbage(void) {
400   const char *this_garbage =
401     m_asprintf("%s/g%lu.%lu", run_base,
402                (unsigned long)sock_stab.st_ino,
403                (unsigned long)getpid());
404
405   r = rename(socket_path, this_garbage);
406   if (r) {
407     if (!(errno == ENOENT))
408       err("rename socket from old runner (from %s to %s)",
409           socket_path, this_garbage);
410   }
411
412   DIR *d = opendir(run_base);
413   if (!d) err("open run directory (%d) to clean up garbage", run_base);
414   struct dirent *de;
415   while ((errno = 0, de = readdir(d))) {
416     if (de->d_name[0] != 'g')
417       continue;
418     tidy_1_garbage(de->d_name);
419   }
420   if (errno) err("read run directory (%d) to clean up garbage", run_base);
421   /* 
422   (void)r;
423   if (r) {
424
425   printf("this_garb: %s\n", this_garbage);
426 }
427
428 static void shbang_opts(const char *const **argv_io,
429                         const struct cmdinfo *cmdinfos) {
430   myopt(argv_io, cmdinfos);
431
432   interp = *(*argv_io)++;
433   if (!interp) errx(127,"need interpreter argument");
434 }
435
436 int main(int argc, const char *const *argv) {
437   const char *smashedopt;
438
439   if (argc>=2 &&
440       (smashedopt = argv[1]) &&
441       smashedopt[0]=='-' &&
442       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
443     /* single argument containg all the options and <interp> */
444     argv += 2; /* eat argv[0] and smashedopt */
445     const char *split_args[MAX_OPTS+1];
446     int split_argc = 0;
447     split_args[split_argc++] = argv[0];
448     for (;;) {
449       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
450       split_args[split_argc++] = smashedopt;
451       if (smashedopt[0] != '-') /* never true on first iteration */
452         break;
453       char *delim = strchr(smashedopt,' ');
454       if (!delim) delim = strchr(smashedopt,',');
455       if (!delim)
456         errx(127,"combined arg lacks <interpreter>");
457       *delim = 0;
458       smashedopt = delim+1;
459     }
460     assert(split_argc <= MAX_OPTS);
461     split_args[split_argc++] = 0;
462
463     const char *const *split_argv = split_args;
464
465     shbang_opts(&split_argv, cmdinfos);
466     /* sets interp */
467     if (!split_argv) errx(127,"combined arg too many non-option arguments");
468   } else {
469     shbang_opts(&argv, cmdinfos);
470   }
471
472   script = *argv++;
473   if (!script) errx(127,"need script argument");
474   if (*argv) errx(127,"too many arguments");
475
476   find_socket_path();
477
478   bool havegarbage = check_garbage();
479
480   if (debugmode) {
481     printf("socket: %s\n",socket_path);
482     printf("interp: %s\n",interp);
483     printf("script: %s\n",script);
484     printf("garbage: %d\n",havegarbage);
485     exit(0);
486   }
487
488   if (havegarbage)
489     tidy_garbage();
490
491   exit(0);
492 }