No empty .Rs/.Re
[netbsd-mini2440.git] / libexec / httpd / cgi-bozo.c
blobe3ef15b392186f165a0c649ca528886419a80d9e
1 /* $NetBSD: cgi-bozo.c,v 1.13 2009/04/18 21:22:03 mrg Exp $ */
3 /* $eterna: cgi-bozo.c,v 1.32 2009/05/22 21:51:38 mrg Exp $ */
5 /*
6 * Copyright (c) 1997-2009 Matthew R. Green
7 * All rights reserved.
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.
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.
33 /* this code implements CGI/1.2 for bozohttpd */
35 #ifndef NO_CGIBIN_SUPPORT
37 #include <sys/param.h>
38 #include <sys/socket.h>
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>
49 #include <netinet/in.h>
51 #include "bozohttpd.h"
53 #define CGIBIN_PREFIX "cgi-bin/"
54 #define CGIBIN_PREFIX_LEN (sizeof(CGIBIN_PREFIX)-1)
56 static char *cgibin; /* cgi-bin directory */
57 static int Cflag; /* added a cgi handler, always process_cgi() */
59 static const char * content_cgihandler(http_req *, const char *);
60 static void finish_cgi_output(http_req *request, int, int);
61 static int parse_header(const char *, ssize_t, char **, char **);
62 static void append_index_html(char **);
64 void
65 set_cgibin(char *path)
67 cgibin = path;
68 debug((DEBUG_OBESE, "cgibin (cgi-bin directory) is %s", cgibin));
71 /* help build up the environ pointer */
72 void
73 spsetenv(const char *env, const char *val, char **envp)
75 char *s1 = bozomalloc(strlen(env) + strlen(val) + 2);
77 strcpy(s1, env);
78 strcat(s1, "=");
79 strcat(s1, val);
80 debug((DEBUG_OBESE, "spsetenv: %s", s1));
81 *envp = s1;
85 * Checks if the request has asked for a cgi-bin. Should only be called if
86 * cgibin is set. If it starts CGIBIN_PREFIX or has a ncontent handler,
87 * process the cgi, otherwise just return. Returns 0 if it did not handle
88 * the request.
90 int
91 process_cgi(http_req *request)
93 char buf[WRSZ];
94 struct headers *headp;
95 const char *type, *clen, *info, *cgihandler;
96 char *query, *s, *t, *path, *env, *command, *file, *url;
97 char **envp, **curenvp, *argv[4];
98 size_t len;
99 ssize_t rbytes;
100 pid_t pid;
101 int envpsize, ix, nph;
102 int sv[2];
104 if (!cgibin && !Cflag)
105 return 0;
107 asprintf(&file, "/%s", request->hr_file);
108 if (file == NULL)
109 return 0;
110 if (request->hr_query && strlen(request->hr_query))
111 query = bozostrdup(request->hr_query);
112 else
113 query = NULL;
115 asprintf(&url, "%s%s%s", file, query ? "?" : "", query ? query : "");
116 if (url == NULL)
117 goto out;
118 debug((DEBUG_NORMAL, "process_cgi: url `%s'", url));
120 path = NULL;
121 envp = NULL;
122 cgihandler = NULL;
123 command = NULL;
124 info = NULL;
126 len = strlen(url);
128 if (auth_check(request, url + 1))
129 goto out;
131 if (!cgibin || strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
132 cgihandler = content_cgihandler(request, file + 1);
133 if (cgihandler == NULL) {
134 debug((DEBUG_FAT, "process_cgi: no handler, returning"));
135 goto out;
137 if (len == 0 || file[len - 1] == '/')
138 append_index_html(&file);
139 debug((DEBUG_NORMAL, "process_cgi: cgihandler `%s'",
140 cgihandler));
141 } else if (len - 1 == CGIBIN_PREFIX_LEN) /* url is "/cgi-bin/" */
142 append_index_html(&file);
144 ix = 0;
145 if (cgihandler) {
146 command = file + 1;
147 path = bozostrdup(cgihandler);
148 argv[ix++] = path;
149 /* argv[] = [ path, command, query, NULL ] */
150 } else {
151 command = file + CGIBIN_PREFIX_LEN + 1;
152 if ((s = strchr(command, '/')) != NULL) {
153 info = bozostrdup(s);
154 *s = '\0';
156 path = bozomalloc(strlen(cgibin) + 1 + strlen(command) + 1);
157 strcpy(path, cgibin);
158 strcat(path, "/");
159 strcat(path, command);
160 /* argv[] = [ command, query, NULL ] */
162 argv[ix++] = command;
163 argv[ix++] = query;
164 argv[ix++] = NULL;
166 nph = strncmp(command, "nph-", 4) == 0;
168 type = request->hr_content_type;
169 clen = request->hr_content_length;
171 envpsize = 13 + request->hr_nheaders +
172 (info && *info ? 1 : 0) +
173 (query && *query ? 1 : 0) +
174 (type && *type ? 1 : 0) +
175 (clen && *clen ? 1 : 0) +
176 (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
177 (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
178 auth_cgi_count(request) +
179 (request->hr_serverport && *request->hr_serverport ? 1 : 0);
181 debug((DEBUG_FAT,
182 "process_cgi: path `%s' cmd `%s' info `%s' query `%s' nph `%d' envpsize `%d'",
183 path, command, strornull(info), strornull(query), nph, envpsize));
185 envp = bozomalloc(sizeof(*envp) * envpsize);
186 for (ix = 0; ix < envpsize; ix++)
187 envp[ix] = NULL;
188 curenvp = envp;
190 SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
191 const char *s2;
192 env = bozomalloc(6 + strlen(headp->h_header) + 1 +
193 strlen(headp->h_value));
195 t = env;
196 strcpy(t, "HTTP_");
197 t += strlen(t);
198 for (s2 = headp->h_header; *s2; t++, s2++)
199 if (islower((u_int)*s2))
200 *t = toupper((u_int)*s2);
201 else if (*s2 == '-')
202 *t = '_';
203 else
204 *t = *s2;
205 *t = '\0';
206 debug((DEBUG_OBESE, "setting header %s as %s = %s",
207 headp->h_header, env, headp->h_value));
208 spsetenv(env, headp->h_value, curenvp++);
209 free(env);
212 #ifndef _PATH_DEFPATH
213 #define _PATH_DEFPATH "/usr/bin:/bin"
214 #endif
216 spsetenv("PATH", _PATH_DEFPATH, curenvp++);
217 spsetenv("IFS", " \t\n", curenvp++);
218 spsetenv("SERVER_NAME", myname, curenvp++);
219 spsetenv("GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
220 spsetenv("SERVER_PROTOCOL", request->hr_proto, curenvp++);
221 spsetenv("REQUEST_METHOD", request->hr_methodstr, curenvp++);
222 spsetenv("SCRIPT_NAME", file, curenvp++);
223 spsetenv("SCRIPT_FILENAME", file + 1, curenvp++);
224 spsetenv("SERVER_SOFTWARE", server_software, curenvp++);
225 spsetenv("REQUEST_URI", request->hr_file, curenvp++);
226 spsetenv("DATE_GMT", http_date(), curenvp++);
227 if (query && *query)
228 spsetenv("QUERY_STRING", query, curenvp++);
229 if (info && *info)
230 spsetenv("PATH_INFO", info, curenvp++);
231 if (type && *type)
232 spsetenv("CONTENT_TYPE", type, curenvp++);
233 if (clen && *clen)
234 spsetenv("CONTENT_LENGTH", clen, curenvp++);
235 if (request->hr_serverport && *request->hr_serverport)
236 spsetenv("SERVER_PORT", request->hr_serverport, curenvp++);
237 if (request->hr_remotehost && *request->hr_remotehost)
238 spsetenv("REMOTE_HOST", request->hr_remotehost, curenvp++);
239 if (request->hr_remoteaddr && *request->hr_remoteaddr)
240 spsetenv("REMOTE_ADDR", request->hr_remoteaddr, curenvp++);
241 auth_cgi_setenv(request, &curenvp);
243 free(file);
244 free(url);
246 debug((DEBUG_FAT, "process_cgi: going exec %s, %s %s %s",
247 path, argv[0], strornull(argv[1]), strornull(argv[2])));
249 if (-1 == socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv))
250 error(1, "child socketpair failed: %s", strerror(errno));
253 * We create 2 procs: one to become the CGI, one read from
254 * the CGI and output to the network, and this parent will
255 * continue reading from the network and writing to the
256 * CGI procsss.
258 switch (fork()) {
259 case -1: /* eep, failure */
260 error(1, "child fork failed: %s", strerror(errno));
261 case 0:
262 close(sv[0]);
263 dup2(sv[1], STDIN_FILENO);
264 dup2(sv[1], STDOUT_FILENO);
265 close(2);
266 close(sv[1]);
267 closelog();
268 daemon_closefds();
270 if (-1 == execve(path, argv, envp))
271 error(1, "child exec failed: %s: %s",
272 path, strerror(errno));
273 /* NOT REACHED */
274 error(1, "child execve returned?!");
277 close(sv[1]);
279 /* parent: read from stdin (bozoread()) write to sv[0] */
280 /* child: read from sv[0] (bozowrite()) write to stdout */
281 pid = fork();
282 if (pid == -1)
283 error(1, "io child fork failed: %s", strerror(errno));
284 else if (pid == 0) {
285 /* child reader/writer */
286 close(STDIN_FILENO);
287 finish_cgi_output(request, sv[0], nph);
288 /* if we're done output, our parent is useless... */
289 kill(getppid(), SIGKILL);
290 debug((DEBUG_FAT, "done processing cgi output"));
291 _exit(0);
293 close(STDOUT_FILENO);
295 /* XXX we should have some goo that times us out
297 while ((rbytes = bozoread(STDIN_FILENO, buf, sizeof buf)) > 0) {
298 ssize_t wbytes;
299 char *bp = buf;
301 while (rbytes) {
302 wbytes = write(sv[0], buf , rbytes);
303 if (wbytes > 0) {
304 rbytes -= wbytes;
305 bp += wbytes;
306 } else
307 error(1, "write failed: %s", strerror(errno));
310 debug((DEBUG_FAT, "done processing cgi input"));
311 exit(0);
313 out:
314 if (query)
315 free(query);
316 if (file)
317 free(file);
318 if (url)
319 free(url);
320 return 0;
324 * handle parsing a CGI header output, transposing a Status: header
325 * into the HTTP reply (ie, instead of "200 OK").
327 static void
328 finish_cgi_output(http_req *request, int in, int nph)
330 char buf[WRSZ];
331 char *str;
332 ssize_t len;
333 ssize_t rbytes;
334 SIMPLEQ_HEAD(, headers) headers;
335 struct headers *hdr, *nhdr;
336 int write_header, nheaders = 0;
338 /* much of this code is like read_request()'s header loop. hmmm... */
339 SIMPLEQ_INIT(&headers);
340 write_header = nph == 0;
341 while (nph == 0 && (str = bozodgetln(in, &len, read)) != NULL) {
342 char *hdr_name, *hdr_value;
344 if (parse_header(str, len, &hdr_name, &hdr_value))
345 break;
348 * The CGI 1.{1,2} spec both say that if the cgi program
349 * returns a `Status:' header field then the server MUST
350 * return it in the response. If the cgi program does
351 * not return any `Status:' header then the server should
352 * respond with 200 OK.
353 * XXX The CGI 1.1 and 1.2 specification differ slightly on
354 * this in that v1.2 says that the script MUST NOT return a
355 * `Status:' header if it is returning a `Location:' header.
356 * For compatibility we are going with the CGI 1.1 behavior.
358 if (strcasecmp(hdr_name, "status") == 0) {
359 debug((DEBUG_OBESE, "process_cgi: writing HTTP header "
360 "from status %s ..", hdr_value));
361 bozoprintf("%s %s\r\n", request->hr_proto, hdr_value);
362 bozoflush(stdout);
363 write_header = 0;
364 free(hdr_name);
365 break;
368 hdr = bozomalloc(sizeof *hdr);
369 hdr->h_header = hdr_name;
370 hdr->h_value = hdr_value;
371 SIMPLEQ_INSERT_TAIL(&headers, hdr, h_next);
372 nheaders++;
375 if (write_header) {
376 debug((DEBUG_OBESE, "process_cgi: writing HTTP header .."));
377 bozoprintf("%s 200 OK\r\n", request->hr_proto);
378 bozoflush(stdout);
381 if (nheaders) {
382 debug((DEBUG_OBESE, "process_cgi: writing delayed HTTP "
383 "headers .."));
384 SIMPLEQ_FOREACH_SAFE(hdr, &headers, h_next, nhdr) {
385 bozoprintf("%s: %s\r\n", hdr->h_header, hdr->h_value);
386 free(hdr->h_header);
387 free(hdr);
389 bozoprintf("\r\n");
390 bozoflush(stdout);
393 /* XXX we should have some goo that times us out
395 while ((rbytes = read(in, buf, sizeof buf)) > 0) {
396 ssize_t wbytes;
397 char *bp = buf;
399 while (rbytes) {
400 wbytes = bozowrite(STDOUT_FILENO, buf, rbytes);
401 if (wbytes > 0) {
402 rbytes -= wbytes;
403 bp += wbytes;
404 } else
405 error(1, "cgi output write failed: %s",
406 strerror(errno));
411 static int
412 parse_header(const char *str, ssize_t len, char **hdr_str, char **hdr_val)
414 char *name, *value;
416 /* if the string passed is zero-length bail out */
417 if (*str == '\0')
418 return -1;
420 value = bozostrdup(str);
422 /* locate the ':' separator in the header/value */
423 name = bozostrnsep(&value, ":", &len);
425 if (NULL == name || -1 == len) {
426 free(name);
427 return -1;
430 /* skip leading space/tab */
431 while (*value == ' ' || *value == '\t')
432 len--, value++;
434 *hdr_str = name;
435 *hdr_val = value;
437 return 0;
441 * given the file name, return a CGI interpreter
443 static const char *
444 content_cgihandler(http_req *request, const char *file)
446 struct content_map *map;
448 debug((DEBUG_FAT, "content_cgihandler: trying file %s", file));
449 map = match_content_map(file, 0);
450 if (map)
451 return (map->cgihandler);
452 return (NULL);
455 static void
456 append_index_html(char **url)
458 *url = bozorealloc(*url, strlen(*url) + strlen(index_html) + 1);
459 strcat(*url, index_html);
460 debug((DEBUG_NORMAL, "append_index_html: url adjusted to `%s'", *url));
463 #ifndef NO_DYNAMIC_CONTENT
464 /* cgi maps are simple ".postfix /path/to/prog" */
465 void
466 add_content_map_cgi(char *arg, char *cgihandler)
468 struct content_map *map;
470 debug((DEBUG_NORMAL, "add_content_map_cgi: name %s cgi %s", arg, cgihandler));
472 Cflag = 1;
474 map = get_content_map(arg);
475 map->name = arg;
476 map->type = map->encoding = map->encoding11 = NULL;
477 map->cgihandler = cgihandler;
479 #endif /* NO_DYNAMIC_CONTENT */
481 #endif /* NO_CGIBIN_SUPPORT */