1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* HTTP routines for Apache proxy */
19 #include "mod_proxy.h"
22 module AP_MODULE_DECLARE_DATA proxy_http_module;
24 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
26 proxy_conn_rec *backend);
29 * Canonicalise http-like URLs.
30 * scheme is the scheme for the URL
31 * url is the URL starting with the first '/'
32 * def_port is the default port for this scheme.
34 static int proxy_http_canon(request_rec *r, char *url)
36 char *host, *path, *search, sport[7];
39 apr_port_t port, def_port;
41 /* ap_port_of_scheme() */
42 if (strncasecmp(url, "http:", 5) == 0) {
46 else if (strncasecmp(url, "https:", 6) == 0) {
53 def_port = apr_uri_port_of_scheme(scheme);
55 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
56 "proxy: HTTP: canonicalising URL %s", url);
59 * We break the URL into host, port, path, search
62 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
64 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
65 "error parsing URL %s: %s",
67 return HTTP_BAD_REQUEST;
70 /* now parse path/search args, according to rfc1738 */
71 /* N.B. if this isn't a true proxy request, then the URL _path_
72 * has already been decoded. True proxy requests have r->uri
73 * == r->unparsed_uri, and no others have that property.
75 if (r->uri == r->unparsed_uri) {
76 search = strchr(url, '?');
84 /* In a reverse proxy, our URL has been processed, so canonicalise
85 * unless proxy-nocanon is set to say it's raw
86 * In a forward proxy, we have and MUST NOT MANGLE the original.
88 switch (r->proxyreq) {
89 default: /* wtf are we doing here? */
90 case PROXYREQ_REVERSE:
91 if (apr_table_get(r->notes, "proxy-nocanon")) {
92 path = url; /* this is the raw path */
95 path = ap_proxy_canonenc(r->pool, url, strlen(url),
96 enc_path, 0, r->proxyreq);
105 return HTTP_BAD_REQUEST;
107 if (port != def_port)
108 apr_snprintf(sport, sizeof(sport), ":%d", port);
112 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
113 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
115 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
116 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
120 /* Clear all connection-based headers from the incoming headers table */
121 typedef struct header_dptr {
126 static ap_regex_t *warn_rx;
127 static int clean_warning_headers(void *data, const char *key, const char *val)
129 apr_table_t *headers = ((header_dptr*)data)->table;
130 apr_pool_t *pool = ((header_dptr*)data)->pool;
133 apr_time_t warn_time;
134 const int nmatch = 3;
135 ap_regmatch_t pmatch[3];
137 if (headers == NULL) {
138 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
141 * Parse this, suckers!
143 * Warning = "Warning" ":" 1#warning-value
145 * warning-value = warn-code SP warn-agent SP warn-text
149 * warn-agent = ( host [ ":" port ] ) | pseudonym
150 * ; the name or pseudonym of the server adding
151 * ; the Warning header, for use in debugging
152 * warn-text = quoted-string
153 * warn-date = <"> HTTP-date <">
155 * Buggrit, use a bloomin' regexp!
156 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
158 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
159 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
160 pmatch[0].rm_eo - pmatch[0].rm_so);
162 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
163 /* OK, we have a date here */
164 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
165 pmatch[2].rm_eo - pmatch[2].rm_so);
166 warn_time = apr_date_parse_http(date);
168 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
169 apr_table_addn(headers, key, warning);
171 val += pmatch[0].rm_eo;
175 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
180 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
181 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
182 if (x.table != NULL) {
183 apr_table_unset(headers, "Warning");
184 return apr_table_overlay(p, headers, x.table);
190 static int clear_conn_headers(void *data, const char *key, const char *val)
192 apr_table_t *headers = ((header_dptr*)data)->table;
193 apr_pool_t *pool = ((header_dptr*)data)->pool;
195 char *next = apr_pstrdup(pool, val);
198 while (*next && !apr_isspace(*next) && (*next != ',')) {
201 while (*next && (apr_isspace(*next) || (*next == ','))) {
204 apr_table_unset(headers, name);
208 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
213 apr_table_unset(headers, "Proxy-Connection");
214 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
215 apr_table_unset(headers, "Connection");
217 static void add_te_chunked(apr_pool_t *p,
218 apr_bucket_alloc_t *bucket_alloc,
219 apr_bucket_brigade *header_brigade)
223 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
225 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
226 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
228 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
229 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
232 static void add_cl(apr_pool_t *p,
233 apr_bucket_alloc_t *bucket_alloc,
234 apr_bucket_brigade *header_brigade,
240 buf = apr_pstrcat(p, "Content-Length: ",
244 ap_xlate_proto_to_ascii(buf, strlen(buf));
245 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
246 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
249 #define ASCII_CRLF "\015\012"
250 #define ASCII_ZERO "\060"
252 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
253 apr_bucket_brigade *header_brigade)
257 /* add empty line at the end of the headers */
258 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
259 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
262 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
263 request_rec *r, proxy_conn_rec *conn,
264 conn_rec *origin, apr_bucket_brigade *bb,
268 apr_off_t transferred;
271 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
272 APR_BRIGADE_INSERT_TAIL(bb, e);
274 apr_brigade_length(bb, 0, &transferred);
275 if (transferred != -1)
276 conn->worker->s->transferred += transferred;
277 status = ap_pass_brigade(origin->output_filters, bb);
278 if (status != APR_SUCCESS) {
279 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
280 "proxy: pass request body failed to %pI (%s)",
281 conn->addr, conn->hostname);
284 apr_brigade_cleanup(bb);
288 #define MAX_MEM_SPOOL 16384
290 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
292 proxy_conn_rec *p_conn,
294 apr_bucket_brigade *header_brigade,
295 apr_bucket_brigade *input_brigade)
301 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
302 apr_bucket_brigade *bb;
305 add_te_chunked(p, bucket_alloc, header_brigade);
306 terminate_headers(bucket_alloc, header_brigade);
308 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
310 char chunk_hdr[20]; /* must be here due to transient bucket. */
312 /* If this brigade contains EOS, either stop or remove it. */
313 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
316 /* We can't pass this EOS to the output_filters. */
317 e = APR_BRIGADE_LAST(input_brigade);
318 apr_bucket_delete(e);
321 apr_brigade_length(input_brigade, 1, &bytes);
323 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
324 "%" APR_UINT64_T_HEX_FMT CRLF,
325 (apr_uint64_t)bytes);
327 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
328 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
330 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
333 * Append the end-of-chunk CRLF
335 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
336 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
338 if (header_brigade) {
339 /* we never sent the header brigade, so go ahead and
340 * take care of that now
345 * Save input_brigade in bb brigade. (At least) in the SSL case
346 * input_brigade contains transient buckets whose data would get
347 * overwritten during the next call of ap_get_brigade in the loop.
348 * ap_save_brigade ensures these buckets to be set aside.
349 * Calling ap_save_brigade with NULL as filter is OK, because
350 * bb brigade already has been created and does not need to get
351 * created by ap_save_brigade.
353 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
354 if (status != APR_SUCCESS) {
358 header_brigade = NULL;
364 /* The request is flushed below this loop with chunk EOS header */
365 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
366 if (status != APR_SUCCESS) {
374 status = ap_get_brigade(r->input_filters, input_brigade,
375 AP_MODE_READBYTES, APR_BLOCK_READ,
378 if (status != APR_SUCCESS) {
383 if (header_brigade) {
384 /* we never sent the header brigade because there was no request body;
390 if (!APR_BRIGADE_EMPTY(input_brigade)) {
391 /* input brigade still has an EOS which we can't pass to the output_filters. */
392 e = APR_BRIGADE_LAST(input_brigade);
393 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
394 apr_bucket_delete(e);
399 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
403 APR_BRIGADE_INSERT_TAIL(bb, e);
405 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
406 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
407 APR_BRIGADE_INSERT_TAIL(bb, e);
410 /* Now we have headers-only, or the chunk EOS mark; flush it */
411 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
415 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
417 proxy_conn_rec *p_conn,
419 apr_bucket_brigade *header_brigade,
420 apr_bucket_brigade *input_brigade,
421 const char *old_cl_val)
424 apr_status_t status = APR_SUCCESS;
425 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
426 apr_bucket_brigade *bb;
428 apr_off_t cl_val = 0;
430 apr_off_t bytes_streamed = 0;
433 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
434 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
439 terminate_headers(bucket_alloc, header_brigade);
441 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
443 apr_brigade_length(input_brigade, 1, &bytes);
444 bytes_streamed += bytes;
446 /* If this brigade contains EOS, either stop or remove it. */
447 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
450 /* We can't pass this EOS to the output_filters. */
451 e = APR_BRIGADE_LAST(input_brigade);
452 apr_bucket_delete(e);
454 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
455 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
456 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
460 /* C-L < bytes streamed?!?
461 * We will error out after the body is completely
462 * consumed, but we can't stream more bytes at the
463 * back end since they would in part be interpreted
464 * as another request! If nothing is sent, then
467 * Prevents HTTP Response Splitting.
469 if (bytes_streamed > cl_val)
472 if (header_brigade) {
473 /* we never sent the header brigade, so go ahead and
474 * take care of that now
479 * Save input_brigade in bb brigade. (At least) in the SSL case
480 * input_brigade contains transient buckets whose data would get
481 * overwritten during the next call of ap_get_brigade in the loop.
482 * ap_save_brigade ensures these buckets to be set aside.
483 * Calling ap_save_brigade with NULL as filter is OK, because
484 * bb brigade already has been created and does not need to get
485 * created by ap_save_brigade.
487 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
488 if (status != APR_SUCCESS) {
492 header_brigade = NULL;
498 /* Once we hit EOS, we are ready to flush. */
499 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
500 if (status != APR_SUCCESS) {
508 status = ap_get_brigade(r->input_filters, input_brigade,
509 AP_MODE_READBYTES, APR_BLOCK_READ,
512 if (status != APR_SUCCESS) {
517 if (bytes_streamed != cl_val) {
518 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
519 "proxy: client %s given Content-Length did not match"
520 " number of body bytes read", r->connection->remote_ip);
524 if (header_brigade) {
525 /* we never sent the header brigade since there was no request
526 * body; send it now with the flush flag
529 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
534 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
536 proxy_conn_rec *p_conn,
538 apr_bucket_brigade *header_brigade,
539 apr_bucket_brigade *input_brigade,
544 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
545 apr_bucket_brigade *body_brigade;
547 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
548 apr_file_t *tmpfile = NULL;
550 body_brigade = apr_brigade_create(p, bucket_alloc);
552 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
554 /* If this brigade contains EOS, either stop or remove it. */
555 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
558 /* We can't pass this EOS to the output_filters. */
559 e = APR_BRIGADE_LAST(input_brigade);
560 apr_bucket_delete(e);
563 apr_brigade_length(input_brigade, 1, &bytes);
565 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
566 /* can't spool any more in memory; write latest brigade to disk */
567 if (tmpfile == NULL) {
568 const char *temp_dir;
571 status = apr_temp_dir_get(&temp_dir, p);
572 if (status != APR_SUCCESS) {
573 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
574 "proxy: search for temporary directory failed");
577 apr_filepath_merge(&template, temp_dir,
578 "modproxy.tmp.XXXXXX",
579 APR_FILEPATH_NATIVE, p);
580 status = apr_file_mktemp(&tmpfile, template, 0, p);
581 if (status != APR_SUCCESS) {
582 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
583 "proxy: creation of temporary file in directory %s failed",
588 for (e = APR_BRIGADE_FIRST(input_brigade);
589 e != APR_BRIGADE_SENTINEL(input_brigade);
590 e = APR_BUCKET_NEXT(e)) {
592 apr_size_t bytes_read, bytes_written;
594 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
595 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
596 if (status != APR_SUCCESS) {
597 const char *tmpfile_name;
599 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
600 tmpfile_name = "(unknown)";
602 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
603 "proxy: write to temporary file %s failed",
607 AP_DEBUG_ASSERT(bytes_read == bytes_written);
608 fsize += bytes_written;
610 apr_brigade_cleanup(input_brigade);
615 * Save input_brigade in body_brigade. (At least) in the SSL case
616 * input_brigade contains transient buckets whose data would get
617 * overwritten during the next call of ap_get_brigade in the loop.
618 * ap_save_brigade ensures these buckets to be set aside.
619 * Calling ap_save_brigade with NULL as filter is OK, because
620 * body_brigade already has been created and does not need to get
621 * created by ap_save_brigade.
623 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
624 if (status != APR_SUCCESS) {
630 bytes_spooled += bytes;
636 status = ap_get_brigade(r->input_filters, input_brigade,
637 AP_MODE_READBYTES, APR_BLOCK_READ,
640 if (status != APR_SUCCESS) {
645 if (bytes_spooled || force_cl) {
646 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
648 terminate_headers(bucket_alloc, header_brigade);
649 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
651 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
653 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
654 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
655 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
657 /* This is all a single brigade, pass with flush flagged */
658 status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
663 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
664 proxy_conn_rec *p_conn, conn_rec *origin,
665 proxy_server_conf *conf,
667 char *url, char *server_portstr)
669 conn_rec *c = r->connection;
670 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
671 apr_bucket_brigade *header_brigade;
672 apr_bucket_brigade *input_brigade;
673 apr_bucket_brigade *temp_brigade;
676 const apr_array_header_t *headers_in_array;
677 const apr_table_entry_t *headers_in;
680 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
681 enum rb_methods rb_method = RB_INIT;
682 const char *old_cl_val = NULL;
683 const char *old_te_val = NULL;
684 apr_off_t bytes_read = 0;
687 apr_table_t *headers_in_copy;
689 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
692 * Send the HTTP/1.1 request to the remote server
695 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
696 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
700 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
703 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
704 origin->keepalive = AP_CONN_CLOSE;
707 ap_xlate_proto_to_ascii(buf, strlen(buf));
708 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
709 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
710 if (conf->preserve_host == 0) {
711 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
712 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
715 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
719 /* don't want to use r->hostname, as the incoming header might have a
722 const char* hostname = apr_table_get(r->headers_in,"Host");
724 hostname = r->server->server_hostname;
725 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
726 "proxy: no HTTP 0.9 request (with no host line) "
727 "on incoming request and preserve host set "
728 "forcing hostname to be %s for uri %s",
732 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
734 ap_xlate_proto_to_ascii(buf, strlen(buf));
735 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
736 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
739 if (conf->viaopt == via_block) {
740 /* Block all outgoing Via: headers */
741 apr_table_unset(r->headers_in, "Via");
742 } else if (conf->viaopt != via_off) {
743 const char *server_name = ap_get_server_name(r);
744 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
745 * then the server name returned by ap_get_server_name() is the
746 * origin server name (which does make too much sense with Via: headers)
747 * so we use the proxy vhost's name instead.
749 if (server_name == r->hostname)
750 server_name = r->server->server_hostname;
751 /* Create a "Via:" request header entry and merge it */
752 /* Generate outgoing Via: header with/without server comment: */
753 apr_table_mergen(r->headers_in, "Via",
754 (conf->viaopt == via_full)
755 ? apr_psprintf(p, "%d.%d %s%s (%s)",
756 HTTP_VERSION_MAJOR(r->proto_num),
757 HTTP_VERSION_MINOR(r->proto_num),
758 server_name, server_portstr,
759 AP_SERVER_BASEVERSION)
760 : apr_psprintf(p, "%d.%d %s%s",
761 HTTP_VERSION_MAJOR(r->proto_num),
762 HTTP_VERSION_MINOR(r->proto_num),
763 server_name, server_portstr)
767 /* X-Forwarded-*: handling
772 * These request headers are only really useful when the mod_proxy
773 * is used in a reverse proxy configuration, so that useful info
774 * about the client can be passed through the reverse proxy and on
775 * to the backend server, which may require the information to
778 * In a forward proxy situation, these options are a potential
779 * privacy violation, as information about clients behind the proxy
780 * are revealed to arbitrary servers out there on the internet.
782 * The HTTP/1.1 Via: header is designed for passing client
783 * information through proxies to a server, and should be used in
784 * a forward proxy configuation instead of X-Forwarded-*. See the
785 * ProxyVia option for details.
788 if (PROXYREQ_REVERSE == r->proxyreq) {
791 /* Add X-Forwarded-For: so that the upstream has a chance to
792 * determine, where the original request came from.
794 apr_table_mergen(r->headers_in, "X-Forwarded-For",
797 /* Add X-Forwarded-Host: so that upstream knows what the
798 * original request hostname was.
800 if ((buf = apr_table_get(r->headers_in, "Host"))) {
801 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
804 /* Add X-Forwarded-Server: so that upstream knows what the
805 * name of this proxy server is (if there are more than one)
806 * XXX: This duplicates Via: - do we strictly need it?
808 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
809 r->server->server_hostname);
814 * Make a copy of the headers_in table before clearing the connection
815 * headers as we need the connection headers later in the http output
816 * filter to prepare the correct response headers.
818 * Note: We need to take r->pool for apr_table_copy as the key / value
819 * pairs in r->headers_in have been created out of r->pool and
820 * p might be (and actually is) a longer living pool.
821 * This would trigger the bad pool ancestry abort in apr_table_copy if
822 * apr is compiled with APR_POOL_DEBUG.
824 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
825 ap_proxy_clear_connection(p, headers_in_copy);
826 /* send request headers */
827 headers_in_array = apr_table_elts(headers_in_copy);
828 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
829 for (counter = 0; counter < headers_in_array->nelts; counter++) {
830 if (headers_in[counter].key == NULL
831 || headers_in[counter].val == NULL
834 || !strcasecmp(headers_in[counter].key, "Host")
836 /* Clear out hop-by-hop request headers not to send
837 * RFC2616 13.5.1 says we should strip these headers
839 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
840 || !strcasecmp(headers_in[counter].key, "TE")
841 || !strcasecmp(headers_in[counter].key, "Trailer")
842 || !strcasecmp(headers_in[counter].key, "Upgrade")
847 /* Do we want to strip Proxy-Authorization ?
848 * If we haven't used it, then NO
849 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
850 * So let's make it configurable by env.
852 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
853 if (r->user != NULL) { /* we've authenticated */
854 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
861 /* Skip Transfer-Encoding and Content-Length for now.
863 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
864 old_te_val = headers_in[counter].val;
867 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
868 old_cl_val = headers_in[counter].val;
872 /* for sub-requests, ignore freshness/expiry headers */
874 if ( !strcasecmp(headers_in[counter].key, "If-Match")
875 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
876 || !strcasecmp(headers_in[counter].key, "If-Range")
877 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
878 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
883 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
884 headers_in[counter].val, CRLF,
886 ap_xlate_proto_to_ascii(buf, strlen(buf));
887 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
888 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
891 /* We have headers, let's figure out our request body... */
892 input_brigade = apr_brigade_create(p, bucket_alloc);
894 /* sub-requests never use keepalives, and mustn't pass request bodies.
895 * Because the new logic looks at input_brigade, we will self-terminate
896 * input_brigade and jump past all of the request body logic...
897 * Reading anything with ap_get_brigade is likely to consume the
898 * main request's body or read beyond EOS - which would be unplesant.
901 /* XXX: Why DON'T sub-requests use keepalives? */
905 apr_table_unset(r->headers_in, "Content-Length");
909 apr_table_unset(r->headers_in, "Transfer-Encoding");
911 rb_method = RB_STREAM_CL;
912 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
913 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
917 /* WE only understand chunked. Other modules might inject
918 * (and therefore, decode) other flavors but we don't know
919 * that the can and have done so unless they they remove
920 * their decoding from the headers_in T-E list.
921 * XXX: Make this extensible, but in doing so, presume the
922 * encoding has been done by the extensions' handler, and
923 * do not modify add_te_chunked's logic
925 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
926 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
927 "proxy: %s Transfer-Encoding is not supported",
932 if (old_cl_val && old_te_val) {
933 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
934 "proxy: client %s (%s) requested Transfer-Encoding "
935 "chunked body with Content-Length (C-L ignored)",
936 c->remote_ip, c->remote_host ? c->remote_host: "");
937 apr_table_unset(r->headers_in, "Content-Length");
939 origin->keepalive = AP_CONN_CLOSE;
943 /* Prefetch MAX_MEM_SPOOL bytes
945 * This helps us avoid any election of C-L v.s. T-E
946 * request bodies, since we are willing to keep in
947 * memory this much data, in any case. This gives
948 * us an instant C-L election if the body is of some
951 temp_brigade = apr_brigade_create(p, bucket_alloc);
953 status = ap_get_brigade(r->input_filters, temp_brigade,
954 AP_MODE_READBYTES, APR_BLOCK_READ,
955 MAX_MEM_SPOOL - bytes_read);
956 if (status != APR_SUCCESS) {
957 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
958 "proxy: prefetch request body failed to %pI (%s)"
960 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
961 c->remote_ip, c->remote_host ? c->remote_host: "");
965 apr_brigade_length(temp_brigade, 1, &bytes);
969 * Save temp_brigade in input_brigade. (At least) in the SSL case
970 * temp_brigade contains transient buckets whose data would get
971 * overwritten during the next call of ap_get_brigade in the loop.
972 * ap_save_brigade ensures these buckets to be set aside.
973 * Calling ap_save_brigade with NULL as filter is OK, because
974 * input_brigade already has been created and does not need to get
975 * created by ap_save_brigade.
977 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
978 if (status != APR_SUCCESS) {
979 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
980 "proxy: processing prefetched request body failed"
981 " to %pI (%s) from %s (%s)",
982 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
983 c->remote_ip, c->remote_host ? c->remote_host: "");
987 /* Ensure we don't hit a wall where we have a buffer too small
988 * for ap_get_brigade's filters to fetch us another bucket,
989 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
990 * (an arbitrary value.)
992 } while ((bytes_read < MAX_MEM_SPOOL - 80)
993 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
995 /* Use chunked request body encoding or send a content-length body?
999 * We have no request body (handled by RB_STREAM_CL)
1001 * We have a request body length <= MAX_MEM_SPOOL
1003 * The administrator has setenv force-proxy-request-1.0
1005 * The client sent a C-L body, and the administrator has
1006 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1008 * The client sent a T-E body, and the administrator has
1009 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1011 * If both proxy-sendcl and proxy-sendchunked are set, the
1012 * behavior is the same as if neither were set, large bodies
1013 * that can't be read will be forwarded in their original
1014 * form of C-L, or T-E.
1016 * To ensure maximum compatibility, setenv proxy-sendcl
1017 * To reduce server resource use, setenv proxy-sendchunked
1019 * Then address specific servers with conditional setenv
1020 * options to restore the default behavior where desireable.
1022 * We have to compute content length by reading the entire request
1023 * body; if request body is not small, we'll spool the remaining
1024 * input to a temporary file. Chunked is always preferable.
1026 * We can only trust the client-provided C-L if the T-E header
1027 * is absent, and the filters are unchanged (the body won't
1028 * be resized by another content filter).
1030 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1031 /* The whole thing fit, so our decision is trivial, use
1032 * the filtered bytes read from the client for the request
1033 * body Content-Length.
1035 * If we expected no body, and read no body, do not set
1036 * the Content-Length.
1038 if (old_cl_val || old_te_val || bytes_read) {
1039 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1041 rb_method = RB_STREAM_CL;
1043 else if (old_te_val) {
1045 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1046 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1047 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1048 rb_method = RB_SPOOL_CL;
1051 rb_method = RB_STREAM_CHUNKED;
1054 else if (old_cl_val) {
1055 if (r->input_filters == r->proto_input_filters) {
1056 rb_method = RB_STREAM_CL;
1059 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1060 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1061 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1062 rb_method = RB_STREAM_CHUNKED;
1065 rb_method = RB_SPOOL_CL;
1069 /* This is an appropriate default; very efficient for no-body
1070 * requests, and has the behavior that it will not add any C-L
1071 * when the old_cl_val is NULL.
1073 rb_method = RB_SPOOL_CL;
1076 /* Yes I hate gotos. This is the subrequest shortcut */
1079 * Handle Connection: header if we do HTTP/1.1 request:
1080 * If we plan to close the backend connection sent Connection: close
1081 * otherwise sent Connection: Keep-Alive.
1084 if (p_conn->close) {
1085 buf = apr_pstrdup(p, "Connection: close" CRLF);
1088 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1090 ap_xlate_proto_to_ascii(buf, strlen(buf));
1091 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1092 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1095 /* send the request body, if any. */
1097 case RB_STREAM_CHUNKED:
1098 status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1102 status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1103 input_brigade, old_cl_val);
1106 status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1107 input_brigade, (old_cl_val != NULL)
1108 || (old_te_val != NULL)
1109 || (bytes_read > 0));
1112 /* shouldn't be possible */
1113 status = APR_EINVAL;
1117 if (status != APR_SUCCESS) {
1118 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1119 "proxy: pass request body failed to %pI (%s)"
1122 p_conn->hostname ? p_conn->hostname: "",
1124 c->remote_host ? c->remote_host: "");
1131 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1132 const char *key, const char *value)
1134 static const char *date_hdrs[]
1135 = { "Date", "Expires", "Last-Modified", NULL };
1136 static const struct {
1138 ap_proxy_header_reverse_map_fn func;
1139 } transform_hdrs[] = {
1140 { "Location", ap_proxy_location_reverse_map },
1141 { "Content-Location", ap_proxy_location_reverse_map },
1142 { "URI", ap_proxy_location_reverse_map },
1143 { "Destination", ap_proxy_location_reverse_map },
1144 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1148 for (i = 0; date_hdrs[i]; ++i) {
1149 if (!strcasecmp(date_hdrs[i], key)) {
1150 apr_table_add(r->headers_out, key,
1151 ap_proxy_date_canon(r->pool, value));
1155 for (i = 0; transform_hdrs[i].name; ++i) {
1156 if (!strcasecmp(transform_hdrs[i].name, key)) {
1157 apr_table_add(r->headers_out, key,
1158 (*transform_hdrs[i].func)(r, c, value));
1162 apr_table_add(r->headers_out, key, value);
1167 * Note: pread_len is the length of the response that we've mistakenly
1168 * read (assuming that we don't consider that an error via
1169 * ProxyBadHeader StartBody). This depends on buffer actually being
1170 * local storage to the calling code in order for pread_len to make
1171 * any sense at all, since we depend on buffer still containing
1172 * what was read by ap_getline() upon return.
1174 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1175 char *buffer, int size,
1176 conn_rec *c, int *pread_len)
1180 char field[MAX_STRING_LEN];
1181 int saw_headers = 0;
1182 void *sconf = r->server->module_config;
1183 proxy_server_conf *psc;
1184 proxy_dir_conf *dconf;
1186 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1187 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1189 r->headers_out = apr_table_make(r->pool, 20);
1193 * Read header lines until we get the empty separator line, a read error,
1194 * the connection closes (EOF), or we timeout.
1196 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1198 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1200 /* We may encounter invalid headers, usually from buggy
1201 * MS IIS servers, so we need to determine just how to handle
1202 * them. We can either ignore them, assume that they mark the
1203 * start-of-body (eg: a missing CRLF) or (the default) mark
1204 * the headers as totally bogus and return a 500. The sole
1205 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1206 * in between the usual MIME headers, which is a favorite
1209 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1211 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1212 if (psc->badopt == bad_error) {
1213 /* Nope, it wasn't even an extra HTTP header. Give up. */
1214 r->headers_out = NULL;
1217 else if (psc->badopt == bad_body) {
1218 /* if we've already started loading headers_out, then
1219 * return what we've accumulated so far, in the hopes
1220 * that they are useful; also note that we likely pre-read
1221 * the first line of the response.
1224 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1225 "proxy: Starting body due to bogus non-header in headers "
1226 "returned by %s (%s)", r->uri, r->method);
1230 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1231 "proxy: No HTTP headers "
1232 "returned by %s (%s)", r->uri, r->method);
1237 /* this is the psc->badopt == bad_ignore case */
1238 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1239 "proxy: Ignoring bogus HTTP header "
1240 "returned by %s (%s)", r->uri, r->method);
1246 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1247 * wrong... and so are many others probably.
1249 while (apr_isspace(*value))
1250 ++value; /* Skip to start of value */
1252 /* should strip trailing whitespace as well */
1253 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1257 /* make sure we add so as not to destroy duplicated headers
1258 * Modify headers requiring canonicalisation and/or affected
1259 * by ProxyPassReverse and family with process_proxy_header
1261 process_proxy_header(r, dconf, buffer, value) ;
1264 /* the header was too long; at the least we should skip extra data */
1265 if (len >= size - 1) {
1266 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1267 >= MAX_STRING_LEN - 1) {
1268 /* soak up the extra data */
1270 if (len == 0) /* time to exit the larger loop as well */
1278 static int addit_dammit(void *v, const char *key, const char *val)
1280 apr_table_addn(v, key, val);
1285 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1286 int fold, int *writen)
1292 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1293 apr_brigade_cleanup(bb);
1295 if (rv == APR_SUCCESS) {
1296 *writen = (int) len;
1297 } else if (rv == APR_ENOSPC) {
1307 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1308 proxy_conn_rec *backend,
1310 proxy_server_conf *conf,
1311 char *server_portstr) {
1312 conn_rec *c = r->connection;
1313 char buffer[HUGE_STRING_LEN];
1318 apr_bucket_brigade *bb, *tmp_bb;
1319 int len, backasswards;
1320 int interim_response; /* non-zero whilst interim 1xx responses
1321 * are being read. */
1323 apr_table_t *save_table;
1324 int backend_broke = 0;
1325 static const char *hop_by_hop_hdrs[] =
1326 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1329 bb = apr_brigade_create(p, c->bucket_alloc);
1331 /* Get response from the remote server, and pass it up the
1335 rp = ap_proxy_make_fake_req(origin, r);
1336 /* In case anyone needs to know, this is a fake request that is really a
1339 rp->proxyreq = PROXYREQ_RESPONSE;
1340 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1344 apr_brigade_cleanup(bb);
1346 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1348 /* handle one potential stray CRLF */
1349 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1352 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1353 "proxy: error reading status line from remote "
1354 "server %s", backend->hostname);
1355 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1356 "Error reading from remote server");
1358 /* XXX: Is this a real headers length send from remote? */
1359 backend->worker->s->read += len;
1361 /* Is it an HTTP/1 response?
1362 * This is buggy if we ever see an HTTP/1.10
1364 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1367 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1371 /* If not an HTTP/1 message or
1372 * if the status line was > 8192 bytes
1374 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1375 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1376 apr_pstrcat(p, "Corrupt status line returned by remote "
1377 "server: ", buffer, NULL));
1381 keepchar = buffer[12];
1383 r->status = atoi(&buffer[9]);
1385 if (keepchar != '\0') {
1386 buffer[12] = keepchar;
1388 /* 2616 requires the space in Status-Line; the origin
1389 * server may have sent one but ap_rgetline_core will
1390 * have stripped it. */
1394 r->status_line = apr_pstrdup(p, &buffer[9]);
1397 /* read the headers. */
1398 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1399 /* Also, take care with headers with multiple occurences. */
1401 /* First, tuck away all already existing cookies */
1402 save_table = apr_table_make(r->pool, 2);
1403 apr_table_do(addit_dammit, save_table, r->headers_out,
1404 "Set-Cookie", NULL);
1406 /* shove the headers direct into r->headers_out */
1407 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1410 if (r->headers_out == NULL) {
1411 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1412 r->server, "proxy: bad HTTP/%d.%d header "
1413 "returned by %s (%s)", major, minor, r->uri,
1415 backend->close += 1;
1417 * ap_send_error relies on a headers_out to be present. we
1418 * are in a bad position here.. so force everything we send out
1419 * to have nothing to do with the incoming packet
1421 r->headers_out = apr_table_make(r->pool,1);
1422 r->status = HTTP_BAD_GATEWAY;
1423 r->status_line = "bad gateway";
1427 /* Now, add in the just read cookies */
1428 apr_table_do(addit_dammit, save_table, r->headers_out,
1429 "Set-Cookie", NULL);
1431 /* and now load 'em all in */
1432 if (!apr_is_empty_table(save_table)) {
1433 apr_table_unset(r->headers_out, "Set-Cookie");
1434 r->headers_out = apr_table_overlay(r->pool,
1439 /* can't have both Content-Length and Transfer-Encoding */
1440 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1441 && apr_table_get(r->headers_out, "Content-Length")) {
1443 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1444 * and Content-Length are received, the latter MUST be
1447 * To help mitigate HTTP Splitting, unset Content-Length
1448 * and shut down the backend server connection
1449 * XXX: We aught to treat such a response as uncachable
1451 apr_table_unset(r->headers_out, "Content-Length");
1452 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1453 "proxy: server %s returned Transfer-Encoding"
1454 " and Content-Length", backend->hostname);
1455 backend->close += 1;
1458 /* strip connection listed hop-by-hop headers from response */
1459 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1462 ap_proxy_clear_connection(p, r->headers_out);
1463 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1464 ap_set_content_type(r, apr_pstrdup(p, buf));
1466 ap_proxy_pre_http_request(origin,rp);
1468 /* Clear hop-by-hop headers */
1469 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1470 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1472 /* Delete warnings with wrong date */
1473 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1475 /* handle Via header in response */
1476 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1477 const char *server_name = ap_get_server_name(r);
1478 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1479 * then the server name returned by ap_get_server_name() is the
1480 * origin server name (which does make too much sense with Via: headers)
1481 * so we use the proxy vhost's name instead.
1483 if (server_name == r->hostname)
1484 server_name = r->server->server_hostname;
1485 /* create a "Via:" response header entry and merge it */
1486 apr_table_addn(r->headers_out, "Via",
1487 (conf->viaopt == via_full)
1488 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1489 HTTP_VERSION_MAJOR(r->proto_num),
1490 HTTP_VERSION_MINOR(r->proto_num),
1493 AP_SERVER_BASEVERSION)
1494 : apr_psprintf(p, "%d.%d %s%s",
1495 HTTP_VERSION_MAJOR(r->proto_num),
1496 HTTP_VERSION_MINOR(r->proto_num),
1502 /* cancel keepalive if HTTP/1.0 or less */
1503 if ((major < 1) || (minor < 1)) {
1504 backend->close += 1;
1505 origin->keepalive = AP_CONN_CLOSE;
1508 /* an http/0.9 response */
1511 r->status_line = "200 OK";
1512 backend->close += 1;
1515 interim_response = ap_is_HTTP_INFO(r->status);
1516 if (interim_response) {
1517 /* RFC2616 tells us to forward this.
1519 * OTOH, an interim response here may mean the backend
1520 * is playing sillybuggers. The Client didn't ask for
1521 * it within the defined HTTP/1.1 mechanisms, and if
1522 * it's an extension, it may also be unsupported by us.
1524 * There's also the possibility that changing existing
1525 * behaviour here might break something.
1527 * So let's make it configurable.
1529 const char *policy = apr_table_get(r->subprocess_env,
1530 "proxy-interim-response");
1531 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1532 "proxy: HTTP: received interim %d response",
1534 if (!policy || !strcasecmp(policy, "RFC")) {
1535 ap_send_interim_response(r, 1);
1537 /* FIXME: refine this to be able to specify per-response-status
1538 * policies and maybe also add option to bail out with 502
1540 else if (strcasecmp(policy, "Suppress")) {
1541 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1542 "undefined proxy interim response policy");
1545 /* Moved the fixups of Date headers and those affected by
1546 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1549 if ((r->status == 401) && (conf->error_override)) {
1551 const char *wa = "WWW-Authenticate";
1552 if ((buf = apr_table_get(r->headers_out, wa))) {
1553 apr_table_set(r->err_headers_out, wa, buf);
1555 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1556 "proxy: origin server sent 401 without WWW-Authenticate header");
1562 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1563 * the response? If so, load the extra data. These are 2 mutually
1564 * exclusive possibilities, that just happen to require very
1567 if (backasswards || pread_len) {
1568 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1571 * At this point in response processing of a 0.9 response,
1572 * we don't know yet whether data is binary or not.
1573 * mod_charset_lite will get control later on, so it cannot
1574 * decide on the conversion of this buffer full of data.
1575 * However, chances are that we are not really talking to an
1576 * HTTP/0.9 server, but to some different protocol, therefore
1577 * the best guess IMHO is to always treat the buffer as "text/x":
1579 ap_xlate_proto_to_ascii(buffer, len);
1580 cntr = (apr_ssize_t)len;
1582 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1583 APR_BRIGADE_INSERT_TAIL(bb, e);
1586 /* send body - but only if a body is expected */
1587 if ((!r->header_only) && /* not HEAD request */
1588 !interim_response && /* not any 1xx response */
1589 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1590 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1592 /* We need to copy the output headers and treat them as input
1593 * headers as well. BUT, we need to do this before we remove
1594 * TE, so that they are preserved accordingly for
1595 * ap_http_filter to know where to end.
1597 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1599 apr_table_unset(r->headers_out,"Transfer-Encoding");
1601 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1602 "proxy: start body send");
1605 * if we are overriding the errors, we can't put the content
1606 * of the page into the brigade
1608 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1609 /* read the body, pass it to the output filters */
1610 apr_read_type_e mode = APR_NONBLOCK_READ;
1614 apr_off_t readbytes;
1617 rv = ap_get_brigade(rp->input_filters, bb,
1618 AP_MODE_READBYTES, mode,
1619 conf->io_buffer_size);
1621 /* ap_get_brigade will return success with an empty brigade
1622 * for a non-blocking read which would block: */
1623 if (APR_STATUS_IS_EAGAIN(rv)
1624 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1625 /* flush to the client and switch to blocking mode */
1626 e = apr_bucket_flush_create(c->bucket_alloc);
1627 APR_BRIGADE_INSERT_TAIL(bb, e);
1628 if (ap_pass_brigade(r->output_filters, bb)
1633 apr_brigade_cleanup(bb);
1634 mode = APR_BLOCK_READ;
1637 else if (rv == APR_EOF) {
1640 else if (rv != APR_SUCCESS) {
1641 /* In this case, we are in real trouble because
1642 * our backend bailed on us. Pass along a 502 error
1645 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1646 "proxy: error reading response");
1647 ap_proxy_backend_broke(r, bb);
1648 ap_pass_brigade(r->output_filters, bb);
1653 /* next time try a non-blocking read */
1654 mode = APR_NONBLOCK_READ;
1656 apr_brigade_length(bb, 0, &readbytes);
1657 backend->worker->s->read += readbytes;
1660 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1661 r->server, "proxy (PID %d): readbytes: %#x",
1662 getpid(), readbytes);
1666 if (APR_BRIGADE_EMPTY(bb)) {
1667 apr_brigade_cleanup(bb);
1671 /* found the last brigade? */
1672 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1673 /* signal that we must leave */
1677 /* try send what we read */
1678 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1680 /* Ack! Phbtt! Die! User aborted! */
1681 backend->close = 1; /* this causes socket close below */
1685 /* make sure we always clean up after ourselves */
1686 apr_brigade_cleanup(bb);
1690 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1691 "proxy: end body send");
1693 else if (!interim_response) {
1694 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1695 "proxy: header only");
1697 /* Pass EOS bucket down the filter chain. */
1698 e = apr_bucket_eos_create(c->bucket_alloc);
1699 APR_BRIGADE_INSERT_TAIL(bb, e);
1700 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1702 /* Ack! Phbtt! Die! User aborted! */
1703 backend->close = 1; /* this causes socket close below */
1706 apr_brigade_cleanup(bb);
1708 } while (interim_response);
1710 /* If our connection with the client is to be aborted, return DONE. */
1711 if (c->aborted || backend_broke) {
1715 if (conf->error_override) {
1716 /* the code above this checks for 'OK' which is what the hook expects */
1717 if (!ap_is_HTTP_ERROR(r->status))
1720 /* clear r->status for override error, otherwise ErrorDocument
1721 * thinks that this is a recursive error, and doesn't find the
1724 int status = r->status;
1725 r->status = HTTP_OK;
1726 /* Discard body, if one is expected */
1727 if (!r->header_only && /* not HEAD request */
1728 (status != HTTP_NO_CONTENT) && /* not 204 */
1729 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1730 ap_discard_request_body(rp);
1739 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1740 proxy_conn_rec *backend)
1742 ap_proxy_release_connection(scheme, backend, r->server);
1747 * This handles http:// URLs, and other URLs using a remote proxy over http
1748 * If proxyhost is NULL, then contact the server directly, otherwise
1750 * Note that if a proxy is used, then URLs other than http: can be accessed,
1751 * also, if we have trouble which is clearly specific to the proxy, then
1752 * we return DECLINED so that we can try another proxy. (Or the direct
1755 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1756 proxy_server_conf *conf,
1757 char *url, const char *proxyname,
1758 apr_port_t proxyport)
1761 char server_portstr[32];
1763 const char *proxy_function;
1765 proxy_conn_rec *backend = NULL;
1768 /* Note: Memory pool allocation.
1769 * A downstream keepalive connection is always connected to the existence
1770 * (or not) of an upstream keepalive connection. If this is not done then
1771 * load balancing against multiple backend servers breaks (one backend
1772 * server ends up taking 100% of the load), and the risk is run of
1773 * downstream keepalive connections being kept open unnecessarily. This
1774 * keeps webservers busy and ties up resources.
1776 * As a result, we allocate all sockets out of the upstream connection
1777 * pool, and when we want to reuse a socket, we check first whether the
1778 * connection ID of the current upstream connection is the same as that
1779 * of the connection when the socket was opened.
1781 apr_pool_t *p = r->connection->pool;
1782 conn_rec *c = r->connection;
1783 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1785 /* find the scheme */
1786 u = strchr(url, ':');
1787 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1790 return HTTP_BAD_REQUEST;
1791 scheme = apr_pstrndup(c->pool, url, u - url);
1792 /* scheme is lowercase */
1793 ap_str_tolower(scheme);
1795 if (strcmp(scheme, "https") == 0) {
1796 if (!ap_proxy_ssl_enable(NULL)) {
1797 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1798 "proxy: HTTPS: declining URL %s"
1799 " (mod_ssl not configured?)", url);
1803 proxy_function = "HTTPS";
1805 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1806 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1807 "proxy: HTTP: declining URL %s", url);
1808 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1812 proxy_function = "HTTP";
1814 proxy_function = "FTP";
1816 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1817 "proxy: HTTP: serving URL %s", url);
1820 /* create space for state information */
1821 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1822 worker, r->server)) != OK)
1826 backend->is_ssl = is_ssl;
1828 * TODO: Currently we cannot handle persistent SSL backend connections,
1829 * because we recreate backend->connection for each request and thus
1830 * try to initialize an already existing SSL connection. This does
1836 /* Step One: Determine Who To Connect To */
1837 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1838 uri, &url, proxyname,
1839 proxyport, server_portstr,
1840 sizeof(server_portstr))) != OK)
1843 /* Step Two: Make the Connection */
1844 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1845 if (r->proxyreq == PROXYREQ_PROXY)
1846 status = HTTP_NOT_FOUND;
1848 status = HTTP_SERVICE_UNAVAILABLE;
1852 /* Step Three: Create conn_rec */
1853 if (!backend->connection) {
1854 if ((status = ap_proxy_connection_create(proxy_function, backend,
1855 c, r->server)) != OK)
1859 /* Step Four: Send the Request */
1860 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1861 conf, uri, url, server_portstr)) != OK)
1864 /* Step Five: Receive the Response */
1865 if ((status = ap_proxy_http_process_response(p, r, backend,
1866 backend->connection,
1867 conf, server_portstr)) != OK)
1870 /* Step Six: Clean Up */
1876 ap_proxy_http_cleanup(proxy_function, r, backend);
1880 static apr_status_t warn_rx_free(void *p)
1882 ap_pregfree((apr_pool_t*)p, warn_rx);
1885 static void ap_proxy_http_register_hook(apr_pool_t *p)
1887 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1888 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1889 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1890 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1893 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1894 STANDARD20_MODULE_STUFF,
1895 NULL, /* create per-directory config structure */
1896 NULL, /* merge per-directory config structures */
1897 NULL, /* create per-server config structure */
1898 NULL, /* merge per-server config structures */
1899 NULL, /* command apr_table_t */
1900 ap_proxy_http_register_hook/* register hooks */