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