2 * uhttpd - Tiny non-forking httpd - CGI handler
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
20 #include "uhttpd-utils.h"
21 #include "uhttpd-cgi.h"
23 static struct http_response * uh_cgi_header_parse(char *buf, int len, int *off)
30 static struct http_response res;
33 if( ((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
34 ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL)
36 *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
38 memset(&res, 0, sizeof(res));
45 for( pos = 0; pos < len; pos++ )
47 if( !hdrname && (buf[pos] == ':') )
51 if( (pos < len) && (buf[pos] == ' ') )
61 else if( (buf[pos] == '\r') || (buf[pos] == '\n') )
68 if( (pos < len) && (buf[pos] == '\n') )
73 if( (hdrcount + 1) < array_size(res.headers) )
75 if( ! strcasecmp(hdrname, "Status") )
77 res.statuscode = atoi(bufptr);
79 if( res.statuscode < 100 )
82 if( ((bufptr = strchr(bufptr, ' ')) != NULL) && (&bufptr[1] != 0) )
83 res.statusmsg = &bufptr[1];
87 res.headers[hdrcount++] = hdrname;
88 res.headers[hdrcount++] = bufptr;
108 static char * uh_cgi_header_lookup(struct http_response *res, const char *hdrname)
112 foreach_header(i, res->headers)
114 if( ! strcasecmp(res->headers[i], hdrname) )
115 return res->headers[i+1];
121 static void uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
123 uh_http_sendf(cl, NULL,
124 "HTTP/%.1f 500 Internal Server Error\r\n"
125 "Content-Type: text/plain\r\n%s\r\n",
128 ? "Transfer-Encoding: chunked\r\n" : ""
131 uh_http_send(cl, req, message, -1);
135 void uh_cgi_request(struct client *cl, struct http_request *req, struct path_info *pi)
137 int i, hdroff, bufoff;
141 int content_length = 0;
144 int rfd[2] = { 0, 0 };
145 int wfd[2] = { 0, 0 };
147 char buf[UH_LIMIT_MSGHEAD];
148 char hdr[UH_LIMIT_MSGHEAD];
153 struct timeval timeout;
154 struct http_response *res;
157 /* spawn pipes for me->child, child->me */
158 if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
160 uh_http_sendhf(cl, 500, "Internal Server Error",
161 "Failed to create pipe: %s", strerror(errno));
163 if( rfd[0] > 0 ) close(rfd[0]);
164 if( rfd[1] > 0 ) close(rfd[1]);
165 if( wfd[0] > 0 ) close(wfd[0]);
166 if( wfd[1] > 0 ) close(wfd[1]);
171 /* fork off child process */
176 uh_http_sendhf(cl, 500, "Internal Server Error",
177 "Failed to fork child: %s", strerror(errno));
186 /* patch stdout and stdin to pipes */
190 /* check for regular, world-executable file */
191 if( (pi->stat.st_mode & S_IFREG) &&
192 (pi->stat.st_mode & S_IXOTH)
194 /* build environment */
197 /* common information */
198 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
199 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
200 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
205 setenv("HTTPS", "on", 1);
209 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
210 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
211 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
212 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
213 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
214 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
216 /* path information */
217 setenv("SCRIPT_NAME", pi->name, 1);
218 setenv("SCRIPT_FILENAME", pi->phys, 1);
219 setenv("DOCUMENT_ROOT", pi->root, 1);
220 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
223 setenv("PATH_INFO", pi->info, 1);
227 if( req->version > 1.0 )
228 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
230 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
233 switch( req->method )
235 case UH_HTTP_MSG_GET:
236 setenv("REQUEST_METHOD", "GET", 1);
239 case UH_HTTP_MSG_HEAD:
240 setenv("REQUEST_METHOD", "HEAD", 1);
243 case UH_HTTP_MSG_POST:
244 setenv("REQUEST_METHOD", "POST", 1);
249 setenv("REQUEST_URI", req->url, 1);
253 setenv("REMOTE_USER", req->realm->user, 1);
255 /* request message headers */
256 foreach_header(i, req->headers)
258 if( ! strcasecmp(req->headers[i], "Accept") )
259 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
261 else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
262 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
264 else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
265 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
267 else if( ! strcasecmp(req->headers[i], "Accept-Language") )
268 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
270 else if( ! strcasecmp(req->headers[i], "Authorization") )
271 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
273 else if( ! strcasecmp(req->headers[i], "Connection") )
274 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
276 else if( ! strcasecmp(req->headers[i], "Cookie") )
277 setenv("HTTP_COOKIE", req->headers[i+1], 1);
279 else if( ! strcasecmp(req->headers[i], "Host") )
280 setenv("HTTP_HOST", req->headers[i+1], 1);
282 else if( ! strcasecmp(req->headers[i], "Referer") )
283 setenv("HTTP_REFERER", req->headers[i+1], 1);
285 else if( ! strcasecmp(req->headers[i], "User-Agent") )
286 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
288 else if( ! strcasecmp(req->headers[i], "Content-Type") )
289 setenv("CONTENT_TYPE", req->headers[i+1], 1);
291 else if( ! strcasecmp(req->headers[i], "Content-Length") )
292 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
296 /* execute child code ... */
297 if( chdir(pi->root) )
300 execl(pi->phys, pi->phys, NULL);
302 /* in case it fails ... */
304 "Status: 500 Internal Server Error\r\n\r\n"
305 "Unable to launch the requested CGI program:\n"
307 pi->phys, strerror(errno)
315 "Status: 403 Forbidden\r\n\r\n"
316 "Access to this resource is forbidden\n"
326 /* parent; handle I/O relaying */
328 /* close unneeded pipe ends */
333 fd_max = max(rfd[0], wfd[1]) + 1;
335 /* find content length */
336 if( req->method == UH_HTTP_MSG_POST )
338 foreach_header(i, req->headers)
340 if( ! strcasecmp(req->headers[i], "Content-Length") )
342 content_length = atoi(req->headers[i+1]);
349 memset(hdr, 0, sizeof(hdr));
351 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
357 FD_SET(rfd[0], &reader);
358 FD_SET(wfd[1], &writer);
363 /* wait until we can read or write or both */
364 if( select(fd_max, &reader, (content_length > -1) ? &writer : NULL, NULL, &timeout) > 0 )
366 /* ready to write to cgi program */
367 if( FD_ISSET(wfd[1], &writer) )
369 /* there is unread post data waiting */
370 if( content_length > 0 )
372 /* read it from socket ... */
373 if( (buflen = uh_tcp_recv(cl, buf, min(content_length, sizeof(buf)))) > 0 )
375 /* ... and write it to child's stdin */
376 if( write(wfd[1], buf, buflen) < 0 )
379 content_length -= buflen;
382 /* unexpected eof! */
385 if( write(wfd[1], "", 0) < 0 )
392 /* there is no more post data, close pipe to child's stdin */
400 /* ready to read from cgi program */
401 if( FD_ISSET(rfd[0], &reader) )
403 /* read data from child ... */
404 if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
406 /* we have not pushed out headers yet, parse input */
409 /* head buffer not full and no end yet */
410 if( hdrlen < sizeof(hdr) )
412 bufoff = min(buflen, sizeof(hdr) - hdrlen);
413 memcpy(&hdr[hdrlen], buf, bufoff);
422 /* try to parse header ... */
423 if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
426 uh_http_sendf(cl, NULL, "HTTP/%.1f %03d %s\r\n",
427 req->version, res->statuscode, res->statusmsg);
429 /* add Content-Type if no Location or Content-Type */
430 if( !uh_cgi_header_lookup(res, "Location") &&
431 !uh_cgi_header_lookup(res, "Content-Type")
433 uh_http_send(cl, NULL,
434 "Content-Type: text/plain\r\n", -1);
437 /* if request was HTTP 1.1 we'll respond chunked */
438 if( (req->version > 1.0) &&
439 !uh_cgi_header_lookup(res, "Transfer-Encoding")
441 uh_http_send(cl, NULL,
442 "Transfer-Encoding: chunked\r\n", -1);
445 /* write headers from CGI program */
446 foreach_header(i, res->headers)
448 uh_http_sendf(cl, NULL, "%s: %s\r\n",
449 res->headers[i], res->headers[i+1]);
452 /* terminate header */
453 uh_http_send(cl, NULL, "\r\n", -1);
455 /* push out remaining head buffer */
456 if( hdroff < hdrlen )
457 uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff);
460 /* ... failed and head buffer exceeded */
461 else if( hdrlen >= sizeof(hdr) )
463 uh_cgi_error_500(cl, req,
464 "The CGI program generated an invalid response:\n\n");
466 uh_http_send(cl, req, hdr, hdrlen);
469 /* ... failed but free buffer space, try again */
475 /* push out remaining read buffer */
476 if( bufoff < buflen )
477 uh_http_send(cl, req, &buf[bufoff], buflen - bufoff);
484 /* headers complete, pass through buffer to socket */
485 uh_http_send(cl, req, buf, buflen);
488 /* looks like eof from child */
491 /* cgi script did not output useful stuff at all */
494 /* I would do this ...
496 * uh_cgi_error_500(cl, req,
497 * "The CGI program generated an "
498 * "invalid response:\n\n");
500 * ... but in order to stay as compatible as possible,
501 * treat whatever we got as text/plain response and
502 * build the required headers here.
505 uh_http_sendf(cl, NULL,
506 "HTTP/%.1f 200 OK\r\n"
507 "Content-Type: text/plain\r\n"
509 req->version, (req->version > 1.0)
510 ? "Transfer-Encoding: chunked\r\n" : ""
513 uh_http_send(cl, req, hdr, hdrlen);
516 /* send final chunk if we're in chunked transfer mode */
517 uh_http_send(cl, req, "", 0);
523 /* no activity for 3 seconds... looks dead */
526 uh_http_sendhf(cl, 504, "Gateway Timeout",
527 "The CGI script took too long to produce a response");