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