chiark / gitweb /
1e368f08fe5c89a47264e8c4d708a09b39e57ccf
[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
80 #include <sys/types.h>
81 #include <sys/stat.h>
82 #include <sys/utsname.h>
83 #include <sys/socket.h>
84 #include <sys/un.h>
85 #include <unistd.h>
86 #include <pwd.h>
87 #include <err.h>
88
89 #include <nettle/sha.h>
90
91 #include "myopt.h"
92
93 #define die  common_die
94 #define diee common_diee
95
96 #define MINHEXHASH 33
97
98 static const char *interp, *ident;
99 static int numservers;
100
101 void diee(const char *m) {
102   err(127, "error: %s failed", m);
103 }
104
105 static void fusagemessage(FILE *f) {
106   fprintf(f, "usage: #!/usr/bin/cgi-fcgi-interp [<options>]\n");
107 }
108
109 void usagemessage(void) { fusagemessage(stderr); }
110
111 static void of_help(const struct cmdinfo *ci, const char *val) {
112   fusagemessage(stdout);
113   if (ferror(stdout)) diee("write usage message to stdout");
114   exit(0);
115 }
116
117 #define MAX_OPTS 5
118
119 static const struct cmdinfo cmdinfos[]= {
120   { "help",   0, .call= of_help               },
121   { 0, 'g',   1, .sassignto= &ident           },
122   { 0, 'M',   1, .iassignto= &numservers      },
123   { 0 }
124 };
125
126 static uid_t us;
127 static const char *run_base, *command, *socket_path;
128
129 static bool find_run_base_var_run(void) {
130   struct stat stab;
131   char *try;
132   int r;
133
134   try = m_asprintf("%s/%lu", "/var/run/user", us);
135   r = lstat(try, &stab);
136   if (r<0) {
137     if (errno == ENOENT ||
138         errno == ENOTDIR ||
139         errno == EACCES ||
140         errno == EPERM)
141       return 0; /* oh well */
142     diee("stat /var/run/user/UID");
143   }
144   if (!S_ISDIR(stab.st_mode)) {
145     warnx("%s not a directory, falling back to ~\n", try);
146     return 0;
147   }
148   if (stab.st_uid != us) {
149     warnx("%s not owned by uid %lu, falling back to ~\n", try,
150           (unsigned long)us);
151     return 0;
152   }
153   if (stab.st_mode & 0077) {
154     warnx("%s writeable by group or other, falling back to ~\n", try);
155     return 0;
156   }
157   run_base = m_asprintf("%s/%s", try, "cgi-fcgi-interp");
158   return 1;
159 }
160
161 static bool find_run_base_home(void) {
162   struct passwd *pw;
163   struct utsname ut;
164   char *dot, *try;
165   int r;
166
167   pw = getpwuid(us);  if (!pw) diee("getpwent(uid)");
168
169   r = uname(&ut);   if (r) diee("uname(2)");
170   dot = strchr(ut.nodename, '.');
171   if (dot) *dot = 0;
172   if (sizeof(ut.nodename) > 32)
173     ut.nodename[32] = 0;
174
175   try = m_asprintf("%s/%s/%s", pw->pw_dir, ".cgi-fcgi-interp", ut.nodename);
176   run_base = try;
177   return 1;
178 }
179
180 static void find_socket_path(void) {
181   struct sockaddr_un sun;
182   int r;
183
184   us = getuid();  if (us==(uid_t)-1) diee("getuid");
185
186   find_run_base_var_run() ||
187     find_run_base_home() ||
188     (abort(),0);
189
190   int maxidentlen = sizeof(sun.sun_path) - strlen(run_base) - 10 - 2;
191
192   if (!ident) {
193     if (maxidentlen < MINHEXHASH)
194       errx(127,"base directory `%s'"
195            " leaves only %d characters for command name hash"
196            " which is too little (<%d)",
197            run_base, maxidentlen, MINHEXHASH);
198
199     int identlen = maxidentlen > 64 ? 64 : maxidentlen;
200     char *hexident = xmalloc(identlen + 2);
201     struct sha256_ctx sc;
202     unsigned char bbuf[32];
203     int i;
204
205     sha256_init(&sc);
206     sha256_update(&sc,strlen(interp)+1,interp);
207     sha256_update(&sc,strlen(command)+1,command);
208     sha256_digest(&sc,sizeof(bbuf),bbuf);
209
210     for (i=0; i<identlen; i += 2)
211       sprintf(hexident+i, "%02x", bbuf[i/2]);
212
213     hexident[identlen] = 0;
214     ident = hexident;
215   }
216
217   if (strlen(ident) > maxidentlen)
218     errx(127, "base directory `%s' plus ident `%s' too long"
219          " (with spare) for socket (max ident %d)\n",
220          run_base, ident, maxidentlen);
221
222   r = mkdir(run_base, 0700);
223   if (r) {
224     if (!(errno == EEXIST))
225       err(127,"mkdir %s",run_base);
226   }
227
228   socket_path = m_asprintf("%s/g%s",run_base,ident);
229 }  
230
231 static bool check_garbage(void) {
232   struct stat sock_stab, cmd_stab;
233   int r;
234
235   r = lstat(socket_path, &sock_stab);
236   if (r) {
237     if ((errno == ENOENT))
238       return 0; /* well, no garbage then */
239     err(127,"stat socket (%s)",socket_path);
240   }
241
242   r = lstat(command, &cmd_stab);
243   if (r) err(127,"lstat command (%s)",command);
244
245   return 0;
246 }
247
248 static void shbang_opts(const char *const **argv_io,
249                         const struct cmdinfo *cmdinfos) {
250   myopt(argv_io, cmdinfos);
251
252   interp = *(*argv_io)++;
253   if (!interp) errx(127,"need interpreter argument");
254 }
255
256 int main(int argc, const char *const *argv) {
257   const char *smashedopt;
258
259   if (argc>=2 &&
260       (smashedopt = argv[1]) &&
261       smashedopt[0]=='-' &&
262       (strchr(smashedopt,' ') || strchr(smashedopt,','))) {
263     /* single argument containg all the options and <interp> */
264     argv += 2; /* eat argv[0] and smashedopt */
265     const char *split_args[MAX_OPTS+1];
266     int split_argc = 0;
267     for (;;) {
268       if (split_argc >= MAX_OPTS) errx(127,"too many options in combined arg");
269       split_args[split_argc++] = smashedopt;
270       if (smashedopt[0] != '-') /* never true on first iteration */
271         break;
272       char *delim = strchr(smashedopt,' ');
273       if (!delim) delim = strchr(smashedopt,',');
274       if (!delim)
275         errx(127,"combined arg lacks <interpreter>");
276       *delim = 0;
277       smashedopt = delim+1;
278     }
279     assert(split_argc <= MAX_OPTS);
280     split_args[split_argc++] = 0;
281
282     const char *const *split_argv = split_args;
283
284     shbang_opts(&split_argv, cmdinfos);
285     /* sets interp */
286     if (!split_argv) errx(127,"combined arg too many non-option arguments");
287   } else {
288     shbang_opts(&argv, cmdinfos);
289   }
290
291   command = *argv++;
292   if (!command) errx(127,"need command argument");
293   if (*argv) errx(127,"too many arguments");
294
295   find_socket_path();
296
297   check_garbage();
298
299   printf("socket: %s\n",socket_path);
300   printf("interp: %s\n",interp);
301   printf("command: %s\n",command);
302
303   exit(0);
304 }