cgi-bozo.c revision 1.1.1.7 1 /* $eterna: cgi-bozo.c,v 1.36 2010/05/10 14:36:37 mrg Exp $ */
2
3 /*
4 * Copyright (c) 1997-2010 Matthew R. Green
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer and
14 * dedication in the documentation and/or other materials provided
15 * with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 */
30
31 /* this code implements CGI/1.2 for bozohttpd */
32
33 #ifndef NO_CGIBIN_SUPPORT
34
35 #include <sys/param.h>
36 #include <sys/socket.h>
37
38 #include <ctype.h>
39 #include <errno.h>
40 #include <paths.h>
41 #include <signal.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <syslog.h>
45 #include <unistd.h>
46
47 #include <netinet/in.h>
48
49 #include "bozohttpd.h"
50
51 #define CGIBIN_PREFIX "cgi-bin/"
52 #define CGIBIN_PREFIX_LEN (sizeof(CGIBIN_PREFIX)-1)
53
54 #ifndef USE_ARG
55 #define USE_ARG(x) /*LINTED*/(void)&(x)
56 #endif
57
58 /*
59 * given the file name, return a CGI interpreter
60 */
61 static const char *
62 content_cgihandler(bozohttpd_t *httpd, bozo_httpreq_t *request,
63 const char *file)
64 {
65 bozo_content_map_t *map;
66
67 USE_ARG(request);
68 debug((httpd, DEBUG_FAT, "content_cgihandler: trying file %s", file));
69 map = bozo_match_content_map(httpd, file, 0);
70 if (map)
71 return map->cgihandler;
72 return NULL;
73 }
74
75 static int
76 parse_header(bozohttpd_t *httpd, const char *str, ssize_t len, char **hdr_str,
77 char **hdr_val)
78 {
79 char *name, *value;
80
81 /* if the string passed is zero-length bail out */
82 if (*str == '\0')
83 return -1;
84
85 value = bozostrdup(httpd, str);
86
87 /* locate the ':' separator in the header/value */
88 name = bozostrnsep(&value, ":", &len);
89
90 if (NULL == name || -1 == len) {
91 free(name);
92 return -1;
93 }
94
95 /* skip leading space/tab */
96 while (*value == ' ' || *value == '\t')
97 len--, value++;
98
99 *hdr_str = name;
100 *hdr_val = value;
101
102 return 0;
103 }
104
105 /*
106 * handle parsing a CGI header output, transposing a Status: header
107 * into the HTTP reply (ie, instead of "200 OK").
108 */
109 static void
110 finish_cgi_output(bozohttpd_t *httpd, bozo_httpreq_t *request, int in, int nph)
111 {
112 char buf[BOZO_WRSZ];
113 char *str;
114 ssize_t len;
115 ssize_t rbytes;
116 SIMPLEQ_HEAD(, bozoheaders) headers;
117 bozoheaders_t *hdr, *nhdr;
118 int write_header, nheaders = 0;
119
120 /* much of this code is like bozo_read_request()'s header loop. */
121 SIMPLEQ_INIT(&headers);
122 write_header = nph == 0;
123 /* was read(2) here - XXX - agc */
124 while (nph == 0 &&
125 (str = bozodgetln(httpd, in, &len, bozo_read)) != NULL) {
126 char *hdr_name, *hdr_value;
127
128 if (parse_header(httpd, str, len, &hdr_name, &hdr_value))
129 break;
130
131 /*
132 * The CGI 1.{1,2} spec both say that if the cgi program
133 * returns a `Status:' header field then the server MUST
134 * return it in the response. If the cgi program does
135 * not return any `Status:' header then the server should
136 * respond with 200 OK.
137 * XXX The CGI 1.1 and 1.2 specification differ slightly on
138 * this in that v1.2 says that the script MUST NOT return a
139 * `Status:' header if it is returning a `Location:' header.
140 * For compatibility we are going with the CGI 1.1 behavior.
141 */
142 if (strcasecmp(hdr_name, "status") == 0) {
143 debug((httpd, DEBUG_OBESE,
144 "bozo_process_cgi: writing HTTP header "
145 "from status %s ..", hdr_value));
146 bozo_printf(httpd, "%s %s\r\n", request->hr_proto,
147 hdr_value);
148 bozo_flush(httpd, stdout);
149 write_header = 0;
150 free(hdr_name);
151 break;
152 }
153
154 hdr = bozomalloc(httpd, sizeof *hdr);
155 hdr->h_header = hdr_name;
156 hdr->h_value = hdr_value;
157 SIMPLEQ_INSERT_TAIL(&headers, hdr, h_next);
158 nheaders++;
159 }
160
161 if (write_header) {
162 debug((httpd, DEBUG_OBESE,
163 "bozo_process_cgi: writing HTTP header .."));
164 bozo_printf(httpd,
165 "%s 200 OK\r\n", request->hr_proto);
166 bozo_flush(httpd, stdout);
167 }
168
169 if (nheaders) {
170 debug((httpd, DEBUG_OBESE,
171 "bozo_process_cgi: writing delayed HTTP headers .."));
172 SIMPLEQ_FOREACH_SAFE(hdr, &headers, h_next, nhdr) {
173 bozo_printf(httpd, "%s: %s\r\n", hdr->h_header,
174 hdr->h_value);
175 free(hdr->h_header);
176 free(hdr);
177 }
178 bozo_printf(httpd, "\r\n");
179 bozo_flush(httpd, stdout);
180 }
181
182 /* XXX we should have some goo that times us out
183 */
184 while ((rbytes = read(in, buf, sizeof buf)) > 0) {
185 ssize_t wbytes;
186 char *bp = buf;
187
188 while (rbytes) {
189 wbytes = bozo_write(httpd, STDOUT_FILENO, buf,
190 (size_t)rbytes);
191 if (wbytes > 0) {
192 rbytes -= wbytes;
193 bp += wbytes;
194 } else
195 bozo_err(httpd, 1,
196 "cgi output write failed: %s",
197 strerror(errno));
198 }
199 }
200 }
201
202 static void
203 append_index_html(bozohttpd_t *httpd, char **url)
204 {
205 *url = bozorealloc(httpd, *url,
206 strlen(*url) + strlen(httpd->index_html) + 1);
207 strcat(*url, httpd->index_html);
208 debug((httpd, DEBUG_NORMAL,
209 "append_index_html: url adjusted to `%s'", *url));
210 }
211
212 void
213 bozo_cgi_setbin(bozohttpd_t *httpd, const char *path)
214 {
215 httpd->cgibin = strdup(path);
216 debug((httpd, DEBUG_OBESE, "cgibin (cgi-bin directory) is %s",
217 httpd->cgibin));
218 }
219
220 /* help build up the environ pointer */
221 void
222 bozo_setenv(bozohttpd_t *httpd, const char *env, const char *val,
223 char **envp)
224 {
225 char *s1 = bozomalloc(httpd, strlen(env) + strlen(val) + 2);
226
227 strcpy(s1, env);
228 strcat(s1, "=");
229 strcat(s1, val);
230 debug((httpd, DEBUG_OBESE, "bozo_setenv: %s", s1));
231 *envp = s1;
232 }
233
234 /*
235 * Checks if the request has asked for a cgi-bin. Should only be called if
236 * cgibin is set. If it starts CGIBIN_PREFIX or has a ncontent handler,
237 * process the cgi, otherwise just return. Returns 0 if it did not handle
238 * the request.
239 */
240 int
241 bozo_process_cgi(bozo_httpreq_t *request)
242 {
243 bozohttpd_t *httpd = request->hr_httpd;
244 char buf[BOZO_WRSZ];
245 char date[40];
246 bozoheaders_t *headp;
247 const char *type, *clen, *info, *cgihandler;
248 char *query, *s, *t, *path, *env, *command, *file, *url;
249 char **envp, **curenvp, *argv[4];
250 size_t len;
251 ssize_t rbytes;
252 pid_t pid;
253 int envpsize, ix, nph;
254 int sv[2];
255
256 if (!httpd->cgibin && !httpd->process_cgi)
257 return 0;
258
259 asprintf(&file, "/%s", request->hr_file);
260 if (file == NULL)
261 return 0;
262 if (request->hr_query && strlen(request->hr_query))
263 query = bozostrdup(httpd, request->hr_query);
264 else
265 query = NULL;
266
267 asprintf(&url, "%s%s%s", file, query ? "?" : "", query ? query : "");
268 if (url == NULL)
269 goto out;
270 debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: url `%s'", url));
271
272 path = NULL;
273 envp = NULL;
274 cgihandler = NULL;
275 command = NULL;
276 info = NULL;
277
278 len = strlen(url);
279
280 if (bozo_auth_check(request, url + 1))
281 goto out;
282
283 if (!httpd->cgibin ||
284 strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
285 cgihandler = content_cgihandler(httpd, request, file + 1);
286 if (cgihandler == NULL) {
287 debug((httpd, DEBUG_FAT,
288 "bozo_process_cgi: no handler, returning"));
289 goto out;
290 }
291 if (len == 0 || file[len - 1] == '/')
292 append_index_html(httpd, &file);
293 debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: cgihandler `%s'",
294 cgihandler));
295 } else if (len - 1 == CGIBIN_PREFIX_LEN) /* url is "/cgi-bin/" */
296 append_index_html(httpd, &file);
297
298 ix = 0;
299 if (cgihandler) {
300 command = file + 1;
301 path = bozostrdup(httpd, cgihandler);
302 argv[ix++] = path;
303 /* argv[] = [ path, command, query, NULL ] */
304 } else {
305 command = file + CGIBIN_PREFIX_LEN + 1;
306 if ((s = strchr(command, '/')) != NULL) {
307 info = bozostrdup(httpd, s);
308 *s = '\0';
309 }
310 path = bozomalloc(httpd,
311 strlen(httpd->cgibin) + 1 + strlen(command) + 1);
312 strcpy(path, httpd->cgibin);
313 strcat(path, "/");
314 strcat(path, command);
315 /* argv[] = [ command, query, NULL ] */
316 }
317 argv[ix++] = command;
318 argv[ix++] = query;
319 argv[ix++] = NULL;
320
321 nph = strncmp(command, "nph-", 4) == 0;
322
323 type = request->hr_content_type;
324 clen = request->hr_content_length;
325
326 envpsize = 13 + request->hr_nheaders +
327 (info && *info ? 1 : 0) +
328 (query && *query ? 1 : 0) +
329 (type && *type ? 1 : 0) +
330 (clen && *clen ? 1 : 0) +
331 (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
332 (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
333 bozo_auth_cgi_count(request) +
334 (request->hr_serverport && *request->hr_serverport ? 1 : 0);
335
336 debug((httpd, DEBUG_FAT,
337 "bozo_process_cgi: path `%s', cmd `%s', info `%s', "
338 "query `%s', nph `%d', envpsize `%d'",
339 path, command, strornull(info),
340 strornull(query), nph, envpsize));
341
342 envp = bozomalloc(httpd, sizeof(*envp) * envpsize);
343 for (ix = 0; ix < envpsize; ix++)
344 envp[ix] = NULL;
345 curenvp = envp;
346
347 SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
348 const char *s2;
349 env = bozomalloc(httpd, 6 + strlen(headp->h_header) + 1 +
350 strlen(headp->h_value));
351
352 t = env;
353 strcpy(t, "HTTP_");
354 t += strlen(t);
355 for (s2 = headp->h_header; *s2; t++, s2++)
356 if (islower((u_int)*s2))
357 *t = toupper((u_int)*s2);
358 else if (*s2 == '-')
359 *t = '_';
360 else
361 *t = *s2;
362 *t = '\0';
363 debug((httpd, DEBUG_OBESE, "setting header %s as %s = %s",
364 headp->h_header, env, headp->h_value));
365 bozo_setenv(httpd, env, headp->h_value, curenvp++);
366 free(env);
367 }
368
369 #ifndef _PATH_DEFPATH
370 #define _PATH_DEFPATH "/usr/bin:/bin"
371 #endif
372
373 bozo_setenv(httpd, "PATH", _PATH_DEFPATH, curenvp++);
374 bozo_setenv(httpd, "IFS", " \t\n", curenvp++);
375 bozo_setenv(httpd, "SERVER_NAME", httpd->virthostname, curenvp++);
376 bozo_setenv(httpd, "GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
377 bozo_setenv(httpd, "SERVER_PROTOCOL", request->hr_proto, curenvp++);
378 bozo_setenv(httpd, "REQUEST_METHOD", request->hr_methodstr, curenvp++);
379 bozo_setenv(httpd, "SCRIPT_NAME", file, curenvp++);
380 bozo_setenv(httpd, "SCRIPT_FILENAME", file + 1, curenvp++);
381 bozo_setenv(httpd, "SERVER_SOFTWARE", httpd->server_software,
382 curenvp++);
383 bozo_setenv(httpd, "REQUEST_URI", request->hr_file, curenvp++);
384 bozo_setenv(httpd, "DATE_GMT", bozo_http_date(date, sizeof(date)),
385 curenvp++);
386 if (query && *query)
387 bozo_setenv(httpd, "QUERY_STRING", query, curenvp++);
388 if (info && *info)
389 bozo_setenv(httpd, "PATH_INFO", info, curenvp++);
390 if (type && *type)
391 bozo_setenv(httpd, "CONTENT_TYPE", type, curenvp++);
392 if (clen && *clen)
393 bozo_setenv(httpd, "CONTENT_LENGTH", clen, curenvp++);
394 if (request->hr_serverport && *request->hr_serverport)
395 bozo_setenv(httpd, "SERVER_PORT", request->hr_serverport,
396 curenvp++);
397 if (request->hr_remotehost && *request->hr_remotehost)
398 bozo_setenv(httpd, "REMOTE_HOST", request->hr_remotehost,
399 curenvp++);
400 if (request->hr_remoteaddr && *request->hr_remoteaddr)
401 bozo_setenv(httpd, "REMOTE_ADDR", request->hr_remoteaddr,
402 curenvp++);
403 bozo_auth_cgi_setenv(request, &curenvp);
404
405 free(file);
406 free(url);
407
408 debug((httpd, DEBUG_FAT, "bozo_process_cgi: going exec %s, %s %s %s",
409 path, argv[0], strornull(argv[1]), strornull(argv[2])));
410
411 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv) == -1)
412 bozo_err(httpd, 1, "child socketpair failed: %s",
413 strerror(errno));
414
415 /*
416 * We create 2 procs: one to become the CGI, one read from
417 * the CGI and output to the network, and this parent will
418 * continue reading from the network and writing to the
419 * CGI procsss.
420 */
421 switch (fork()) {
422 case -1: /* eep, failure */
423 bozo_err(httpd, 1, "child fork failed: %s", strerror(errno));
424 /*NOTREACHED*/
425 case 0:
426 close(sv[0]);
427 dup2(sv[1], STDIN_FILENO);
428 dup2(sv[1], STDOUT_FILENO);
429 close(2);
430 close(sv[1]);
431 closelog();
432 bozo_daemon_closefds(httpd);
433
434 if (-1 == execve(path, argv, envp))
435 bozo_err(httpd, 1, "child exec failed: %s: %s",
436 path, strerror(errno));
437 /* NOT REACHED */
438 bozo_err(httpd, 1, "child execve returned?!");
439 }
440
441 close(sv[1]);
442
443 /* parent: read from stdin (bozo_read()) write to sv[0] */
444 /* child: read from sv[0] (bozo_write()) write to stdout */
445 pid = fork();
446 if (pid == -1)
447 bozo_err(httpd, 1, "io child fork failed: %s", strerror(errno));
448 else if (pid == 0) {
449 /* child reader/writer */
450 close(STDIN_FILENO);
451 finish_cgi_output(httpd, request, sv[0], nph);
452 /* if we're done output, our parent is useless... */
453 kill(getppid(), SIGKILL);
454 debug((httpd, DEBUG_FAT, "done processing cgi output"));
455 _exit(0);
456 }
457 close(STDOUT_FILENO);
458
459 /* XXX we should have some goo that times us out
460 */
461 while ((rbytes = bozo_read(httpd, STDIN_FILENO, buf, sizeof buf)) > 0) {
462 ssize_t wbytes;
463 char *bp = buf;
464
465 while (rbytes) {
466 wbytes = write(sv[0], buf, (size_t)rbytes);
467 if (wbytes > 0) {
468 rbytes -= wbytes;
469 bp += wbytes;
470 } else
471 bozo_err(httpd, 1, "write failed: %s",
472 strerror(errno));
473 }
474 }
475 debug((httpd, DEBUG_FAT, "done processing cgi input"));
476 exit(0);
477
478 out:
479 if (query)
480 free(query);
481 if (file)
482 free(file);
483 if (url)
484 free(url);
485 return 0;
486 }
487
488 #ifndef NO_DYNAMIC_CONTENT
489 /* cgi maps are simple ".postfix /path/to/prog" */
490 void
491 bozo_add_content_map_cgi(bozohttpd_t *httpd, const char *arg, const char *cgihandler)
492 {
493 bozo_content_map_t *map;
494
495 debug((httpd, DEBUG_NORMAL, "bozo_add_content_map_cgi: name %s cgi %s",
496 arg, cgihandler));
497
498 httpd->process_cgi = 1;
499
500 map = bozo_get_content_map(httpd, arg);
501 map->name = arg;
502 map->type = map->encoding = map->encoding11 = NULL;
503 map->cgihandler = cgihandler;
504 }
505 #endif /* NO_DYNAMIC_CONTENT */
506
507 #endif /* NO_CGIBIN_SUPPORT */
508