Wade Berrier writes:
[oweals/busybox.git] / networking / httpd.c
index 6f5100c9ebe15188cf9d5117edede088d303a8f4..83ded53309b2080c0a67829ac293f30aee31f0be 100644 (file)
@@ -2,7 +2,7 @@
  * httpd implementation for busybox
  *
  * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
- * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
+ * Copyright (C) 2003,2004 Vladimir Oleynik <dzo@simtreas.ru>
  *
  * simplify patch stolen from libbb without using strdup
  *
  *
  * When a url contains "cgi-bin" it is assumed to be a cgi script.  The
  * server changes directory to the location of the script and executes it
- * after setting QUERY_STRING and other environment variables.  If url args
- * are included in the url or as a post, the args are placed into decoded
- * environment variables.  e.g. /cgi-bin/setup?foo=Hello%20World  will set
- * the $CGI_foo environment variable to "Hello World" while
- * CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV enabled.
+ * after setting QUERY_STRING and other environment variables.
  *
  * The server can also be invoked as a url arg decoder and html text encoder
  * as follows:
  *  foo=`httpd -d $foo`           # decode "Hello%20World" as "Hello World"
  *  bar=`httpd -e "<Hello World>"`  # encode as "&#60Hello&#32World&#62"
  * Note that url encoding for arguments is not the same as html encoding for
- * presenation.  -d decodes a url-encoded argument while -e encodes in html
+ * presentation.  -d decodes a url-encoded argument while -e encodes in html
  * for page display.
  *
  * httpd.conf has the following format:
- * 
+ *
  * A:172.20.         # Allow address from 172.20.0.0/16
  * A:10.0.0.0/25     # Allow any address from 10.0.0.0-10.0.0.127
  * A:10.0.0.0/255.255.255.128  # Allow any address that previous set
  * /adm:admin:setup  # Require user admin, pwd setup on urls starting with /adm/
  * /adm:toor:PaSsWd  # or user toor, pwd PaSsWd on urls starting with /adm/
  * .au:audio/basic   # additional mime type for audio.au files
- * 
- * A/D may be as a/d or allow/deny - first char case unsensitive
+ *
+ * A/D may be as a/d or allow/deny - first char case insensitive
  * Deny IP rules take precedence over allow rules.
- * 
- * 
+ *
+ *
  * The Deny/Allow IP logic:
- * 
+ *
  *  - Default is to allow all.  No addresses are denied unless
- *        denied with a D: rule.
+ *         denied with a D: rule.
  *  - Order of Deny/Allow rules is significant
  *  - Deny rules take precedence over allow rules.
  *  - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
- *      addresses.
+ *       addresses.
  *  - Specification of Allow all (A:*) is a no-op
- * 
+ *
  * Example:
  *   1. Allow only specified addresses
  *     A:172.20          # Allow any address that begins with 172.20.
  *     A:10.10.          # Allow any address that begins with 10.10.
  *     A:127.0.0.1       # Allow local loopback connections
  *     D:*               # Deny from other IP connections
- * 
+ *
  *   2. Only deny specified addresses
  *     D:1.2.3.        # deny from 1.2.3.0 - 1.2.3.255
  *     D:2.3.4.        # deny from 2.3.4.0 - 2.3.4.255
  *     A:*             # (optional line added for clarity)
- * 
+ *
  * If a sub directory contains a config file it is parsed and merged with
  * any existing settings as if it was appended to the original configuration.
  *
  * subdir http request, any merge is discarded when the process exits.  As a
  * result, the subdir settings only have a lifetime of a single request.
  *
- * 
- * If -c is not set, an attempt will be made to open the default 
+ *
+ * If -c is not set, an attempt will be made to open the default
  * root configuration file.  If -c is set and the file is not found, the
  * server exits with an error.
- * 
+ *
 */
 
 
 #include "busybox.h"
 
 
-static const char httpdVersion[] = "busybox httpd/1.30 7-Sep-2003";
+static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
 static const char default_path_httpd_conf[] = "/etc";
 static const char httpd_conf[] = "httpd.conf";
 static const char home[] = "./";
@@ -131,8 +127,9 @@ static const char home[] = "./";
 # define cont_l_fmt "%ld"
 #endif
 
+#define TIMEOUT 60
 
-// Note: bussybox xfuncs are not used because we want the server to keep running
+// Note: busybox xfuncs are not used because we want the server to keep running
 //       if something bad happens due to a malformed user request.
 //       As a result, all memory allocation after daemonize
 //       is checked rigorously
@@ -142,7 +139,6 @@ static const char home[] = "./";
 /* Configure options, disabled by default as custom httpd feature */
 
 /* disabled as optional features */
-//#define CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
 //#define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
 //#define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
 //#define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
@@ -166,7 +162,6 @@ static const char home[] = "./";
 /* unset config option for remove warning as redefined */
 #undef CONFIG_FEATURE_HTTPD_BASIC_AUTH
 #undef CONFIG_FEATURE_HTTPD_AUTH_MD5
-#undef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
 #undef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
 #undef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
 #undef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
@@ -176,7 +171,6 @@ static const char home[] = "./";
 /* enable all features now */
 #define CONFIG_FEATURE_HTTPD_BASIC_AUTH
 #define CONFIG_FEATURE_HTTPD_AUTH_MD5
-#define CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
 #define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
 #define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
 #define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
@@ -202,8 +196,6 @@ void bb_show_usage(void)
 #undef DEBUG
 #endif
 
-#define MAX_POST_SIZE (64*1024) /* 64k. Its Small? May be ;) */
-
 #define MAX_MEMORY_BUFF 8192    /* IO buffer */
 
 typedef struct HT_ACCESS {
@@ -225,7 +217,15 @@ typedef struct
 
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
   const char *realm;
+  char *remoteuser;
+#endif
+
+  const char *query;
+
+#ifdef CONFIG_FEATURE_HTTPD_CGI
+  char *referer;
 #endif
+
   const char *configFile;
 
   unsigned int rmt_ip;
@@ -234,8 +234,11 @@ typedef struct
 #endif
   unsigned port;           /* server initial port and for
                              set env REMOTE_PORT */
+  union HTTPD_FOUND {
+       const char *found_mime_type;
+       const char *found_moved_temporarily;
+  } httpd_found;
 
-  const char *found_mime_type;
   off_t ContentLength;          /* -1 - unknown */
   time_t last_mod;
 
@@ -257,6 +260,8 @@ typedef struct
 #define a_c_r 0
 #define a_c_w 1
 #endif
+  volatile int alarm_signaled;
+
 } HttpdConfig;
 
 static HttpdConfig *config;
@@ -264,7 +269,7 @@ static HttpdConfig *config;
 static const char request_GET[] = "GET";    /* size algorithic optimize */
 
 static const char* const suffixTable [] = {
-/* Warning: shorted equalent suffix in one line must be first */
+/* Warning: shorted equivalent suffix in one line must be first */
   ".htm.html", "text/html",
   ".jpg.jpeg", "image/jpeg",
   ".gif", "image/gif",
@@ -288,11 +293,13 @@ static const char* const suffixTable [] = {
 typedef enum
 {
   HTTP_OK = 200,
+  HTTP_MOVED_TEMPORARILY = 302,
+  HTTP_BAD_REQUEST = 400,       /* malformed syntax */
   HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
   HTTP_NOT_FOUND = 404,
-  HTTP_NOT_IMPLEMENTED = 501,   /* used for unrecognized requests */
-  HTTP_BAD_REQUEST = 400,       /* malformed syntax */
   HTTP_FORBIDDEN = 403,
+  HTTP_REQUEST_TIMEOUT = 408,
+  HTTP_NOT_IMPLEMENTED = 501,   /* used for unrecognized requests */
   HTTP_INTERNAL_SERVER_ERROR = 500,
 #if 0 /* future use */
   HTTP_CONTINUE = 100,
@@ -303,7 +310,6 @@ typedef enum
   HTTP_NO_CONTENT = 204,
   HTTP_MULTIPLE_CHOICES = 300,
   HTTP_MOVED_PERMANENTLY = 301,
-  HTTP_MOVED_TEMPORARILY = 302,
   HTTP_NOT_MODIFIED = 304,
   HTTP_PAYMENT_REQUIRED = 402,
   HTTP_BAD_GATEWAY = 502,
@@ -321,6 +327,9 @@ typedef struct
 
 static const HttpEnumString httpResponseNames[] = {
   { HTTP_OK, "OK" },
+  { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
+  { HTTP_REQUEST_TIMEOUT, "Request Timeout",
+    "No request appeared within a reasonable time period." },
   { HTTP_NOT_IMPLEMENTED, "Not Implemented",
     "The requested method is not recognized by this server." },
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
@@ -338,7 +347,6 @@ static const HttpEnumString httpResponseNames[] = {
   { HTTP_NO_CONTENT, "No Content" },
   { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
   { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
-  { HTTP_MOVED_TEMPORARILY, "Moved Temporarily" },
   { HTTP_NOT_MODIFIED, "Not Modified" },
   { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
   { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
@@ -451,7 +459,7 @@ static void free_config_lines(Htaccess **pprev)
  > $Function: parse_conf()
  *
  * $Description: parse configuration file into in-memory linked list.
- * 
+ *
  * The first non-white character is examined to determine if the config line
  * is one of the following:
  *    .ext:mime/type   # new mime type not compiled into httpd
@@ -468,17 +476,16 @@ static void free_config_lines(Htaccess **pprev)
  *                              checks.
  *      (int) flag  . . . . . . the source of the parse request.
  *
- * $Return: (None) 
+ * $Return: (None)
  *
  ****************************************************************************/
 static void parse_conf(const char *path, int flag)
 {
     FILE *f;
-#if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
-    Htaccess *cur;
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
-    Htaccess *prev;
-#endif
+    Htaccess *prev, *cur;
+#elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
+    Htaccess *cur;
 #endif
 
     const char *cf = config->configFile;
@@ -780,7 +787,7 @@ static char *decodeString(char *orig, int flag_plus_to_space)
  *
  > $Function: addEnv()
  *
- * $Description: Add an enviornment variable setting to the global list.
+ * $Description: Add an environment variable setting to the global list.
  *    A NAME=VALUE string is allocated, filled, and added to the list of
  *    environment settings passed to the cgi execution script.
  *
@@ -822,58 +829,6 @@ static void addEnvPort(const char *port_name)
 #endif
 #endif          /* CONFIG_FEATURE_HTTPD_CGI */
 
-#ifdef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
-/****************************************************************************
- *
- > $Function: addEnvCgi
- *
- * $Description: Create environment variables given a URL encoded arg list.
- *   For each variable setting the URL encoded arg list, create a corresponding
- *   environment variable.  URL encoded arguments have the form
- *      name1=value1&name2=value2&name3=&ignores
- *       from this example, name3 set empty value, tail without '=' skiping
- *
- * $Parameters:
- *      (char *) pargs . . . . A pointer to the URL encoded arguments.
- *
- * $Return: None
- *
- * $Errors: None
- *
- ****************************************************************************/
-static void addEnvCgi(const char *pargs)
-{
-  char *args;
-  char *memargs;
-  char *namelist; /* space separated list of arg names */
-  if (pargs==0) return;
-
-  /* args are a list of name=value&name2=value2 sequences */
-  namelist = (char *) malloc(strlen(pargs));
-  if (namelist) namelist[0]=0;
-  memargs = args = strdup(pargs);
-  while (args && *args) {
-    const char *name = args;
-    char *value = strchr(args, '=');
-
-    if (!value)         /* &XXX without '=' */
-       break;
-    *value++ = 0;
-    args = strchr(value, '&');
-    if (args)
-       *args++ = 0;
-    addEnv("CGI", name, decodeString(value, 1));
-    if (*namelist) strcat(namelist, " ");
-    strcat(namelist, name);
-  }
-  free(memargs);
-  if (namelist) {
-    addEnv("CGI", "ARGLIST_", namelist);
-    free(namelist);
-  }
-}
-#endif /* CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV */
-
 
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
 /****************************************************************************
@@ -1000,6 +955,7 @@ static int sendHeaders(HttpResponseNum responseNum)
   char *buf = config->buf;
   const char *responseString = "";
   const char *infoString = 0;
+  const char *mime_type;
   unsigned int i;
   time_t timer = time(0);
   char timeStr[80];
@@ -1013,16 +969,16 @@ static int sendHeaders(HttpResponseNum responseNum)
                        break;
                }
   }
-  if (responseNum != HTTP_OK) {
-       config->found_mime_type = "text/html";  // error message is HTML
-  }
+  /* error message is HTML */
+  mime_type = responseNum == HTTP_OK ?
+               config->httpd_found.found_mime_type : "text/html";
 
   /* emit the current date */
   strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
   len = sprintf(buf,
        "HTTP/1.0 %d %s\nContent-type: %s\r\n"
        "Date: %s\r\nConnection: close\r\n",
-         responseNum, responseString, config->found_mime_type, timeStr);
+         responseNum, responseString, mime_type, timeStr);
 
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
   if (responseNum == HTTP_UNAUTHORIZED) {
@@ -1030,6 +986,13 @@ static int sendHeaders(HttpResponseNum responseNum)
                                                            config->realm);
   }
 #endif
+  if(responseNum == HTTP_MOVED_TEMPORARILY) {
+       len += sprintf(buf+len, "Location: %s/%s%s\r\n",
+               config->httpd_found.found_moved_temporarily,
+               (config->query ? "?" : ""),
+               (config->query ? config->query : ""));
+  }
+
   if (config->ContentLength != -1) {    /* file */
     strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
     len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
@@ -1058,15 +1021,13 @@ static int sendHeaders(HttpResponseNum responseNum)
  *
  *   Characters are read one at a time until an eol sequence is found.
  *
- * $Parameters:
- *      (char *) buf  . . Where to place the read result.
- *
  * $Return: (int) . . . . number of characters read.  -1 if error.
  *
  ****************************************************************************/
-static int getLine(char *buf)
+static int getLine(void)
 {
   int  count = 0;
+  char *buf = config->buf;
 
   while (read(a_c_r, buf + count, 1) == 1) {
     if (buf[count] == '\r') continue;
@@ -1093,11 +1054,10 @@ static int getLine(char *buf)
  *   data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
  *
  * $Parameters:
- *      (const char *) url . . . The requested URL (with leading /).
- *      (const char *urlArgs). . Any URL arguments.
- *      (const char *body) . . . POST body contents.
- *      (int bodyLen)  . . . . . Length of the post body.
- *      (const char *cookie) . . For set HTTP_COOKIE.
+ *      (const char *) url . . . . . . The requested URL (with leading /).
+ *      (int bodyLen)  . . . . . . . . Length of the post body.
+ *      (const char *cookie) . . . . . For set HTTP_COOKIE.
+ *      (const char *content_type) . . For set CONTENT_TYPE.
 
  *
  * $Return: (char *)  . . . . A pointer to the decoded string (same as input).
@@ -1106,8 +1066,8 @@ static int getLine(char *buf)
  *
  ****************************************************************************/
 static int sendCgi(const char *url,
-                  const char *request, const char *urlArgs,
-                  const char *body, int bodyLen, const char *cookie)
+                  const char *request, int bodyLen, const char *cookie,
+                  const char *content_type)
 {
   int fromCgi[2];  /* pipe for reading data from CGI */
   int toCgi[2];    /* pipe for sending data to CGI */
@@ -1174,11 +1134,12 @@ static int sendCgi(const char *url,
        *script = '/';          /* is directory, find next '/' */
       }
       addEnv("PATH", "INFO", script);   /* set /PATH_INFO or NULL */
+      addEnv("PATH",           "",         getenv("PATH"));
       addEnv("REQUEST",        "METHOD",   request);
-      if(urlArgs) {
-       char *uri = alloca(strlen(purl) + 2 + strlen(urlArgs));
+      if(config->query) {
+       char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
        if(uri)
-           sprintf(uri, "%s?%s", purl, urlArgs);
+           sprintf(uri, "%s?%s", purl, config->query);
        addEnv("REQUEST",        "URI",   uri);
       } else {
        addEnv("REQUEST",        "URI",   purl);
@@ -1187,32 +1148,32 @@ static int sendCgi(const char *url,
        *script = '\0';         /* reduce /PATH_INFO */
       /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
       addEnv("SCRIPT_NAME",    "",         purl);
-      addEnv("QUERY_STRING",   "",         urlArgs);
+      addEnv("QUERY_STRING",   "",         config->query);
       addEnv("SERVER",         "SOFTWARE", httpdVersion);
       addEnv("SERVER",         "PROTOCOL", "HTTP/1.0");
       addEnv("GATEWAY_INTERFACE", "",      "CGI/1.1");
-#ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
       addEnv("REMOTE",         "ADDR",     config->rmt_ip_str);
+#ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
       addEnvPort("REMOTE");
-#else
-      addEnv("REMOTE_ADDR",     "",        config->rmt_ip_str);
 #endif
       if(bodyLen) {
        char sbl[32];
 
        sprintf(sbl, "%d", bodyLen);
-       addEnv("CONTENT_LENGTH", "", sbl);
+       addEnv("CONTENT", "LENGTH", sbl);
       }
       if(cookie)
-       addEnv("HTTP_COOKIE", "", cookie);
-
-#ifdef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
-      if (request != request_GET) {
-       addEnvCgi(body);
-      } else {
-       addEnvCgi(urlArgs);
+       addEnv("HTTP", "COOKIE", cookie);
+      if(content_type)
+       addEnv("CONTENT", "TYPE", content_type);
+#ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
+      if(config->remoteuser) {
+       addEnv("REMOTE", "USER", config->remoteuser);
+       addEnv("AUTH_TYPE", "", "Basic");
       }
 #endif
+      if(config->referer)
+       addEnv("HTTP", "REFERER", config->referer);
 
        /* set execve argp[0] without path */
       argp[0] = strrchr( purl, '/' ) + 1;
@@ -1242,28 +1203,41 @@ static int sendCgi(const char *url,
   if (pid) {
     /* parent process */
     int status;
+    size_t post_readed_size = 0, post_readed_idx = 0;
 
     inFd  = fromCgi[0];
     outFd = toCgi[1];
     close(fromCgi[1]);
     close(toCgi[0]);
-    if (body) bb_full_write(outFd, body, bodyLen);
-    close(outFd);
+    signal(SIGPIPE, SIG_IGN);
 
     while (1) {
-      struct timeval timeout;
       fd_set readSet;
-      char buf[160];
+      fd_set writeSet;
+      char wbuf[128];
       int nfound;
       int count;
 
       FD_ZERO(&readSet);
+      FD_ZERO(&writeSet);
       FD_SET(inFd, &readSet);
-
+      if(bodyLen > 0 || post_readed_size > 0) {
+       FD_SET(outFd, &writeSet);
+       nfound = outFd > inFd ? outFd : inFd;
+       if(post_readed_size == 0) {
+               FD_SET(a_c_r, &readSet);
+               if(nfound < a_c_r)
+                       nfound = a_c_r;
+       }
       /* Now wait on the set of sockets! */
-      timeout.tv_sec = 0;
-      timeout.tv_usec = 10000;
-      nfound = select(inFd + 1, &readSet, 0, 0, &timeout);
+       nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
+      } else {
+       if(!bodyLen) {
+               close(outFd);
+               bodyLen = -1;
+       }
+       nfound = select(inFd + 1, &readSet, 0, 0, NULL);
+      }
 
       if (nfound <= 0) {
        if (waitpid(pid, &status, WNOHANG) > 0) {
@@ -1276,29 +1250,58 @@ static int sendCgi(const char *url,
              bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
          }
 #endif
-         pid = -1;
          break;
        }
+      } else if(post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
+               count = bb_full_write(outFd, wbuf + post_readed_idx, post_readed_size);
+               if(count > 0) {
+                       post_readed_size -= count;
+                       post_readed_idx += count;
+                       if(post_readed_size == 0)
+                               post_readed_idx = 0;
+               }
+      } else if(bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
+               count = bodyLen > sizeof(wbuf) ? sizeof(wbuf) : bodyLen;
+               count = safe_read(a_c_r, wbuf, count);
+               if(count > 0) {
+                       post_readed_size += count;
+                       bodyLen -= count;
       } else {
+                       bodyLen = 0;    /* closed */
+               }
+      }
+      if(FD_ISSET(inFd, &readSet)) {
        int s = a_c_w;
+       char *rbuf = config->buf;
+
+#ifndef PIPE_BUF
+# define PIPESIZE 4096          /* amount of buffering in a pipe */
+#else
+# define PIPESIZE PIPE_BUF
+#endif
+#if PIPESIZE >= MAX_MEMORY_BUFF
+# error "PIPESIZE >= MAX_MEMORY_BUFF"
+#endif
 
        // There is something to read
-       count = bb_full_read(inFd, buf, sizeof(buf)-1);
-       // If a read returns 0 at this point then some type of error has
-       // occurred.  Bail now.
-       if (count == 0) break;
+       count = safe_read(inFd, rbuf, PIPESIZE);
+       if (count == 0)
+               break;  /* closed */
        if (count > 0) {
          if (firstLine) {
+           rbuf[count] = 0;
            /* check to see if the user script added headers */
-           if (strncmp(buf, "HTTP/1.0 200 OK\n", 4) != 0) {
+           if(strncmp(rbuf, "HTTP/1.0 200 OK\n", 4) != 0) {
              bb_full_write(s, "HTTP/1.0 200 OK\n", 16);
            }
-           if (strstr(buf, "ontent-") == 0) {
+           if (strstr(rbuf, "ontent-") == 0) {
              bb_full_write(s, "Content-type: text/plain\n\n", 26);
            }
-           firstLine=0;
+           firstLine = 0;
          }
-         bb_full_write(s, buf, count);
+         if (bb_full_write(s, rbuf, count) != count)
+             break;
+
 #ifdef DEBUG
          if (config->debugHttpd)
                fprintf(stderr, "cgi read %d bytes\n", count);
@@ -1319,12 +1322,11 @@ static int sendCgi(const char *url,
  *
  * $Parameter:
  *      (const char *) url . . The URL requested.
- *      (char *) buf . . . . . The stack buffer.
  *
  * $Return: (int)  . . . . . . Always 0.
  *
  ****************************************************************************/
-static int sendFile(const char *url, char *buf)
+static int sendFile(const char *url)
 {
   char * suffix;
   int  f;
@@ -1340,14 +1342,14 @@ static int sendFile(const char *url, char *buf)
                        break;
        }
   /* also, if not found, set default as "application/octet-stream";  */
-  config->found_mime_type = *(table+1);
+  config->httpd_found.found_mime_type = *(table+1);
 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
   if (suffix) {
     Htaccess * cur;
 
     for (cur = config->mime_a; cur; cur = cur->next) {
        if(strcmp(cur->before_colon, suffix) == 0) {
-               config->found_mime_type = cur->after_colon;
+               config->httpd_found.found_mime_type = cur->after_colon;
                break;
        }
     }
@@ -1357,16 +1359,18 @@ static int sendFile(const char *url, char *buf)
 #ifdef DEBUG
     if (config->debugHttpd)
        fprintf(stderr, "Sending file '%s' Content-type: %s\n",
-                                       url, config->found_mime_type);
+                                       url, config->httpd_found.found_mime_type);
 #endif
 
   f = open(url, O_RDONLY);
   if (f >= 0) {
        int count;
+       char *buf = config->buf;
 
        sendHeaders(HTTP_OK);
        while ((count = bb_full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
-               bb_full_write(a_c_w, buf, count);
+               if (bb_full_write(a_c_w, buf, count) != count)
+                       break;
        }
        close(f);
   } else {
@@ -1404,7 +1408,7 @@ static int checkPermIP(void)
            return cur->allow_deny == 'A';   /* Allow/Deny */
     }
 
-    /* if uncofigured, return 1 - access from all */
+    /* if unconfigured, return 1 - access from all */
     return !config->flg_deny_all;
 }
 
@@ -1449,20 +1453,21 @@ static int checkPerm(const char *path, const char *request)
 
            if(strncmp(p0, path, l) == 0 &&
                            (l == 1 || path[l] == '/' || path[l] == 0)) {
+               char *u;
                /* path match found.  Check request */
-
                /* for check next /path:user:password */
                prev = p0;
+               u = strchr(request, ':');
+               if(u == NULL) {
+                       /* bad request, ':' required */
+                       break;
+                       }
+
 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
                {
                        char *cipher;
                        char *pp;
-                       char *u = strchr(request, ':');
 
-                       if(u == NULL) {
-                               /* bad request, ':' required */
-                               continue;
-                       }
                        if(strncmp(p, request, u-request) != 0) {
                                /* user uncompared */
                                continue;
@@ -1473,14 +1478,21 @@ static int checkPerm(const char *path, const char *request)
                                pp++;
                                cipher = pw_encrypt(u+1, pp);
                                if (strcmp(cipher, pp) == 0)
-                                       return 1;   /* Ok */
+                                       goto set_remoteuser_var;   /* Ok */
                                /* unauthorized */
                                continue;
                        }
                }
 #endif
-               if (strcmp(p, request) == 0)
+               if (strcmp(p, request) == 0) {
+#ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
+set_remoteuser_var:
+#endif
+                   config->remoteuser = strdup(request);
+                   if(config->remoteuser)
+                       config->remoteuser[(u - request)] = 0;
                    return 1;   /* Ok */
+               }
                /* unauthorized */
            }
        }
@@ -1491,6 +1503,20 @@ static int checkPerm(const char *path, const char *request)
 
 #endif  /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
 
+/****************************************************************************
+ *
+ > $Function: handleIncoming()
+ *
+ * $Description: Handle an incoming http request.
+ *
+ ****************************************************************************/
+
+static void
+handle_sigalrm( int sig )
+{
+    sendHeaders(HTTP_REQUEST_TIMEOUT);
+    config->alarm_signaled = sig;
+}
 
 /****************************************************************************
  *
@@ -1505,25 +1531,36 @@ static void handleIncoming(void)
   char *url;
   char *purl;
   int  blank = -1;
-  char *urlArgs;
+  char *test;
+  struct stat sb;
+  int ip_allowed;
 #ifdef CONFIG_FEATURE_HTTPD_CGI
   const char *prequest = request_GET;
-  char *body = 0;
   long length=0;
   char *cookie = 0;
+  char *content_type = 0;
 #endif
-  char *test;
-  struct stat sb;
-  int ip_allowed;
+#ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
+  fd_set s_fd;
+  struct timeval tv;
+  int retval;
+#endif
+  struct sigaction sa;
 
 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
   int credentials = -1;  /* if not requred this is Ok */
 #endif
 
+  sa.sa_handler = handle_sigalrm;
+  sigemptyset(&sa.sa_mask);
+  sa.sa_flags = 0; /* no SA_RESTART */
+  sigaction(SIGALRM, &sa, NULL);
+
   do {
     int  count;
 
-    if (getLine(buf) <= 0)
+    (void) alarm( TIMEOUT );
+    if (getLine() <= 0)
        break;  /* closed */
 
     purl = strpbrk(buf, " \t");
@@ -1562,9 +1599,11 @@ BAD_REQUEST:
     }
     strcpy(url, buf);
     /* extract url args if present */
-    urlArgs = strchr(url, '?');
-    if (urlArgs)
-      *urlArgs++ = 0;
+    test = strchr(url, '?');
+    if (test) {
+      *test++ = 0;
+      config->query = test;
+    }
 
     /* algorithm stolen from libbb bb_simplify_path(),
        but don`t strdup and reducing trailing slash and protect out root */
@@ -1594,17 +1633,16 @@ BAD_REQUEST:
     *++purl = 0;        /* so keep last character */
     test = purl;        /* end ptr */
 
+    /* If URL is directory, adding '/' */
     /* If URL is directory, adding '/' */
     if(test[-1] != '/') {
            if ( is_directory(url + 1, 1, &sb) ) {
-                   *test++ = '/';
-                   *test = 0;
-                   purl = test;    /* end ptr */
+                   config->httpd_found.found_moved_temporarily = url;
            }
     }
 #ifdef DEBUG
     if (config->debugHttpd)
-       fprintf(stderr, "url='%s', args=%s\n", url, urlArgs);
+       fprintf(stderr, "url='%s', args=%s\n", url, config->query);
 #endif
 
     test = url;
@@ -1621,7 +1659,7 @@ BAD_REQUEST:
     }
 
     // read until blank line for HTTP version specified, else parse immediate
-    while (blank >= 0 && (count = getLine(buf)) > 0) {
+    while (blank >= 0 && alarm(TIMEOUT) >= 0 && (count = getLine()) > 0) {
 
 #ifdef DEBUG
       if (config->debugHttpd) fprintf(stderr, "Header: '%s'\n", buf);
@@ -1636,6 +1674,14 @@ BAD_REQUEST:
                for(test = buf + 7; isspace(*test); test++)
                        ;
                cookie = strdup(test);
+      } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
+               for(test = buf + 13; isspace(*test); test++)
+                       ;
+               content_type = strdup(test);
+      } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
+               for(test = buf + 8; isspace(*test); test++)
+                       ;
+               config->referer = strdup(test);
       }
 #endif
 
@@ -1658,6 +1704,9 @@ BAD_REQUEST:
 
     }   /* while extra header reading */
 
+    (void) alarm( 0 );
+    if(config->alarm_signaled)
+       break;
 
     if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
                /* protect listing [/path]/httpd_conf or IP deny */
@@ -1675,27 +1724,27 @@ FORBIDDEN:      /* protect listing /cgi-bin */
     }
 #endif
 
+    if(config->httpd_found.found_moved_temporarily) {
+       sendHeaders(HTTP_MOVED_TEMPORARILY);
+#ifdef DEBUG
+       /* clear unforked memory flag */
+       if(config->debugHttpd)
+               config->httpd_found.found_moved_temporarily = NULL;
+#endif
+       break;
+    }
+
     test = url + 1;      /* skip first '/' */
 
 #ifdef CONFIG_FEATURE_HTTPD_CGI
     /* if strange Content-Length */
-    if (length < 0 || length > MAX_POST_SIZE)
+    if (length < 0)
        break;
 
-    if (length > 0) {
-      body = malloc(length + 1);
-      if (body) {
-       length = bb_full_read(a_c_r, body, length);
-       if(length < 0)          // closed
-               length = 0;
-       body[length] = 0;       // always null terminate for safety
-      }
-    }
-
     if (strncmp(test, "cgi-bin", 7) == 0) {
                if(test[7] == '/' && test[8] == 0)
                        goto FORBIDDEN;     // protect listing cgi-bin/
-               sendCgi(url, prequest, urlArgs, body, length, cookie);
+               sendCgi(url, prequest, length, cookie, content_type);
     } else {
        if (prequest != request_GET)
                sendHeaders(HTTP_NOT_IMPLEMENTED);
@@ -1707,7 +1756,7 @@ FORBIDDEN:      /* protect listing /cgi-bin */
                        config->ContentLength = sb.st_size;
                        config->last_mod = sb.st_mtime;
                }
-               sendFile(test, buf);
+               sendFile(test);
 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
                /* unset if non inetd looped */
                config->ContentLength = -1;
@@ -1727,10 +1776,25 @@ FORBIDDEN:      /* protect listing /cgi-bin */
   if (config->debugHttpd) fprintf(stderr, "closing socket\n");
 # endif
 # ifdef CONFIG_FEATURE_HTTPD_CGI
-  free(body);
   free(cookie);
+  free(content_type);
+  free(config->referer);
+#ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
+  free(config->remoteuser);
+#endif
 # endif
   shutdown(a_c_w, SHUT_WR);
+
+  /* Properly wait for remote to closed */
+  FD_ZERO (&s_fd) ;
+  FD_SET (a_c_w, &s_fd) ;
+
+  do {
+    tv.tv_sec = 2 ;
+    tv.tv_usec = 0 ;
+    retval = select (a_c_w + 1, &s_fd, NULL, NULL, &tv);
+  } while (retval > 0 && (read (a_c_w, buf, sizeof (config->buf)) > 0));
+
   shutdown(a_c_r, SHUT_RD);
   close(config->accepted_socket);
 #endif  /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
@@ -1763,7 +1827,7 @@ static int miniHttpd(int server)
   while (1) {
     readfd = portfd;
 
-    /* Now wait INDEFINATELY on the set of sockets! */
+    /* Now wait INDEFINITELY on the set of sockets! */
     if (select(server + 1, &readfd, 0, 0, 0) > 0) {
       if (FD_ISSET(server, &readfd)) {
        int on;
@@ -1988,7 +2052,7 @@ int httpd_main(int argc, char *argv[])
 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
   server = openServer();
 # ifdef CONFIG_FEATURE_HTTPD_SETUID
-  /* drop privilegies */
+  /* drop privileges */
   if(uid > 0)
        setuid(uid);
 # endif
@@ -1997,13 +2061,12 @@ int httpd_main(int argc, char *argv[])
 #ifdef CONFIG_FEATURE_HTTPD_CGI
    {
        char *p = getenv("PATH");
-
-       if(p)
-               p = bb_xstrdup(p);
-       clearenv();
        if(p) {
-               setenv("PATH", p, 0);
+               p = bb_xstrdup(p);
        }
+       clearenv();
+       if(p)
+               setenv("PATH", p, 1);
 # ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
        addEnvPort("SERVER");
 # endif