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