chiark / gitweb /
cgi-fcgi-interp: Import timespeccmp from FreeBSD
[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  *  -D
54  *         Debug mode.  Do not actually run program.  Instead, print
55  *         out what we would do.
56  *
57  * <options> and <interpreter> can be put into a single argument
58  * to cgi-fcgi-interp, separated by spaces or commas.  <interpreter>
59  * must come last.
60  *
61  * cgi-fcgi-interp automatically expires old sockets, including
62  * ones where the named script is out of date.
63  */
64
65 /*
66  * Uses one of two directories
67  *   /var/run/user/<UID>/cgi-fcgi-interp/
68  *   ~/.cgi-fcgi-interp/<node>/
69  * and inside there uses these paths
70  *   s<ident>
71  *   g<inum>
72  *
73  * If -M<ident> is not specified then an initial substricg of the
74  * lowercase hex of the sha256 of the <script> (ie, our argv[1]) is
75  * used.  The substring is chosen so that the whole path is 10 bytes
76  * shorter than sizeof(sun_path).  But always at least 33 characters.
77  *
78  * <node> is truncated at the first `.' and after the first 32
79  * characters.
80  *
81  * Algorithm:
82  *  - see if /var/run/user exists
83  *       if so, lstat /var/run/user/<UID> and check that
84  *         we own it and it's X700; if not, fail
85  *         if it's ok then <base> is /var/run/user/<UID>
86  *       otherwise, look for and maybe create ~/.cgi-fcgi-interp
87  *         (where ~ is HOME or from getpwuid)
88  *         and then <base> is ~/.cgi-fcgi-interp/<node>
89  *  - calculate pathname (checking <ident> length is OK)
90  *  - check for and maybe create <base>
91  *  - stat and lstat the <script>
92  *  - stat the socket and check its timestamp
93  *       if it is too old, rename it to g<inum>.<pid> (where
94  *       <inum> and <pid> are in decimal)
95  *       and run garbage collection
96  *  - run  cgi-fcgi -connect SOCKET SCRIPT
97  */
98
99 #include "common.h"
100
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <errno.h>
105 #include <stdbool.h>
106 #include <assert.h>
107 #include <limits.h>
108
109 #include <sys/types.h>
110 #include <sys/stat.h>
111 #include <sys/utsname.h>
112 #include <sys/socket.h>
113 #include <sys/un.h>
114 #include <unistd.h>
115 #include <pwd.h>
116 #include <err.h>
117
118 #include <nettle/sha.h>
119
120 #include "myopt.h"
121
122 #define die  common_die
123 #define diee common_diee
124
125 #define MINHEXHASH 33
126
127 static const char *interp, *ident;
128 static int numservers, debugmode;
129
130 void diee(const char *m) {
131   err(127, "error: %s failed", m);
132 }
133
134 static void fusagemessage(FILE *f) {
135   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
136 }
137
138 void usagemessage(void) { fusagemessage(stderr); }
139
140 static void of_help(const struct cmdinfo *ci, const char *val) {
141   fusagemessage(stdout);
142   if (ferror(stdout)) diee("write usage message to stdout");
143   exit(0);
144 }
145
146 static void of_iassign(const struct cmdinfo *ci, const char *val) {
147   long v;
148   char *ep;
149   errno= 0; v= strtol(val,&ep,10);
150   if (!*val || *ep || errno || v<INT_MIN || v>INT_MAX)
151     badusage("bad integer argument `%s' for --%s",val,ci->olong);
152   *ci->iassignto = v;
153 }
154
155 #define MAX_OPTS 5
156
157 static const struct cmdinfo cmdinfos[]= {
158   { "help",   0, .call= of_help               },
159   { 0, 'g',   1, .sassignto= &ident           },
160   { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
161   { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
162   { 0 }
163 };
164
165 static uid_t us;
166 static const char *run_base, *script, *socket_path;
167
168 static bool find_run_base_var_run(void) {
169   struct stat stab;
170   char *try;
171   int r;
172
173   try = m_asprintf("%s/%lu", "/var/run/user", us);
174   r = lstat(try, &stab);
175   if (r<0) {
176     if (errno == ENOENT ||
177         errno == ENOTDIR ||
178         errno == EACCES ||
179         errno == EPERM)
180       return 0; /* oh well */
181     diee("stat /var/run/user/UID");
182   }
183   if (!S_ISDIR(stab.st_mode)) {
184     warnx("%s not a directory, falling back to ~\n", try);
185     return 0;
186   }
187   if (stab.st_uid != us) {
188     warnx("%s not owned by uid %lu, falling back to ~\n", try,
189           (unsigned long)us);
190     return 0;
191   }
192   if (stab.st_mode & 0077) {
193     warnx("%s writeable by group or other, falling back to ~\n", try);
194     return 0;
195   }
196   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
197   return 1;
198 }
199
200 static bool find_run_base_home(void) {
201   struct passwd *pw;
202   struct utsname ut;
203   char *dot, *try;
204   int r;
205
206   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
207
208   r = uname(&ut);   if (r) diee("uname(2)");
209   dot = strchr(ut.nodename, '.');
210   if (dot) *dot = 0;
211   if (sizeof(ut.nodename) > 32)
212     ut.nodename[32] = 0;
213
214   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
215   run_base = try;
216   return 1;
217 }
218
219 static void find_socket_path(void) {
220   struct sockaddr_un sun;
221   int r;
222
223   us = getuid();  if (us==(uid_t)-1) diee("getuid");
224
225   find_run_base_var_run() ||
226     find_run_base_home() ||
227     (abort(),0);
228
229   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
230
231   if (!ident) {
232     if (maxidentlen < MINHEXHASH)
233       errx(127,"base directory `%s'"
234            " leaves only %d characters for id hash"
235            " which is too little (<%d)",
236            run_base, maxidentlen, MINHEXHASH);
237
238     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
239     char *hexident = xmalloc(identlen + 2);
240     struct sha256_ctx sc;
241     unsigned char bbuf[32];
242     int i;
243
244     sha256_init(&sc);
245     sha256_update(&sc,strlen(interp)+1,interp);
246     sha256_update(&sc,strlen(script)+1,script);
247     sha256_digest(&sc,sizeof(bbuf),bbuf);
248
249     for (i=0; i<identlen; i += 2)
250       sprintf(hexident+i, "%02x", bbuf[i/2]);
251
252     hexident[identlen] = 0;
253     ident = hexident;
254   }
255
256   if (strlen(ident) > maxidentlen)
257     errx(127, "base directory `%s' plus ident `%s' too long"
258          " (with spare) for socket (max ident %d)\n",
259          run_base, ident, maxidentlen);
260
261   r = mkdir(run_base, 0700);
262   if (r) {
263     if (!(errno == EEXIST))
264       err(127,"mkdir %s",run_base);
265   }
266
267   socket_path = m_asprintf("%s/g%s",run_base,ident);
268 }  
269
270 /*
271  * Regarding the macro timespeccmp:
272  *
273  * Copyright (c) 1982, 1986, 1993
274  *      The Regents of the University of California.  All rights reserved.
275  *
276  * Redistribution and use in source and binary forms, with or without
277  * modification, are permitted provided that the following conditions
278  * are met:
279  * 1. Redistributions of source code must retain the above copyright
280  *    notice, this list of conditions and the following disclaimer.
281  * 2. Redistributions in binary form must reproduce the above copyright
282  *    notice, this list of conditions and the following disclaimer in the
283  *    documentation and/or other materials provided with the distribution.
284  * 4. Neither the name of the University nor the names of its contributors
285  *    may be used to endorse or promote products derived from this software
286  *    without specific prior written permission.
287  *
288  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
289  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
290  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
291  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
292  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
293  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
294  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
295  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
296  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
297  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
298  * SUCH DAMAGE.
299  *
300  *      @(#)time.h      8.5 (Berkeley) 5/4/95
301  * $FreeBSD: head/sys/sys/time.h 275985 2014-12-21 05:07:11Z imp $
302  */
303 #ifndef timespeccmp
304 #define timespeccmp(tvp, uvp, cmp)                                      \
305         (((tvp)->tv_sec == (uvp)->tv_sec) ?                             \
306             ((tvp)->tv_nsec cmp (uvp)->tv_nsec) :                       \
307             ((tvp)->tv_sec cmp (uvp)->tv_sec))
308 #endif /*timespeccmp*/
309
310 static bool stab_isnewer(const struct stat *a, const struct stat *b) {
311   return 0;
312 }
313
314 static bool check_garbage(void) {
315   struct stat sock_stab, script_stab;
316   int r;
317
318   r = lstat(script, &script_stab);
319   if (r) err(127,"lstat script (%s)",script);
320
321   r = lstat(socket_path, &sock_stab);
322   if (r) {
323     if ((errno == ENOENT))
324       return 0; /* well, no garbage then */
325     err(127,"stat socket (%s)",socket_path);
326   }
327
328   if (stab_isnewer(&script_stab, &sock_stab))
329     return 1;
330
331   if (S_ISLNK(script_stab.st_mode)) {
332     r = stat(script, &script_stab);
333     if (r) err(127,"stat script (%s0",script);
334
335     if (stab_isnewer(&script_stab, &sock_stab))
336       return 1;
337   }
338
339   return 0;
340 }
341
342 static void shbang_opts(const char *const **argv_io,
343                         const struct cmdinfo *cmdinfos) {
344   myopt(argv_io, cmdinfos);
345
346   interp = *(*argv_io)++;
347   if (!interp) errx(127,"need interpreter argument");
348 }
349
350 int main(int argc, const char *const *argv) {
351   const char *smashedopt;
352
353   if (argc>=2 &&
354       (smashedopt = argv[1]) &&
355       smashedopt[0]=='-' &&
356       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
357     /* single argument containg all the options and <interp> */
358     argv += 2; /* eat argv[0] and smashedopt */
359     const char *split_args[MAX_OPTS+1];
360     int split_argc = 0;
361     split_args[split_argc++] = argv[0];
362     for (;;) {
363       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
364       split_args[split_argc++] = smashedopt;
365       if (smashedopt[0] != '-') /* never true on first iteration */
366         break;
367       char *delim = strchr(smashedopt,' ');
368       if (!delim) delim = strchr(smashedopt,',');
369       if (!delim)
370         errx(127,"combined arg lacks <interpreter>");
371       *delim = 0;
372       smashedopt = delim+1;
373     }
374     assert(split_argc <= MAX_OPTS);
375     split_args[split_argc++] = 0;
376
377     const char *const *split_argv = split_args;
378
379     shbang_opts(&split_argv, cmdinfos);
380     /* sets interp */
381     if (!split_argv) errx(127,"combined arg too many non-option arguments");
382   } else {
383     shbang_opts(&argv, cmdinfos);
384   }
385
386   script = *argv++;
387   if (!script) errx(127,"need script argument");
388   if (*argv) errx(127,"too many arguments");
389
390   find_socket_path();
391
392   check_garbage();
393
394   if (debugmode) {
395     printf("socket: %s\n",socket_path);
396     printf("interp: %s\n",interp);
397     printf("script: %s\n",script);
398   }
399
400   exit(0);
401 }