576df0
# ./pullrev.sh 1828172 1862968 1863191 1867878 1867882 1867968 1867970 1867971
576df0
http://svn.apache.org/viewvc?view=revision&revision=1828172
576df0
http://svn.apache.org/viewvc?view=revision&revision=1862968
576df0
http://svn.apache.org/viewvc?view=revision&revision=1863191
576df0
http://svn.apache.org/viewvc?view=revision&revision=1867878
576df0
http://svn.apache.org/viewvc?view=revision&revision=1867882
576df0
http://svn.apache.org/viewvc?view=revision&revision=1867968
576df0
http://svn.apache.org/viewvc?view=revision&revision=1867970
576df0
http://svn.apache.org/viewvc?view=revision&revision=1867971
576df0
576df0
--- httpd-2.4.41/modules/generators/mod_cgi.c
576df0
+++ httpd-2.4.41/modules/generators/mod_cgi.c
576df0
@@ -92,6 +92,10 @@
576df0
     apr_size_t  bufbytes;
576df0
 } cgi_server_conf;
576df0
 
576df0
+typedef struct {
576df0
+    apr_interval_time_t timeout;
576df0
+} cgi_dirconf;
576df0
+
576df0
 static void *create_cgi_config(apr_pool_t *p, server_rec *s)
576df0
 {
576df0
     cgi_server_conf *c =
576df0
@@ -112,6 +116,12 @@
576df0
     return overrides->logname ? overrides : base;
576df0
 }
576df0
 
576df0
+static void *create_cgi_dirconf(apr_pool_t *p, char *dummy)
576df0
+{
576df0
+    cgi_dirconf *c = (cgi_dirconf *) apr_pcalloc(p, sizeof(cgi_dirconf));
576df0
+    return c;
576df0
+}
576df0
+
576df0
 static const char *set_scriptlog(cmd_parms *cmd, void *dummy, const char *arg)
576df0
 {
576df0
     server_rec *s = cmd->server;
576df0
@@ -150,6 +160,17 @@
576df0
     return NULL;
576df0
 }
576df0
 
576df0
+static const char *set_script_timeout(cmd_parms *cmd, void *dummy, const char *arg)
576df0
+{
576df0
+    cgi_dirconf *dc = dummy;
576df0
+
576df0
+    if (ap_timeout_parameter_parse(arg, &dc->timeout, "s") != APR_SUCCESS) {
576df0
+        return "CGIScriptTimeout has wrong format";
576df0
+    }
576df0
+
576df0
+    return NULL;
576df0
+}
576df0
+
576df0
 static const command_rec cgi_cmds[] =
576df0
 {
576df0
 AP_INIT_TAKE1("ScriptLog", set_scriptlog, NULL, RSRC_CONF,
576df0
@@ -158,6 +179,9 @@
576df0
      "the maximum length (in bytes) of the script debug log"),
576df0
 AP_INIT_TAKE1("ScriptLogBuffer", set_scriptlog_buffer, NULL, RSRC_CONF,
576df0
      "the maximum size (in bytes) to record of a POST request"),
576df0
+AP_INIT_TAKE1("CGIScriptTimeout", set_script_timeout, NULL, RSRC_CONF | ACCESS_CONF,
576df0
+     "The amount of time to wait between successful reads from "
576df0
+     "the CGI script, in seconds."),
576df0
     {NULL}
576df0
 };
576df0
 
576df0
@@ -471,23 +495,26 @@
576df0
                           apr_filepath_name_get(r->filename));
576df0
         }
576df0
         else {
576df0
+            cgi_dirconf *dc = ap_get_module_config(r->per_dir_config, &cgi_module);
576df0
+            apr_interval_time_t timeout = dc->timeout > 0 ? dc->timeout : r->server->timeout;
576df0
+
576df0
             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
576df0
 
576df0
             *script_in = procnew->out;
576df0
             if (!*script_in)
576df0
                 return APR_EBADF;
576df0
-            apr_file_pipe_timeout_set(*script_in, r->server->timeout);
576df0
+            apr_file_pipe_timeout_set(*script_in, timeout);
576df0
 
576df0
             if (e_info->prog_type == RUN_AS_CGI) {
576df0
                 *script_out = procnew->in;
576df0
                 if (!*script_out)
576df0
                     return APR_EBADF;
576df0
-                apr_file_pipe_timeout_set(*script_out, r->server->timeout);
576df0
+                apr_file_pipe_timeout_set(*script_out, timeout);
576df0
 
576df0
                 *script_err = procnew->err;
576df0
                 if (!*script_err)
576df0
                     return APR_EBADF;
576df0
-                apr_file_pipe_timeout_set(*script_err, r->server->timeout);
576df0
+                apr_file_pipe_timeout_set(*script_err, timeout);
576df0
             }
576df0
         }
576df0
     }
576df0
@@ -541,212 +568,10 @@
576df0
     return APR_SUCCESS;
576df0
 }
576df0
 
576df0
-static void discard_script_output(apr_bucket_brigade *bb)
576df0
-{
576df0
-    apr_bucket *e;
576df0
-    const char *buf;
576df0
-    apr_size_t len;
576df0
-    apr_status_t rv;
576df0
-
576df0
-    for (e = APR_BRIGADE_FIRST(bb);
576df0
-         e != APR_BRIGADE_SENTINEL(bb);
576df0
-         e = APR_BUCKET_NEXT(e))
576df0
-    {
576df0
-        if (APR_BUCKET_IS_EOS(e)) {
576df0
-            break;
576df0
-        }
576df0
-        rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
576df0
-        if (rv != APR_SUCCESS) {
576df0
-            break;
576df0
-        }
576df0
-    }
576df0
-}
576df0
-
576df0
 #if APR_FILES_AS_SOCKETS
576df0
-
576df0
-/* A CGI bucket type is needed to catch any output to stderr from the
576df0
- * script; see PR 22030. */
576df0
-static const apr_bucket_type_t bucket_type_cgi;
576df0
-
576df0
-struct cgi_bucket_data {
576df0
-    apr_pollset_t *pollset;
576df0
-    request_rec *r;
576df0
-};
576df0
-
576df0
-/* Create a CGI bucket using pipes from script stdout 'out'
576df0
- * and stderr 'err', for request 'r'. */
576df0
-static apr_bucket *cgi_bucket_create(request_rec *r,
576df0
-                                     apr_file_t *out, apr_file_t *err,
576df0
-                                     apr_bucket_alloc_t *list)
576df0
-{
576df0
-    apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
576df0
-    apr_status_t rv;
576df0
-    apr_pollfd_t fd;
576df0
-    struct cgi_bucket_data *data = apr_palloc(r->pool, sizeof *data);
576df0
-
576df0
-    APR_BUCKET_INIT(b);
576df0
-    b->free = apr_bucket_free;
576df0
-    b->list = list;
576df0
-    b->type = &bucket_type_cgi;
576df0
-    b->length = (apr_size_t)(-1);
576df0
-    b->start = -1;
576df0
-
576df0
-    /* Create the pollset */
576df0
-    rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
576df0
-    if (rv != APR_SUCCESS) {
576df0
-        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01217)
576df0
-                     "apr_pollset_create(); check system or user limits");
576df0
-        return NULL;
576df0
-    }
576df0
-
576df0
-    fd.desc_type = APR_POLL_FILE;
576df0
-    fd.reqevents = APR_POLLIN;
576df0
-    fd.p = r->pool;
576df0
-    fd.desc.f = out; /* script's stdout */
576df0
-    fd.client_data = (void *)1;
576df0
-    rv = apr_pollset_add(data->pollset, &fd;;
576df0
-    if (rv != APR_SUCCESS) {
576df0
-        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01218)
576df0
-                     "apr_pollset_add(); check system or user limits");
576df0
-        return NULL;
576df0
-    }
576df0
-
576df0
-    fd.desc.f = err; /* script's stderr */
576df0
-    fd.client_data = (void *)2;
576df0
-    rv = apr_pollset_add(data->pollset, &fd;;
576df0
-    if (rv != APR_SUCCESS) {
576df0
-        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01219)
576df0
-                     "apr_pollset_add(); check system or user limits");
576df0
-        return NULL;
576df0
-    }
576df0
-
576df0
-    data->r = r;
576df0
-    b->data = data;
576df0
-    return b;
576df0
-}
576df0
-
576df0
-/* Create a duplicate CGI bucket using given bucket data */
576df0
-static apr_bucket *cgi_bucket_dup(struct cgi_bucket_data *data,
576df0
-                                  apr_bucket_alloc_t *list)
576df0
-{
576df0
-    apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
576df0
-    APR_BUCKET_INIT(b);
576df0
-    b->free = apr_bucket_free;
576df0
-    b->list = list;
576df0
-    b->type = &bucket_type_cgi;
576df0
-    b->length = (apr_size_t)(-1);
576df0
-    b->start = -1;
576df0
-    b->data = data;
576df0
-    return b;
576df0
-}
576df0
-
576df0
-/* Handle stdout from CGI child.  Duplicate of logic from the _read
576df0
- * method of the real APR pipe bucket implementation. */
576df0
-static apr_status_t cgi_read_stdout(apr_bucket *a, apr_file_t *out,
576df0
-                                    const char **str, apr_size_t *len)
576df0
-{
576df0
-    char *buf;
576df0
-    apr_status_t rv;
576df0
-
576df0
-    *str = NULL;
576df0
-    *len = APR_BUCKET_BUFF_SIZE;
576df0
-    buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
576df0
-
576df0
-    rv = apr_file_read(out, buf, len);
576df0
-
576df0
-    if (rv != APR_SUCCESS && rv != APR_EOF) {
576df0
-        apr_bucket_free(buf);
576df0
-        return rv;
576df0
-    }
576df0
-
576df0
-    if (*len > 0) {
576df0
-        struct cgi_bucket_data *data = a->data;
576df0
-        apr_bucket_heap *h;
576df0
-
576df0
-        /* Change the current bucket to refer to what we read */
576df0
-        a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
576df0
-        h = a->data;
576df0
-        h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
576df0
-        *str = buf;
576df0
-        APR_BUCKET_INSERT_AFTER(a, cgi_bucket_dup(data, a->list));
576df0
-    }
576df0
-    else {
576df0
-        apr_bucket_free(buf);
576df0
-        a = apr_bucket_immortal_make(a, "", 0);
576df0
-        *str = a->data;
576df0
-    }
576df0
-    return rv;
576df0
-}
576df0
-
576df0
-/* Read method of CGI bucket: polls on stderr and stdout of the child,
576df0
- * sending any stderr output immediately away to the error log. */
576df0
-static apr_status_t cgi_bucket_read(apr_bucket *b, const char **str,
576df0
-                                    apr_size_t *len, apr_read_type_e block)
576df0
-{
576df0
-    struct cgi_bucket_data *data = b->data;
576df0
-    apr_interval_time_t timeout;
576df0
-    apr_status_t rv;
576df0
-    int gotdata = 0;
576df0
-
576df0
-    timeout = block == APR_NONBLOCK_READ ? 0 : data->r->server->timeout;
576df0
-
576df0
-    do {
576df0
-        const apr_pollfd_t *results;
576df0
-        apr_int32_t num;
576df0
-
576df0
-        rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
576df0
-        if (APR_STATUS_IS_TIMEUP(rv)) {
576df0
-            if (timeout) {
576df0
-                ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, data->r, APLOGNO(01220)
576df0
-                              "Timeout waiting for output from CGI script %s",
576df0
-                              data->r->filename);
576df0
-                return rv;
576df0
-            }
576df0
-            else {
576df0
-                return APR_EAGAIN;
576df0
-            }
576df0
-        }
576df0
-        else if (APR_STATUS_IS_EINTR(rv)) {
576df0
-            continue;
576df0
-        }
576df0
-        else if (rv != APR_SUCCESS) {
576df0
-            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r, APLOGNO(01221)
576df0
-                          "poll failed waiting for CGI child");
576df0
-            return rv;
576df0
-        }
576df0
-
576df0
-        for (; num; num--, results++) {
576df0
-            if (results[0].client_data == (void *)1) {
576df0
-                /* stdout */
576df0
-                rv = cgi_read_stdout(b, results[0].desc.f, str, len);
576df0
-                if (APR_STATUS_IS_EOF(rv)) {
576df0
-                    rv = APR_SUCCESS;
576df0
-                }
576df0
-                gotdata = 1;
576df0
-            } else {
576df0
-                /* stderr */
576df0
-                apr_status_t rv2 = log_script_err(data->r, results[0].desc.f);
576df0
-                if (APR_STATUS_IS_EOF(rv2)) {
576df0
-                    apr_pollset_remove(data->pollset, &results[0]);
576df0
-                }
576df0
-            }
576df0
-        }
576df0
-
576df0
-    } while (!gotdata);
576df0
-
576df0
-    return rv;
576df0
-}
576df0
-
576df0
-static const apr_bucket_type_t bucket_type_cgi = {
576df0
-    "CGI", 5, APR_BUCKET_DATA,
576df0
-    apr_bucket_destroy_noop,
576df0
-    cgi_bucket_read,
576df0
-    apr_bucket_setaside_notimpl,
576df0
-    apr_bucket_split_notimpl,
576df0
-    apr_bucket_copy_notimpl
576df0
-};
576df0
-
576df0
+#define WANT_CGI_BUCKET
576df0
 #endif
576df0
+#include "cgi_common.h"
576df0
 
576df0
 static int cgi_handler(request_rec *r)
576df0
 {
576df0
@@ -766,6 +591,8 @@
576df0
     apr_status_t rv;
576df0
     cgi_exec_info_t e_info;
576df0
     conn_rec *c;
576df0
+    cgi_dirconf *dc = ap_get_module_config(r->per_dir_config, &cgi_module);
576df0
+    apr_interval_time_t timeout = dc->timeout > 0 ? dc->timeout : r->server->timeout;
576df0
 
576df0
     if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
576df0
         return DECLINED;
576df0
@@ -925,10 +752,7 @@
576df0
     AP_DEBUG_ASSERT(script_in != NULL);
576df0
 
576df0
 #if APR_FILES_AS_SOCKETS
576df0
-    apr_file_pipe_timeout_set(script_in, 0);
576df0
-    apr_file_pipe_timeout_set(script_err, 0);
576df0
-
576df0
-    b = cgi_bucket_create(r, script_in, script_err, c->bucket_alloc);
576df0
+    b = cgi_bucket_create(r, dc->timeout, script_in, script_err, c->bucket_alloc);
576df0
     if (b == NULL)
576df0
         return HTTP_INTERNAL_SERVER_ERROR;
576df0
 #else
576df0
@@ -938,111 +762,7 @@
576df0
     b = apr_bucket_eos_create(c->bucket_alloc);
576df0
     APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
 
576df0
-    /* Handle script return... */
576df0
-    if (!nph) {
576df0
-        const char *location;
576df0
-        char sbuf[MAX_STRING_LEN];
576df0
-        int ret;
576df0
-
576df0
-        if ((ret = ap_scan_script_header_err_brigade_ex(r, bb, sbuf,
576df0
-                                                        APLOG_MODULE_INDEX)))
576df0
-        {
576df0
-            ret = log_script(r, conf, ret, dbuf, sbuf, bb, script_err);
576df0
-
576df0
-            /*
576df0
-             * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
576df0
-             * does not set an explicit status and ap_meets_conditions, which
576df0
-             * is called by ap_scan_script_header_err_brigade, detects that
576df0
-             * the conditions of the requests are met and the response is
576df0
-             * not modified.
576df0
-             * In this case set r->status and return OK in order to prevent
576df0
-             * running through the error processing stack as this would
576df0
-             * break with mod_cache, if the conditions had been set by
576df0
-             * mod_cache itself to validate a stale entity.
576df0
-             * BTW: We circumvent the error processing stack anyway if the
576df0
-             * CGI script set an explicit status code (whatever it is) and
576df0
-             * the only possible values for ret here are:
576df0
-             *
576df0
-             * HTTP_NOT_MODIFIED          (set by ap_meets_conditions)
576df0
-             * HTTP_PRECONDITION_FAILED   (set by ap_meets_conditions)
576df0
-             * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
576df0
-             * processing of the response of the CGI script, e.g broken headers
576df0
-             * or a crashed CGI process).
576df0
-             */
576df0
-            if (ret == HTTP_NOT_MODIFIED) {
576df0
-                r->status = ret;
576df0
-                return OK;
576df0
-            }
576df0
-
576df0
-            return ret;
576df0
-        }
576df0
-
576df0
-        location = apr_table_get(r->headers_out, "Location");
576df0
-
576df0
-        if (location && r->status == 200) {
576df0
-            /* For a redirect whether internal or not, discard any
576df0
-             * remaining stdout from the script, and log any remaining
576df0
-             * stderr output, as normal. */
576df0
-            discard_script_output(bb);
576df0
-            apr_brigade_destroy(bb);
576df0
-            apr_file_pipe_timeout_set(script_err, r->server->timeout);
576df0
-            log_script_err(r, script_err);
576df0
-        }
576df0
-
576df0
-        if (location && location[0] == '/' && r->status == 200) {
576df0
-            /* This redirect needs to be a GET no matter what the original
576df0
-             * method was.
576df0
-             */
576df0
-            r->method = "GET";
576df0
-            r->method_number = M_GET;
576df0
-
576df0
-            /* We already read the message body (if any), so don't allow
576df0
-             * the redirected request to think it has one.  We can ignore
576df0
-             * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
576df0
-             */
576df0
-            apr_table_unset(r->headers_in, "Content-Length");
576df0
-
576df0
-            ap_internal_redirect_handler(location, r);
576df0
-            return OK;
576df0
-        }
576df0
-        else if (location && r->status == 200) {
576df0
-            /* XXX: Note that if a script wants to produce its own Redirect
576df0
-             * body, it now has to explicitly *say* "Status: 302"
576df0
-             */
576df0
-            return HTTP_MOVED_TEMPORARILY;
576df0
-        }
576df0
-
576df0
-        rv = ap_pass_brigade(r->output_filters, bb);
576df0
-    }
576df0
-    else /* nph */ {
576df0
-        struct ap_filter_t *cur;
576df0
-
576df0
-        /* get rid of all filters up through protocol...  since we
576df0
-         * haven't parsed off the headers, there is no way they can
576df0
-         * work
576df0
-         */
576df0
-
576df0
-        cur = r->proto_output_filters;
576df0
-        while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
576df0
-            cur = cur->next;
576df0
-        }
576df0
-        r->output_filters = r->proto_output_filters = cur;
576df0
-
576df0
-        rv = ap_pass_brigade(r->output_filters, bb);
576df0
-    }
576df0
-
576df0
-    /* don't soak up script output if errors occurred writing it
576df0
-     * out...  otherwise, we prolong the life of the script when the
576df0
-     * connection drops or we stopped sending output for some other
576df0
-     * reason */
576df0
-    if (rv == APR_SUCCESS && !r->connection->aborted) {
576df0
-        apr_file_pipe_timeout_set(script_err, r->server->timeout);
576df0
-        log_script_err(r, script_err);
576df0
-    }
576df0
-
576df0
-    apr_file_close(script_err);
576df0
-
576df0
-    return OK;                      /* NOT r->status, even if it has changed. */
576df0
+    return cgi_handle_response(r, nph, bb, timeout, conf, dbuf, script_err);
576df0
 }
576df0
 
576df0
 /*============================================================================
576df0
@@ -1277,7 +997,7 @@
576df0
 AP_DECLARE_MODULE(cgi) =
576df0
 {
576df0
     STANDARD20_MODULE_STUFF,
576df0
-    NULL,                        /* dir config creater */
576df0
+    create_cgi_dirconf,          /* dir config creater */
576df0
     NULL,                        /* dir merger --- default is to override */
576df0
     create_cgi_config,           /* server config */
576df0
     merge_cgi_config,            /* merge server config */
576df0
--- httpd-2.4.41/modules/generators/config5.m4
576df0
+++ httpd-2.4.41/modules/generators/config5.m4
576df0
@@ -78,4 +78,15 @@
576df0
 
576df0
 APR_ADDTO(INCLUDES, [-I\$(top_srcdir)/$modpath_current])
576df0
 
576df0
+AC_ARG_ENABLE(cgid-fdpassing,
576df0
+  [APACHE_HELP_STRING(--enable-cgid-fdpassing,Enable experimental mod_cgid support for fd passing)],
576df0
+  [if test "$enableval" = "yes"; then
576df0
+     AC_CHECK_DECL(CMSG_DATA,
576df0
+       [AC_DEFINE([HAVE_CGID_FDPASSING], 1, [Enable FD passing support in mod_cgid])],
576df0
+       [AC_MSG_ERROR([cannot support mod_cgid fd-passing on this system])], [
576df0
+#include <sys/types.h>
576df0
+#include <sys/socket.h>])
576df0
+  fi
576df0
+])
576df0
+
576df0
 APACHE_MODPATH_FINISH
576df0
--- httpd-2.4.41/modules/generators/mod_cgid.c
576df0
+++ httpd-2.4.41/modules/generators/mod_cgid.c
576df0
@@ -342,15 +342,19 @@
576df0
     return close(fd);
576df0
 }
576df0
 
576df0
-/* deal with incomplete reads and signals
576df0
- * assume you really have to read buf_size bytes
576df0
- */
576df0
-static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
576df0
+/* Read from the socket dealing with incomplete messages and signals.
576df0
+ * Returns 0 on success or errno on failure.  Stderr fd passed as
576df0
+ * auxiliary data from other end is written to *errfd, or else stderr
576df0
+ * fileno if not present. */
576df0
+static apr_status_t sock_readhdr(int fd, int *errfd, void *vbuf, size_t buf_size)
576df0
 {
576df0
-    char *buf = vbuf;
576df0
     int rc;
576df0
+#ifndef HAVE_CGID_FDPASSING
576df0
+    char *buf = vbuf;
576df0
     size_t bytes_read = 0;
576df0
 
576df0
+    if (errfd) *errfd = 0;
576df0
+    
576df0
     do {
576df0
         do {
576df0
             rc = read(fd, buf + bytes_read, buf_size - bytes_read);
576df0
@@ -365,9 +369,60 @@
576df0
         }
576df0
     } while (bytes_read < buf_size);
576df0
 
576df0
+   
576df0
+#else /* with FD passing */
576df0
+    struct msghdr msg = {0};
576df0
+    struct iovec vec = {vbuf, buf_size};
576df0
+    struct cmsghdr *cmsg;
576df0
+    union {  /* union to ensure alignment */
576df0
+        struct cmsghdr cm;
576df0
+        char buf[CMSG_SPACE(sizeof(int))];
576df0
+    } u;
576df0
+    
576df0
+    msg.msg_iov = &vec;
576df0
+    msg.msg_iovlen = 1;
576df0
+
576df0
+    if (errfd) {
576df0
+        msg.msg_control = u.buf;
576df0
+        msg.msg_controllen = sizeof(u.buf);
576df0
+        *errfd = 0;
576df0
+    }
576df0
+    
576df0
+    /* use MSG_WAITALL to skip loop on truncated reads */
576df0
+    do {
576df0
+        rc = recvmsg(fd, &msg, MSG_WAITALL);
576df0
+    } while (rc < 0 && errno == EINTR);
576df0
+
576df0
+    if (rc == 0) {
576df0
+        return ECONNRESET;
576df0
+    }
576df0
+    else if (rc < 0) {
576df0
+        return errno;
576df0
+    }
576df0
+    else if (rc != buf_size) {
576df0
+        /* MSG_WAITALL should ensure the recvmsg blocks until the
576df0
+         * entire length is read, but let's be paranoid. */
576df0
+        return APR_INCOMPLETE;
576df0
+    }
576df0
+
576df0
+    if (errfd
576df0
+        && (cmsg = CMSG_FIRSTHDR(&msg)) != NULL
576df0
+        && cmsg->cmsg_len == CMSG_LEN(sizeof(*errfd))
576df0
+        && cmsg->cmsg_level == SOL_SOCKET
576df0
+        && cmsg->cmsg_type == SCM_RIGHTS) {
576df0
+        *errfd = *((int *) CMSG_DATA(cmsg));
576df0
+    }
576df0
+#endif
576df0
+    
576df0
     return APR_SUCCESS;
576df0
 }
576df0
 
576df0
+/* As sock_readhdr but without auxiliary fd passing. */
576df0
+static apr_status_t sock_read(int fd, void *vbuf, size_t buf_size)
576df0
+{
576df0
+    return sock_readhdr(fd, NULL, vbuf, buf_size);
576df0
+}
576df0
+
576df0
 /* deal with signals
576df0
  */
576df0
 static apr_status_t sock_write(int fd, const void *buf, size_t buf_size)
576df0
@@ -384,7 +439,7 @@
576df0
     return APR_SUCCESS;
576df0
 }
576df0
 
576df0
-static apr_status_t sock_writev(int fd, request_rec *r, int count, ...)
576df0
+static apr_status_t sock_writev(int fd, int auxfd, request_rec *r, int count, ...)
576df0
 {
576df0
     va_list ap;
576df0
     int rc;
576df0
@@ -399,9 +454,39 @@
576df0
     }
576df0
     va_end(ap);
576df0
 
576df0
+#ifndef HAVE_CGID_FDPASSING
576df0
     do {
576df0
         rc = writev(fd, vec, count);
576df0
     } while (rc < 0 && errno == EINTR);
576df0
+#else
576df0
+    {
576df0
+        struct msghdr msg = { 0 };
576df0
+        struct cmsghdr *cmsg;
576df0
+        union { /* union for alignment */
576df0
+            char buf[CMSG_SPACE(sizeof(int))];
576df0
+            struct cmsghdr align;
576df0
+        } u;
576df0
+
576df0
+        msg.msg_iov = vec;
576df0
+        msg.msg_iovlen = count;
576df0
+
576df0
+        if (auxfd) {
576df0
+            msg.msg_control = u.buf;
576df0
+            msg.msg_controllen = sizeof(u.buf);
576df0
+
576df0
+            cmsg = CMSG_FIRSTHDR(&msg;;
576df0
+            cmsg->cmsg_level = SOL_SOCKET;
576df0
+            cmsg->cmsg_type = SCM_RIGHTS;
576df0
+            cmsg->cmsg_len = CMSG_LEN(sizeof(int));
576df0
+            *((int *) CMSG_DATA(cmsg)) = auxfd;
576df0
+        }
576df0
+
576df0
+        do {
576df0
+            rc = sendmsg(fd, &msg, 0);
576df0
+        } while (rc < 0 && errno == EINTR);
576df0
+    }
576df0
+#endif
576df0
+    
576df0
     if (rc < 0) {
576df0
         return errno;
576df0
     }
576df0
@@ -410,7 +495,7 @@
576df0
 }
576df0
 
576df0
 static apr_status_t get_req(int fd, request_rec *r, char **argv0, char ***env,
576df0
-                            cgid_req_t *req)
576df0
+                            int *errfd, cgid_req_t *req)
576df0
 {
576df0
     int i;
576df0
     char **environ;
576df0
@@ -421,7 +506,7 @@
576df0
     r->server = apr_pcalloc(r->pool, sizeof(server_rec));
576df0
 
576df0
     /* read the request header */
576df0
-    stat = sock_read(fd, req, sizeof(*req));
576df0
+    stat = sock_readhdr(fd, errfd, req, sizeof(*req));
576df0
     if (stat != APR_SUCCESS) {
576df0
         return stat;
576df0
     }
576df0
@@ -479,14 +564,15 @@
576df0
     return APR_SUCCESS;
576df0
 }
576df0
 
576df0
-static apr_status_t send_req(int fd, request_rec *r, char *argv0, char **env,
576df0
-                             int req_type)
576df0
+static apr_status_t send_req(int fd, apr_file_t *errpipe, request_rec *r,
576df0
+                             char *argv0, char **env, int req_type)
576df0
 {
576df0
     int i;
576df0
     cgid_req_t req = {0};
576df0
     apr_status_t stat;
576df0
     ap_unix_identity_t * ugid = ap_run_get_suexec_identity(r);
576df0
     core_dir_config *core_conf = ap_get_core_module_config(r->per_dir_config);
576df0
+    int errfd;
576df0
 
576df0
 
576df0
     if (ugid == NULL) {
576df0
@@ -507,16 +593,21 @@
576df0
     req.args_len = r->args ? strlen(r->args) : 0;
576df0
     req.loglevel = r->server->log.level;
576df0
 
576df0
+    if (errpipe)
576df0
+        apr_os_file_get(&errfd, errpipe);
576df0
+    else
576df0
+        errfd = 0;
576df0
+    
576df0
     /* Write the request header */
576df0
     if (req.args_len) {
576df0
-        stat = sock_writev(fd, r, 5,
576df0
+        stat = sock_writev(fd, errfd, r, 5,
576df0
                            &req, sizeof(req),
576df0
                            r->filename, req.filename_len,
576df0
                            argv0, req.argv0_len,
576df0
                            r->uri, req.uri_len,
576df0
                            r->args, req.args_len);
576df0
     } else {
576df0
-        stat = sock_writev(fd, r, 4,
576df0
+        stat = sock_writev(fd, errfd, r, 4,
576df0
                            &req, sizeof(req),
576df0
                            r->filename, req.filename_len,
576df0
                            argv0, req.argv0_len,
576df0
@@ -531,7 +622,7 @@
576df0
     for (i = 0; i < req.env_count; i++) {
576df0
         apr_size_t curlen = strlen(env[i]);
576df0
 
576df0
-        if ((stat = sock_writev(fd, r, 2, &curlen, sizeof(curlen),
576df0
+        if ((stat = sock_writev(fd, 0, r, 2, &curlen, sizeof(curlen),
576df0
                                 env[i], curlen)) != APR_SUCCESS) {
576df0
             return stat;
576df0
         }
576df0
@@ -582,20 +673,34 @@
576df0
     }
576df0
 }
576df0
 
576df0
+/* Callback executed in the forked child process if exec of the CGI
576df0
+ * script fails.  For the fd-passing case, output to stderr goes to
576df0
+ * the client (request handling thread) and is logged via
576df0
+ * ap_log_rerror there.  For the non-fd-passing case, the "fake"
576df0
+ * request_rec passed via userdata is used to log. */
576df0
 static void cgid_child_errfn(apr_pool_t *pool, apr_status_t err,
576df0
                              const char *description)
576df0
 {
576df0
-    request_rec *r;
576df0
     void *vr;
576df0
 
576df0
     apr_pool_userdata_get(&vr, ERRFN_USERDATA_KEY, pool);
576df0
-    r = vr;
576df0
-
576df0
-    /* sure we got r, but don't call ap_log_rerror() because we don't
576df0
-     * have r->headers_in and possibly other storage referenced by
576df0
-     * ap_log_rerror()
576df0
-     */
576df0
-    ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server, APLOGNO(01241) "%s", description);
576df0
+    if (vr) {
576df0
+        request_rec *r = vr;
576df0
+        
576df0
+        /* sure we got r, but don't call ap_log_rerror() because we don't
576df0
+         * have r->headers_in and possibly other storage referenced by
576df0
+         * ap_log_rerror()
576df0
+         */
576df0
+        ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server, APLOGNO(01241) "%s", description);
576df0
+    }
576df0
+    else {
576df0
+        const char *logstr;
576df0
+        
576df0
+        logstr = apr_psprintf(pool, APLOGNO(01241) "error spawning CGI child: %s (%pm)\n",
576df0
+                              description, &err;;
576df0
+        fputs(logstr, stderr);
576df0
+        fflush(stderr);
576df0
+    }
576df0
 }
576df0
 
576df0
 static int cgid_server(void *data)
576df0
@@ -669,7 +774,7 @@
576df0
     }
576df0
 
576df0
     while (!daemon_should_exit) {
576df0
-        int errfileno = STDERR_FILENO;
576df0
+        int errfileno;
576df0
         char *argv0 = NULL;
576df0
         char **env = NULL;
576df0
         const char * const *argv;
576df0
@@ -709,7 +814,7 @@
576df0
         r = apr_pcalloc(ptrans, sizeof(request_rec));
576df0
         procnew = apr_pcalloc(ptrans, sizeof(*procnew));
576df0
         r->pool = ptrans;
576df0
-        stat = get_req(sd2, r, &argv0, &env, &cgid_req);
576df0
+        stat = get_req(sd2, r, &argv0, &env, &errfileno, &cgid_req);
576df0
         if (stat != APR_SUCCESS) {
576df0
             ap_log_error(APLOG_MARK, APLOG_ERR, stat,
576df0
                          main_server, APLOGNO(01248)
576df0
@@ -741,6 +846,16 @@
576df0
             continue;
576df0
         }
576df0
 
576df0
+        if (errfileno == 0) {
576df0
+            errfileno = STDERR_FILENO;
576df0
+        }
576df0
+        else {
576df0
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, main_server,
576df0
+                          "using passed fd %d as stderr", errfileno);
576df0
+            /* Limit the received fd lifetime to pool lifetime */
576df0
+            apr_pool_cleanup_register(ptrans, (void *)((long)errfileno),
576df0
+                                      close_unix_socket, close_unix_socket);
576df0
+        }
576df0
         apr_os_file_put(&r->server->error_log, &errfileno, 0, r->pool);
576df0
         apr_os_file_put(&inout, &sd2, 0, r->pool);
576df0
 
576df0
@@ -800,7 +915,10 @@
576df0
             close(sd2);
576df0
         }
576df0
         else {
576df0
-            apr_pool_userdata_set(r, ERRFN_USERDATA_KEY, apr_pool_cleanup_null, ptrans);
576df0
+            if (errfileno == STDERR_FILENO) {
576df0
+                /* Used by cgid_child_errfn without fd-passing. */
576df0
+                apr_pool_userdata_set(r, ERRFN_USERDATA_KEY, apr_pool_cleanup_null, ptrans);
576df0
+            }
576df0
 
576df0
             argv = (const char * const *)create_argv(r->pool, NULL, NULL, NULL, argv0, r->args);
576df0
 
576df0
@@ -1099,6 +1217,33 @@
576df0
     return ret;
576df0
 }
576df0
 
576df0
+/* Soak up stderr from a script and redirect it to the error log.
576df0
+ * TODO: log_scripterror() and this could move to cgi_common.h. */
576df0
+static apr_status_t log_script_err(request_rec *r, apr_file_t *script_err)
576df0
+{
576df0
+    char argsbuffer[HUGE_STRING_LEN];
576df0
+    char *newline;
576df0
+    apr_status_t rv;
576df0
+    cgid_server_conf *conf = ap_get_module_config(r->server->module_config, &cgid_module);
576df0
+
576df0
+    while ((rv = apr_file_gets(argsbuffer, HUGE_STRING_LEN,
576df0
+                               script_err)) == APR_SUCCESS) {
576df0
+
576df0
+        newline = strchr(argsbuffer, '\n');
576df0
+        if (newline) {
576df0
+            char *prev = newline - 1;
576df0
+            if (prev >= argsbuffer && *prev == '\r') {
576df0
+                newline = prev;
576df0
+            }
576df0
+
576df0
+            *newline = '\0';
576df0
+        }
576df0
+        log_scripterror(r, conf, r->status, 0, argsbuffer);
576df0
+    }
576df0
+
576df0
+    return rv;
576df0
+}
576df0
+
576df0
 static int log_script(request_rec *r, cgid_server_conf * conf, int ret,
576df0
                       char *dbuf, const char *sbuf, apr_bucket_brigade *bb,
576df0
                       apr_file_t *script_err)
576df0
@@ -1204,6 +1349,13 @@
576df0
     return ret;
576df0
 }
576df0
 
576df0
+/* Pull in CGI bucket implementation. */
576df0
+#define cgi_server_conf cgid_server_conf
576df0
+#ifdef HAVE_CGID_FDPASSING
576df0
+#define WANT_CGI_BUCKET
576df0
+#endif
576df0
+#include "cgi_common.h"
576df0
+
576df0
 static int connect_to_daemon(int *sdptr, request_rec *r,
576df0
                              cgid_server_conf *conf)
576df0
 {
576df0
@@ -1270,27 +1422,6 @@
576df0
     return OK;
576df0
 }
576df0
 
576df0
-static void discard_script_output(apr_bucket_brigade *bb)
576df0
-{
576df0
-    apr_bucket *e;
576df0
-    const char *buf;
576df0
-    apr_size_t len;
576df0
-    apr_status_t rv;
576df0
-
576df0
-    for (e = APR_BRIGADE_FIRST(bb);
576df0
-         e != APR_BRIGADE_SENTINEL(bb);
576df0
-         e = APR_BUCKET_NEXT(e))
576df0
-    {
576df0
-        if (APR_BUCKET_IS_EOS(e)) {
576df0
-            break;
576df0
-        }
576df0
-        rv = apr_bucket_read(e, &buf, &len, APR_BLOCK_READ);
576df0
-        if (rv != APR_SUCCESS) {
576df0
-            break;
576df0
-        }
576df0
-    }
576df0
-}
576df0
-
576df0
 /****************************************************************
576df0
  *
576df0
  * Actual cgid handling...
576df0
@@ -1395,6 +1526,7 @@
576df0
 
576df0
 static int cgid_handler(request_rec *r)
576df0
 {
576df0
+    conn_rec *c = r->connection;
576df0
     int retval, nph, dbpos;
576df0
     char *argv0, *dbuf;
576df0
     apr_bucket_brigade *bb;
576df0
@@ -1404,10 +1536,11 @@
576df0
     int seen_eos, child_stopped_reading;
576df0
     int sd;
576df0
     char **env;
576df0
-    apr_file_t *tempsock;
576df0
+    apr_file_t *tempsock, *script_err, *errpipe_out;
576df0
     struct cleanup_script_info *info;
576df0
     apr_status_t rv;
576df0
     cgid_dirconf *dc;
576df0
+    apr_interval_time_t timeout;
576df0
 
576df0
     if (strcmp(r->handler, CGI_MAGIC_TYPE) && strcmp(r->handler, "cgi-script")) {
576df0
         return DECLINED;
576df0
@@ -1416,7 +1549,7 @@
576df0
     conf = ap_get_module_config(r->server->module_config, &cgid_module);
576df0
     dc = ap_get_module_config(r->per_dir_config, &cgid_module);
576df0
 
576df0
-    
576df0
+    timeout = dc->timeout > 0 ? dc->timeout : r->server->timeout;
576df0
     is_included = !strcmp(r->protocol, "INCLUDED");
576df0
 
576df0
     if ((argv0 = strrchr(r->filename, '/')) != NULL) {
576df0
@@ -1469,6 +1602,17 @@
576df0
     }
576df0
     */
576df0
 
576df0
+#ifdef HAVE_CGID_FDPASSING
576df0
+    rv = apr_file_pipe_create(&script_err, &errpipe_out, r->pool);
576df0
+    if (rv) {
576df0
+        return log_scripterror(r, conf, HTTP_SERVICE_UNAVAILABLE, rv, APLOGNO(10176)
576df0
+                               "could not create pipe for stderr");
576df0
+    }
576df0
+#else
576df0
+    script_err = NULL;
576df0
+    errpipe_out = NULL;
576df0
+#endif
576df0
+    
576df0
     /*
576df0
      * httpd core function used to add common environment variables like
576df0
      * DOCUMENT_ROOT. 
576df0
@@ -1481,12 +1625,16 @@
576df0
         return retval;
576df0
     }
576df0
 
576df0
-    rv = send_req(sd, r, argv0, env, CGI_REQ);
576df0
+    rv = send_req(sd, errpipe_out, r, argv0, env, CGI_REQ);
576df0
     if (rv != APR_SUCCESS) {
576df0
         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01268)
576df0
                      "write to cgi daemon process");
576df0
     }
576df0
 
576df0
+    /* The write-end of the pipe is only used by the server, so close
576df0
+     * it here. */
576df0
+    if (errpipe_out) apr_file_close(errpipe_out);
576df0
+    
576df0
     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
576df0
     info->conf = conf;
576df0
     info->r = r;
576df0
@@ -1508,12 +1656,7 @@
576df0
      */
576df0
 
576df0
     apr_os_pipe_put_ex(&tempsock, &sd, 1, r->pool);
576df0
-    if (dc->timeout > 0) { 
576df0
-        apr_file_pipe_timeout_set(tempsock, dc->timeout);
576df0
-    }
576df0
-    else { 
576df0
-        apr_file_pipe_timeout_set(tempsock, r->server->timeout);
576df0
-    }
576df0
+    apr_file_pipe_timeout_set(tempsock, timeout);
576df0
     apr_pool_cleanup_kill(r->pool, (void *)((long)sd), close_unix_socket);
576df0
 
576df0
     /* Transfer any put/post args, CERN style...
576df0
@@ -1605,114 +1748,19 @@
576df0
      */
576df0
     shutdown(sd, 1);
576df0
 
576df0
-    /* Handle script return... */
576df0
-    if (!nph) {
576df0
-        conn_rec *c = r->connection;
576df0
-        const char *location;
576df0
-        char sbuf[MAX_STRING_LEN];
576df0
-        int ret;
576df0
-
576df0
-        bb = apr_brigade_create(r->pool, c->bucket_alloc);
576df0
-        b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
576df0
-        APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
-        b = apr_bucket_eos_create(c->bucket_alloc);
576df0
-        APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
-
576df0
-        if ((ret = ap_scan_script_header_err_brigade_ex(r, bb, sbuf,
576df0
-                                                        APLOG_MODULE_INDEX)))
576df0
-        {
576df0
-            ret = log_script(r, conf, ret, dbuf, sbuf, bb, NULL);
576df0
-
576df0
-            /*
576df0
-             * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
576df0
-             * does not set an explicit status and ap_meets_conditions, which
576df0
-             * is called by ap_scan_script_header_err_brigade, detects that
576df0
-             * the conditions of the requests are met and the response is
576df0
-             * not modified.
576df0
-             * In this case set r->status and return OK in order to prevent
576df0
-             * running through the error processing stack as this would
576df0
-             * break with mod_cache, if the conditions had been set by
576df0
-             * mod_cache itself to validate a stale entity.
576df0
-             * BTW: We circumvent the error processing stack anyway if the
576df0
-             * CGI script set an explicit status code (whatever it is) and
576df0
-             * the only possible values for ret here are:
576df0
-             *
576df0
-             * HTTP_NOT_MODIFIED          (set by ap_meets_conditions)
576df0
-             * HTTP_PRECONDITION_FAILED   (set by ap_meets_conditions)
576df0
-             * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
576df0
-             * processing of the response of the CGI script, e.g broken headers
576df0
-             * or a crashed CGI process).
576df0
-             */
576df0
-            if (ret == HTTP_NOT_MODIFIED) {
576df0
-                r->status = ret;
576df0
-                return OK;
576df0
-            }
576df0
-
576df0
-            return ret;
576df0
-        }
576df0
-
576df0
-        location = apr_table_get(r->headers_out, "Location");
576df0
-
576df0
-        if (location && location[0] == '/' && r->status == 200) {
576df0
-
576df0
-            /* Soak up all the script output */
576df0
-            discard_script_output(bb);
576df0
-            apr_brigade_destroy(bb);
576df0
-            /* This redirect needs to be a GET no matter what the original
576df0
-             * method was.
576df0
-             */
576df0
-            r->method = "GET";
576df0
-            r->method_number = M_GET;
576df0
-
576df0
-            /* We already read the message body (if any), so don't allow
576df0
-             * the redirected request to think it has one. We can ignore
576df0
-             * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
576df0
-             */
576df0
-            apr_table_unset(r->headers_in, "Content-Length");
576df0
-
576df0
-            ap_internal_redirect_handler(location, r);
576df0
-            return OK;
576df0
-        }
576df0
-        else if (location && r->status == 200) {
576df0
-            /* XXX: Note that if a script wants to produce its own Redirect
576df0
-             * body, it now has to explicitly *say* "Status: 302"
576df0
-             */
576df0
-            discard_script_output(bb);
576df0
-            apr_brigade_destroy(bb);
576df0
-            return HTTP_MOVED_TEMPORARILY;
576df0
-        }
576df0
-
576df0
-        rv = ap_pass_brigade(r->output_filters, bb);
576df0
-        if (rv != APR_SUCCESS) { 
576df0
-            ap_log_rerror(APLOG_MARK, APLOG_TRACE1, rv, r,
576df0
-                          "Failed to flush CGI output to client");
576df0
-        }
576df0
-    }
576df0
-
576df0
-    if (nph) {
576df0
-        conn_rec *c = r->connection;
576df0
-        struct ap_filter_t *cur;
576df0
-
576df0
-        /* get rid of all filters up through protocol...  since we
576df0
-         * haven't parsed off the headers, there is no way they can
576df0
-         * work
576df0
-         */
576df0
-
576df0
-        cur = r->proto_output_filters;
576df0
-        while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
576df0
-            cur = cur->next;
576df0
-        }
576df0
-        r->output_filters = r->proto_output_filters = cur;
576df0
-
576df0
-        bb = apr_brigade_create(r->pool, c->bucket_alloc);
576df0
-        b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
576df0
-        APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
-        b = apr_bucket_eos_create(c->bucket_alloc);
576df0
-        APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
-        ap_pass_brigade(r->output_filters, bb);
576df0
-    }
576df0
+    bb = apr_brigade_create(r->pool, c->bucket_alloc);
576df0
+#ifdef HAVE_CGID_FDPASSING
576df0
+    b = cgi_bucket_create(r, dc->timeout, tempsock, script_err, c->bucket_alloc);
576df0
+    if (b == NULL)
576df0
+        return HTTP_INTERNAL_SERVER_ERROR; /* should call log_scripterror() w/ _UNAVAILABLE? */
576df0
+#else
576df0
+    b = apr_bucket_pipe_create(tempsock, c->bucket_alloc);
576df0
+#endif
576df0
+    APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
+    b = apr_bucket_eos_create(c->bucket_alloc);
576df0
+    APR_BRIGADE_INSERT_TAIL(bb, b);
576df0
 
576df0
-    return OK; /* NOT r->status, even if it has changed. */
576df0
+    return cgi_handle_response(r, nph, bb, timeout, conf, dbuf, script_err);
576df0
 }
576df0
 
576df0
 
576df0
@@ -1829,7 +1877,7 @@
576df0
         return retval;
576df0
     }
576df0
 
576df0
-    send_req(sd, r, command, env, SSI_REQ);
576df0
+    send_req(sd, NULL, r, command, env, SSI_REQ);
576df0
 
576df0
     info = apr_palloc(r->pool, sizeof(struct cleanup_script_info));
576df0
     info->conf = conf;
576df0
--- httpd-2.4.41/modules/generators/cgi_common.h
576df0
+++ httpd-2.4.41/modules/generators/cgi_common.h
576df0
@@ -0,0 +1,359 @@
576df0
+/* Licensed to the Apache Software Foundation (ASF) under one or more
576df0
+ * contributor license agreements.  See the NOTICE file distributed with
576df0
+ * this work for additional information regarding copyright ownership.
576df0
+ * The ASF licenses this file to You under the Apache License, Version 2.0
576df0
+ * (the "License"); you may not use this file except in compliance with
576df0
+ * the License.  You may obtain a copy of the License at
576df0
+ *
576df0
+ *     http://www.apache.org/licenses/LICENSE-2.0
576df0
+ *
576df0
+ * Unless required by applicable law or agreed to in writing, software
576df0
+ * distributed under the License is distributed on an "AS IS" BASIS,
576df0
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
576df0
+ * See the License for the specific language governing permissions and
576df0
+ * limitations under the License.
576df0
+ */
576df0
+
576df0
+#include "apr.h"
576df0
+#include "apr_strings.h"
576df0
+#include "apr_buckets.h"
576df0
+#include "apr_lib.h"
576df0
+#include "apr_poll.h"
576df0
+
576df0
+#define APR_WANT_STRFUNC
576df0
+#define APR_WANT_MEMFUNC
576df0
+#include "apr_want.h"
576df0
+
576df0
+#include "httpd.h"
576df0
+#include "util_filter.h"
576df0
+
576df0
+static void discard_script_output(apr_bucket_brigade *bb)
576df0
+{
576df0
+    apr_bucket *e;
576df0
+    const char *buf;
576df0
+    apr_size_t len;
576df0
+
576df0
+    for (e = APR_BRIGADE_FIRST(bb);
576df0
+         e != APR_BRIGADE_SENTINEL(bb) && !APR_BUCKET_IS_EOS(e);
576df0
+         e = APR_BRIGADE_FIRST(bb))
576df0
+    {
576df0
+        if (apr_bucket_read(e, &buf, &len, APR_BLOCK_READ)) {
576df0
+            break;
576df0
+        }
576df0
+        apr_bucket_delete(e);
576df0
+    }
576df0
+}
576df0
+
576df0
+#ifdef WANT_CGI_BUCKET
576df0
+/* A CGI bucket type is needed to catch any output to stderr from the
576df0
+ * script; see PR 22030. */
576df0
+static const apr_bucket_type_t bucket_type_cgi;
576df0
+
576df0
+struct cgi_bucket_data {
576df0
+    apr_pollset_t *pollset;
576df0
+    request_rec *r;
576df0
+    apr_interval_time_t timeout;
576df0
+};
576df0
+
576df0
+/* Create a CGI bucket using pipes from script stdout 'out'
576df0
+ * and stderr 'err', for request 'r'. */
576df0
+static apr_bucket *cgi_bucket_create(request_rec *r,
576df0
+                                     apr_interval_time_t timeout,
576df0
+                                     apr_file_t *out, apr_file_t *err,
576df0
+                                     apr_bucket_alloc_t *list)
576df0
+{
576df0
+    apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
576df0
+    apr_status_t rv;
576df0
+    apr_pollfd_t fd;
576df0
+    struct cgi_bucket_data *data = apr_palloc(r->pool, sizeof *data);
576df0
+
576df0
+    /* Disable APR timeout handling since we'll use poll() entirely. */
576df0
+    apr_file_pipe_timeout_set(out, 0);
576df0
+    apr_file_pipe_timeout_set(err, 0);
576df0
+    
576df0
+    APR_BUCKET_INIT(b);
576df0
+    b->free = apr_bucket_free;
576df0
+    b->list = list;
576df0
+    b->type = &bucket_type_cgi;
576df0
+    b->length = (apr_size_t)(-1);
576df0
+    b->start = -1;
576df0
+
576df0
+    /* Create the pollset */
576df0
+    rv = apr_pollset_create(&data->pollset, 2, r->pool, 0);
576df0
+    if (rv != APR_SUCCESS) {
576df0
+        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01217)
576df0
+                     "apr_pollset_create(); check system or user limits");
576df0
+        return NULL;
576df0
+    }
576df0
+
576df0
+    fd.desc_type = APR_POLL_FILE;
576df0
+    fd.reqevents = APR_POLLIN;
576df0
+    fd.p = r->pool;
576df0
+    fd.desc.f = out; /* script's stdout */
576df0
+    fd.client_data = (void *)1;
576df0
+    rv = apr_pollset_add(data->pollset, &fd;;
576df0
+    if (rv != APR_SUCCESS) {
576df0
+        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01218)
576df0
+                     "apr_pollset_add(); check system or user limits");
576df0
+        return NULL;
576df0
+    }
576df0
+
576df0
+    fd.desc.f = err; /* script's stderr */
576df0
+    fd.client_data = (void *)2;
576df0
+    rv = apr_pollset_add(data->pollset, &fd;;
576df0
+    if (rv != APR_SUCCESS) {
576df0
+        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01219)
576df0
+                     "apr_pollset_add(); check system or user limits");
576df0
+        return NULL;
576df0
+    }
576df0
+
576df0
+    data->r = r;
576df0
+    data->timeout = timeout;
576df0
+    b->data = data;
576df0
+    return b;
576df0
+}
576df0
+
576df0
+/* Create a duplicate CGI bucket using given bucket data */
576df0
+static apr_bucket *cgi_bucket_dup(struct cgi_bucket_data *data,
576df0
+                                  apr_bucket_alloc_t *list)
576df0
+{
576df0
+    apr_bucket *b = apr_bucket_alloc(sizeof(*b), list);
576df0
+    APR_BUCKET_INIT(b);
576df0
+    b->free = apr_bucket_free;
576df0
+    b->list = list;
576df0
+    b->type = &bucket_type_cgi;
576df0
+    b->length = (apr_size_t)(-1);
576df0
+    b->start = -1;
576df0
+    b->data = data;
576df0
+    return b;
576df0
+}
576df0
+
576df0
+/* Handle stdout from CGI child.  Duplicate of logic from the _read
576df0
+ * method of the real APR pipe bucket implementation. */
576df0
+static apr_status_t cgi_read_stdout(apr_bucket *a, apr_file_t *out,
576df0
+                                    const char **str, apr_size_t *len)
576df0
+{
576df0
+    char *buf;
576df0
+    apr_status_t rv;
576df0
+
576df0
+    *str = NULL;
576df0
+    *len = APR_BUCKET_BUFF_SIZE;
576df0
+    buf = apr_bucket_alloc(*len, a->list); /* XXX: check for failure? */
576df0
+
576df0
+    rv = apr_file_read(out, buf, len);
576df0
+
576df0
+    if (rv != APR_SUCCESS && rv != APR_EOF) {
576df0
+        apr_bucket_free(buf);
576df0
+        return rv;
576df0
+    }
576df0
+
576df0
+    if (*len > 0) {
576df0
+        struct cgi_bucket_data *data = a->data;
576df0
+        apr_bucket_heap *h;
576df0
+
576df0
+        /* Change the current bucket to refer to what we read */
576df0
+        a = apr_bucket_heap_make(a, buf, *len, apr_bucket_free);
576df0
+        h = a->data;
576df0
+        h->alloc_len = APR_BUCKET_BUFF_SIZE; /* note the real buffer size */
576df0
+        *str = buf;
576df0
+        APR_BUCKET_INSERT_AFTER(a, cgi_bucket_dup(data, a->list));
576df0
+    }
576df0
+    else {
576df0
+        apr_bucket_free(buf);
576df0
+        a = apr_bucket_immortal_make(a, "", 0);
576df0
+        *str = a->data;
576df0
+    }
576df0
+    return rv;
576df0
+}
576df0
+
576df0
+/* Read method of CGI bucket: polls on stderr and stdout of the child,
576df0
+ * sending any stderr output immediately away to the error log. */
576df0
+static apr_status_t cgi_bucket_read(apr_bucket *b, const char **str,
576df0
+                                    apr_size_t *len, apr_read_type_e block)
576df0
+{
576df0
+    struct cgi_bucket_data *data = b->data;
576df0
+    apr_interval_time_t timeout = 0;
576df0
+    apr_status_t rv;
576df0
+    int gotdata = 0;
576df0
+
576df0
+    if (block != APR_NONBLOCK_READ) {
576df0
+        timeout = data->timeout > 0 ? data->timeout : data->r->server->timeout;
576df0
+    }
576df0
+
576df0
+    do {
576df0
+        const apr_pollfd_t *results;
576df0
+        apr_int32_t num;
576df0
+
576df0
+        rv = apr_pollset_poll(data->pollset, timeout, &num, &results);
576df0
+        if (APR_STATUS_IS_TIMEUP(rv)) {
576df0
+            if (timeout) {
576df0
+                ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, data->r, APLOGNO(01220)
576df0
+                              "Timeout waiting for output from CGI script %s",
576df0
+                              data->r->filename);
576df0
+                return rv;
576df0
+            }
576df0
+            else {
576df0
+                return APR_EAGAIN;
576df0
+            }
576df0
+        }
576df0
+        else if (APR_STATUS_IS_EINTR(rv)) {
576df0
+            continue;
576df0
+        }
576df0
+        else if (rv != APR_SUCCESS) {
576df0
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r, APLOGNO(01221)
576df0
+                          "poll failed waiting for CGI child");
576df0
+            return rv;
576df0
+        }
576df0
+
576df0
+        for (; num; num--, results++) {
576df0
+            if (results[0].client_data == (void *)1) {
576df0
+                /* stdout */
576df0
+                rv = cgi_read_stdout(b, results[0].desc.f, str, len);
576df0
+                if (APR_STATUS_IS_EOF(rv)) {
576df0
+                    rv = APR_SUCCESS;
576df0
+                }
576df0
+                gotdata = 1;
576df0
+            } else {
576df0
+                /* stderr */
576df0
+                apr_status_t rv2 = log_script_err(data->r, results[0].desc.f);
576df0
+                if (APR_STATUS_IS_EOF(rv2)) {
576df0
+                    apr_pollset_remove(data->pollset, &results[0]);
576df0
+                }
576df0
+            }
576df0
+        }
576df0
+
576df0
+    } while (!gotdata);
576df0
+
576df0
+    return rv;
576df0
+}
576df0
+
576df0
+static const apr_bucket_type_t bucket_type_cgi = {
576df0
+    "CGI", 5, APR_BUCKET_DATA,
576df0
+    apr_bucket_destroy_noop,
576df0
+    cgi_bucket_read,
576df0
+    apr_bucket_setaside_notimpl,
576df0
+    apr_bucket_split_notimpl,
576df0
+    apr_bucket_copy_notimpl
576df0
+};
576df0
+
576df0
+#endif /* WANT_CGI_BUCKET */
576df0
+
576df0
+/* Handle the CGI response output, having set up the brigade with the
576df0
+ * CGI or PIPE bucket as appropriate. */
576df0
+static int cgi_handle_response(request_rec *r, int nph, apr_bucket_brigade *bb,
576df0
+                               apr_interval_time_t timeout, cgi_server_conf *conf,
576df0
+                               char *logdata, apr_file_t *script_err)
576df0
+{
576df0
+    apr_status_t rv;
576df0
+    
576df0
+    /* Handle script return... */
576df0
+    if (!nph) {
576df0
+        const char *location;
576df0
+        char sbuf[MAX_STRING_LEN];
576df0
+        int ret;
576df0
+
576df0
+        if ((ret = ap_scan_script_header_err_brigade_ex(r, bb, sbuf,
576df0
+                                                        APLOG_MODULE_INDEX)))
576df0
+        {
576df0
+            ret = log_script(r, conf, ret, logdata, sbuf, bb, script_err);
576df0
+
576df0
+            /*
576df0
+             * ret could be HTTP_NOT_MODIFIED in the case that the CGI script
576df0
+             * does not set an explicit status and ap_meets_conditions, which
576df0
+             * is called by ap_scan_script_header_err_brigade, detects that
576df0
+             * the conditions of the requests are met and the response is
576df0
+             * not modified.
576df0
+             * In this case set r->status and return OK in order to prevent
576df0
+             * running through the error processing stack as this would
576df0
+             * break with mod_cache, if the conditions had been set by
576df0
+             * mod_cache itself to validate a stale entity.
576df0
+             * BTW: We circumvent the error processing stack anyway if the
576df0
+             * CGI script set an explicit status code (whatever it is) and
576df0
+             * the only possible values for ret here are:
576df0
+             *
576df0
+             * HTTP_NOT_MODIFIED          (set by ap_meets_conditions)
576df0
+             * HTTP_PRECONDITION_FAILED   (set by ap_meets_conditions)
576df0
+             * HTTP_INTERNAL_SERVER_ERROR (if something went wrong during the
576df0
+             * processing of the response of the CGI script, e.g broken headers
576df0
+             * or a crashed CGI process).
576df0
+             */
576df0
+            if (ret == HTTP_NOT_MODIFIED) {
576df0
+                r->status = ret;
576df0
+                return OK;
576df0
+            }
576df0
+
576df0
+            return ret;
576df0
+        }
576df0
+
576df0
+        location = apr_table_get(r->headers_out, "Location");
576df0
+
576df0
+        if (location && r->status == 200) {
576df0
+            /* For a redirect whether internal or not, discard any
576df0
+             * remaining stdout from the script, and log any remaining
576df0
+             * stderr output, as normal. */
576df0
+            discard_script_output(bb);
576df0
+            apr_brigade_destroy(bb);
576df0
+
576df0
+            if (script_err) {
576df0
+                apr_file_pipe_timeout_set(script_err, timeout);
576df0
+                log_script_err(r, script_err);
576df0
+            }
576df0
+        }
576df0
+
576df0
+        if (location && location[0] == '/' && r->status == 200) {
576df0
+            /* This redirect needs to be a GET no matter what the original
576df0
+             * method was.
576df0
+             */
576df0
+            r->method = "GET";
576df0
+            r->method_number = M_GET;
576df0
+
576df0
+            /* We already read the message body (if any), so don't allow
576df0
+             * the redirected request to think it has one.  We can ignore
576df0
+             * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR.
576df0
+             */
576df0
+            apr_table_unset(r->headers_in, "Content-Length");
576df0
+
576df0
+            ap_internal_redirect_handler(location, r);
576df0
+            return OK;
576df0
+        }
576df0
+        else if (location && r->status == 200) {
576df0
+            /* XXX: Note that if a script wants to produce its own Redirect
576df0
+             * body, it now has to explicitly *say* "Status: 302"
576df0
+             */
576df0
+            discard_script_output(bb);
576df0
+            apr_brigade_destroy(bb);
576df0
+            return HTTP_MOVED_TEMPORARILY;
576df0
+        }
576df0
+
576df0
+        rv = ap_pass_brigade(r->output_filters, bb);
576df0
+    }
576df0
+    else /* nph */ {
576df0
+        struct ap_filter_t *cur;
576df0
+
576df0
+        /* get rid of all filters up through protocol...  since we
576df0
+         * haven't parsed off the headers, there is no way they can
576df0
+         * work
576df0
+         */
576df0
+
576df0
+        cur = r->proto_output_filters;
576df0
+        while (cur && cur->frec->ftype < AP_FTYPE_CONNECTION) {
576df0
+            cur = cur->next;
576df0
+        }
576df0
+        r->output_filters = r->proto_output_filters = cur;
576df0
+
576df0
+        rv = ap_pass_brigade(r->output_filters, bb);
576df0
+    }
576df0
+
576df0
+    /* don't soak up script output if errors occurred writing it
576df0
+     * out...  otherwise, we prolong the life of the script when the
576df0
+     * connection drops or we stopped sending output for some other
576df0
+     * reason */
576df0
+    if (script_err && rv == APR_SUCCESS && !r->connection->aborted) {
576df0
+        apr_file_pipe_timeout_set(script_err, timeout);
576df0
+        log_script_err(r, script_err);
576df0
+    }
576df0
+
576df0
+    if (script_err) apr_file_close(script_err);
576df0
+
576df0
+    return OK;                      /* NOT r->status, even if it has changed. */
576df0
+}