1 /*        $NetBSD: cgi-bozo.c,v 1.56 2023/09/20 08:41:35 shm Exp $    */
2 
3 /*        $eterna: cgi-bozo.c,v 1.40 2011/11/18 09:21:15 mrg Exp $    */
4 
5 /*
6  * Copyright (c) 1997-2021 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 #include <assert.h>
49 
50 #include <netinet/in.h>
51 
52 #include "bozohttpd.h"
53 
54 #define CGIBIN_PREFIX                   "cgi-bin/"
55 #define CGIBIN_PREFIX_LEN     (sizeof(CGIBIN_PREFIX)-1)
56 
57 #ifndef USE_ARG
58 #define USE_ARG(x)  /*LINTED*/(void)&(x)
59 #endif
60 
61 /*
62  * given the file name, return a CGI interpreter
63  */
64 static const char *
content_cgihandler(bozohttpd_t * httpd,bozo_httpreq_t * request,const char * file)65 content_cgihandler(bozohttpd_t *httpd, bozo_httpreq_t *request,
66                        const char *file)
67 {
68           bozo_content_map_t  *map;
69 
70           USE_ARG(request);
71           debug((httpd, DEBUG_FAT, "content_cgihandler: trying file %s", file));
72           map = bozo_match_content_map(httpd, file, 0);
73           if (map)
74                     return map->cgihandler;
75           return NULL;
76 }
77 
78 static int
parse_header(bozo_httpreq_t * request,const char * str,ssize_t len,char ** hdr_str,char ** hdr_val)79 parse_header(bozo_httpreq_t *request, const char *str, ssize_t len,
80                char **hdr_str, char **hdr_val)
81 {
82           struct    bozohttpd_t *httpd = request->hr_httpd;
83           char      *name, *value;
84 
85           /* if the string passed is zero-length bail out */
86           if (*str == '\0')
87                     return -1;
88 
89           value = bozostrdup(httpd, request, str);
90 
91           /* locate the ':' separator in the header/value */
92           name = bozostrnsep(&value, ":", &len);
93 
94           if (NULL == name || -1 == len) {
95                     free(value);
96                     return -1;
97           }
98 
99           /* skip leading space/tab */
100           while (*value == ' ' || *value == '\t')
101                     len--, value++;
102 
103           *hdr_str = name;
104           *hdr_val = value;
105 
106           return 0;
107 }
108 
109 /*
110  * handle parsing a CGI header output, transposing a Status: header
111  * into the HTTP reply (ie, instead of "200 OK").
112  */
113 static void
finish_cgi_output(bozohttpd_t * httpd,bozo_httpreq_t * request,int in,int nph)114 finish_cgi_output(bozohttpd_t *httpd, bozo_httpreq_t *request, int in, int nph)
115 {
116           char      buf[BOZO_WRSZ];
117           char      *str;
118           ssize_t   len;
119           ssize_t rbytes;
120           SIMPLEQ_HEAD(, bozoheaders)   headers;
121           bozoheaders_t *hdr, *nhdr;
122           int       write_header, nheaders = 0;
123 
124           /* much of this code is like bozo_read_request()'s header loop. */
125           SIMPLEQ_INIT(&headers);
126           write_header = nph == 0;
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                      * 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                                         "%s: writing HTTP header "
148                                         "from status %s ..", __func__, 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                               "%s: writing HTTP header ..", __func__));
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                               "%s:  writing delayed HTTP headers ..", __func__));
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           /* CGI programs should perform their own timeouts */
186           while ((rbytes = read(in, buf, sizeof buf)) > 0) {
187                     ssize_t wbytes;
188 
189                     while (rbytes) {
190                               wbytes = bozo_write(httpd, STDOUT_FILENO, buf,
191                                                       (size_t)rbytes);
192                               if (wbytes > 0)
193                                         rbytes -= wbytes;
194                               else
195                                         bozoerr(httpd, 1,
196                                                   "cgi output write failed: %s",
197                                                   strerror(errno));
198                     }
199           }
200 }
201 
202 static void
append_index_html(bozohttpd_t * httpd,char ** url)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 /* This function parse search-string according to section 4.4 of RFC3875 */
213 static char **
parse_search_string(bozo_httpreq_t * request,const char * query,size_t * args_len)214 parse_search_string(bozo_httpreq_t *request, const char *query, size_t *args_len)
215 {
216           struct    bozohttpd_t *httpd = request->hr_httpd;
217           size_t i;
218           char *s, *str, **args;
219 
220           *args_len = 0;
221 
222           /* URI MUST not contain any unencoded '=' - RFC3875, section 4.4 */
223           if (strchr(query, '='))
224                     return NULL;
225 
226           str = bozostrdup(httpd, request, query);
227 
228           /*
229            * there's no more arguments than '+' chars in the query string as it's
230            * the separator
231            */
232           *args_len = 1;
233           /* count '+' in str */
234           for (s = str; (s = strchr(s, '+')) != NULL; (*args_len)++)
235                     s++;
236 
237           args = bozomalloc(httpd, sizeof(*args) * (*args_len + 1));
238 
239           args[0] = str;
240           args[*args_len] = NULL;
241           for (s = str, i = 1; (s = strchr(s, '+')) != NULL; i++) {
242                     *s = '\0';
243                     s++;
244                     args[i] = s;
245           }
246 
247           /*
248            * check if search-strings are valid:
249            *
250            * RFC3875, section 4.4:
251            *
252            * search-string = search-word *( "+" search-word )
253            * search-word   = 1*schar
254            * schar             = unreserved | escaped | xreserved
255            * xreserved         = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "," |
256            *                     "$"
257            *
258            * section 2.3:
259            *
260            * hex          = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" |
261            *                  "b" | "c" | "d" | "e" | "f"
262            * escaped    = "%" hex hex
263            * unreserved = alpha | digit | mark
264            * mark         = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
265            *
266            * section 2.2:
267            *
268            * alpha  = lowalpha | hialpha
269            * lowalpha         = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
270            *                    "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
271            *                    "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
272            *                    "y" | "z"
273            * hialpha          = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" |
274            *                    "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" |
275            *                    "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" |
276            *                  "Y" | "Z"
277            * digit        = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
278            *                    "8" | "9"
279            */
280 #define   UNRESERVED_CHAR     "-_.!~*'()"
281 #define   XRESERVED_CHAR      ";/?:@&=,$"
282 
283           for (i = 0; i < *args_len; i++) {
284                     s = args[i];
285                     /* search-word MUST have at least one schar */
286                     if (*s == '\0')
287                               goto parse_err;
288                     while (*s) {
289                               /* check if it's unreserved */
290                               if (isalpha((unsigned char)*s) ||
291                                   isdigit((unsigned char)*s) ||
292                                   strchr(UNRESERVED_CHAR, *s)) {
293                                         s++;
294                                         continue;
295                               }
296 
297                               /* check if it's escaped */
298                               if (*s == '%') {
299                                         if (s[1] == '\0' || s[2] == '\0')
300                                                   goto parse_err;
301                                         if (!isxdigit((unsigned char)s[1]) ||
302                                             !isxdigit((unsigned char)s[2]))
303                                                   goto parse_err;
304                                         s += 3;
305                                         continue;
306                               }
307 
308                               /* check if it's xreserved */
309 
310                               if (strchr(XRESERVED_CHAR, *s)) {
311                                         s++;
312                                         continue;
313                               }
314 
315                               goto parse_err;
316                     }
317           }
318 
319           /* decode percent encoding */
320           for (i = 0; i < *args_len; i++) {
321                     if (bozo_decode_url_percent(request, args[i]))
322                               goto parse_err;
323           }
324 
325           /* allocate each arg separately */
326           for (i = 0; i < *args_len; i++)
327                     args[i] = bozostrdup(httpd, request, args[i]);
328           free(str);
329 
330           return args;
331 
332 parse_err:
333 
334           free(str);
335           free(args);
336           *args_len = 0;
337 
338           return NULL;
339 
340 }
341 
342 void
bozo_cgi_setbin(bozohttpd_t * httpd,const char * path)343 bozo_cgi_setbin(bozohttpd_t *httpd, const char *path)
344 {
345           httpd->cgibin = bozostrdup(httpd, NULL, path);
346           debug((httpd, DEBUG_OBESE, "cgibin (cgi-bin directory) is %s",
347                  httpd->cgibin));
348 }
349 
350 /* help build up the environ pointer */
351 void
bozo_setenv(bozohttpd_t * httpd,const char * env,const char * val,char ** envp)352 bozo_setenv(bozohttpd_t *httpd, const char *env, const char *val,
353                     char **envp)
354 {
355           char *s1 = bozomalloc(httpd, strlen(env) + strlen(val) + 2);
356 
357           strcpy(s1, env);
358           strcat(s1, "=");
359           strcat(s1, val);
360           debug((httpd, DEBUG_OBESE, "bozo_setenv: %s", s1));
361           *envp = s1;
362 }
363 
364 /*
365  * Checks if the request has asked for a cgi-bin.  Should only be called if
366  * cgibin is set.  If it starts CGIBIN_PREFIX or has a ncontent handler,
367  * process the cgi, otherwise just return.  Returns 0 if it did not handle
368  * the request.
369  */
370 int
bozo_process_cgi(bozo_httpreq_t * request)371 bozo_process_cgi(bozo_httpreq_t *request)
372 {
373           bozohttpd_t *httpd = request->hr_httpd;
374           char      buf[BOZO_WRSZ];
375           char      date[40];
376           bozoheaders_t *headp;
377           const char *type, *clen, *info, *cgihandler;
378           char      *query, *s, *t, *path, *env, *command, *file, *url;
379           char      **envp, **curenvp, **argv, **search_string_argv = NULL;
380           char      **lastenvp;
381           char      *uri;
382           size_t    i, len, search_string_argc = 0;
383           ssize_t rbytes;
384           pid_t     pid;
385           int       envpsize, ix, nph;
386           int       sv[2];
387 
388           if (!httpd->cgibin && !httpd->process_cgi)
389                     return 0;
390 
391 #ifndef NO_USER_SUPPORT
392           if (request->hr_user && !httpd->enable_cgi_users)
393                     return 0;
394 #endif /* !NO_USER_SUPPORT */
395 
396           if (request->hr_oldfile && strcmp(request->hr_oldfile, "/") != 0)
397                     uri = request->hr_oldfile;
398           else
399                     uri = request->hr_file;
400 
401           if (uri[0] == '/')
402                     file = bozostrdup(httpd, request, uri);
403           else
404                     bozoasprintf(httpd, &file, "/%s", uri);
405 
406           if (request->hr_query && strlen(request->hr_query))
407                     query = bozostrdup(httpd, request, request->hr_query);
408           else
409                     query = NULL;
410 
411           bozoasprintf(httpd, &url, "%s%s%s",
412                          file,
413                          query ? "?" : "",
414                          query ? query : "");
415           debug((httpd, DEBUG_NORMAL, "%s: url `%s'", __func__, url));
416 
417           path = NULL;
418           envp = NULL;
419           cgihandler = NULL;
420           command = NULL;
421           info = NULL;
422 
423           len = strlen(url);
424 
425           if (bozo_auth_check(request, url + 1))
426                     goto out;
427 
428           if (!httpd->cgibin ||
429               strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
430                     cgihandler = content_cgihandler(httpd, request, file + 1);
431                     if (cgihandler == NULL) {
432                               debug((httpd, DEBUG_FAT,
433                                         "%s: no handler, returning", __func__));
434                               goto out;
435                     }
436                     if (len == 0 || file[len - 1] == '/')
437                               append_index_html(httpd, &file);
438                     debug((httpd, DEBUG_NORMAL, "%s: cgihandler `%s'",
439                         __func__, cgihandler));
440           } else if (len - 1 == CGIBIN_PREFIX_LEN)          /* url is "/cgi-bin/" */
441                     append_index_html(httpd, &file);
442 
443           /* RFC3875 sect. 4.4. - search-string support */
444           if (query != NULL) {
445                     search_string_argv = parse_search_string(request, query,
446                         &search_string_argc);
447           }
448 
449           debug((httpd, DEBUG_NORMAL, "parse_search_string args no: %zu",
450               search_string_argc));
451           for (i = 0; i < search_string_argc; i++) {
452                     debug((httpd, DEBUG_FAT,
453                         "search_string[%zu]: `%s'", i, search_string_argv[i]));
454           }
455 
456           argv = bozomalloc(httpd, sizeof(*argv) * (3 + search_string_argc));
457 
458           ix = 0;
459           if (cgihandler) {
460                     command = file + 1;
461                     path = bozostrdup(httpd, request, cgihandler);
462           } else {
463                     command = file + CGIBIN_PREFIX_LEN + 1;
464                     if ((s = strchr(command, '/')) != NULL) {
465                               info = bozostrdup(httpd, request, s);
466                               *s = '\0';
467                     }
468                     path = bozomalloc(httpd,
469                                         strlen(httpd->cgibin) + 1 + strlen(command) + 1);
470                     strcpy(path, httpd->cgibin);
471                     strcat(path, "/");
472                     strcat(path, command);
473           }
474 
475           argv[ix++] = path;
476 
477           /* copy search-string args */
478           for (i = 0; i < search_string_argc; i++)
479                     argv[ix++] = search_string_argv[i];
480 
481           argv[ix++] = NULL;
482           nph = strncmp(command, "nph-", 4) == 0;
483 
484           type = request->hr_content_type;
485           clen = request->hr_content_length;
486 
487           envpsize = 13 + request->hr_nheaders +
488               (info && *info ? 1 : 0) +
489               (query && *query ? 1 : 0) +
490               (type && *type ? 1 : 0) +
491               (clen && *clen ? 1 : 0) +
492               (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
493               (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
494               (cgihandler ? 1 : 0) +
495               bozo_auth_cgi_count(request) +
496               (request->hr_serverport && *request->hr_serverport ? 1 : 0);
497 
498           debug((httpd, DEBUG_FAT,
499                     "%s: path `%s', cmd `%s', info `%s', "
500                     "query `%s', nph `%d', envpsize `%d'", __func__,
501                     path, command, strornull(info),
502                     strornull(query), nph, envpsize));
503 
504           envp = bozomalloc(httpd, sizeof(*envp) * envpsize);
505           for (ix = 0; ix < envpsize; ix++)
506                     envp[ix] = NULL;
507           curenvp = envp;
508           lastenvp = envp + envpsize;
509 
510           SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
511                     const char *s2;
512                     env = bozomalloc(httpd, 6 + strlen(headp->h_header) + 1 +
513                         strlen(headp->h_value));
514 
515                     t = env;
516                     strcpy(t, "HTTP_");
517                     t += strlen(t);
518                     for (s2 = headp->h_header; *s2; t++, s2++)
519                               if (islower((unsigned char)*s2))
520                                         *t = toupper((unsigned char)*s2);
521                               else if (*s2 == '-')
522                                         *t = '_';
523                               else
524                                         *t = *s2;
525                     *t = '\0';
526                     debug((httpd, DEBUG_OBESE, "setting header %s as %s = %s",
527                         headp->h_header, env, headp->h_value));
528                     bozo_setenv(httpd, env, headp->h_value, curenvp++);
529                     free(env);
530           }
531 
532 #ifndef _PATH_DEFPATH
533 #define _PATH_DEFPATH "/usr/bin:/bin"
534 #endif
535 
536           bozo_setenv(httpd, "PATH", _PATH_DEFPATH, curenvp++);
537           bozo_setenv(httpd, "IFS", " \t\n", curenvp++);
538           bozo_setenv(httpd, "SERVER_NAME", BOZOHOST(httpd,request), curenvp++);
539           bozo_setenv(httpd, "GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
540           bozo_setenv(httpd, "SERVER_PROTOCOL", request->hr_proto, curenvp++);
541           bozo_setenv(httpd, "REQUEST_METHOD", request->hr_methodstr, curenvp++);
542           bozo_setenv(httpd, "SCRIPT_NAME", file, curenvp++);
543           bozo_setenv(httpd, "SCRIPT_FILENAME", file + 1, curenvp++);
544           bozo_setenv(httpd, "SERVER_SOFTWARE", httpd->server_software,
545                               curenvp++);
546           bozo_setenv(httpd, "REQUEST_URI", uri, curenvp++);
547           bozo_setenv(httpd, "DATE_GMT", bozo_http_date(date, sizeof(date)),
548                               curenvp++);
549           /* RFC3875 section 4.1.7 says that QUERY_STRING MUST be defined. */
550           if (query && *query)
551                     bozo_setenv(httpd, "QUERY_STRING", query, curenvp++);
552           else
553                     bozo_setenv(httpd, "QUERY_STRING", "", curenvp++);
554           if (info && *info)
555                     bozo_setenv(httpd, "PATH_INFO", info, curenvp++);
556           if (type && *type)
557                     bozo_setenv(httpd, "CONTENT_TYPE", type, curenvp++);
558           if (clen && *clen)
559                     bozo_setenv(httpd, "CONTENT_LENGTH", clen, curenvp++);
560           if (request->hr_serverport && *request->hr_serverport)
561                     bozo_setenv(httpd, "SERVER_PORT", request->hr_serverport,
562                                         curenvp++);
563           if (request->hr_remotehost && *request->hr_remotehost)
564                     bozo_setenv(httpd, "REMOTE_HOST", request->hr_remotehost,
565                                         curenvp++);
566           if (request->hr_remoteaddr && *request->hr_remoteaddr)
567                     bozo_setenv(httpd, "REMOTE_ADDR", request->hr_remoteaddr,
568                                         curenvp++);
569           /*
570            * Apache does this when invoking content handlers, and PHP
571            * 5.3 requires it as a "security" measure.
572            */
573           if (cgihandler)
574                     bozo_setenv(httpd, "REDIRECT_STATUS", "200", curenvp++);
575           bozo_auth_cgi_setenv(request, &curenvp);
576 
577           debug((httpd, DEBUG_FAT, "%s: going exec %s with args:", __func__,
578               path));
579 
580           for (i = 0; argv[i] != NULL; i++) {
581                     debug((httpd, DEBUG_FAT, "%s: argv[%zu] = `%s'", __func__,
582                         i, argv[i]));
583           }
584 
585           if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv) == -1)
586                     bozoerr(httpd, 1, "child socketpair failed: %s",
587                                         strerror(errno));
588 
589           *curenvp = 0;
590           assert(lastenvp > curenvp);
591 
592           /*
593            * We create 2 procs: one to become the CGI, one read from
594            * the CGI and output to the network, and this parent will
595            * continue reading from the network and writing to the
596            * CGI procsss.
597            */
598           switch (fork()) {
599           case -1: /* eep, failure */
600                     bozoerr(httpd, 1, "child fork failed: %s", strerror(errno));
601                     /*NOTREACHED*/
602           case 0:
603                     close(sv[0]);
604                     dup2(sv[1], STDIN_FILENO);
605                     dup2(sv[1], STDOUT_FILENO);
606                     close(2);
607                     close(sv[1]);
608                     closelog();
609                     bozo_daemon_closefds(httpd);
610 
611                     if (-1 == execve(path, argv, envp)) {
612                               int saveerrno = errno;
613                               bozo_http_error(httpd, 404, request,
614                                         "Cannot execute CGI");
615                               /* don't log easy to trigger events */
616                               if (saveerrno != ENOENT &&
617                                   saveerrno != EISDIR &&
618                                   saveerrno != EACCES)
619                                         bozoerr(httpd, 1, "child exec failed: %s: %s",
620                                               path, strerror(saveerrno));
621                               _exit(1);
622                     }
623                     /* NOT REACHED */
624                     bozoerr(httpd, 1, "child execve returned?!");
625           }
626 
627           free(query);
628           free(file);
629           free(url);
630           for (i = 0; i < search_string_argc; i++)
631                     free(search_string_argv[i]);
632           free(search_string_argv);
633 
634           close(sv[1]);
635 
636           /* parent: read from stdin (bozo_read()) write to sv[0] */
637           /* child: read from sv[0] (bozo_write()) write to stdout */
638           pid = fork();
639           if (pid == -1)
640                     bozoerr(httpd, 1, "io child fork failed: %s", strerror(errno));
641           else if (pid == 0) {
642                     /* child reader/writer */
643                     close(STDIN_FILENO);
644                     finish_cgi_output(httpd, request, sv[0], nph);
645                     /* if we do SSL, send a SSL_shutdown now */
646                     bozo_ssl_shutdown(request->hr_httpd);
647                     /* if we're done output, our parent is useless... */
648                     kill(getppid(), SIGKILL);
649                     debug((httpd, DEBUG_FAT, "done processing cgi output"));
650                     _exit(0);
651           }
652           close(STDOUT_FILENO);
653 
654           /* CGI programs should perform their own timeouts */
655           while ((rbytes = bozo_read(httpd, STDIN_FILENO, buf, sizeof buf)) > 0) {
656                     ssize_t wbytes;
657 
658                     while (rbytes) {
659                               wbytes = write(sv[0], buf, (size_t)rbytes);
660                               if (wbytes > 0)
661                                         rbytes -= wbytes;
662                               else
663                                         bozoerr(httpd, 1, "write failed: %s",
664                                                   strerror(errno));
665                     }
666           }
667           debug((httpd, DEBUG_FAT, "done processing cgi input"));
668           exit(0);
669 
670  out:
671 
672           for (i = 0; i < search_string_argc; i++)
673                     free(search_string_argv[i]);
674           free(search_string_argv);
675           free(query);
676           free(file);
677           free(url);
678           return 0;
679 }
680 
681 #ifndef NO_DYNAMIC_CONTENT
682 /* cgi maps are simple ".postfix /path/to/prog" */
683 void
bozo_add_content_map_cgi(bozohttpd_t * httpd,const char * arg,const char * cgihandler)684 bozo_add_content_map_cgi(bozohttpd_t *httpd, const char *arg,
685                          const char *cgihandler)
686 {
687           bozo_content_map_t *map;
688 
689           debug((httpd, DEBUG_NORMAL, "bozo_add_content_map_cgi: name %s cgi %s",
690                     arg, cgihandler));
691 
692           httpd->process_cgi = 1;
693 
694           map = bozo_get_content_map(httpd, arg);
695           map->name = arg;
696           map->type = map->encoding = map->encoding11 = NULL;
697           map->cgihandler = cgihandler;
698 }
699 #endif /* NO_DYNAMIC_CONTENT */
700 
701 #endif /* NO_CGIBIN_SUPPORT */
702