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