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