X-Git-Url: https://granicus.if.org/sourcecode?a=blobdiff_plain;f=modules%2Fproxy%2Fmod_proxy_http.c;h=7822366c0fae1756a480b900954b4cb7dc943e60;hb=2af2fa44ad916dd01102764e3a7674a450622028;hp=ff2b3c82e7a2905da115e8e93a030dcadcffab5d;hpb=b0c37384b3f8fa1e0cb7a0d2c62a4efa9fb4b88f;p=apache diff --git a/modules/proxy/mod_proxy_http.c b/modules/proxy/mod_proxy_http.c index ff2b3c82e7..7822366c0f 100644 --- a/modules/proxy/mod_proxy_http.c +++ b/modules/proxy/mod_proxy_http.c @@ -17,6 +17,7 @@ /* HTTP routines for Apache proxy */ #include "mod_proxy.h" +#include "ap_regex.h" module AP_MODULE_DECLARE_DATA proxy_http_module; @@ -32,7 +33,8 @@ static apr_status_t ap_proxy_http_cleanup(const char *scheme, */ static int proxy_http_canon(request_rec *r, char *url) { - char *host, *path, *search, sport[7]; + char *host, *path, sport[7]; + char *search = NULL; const char *err; const char *scheme; apr_port_t port, def_port; @@ -51,8 +53,8 @@ static int proxy_http_canon(request_rec *r, char *url) } def_port = apr_uri_port_of_scheme(scheme); - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: HTTP: canonicalising URL %s", url); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, + "HTTP: canonicalising URL %s", url); /* do syntatic check. * We break the URL into host, port, path, search @@ -60,27 +62,36 @@ static int proxy_http_canon(request_rec *r, char *url) port = def_port; err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port); if (err) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, - "error parsing URL %s: %s", - url, err); + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01083) + "error parsing URL %s: %s", url, err); return HTTP_BAD_REQUEST; } - /* now parse path/search args, according to rfc1738 */ - /* N.B. if this isn't a true proxy request, then the URL _path_ - * has already been decoded. True proxy requests have r->uri - * == r->unparsed_uri, and no others have that property. + /* + * now parse path/search args, according to rfc1738: + * process the path. + * + * In a reverse proxy, our URL has been processed, so canonicalise + * unless proxy-nocanon is set to say it's raw + * In a forward proxy, we have and MUST NOT MANGLE the original. */ - if (r->uri == r->unparsed_uri) { - search = strchr(url, '?'); - if (search != NULL) - *(search++) = '\0'; + switch (r->proxyreq) { + default: /* wtf are we doing here? */ + case PROXYREQ_REVERSE: + if (apr_table_get(r->notes, "proxy-nocanon")) { + path = url; /* this is the raw path */ + } + else { + path = ap_proxy_canonenc(r->pool, url, strlen(url), + enc_path, 0, r->proxyreq); + search = r->args; + } + break; + case PROXYREQ_PROXY: + path = url; + break; } - else - search = r->args; - /* process path */ - path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq); if (path == NULL) return HTTP_BAD_REQUEST; @@ -98,16 +109,16 @@ static int proxy_http_canon(request_rec *r, char *url) } /* Clear all connection-based headers from the incoming headers table */ -typedef struct foo { +typedef struct header_dptr { apr_pool_t *pool; apr_table_t *table; apr_time_t time; -} foo; +} header_dptr; static ap_regex_t *warn_rx; static int clean_warning_headers(void *data, const char *key, const char *val) { - apr_table_t *headers = ((foo*)data)->table; - apr_pool_t *pool = ((foo*)data)->pool; + apr_table_t *headers = ((header_dptr*)data)->table; + apr_pool_t *pool = ((header_dptr*)data)->pool; char *warning; char *date; apr_time_t warn_time; @@ -115,7 +126,7 @@ static int clean_warning_headers(void *data, const char *key, const char *val) ap_regmatch_t pmatch[3]; if (headers == NULL) { - ((foo*)data)->table = headers = apr_table_make(pool, 2); + ((header_dptr*)data)->table = headers = apr_table_make(pool, 2); } /* * Parse this, suckers! @@ -145,7 +156,7 @@ static int clean_warning_headers(void *data, const char *key, const char *val) pmatch[2].rm_eo - pmatch[2].rm_so); warn_time = apr_date_parse_http(date); } - if (!warn_time || (warn_time == ((foo*)data)->time)) { + if (!warn_time || (warn_time == ((header_dptr*)data)->time)) { apr_table_addn(headers, key, warning); } val += pmatch[0].rm_eo; @@ -154,7 +165,7 @@ static int clean_warning_headers(void *data, const char *key, const char *val) } static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers) { - foo x; + header_dptr x; x.pool = p; x.table = NULL; x.time = apr_date_parse_http(apr_table_get(headers, "Date")); @@ -169,8 +180,8 @@ static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers) } static int clear_conn_headers(void *data, const char *key, const char *val) { - apr_table_t *headers = ((foo*)data)->table; - apr_pool_t *pool = ((foo*)data)->pool; + apr_table_t *headers = ((header_dptr*)data)->table; + apr_pool_t *pool = ((header_dptr*)data)->pool; const char *name; char *next = apr_pstrdup(pool, val); while (*next) { @@ -187,7 +198,7 @@ static int clear_conn_headers(void *data, const char *key, const char *val) } static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers) { - foo x; + header_dptr x; x.pool = p; x.table = headers; apr_table_unset(headers, "Proxy-Connection"); @@ -239,8 +250,8 @@ static void terminate_headers(apr_bucket_alloc_t *bucket_alloc, APR_BRIGADE_INSERT_TAIL(header_brigade, e); } -static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc, - request_rec *r, proxy_conn_rec *conn, +static int pass_brigade(apr_bucket_alloc_t *bucket_alloc, + request_rec *r, proxy_conn_rec *p_conn, conn_rec *origin, apr_bucket_brigade *bb, int flush) { @@ -253,28 +264,41 @@ static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc, } apr_brigade_length(bb, 0, &transferred); if (transferred != -1) - conn->worker->s->transferred += transferred; + p_conn->worker->s->transferred += transferred; status = ap_pass_brigade(origin->output_filters, bb); if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: pass request body failed to %pI (%s)", - conn->addr, conn->hostname); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01084) + "pass request body failed to %pI (%s)", + p_conn->addr, p_conn->hostname); + if (origin->aborted) { + const char *ssl_note; + + if (((ssl_note = apr_table_get(origin->notes, "SSL_connect_rv")) + != NULL) && (strcmp(ssl_note, "err") == 0)) { + return ap_proxyerror(r, HTTP_INTERNAL_SERVER_ERROR, + "Error during SSL Handshake with" + " remote server"); + } + return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY; + } + else { + return HTTP_BAD_REQUEST; + } } apr_brigade_cleanup(bb); - return APR_SUCCESS; + return OK; } #define MAX_MEM_SPOOL 16384 -static apr_status_t stream_reqbody_chunked(apr_pool_t *p, +static int stream_reqbody_chunked(apr_pool_t *p, request_rec *r, proxy_conn_rec *p_conn, conn_rec *origin, apr_bucket_brigade *header_brigade, apr_bucket_brigade *input_brigade) { - int seen_eos = 0; + int seen_eos = 0, rv = OK; apr_size_t hdr_len; apr_off_t bytes; apr_status_t status; @@ -332,7 +356,7 @@ static apr_status_t stream_reqbody_chunked(apr_pool_t *p, */ status = ap_save_brigade(NULL, &bb, &input_brigade, p); if (status != APR_SUCCESS) { - return status; + return HTTP_INTERNAL_SERVER_ERROR; } header_brigade = NULL; @@ -342,9 +366,9 @@ static apr_status_t stream_reqbody_chunked(apr_pool_t *p, } /* The request is flushed below this loop with chunk EOS header */ - status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0); - if (status != APR_SUCCESS) { - return status; + rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0); + if (rv != OK) { + return rv; } if (seen_eos) { @@ -356,7 +380,7 @@ static apr_status_t stream_reqbody_chunked(apr_pool_t *p, HUGE_STRING_LEN); if (status != APR_SUCCESS) { - return status; + return HTTP_BAD_REQUEST; } } @@ -388,11 +412,11 @@ static apr_status_t stream_reqbody_chunked(apr_pool_t *p, } /* Now we have headers-only, or the chunk EOS mark; flush it */ - status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1); - return status; + rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1); + return rv; } -static apr_status_t stream_reqbody_cl(apr_pool_t *p, +static int stream_reqbody_cl(apr_pool_t *p, request_rec *r, proxy_conn_rec *p_conn, conn_rec *origin, @@ -400,7 +424,7 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, apr_bucket_brigade *input_brigade, const char *old_cl_val) { - int seen_eos = 0; + int seen_eos = 0, rv = 0; apr_status_t status = APR_SUCCESS; apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc; apr_bucket_brigade *bb; @@ -410,10 +434,16 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, apr_off_t bytes_streamed = 0; if (old_cl_val) { + char *endstr; + add_cl(p, bucket_alloc, header_brigade, old_cl_val); - if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL, - 0))) { - return status; + status = apr_strtoff(&cl_val, old_cl_val, &endstr, 10); + + if (status || *endstr || endstr == old_cl_val || cl_val < 0) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01085) + "could not parse request Content-Length (%s)", + old_cl_val); + return HTTP_BAD_REQUEST; } } terminate_headers(bucket_alloc, header_brigade); @@ -446,8 +476,13 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, * * Prevents HTTP Response Splitting. */ - if (bytes_streamed > cl_val) - continue; + if (bytes_streamed > cl_val) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01086) + "read more bytes of request body than expected " + "(got %" APR_OFF_T_FMT ", expected %" APR_OFF_T_FMT ")", + bytes_streamed, cl_val); + return HTTP_INTERNAL_SERVER_ERROR; + } if (header_brigade) { /* we never sent the header brigade, so go ahead and @@ -466,7 +501,7 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, */ status = ap_save_brigade(NULL, &bb, &input_brigade, p); if (status != APR_SUCCESS) { - return status; + return HTTP_INTERNAL_SERVER_ERROR; } header_brigade = NULL; @@ -476,9 +511,9 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, } /* Once we hit EOS, we are ready to flush. */ - status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos); - if (status != APR_SUCCESS) { - return status; + rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos); + if (rv != OK) { + return rv ; } if (seen_eos) { @@ -490,15 +525,15 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, HUGE_STRING_LEN); if (status != APR_SUCCESS) { - return status; + return HTTP_BAD_REQUEST; } } if (bytes_streamed != cl_val) { - ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, - "proxy: client %s given Content-Length did not match" - " number of body bytes read", r->connection->remote_ip); - return APR_EOF; + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01087) + "client %s given Content-Length did not match" + " number of body bytes read", r->connection->peer_ip); + return HTTP_BAD_REQUEST; } if (header_brigade) { @@ -506,12 +541,13 @@ static apr_status_t stream_reqbody_cl(apr_pool_t *p, * body; send it now with the flush flag */ bb = header_brigade; - status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1); + return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1)); } - return status; + + return OK; } -static apr_status_t spool_reqbody_cl(apr_pool_t *p, +static int spool_reqbody_cl(apr_pool_t *p, request_rec *r, proxy_conn_rec *p_conn, conn_rec *origin, @@ -526,9 +562,12 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, apr_bucket *e; apr_off_t bytes, bytes_spooled = 0, fsize = 0; apr_file_t *tmpfile = NULL; + apr_off_t limit; body_brigade = apr_brigade_create(p, bucket_alloc); + limit = ap_get_limit_req_body(r); + while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade))) { /* If this brigade contains EOS, either stop or remove it. */ @@ -543,6 +582,17 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, apr_brigade_length(input_brigade, 1, &bytes); if (bytes_spooled + bytes > MAX_MEM_SPOOL) { + /* + * LimitRequestBody does not affect Proxy requests (Should it?). + * Let it take effect if we decide to store the body in a + * temporary file on disk. + */ + if (bytes_spooled + bytes > limit) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01088) + "Request body is larger than the configured " + "limit of %" APR_OFF_T_FMT, limit); + return HTTP_REQUEST_ENTITY_TOO_LARGE; + } /* can't spool any more in memory; write latest brigade to disk */ if (tmpfile == NULL) { const char *temp_dir; @@ -550,19 +600,19 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, status = apr_temp_dir_get(&temp_dir, p); if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: search for temporary directory failed"); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01089) + "search for temporary directory failed"); + return HTTP_INTERNAL_SERVER_ERROR; } apr_filepath_merge(&template, temp_dir, "modproxy.tmp.XXXXXX", APR_FILEPATH_NATIVE, p); status = apr_file_mktemp(&tmpfile, template, 0, p); if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: creation of temporary file in directory %s failed", - temp_dir); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01090) + "creation of temporary file in directory " + "%s failed", temp_dir); + return HTTP_INTERNAL_SERVER_ERROR; } } for (e = APR_BRIGADE_FIRST(input_brigade); @@ -579,10 +629,10 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) { tmpfile_name = "(unknown)"; } - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: write to temporary file %s failed", - tmpfile_name); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01091) + "write to temporary file %s failed", + tmpfile_name); + return HTTP_INTERNAL_SERVER_ERROR; } AP_DEBUG_ASSERT(bytes_read == bytes_written); fsize += bytes_written; @@ -602,7 +652,7 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, */ status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p); if (status != APR_SUCCESS) { - return status; + return HTTP_INTERNAL_SERVER_ERROR; } } @@ -618,7 +668,7 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, HUGE_STRING_LEN); if (status != APR_SUCCESS) { - return status; + return HTTP_BAD_REQUEST; } } @@ -635,13 +685,62 @@ static apr_status_t spool_reqbody_cl(apr_pool_t *p, APR_BRIGADE_INSERT_TAIL(header_brigade, e); } /* This is all a single brigade, pass with flush flagged */ - status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1); - return status; + return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1)); +} + +/* + * Transform buckets from one bucket allocator to another one by creating a + * transient bucket for each data bucket and let it use the data read from + * the old bucket. Metabuckets are transformed by just recreating them. + * Attention: Currently only the following bucket types are handled: + * + * All data buckets + * FLUSH + * EOS + * + * If an other bucket type is found its type is logged as a debug message + * and APR_EGENERAL is returned. + */ +static apr_status_t proxy_buckets_lifetime_transform(request_rec *r, + apr_bucket_brigade *from, apr_bucket_brigade *to) +{ + apr_bucket *e; + apr_bucket *new; + const char *data; + apr_size_t bytes; + apr_status_t rv = APR_SUCCESS; + + apr_brigade_cleanup(to); + for (e = APR_BRIGADE_FIRST(from); + e != APR_BRIGADE_SENTINEL(from); + e = APR_BUCKET_NEXT(e)) { + if (!APR_BUCKET_IS_METADATA(e)) { + apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ); + new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(to, new); + } + else if (APR_BUCKET_IS_FLUSH(e)) { + new = apr_bucket_flush_create(r->connection->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(to, new); + } + else if (APR_BUCKET_IS_EOS(e)) { + new = apr_bucket_eos_create(r->connection->bucket_alloc); + APR_BRIGADE_INSERT_TAIL(to, new); + } + else { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00964) + "Unhandled bucket type of type %s in" + " proxy_buckets_lifetime_transform", e->type->name); + apr_bucket_delete(e); + rv = APR_EGENERAL; + } + } + return rv; } static -apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, - proxy_conn_rec *p_conn, conn_rec *origin, +int ap_proxy_http_request(apr_pool_t *p, request_rec *r, + proxy_conn_rec *p_conn, proxy_worker *worker, proxy_server_conf *conf, apr_uri_t *uri, char *url, char *server_portstr) @@ -663,16 +762,37 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, const char *old_te_val = NULL; apr_off_t bytes_read = 0; apr_off_t bytes; - int force10; + int force10, rv; apr_table_t *headers_in_copy; + proxy_dir_conf *dconf; + conn_rec *origin = p_conn->connection; + int do_100_continue; + dconf = ap_get_module_config(r->per_dir_config, &proxy_module); header_brigade = apr_brigade_create(p, origin->bucket_alloc); /* * Send the HTTP/1.1 request to the remote server */ + /* + * To be compliant, we only use 100-Continue for requests with bodies. + * We also make sure we won't be talking HTTP/1.0 as well. + */ + do_100_continue = (worker->s->ping_timeout_set + && ap_request_has_body(r) + && (PROXYREQ_REVERSE == r->proxyreq) + && !(apr_table_get(r->subprocess_env, "force-proxy-request-1.0"))); + if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) { + /* + * According to RFC 2616 8.2.3 we are not allowed to forward an + * Expect: 100-continue to an HTTP/1.0 server. Instead we MUST return + * a HTTP_EXPECTATION_FAILED + */ + if (r->expecting_100) { + return HTTP_EXPECTATION_FAILED; + } buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL); force10 = 1; p_conn->close++; @@ -687,12 +807,21 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, ap_xlate_proto_to_ascii(buf, strlen(buf)); e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(header_brigade, e); - if (conf->preserve_host == 0) { - if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) { - buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str, - CRLF, NULL); + if (dconf->preserve_host == 0) { + if (ap_strchr_c(uri->hostname, ':')) { /* if literal IPv6 address */ + if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) { + buf = apr_pstrcat(p, "Host: [", uri->hostname, "]:", + uri->port_str, CRLF, NULL); + } else { + buf = apr_pstrcat(p, "Host: [", uri->hostname, "]", CRLF, NULL); + } } else { - buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL); + if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) { + buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", + uri->port_str, CRLF, NULL); + } else { + buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL); + } } } else { @@ -702,12 +831,11 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, const char* hostname = apr_table_get(r->headers_in,"Host"); if (!hostname) { hostname = r->server->server_hostname; - ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, - "proxy: no HTTP 0.9 request (with no host line) " + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01092) + "no HTTP 0.9 request (with no host line) " "on incoming request and preserve host set " "forcing hostname to be %s for uri %s", - hostname, - r->uri ); + hostname, r->uri); } buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL); } @@ -744,6 +872,14 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, ); } + /* Use HTTP/1.1 100-Continue as quick "HTTP ping" test + * to backend + */ + if (do_100_continue) { + apr_table_mergen(r->headers_in, "Expect", "100-Continue"); + r->expecting_100 = 1; + } + /* X-Forwarded-*: handling * * XXX Privacy Note: @@ -764,29 +900,30 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, * a forward proxy configuation instead of X-Forwarded-*. See the * ProxyVia option for details. */ + if (dconf->add_forwarded_headers) { + if (PROXYREQ_REVERSE == r->proxyreq) { + const char *buf; + + /* Add X-Forwarded-For: so that the upstream has a chance to + * determine, where the original request came from. + */ + apr_table_mergen(r->headers_in, "X-Forwarded-For", + r->useragent_ip); + + /* Add X-Forwarded-Host: so that upstream knows what the + * original request hostname was. + */ + if ((buf = apr_table_get(r->headers_in, "Host"))) { + apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf); + } - if (PROXYREQ_REVERSE == r->proxyreq) { - const char *buf; - - /* Add X-Forwarded-For: so that the upstream has a chance to - * determine, where the original request came from. - */ - apr_table_mergen(r->headers_in, "X-Forwarded-For", - c->remote_ip); - - /* Add X-Forwarded-Host: so that upstream knows what the - * original request hostname was. - */ - if ((buf = apr_table_get(r->headers_in, "Host"))) { - apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf); - } - - /* Add X-Forwarded-Server: so that upstream knows what the - * name of this proxy server is (if there are more than one) - * XXX: This duplicates Via: - do we strictly need it? - */ - apr_table_mergen(r->headers_in, "X-Forwarded-Server", - r->server->server_hostname); + /* Add X-Forwarded-Server: so that upstream knows what the + * name of this proxy server is (if there are more than one) + * XXX: This duplicates Via: - do we strictly need it? + */ + apr_table_mergen(r->headers_in, "X-Forwarded-Server", + r->server->server_hostname); + } } proxy_run_fixups(r); @@ -876,8 +1013,11 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, * input_brigade and jump past all of the request body logic... * Reading anything with ap_get_brigade is likely to consume the * main request's body or read beyond EOS - which would be unplesant. + * + * An exception: when a kept_body is present, then subrequest CAN use + * pass request bodies, and we DONT skip the body. */ - if (r->main) { + if (!r->kept_body && r->main) { /* XXX: Why DON'T sub-requests use keepalives? */ p_conn->close++; if (old_cl_val) { @@ -902,18 +1042,17 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, * encoding has been done by the extensions' handler, and * do not modify add_te_chunked's logic */ - if (old_te_val && strcmp(old_te_val, "chunked") != 0) { - ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server, - "proxy: %s Transfer-Encoding is not supported", - old_te_val); - return APR_EINVAL; + if (old_te_val && strcasecmp(old_te_val, "chunked") != 0) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01093) + "%s Transfer-Encoding is not supported", old_te_val); + return HTTP_INTERNAL_SERVER_ERROR; } if (old_cl_val && old_te_val) { - ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server, - "proxy: client %s (%s) requested Transfer-Encoding " - "chunked body with Content-Length (C-L ignored)", - c->remote_ip, c->remote_host ? c->remote_host: ""); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01094) + "client %s (%s) requested Transfer-Encoding " + "chunked body with Content-Length (C-L ignored)", + c->peer_ip, c->remote_host ? c->remote_host: ""); apr_table_unset(r->headers_in, "Content-Length"); old_cl_val = NULL; origin->keepalive = AP_CONN_CLOSE; @@ -934,12 +1073,12 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, AP_MODE_READBYTES, APR_BLOCK_READ, MAX_MEM_SPOOL - bytes_read); if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: prefetch request body failed to %pI (%s)" - " from %s (%s)", - p_conn->addr, p_conn->hostname ? p_conn->hostname: "", - c->remote_ip, c->remote_host ? c->remote_host: ""); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01095) + "prefetch request body failed to %pI (%s)" + " from %s (%s)", + p_conn->addr, p_conn->hostname ? p_conn->hostname: "", + c->peer_ip, c->remote_host ? c->remote_host: ""); + return HTTP_BAD_REQUEST; } apr_brigade_length(temp_brigade, 1, &bytes); @@ -956,12 +1095,12 @@ apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r, */ status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p); if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: processing prefetched request body failed" - " to %pI (%s) from %s (%s)", - p_conn->addr, p_conn->hostname ? p_conn->hostname: "", - c->remote_ip, c->remote_host ? c->remote_host: ""); - return status; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01096) + "processing prefetched request body failed" + " to %pI (%s) from %s (%s)", + p_conn->addr, p_conn->hostname ? p_conn->hostname: "", + c->peer_ip, c->remote_host ? c->remote_host: ""); + return HTTP_INTERNAL_SERVER_ERROR; } /* Ensure we don't hit a wall where we have a buffer too small @@ -1075,37 +1214,94 @@ skip_body: /* send the request body, if any. */ switch(rb_method) { case RB_STREAM_CHUNKED: - status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade, + rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade, input_brigade); break; case RB_STREAM_CL: - status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade, + rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade, input_brigade, old_cl_val); break; case RB_SPOOL_CL: - status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade, + rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade, input_brigade, (old_cl_val != NULL) || (old_te_val != NULL) || (bytes_read > 0)); break; default: /* shouldn't be possible */ - status = APR_EINVAL; + rv = HTTP_INTERNAL_SERVER_ERROR ; break; } - if (status != APR_SUCCESS) { - ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server, - "proxy: pass request body failed to %pI (%s)" - " from %s (%s)", - p_conn->addr, - p_conn->hostname ? p_conn->hostname: "", - c->remote_ip, - c->remote_host ? c->remote_host: ""); - return status; + if (rv != OK) { + /* apr_status_t value has been logged in lower level method */ + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01097) + "pass request body failed to %pI (%s) from %s (%s)", + p_conn->addr, p_conn->hostname ? p_conn->hostname: "", + c->peer_ip, c->remote_host ? c->remote_host: ""); + return rv; + } + + return OK; +} + +/* + * If the date is a valid RFC 850 date or asctime() date, then it + * is converted to the RFC 1123 format. + */ +static const char *date_canon(apr_pool_t *p, const char *date) +{ + apr_status_t rv; + char* ndate; + + apr_time_t time = apr_date_parse_http(date); + if (!time) { + return date; + } + + ndate = apr_palloc(p, APR_RFC822_DATE_LEN); + rv = apr_rfc822_date(ndate, time); + if (rv != APR_SUCCESS) { + return date; } - return APR_SUCCESS; + return ndate; +} + +static request_rec *make_fake_req(conn_rec *c, request_rec *r) +{ + apr_pool_t *pool; + request_rec *rp; + + apr_pool_create(&pool, c->pool); + + rp = apr_pcalloc(pool, sizeof(*r)); + + rp->pool = pool; + rp->status = HTTP_OK; + + rp->headers_in = apr_table_make(pool, 50); + rp->subprocess_env = apr_table_make(pool, 50); + rp->headers_out = apr_table_make(pool, 12); + rp->err_headers_out = apr_table_make(pool, 5); + rp->notes = apr_table_make(pool, 5); + + rp->server = r->server; + rp->log = r->log; + rp->proxyreq = r->proxyreq; + rp->request_time = r->request_time; + rp->connection = c; + rp->output_filters = c->output_filters; + rp->input_filters = c->input_filters; + rp->proto_output_filters = c->output_filters; + rp->proto_input_filters = c->input_filters; + rp->useragent_ip = c->peer_ip; + rp->useragent_addr = c->peer_addr; + + rp->request_config = ap_create_request_config(pool); + proxy_run_create_req(r, rp); + + return rp; } static void process_proxy_header(request_rec *r, proxy_dir_conf *c, @@ -1128,7 +1324,7 @@ static void process_proxy_header(request_rec *r, proxy_dir_conf *c, for (i = 0; date_hdrs[i]; ++i) { if (!strcasecmp(date_hdrs[i], key)) { apr_table_add(r->headers_out, key, - ap_proxy_date_canon(r->pool, value)); + date_canon(r->pool, value)); return; } } @@ -1173,7 +1369,10 @@ static void ap_proxy_read_headers(request_rec *r, request_rec *rr, * Read header lines until we get the empty separator line, a read error, * the connection closes (EOF), or we timeout. */ + ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, + "Headers received from backend:"); while ((len = ap_getline(buffer, size, rr, 1)) > 0) { + ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, "%s", buffer); if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */ @@ -1201,23 +1400,24 @@ static void ap_proxy_read_headers(request_rec *r, request_rec *rr, * the first line of the response. */ if (saw_headers) { - ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server, - "proxy: Starting body due to bogus non-header in headers " - "returned by %s (%s)", r->uri, r->method); + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01098) + "Starting body due to bogus non-header " + "in headers returned by %s (%s)", + r->uri, r->method); *pread_len = len; return ; } else { - ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server, - "proxy: No HTTP headers " - "returned by %s (%s)", r->uri, r->method); + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01099) + "No HTTP headers returned by %s (%s)", + r->uri, r->method); return ; } } } /* this is the psc->badopt == bad_ignore case */ - ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server, - "proxy: Ignoring bogus HTTP header " - "returned by %s (%s)", r->uri, r->method); + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01100) + "Ignoring bogus HTTP header returned by %s (%s)", + r->uri, r->method); continue; } @@ -1274,7 +1474,7 @@ apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec if (rv == APR_SUCCESS) { *writen = (int) len; - } else if (rv == APR_ENOSPC) { + } else if (APR_STATUS_IS_ENOSPC(rv)) { *writen = n; } else { *writen = -1; @@ -1283,55 +1483,160 @@ apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec return rv; } +/* + * Limit the number of interim respones we sent back to the client. Otherwise + * we suffer from a memory build up. Besides there is NO sense in sending back + * an unlimited number of interim responses to the client. Thus if we cross + * this limit send back a 502 (Bad Gateway). + */ +#ifndef AP_MAX_INTERIM_RESPONSES +#define AP_MAX_INTERIM_RESPONSES 10 +#endif + static apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, - proxy_conn_rec *backend, - conn_rec *origin, + proxy_conn_rec **backend_ptr, + proxy_worker *worker, proxy_server_conf *conf, char *server_portstr) { conn_rec *c = r->connection; char buffer[HUGE_STRING_LEN]; const char *buf; char keepchar; - request_rec *rp; apr_bucket *e; apr_bucket_brigade *bb, *tmp_bb; + apr_bucket_brigade *pass_bb; int len, backasswards; - int interim_response; /* non-zero whilst interim 1xx responses - * are being read. */ + int interim_response = 0; /* non-zero whilst interim 1xx responses + * are being read. */ int pread_len = 0; apr_table_t *save_table; int backend_broke = 0; static const char *hop_by_hop_hdrs[] = {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL}; int i; + const char *te = NULL; + int original_status = r->status; + int proxy_status = OK; + const char *original_status_line = r->status_line; + const char *proxy_status_line = NULL; + proxy_conn_rec *backend = *backend_ptr; + conn_rec *origin = backend->connection; + apr_interval_time_t old_timeout = 0; + proxy_dir_conf *dconf; + int do_100_continue; + + dconf = ap_get_module_config(r->per_dir_config, &proxy_module); + + do_100_continue = (worker->s->ping_timeout_set + && ap_request_has_body(r) + && (PROXYREQ_REVERSE == r->proxyreq) + && !(apr_table_get(r->subprocess_env, "force-proxy-request-1.0"))); bb = apr_brigade_create(p, c->bucket_alloc); + pass_bb = apr_brigade_create(p, c->bucket_alloc); + + /* Setup for 100-Continue timeout if appropriate */ + if (do_100_continue) { + apr_socket_timeout_get(backend->sock, &old_timeout); + if (worker->s->ping_timeout != old_timeout) { + apr_status_t rc; + rc = apr_socket_timeout_set(backend->sock, worker->s->ping_timeout); + if (rc != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01101) + "could not set 100-Continue timeout"); + } + } + } /* Get response from the remote server, and pass it up the * filter chain */ - rp = ap_proxy_make_fake_req(origin, r); + backend->r = make_fake_req(origin, r); /* In case anyone needs to know, this is a fake request that is really a * response. */ - rp->proxyreq = PROXYREQ_RESPONSE; + backend->r->proxyreq = PROXYREQ_RESPONSE; + apr_table_setn(r->notes, "proxy-source-port", apr_psprintf(r->pool, "%hu", + origin->local_addr->port)); tmp_bb = apr_brigade_create(p, c->bucket_alloc); do { apr_status_t rc; apr_brigade_cleanup(bb); - rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len); + rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len); if (len == 0) { /* handle one potential stray CRLF */ - rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len); + rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len); } if (len <= 0) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, - "proxy: error reading status line from remote " - "server %s", backend->hostname); + ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01102) + "error reading status line from remote " + "server %s:%d", backend->hostname, backend->port); + if (APR_STATUS_IS_TIMEUP(rc)) { + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01103) "read timeout"); + if (do_100_continue) { + return ap_proxyerror(r, HTTP_SERVICE_UNAVAILABLE, "Timeout on 100-Continue"); + } + } + /* + * If we are a reverse proxy request shutdown the connection + * WITHOUT ANY response to trigger a retry by the client + * if allowed (as for idempotent requests). + * BUT currently we should not do this if the request is the + * first request on a keepalive connection as browsers like + * seamonkey only display an empty page in this case and do + * not do a retry. We should also not do this on a + * connection which times out; instead handle as + * we normally would handle timeouts + */ + if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives && + !APR_STATUS_IS_TIMEUP(rc)) { + apr_bucket *eos; + + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01104) + "Closing connection to client because" + " reading from backend server %s:%d failed." + " Number of keepalives %i", backend->hostname, + backend->port, c->keepalives); + ap_proxy_backend_broke(r, bb); + /* + * Add an EOC bucket to signal the ap_http_header_filter + * that it should get out of our way, BUT ensure that the + * EOC bucket is inserted BEFORE an EOS bucket in bb as + * some resource filters like mod_deflate pass everything + * up to the EOS down the chain immediately and sent the + * remainder of the brigade later (or even never). But in + * this case the ap_http_header_filter does not get out of + * our way soon enough. + */ + e = ap_bucket_eoc_create(c->bucket_alloc); + eos = APR_BRIGADE_LAST(bb); + while ((APR_BRIGADE_SENTINEL(bb) != eos) + && !APR_BUCKET_IS_EOS(eos)) { + eos = APR_BUCKET_PREV(eos); + } + if (eos == APR_BRIGADE_SENTINEL(bb)) { + APR_BRIGADE_INSERT_TAIL(bb, e); + } + else { + APR_BUCKET_INSERT_BEFORE(eos, e); + } + ap_pass_brigade(r->output_filters, bb); + /* Mark the backend connection for closing */ + backend->close = 1; + /* Need to return OK to avoid sending an error message */ + return OK; + } + else if (!c->keepalives) { + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01105) + "NOT Closing connection to client" + " although reading from backend server %s:%d" + " failed.", + backend->hostname, backend->port); + } return ap_proxyerror(r, HTTP_BAD_GATEWAY, "Error reading from remote server"); } @@ -1344,14 +1649,13 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) { int major, minor; - if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) { - major = 1; - minor = 1; - } + major = buffer[5] - '0'; + minor = buffer[7] - '0'; + /* If not an HTTP/1 message or * if the status line was > 8192 bytes */ - else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) { + if ((major != 1) || (len >= sizeof(buffer)-1)) { return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p, "Corrupt status line returned by remote " "server: ", buffer, NULL)); @@ -1360,7 +1664,9 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, keepchar = buffer[12]; buffer[12] = '\0'; - r->status = atoi(&buffer[9]); + proxy_status = atoi(&buffer[9]); + apr_table_setn(r->notes, "proxy-status", + apr_pstrdup(r->pool, &buffer[9])); if (keepchar != '\0') { buffer[12] = keepchar; @@ -1371,8 +1677,16 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, buffer[12] = ' '; buffer[13] = '\0'; } - r->status_line = apr_pstrdup(p, &buffer[9]); + proxy_status_line = apr_pstrdup(p, &buffer[9]); + /* The status out of the front is the same as the status coming in + * from the back, until further notice. + */ + r->status = proxy_status; + r->status_line = proxy_status_line; + + ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, + "Status from backend: %d", proxy_status); /* read the headers. */ /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/ @@ -1384,14 +1698,13 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, "Set-Cookie", NULL); /* shove the headers direct into r->headers_out */ - ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin, + ap_proxy_read_headers(r, backend->r, buffer, sizeof(buffer), origin, &pread_len); if (r->headers_out == NULL) { - ap_log_error(APLOG_MARK, APLOG_WARNING, 0, - r->server, "proxy: bad HTTP/%d.%d header " - "returned by %s (%s)", major, minor, r->uri, - r->method); + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01106) + "bad HTTP/%d.%d header returned by %s (%s)", + major, minor, r->uri, r->method); backend->close += 1; /* * ap_send_error relies on a headers_out to be present. we @@ -1429,21 +1742,28 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, * XXX: We aught to treat such a response as uncachable */ apr_table_unset(r->headers_out, "Content-Length"); - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: server %s returned Transfer-Encoding" - " and Content-Length", backend->hostname); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01107) + "server %s:%d returned Transfer-Encoding" + " and Content-Length", + backend->hostname, backend->port); backend->close += 1; } + /* + * Save a possible Transfer-Encoding header as we need it later for + * ap_http_filter to know where to end. + */ + te = apr_table_get(r->headers_out, "Transfer-Encoding"); /* strip connection listed hop-by-hop headers from response */ - backend->close += ap_proxy_liststr(apr_table_get(r->headers_out, - "Connection"), - "close"); + backend->close += ap_find_token(p, + apr_table_get(r->headers_out, "Connection"), "close"); ap_proxy_clear_connection(p, r->headers_out); if ((buf = apr_table_get(r->headers_out, "Content-Type"))) { ap_set_content_type(r, apr_pstrdup(p, buf)); } - ap_proxy_pre_http_request(origin,rp); + if (!ap_is_HTTP_INFO(proxy_status)) { + ap_proxy_pre_http_request(origin, backend->r); + } /* Clear hop-by-hop headers */ for (i=0; hop_by_hop_hdrs[i]; ++i) { @@ -1492,24 +1812,59 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, backend->close += 1; } - interim_response = ap_is_HTTP_INFO(r->status); + if (ap_is_HTTP_INFO(proxy_status)) { + interim_response++; + /* Reset to old timeout iff we've adjusted it */ + if (do_100_continue + && (r->status == HTTP_CONTINUE) + && (worker->s->ping_timeout != old_timeout)) { + apr_socket_timeout_set(backend->sock, old_timeout); + } + } + else { + interim_response = 0; + } if (interim_response) { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL, - "proxy: HTTP: received interim %d response", - r->status); + /* RFC2616 tells us to forward this. + * + * OTOH, an interim response here may mean the backend + * is playing sillybuggers. The Client didn't ask for + * it within the defined HTTP/1.1 mechanisms, and if + * it's an extension, it may also be unsupported by us. + * + * There's also the possibility that changing existing + * behaviour here might break something. + * + * So let's make it configurable. + */ + const char *policy = apr_table_get(r->subprocess_env, + "proxy-interim-response"); + ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, + "HTTP: received interim %d response", r->status); + if (!policy || !strcasecmp(policy, "RFC")) { + ap_send_interim_response(r, 1); + } + /* FIXME: refine this to be able to specify per-response-status + * policies and maybe also add option to bail out with 502 + */ + else if (strcasecmp(policy, "Suppress")) { + ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01108) + "undefined proxy interim response policy"); + } } /* Moved the fixups of Date headers and those affected by * ProxyPassReverse/etc from here to ap_proxy_read_headers */ - if ((r->status == 401) && (conf->error_override)) { + if ((proxy_status == 401) && (dconf->error_override)) { const char *buf; const char *wa = "WWW-Authenticate"; if ((buf = apr_table_get(r->headers_out, wa))) { apr_table_set(r->err_headers_out, wa, buf); } else { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: origin server sent 401 without WWW-Authenticate header"); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01109) + "origin server sent 401 without " + "WWW-Authenticate header"); } } @@ -1538,39 +1893,72 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(bb, e); } + /* PR 41646: get HEAD right with ProxyErrorOverride */ + if (ap_is_HTTP_ERROR(r->status) && dconf->error_override) { + /* clear r->status for override error, otherwise ErrorDocument + * thinks that this is a recursive error, and doesn't find the + * custom error page + */ + r->status = HTTP_OK; + /* Discard body, if one is expected */ + if (!r->header_only && /* not HEAD request */ + (proxy_status != HTTP_NO_CONTENT) && /* not 204 */ + (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */ + ap_discard_request_body(backend->r); + } + return proxy_status; + } /* send body - but only if a body is expected */ if ((!r->header_only) && /* not HEAD request */ !interim_response && /* not any 1xx response */ - (r->status != HTTP_NO_CONTENT) && /* not 204 */ - (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */ + (proxy_status != HTTP_NO_CONTENT) && /* not 204 */ + (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */ /* We need to copy the output headers and treat them as input * headers as well. BUT, we need to do this before we remove * TE, so that they are preserved accordingly for * ap_http_filter to know where to end. */ - rp->headers_in = apr_table_copy(r->pool, r->headers_out); + backend->r->headers_in = apr_table_clone(backend->r->pool, r->headers_out); + /* + * Restore Transfer-Encoding header from response if we saved + * one before and there is none left. We need it for the + * ap_http_filter. See above. + */ + if (te && !apr_table_get(backend->r->headers_in, "Transfer-Encoding")) { + apr_table_add(backend->r->headers_in, "Transfer-Encoding", te); + } apr_table_unset(r->headers_out,"Transfer-Encoding"); - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: start body send"); + ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "start body send"); /* * if we are overriding the errors, we can't put the content * of the page into the brigade */ - if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) { + if (!dconf->error_override || !ap_is_HTTP_ERROR(proxy_status)) { /* read the body, pass it to the output filters */ apr_read_type_e mode = APR_NONBLOCK_READ; int finish = FALSE; + /* Handle the case where the error document is itself reverse + * proxied and was successful. We must maintain any previous + * error status so that an underlying error (eg HTTP_NOT_FOUND) + * doesn't become an HTTP_OK. + */ + if (dconf->error_override && !ap_is_HTTP_ERROR(proxy_status) + && ap_is_HTTP_ERROR(original_status)) { + r->status = original_status; + r->status_line = original_status_line; + } + do { apr_off_t readbytes; apr_status_t rv; - rv = ap_get_brigade(rp->input_filters, bb, + rv = ap_get_brigade(backend->r->input_filters, bb, AP_MODE_READBYTES, mode, conf->io_buffer_size); @@ -1598,8 +1986,8 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, * our backend bailed on us. Pass along a 502 error * error bucket */ - ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c, - "proxy: error reading response"); + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01110) + "error reading response"); ap_proxy_backend_broke(r, bb); ap_pass_brigade(r->output_filters, bb); backend_broke = 1; @@ -1613,9 +2001,8 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, backend->worker->s->read += readbytes; #if DEBUGGING { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, - r->server, "proxy (PID %d): readbytes: %#x", - getpid(), readbytes); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01111) + "readbytes: %#x", readbytes); } #endif /* sanity check */ @@ -1624,71 +2011,102 @@ apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r, break; } + /* Switch the allocator lifetime of the buckets */ + proxy_buckets_lifetime_transform(r, bb, pass_bb); + /* found the last brigade? */ - if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) { + if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(pass_bb))) { + /* signal that we must leave */ finish = TRUE; + + /* the brigade may contain transient buckets that contain + * data that lives only as long as the backend connection. + * Force a setaside so these transient buckets become heap + * buckets that live as long as the request. + */ + for (e = APR_BRIGADE_FIRST(pass_bb); e + != APR_BRIGADE_SENTINEL(pass_bb); e + = APR_BUCKET_NEXT(e)) { + apr_bucket_setaside(e, r->pool); + } + + /* finally it is safe to clean up the brigade from the + * connection pool, as we have forced a setaside on all + * buckets. + */ + apr_brigade_cleanup(bb); + + /* make sure we release the backend connection as soon + * as we know we are done, so that the backend isn't + * left waiting for a slow client to eventually + * acknowledge the data. + */ + ap_proxy_release_connection(backend->worker->s->scheme, + backend, r->server); + /* Ensure that the backend is not reused */ + *backend_ptr = NULL; + } /* try send what we read */ - if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS + if (ap_pass_brigade(r->output_filters, pass_bb) != APR_SUCCESS || c->aborted) { /* Ack! Phbtt! Die! User aborted! */ - backend->close = 1; /* this causes socket close below */ + /* Only close backend if we haven't got all from the + * backend. Furthermore if *backend_ptr is NULL it is no + * longer safe to fiddle around with backend as it might + * be already in use by another thread. + */ + if (*backend_ptr) { + backend->close = 1; /* this causes socket close below */ + } finish = TRUE; } /* make sure we always clean up after ourselves */ + apr_brigade_cleanup(pass_bb); apr_brigade_cleanup(bb); } while (!finish); } - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: end body send"); + ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "end body send"); } else if (!interim_response) { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: header only"); + ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "header only"); + + /* make sure we release the backend connection as soon + * as we know we are done, so that the backend isn't + * left waiting for a slow client to eventually + * acknowledge the data. + */ + ap_proxy_release_connection(backend->worker->s->scheme, + backend, r->server); + *backend_ptr = NULL; /* Pass EOS bucket down the filter chain. */ e = apr_bucket_eos_create(c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(bb, e); - if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS - || c->aborted) { - /* Ack! Phbtt! Die! User aborted! */ - backend->close = 1; /* this causes socket close below */ - } + ap_pass_brigade(r->output_filters, bb); apr_brigade_cleanup(bb); } - } while (interim_response); + } while (interim_response && (interim_response < AP_MAX_INTERIM_RESPONSES)); + + /* See define of AP_MAX_INTERIM_RESPONSES for why */ + if (interim_response >= AP_MAX_INTERIM_RESPONSES) { + return ap_proxyerror(r, HTTP_BAD_GATEWAY, + apr_psprintf(p, + "Too many (%d) interim responses from origin server", + interim_response)); + } /* If our connection with the client is to be aborted, return DONE. */ if (c->aborted || backend_broke) { return DONE; } - if (conf->error_override) { - /* the code above this checks for 'OK' which is what the hook expects */ - if (!ap_is_HTTP_ERROR(r->status)) - return OK; - else { - /* clear r->status for override error, otherwise ErrorDocument - * thinks that this is a recursive error, and doesn't find the - * custom error page - */ - int status = r->status; - r->status = HTTP_OK; - /* Discard body, if one is expected */ - if (!r->header_only && /* not HEAD request */ - (status != HTTP_NO_CONTENT) && /* not 204 */ - (status != HTTP_NOT_MODIFIED)) { /* not 304 */ - ap_discard_request_body(rp); - } - return status; - } - } else - return OK; + return OK; } static @@ -1720,23 +2138,14 @@ static int proxy_http_handler(request_rec *r, proxy_worker *worker, const char *u; proxy_conn_rec *backend = NULL; int is_ssl = 0; - - /* Note: Memory pool allocation. - * A downstream keepalive connection is always connected to the existence - * (or not) of an upstream keepalive connection. If this is not done then - * load balancing against multiple backend servers breaks (one backend - * server ends up taking 100% of the load), and the risk is run of - * downstream keepalive connections being kept open unnecessarily. This - * keeps webservers busy and ties up resources. - * - * As a result, we allocate all sockets out of the upstream connection - * pool, and when we want to reuse a socket, we check first whether the - * connection ID of the current upstream connection is the same as that - * of the connection when the socket was opened. - */ - apr_pool_t *p = r->connection->pool; conn_rec *c = r->connection; - apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri)); + int retry = 0; + /* + * Use a shorter-lived pool to reduce memory usage + * and avoid a memory leak + */ + apr_pool_t *p = r->pool; + apr_uri_t *uri = apr_palloc(p, sizeof(*uri)); /* find the scheme */ u = strchr(url, ':'); @@ -1744,23 +2153,23 @@ static int proxy_http_handler(request_rec *r, proxy_worker *worker, return DECLINED; if ((u - url) > 14) return HTTP_BAD_REQUEST; - scheme = apr_pstrndup(c->pool, url, u - url); + scheme = apr_pstrndup(p, url, u - url); /* scheme is lowercase */ ap_str_tolower(scheme); /* is it for us? */ if (strcmp(scheme, "https") == 0) { if (!ap_proxy_ssl_enable(NULL)) { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: HTTPS: declining URL %s" - " (mod_ssl not configured?)", url); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01112) + "HTTPS: declining URL %s (mod_ssl not configured?)", + url); return DECLINED; } is_ssl = 1; proxy_function = "HTTPS"; } else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) { - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: HTTP: declining URL %s", url); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01113) "HTTP: declining URL %s", + url); return DECLINED; /* only interested in HTTP, or FTP via proxy */ } else { @@ -1769,8 +2178,7 @@ static int proxy_http_handler(request_rec *r, proxy_worker *worker, else proxy_function = "FTP"; } - ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, - "proxy: HTTP: serving URL %s", url); + ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "HTTP: serving URL %s", url); /* create space for state information */ @@ -1780,51 +2188,86 @@ static int proxy_http_handler(request_rec *r, proxy_worker *worker, backend->is_ssl = is_ssl; + + if (is_ssl) { + ap_proxy_ssl_connection_cleanup(backend, r); + } + /* - * TODO: Currently we cannot handle persistent SSL backend connections, - * because we recreate backend->connection for each request and thus - * try to initialize an already existing SSL connection. This does - * not work. + * In the case that we are handling a reverse proxy connection and this + * is not a request that is coming over an already kept alive connection + * with the client, do NOT reuse the connection to the backend, because + * we cannot forward a failure to the client in this case as the client + * does NOT expect this in this situation. + * Yes, this creates a performance penalty. */ - if (is_ssl) + if ((r->proxyreq == PROXYREQ_REVERSE) && (!c->keepalives) + && (apr_table_get(r->subprocess_env, "proxy-initial-not-pooled"))) { backend->close = 1; + } + + while (retry < 2) { + char *locurl = url; - /* Step One: Determine Who To Connect To */ - if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend, - uri, &url, proxyname, + /* Step One: Determine Who To Connect To */ + if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend, + uri, &locurl, proxyname, proxyport, server_portstr, sizeof(server_portstr))) != OK) - goto cleanup; + break; - /* Step Two: Make the Connection */ - if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) { - if (r->proxyreq == PROXYREQ_PROXY) - status = HTTP_NOT_FOUND; - else + /* Step Two: Make the Connection */ + if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01114) + "HTTP: failed to make connection to backend: %s", + backend->hostname); status = HTTP_SERVICE_UNAVAILABLE; - goto cleanup; - } + break; + } - /* Step Three: Create conn_rec */ - if (!backend->connection) { - if ((status = ap_proxy_connection_create(proxy_function, backend, - c, r->server)) != OK) - goto cleanup; - } + /* Step Three: Create conn_rec */ + if (!backend->connection) { + if ((status = ap_proxy_connection_create(proxy_function, backend, + c, r->server)) != OK) + break; + /* + * On SSL connections set a note on the connection what CN is + * requested, such that mod_ssl can check if it is requested to do + * so. + */ + if (is_ssl) { + apr_table_set(backend->connection->notes, "proxy-request-hostname", + uri->hostname); + } + } - /* Step Four: Send the Request */ - if ((status = ap_proxy_http_request(p, r, backend, backend->connection, - conf, uri, url, server_portstr)) != OK) - goto cleanup; + /* Step Four: Send the Request + * On the off-chance that we forced a 100-Continue as a + * kinda HTTP ping test, allow for retries + */ + if ((status = ap_proxy_http_request(p, r, backend, worker, + conf, uri, locurl, server_portstr)) != OK) { + if ((status == HTTP_SERVICE_UNAVAILABLE) && worker->s->ping_timeout_set) { + backend->close = 1; + ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r, APLOGNO(01115) + "HTTP: 100-Continue failed to %pI (%s)", + worker->cp->addr, worker->s->hostname); + retry++; + continue; + } else { + break; + } - /* Step Five: Receive the Response */ - if ((status = ap_proxy_http_process_response(p, r, backend, - backend->connection, - conf, server_portstr)) != OK) - goto cleanup; + } - /* Step Six: Clean Up */ + /* Step Five: Receive the Response... Fall thru to cleanup */ + status = ap_proxy_http_process_response(p, r, &backend, worker, + conf, server_portstr); + break; + } + + /* Step Six: Clean Up */ cleanup: if (backend) { if (status != OK) @@ -1833,20 +2276,14 @@ cleanup: } return status; } -static apr_status_t warn_rx_free(void *p) -{ - ap_pregfree((apr_pool_t*)p, warn_rx); - return APR_SUCCESS; -} static void ap_proxy_http_register_hook(apr_pool_t *p) { proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST); proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST); warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0); - apr_pool_cleanup_register(p, p, warn_rx_free, NULL); } -module AP_MODULE_DECLARE_DATA proxy_http_module = { +AP_DECLARE_MODULE(proxy_http) = { STANDARD20_MODULE_STUFF, NULL, /* create per-directory config structure */ NULL, /* merge per-directory config structures */