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