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 * In a forward proxy, we have and MUST NOT MANGLE the original,
86 * so just check it for disallowed chars.
88 switch (r->proxyreq) {
89 default: /* wtf are we doing here? */
90 case PROXYREQ_REVERSE:
91 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
99 return HTTP_BAD_REQUEST;
101 if (port != def_port)
102 apr_snprintf(sport, sizeof(sport), ":%d", port);
106 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
107 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
109 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
110 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
114 /* Clear all connection-based headers from the incoming headers table */
115 typedef struct header_dptr {
120 static ap_regex_t *warn_rx;
121 static int clean_warning_headers(void *data, const char *key, const char *val)
123 apr_table_t *headers = ((header_dptr*)data)->table;
124 apr_pool_t *pool = ((header_dptr*)data)->pool;
127 apr_time_t warn_time;
128 const int nmatch = 3;
129 ap_regmatch_t pmatch[3];
131 if (headers == NULL) {
132 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
135 * Parse this, suckers!
137 * Warning = "Warning" ":" 1#warning-value
139 * warning-value = warn-code SP warn-agent SP warn-text
143 * warn-agent = ( host [ ":" port ] ) | pseudonym
144 * ; the name or pseudonym of the server adding
145 * ; the Warning header, for use in debugging
146 * warn-text = quoted-string
147 * warn-date = <"> HTTP-date <">
149 * Buggrit, use a bloomin' regexp!
150 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
152 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
153 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
154 pmatch[0].rm_eo - pmatch[0].rm_so);
156 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
157 /* OK, we have a date here */
158 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
159 pmatch[2].rm_eo - pmatch[2].rm_so);
160 warn_time = apr_date_parse_http(date);
162 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
163 apr_table_addn(headers, key, warning);
165 val += pmatch[0].rm_eo;
169 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
174 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
175 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
176 if (x.table != NULL) {
177 apr_table_unset(headers, "Warning");
178 return apr_table_overlay(p, headers, x.table);
184 static int clear_conn_headers(void *data, const char *key, const char *val)
186 apr_table_t *headers = ((header_dptr*)data)->table;
187 apr_pool_t *pool = ((header_dptr*)data)->pool;
189 char *next = apr_pstrdup(pool, val);
192 while (*next && !apr_isspace(*next) && (*next != ',')) {
195 while (*next && (apr_isspace(*next) || (*next == ','))) {
198 apr_table_unset(headers, name);
202 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
207 apr_table_unset(headers, "Proxy-Connection");
208 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
209 apr_table_unset(headers, "Connection");
211 static void add_te_chunked(apr_pool_t *p,
212 apr_bucket_alloc_t *bucket_alloc,
213 apr_bucket_brigade *header_brigade)
217 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
219 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
220 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
222 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
223 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
226 static void add_cl(apr_pool_t *p,
227 apr_bucket_alloc_t *bucket_alloc,
228 apr_bucket_brigade *header_brigade,
234 buf = apr_pstrcat(p, "Content-Length: ",
238 ap_xlate_proto_to_ascii(buf, strlen(buf));
239 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
240 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
243 #define ASCII_CRLF "\015\012"
244 #define ASCII_ZERO "\060"
246 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
247 apr_bucket_brigade *header_brigade)
251 /* add empty line at the end of the headers */
252 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
253 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
256 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
257 request_rec *r, proxy_conn_rec *conn,
258 conn_rec *origin, apr_bucket_brigade *bb,
262 apr_off_t transferred;
265 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
266 APR_BRIGADE_INSERT_TAIL(bb, e);
268 apr_brigade_length(bb, 0, &transferred);
269 if (transferred != -1)
270 conn->worker->s->transferred += transferred;
271 status = ap_pass_brigade(origin->output_filters, bb);
272 if (status != APR_SUCCESS) {
273 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
274 "proxy: pass request body failed to %pI (%s)",
275 conn->addr, conn->hostname);
278 apr_brigade_cleanup(bb);
282 #define MAX_MEM_SPOOL 16384
284 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
286 proxy_conn_rec *p_conn,
288 apr_bucket_brigade *header_brigade,
289 apr_bucket_brigade *input_brigade)
295 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
296 apr_bucket_brigade *bb;
299 add_te_chunked(p, bucket_alloc, header_brigade);
300 terminate_headers(bucket_alloc, header_brigade);
302 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
304 char chunk_hdr[20]; /* must be here due to transient bucket. */
306 /* If this brigade contains EOS, either stop or remove it. */
307 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
310 /* We can't pass this EOS to the output_filters. */
311 e = APR_BRIGADE_LAST(input_brigade);
312 apr_bucket_delete(e);
315 apr_brigade_length(input_brigade, 1, &bytes);
317 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
318 "%" APR_UINT64_T_HEX_FMT CRLF,
319 (apr_uint64_t)bytes);
321 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
322 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
324 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
327 * Append the end-of-chunk CRLF
329 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
330 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
332 if (header_brigade) {
333 /* we never sent the header brigade, so go ahead and
334 * take care of that now
339 * Save input_brigade in bb brigade. (At least) in the SSL case
340 * input_brigade contains transient buckets whose data would get
341 * overwritten during the next call of ap_get_brigade in the loop.
342 * ap_save_brigade ensures these buckets to be set aside.
343 * Calling ap_save_brigade with NULL as filter is OK, because
344 * bb brigade already has been created and does not need to get
345 * created by ap_save_brigade.
347 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
348 if (status != APR_SUCCESS) {
352 header_brigade = NULL;
358 /* The request is flushed below this loop with chunk EOS header */
359 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
360 if (status != APR_SUCCESS) {
368 status = ap_get_brigade(r->input_filters, input_brigade,
369 AP_MODE_READBYTES, APR_BLOCK_READ,
372 if (status != APR_SUCCESS) {
377 if (header_brigade) {
378 /* we never sent the header brigade because there was no request body;
384 if (!APR_BRIGADE_EMPTY(input_brigade)) {
385 /* input brigade still has an EOS which we can't pass to the output_filters. */
386 e = APR_BRIGADE_LAST(input_brigade);
387 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
388 apr_bucket_delete(e);
393 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
397 APR_BRIGADE_INSERT_TAIL(bb, e);
399 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
400 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
401 APR_BRIGADE_INSERT_TAIL(bb, e);
404 /* Now we have headers-only, or the chunk EOS mark; flush it */
405 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
409 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
411 proxy_conn_rec *p_conn,
413 apr_bucket_brigade *header_brigade,
414 apr_bucket_brigade *input_brigade,
415 const char *old_cl_val)
418 apr_status_t status = APR_SUCCESS;
419 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
420 apr_bucket_brigade *bb;
422 apr_off_t cl_val = 0;
424 apr_off_t bytes_streamed = 0;
427 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
428 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
433 terminate_headers(bucket_alloc, header_brigade);
435 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
437 apr_brigade_length(input_brigade, 1, &bytes);
438 bytes_streamed += bytes;
440 /* If this brigade contains EOS, either stop or remove it. */
441 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
444 /* We can't pass this EOS to the output_filters. */
445 e = APR_BRIGADE_LAST(input_brigade);
446 apr_bucket_delete(e);
448 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
449 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
450 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
454 /* C-L < bytes streamed?!?
455 * We will error out after the body is completely
456 * consumed, but we can't stream more bytes at the
457 * back end since they would in part be interpreted
458 * as another request! If nothing is sent, then
461 * Prevents HTTP Response Splitting.
463 if (bytes_streamed > cl_val)
466 if (header_brigade) {
467 /* we never sent the header brigade, so go ahead and
468 * take care of that now
473 * Save input_brigade in bb brigade. (At least) in the SSL case
474 * input_brigade contains transient buckets whose data would get
475 * overwritten during the next call of ap_get_brigade in the loop.
476 * ap_save_brigade ensures these buckets to be set aside.
477 * Calling ap_save_brigade with NULL as filter is OK, because
478 * bb brigade already has been created and does not need to get
479 * created by ap_save_brigade.
481 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
482 if (status != APR_SUCCESS) {
486 header_brigade = NULL;
492 /* Once we hit EOS, we are ready to flush. */
493 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
494 if (status != APR_SUCCESS) {
502 status = ap_get_brigade(r->input_filters, input_brigade,
503 AP_MODE_READBYTES, APR_BLOCK_READ,
506 if (status != APR_SUCCESS) {
511 if (bytes_streamed != cl_val) {
512 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
513 "proxy: client %s given Content-Length did not match"
514 " number of body bytes read", r->connection->remote_ip);
518 if (header_brigade) {
519 /* we never sent the header brigade since there was no request
520 * body; send it now with the flush flag
523 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
528 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
530 proxy_conn_rec *p_conn,
532 apr_bucket_brigade *header_brigade,
533 apr_bucket_brigade *input_brigade,
538 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
539 apr_bucket_brigade *body_brigade;
541 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
542 apr_file_t *tmpfile = NULL;
544 body_brigade = apr_brigade_create(p, bucket_alloc);
546 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
548 /* If this brigade contains EOS, either stop or remove it. */
549 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
552 /* We can't pass this EOS to the output_filters. */
553 e = APR_BRIGADE_LAST(input_brigade);
554 apr_bucket_delete(e);
557 apr_brigade_length(input_brigade, 1, &bytes);
559 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
560 /* can't spool any more in memory; write latest brigade to disk */
561 if (tmpfile == NULL) {
562 const char *temp_dir;
565 status = apr_temp_dir_get(&temp_dir, p);
566 if (status != APR_SUCCESS) {
567 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
568 "proxy: search for temporary directory failed");
571 apr_filepath_merge(&template, temp_dir,
572 "modproxy.tmp.XXXXXX",
573 APR_FILEPATH_NATIVE, p);
574 status = apr_file_mktemp(&tmpfile, template, 0, p);
575 if (status != APR_SUCCESS) {
576 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
577 "proxy: creation of temporary file in directory %s failed",
582 for (e = APR_BRIGADE_FIRST(input_brigade);
583 e != APR_BRIGADE_SENTINEL(input_brigade);
584 e = APR_BUCKET_NEXT(e)) {
586 apr_size_t bytes_read, bytes_written;
588 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
589 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
590 if (status != APR_SUCCESS) {
591 const char *tmpfile_name;
593 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
594 tmpfile_name = "(unknown)";
596 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
597 "proxy: write to temporary file %s failed",
601 AP_DEBUG_ASSERT(bytes_read == bytes_written);
602 fsize += bytes_written;
604 apr_brigade_cleanup(input_brigade);
609 * Save input_brigade in body_brigade. (At least) in the SSL case
610 * input_brigade contains transient buckets whose data would get
611 * overwritten during the next call of ap_get_brigade in the loop.
612 * ap_save_brigade ensures these buckets to be set aside.
613 * Calling ap_save_brigade with NULL as filter is OK, because
614 * body_brigade already has been created and does not need to get
615 * created by ap_save_brigade.
617 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
618 if (status != APR_SUCCESS) {
624 bytes_spooled += bytes;
630 status = ap_get_brigade(r->input_filters, input_brigade,
631 AP_MODE_READBYTES, APR_BLOCK_READ,
634 if (status != APR_SUCCESS) {
639 if (bytes_spooled || force_cl) {
640 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
642 terminate_headers(bucket_alloc, header_brigade);
643 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
645 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
647 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
648 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
649 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
651 /* This is all a single brigade, pass with flush flagged */
652 status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
657 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
658 proxy_conn_rec *p_conn, conn_rec *origin,
659 proxy_server_conf *conf,
661 char *url, char *server_portstr)
663 conn_rec *c = r->connection;
664 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
665 apr_bucket_brigade *header_brigade;
666 apr_bucket_brigade *input_brigade;
667 apr_bucket_brigade *temp_brigade;
670 const apr_array_header_t *headers_in_array;
671 const apr_table_entry_t *headers_in;
674 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
675 enum rb_methods rb_method = RB_INIT;
676 const char *old_cl_val = NULL;
677 const char *old_te_val = NULL;
678 apr_off_t bytes_read = 0;
681 apr_table_t *headers_in_copy;
683 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
686 * Send the HTTP/1.1 request to the remote server
689 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
690 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
694 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
697 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
698 origin->keepalive = AP_CONN_CLOSE;
701 ap_xlate_proto_to_ascii(buf, strlen(buf));
702 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
703 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
704 if (conf->preserve_host == 0) {
705 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
706 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
709 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
713 /* don't want to use r->hostname, as the incoming header might have a
716 const char* hostname = apr_table_get(r->headers_in,"Host");
718 hostname = r->server->server_hostname;
719 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
720 "proxy: no HTTP 0.9 request (with no host line) "
721 "on incoming request and preserve host set "
722 "forcing hostname to be %s for uri %s",
726 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
728 ap_xlate_proto_to_ascii(buf, strlen(buf));
729 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
730 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
733 if (conf->viaopt == via_block) {
734 /* Block all outgoing Via: headers */
735 apr_table_unset(r->headers_in, "Via");
736 } else if (conf->viaopt != via_off) {
737 const char *server_name = ap_get_server_name(r);
738 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
739 * then the server name returned by ap_get_server_name() is the
740 * origin server name (which does make too much sense with Via: headers)
741 * so we use the proxy vhost's name instead.
743 if (server_name == r->hostname)
744 server_name = r->server->server_hostname;
745 /* Create a "Via:" request header entry and merge it */
746 /* Generate outgoing Via: header with/without server comment: */
747 apr_table_mergen(r->headers_in, "Via",
748 (conf->viaopt == via_full)
749 ? apr_psprintf(p, "%d.%d %s%s (%s)",
750 HTTP_VERSION_MAJOR(r->proto_num),
751 HTTP_VERSION_MINOR(r->proto_num),
752 server_name, server_portstr,
753 AP_SERVER_BASEVERSION)
754 : apr_psprintf(p, "%d.%d %s%s",
755 HTTP_VERSION_MAJOR(r->proto_num),
756 HTTP_VERSION_MINOR(r->proto_num),
757 server_name, server_portstr)
761 /* X-Forwarded-*: handling
766 * These request headers are only really useful when the mod_proxy
767 * is used in a reverse proxy configuration, so that useful info
768 * about the client can be passed through the reverse proxy and on
769 * to the backend server, which may require the information to
772 * In a forward proxy situation, these options are a potential
773 * privacy violation, as information about clients behind the proxy
774 * are revealed to arbitrary servers out there on the internet.
776 * The HTTP/1.1 Via: header is designed for passing client
777 * information through proxies to a server, and should be used in
778 * a forward proxy configuation instead of X-Forwarded-*. See the
779 * ProxyVia option for details.
782 if (PROXYREQ_REVERSE == r->proxyreq) {
785 /* Add X-Forwarded-For: so that the upstream has a chance to
786 * determine, where the original request came from.
788 apr_table_mergen(r->headers_in, "X-Forwarded-For",
791 /* Add X-Forwarded-Host: so that upstream knows what the
792 * original request hostname was.
794 if ((buf = apr_table_get(r->headers_in, "Host"))) {
795 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
798 /* Add X-Forwarded-Server: so that upstream knows what the
799 * name of this proxy server is (if there are more than one)
800 * XXX: This duplicates Via: - do we strictly need it?
802 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
803 r->server->server_hostname);
808 * Make a copy of the headers_in table before clearing the connection
809 * headers as we need the connection headers later in the http output
810 * filter to prepare the correct response headers.
812 * Note: We need to take r->pool for apr_table_copy as the key / value
813 * pairs in r->headers_in have been created out of r->pool and
814 * p might be (and actually is) a longer living pool.
815 * This would trigger the bad pool ancestry abort in apr_table_copy if
816 * apr is compiled with APR_POOL_DEBUG.
818 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
819 ap_proxy_clear_connection(p, headers_in_copy);
820 /* send request headers */
821 headers_in_array = apr_table_elts(headers_in_copy);
822 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
823 for (counter = 0; counter < headers_in_array->nelts; counter++) {
824 if (headers_in[counter].key == NULL
825 || headers_in[counter].val == NULL
828 || !strcasecmp(headers_in[counter].key, "Host")
830 /* Clear out hop-by-hop request headers not to send
831 * RFC2616 13.5.1 says we should strip these headers
833 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
834 || !strcasecmp(headers_in[counter].key, "TE")
835 || !strcasecmp(headers_in[counter].key, "Trailer")
836 || !strcasecmp(headers_in[counter].key, "Upgrade")
841 /* Do we want to strip Proxy-Authorization ?
842 * If we haven't used it, then NO
843 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
844 * So let's make it configurable by env.
846 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
847 if (r->user != NULL) { /* we've authenticated */
848 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
855 /* Skip Transfer-Encoding and Content-Length for now.
857 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
858 old_te_val = headers_in[counter].val;
861 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
862 old_cl_val = headers_in[counter].val;
866 /* for sub-requests, ignore freshness/expiry headers */
868 if ( !strcasecmp(headers_in[counter].key, "If-Match")
869 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
870 || !strcasecmp(headers_in[counter].key, "If-Range")
871 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
872 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
877 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
878 headers_in[counter].val, CRLF,
880 ap_xlate_proto_to_ascii(buf, strlen(buf));
881 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
882 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
885 /* We have headers, let's figure out our request body... */
886 input_brigade = apr_brigade_create(p, bucket_alloc);
888 /* sub-requests never use keepalives, and mustn't pass request bodies.
889 * Because the new logic looks at input_brigade, we will self-terminate
890 * input_brigade and jump past all of the request body logic...
891 * Reading anything with ap_get_brigade is likely to consume the
892 * main request's body or read beyond EOS - which would be unplesant.
895 /* XXX: Why DON'T sub-requests use keepalives? */
899 apr_table_unset(r->headers_in, "Content-Length");
903 apr_table_unset(r->headers_in, "Transfer-Encoding");
905 rb_method = RB_STREAM_CL;
906 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
907 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
911 /* WE only understand chunked. Other modules might inject
912 * (and therefore, decode) other flavors but we don't know
913 * that the can and have done so unless they they remove
914 * their decoding from the headers_in T-E list.
915 * XXX: Make this extensible, but in doing so, presume the
916 * encoding has been done by the extensions' handler, and
917 * do not modify add_te_chunked's logic
919 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
920 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
921 "proxy: %s Transfer-Encoding is not supported",
926 if (old_cl_val && old_te_val) {
927 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
928 "proxy: client %s (%s) requested Transfer-Encoding "
929 "chunked body with Content-Length (C-L ignored)",
930 c->remote_ip, c->remote_host ? c->remote_host: "");
931 apr_table_unset(r->headers_in, "Content-Length");
933 origin->keepalive = AP_CONN_CLOSE;
937 /* Prefetch MAX_MEM_SPOOL bytes
939 * This helps us avoid any election of C-L v.s. T-E
940 * request bodies, since we are willing to keep in
941 * memory this much data, in any case. This gives
942 * us an instant C-L election if the body is of some
945 temp_brigade = apr_brigade_create(p, bucket_alloc);
947 status = ap_get_brigade(r->input_filters, temp_brigade,
948 AP_MODE_READBYTES, APR_BLOCK_READ,
949 MAX_MEM_SPOOL - bytes_read);
950 if (status != APR_SUCCESS) {
951 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
952 "proxy: prefetch request body failed to %pI (%s)"
954 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
955 c->remote_ip, c->remote_host ? c->remote_host: "");
959 apr_brigade_length(temp_brigade, 1, &bytes);
963 * Save temp_brigade in input_brigade. (At least) in the SSL case
964 * temp_brigade contains transient buckets whose data would get
965 * overwritten during the next call of ap_get_brigade in the loop.
966 * ap_save_brigade ensures these buckets to be set aside.
967 * Calling ap_save_brigade with NULL as filter is OK, because
968 * input_brigade already has been created and does not need to get
969 * created by ap_save_brigade.
971 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
972 if (status != APR_SUCCESS) {
973 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
974 "proxy: processing prefetched request body failed"
975 " to %pI (%s) from %s (%s)",
976 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
977 c->remote_ip, c->remote_host ? c->remote_host: "");
981 /* Ensure we don't hit a wall where we have a buffer too small
982 * for ap_get_brigade's filters to fetch us another bucket,
983 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
984 * (an arbitrary value.)
986 } while ((bytes_read < MAX_MEM_SPOOL - 80)
987 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
989 /* Use chunked request body encoding or send a content-length body?
993 * We have no request body (handled by RB_STREAM_CL)
995 * We have a request body length <= MAX_MEM_SPOOL
997 * The administrator has setenv force-proxy-request-1.0
999 * The client sent a C-L body, and the administrator has
1000 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1002 * The client sent a T-E body, and the administrator has
1003 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1005 * If both proxy-sendcl and proxy-sendchunked are set, the
1006 * behavior is the same as if neither were set, large bodies
1007 * that can't be read will be forwarded in their original
1008 * form of C-L, or T-E.
1010 * To ensure maximum compatibility, setenv proxy-sendcl
1011 * To reduce server resource use, setenv proxy-sendchunked
1013 * Then address specific servers with conditional setenv
1014 * options to restore the default behavior where desireable.
1016 * We have to compute content length by reading the entire request
1017 * body; if request body is not small, we'll spool the remaining
1018 * input to a temporary file. Chunked is always preferable.
1020 * We can only trust the client-provided C-L if the T-E header
1021 * is absent, and the filters are unchanged (the body won't
1022 * be resized by another content filter).
1024 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1025 /* The whole thing fit, so our decision is trivial, use
1026 * the filtered bytes read from the client for the request
1027 * body Content-Length.
1029 * If we expected no body, and read no body, do not set
1030 * the Content-Length.
1032 if (old_cl_val || old_te_val || bytes_read) {
1033 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1035 rb_method = RB_STREAM_CL;
1037 else if (old_te_val) {
1039 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1040 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1041 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1042 rb_method = RB_SPOOL_CL;
1045 rb_method = RB_STREAM_CHUNKED;
1048 else if (old_cl_val) {
1049 if (r->input_filters == r->proto_input_filters) {
1050 rb_method = RB_STREAM_CL;
1053 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1054 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1055 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1056 rb_method = RB_STREAM_CHUNKED;
1059 rb_method = RB_SPOOL_CL;
1063 /* This is an appropriate default; very efficient for no-body
1064 * requests, and has the behavior that it will not add any C-L
1065 * when the old_cl_val is NULL.
1067 rb_method = RB_SPOOL_CL;
1070 /* Yes I hate gotos. This is the subrequest shortcut */
1073 * Handle Connection: header if we do HTTP/1.1 request:
1074 * If we plan to close the backend connection sent Connection: close
1075 * otherwise sent Connection: Keep-Alive.
1078 if (p_conn->close) {
1079 buf = apr_pstrdup(p, "Connection: close" CRLF);
1082 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1084 ap_xlate_proto_to_ascii(buf, strlen(buf));
1085 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1086 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1089 /* send the request body, if any. */
1091 case RB_STREAM_CHUNKED:
1092 status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1096 status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1097 input_brigade, old_cl_val);
1100 status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1101 input_brigade, (old_cl_val != NULL)
1102 || (old_te_val != NULL)
1103 || (bytes_read > 0));
1106 /* shouldn't be possible */
1107 status = APR_EINVAL;
1111 if (status != APR_SUCCESS) {
1112 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1113 "proxy: pass request body failed to %pI (%s)"
1116 p_conn->hostname ? p_conn->hostname: "",
1118 c->remote_host ? c->remote_host: "");
1125 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1126 const char *key, const char *value)
1128 static const char *date_hdrs[]
1129 = { "Date", "Expires", "Last-Modified", NULL };
1130 static const struct {
1132 ap_proxy_header_reverse_map_fn func;
1133 } transform_hdrs[] = {
1134 { "Location", ap_proxy_location_reverse_map },
1135 { "Content-Location", ap_proxy_location_reverse_map },
1136 { "URI", ap_proxy_location_reverse_map },
1137 { "Destination", ap_proxy_location_reverse_map },
1138 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1142 for (i = 0; date_hdrs[i]; ++i) {
1143 if (!strcasecmp(date_hdrs[i], key)) {
1144 apr_table_add(r->headers_out, key,
1145 ap_proxy_date_canon(r->pool, value));
1149 for (i = 0; transform_hdrs[i].name; ++i) {
1150 if (!strcasecmp(transform_hdrs[i].name, key)) {
1151 apr_table_add(r->headers_out, key,
1152 (*transform_hdrs[i].func)(r, c, value));
1156 apr_table_add(r->headers_out, key, value);
1161 * Note: pread_len is the length of the response that we've mistakenly
1162 * read (assuming that we don't consider that an error via
1163 * ProxyBadHeader StartBody). This depends on buffer actually being
1164 * local storage to the calling code in order for pread_len to make
1165 * any sense at all, since we depend on buffer still containing
1166 * what was read by ap_getline() upon return.
1168 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1169 char *buffer, int size,
1170 conn_rec *c, int *pread_len)
1174 char field[MAX_STRING_LEN];
1175 int saw_headers = 0;
1176 void *sconf = r->server->module_config;
1177 proxy_server_conf *psc;
1178 proxy_dir_conf *dconf;
1180 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1181 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1183 r->headers_out = apr_table_make(r->pool, 20);
1187 * Read header lines until we get the empty separator line, a read error,
1188 * the connection closes (EOF), or we timeout.
1190 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1192 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1194 /* We may encounter invalid headers, usually from buggy
1195 * MS IIS servers, so we need to determine just how to handle
1196 * them. We can either ignore them, assume that they mark the
1197 * start-of-body (eg: a missing CRLF) or (the default) mark
1198 * the headers as totally bogus and return a 500. The sole
1199 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1200 * in between the usual MIME headers, which is a favorite
1203 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1205 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1206 if (psc->badopt == bad_error) {
1207 /* Nope, it wasn't even an extra HTTP header. Give up. */
1208 r->headers_out = NULL;
1211 else if (psc->badopt == bad_body) {
1212 /* if we've already started loading headers_out, then
1213 * return what we've accumulated so far, in the hopes
1214 * that they are useful; also note that we likely pre-read
1215 * the first line of the response.
1218 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1219 "proxy: Starting body due to bogus non-header in headers "
1220 "returned by %s (%s)", r->uri, r->method);
1224 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1225 "proxy: No HTTP headers "
1226 "returned by %s (%s)", r->uri, r->method);
1231 /* this is the psc->badopt == bad_ignore case */
1232 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1233 "proxy: Ignoring bogus HTTP header "
1234 "returned by %s (%s)", r->uri, r->method);
1240 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1241 * wrong... and so are many others probably.
1243 while (apr_isspace(*value))
1244 ++value; /* Skip to start of value */
1246 /* should strip trailing whitespace as well */
1247 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1251 /* make sure we add so as not to destroy duplicated headers
1252 * Modify headers requiring canonicalisation and/or affected
1253 * by ProxyPassReverse and family with process_proxy_header
1255 process_proxy_header(r, dconf, buffer, value) ;
1258 /* the header was too long; at the least we should skip extra data */
1259 if (len >= size - 1) {
1260 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1261 >= MAX_STRING_LEN - 1) {
1262 /* soak up the extra data */
1264 if (len == 0) /* time to exit the larger loop as well */
1272 static int addit_dammit(void *v, const char *key, const char *val)
1274 apr_table_addn(v, key, val);
1279 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1280 int fold, int *writen)
1286 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1287 apr_brigade_cleanup(bb);
1289 if (rv == APR_SUCCESS) {
1290 *writen = (int) len;
1291 } else if (rv == APR_ENOSPC) {
1301 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1302 proxy_conn_rec *backend,
1304 proxy_server_conf *conf,
1305 char *server_portstr) {
1306 conn_rec *c = r->connection;
1307 char buffer[HUGE_STRING_LEN];
1312 apr_bucket_brigade *bb, *tmp_bb;
1313 int len, backasswards;
1314 int interim_response; /* non-zero whilst interim 1xx responses
1315 * are being read. */
1317 apr_table_t *save_table;
1318 int backend_broke = 0;
1319 static const char *hop_by_hop_hdrs[] =
1320 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1323 bb = apr_brigade_create(p, c->bucket_alloc);
1325 /* Get response from the remote server, and pass it up the
1329 rp = ap_proxy_make_fake_req(origin, r);
1330 /* In case anyone needs to know, this is a fake request that is really a
1333 rp->proxyreq = PROXYREQ_RESPONSE;
1334 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1338 apr_brigade_cleanup(bb);
1340 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1342 /* handle one potential stray CRLF */
1343 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1346 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1347 "proxy: error reading status line from remote "
1348 "server %s", backend->hostname);
1349 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1350 "Error reading from remote server");
1352 /* XXX: Is this a real headers length send from remote? */
1353 backend->worker->s->read += len;
1355 /* Is it an HTTP/1 response?
1356 * This is buggy if we ever see an HTTP/1.10
1358 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1361 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1365 /* If not an HTTP/1 message or
1366 * if the status line was > 8192 bytes
1368 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1369 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1370 apr_pstrcat(p, "Corrupt status line returned by remote "
1371 "server: ", buffer, NULL));
1375 keepchar = buffer[12];
1377 r->status = atoi(&buffer[9]);
1379 if (keepchar != '\0') {
1380 buffer[12] = keepchar;
1382 /* 2616 requires the space in Status-Line; the origin
1383 * server may have sent one but ap_rgetline_core will
1384 * have stripped it. */
1388 r->status_line = apr_pstrdup(p, &buffer[9]);
1391 /* read the headers. */
1392 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1393 /* Also, take care with headers with multiple occurences. */
1395 /* First, tuck away all already existing cookies */
1396 save_table = apr_table_make(r->pool, 2);
1397 apr_table_do(addit_dammit, save_table, r->headers_out,
1398 "Set-Cookie", NULL);
1400 /* shove the headers direct into r->headers_out */
1401 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1404 if (r->headers_out == NULL) {
1405 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1406 r->server, "proxy: bad HTTP/%d.%d header "
1407 "returned by %s (%s)", major, minor, r->uri,
1409 backend->close += 1;
1411 * ap_send_error relies on a headers_out to be present. we
1412 * are in a bad position here.. so force everything we send out
1413 * to have nothing to do with the incoming packet
1415 r->headers_out = apr_table_make(r->pool,1);
1416 r->status = HTTP_BAD_GATEWAY;
1417 r->status_line = "bad gateway";
1421 /* Now, add in the just read cookies */
1422 apr_table_do(addit_dammit, save_table, r->headers_out,
1423 "Set-Cookie", NULL);
1425 /* and now load 'em all in */
1426 if (!apr_is_empty_table(save_table)) {
1427 apr_table_unset(r->headers_out, "Set-Cookie");
1428 r->headers_out = apr_table_overlay(r->pool,
1433 /* can't have both Content-Length and Transfer-Encoding */
1434 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1435 && apr_table_get(r->headers_out, "Content-Length")) {
1437 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1438 * and Content-Length are received, the latter MUST be
1441 * To help mitigate HTTP Splitting, unset Content-Length
1442 * and shut down the backend server connection
1443 * XXX: We aught to treat such a response as uncachable
1445 apr_table_unset(r->headers_out, "Content-Length");
1446 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1447 "proxy: server %s returned Transfer-Encoding"
1448 " and Content-Length", backend->hostname);
1449 backend->close += 1;
1452 /* strip connection listed hop-by-hop headers from response */
1453 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1456 ap_proxy_clear_connection(p, r->headers_out);
1457 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1458 ap_set_content_type(r, apr_pstrdup(p, buf));
1460 ap_proxy_pre_http_request(origin,rp);
1462 /* Clear hop-by-hop headers */
1463 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1464 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1466 /* Delete warnings with wrong date */
1467 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1469 /* handle Via header in response */
1470 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1471 const char *server_name = ap_get_server_name(r);
1472 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1473 * then the server name returned by ap_get_server_name() is the
1474 * origin server name (which does make too much sense with Via: headers)
1475 * so we use the proxy vhost's name instead.
1477 if (server_name == r->hostname)
1478 server_name = r->server->server_hostname;
1479 /* create a "Via:" response header entry and merge it */
1480 apr_table_addn(r->headers_out, "Via",
1481 (conf->viaopt == via_full)
1482 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1483 HTTP_VERSION_MAJOR(r->proto_num),
1484 HTTP_VERSION_MINOR(r->proto_num),
1487 AP_SERVER_BASEVERSION)
1488 : apr_psprintf(p, "%d.%d %s%s",
1489 HTTP_VERSION_MAJOR(r->proto_num),
1490 HTTP_VERSION_MINOR(r->proto_num),
1496 /* cancel keepalive if HTTP/1.0 or less */
1497 if ((major < 1) || (minor < 1)) {
1498 backend->close += 1;
1499 origin->keepalive = AP_CONN_CLOSE;
1502 /* an http/0.9 response */
1505 r->status_line = "200 OK";
1506 backend->close += 1;
1509 interim_response = ap_is_HTTP_INFO(r->status);
1510 if (interim_response) {
1511 /* RFC2616 tells us to forward this.
1513 * OTOH, an interim response here may mean the backend
1514 * is playing sillybuggers. The Client didn't ask for
1515 * it within the defined HTTP/1.1 mechanisms, and if
1516 * it's an extension, it may also be unsupported by us.
1518 * There's also the possibility that changing existing
1519 * behaviour here might break something.
1521 * So let's make it configurable.
1523 const char *policy = apr_table_get(r->subprocess_env,
1524 "proxy-interim-response");
1525 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1526 "proxy: HTTP: received interim %d response",
1528 if (!policy || !strcasecmp(policy, "RFC")) {
1529 ap_send_interim_response(r);
1531 /* FIXME: refine this to be able to specify per-response-status
1532 * policies and maybe also add option to bail out with 502
1534 else if (strcasecmp(policy, "Suppress")) {
1535 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1536 "undefined proxy interim response policy");
1539 /* Moved the fixups of Date headers and those affected by
1540 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1543 if ((r->status == 401) && (conf->error_override)) {
1545 const char *wa = "WWW-Authenticate";
1546 if ((buf = apr_table_get(r->headers_out, wa))) {
1547 apr_table_set(r->err_headers_out, wa, buf);
1549 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1550 "proxy: origin server sent 401 without WWW-Authenticate header");
1556 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1557 * the response? If so, load the extra data. These are 2 mutually
1558 * exclusive possibilities, that just happen to require very
1561 if (backasswards || pread_len) {
1562 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1565 * At this point in response processing of a 0.9 response,
1566 * we don't know yet whether data is binary or not.
1567 * mod_charset_lite will get control later on, so it cannot
1568 * decide on the conversion of this buffer full of data.
1569 * However, chances are that we are not really talking to an
1570 * HTTP/0.9 server, but to some different protocol, therefore
1571 * the best guess IMHO is to always treat the buffer as "text/x":
1573 ap_xlate_proto_to_ascii(buffer, len);
1574 cntr = (apr_ssize_t)len;
1576 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1577 APR_BRIGADE_INSERT_TAIL(bb, e);
1580 /* send body - but only if a body is expected */
1581 if ((!r->header_only) && /* not HEAD request */
1582 !interim_response && /* not any 1xx response */
1583 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1584 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1586 /* We need to copy the output headers and treat them as input
1587 * headers as well. BUT, we need to do this before we remove
1588 * TE, so that they are preserved accordingly for
1589 * ap_http_filter to know where to end.
1591 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1593 apr_table_unset(r->headers_out,"Transfer-Encoding");
1595 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1596 "proxy: start body send");
1599 * if we are overriding the errors, we can't put the content
1600 * of the page into the brigade
1602 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1603 /* read the body, pass it to the output filters */
1604 apr_read_type_e mode = APR_NONBLOCK_READ;
1608 apr_off_t readbytes;
1611 rv = ap_get_brigade(rp->input_filters, bb,
1612 AP_MODE_READBYTES, mode,
1613 conf->io_buffer_size);
1615 /* ap_get_brigade will return success with an empty brigade
1616 * for a non-blocking read which would block: */
1617 if (APR_STATUS_IS_EAGAIN(rv)
1618 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1619 /* flush to the client and switch to blocking mode */
1620 e = apr_bucket_flush_create(c->bucket_alloc);
1621 APR_BRIGADE_INSERT_TAIL(bb, e);
1622 if (ap_pass_brigade(r->output_filters, bb)
1627 apr_brigade_cleanup(bb);
1628 mode = APR_BLOCK_READ;
1631 else if (rv == APR_EOF) {
1634 else if (rv != APR_SUCCESS) {
1635 /* In this case, we are in real trouble because
1636 * our backend bailed on us. Pass along a 502 error
1639 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1640 "proxy: error reading response");
1641 ap_proxy_backend_broke(r, bb);
1642 ap_pass_brigade(r->output_filters, bb);
1647 /* next time try a non-blocking read */
1648 mode = APR_NONBLOCK_READ;
1650 apr_brigade_length(bb, 0, &readbytes);
1651 backend->worker->s->read += readbytes;
1654 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1655 r->server, "proxy (PID %d): readbytes: %#x",
1656 getpid(), readbytes);
1660 if (APR_BRIGADE_EMPTY(bb)) {
1661 apr_brigade_cleanup(bb);
1665 /* found the last brigade? */
1666 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1667 /* signal that we must leave */
1671 /* try send what we read */
1672 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1674 /* Ack! Phbtt! Die! User aborted! */
1675 backend->close = 1; /* this causes socket close below */
1679 /* make sure we always clean up after ourselves */
1680 apr_brigade_cleanup(bb);
1684 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1685 "proxy: end body send");
1687 else if (!interim_response) {
1688 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1689 "proxy: header only");
1691 /* Pass EOS bucket down the filter chain. */
1692 e = apr_bucket_eos_create(c->bucket_alloc);
1693 APR_BRIGADE_INSERT_TAIL(bb, e);
1694 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1696 /* Ack! Phbtt! Die! User aborted! */
1697 backend->close = 1; /* this causes socket close below */
1700 apr_brigade_cleanup(bb);
1702 } while (interim_response);
1704 /* If our connection with the client is to be aborted, return DONE. */
1705 if (c->aborted || backend_broke) {
1709 if (conf->error_override) {
1710 /* the code above this checks for 'OK' which is what the hook expects */
1711 if (!ap_is_HTTP_ERROR(r->status))
1714 /* clear r->status for override error, otherwise ErrorDocument
1715 * thinks that this is a recursive error, and doesn't find the
1718 int status = r->status;
1719 r->status = HTTP_OK;
1720 /* Discard body, if one is expected */
1721 if (!r->header_only && /* not HEAD request */
1722 (status != HTTP_NO_CONTENT) && /* not 204 */
1723 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1724 ap_discard_request_body(rp);
1733 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1734 proxy_conn_rec *backend)
1736 ap_proxy_release_connection(scheme, backend, r->server);
1741 * This handles http:// URLs, and other URLs using a remote proxy over http
1742 * If proxyhost is NULL, then contact the server directly, otherwise
1744 * Note that if a proxy is used, then URLs other than http: can be accessed,
1745 * also, if we have trouble which is clearly specific to the proxy, then
1746 * we return DECLINED so that we can try another proxy. (Or the direct
1749 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1750 proxy_server_conf *conf,
1751 char *url, const char *proxyname,
1752 apr_port_t proxyport)
1755 char server_portstr[32];
1757 const char *proxy_function;
1759 proxy_conn_rec *backend = NULL;
1762 /* Note: Memory pool allocation.
1763 * A downstream keepalive connection is always connected to the existence
1764 * (or not) of an upstream keepalive connection. If this is not done then
1765 * load balancing against multiple backend servers breaks (one backend
1766 * server ends up taking 100% of the load), and the risk is run of
1767 * downstream keepalive connections being kept open unnecessarily. This
1768 * keeps webservers busy and ties up resources.
1770 * As a result, we allocate all sockets out of the upstream connection
1771 * pool, and when we want to reuse a socket, we check first whether the
1772 * connection ID of the current upstream connection is the same as that
1773 * of the connection when the socket was opened.
1775 apr_pool_t *p = r->connection->pool;
1776 conn_rec *c = r->connection;
1777 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1779 /* find the scheme */
1780 u = strchr(url, ':');
1781 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1784 return HTTP_BAD_REQUEST;
1785 scheme = apr_pstrndup(c->pool, url, u - url);
1786 /* scheme is lowercase */
1787 ap_str_tolower(scheme);
1789 if (strcmp(scheme, "https") == 0) {
1790 if (!ap_proxy_ssl_enable(NULL)) {
1791 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1792 "proxy: HTTPS: declining URL %s"
1793 " (mod_ssl not configured?)", url);
1797 proxy_function = "HTTPS";
1799 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1800 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1801 "proxy: HTTP: declining URL %s", url);
1802 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1806 proxy_function = "HTTP";
1808 proxy_function = "FTP";
1810 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1811 "proxy: HTTP: serving URL %s", url);
1814 /* create space for state information */
1815 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1816 worker, r->server)) != OK)
1820 backend->is_ssl = is_ssl;
1822 * TODO: Currently we cannot handle persistent SSL backend connections,
1823 * because we recreate backend->connection for each request and thus
1824 * try to initialize an already existing SSL connection. This does
1830 /* Step One: Determine Who To Connect To */
1831 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1832 uri, &url, proxyname,
1833 proxyport, server_portstr,
1834 sizeof(server_portstr))) != OK)
1837 /* Step Two: Make the Connection */
1838 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1839 if (r->proxyreq == PROXYREQ_PROXY)
1840 status = HTTP_NOT_FOUND;
1842 status = HTTP_SERVICE_UNAVAILABLE;
1846 /* Step Three: Create conn_rec */
1847 if (!backend->connection) {
1848 if ((status = ap_proxy_connection_create(proxy_function, backend,
1849 c, r->server)) != OK)
1853 /* Step Four: Send the Request */
1854 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1855 conf, uri, url, server_portstr)) != OK)
1858 /* Step Five: Receive the Response */
1859 if ((status = ap_proxy_http_process_response(p, r, backend,
1860 backend->connection,
1861 conf, server_portstr)) != OK)
1864 /* Step Six: Clean Up */
1870 ap_proxy_http_cleanup(proxy_function, r, backend);
1874 static apr_status_t warn_rx_free(void *p)
1876 ap_pregfree((apr_pool_t*)p, warn_rx);
1879 static void ap_proxy_http_register_hook(apr_pool_t *p)
1881 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1882 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1883 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1884 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1887 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1888 STANDARD20_MODULE_STUFF,
1889 NULL, /* create per-directory config structure */
1890 NULL, /* merge per-directory config structures */
1891 NULL, /* create per-server config structure */
1892 NULL, /* merge per-server config structures */
1893 NULL, /* command apr_table_t */
1894 ap_proxy_http_register_hook/* register hooks */