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