cgi-bozo.c revision 1.1.1.10 1 /* $eterna: cgi-bozo.c,v 1.40 2011/11/18 09:21:15 mrg Exp $ */
2
3 /*
4 * Copyright (c) 1997-2011 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 char *uri;
251 size_t len;
252 ssize_t rbytes;
253 pid_t pid;
254 int envpsize, ix, nph;
255 int sv[2];
256
257 if (!httpd->cgibin && !httpd->process_cgi)
258 return 0;
259
260 uri = request->hr_oldfile ? request->hr_oldfile : request->hr_file;
261 if (uri[0] == '/')
262 file = bozostrdup(httpd, uri);
263 else
264 asprintf(&file, "/%s", uri);
265 if (file == NULL)
266 return 0;
267
268 if (request->hr_query && strlen(request->hr_query))
269 query = bozostrdup(httpd, request->hr_query);
270 else
271 query = NULL;
272
273 asprintf(&url, "%s%s%s", file, query ? "?" : "", query ? query : "");
274 if (url == NULL)
275 goto out;
276 debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: url `%s'", url));
277
278 path = NULL;
279 envp = NULL;
280 cgihandler = NULL;
281 command = NULL;
282 info = NULL;
283
284 len = strlen(url);
285
286 if (bozo_auth_check(request, url + 1))
287 goto out;
288
289 if (!httpd->cgibin ||
290 strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
291 cgihandler = content_cgihandler(httpd, request, file + 1);
292 if (cgihandler == NULL) {
293 debug((httpd, DEBUG_FAT,
294 "bozo_process_cgi: no handler, returning"));
295 goto out;
296 }
297 if (len == 0 || file[len - 1] == '/')
298 append_index_html(httpd, &file);
299 debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: cgihandler `%s'",
300 cgihandler));
301 } else if (len - 1 == CGIBIN_PREFIX_LEN) /* url is "/cgi-bin/" */
302 append_index_html(httpd, &file);
303
304 ix = 0;
305 if (cgihandler) {
306 command = file + 1;
307 path = bozostrdup(httpd, cgihandler);
308 argv[ix++] = path;
309 /* argv[] = [ path, command, query, NULL ] */
310 } else {
311 command = file + CGIBIN_PREFIX_LEN + 1;
312 if ((s = strchr(command, '/')) != NULL) {
313 info = bozostrdup(httpd, s);
314 *s = '\0';
315 }
316 path = bozomalloc(httpd,
317 strlen(httpd->cgibin) + 1 + strlen(command) + 1);
318 strcpy(path, httpd->cgibin);
319 strcat(path, "/");
320 strcat(path, command);
321 /* argv[] = [ command, query, NULL ] */
322 }
323 argv[ix++] = command;
324 argv[ix++] = query;
325 argv[ix++] = NULL;
326
327 nph = strncmp(command, "nph-", 4) == 0;
328
329 type = request->hr_content_type;
330 clen = request->hr_content_length;
331
332 envpsize = 13 + request->hr_nheaders +
333 (info && *info ? 1 : 0) +
334 (query && *query ? 1 : 0) +
335 (type && *type ? 1 : 0) +
336 (clen && *clen ? 1 : 0) +
337 (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
338 (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
339 bozo_auth_cgi_count(request) +
340 (request->hr_serverport && *request->hr_serverport ? 1 : 0);
341
342 debug((httpd, DEBUG_FAT,
343 "bozo_process_cgi: path `%s', cmd `%s', info `%s', "
344 "query `%s', nph `%d', envpsize `%d'",
345 path, command, strornull(info),
346 strornull(query), nph, envpsize));
347
348 envp = bozomalloc(httpd, sizeof(*envp) * envpsize);
349 for (ix = 0; ix < envpsize; ix++)
350 envp[ix] = NULL;
351 curenvp = envp;
352
353 SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
354 const char *s2;
355 env = bozomalloc(httpd, 6 + strlen(headp->h_header) + 1 +
356 strlen(headp->h_value));
357
358 t = env;
359 strcpy(t, "HTTP_");
360 t += strlen(t);
361 for (s2 = headp->h_header; *s2; t++, s2++)
362 if (islower((u_int)*s2))
363 *t = toupper((u_int)*s2);
364 else if (*s2 == '-')
365 *t = '_';
366 else
367 *t = *s2;
368 *t = '\0';
369 debug((httpd, DEBUG_OBESE, "setting header %s as %s = %s",
370 headp->h_header, env, headp->h_value));
371 bozo_setenv(httpd, env, headp->h_value, curenvp++);
372 free(env);
373 }
374
375 #ifndef _PATH_DEFPATH
376 #define _PATH_DEFPATH "/usr/bin:/bin"
377 #endif
378
379 bozo_setenv(httpd, "PATH", _PATH_DEFPATH, curenvp++);
380 bozo_setenv(httpd, "IFS", " \t\n", curenvp++);
381 bozo_setenv(httpd, "SERVER_NAME", httpd->virthostname, curenvp++);
382 bozo_setenv(httpd, "GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
383 bozo_setenv(httpd, "SERVER_PROTOCOL", request->hr_proto, curenvp++);
384 bozo_setenv(httpd, "REQUEST_METHOD", request->hr_methodstr, curenvp++);
385 bozo_setenv(httpd, "SCRIPT_NAME", file, curenvp++);
386 bozo_setenv(httpd, "SCRIPT_FILENAME", file + 1, curenvp++);
387 bozo_setenv(httpd, "SERVER_SOFTWARE", httpd->server_software,
388 curenvp++);
389 bozo_setenv(httpd, "REQUEST_URI", uri, curenvp++);
390 bozo_setenv(httpd, "DATE_GMT", bozo_http_date(date, sizeof(date)),
391 curenvp++);
392 if (query && *query)
393 bozo_setenv(httpd, "QUERY_STRING", query, curenvp++);
394 if (info && *info)
395 bozo_setenv(httpd, "PATH_INFO", info, curenvp++);
396 if (type && *type)
397 bozo_setenv(httpd, "CONTENT_TYPE", type, curenvp++);
398 if (clen && *clen)
399 bozo_setenv(httpd, "CONTENT_LENGTH", clen, curenvp++);
400 if (request->hr_serverport && *request->hr_serverport)
401 bozo_setenv(httpd, "SERVER_PORT", request->hr_serverport,
402 curenvp++);
403 if (request->hr_remotehost && *request->hr_remotehost)
404 bozo_setenv(httpd, "REMOTE_HOST", request->hr_remotehost,
405 curenvp++);
406 if (request->hr_remoteaddr && *request->hr_remoteaddr)
407 bozo_setenv(httpd, "REMOTE_ADDR", request->hr_remoteaddr,
408 curenvp++);
409 /*
410 * XXX Apache does this when invoking content handlers, and PHP
411 * XXX 5.3 requires it as a "security" measure.
412 */
413 if (cgihandler)
414 bozo_setenv(httpd, "REDIRECT_STATUS", "200", curenvp++);
415 bozo_auth_cgi_setenv(request, &curenvp);
416
417 free(file);
418 free(url);
419
420 debug((httpd, DEBUG_FAT, "bozo_process_cgi: going exec %s, %s %s %s",
421 path, argv[0], strornull(argv[1]), strornull(argv[2])));
422
423 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv) == -1)
424 bozo_err(httpd, 1, "child socketpair failed: %s",
425 strerror(errno));
426
427 /*
428 * We create 2 procs: one to become the CGI, one read from
429 * the CGI and output to the network, and this parent will
430 * continue reading from the network and writing to the
431 * CGI procsss.
432 */
433 switch (fork()) {
434 case -1: /* eep, failure */
435 bozo_err(httpd, 1, "child fork failed: %s", strerror(errno));
436 /*NOTREACHED*/
437 case 0:
438 close(sv[0]);
439 dup2(sv[1], STDIN_FILENO);
440 dup2(sv[1], STDOUT_FILENO);
441 close(2);
442 close(sv[1]);
443 closelog();
444 bozo_daemon_closefds(httpd);
445
446 if (-1 == execve(path, argv, envp))
447 bozo_err(httpd, 1, "child exec failed: %s: %s",
448 path, strerror(errno));
449 /* NOT REACHED */
450 bozo_err(httpd, 1, "child execve returned?!");
451 }
452
453 close(sv[1]);
454
455 /* parent: read from stdin (bozo_read()) write to sv[0] */
456 /* child: read from sv[0] (bozo_write()) write to stdout */
457 pid = fork();
458 if (pid == -1)
459 bozo_err(httpd, 1, "io child fork failed: %s", strerror(errno));
460 else if (pid == 0) {
461 /* child reader/writer */
462 close(STDIN_FILENO);
463 finish_cgi_output(httpd, request, sv[0], nph);
464 /* if we're done output, our parent is useless... */
465 kill(getppid(), SIGKILL);
466 debug((httpd, DEBUG_FAT, "done processing cgi output"));
467 _exit(0);
468 }
469 close(STDOUT_FILENO);
470
471 /* XXX we should have some goo that times us out
472 */
473 while ((rbytes = bozo_read(httpd, STDIN_FILENO, buf, sizeof buf)) > 0) {
474 ssize_t wbytes;
475 char *bp = buf;
476
477 while (rbytes) {
478 wbytes = write(sv[0], buf, (size_t)rbytes);
479 if (wbytes > 0) {
480 rbytes -= wbytes;
481 bp += wbytes;
482 } else
483 bozo_err(httpd, 1, "write failed: %s",
484 strerror(errno));
485 }
486 }
487 debug((httpd, DEBUG_FAT, "done processing cgi input"));
488 exit(0);
489
490 out:
491 if (query)
492 free(query);
493 if (file)
494 free(file);
495 if (url)
496 free(url);
497 return 0;
498 }
499
500 #ifndef NO_DYNAMIC_CONTENT
501 /* cgi maps are simple ".postfix /path/to/prog" */
502 void
503 bozo_add_content_map_cgi(bozohttpd_t *httpd, const char *arg, const char *cgihandler)
504 {
505 bozo_content_map_t *map;
506
507 debug((httpd, DEBUG_NORMAL, "bozo_add_content_map_cgi: name %s cgi %s",
508 arg, cgihandler));
509
510 httpd->process_cgi = 1;
511
512 map = bozo_get_content_map(httpd, arg);
513 map->name = arg;
514 map->namelen = strlen(map->name);
515 map->type = map->encoding = map->encoding11 = NULL;
516 map->cgihandler = cgihandler;
517 }
518 #endif /* NO_DYNAMIC_CONTENT */
519
520 #endif /* NO_CGIBIN_SUPPORT */
521