uhttpd: terminate I/O loops if socket writes fail
[project/luci.git] / contrib / package / uhttpd / src / uhttpd-cgi.c
index 4c1265b..4889819 100644 (file)
@@ -1,6 +1,24 @@
+/*
+ * uhttpd - Tiny non-forking httpd - CGI handler
+ *
+ *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
 #include "uhttpd.h"
-#include "uhttpd-cgi.h"
 #include "uhttpd-utils.h"
+#include "uhttpd-cgi.h"
 
 static struct http_response * uh_cgi_header_parse(char *buf, int len, int *off)
 {
@@ -12,9 +30,10 @@ static struct http_response * uh_cgi_header_parse(char *buf, int len, int *off)
        static struct http_response res;
 
 
-       if( (bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL )
-       {
-               *off = (int)(bufptr - buf) + 4;
+       if( ((bufptr = strfind(buf, len, "\r\n\r\n", 4)) != NULL) ||
+           ((bufptr = strfind(buf, len, "\n\n", 2)) != NULL)
+       ) {
+               *off = (int)(bufptr - buf) + ((bufptr[0] == '\r') ? 4 : 2);
 
                memset(&res, 0, sizeof(res));
 
@@ -99,21 +118,24 @@ static char * uh_cgi_header_lookup(struct http_response *res, const char *hdrnam
        return NULL;
 }
 
-static void uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
+static int uh_cgi_error_500(struct client *cl, struct http_request *req, const char *message)
 {
-       uh_http_sendf(cl, NULL,
+       if( uh_http_sendf(cl, NULL,
                "HTTP/%.1f 500 Internal Server Error\r\n"
                "Content-Type: text/plain\r\n%s\r\n",
                        req->version, 
                        (req->version > 1.0)
                                ? "Transfer-Encoding: chunked\r\n" : ""
-       );
+               ) >= 0
+       ) {
+               return uh_http_send(cl, req, message, -1);
+       }
 
-       uh_http_send(cl, req, message, -1);
+       return -1;
 }
 
 
-void uh_cgi_request(struct client *cl, struct http_request *req)
+void uh_cgi_request(struct client *cl, struct http_request *req, struct path_info *pi)
 {
        int i, hdroff, bufoff;
        int hdrlen = 0;
@@ -133,7 +155,6 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
 
        struct timeval timeout;
        struct http_response *res;
-       struct uh_path_info *pi;
 
 
        /* spawn pipes for me->child, child->me */
@@ -169,143 +190,133 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
                        dup2(rfd[1], 1);
                        dup2(wfd[0], 0);
 
-                       if( (pi = uh_path_lookup(cl, req->url)) != NULL )
-                       {
-                               /* check for regular, world-executable file */
-                               if( (pi->stat.st_mode & S_IFREG) &&
-                                   (pi->stat.st_mode & S_IXOTH)
-                               ) {
-                                       /* build environment */
-                                       clearenv();
-
-                                       /* common information */
-                                       setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
-                                       setenv("SERVER_SOFTWARE", "uHTTPd", 1);
-                                       setenv("PATH", "/usr/bin:/bin", 1);
+                       /* check for regular, world-executable file */
+                       if( (pi->stat.st_mode & S_IFREG) &&
+                           (pi->stat.st_mode & S_IXOTH)
+                       ) {
+                               /* build environment */
+                               clearenv();
+
+                               /* common information */
+                               setenv("GATEWAY_INTERFACE", "CGI/1.1", 1);
+                               setenv("SERVER_SOFTWARE", "uHTTPd", 1);
+                               setenv("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
 
 #ifdef HAVE_TLS
-                                       /* https? */
-                                       if( cl->tls )
-                                               setenv("HTTPS", "on", 1);
+                               /* https? */
+                               if( cl->tls )
+                                       setenv("HTTPS", "on", 1);
 #endif
 
-                                       /* addresses */
-                                       setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
-                                       setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
-                                       setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
-                                       setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
-                                       setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
-                                       setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
+                               /* addresses */
+                               setenv("SERVER_NAME", sa_straddr(&cl->servaddr), 1);
+                               setenv("SERVER_ADDR", sa_straddr(&cl->servaddr), 1);
+                               setenv("SERVER_PORT", sa_strport(&cl->servaddr), 1);
+                               setenv("REMOTE_HOST", sa_straddr(&cl->peeraddr), 1);
+                               setenv("REMOTE_ADDR", sa_straddr(&cl->peeraddr), 1);
+                               setenv("REMOTE_PORT", sa_strport(&cl->peeraddr), 1);
 
-                                       /* path information */
-                                       setenv("SCRIPT_NAME", pi->name, 1);
-                                       setenv("SCRIPT_FILENAME", pi->phys, 1);
-                                       setenv("SCRIPT_WORKDIR", pi->wdir, 1);  /* nonstandard */
-                                       setenv("DOCUMENT_ROOT", pi->root, 1);
-                                       setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
+                               /* path information */
+                               setenv("SCRIPT_NAME", pi->name, 1);
+                               setenv("SCRIPT_FILENAME", pi->phys, 1);
+                               setenv("DOCUMENT_ROOT", pi->root, 1);
+                               setenv("QUERY_STRING", pi->query ? pi->query : "", 1);
 
-                                       if( pi->info )
-                                               setenv("PATH_INFO", pi->info, 1);
+                               if( pi->info )
+                                       setenv("PATH_INFO", pi->info, 1);
 
 
-                                       /* http version */
-                                       if( req->version > 1.0 )
-                                               setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
-                                       else
-                                               setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
+                               /* http version */
+                               if( req->version > 1.0 )
+                                       setenv("SERVER_PROTOCOL", "HTTP/1.1", 1);
+                               else
+                                       setenv("SERVER_PROTOCOL", "HTTP/1.0", 1);
 
-                                       /* request method */
-                                       switch( req->method )
-                                       {
-                                               case UH_HTTP_MSG_GET:
-                                                       setenv("REQUEST_METHOD", "GET", 1);
-                                                       break;
+                               /* request method */
+                               switch( req->method )
+                               {
+                                       case UH_HTTP_MSG_GET:
+                                               setenv("REQUEST_METHOD", "GET", 1);
+                                               break;
 
-                                               case UH_HTTP_MSG_HEAD:
-                                                       setenv("REQUEST_METHOD", "HEAD", 1);
-                                                       break;
+                                       case UH_HTTP_MSG_HEAD:
+                                               setenv("REQUEST_METHOD", "HEAD", 1);
+                                               break;
 
-                                               case UH_HTTP_MSG_POST:
-                                                       setenv("REQUEST_METHOD", "POST", 1);
-                                                       break;
-                                       }
+                                       case UH_HTTP_MSG_POST:
+                                               setenv("REQUEST_METHOD", "POST", 1);
+                                               break;
+                               }
 
-                                       /* request url */
-                                       setenv("REQUEST_URI", req->url, 1);
+                               /* request url */
+                               setenv("REQUEST_URI", req->url, 1);
 
-                                       /* request message headers */
-                                       foreach_header(i, req->headers)
-                                       {
-                                               if( ! strcasecmp(req->headers[i], "Accept") )
-                                                       setenv("HTTP_ACCEPT", req->headers[i+1], 1);
+                               /* remote user */
+                               if( req->realm )
+                                       setenv("REMOTE_USER", req->realm->user, 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
-                                                       setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
+                               /* request message headers */
+                               foreach_header(i, req->headers)
+                               {
+                                       if( ! strcasecmp(req->headers[i], "Accept") )
+                                               setenv("HTTP_ACCEPT", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
-                                                       setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Accept-Charset") )
+                                               setenv("HTTP_ACCEPT_CHARSET", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Accept-Language") )
-                                                       setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Accept-Encoding") )
+                                               setenv("HTTP_ACCEPT_ENCODING", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Authorization") )
-                                                       setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Accept-Language") )
+                                               setenv("HTTP_ACCEPT_LANGUAGE", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Connection") )
-                                                       setenv("HTTP_CONNECTION", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Authorization") )
+                                               setenv("HTTP_AUTHORIZATION", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Cookie") )
-                                                       setenv("HTTP_COOKIE", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Connection") )
+                                               setenv("HTTP_CONNECTION", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Host") )
-                                                       setenv("HTTP_HOST", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Cookie") )
+                                               setenv("HTTP_COOKIE", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Referer") )
-                                                       setenv("HTTP_REFERER", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Host") )
+                                               setenv("HTTP_HOST", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "User-Agent") )
-                                                       setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "Referer") )
+                                               setenv("HTTP_REFERER", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Content-Type") )
-                                                       setenv("CONTENT_TYPE", req->headers[i+1], 1);
+                                       else if( ! strcasecmp(req->headers[i], "User-Agent") )
+                                               setenv("HTTP_USER_AGENT", req->headers[i+1], 1);
 
-                                               else if( ! strcasecmp(req->headers[i], "Content-Length") )
-                                                       setenv("CONTENT_LENGTH", req->headers[i+1], 1);
-                                       }
+                                       else if( ! strcasecmp(req->headers[i], "Content-Type") )
+                                               setenv("CONTENT_TYPE", req->headers[i+1], 1);
 
+                                       else if( ! strcasecmp(req->headers[i], "Content-Length") )
+                                               setenv("CONTENT_LENGTH", req->headers[i+1], 1);
+                               }
 
-                                       /* execute child code ... */
-                                       if( chdir(pi->wdir) )
-                                               perror("chdir()");
 
-                                       execl(pi->phys, pi->phys, NULL);
+                               /* execute child code ... */
+                               if( chdir(pi->root) )
+                                       perror("chdir()");
 
-                                       /* in case it fails ... */
-                                       printf(
-                                               "Status: 500 Internal Server Error\r\n\r\n"
-                                               "Unable to launch the requested CGI program:\n"
-                                               "  %s: %s\n",
-                                                       pi->phys, strerror(errno)
-                                       );
-                               }
+                               execl(pi->phys, pi->phys, NULL);
 
-                               /* 403 */
-                               else
-                               {
-                                       printf(
-                                               "Status: 403 Forbidden\r\n\r\n"
-                                               "Access to this resource is forbidden\n"
-                                       );
-                               }
+                               /* in case it fails ... */
+                               printf(
+                                       "Status: 500 Internal Server Error\r\n\r\n"
+                                       "Unable to launch the requested CGI program:\n"
+                                       "  %s: %s\n",
+                                               pi->phys, strerror(errno)
+                               );
                        }
 
-                       /* 404 */
+                       /* 403 */
                        else
                        {
                                printf(
-                                       "Status: 404 Not Found\r\n\r\n"
-                                       "Unable to launch the requested CGI program:\n"
-                                       "  No such file or directory\n"
+                                       "Status: 403 Forbidden\r\n\r\n"
+                                       "Access to this resource is forbidden\n"
                                );
                        }
 
@@ -340,6 +351,9 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
 
                        memset(hdr, 0, sizeof(hdr));
 
+#define ensure(x) \
+       do { if( x < 0 ) goto out; } while(0)
+
                        /* I/O loop, watch our pipe ends and dispatch child reads/writes from/to socket */
                        while( 1 )
                        {
@@ -349,7 +363,7 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
                                FD_SET(rfd[0], &reader);
                                FD_SET(wfd[1], &writer);
 
-                               timeout.tv_sec = 3;
+                               timeout.tv_sec = 15;
                                timeout.tv_usec = 0;
 
                                /* wait until we can read or write or both */
@@ -382,7 +396,7 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
                                                }
 
                                                /* there is no more post data, close pipe to child's stdin */
-                                               else
+                                               else if( content_length > -1 )
                                                {
                                                        close(wfd[1]);
                                                        content_length = -1;
@@ -415,47 +429,49 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
                                                                if( (res = uh_cgi_header_parse(hdr, hdrlen, &hdroff)) != NULL )
                                                                {
                                                                        /* write status */
-                                                                       uh_http_sendf(cl, NULL, "HTTP/%.1f %03d %s\r\n",
-                                                                               req->version, res->statuscode, res->statusmsg);
+                                                                       ensure(uh_http_sendf(cl, NULL,
+                                                                               "HTTP/%.1f %03d %s\r\n",
+                                                                               req->version, res->statuscode,
+                                                                               res->statusmsg));
 
                                                                        /* add Content-Type if no Location or Content-Type */
                                                                        if( !uh_cgi_header_lookup(res, "Location") &&
                                                                            !uh_cgi_header_lookup(res, "Content-Type")
                                                                        ) {
-                                                                               uh_http_send(cl, NULL,
-                                                                                       "Content-Type: text/plain\r\n", -1);
+                                                                               ensure(uh_http_send(cl, NULL,
+                                                                                       "Content-Type: text/plain\r\n", -1));
                                                                        }
 
                                                                        /* if request was HTTP 1.1 we'll respond chunked */
                                                                        if( (req->version > 1.0) &&
                                                                            !uh_cgi_header_lookup(res, "Transfer-Encoding")
                                                                        ) {
-                                                                               uh_http_send(cl, NULL,
-                                                                                       "Transfer-Encoding: chunked\r\n", -1);
+                                                                               ensure(uh_http_send(cl, NULL,
+                                                                                       "Transfer-Encoding: chunked\r\n", -1));
                                                                        }
 
                                                                        /* write headers from CGI program */
                                                                        foreach_header(i, res->headers)
                                                                        {
-                                                                               uh_http_sendf(cl, NULL, "%s: %s\r\n",
-                                                                                       res->headers[i], res->headers[i+1]);
+                                                                               ensure(uh_http_sendf(cl, NULL, "%s: %s\r\n",
+                                                                                       res->headers[i], res->headers[i+1]));
                                                                        }
 
                                                                        /* terminate header */
-                                                                       uh_http_send(cl, NULL, "\r\n", -1);
+                                                                       ensure(uh_http_send(cl, NULL, "\r\n", -1));
 
                                                                        /* push out remaining head buffer */
                                                                        if( hdroff < hdrlen )
-                                                                               uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff);
+                                                                               ensure(uh_http_send(cl, req, &hdr[hdroff], hdrlen - hdroff));
                                                                }
 
                                                                /* ... failed and head buffer exceeded */
                                                                else if( hdrlen >= sizeof(hdr) )
                                                                {
-                                                                       uh_cgi_error_500(cl, req,
-                                                                               "The CGI program generated an invalid response:\n\n");
+                                                                       ensure(uh_cgi_error_500(cl, req,
+                                                                               "The CGI program generated an invalid response:\n\n"));
 
-                                                                       uh_http_send(cl, req, hdr, hdrlen);
+                                                                       ensure(uh_http_send(cl, req, hdr, hdrlen));
                                                                }
 
                                                                /* ... failed but free buffer space, try again */
@@ -466,7 +482,7 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
 
                                                                /* push out remaining read buffer */
                                                                if( bufoff < buflen )
-                                                                       uh_http_send(cl, req, &buf[bufoff], buflen - bufoff);
+                                                                       ensure(uh_http_send(cl, req, &buf[bufoff], buflen - bufoff));
 
                                                                header_sent = 1;
                                                                continue;
@@ -474,29 +490,55 @@ void uh_cgi_request(struct client *cl, struct http_request *req)
 
 
                                                        /* headers complete, pass through buffer to socket */
-                                                       uh_http_send(cl, req, buf, buflen);
+                                                       ensure(uh_http_send(cl, req, buf, buflen));
                                                }
 
                                                /* looks like eof from child */
                                                else
                                                {
+                                                       /* cgi script did not output useful stuff at all */
+                                                       if( ! header_sent )
+                                                       {
+                                                               /* I would do this ...
+                                                                *
+                                                                *    uh_cgi_error_500(cl, req,
+                                                                *        "The CGI program generated an "
+                                                                *        "invalid response:\n\n");
+                                                                *
+                                                                * ... but in order to stay as compatible as possible,
+                                                                * treat whatever we got as text/plain response and
+                                                                * build the required headers here.
+                                                                */
+
+                                                               ensure(uh_http_sendf(cl, NULL,
+                                                                       "HTTP/%.1f 200 OK\r\n"
+                                                                       "Content-Type: text/plain\r\n"
+                                                                       "%s\r\n",
+                                                                               req->version, (req->version > 1.0)
+                                                                                       ? "Transfer-Encoding: chunked\r\n" : ""
+                                                               ));
+
+                                                               ensure(uh_http_send(cl, req, hdr, hdrlen));
+                                                       }
+
                                                        /* send final chunk if we're in chunked transfer mode */
-                                                       uh_http_send(cl, req, "", 0);
+                                                       ensure(uh_http_send(cl, req, "", 0));
                                                        break;
                                                }
                                        }
                                }
 
-                               /* no activity for 3 seconds... looks dead */
+                               /* no activity for 15 seconds... looks dead */
                                else
                                {
-                                       uh_http_sendhf(cl, 504, "Gateway Timeout",
-                                               "The CGI script took too long to produce a response");
+                                       ensure(uh_http_sendhf(cl, 504, "Gateway Timeout",
+                                               "The CGI script took too long to produce a response"));
 
                                        break;
                                }
                        }
 
+               out:
                        close(rfd[0]);
                        close(wfd[1]);