chiark / gitweb /
cgi-fcgi-interp: Do not eat an option in squashed arg style
[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  * The result is a program which looks, when executed via the #!
7  * line, like a CGI program.  But the script inside will be executed
8  * via <interpreter> in an fcgi context.
9  *
10  * Options:
11  *
12  *  <interpreter>
13  *          The real interpreter to use.  Eg "perl".  Need not
14  *          be an absolute path; will be fed to execvp.
15  *
16  *  -g<ident>
17  *          Use <ident> rather than hex(sha256(<script>))
18  *          as the basename of the leafname of the fcgi rendezvous
19  *          socket.  If <ident> contains only hex digit characters it
20  *          ought to be no more than 32 characters.  <ident> should
21  *          not contain spaces or commas (see below).
22  *
23  *  -M<numservers>
24  *         Start <numservers> instances of the program.  This
25  *         determines the maximum concurrency.  (Note that unlike
26  *         speedy, the specified number of servers is started
27  *         right away.)  The default is 4.
28  *
29  *  -D
30  *         Debug mode.  Do not actually run program.  Instead, print
31  *         out what we would do.
32  *
33  * <options> and <interpreter> can be put into a single argument
34  * to cgi-fcgi-interp, separated by spaces or commas.  <interpreter>
35  * must come last.
36  *
37  * cgi-fcgi-interp automatically expires old sockets, including
38  * ones where the named script is out of date.
39  */
40
41 /*
42  * Uses one of two directories
43  *   /var/run/user/<UID>/cgi-fcgi-interp/
44  *   ~/.cgi-fcgi-interp/<node>/
45  * and inside there uses these paths
46  *   s<ident>
47  *   g<inum>
48  *
49  * If -M<ident> is not specified then an initial substricg of the
50  * lowercase hex of the sha256 of the <script> (ie, our argv[1]) is
51  * used.  The substring is chosen so that the whole path is 10 bytes
52  * shorter than sizeof(sun_path).  But always at least 33 characters.
53  *
54  * <node> is truncated at the first `.' and after the first 32
55  * characters.
56  *
57  * Algorithm:
58  *  - see if /var/run/user exists
59  *       if so, lstat /var/run/user/<UID> and check that
60  *         we own it and it's X700; if not, fail
61  *         if it's ok then <base> is /var/run/user/<UID>
62  *       otherwise, look for and maybe create ~/.cgi-fcgi-interp
63  *         (where ~ is HOME or from getpwuid)
64  *         and then <base> is ~/.cgi-fcgi-interp/<node>
65  *  - calculate pathname (checking <ident> length is OK)
66  *  - check for and maybe create <base>
67  *  - stat and lstat the <script>
68  *  - stat the socket and check its timestamp
69  *       if it is too hold, rename it to g<inum> (where
70  *       <inum> is in decimal)
71  *       and run garbage collection
72  *  - run  cgi-fcgi -connect SOCKET SCRIPT
73  */
74
75 #include "common.h"
76
77 #include <stdio.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <errno.h>
81 #include <stdbool.h>
82 #include <assert.h>
83 #include <limits.h>
84
85 #include <sys/types.h>
86 #include <sys/stat.h>
87 #include <sys/utsname.h>
88 #include <sys/socket.h>
89 #include <sys/un.h>
90 #include <unistd.h>
91 #include <pwd.h>
92 #include <err.h>
93
94 #include <nettle/sha.h>
95
96 #include "myopt.h"
97
98 #define die  common_die
99 #define diee common_diee
100
101 #define MINHEXHASH 33
102
103 static const char *interp, *ident;
104 static int numservers, debugmode;
105
106 void diee(const char *m) {
107   err(127, "error: %s failed", m);
108 }
109
110 static void fusagemessage(FILE *f) {
111   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
112 }
113
114 void usagemessage(void) { fusagemessage(stderr); }
115
116 static void of_help(const struct cmdinfo *ci, const char *val) {
117   fusagemessage(stdout);
118   if (ferror(stdout)) diee("write usage message to stdout");
119   exit(0);
120 }
121
122 static void of_iassign(const struct cmdinfo *ci, const char *val) {
123   long v;
124   char *ep;
125   errno= 0; v= strtol(val,&ep,10);
126   if (!*val || *ep || errno || v<INT_MIN || v>INT_MAX)
127     badusage("bad integer argument `%s' for --%s",val,ci->olong);
128   *ci->iassignto = v;
129 }
130
131 #define MAX_OPTS 5
132
133 static const struct cmdinfo cmdinfos[]= {
134   { "help",   0, .call= of_help               },
135   { 0, 'g',   1, .sassignto= &ident           },
136   { 0, 'M',   1, .call=of_iassign, .iassignto= &numservers      },
137   { 0, 'D',   0, .iassignto= &debugmode, .arg= 1 },
138   { 0 }
139 };
140
141 static uid_t us;
142 static const char *run_base, *command, *socket_path;
143
144 static bool find_run_base_var_run(void) {
145   struct stat stab;
146   char *try;
147   int r;
148
149   try = m_asprintf("%s/%lu", "/var/run/user", us);
150   r = lstat(try, &stab);
151   if (r<0) {
152     if (errno == ENOENT ||
153         errno == ENOTDIR ||
154         errno == EACCES ||
155         errno == EPERM)
156       return 0; /* oh well */
157     diee("stat /var/run/user/UID");
158   }
159   if (!S_ISDIR(stab.st_mode)) {
160     warnx("%s not a directory, falling back to ~\n", try);
161     return 0;
162   }
163   if (stab.st_uid != us) {
164     warnx("%s not owned by uid %lu, falling back to ~\n", try,
165           (unsigned long)us);
166     return 0;
167   }
168   if (stab.st_mode & 0077) {
169     warnx("%s writeable by group or other, falling back to ~\n", try);
170     return 0;
171   }
172   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
173   return 1;
174 }
175
176 static bool find_run_base_home(void) {
177   struct passwd *pw;
178   struct utsname ut;
179   char *dot, *try;
180   int r;
181
182   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
183
184   r = uname(&ut);   if (r) diee("uname(2)");
185   dot = strchr(ut.nodename, '.');
186   if (dot) *dot = 0;
187   if (sizeof(ut.nodename) > 32)
188     ut.nodename[32] = 0;
189
190   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
191   run_base = try;
192   return 1;
193 }
194
195 static void find_socket_path(void) {
196   struct sockaddr_un sun;
197   int r;
198
199   us = getuid();  if (us==(uid_t)-1) diee("getuid");
200
201   find_run_base_var_run() ||
202     find_run_base_home() ||
203     (abort(),0);
204
205   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
206
207   if (!ident) {
208     if (maxidentlen < MINHEXHASH)
209       errx(127,"base directory `%s'"
210            " leaves only %d characters for command name hash"
211            " which is too little (<%d)",
212            run_base, maxidentlen, MINHEXHASH);
213
214     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
215     char *hexident = xmalloc(identlen + 2);
216     struct sha256_ctx sc;
217     unsigned char bbuf[32];
218     int i;
219
220     sha256_init(&sc);
221     sha256_update(&sc,strlen(interp)+1,interp);
222     sha256_update(&sc,strlen(command)+1,command);
223     sha256_digest(&sc,sizeof(bbuf),bbuf);
224
225     for (i=0; i<identlen; i += 2)
226       sprintf(hexident+i, "%02x", bbuf[i/2]);
227
228     hexident[identlen] = 0;
229     ident = hexident;
230   }
231
232   if (strlen(ident) > maxidentlen)
233     errx(127, "base directory `%s' plus ident `%s' too long"
234          " (with spare) for socket (max ident %d)\n",
235          run_base, ident, maxidentlen);
236
237   r = mkdir(run_base, 0700);
238   if (r) {
239     if (!(errno == EEXIST))
240       err(127,"mkdir %s",run_base);
241   }
242
243   socket_path = m_asprintf("%s/g%s",run_base,ident);
244 }  
245
246 static bool check_garbage(void) {
247   struct stat sock_stab, cmd_stab;
248   int r;
249
250   r = lstat(socket_path, &sock_stab);
251   if (r) {
252     if ((errno == ENOENT))
253       return 0; /* well, no garbage then */
254     err(127,"stat socket (%s)",socket_path);
255   }
256
257   r = lstat(command, &cmd_stab);
258   if (r) err(127,"lstat command (%s)",command);
259
260   return 0;
261 }
262
263 static void shbang_opts(const char *const **argv_io,
264                         const struct cmdinfo *cmdinfos) {
265   myopt(argv_io, cmdinfos);
266
267   interp = *(*argv_io)++;
268   if (!interp) errx(127,"need interpreter argument");
269 }
270
271 int main(int argc, const char *const *argv) {
272   const char *smashedopt;
273
274   if (argc>=2 &&
275       (smashedopt = argv[1]) &&
276       smashedopt[0]=='-' &&
277       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
278     /* single argument containg all the options and <interp> */
279     argv += 2; /* eat argv[0] and smashedopt */
280     const char *split_args[MAX_OPTS+1];
281     int split_argc = 0;
282     split_args[split_argc++] = argv[0];
283     for (;;) {
284       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
285       split_args[split_argc++] = smashedopt;
286       if (smashedopt[0] != '-') /* never true on first iteration */
287         break;
288       char *delim = strchr(smashedopt,' ');
289       if (!delim) delim = strchr(smashedopt,',');
290       if (!delim)
291         errx(127,"combined arg lacks <interpreter>");
292       *delim = 0;
293       smashedopt = delim+1;
294     }
295     assert(split_argc <= MAX_OPTS);
296     split_args[split_argc++] = 0;
297
298     const char *const *split_argv = split_args;
299
300     shbang_opts(&split_argv, cmdinfos);
301     /* sets interp */
302     if (!split_argv) errx(127,"combined arg too many non-option arguments");
303   } else {
304     shbang_opts(&argv, cmdinfos);
305   }
306
307   command = *argv++;
308   if (!command) errx(127,"need command argument");
309   if (*argv) errx(127,"too many arguments");
310
311   find_socket_path();
312
313   check_garbage();
314
315   if (debugmode) {
316     printf("socket: %s\n",socket_path);
317     printf("interp: %s\n",interp);
318     printf("command: %s\n",command);
319   }
320
321   exit(0);
322 }