2 * uhttpd - Tiny single-threaded 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 int uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
123 if( 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 return uh_http_send(cl, req, message, -1);
139 struct client *cl, struct http_request *req,
140 struct path_info *pi, struct interpreter *ip
142 int i, hdroff, bufoff, rv;
146 int content_length = 0;
149 int rfd[2] = { 0, 0 };
150 int wfd[2] = { 0, 0 };
152 char buf[UH_LIMIT_MSGHEAD];
153 char hdr[UH_LIMIT_MSGHEAD];
161 struct timeval timeout;
162 struct http_response *res;
165 /* spawn pipes for me->child, child->me */
166 if( (pipe(rfd) < 0) || (pipe(wfd) < 0) )
168 uh_http_sendhf(cl, 500, "Internal Server Error",
169 "Failed to create pipe: %s", strerror(errno));
171 if( rfd[0] > 0 ) close(rfd[0]);
172 if( rfd[1] > 0 ) close(rfd[1]);
173 if( wfd[0] > 0 ) close(wfd[0]);
174 if( wfd[1] > 0 ) close(wfd[1]);
179 /* fork off child process */
180 switch( (child = fork()) )
184 uh_http_sendhf(cl, 500, "Internal Server Error",
185 "Failed to fork child: %s", strerror(errno));
190 /* restore SIGTERM */
192 sa.sa_handler = SIG_DFL;
193 sigemptyset(&sa.sa_mask);
194 sigaction(SIGTERM, &sa, NULL);
196 /* close loose pipe ends */
200 /* patch stdout and stdin to pipes */
204 /* check for regular, world-executable file _or_ interpreter */
205 if( ((pi->stat.st_mode & S_IFREG) &&
206 (pi->stat.st_mode & S_IXOTH)) || (ip != NULL)
208 /* build environment */
211 /* common information */
212 setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
213 setenv("SERVER_SOFTWARE", "uHTTPd", 1);
214 setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
219 setenv("HTTPS", "on", 1);
223 setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
224 setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
225 setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
226 setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
227 setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
228 setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
230 /* path information */
231 setenv("SCRIPT_NAME", pi->name, 1);
232 setenv("SCRIPT_FILENAME", pi->phys, 1);
233 setenv("DOCUMENT_ROOT", pi->root, 1);
234 setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
237 setenv("PATH_INFO", pi->info, 1);
239 /* REDIRECT_STATUS, php-cgi wants it */
240 switch( req->redirect_status )
243 setenv("REDIRECT_STATUS", "404", 1);
247 setenv("REDIRECT_STATUS", "200", 1);
252 if( req->version > 1.0 )
253 setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
255 setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
258 switch( req->method )
260 case UH_HTTP_MSG_GET:
261 setenv("REQUEST_METHOD", "GET", 1);
264 case UH_HTTP_MSG_HEAD:
265 setenv("REQUEST_METHOD", "HEAD", 1);
268 case UH_HTTP_MSG_POST:
269 setenv("REQUEST_METHOD", "POST", 1);
274 setenv("REQUEST_URI", req->url, 1);
278 setenv("REMOTE_USER", req->realm->user, 1);
280 /* request message headers */
281 foreach_header(i, req->headers)
283 if( ! strcasecmp(req->headers[i], "Accept") )
284 setenv("HTTP_ACCEPT", req->headers[i+1], 1);
286 else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
287 setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
289 else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
290 setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
292 else if( ! strcasecmp(req->headers[i], "Accept-Language") )
293 setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
295 else if( ! strcasecmp(req->headers[i], "Authorization") )
296 setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
298 else if( ! strcasecmp(req->headers[i], "Connection") )
299 setenv("HTTP_CONNECTION", req->headers[i+1], 1);
301 else if( ! strcasecmp(req->headers[i], "Cookie") )
302 setenv("HTTP_COOKIE", req->headers[i+1], 1);
304 else if( ! strcasecmp(req->headers[i], "Host") )
305 setenv("HTTP_HOST", req->headers[i+1], 1);
307 else if( ! strcasecmp(req->headers[i], "Referer") )
308 setenv("HTTP_REFERER", req->headers[i+1], 1);
310 else if( ! strcasecmp(req->headers[i], "User-Agent") )
311 setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
313 else if( ! strcasecmp(req->headers[i], "Content-Type") )
314 setenv("CONTENT_TYPE", req->headers[i+1], 1);
316 else if( ! strcasecmp(req->headers[i], "Content-Length") )
317 setenv("CONTENT_LENGTH", req->headers[i+1], 1);
321 /* execute child code ... */
322 if( chdir(pi->root) )
326 execl(ip->path, ip->path, pi->phys, NULL);
328 execl(pi->phys, pi->phys, NULL);
330 /* in case it fails ... */
332 "Status: 500 Internal Server Error\r\n\r\n"
333 "Unable to launch the requested CGI program:\n"
335 ip ? ip->path : pi->phys, strerror(errno)
343 "Status: 403 Forbidden\r\n\r\n"
344 "Access to this resource is forbidden\n"
354 /* parent; handle I/O relaying */
356 /* close unneeded pipe ends */
361 fd_max = max(rfd[0], wfd[1]) + 1;
363 /* find content length */
364 if( req->method == UH_HTTP_MSG_POST )
366 foreach_header(i, req->headers)
368 if( ! strcasecmp(req->headers[i], "Content-Length") )
370 content_length = atoi(req->headers[i+1]);
377 memset(hdr, 0, sizeof(hdr));
379 /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
385 FD_SET(rfd[0], &reader);
386 FD_SET(wfd[1], &writer);
388 timeout.tv_sec = (header_sent < 1) ? cl->server->conf->script_timeout : 3;
391 ensure_out(rv = select_intr(fd_max, &reader,
392 (content_length > -1) ? &writer : NULL, NULL, &timeout));
397 ensure_out(kill(child, 0));
400 /* wait until we can read or write or both */
403 /* ready to write to cgi program */
404 if( FD_ISSET(wfd[1], &writer) )
406 /* there is unread post data waiting */
407 if( content_length > 0 )
409 /* read it from socket ... */
410 ensure_out(buflen = uh_tcp_recv(cl, buf,
411 min(content_length, sizeof(buf))));
415 /* ... and write it to child's stdin */
416 if( write(wfd[1], buf, buflen) < 0 )
419 content_length -= buflen;
422 /* unexpected eof! */
425 if( write(wfd[1], "", 0) < 0 )
432 /* there is no more post data, close pipe to child's stdin */
433 else if( content_length > -1 )
440 /* ready to read from cgi program */
441 if( FD_ISSET(rfd[0], &reader) )
443 /* read data from child ... */
444 if( (buflen = read(rfd[0], buf, sizeof(buf))) > 0 )
446 /* we have not pushed out headers yet, parse input */
449 /* head buffer not full and no end yet */
450 if( hdrlen < sizeof(hdr) )
452 bufoff = min(buflen, sizeof(hdr) - hdrlen);
453 memcpy(&hdr[hdrlen], buf, bufoff);
462 /* try to parse header ... */
463 if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
466 ensure_out(uh_http_sendf(cl, NULL,
467 "HTTP/%.1f %03d %s\r\n"
468 "Connection: close\r\n",
469 req->version, res->statuscode,
472 /* add Content-Type if no Location or Content-Type */
473 if( !uh_cgi_header_lookup(res, "Location") &&
474 !uh_cgi_header_lookup(res, "Content-Type")
476 ensure_out(uh_http_send(cl, NULL,
477 "Content-Type: text/plain\r\n", -1));
480 /* if request was HTTP 1.1 we'll respond chunked */
481 if( (req->version > 1.0) &&
482 !uh_cgi_header_lookup(res, "Transfer-Encoding")
484 ensure_out(uh_http_send(cl, NULL,
485 "Transfer-Encoding: chunked\r\n", -1));
488 /* write headers from CGI program */
489 foreach_header(i, res->headers)
491 ensure_out(uh_http_sendf(cl, NULL, "%s: %s\r\n",
492 res->headers[i], res->headers[i+1]));
495 /* terminate header */
496 ensure_out(uh_http_send(cl, NULL, "\r\n", -1));
498 /* push out remaining head buffer */
499 if( hdroff < hdrlen )
500 ensure_out(uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff));
503 /* ... failed and head buffer exceeded */
504 else if( hdrlen >= sizeof(hdr) )
506 ensure_out(uh_cgi_error_500(cl, req,
507 "The CGI program generated an invalid response:\n\n"));
509 ensure_out(uh_http_send(cl, req, hdr, hdrlen));
512 /* ... failed but free buffer space, try again */
518 /* push out remaining read buffer */
519 if( bufoff < buflen )
520 ensure_out(uh_http_send(cl, req, &buf[bufoff], buflen - bufoff));
527 /* headers complete, pass through buffer to socket */
528 ensure_out(uh_http_send(cl, req, buf, buflen));
531 /* looks like eof from child */
534 /* cgi script did not output useful stuff at all */
537 /* I would do this ...
539 * uh_cgi_error_500(cl, req,
540 * "The CGI program generated an "
541 * "invalid response:\n\n");
543 * ... but in order to stay as compatible as possible,
544 * treat whatever we got as text/plain response and
545 * build the required headers here.
548 ensure_out(uh_http_sendf(cl, NULL,
549 "HTTP/%.1f 200 OK\r\n"
550 "Content-Type: text/plain\r\n"
552 req->version, (req->version > 1.0)
553 ? "Transfer-Encoding: chunked\r\n" : ""
556 ensure_out(uh_http_send(cl, req, hdr, hdrlen));
559 /* send final chunk if we're in chunked transfer mode */
560 ensure_out(uh_http_send(cl, req, "", 0));
566 /* timeout exceeded or interrupted by SIGCHLD */
569 if( (errno != EINTR) && ! header_sent )
571 ensure_out(uh_http_sendhf(cl, 504, "Gateway Timeout",
572 "The CGI script took too long to produce "
576 /* send final chunk if we're in chunked transfer mode */
577 ensure_out(uh_http_send(cl, req, "", 0));
587 if( !kill(child, 0) )
589 kill(child, SIGTERM);
590 waitpid(child, NULL, 0);