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"
21 module AP_MODULE_DECLARE_DATA proxy_http_module;
23 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
25 proxy_conn_rec *backend);
28 * Canonicalise http-like URLs.
29 * scheme is the scheme for the URL
30 * url is the URL starting with the first '/'
31 * def_port is the default port for this scheme.
33 static int proxy_http_canon(request_rec *r, char *url)
35 char *host, *path, *search, sport[7];
38 apr_port_t port, def_port;
40 const char *allowed = "~$-_.+!*'(),;:@&=/"; /* allowed+reserved from
43 /* ap_port_of_scheme() */
44 if (strncasecmp(url, "http:", 5) == 0) {
48 else if (strncasecmp(url, "https:", 6) == 0) {
55 def_port = apr_uri_port_of_scheme(scheme);
57 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
58 "proxy: HTTP: canonicalising URL %s", url);
61 * We break the URL into host, port, path, search
64 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
66 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
67 "error parsing URL %s: %s",
69 return HTTP_BAD_REQUEST;
72 /* now parse path/search args, according to rfc1738 */
73 /* N.B. if this isn't a true proxy request, then the URL _path_
74 * has already been decoded. True proxy requests have r->uri
75 * == r->unparsed_uri, and no others have that property.
77 if (r->uri == r->unparsed_uri) {
78 search = strchr(url, '?');
86 /* In a reverse proxy, our URL has been processed, so canonicalise
87 * In a forward proxy, we have and MUST NOT MANGLE the original,
88 * so just check it for disallowed chars.
90 switch (r->proxyreq) {
91 default: /* wtf are we doing here? */
92 case PROXYREQ_REVERSE:
93 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
96 for (p = url; *p; ++p) {
97 if (!apr_isalnum(*p) && !strchr(allowed, *p)) {
98 if (*p == '%' && apr_isxdigit(p[1]) && apr_isxdigit(p[2])) {
99 p += 2; /* an encoded char */
102 return HTTP_BAD_REQUEST; /* reject bad char in URL */
111 return HTTP_BAD_REQUEST;
113 if (port != def_port)
114 apr_snprintf(sport, sizeof(sport), ":%d", port);
118 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
119 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
121 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
122 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
126 /* Clear all connection-based headers from the incoming headers table */
127 typedef struct header_dptr {
132 static ap_regex_t *warn_rx;
133 static int clean_warning_headers(void *data, const char *key, const char *val)
135 apr_table_t *headers = ((header_dptr*)data)->table;
136 apr_pool_t *pool = ((header_dptr*)data)->pool;
139 apr_time_t warn_time;
140 const int nmatch = 3;
141 ap_regmatch_t pmatch[3];
143 if (headers == NULL) {
144 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
147 * Parse this, suckers!
149 * Warning = "Warning" ":" 1#warning-value
151 * warning-value = warn-code SP warn-agent SP warn-text
155 * warn-agent = ( host [ ":" port ] ) | pseudonym
156 * ; the name or pseudonym of the server adding
157 * ; the Warning header, for use in debugging
158 * warn-text = quoted-string
159 * warn-date = <"> HTTP-date <">
161 * Buggrit, use a bloomin' regexp!
162 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
164 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
165 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
166 pmatch[0].rm_eo - pmatch[0].rm_so);
168 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
169 /* OK, we have a date here */
170 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
171 pmatch[2].rm_eo - pmatch[2].rm_so);
172 warn_time = apr_date_parse_http(date);
174 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
175 apr_table_addn(headers, key, warning);
177 val += pmatch[0].rm_eo;
181 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
186 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
187 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
188 if (x.table != NULL) {
189 apr_table_unset(headers, "Warning");
190 return apr_table_overlay(p, headers, x.table);
196 static int clear_conn_headers(void *data, const char *key, const char *val)
198 apr_table_t *headers = ((header_dptr*)data)->table;
199 apr_pool_t *pool = ((header_dptr*)data)->pool;
201 char *next = apr_pstrdup(pool, val);
204 while (*next && !apr_isspace(*next) && (*next != ',')) {
207 while (*next && (apr_isspace(*next) || (*next == ','))) {
210 apr_table_unset(headers, name);
214 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
219 apr_table_unset(headers, "Proxy-Connection");
220 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
221 apr_table_unset(headers, "Connection");
223 static void add_te_chunked(apr_pool_t *p,
224 apr_bucket_alloc_t *bucket_alloc,
225 apr_bucket_brigade *header_brigade)
229 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
231 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
232 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
234 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
235 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
238 static void add_cl(apr_pool_t *p,
239 apr_bucket_alloc_t *bucket_alloc,
240 apr_bucket_brigade *header_brigade,
246 buf = apr_pstrcat(p, "Content-Length: ",
250 ap_xlate_proto_to_ascii(buf, strlen(buf));
251 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
252 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
255 #define ASCII_CRLF "\015\012"
256 #define ASCII_ZERO "\060"
258 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
259 apr_bucket_brigade *header_brigade)
263 /* add empty line at the end of the headers */
264 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
265 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
268 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
269 request_rec *r, proxy_conn_rec *conn,
270 conn_rec *origin, apr_bucket_brigade *bb,
274 apr_off_t transferred;
277 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
278 APR_BRIGADE_INSERT_TAIL(bb, e);
280 apr_brigade_length(bb, 0, &transferred);
281 if (transferred != -1)
282 conn->worker->s->transferred += transferred;
283 status = ap_pass_brigade(origin->output_filters, bb);
284 if (status != APR_SUCCESS) {
285 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
286 "proxy: pass request body failed to %pI (%s)",
287 conn->addr, conn->hostname);
290 apr_brigade_cleanup(bb);
294 #define MAX_MEM_SPOOL 16384
296 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
298 proxy_conn_rec *p_conn,
300 apr_bucket_brigade *header_brigade,
301 apr_bucket_brigade *input_brigade)
307 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
308 apr_bucket_brigade *bb;
311 add_te_chunked(p, bucket_alloc, header_brigade);
312 terminate_headers(bucket_alloc, header_brigade);
314 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
316 char chunk_hdr[20]; /* must be here due to transient bucket. */
318 /* If this brigade contains EOS, either stop or remove it. */
319 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
322 /* We can't pass this EOS to the output_filters. */
323 e = APR_BRIGADE_LAST(input_brigade);
324 apr_bucket_delete(e);
327 apr_brigade_length(input_brigade, 1, &bytes);
329 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
330 "%" APR_UINT64_T_HEX_FMT CRLF,
331 (apr_uint64_t)bytes);
333 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
334 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
336 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
339 * Append the end-of-chunk CRLF
341 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
342 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
344 if (header_brigade) {
345 /* we never sent the header brigade, so go ahead and
346 * take care of that now
351 * Save input_brigade in bb brigade. (At least) in the SSL case
352 * input_brigade contains transient buckets whose data would get
353 * overwritten during the next call of ap_get_brigade in the loop.
354 * ap_save_brigade ensures these buckets to be set aside.
355 * Calling ap_save_brigade with NULL as filter is OK, because
356 * bb brigade already has been created and does not need to get
357 * created by ap_save_brigade.
359 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
360 if (status != APR_SUCCESS) {
364 header_brigade = NULL;
370 /* The request is flushed below this loop with chunk EOS header */
371 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
372 if (status != APR_SUCCESS) {
380 status = ap_get_brigade(r->input_filters, input_brigade,
381 AP_MODE_READBYTES, APR_BLOCK_READ,
384 if (status != APR_SUCCESS) {
389 if (header_brigade) {
390 /* we never sent the header brigade because there was no request body;
396 if (!APR_BRIGADE_EMPTY(input_brigade)) {
397 /* input brigade still has an EOS which we can't pass to the output_filters. */
398 e = APR_BRIGADE_LAST(input_brigade);
399 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
400 apr_bucket_delete(e);
405 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
409 APR_BRIGADE_INSERT_TAIL(bb, e);
411 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
412 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
413 APR_BRIGADE_INSERT_TAIL(bb, e);
416 /* Now we have headers-only, or the chunk EOS mark; flush it */
417 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
421 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
423 proxy_conn_rec *p_conn,
425 apr_bucket_brigade *header_brigade,
426 apr_bucket_brigade *input_brigade,
427 const char *old_cl_val)
430 apr_status_t status = APR_SUCCESS;
431 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
432 apr_bucket_brigade *bb;
434 apr_off_t cl_val = 0;
436 apr_off_t bytes_streamed = 0;
439 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
440 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
445 terminate_headers(bucket_alloc, header_brigade);
447 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
449 apr_brigade_length(input_brigade, 1, &bytes);
450 bytes_streamed += bytes;
452 /* If this brigade contains EOS, either stop or remove it. */
453 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
456 /* We can't pass this EOS to the output_filters. */
457 e = APR_BRIGADE_LAST(input_brigade);
458 apr_bucket_delete(e);
460 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
461 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
462 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
466 /* C-L < bytes streamed?!?
467 * We will error out after the body is completely
468 * consumed, but we can't stream more bytes at the
469 * back end since they would in part be interpreted
470 * as another request! If nothing is sent, then
473 * Prevents HTTP Response Splitting.
475 if (bytes_streamed > cl_val)
478 if (header_brigade) {
479 /* we never sent the header brigade, so go ahead and
480 * take care of that now
485 * Save input_brigade in bb brigade. (At least) in the SSL case
486 * input_brigade contains transient buckets whose data would get
487 * overwritten during the next call of ap_get_brigade in the loop.
488 * ap_save_brigade ensures these buckets to be set aside.
489 * Calling ap_save_brigade with NULL as filter is OK, because
490 * bb brigade already has been created and does not need to get
491 * created by ap_save_brigade.
493 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
494 if (status != APR_SUCCESS) {
498 header_brigade = NULL;
504 /* Once we hit EOS, we are ready to flush. */
505 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
506 if (status != APR_SUCCESS) {
514 status = ap_get_brigade(r->input_filters, input_brigade,
515 AP_MODE_READBYTES, APR_BLOCK_READ,
518 if (status != APR_SUCCESS) {
523 if (bytes_streamed != cl_val) {
524 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
525 "proxy: client %s given Content-Length did not match"
526 " number of body bytes read", r->connection->remote_ip);
530 if (header_brigade) {
531 /* we never sent the header brigade since there was no request
532 * body; send it now with the flush flag
535 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
540 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
542 proxy_conn_rec *p_conn,
544 apr_bucket_brigade *header_brigade,
545 apr_bucket_brigade *input_brigade,
550 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
551 apr_bucket_brigade *body_brigade;
553 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
554 apr_file_t *tmpfile = NULL;
556 body_brigade = apr_brigade_create(p, bucket_alloc);
558 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
560 /* If this brigade contains EOS, either stop or remove it. */
561 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
564 /* We can't pass this EOS to the output_filters. */
565 e = APR_BRIGADE_LAST(input_brigade);
566 apr_bucket_delete(e);
569 apr_brigade_length(input_brigade, 1, &bytes);
571 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
572 /* can't spool any more in memory; write latest brigade to disk */
573 if (tmpfile == NULL) {
574 const char *temp_dir;
577 status = apr_temp_dir_get(&temp_dir, p);
578 if (status != APR_SUCCESS) {
579 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
580 "proxy: search for temporary directory failed");
583 apr_filepath_merge(&template, temp_dir,
584 "modproxy.tmp.XXXXXX",
585 APR_FILEPATH_NATIVE, p);
586 status = apr_file_mktemp(&tmpfile, template, 0, p);
587 if (status != APR_SUCCESS) {
588 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
589 "proxy: creation of temporary file in directory %s failed",
594 for (e = APR_BRIGADE_FIRST(input_brigade);
595 e != APR_BRIGADE_SENTINEL(input_brigade);
596 e = APR_BUCKET_NEXT(e)) {
598 apr_size_t bytes_read, bytes_written;
600 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
601 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
602 if (status != APR_SUCCESS) {
603 const char *tmpfile_name;
605 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
606 tmpfile_name = "(unknown)";
608 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
609 "proxy: write to temporary file %s failed",
613 AP_DEBUG_ASSERT(bytes_read == bytes_written);
614 fsize += bytes_written;
616 apr_brigade_cleanup(input_brigade);
621 * Save input_brigade in body_brigade. (At least) in the SSL case
622 * input_brigade contains transient buckets whose data would get
623 * overwritten during the next call of ap_get_brigade in the loop.
624 * ap_save_brigade ensures these buckets to be set aside.
625 * Calling ap_save_brigade with NULL as filter is OK, because
626 * body_brigade already has been created and does not need to get
627 * created by ap_save_brigade.
629 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
630 if (status != APR_SUCCESS) {
636 bytes_spooled += bytes;
642 status = ap_get_brigade(r->input_filters, input_brigade,
643 AP_MODE_READBYTES, APR_BLOCK_READ,
646 if (status != APR_SUCCESS) {
651 if (bytes_spooled || force_cl) {
652 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
654 terminate_headers(bucket_alloc, header_brigade);
655 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
657 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
659 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
660 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
661 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
663 /* This is all a single brigade, pass with flush flagged */
664 status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
669 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
670 proxy_conn_rec *p_conn, conn_rec *origin,
671 proxy_server_conf *conf,
673 char *url, char *server_portstr)
675 conn_rec *c = r->connection;
676 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
677 apr_bucket_brigade *header_brigade;
678 apr_bucket_brigade *input_brigade;
679 apr_bucket_brigade *temp_brigade;
682 const apr_array_header_t *headers_in_array;
683 const apr_table_entry_t *headers_in;
686 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
687 enum rb_methods rb_method = RB_INIT;
688 const char *old_cl_val = NULL;
689 const char *old_te_val = NULL;
690 apr_off_t bytes_read = 0;
693 apr_table_t *headers_in_copy;
695 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
698 * Send the HTTP/1.1 request to the remote server
701 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
702 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
706 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
709 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
710 origin->keepalive = AP_CONN_CLOSE;
713 ap_xlate_proto_to_ascii(buf, strlen(buf));
714 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
715 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
716 if (conf->preserve_host == 0) {
717 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
718 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
721 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
725 /* don't want to use r->hostname, as the incoming header might have a
728 const char* hostname = apr_table_get(r->headers_in,"Host");
730 hostname = r->server->server_hostname;
731 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
732 "proxy: no HTTP 0.9 request (with no host line) "
733 "on incoming request and preserve host set "
734 "forcing hostname to be %s for uri %s",
738 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
740 ap_xlate_proto_to_ascii(buf, strlen(buf));
741 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
742 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
745 if (conf->viaopt == via_block) {
746 /* Block all outgoing Via: headers */
747 apr_table_unset(r->headers_in, "Via");
748 } else if (conf->viaopt != via_off) {
749 const char *server_name = ap_get_server_name(r);
750 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
751 * then the server name returned by ap_get_server_name() is the
752 * origin server name (which does make too much sense with Via: headers)
753 * so we use the proxy vhost's name instead.
755 if (server_name == r->hostname)
756 server_name = r->server->server_hostname;
757 /* Create a "Via:" request header entry and merge it */
758 /* Generate outgoing Via: header with/without server comment: */
759 apr_table_mergen(r->headers_in, "Via",
760 (conf->viaopt == via_full)
761 ? apr_psprintf(p, "%d.%d %s%s (%s)",
762 HTTP_VERSION_MAJOR(r->proto_num),
763 HTTP_VERSION_MINOR(r->proto_num),
764 server_name, server_portstr,
765 AP_SERVER_BASEVERSION)
766 : apr_psprintf(p, "%d.%d %s%s",
767 HTTP_VERSION_MAJOR(r->proto_num),
768 HTTP_VERSION_MINOR(r->proto_num),
769 server_name, server_portstr)
773 /* X-Forwarded-*: handling
778 * These request headers are only really useful when the mod_proxy
779 * is used in a reverse proxy configuration, so that useful info
780 * about the client can be passed through the reverse proxy and on
781 * to the backend server, which may require the information to
784 * In a forward proxy situation, these options are a potential
785 * privacy violation, as information about clients behind the proxy
786 * are revealed to arbitrary servers out there on the internet.
788 * The HTTP/1.1 Via: header is designed for passing client
789 * information through proxies to a server, and should be used in
790 * a forward proxy configuation instead of X-Forwarded-*. See the
791 * ProxyVia option for details.
794 if (PROXYREQ_REVERSE == r->proxyreq) {
797 /* Add X-Forwarded-For: so that the upstream has a chance to
798 * determine, where the original request came from.
800 apr_table_mergen(r->headers_in, "X-Forwarded-For",
803 /* Add X-Forwarded-Host: so that upstream knows what the
804 * original request hostname was.
806 if ((buf = apr_table_get(r->headers_in, "Host"))) {
807 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
810 /* Add X-Forwarded-Server: so that upstream knows what the
811 * name of this proxy server is (if there are more than one)
812 * XXX: This duplicates Via: - do we strictly need it?
814 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
815 r->server->server_hostname);
820 * Make a copy of the headers_in table before clearing the connection
821 * headers as we need the connection headers later in the http output
822 * filter to prepare the correct response headers.
824 * Note: We need to take r->pool for apr_table_copy as the key / value
825 * pairs in r->headers_in have been created out of r->pool and
826 * p might be (and actually is) a longer living pool.
827 * This would trigger the bad pool ancestry abort in apr_table_copy if
828 * apr is compiled with APR_POOL_DEBUG.
830 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
831 ap_proxy_clear_connection(p, headers_in_copy);
832 /* send request headers */
833 headers_in_array = apr_table_elts(headers_in_copy);
834 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
835 for (counter = 0; counter < headers_in_array->nelts; counter++) {
836 if (headers_in[counter].key == NULL
837 || headers_in[counter].val == NULL
840 || !strcasecmp(headers_in[counter].key, "Host")
842 /* Clear out hop-by-hop request headers not to send
843 * RFC2616 13.5.1 says we should strip these headers
845 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
846 || !strcasecmp(headers_in[counter].key, "TE")
847 || !strcasecmp(headers_in[counter].key, "Trailer")
848 || !strcasecmp(headers_in[counter].key, "Upgrade")
853 /* Do we want to strip Proxy-Authorization ?
854 * If we haven't used it, then NO
855 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
856 * So let's make it configurable by env.
858 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
859 if (r->user != NULL) { /* we've authenticated */
860 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
867 /* Skip Transfer-Encoding and Content-Length for now.
869 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
870 old_te_val = headers_in[counter].val;
873 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
874 old_cl_val = headers_in[counter].val;
878 /* for sub-requests, ignore freshness/expiry headers */
880 if ( !strcasecmp(headers_in[counter].key, "If-Match")
881 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
882 || !strcasecmp(headers_in[counter].key, "If-Range")
883 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
884 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
889 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
890 headers_in[counter].val, CRLF,
892 ap_xlate_proto_to_ascii(buf, strlen(buf));
893 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
894 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
897 /* We have headers, let's figure out our request body... */
898 input_brigade = apr_brigade_create(p, bucket_alloc);
900 /* sub-requests never use keepalives, and mustn't pass request bodies.
901 * Because the new logic looks at input_brigade, we will self-terminate
902 * input_brigade and jump past all of the request body logic...
903 * Reading anything with ap_get_brigade is likely to consume the
904 * main request's body or read beyond EOS - which would be unplesant.
907 /* XXX: Why DON'T sub-requests use keepalives? */
911 apr_table_unset(r->headers_in, "Content-Length");
915 apr_table_unset(r->headers_in, "Transfer-Encoding");
917 rb_method = RB_STREAM_CL;
918 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
919 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
923 /* WE only understand chunked. Other modules might inject
924 * (and therefore, decode) other flavors but we don't know
925 * that the can and have done so unless they they remove
926 * their decoding from the headers_in T-E list.
927 * XXX: Make this extensible, but in doing so, presume the
928 * encoding has been done by the extensions' handler, and
929 * do not modify add_te_chunked's logic
931 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
932 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
933 "proxy: %s Transfer-Encoding is not supported",
938 if (old_cl_val && old_te_val) {
939 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
940 "proxy: client %s (%s) requested Transfer-Encoding "
941 "chunked body with Content-Length (C-L ignored)",
942 c->remote_ip, c->remote_host ? c->remote_host: "");
943 apr_table_unset(r->headers_in, "Content-Length");
945 origin->keepalive = AP_CONN_CLOSE;
949 /* Prefetch MAX_MEM_SPOOL bytes
951 * This helps us avoid any election of C-L v.s. T-E
952 * request bodies, since we are willing to keep in
953 * memory this much data, in any case. This gives
954 * us an instant C-L election if the body is of some
957 temp_brigade = apr_brigade_create(p, bucket_alloc);
959 status = ap_get_brigade(r->input_filters, temp_brigade,
960 AP_MODE_READBYTES, APR_BLOCK_READ,
961 MAX_MEM_SPOOL - bytes_read);
962 if (status != APR_SUCCESS) {
963 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
964 "proxy: prefetch request body failed to %pI (%s)"
966 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
967 c->remote_ip, c->remote_host ? c->remote_host: "");
971 apr_brigade_length(temp_brigade, 1, &bytes);
975 * Save temp_brigade in input_brigade. (At least) in the SSL case
976 * temp_brigade contains transient buckets whose data would get
977 * overwritten during the next call of ap_get_brigade in the loop.
978 * ap_save_brigade ensures these buckets to be set aside.
979 * Calling ap_save_brigade with NULL as filter is OK, because
980 * input_brigade already has been created and does not need to get
981 * created by ap_save_brigade.
983 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
984 if (status != APR_SUCCESS) {
985 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
986 "proxy: processing prefetched request body failed"
987 " to %pI (%s) from %s (%s)",
988 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
989 c->remote_ip, c->remote_host ? c->remote_host: "");
993 /* Ensure we don't hit a wall where we have a buffer too small
994 * for ap_get_brigade's filters to fetch us another bucket,
995 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
996 * (an arbitrary value.)
998 } while ((bytes_read < MAX_MEM_SPOOL - 80)
999 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1001 /* Use chunked request body encoding or send a content-length body?
1005 * We have no request body (handled by RB_STREAM_CL)
1007 * We have a request body length <= MAX_MEM_SPOOL
1009 * The administrator has setenv force-proxy-request-1.0
1011 * The client sent a C-L body, and the administrator has
1012 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1014 * The client sent a T-E body, and the administrator has
1015 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1017 * If both proxy-sendcl and proxy-sendchunked are set, the
1018 * behavior is the same as if neither were set, large bodies
1019 * that can't be read will be forwarded in their original
1020 * form of C-L, or T-E.
1022 * To ensure maximum compatibility, setenv proxy-sendcl
1023 * To reduce server resource use, setenv proxy-sendchunked
1025 * Then address specific servers with conditional setenv
1026 * options to restore the default behavior where desireable.
1028 * We have to compute content length by reading the entire request
1029 * body; if request body is not small, we'll spool the remaining
1030 * input to a temporary file. Chunked is always preferable.
1032 * We can only trust the client-provided C-L if the T-E header
1033 * is absent, and the filters are unchanged (the body won't
1034 * be resized by another content filter).
1036 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1037 /* The whole thing fit, so our decision is trivial, use
1038 * the filtered bytes read from the client for the request
1039 * body Content-Length.
1041 * If we expected no body, and read no body, do not set
1042 * the Content-Length.
1044 if (old_cl_val || old_te_val || bytes_read) {
1045 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1047 rb_method = RB_STREAM_CL;
1049 else if (old_te_val) {
1051 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1052 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1053 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1054 rb_method = RB_SPOOL_CL;
1057 rb_method = RB_STREAM_CHUNKED;
1060 else if (old_cl_val) {
1061 if (r->input_filters == r->proto_input_filters) {
1062 rb_method = RB_STREAM_CL;
1065 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1066 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1067 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1068 rb_method = RB_STREAM_CHUNKED;
1071 rb_method = RB_SPOOL_CL;
1075 /* This is an appropriate default; very efficient for no-body
1076 * requests, and has the behavior that it will not add any C-L
1077 * when the old_cl_val is NULL.
1079 rb_method = RB_SPOOL_CL;
1082 /* Yes I hate gotos. This is the subrequest shortcut */
1085 * Handle Connection: header if we do HTTP/1.1 request:
1086 * If we plan to close the backend connection sent Connection: close
1087 * otherwise sent Connection: Keep-Alive.
1090 if (p_conn->close) {
1091 buf = apr_pstrdup(p, "Connection: close" CRLF);
1094 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1096 ap_xlate_proto_to_ascii(buf, strlen(buf));
1097 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1098 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1101 /* send the request body, if any. */
1103 case RB_STREAM_CHUNKED:
1104 status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1108 status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1109 input_brigade, old_cl_val);
1112 status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1113 input_brigade, (old_cl_val != NULL)
1114 || (old_te_val != NULL)
1115 || (bytes_read > 0));
1118 /* shouldn't be possible */
1119 status = APR_EINVAL;
1123 if (status != APR_SUCCESS) {
1124 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1125 "proxy: pass request body failed to %pI (%s)"
1128 p_conn->hostname ? p_conn->hostname: "",
1130 c->remote_host ? c->remote_host: "");
1137 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1138 const char *key, const char *value)
1140 static const char *date_hdrs[]
1141 = { "Date", "Expires", "Last-Modified", NULL };
1142 static const struct {
1144 ap_proxy_header_reverse_map_fn func;
1145 } transform_hdrs[] = {
1146 { "Location", ap_proxy_location_reverse_map },
1147 { "Content-Location", ap_proxy_location_reverse_map },
1148 { "URI", ap_proxy_location_reverse_map },
1149 { "Destination", ap_proxy_location_reverse_map },
1150 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1154 for (i = 0; date_hdrs[i]; ++i) {
1155 if (!strcasecmp(date_hdrs[i], key)) {
1156 apr_table_add(r->headers_out, key,
1157 ap_proxy_date_canon(r->pool, value));
1161 for (i = 0; transform_hdrs[i].name; ++i) {
1162 if (!strcasecmp(transform_hdrs[i].name, key)) {
1163 apr_table_add(r->headers_out, key,
1164 (*transform_hdrs[i].func)(r, c, value));
1168 apr_table_add(r->headers_out, key, value);
1173 * Note: pread_len is the length of the response that we've mistakenly
1174 * read (assuming that we don't consider that an error via
1175 * ProxyBadHeader StartBody). This depends on buffer actually being
1176 * local storage to the calling code in order for pread_len to make
1177 * any sense at all, since we depend on buffer still containing
1178 * what was read by ap_getline() upon return.
1180 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1181 char *buffer, int size,
1182 conn_rec *c, int *pread_len)
1186 char field[MAX_STRING_LEN];
1187 int saw_headers = 0;
1188 void *sconf = r->server->module_config;
1189 proxy_server_conf *psc;
1190 proxy_dir_conf *dconf;
1192 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1193 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1195 r->headers_out = apr_table_make(r->pool, 20);
1199 * Read header lines until we get the empty separator line, a read error,
1200 * the connection closes (EOF), or we timeout.
1202 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1204 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1206 /* We may encounter invalid headers, usually from buggy
1207 * MS IIS servers, so we need to determine just how to handle
1208 * them. We can either ignore them, assume that they mark the
1209 * start-of-body (eg: a missing CRLF) or (the default) mark
1210 * the headers as totally bogus and return a 500. The sole
1211 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1212 * in between the usual MIME headers, which is a favorite
1215 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1217 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1218 if (psc->badopt == bad_error) {
1219 /* Nope, it wasn't even an extra HTTP header. Give up. */
1220 r->headers_out = NULL;
1223 else if (psc->badopt == bad_body) {
1224 /* if we've already started loading headers_out, then
1225 * return what we've accumulated so far, in the hopes
1226 * that they are useful; also note that we likely pre-read
1227 * the first line of the response.
1230 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1231 "proxy: Starting body due to bogus non-header in headers "
1232 "returned by %s (%s)", r->uri, r->method);
1236 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1237 "proxy: No HTTP headers "
1238 "returned by %s (%s)", r->uri, r->method);
1243 /* this is the psc->badopt == bad_ignore case */
1244 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1245 "proxy: Ignoring bogus HTTP header "
1246 "returned by %s (%s)", r->uri, r->method);
1252 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1253 * wrong... and so are many others probably.
1255 while (apr_isspace(*value))
1256 ++value; /* Skip to start of value */
1258 /* should strip trailing whitespace as well */
1259 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1263 /* make sure we add so as not to destroy duplicated headers
1264 * Modify headers requiring canonicalisation and/or affected
1265 * by ProxyPassReverse and family with process_proxy_header
1267 process_proxy_header(r, dconf, buffer, value) ;
1270 /* the header was too long; at the least we should skip extra data */
1271 if (len >= size - 1) {
1272 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1273 >= MAX_STRING_LEN - 1) {
1274 /* soak up the extra data */
1276 if (len == 0) /* time to exit the larger loop as well */
1284 static int addit_dammit(void *v, const char *key, const char *val)
1286 apr_table_addn(v, key, val);
1291 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1292 int fold, int *writen)
1298 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1299 apr_brigade_cleanup(bb);
1301 if (rv == APR_SUCCESS) {
1302 *writen = (int) len;
1303 } else if (rv == APR_ENOSPC) {
1313 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1314 proxy_conn_rec *backend,
1316 proxy_server_conf *conf,
1317 char *server_portstr) {
1318 conn_rec *c = r->connection;
1319 char buffer[HUGE_STRING_LEN];
1324 apr_bucket_brigade *bb, *tmp_bb;
1325 int len, backasswards;
1326 int interim_response; /* non-zero whilst interim 1xx responses
1327 * are being read. */
1329 apr_table_t *save_table;
1330 int backend_broke = 0;
1331 static const char *hop_by_hop_hdrs[] =
1332 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1335 bb = apr_brigade_create(p, c->bucket_alloc);
1337 /* Get response from the remote server, and pass it up the
1341 rp = ap_proxy_make_fake_req(origin, r);
1342 /* In case anyone needs to know, this is a fake request that is really a
1345 rp->proxyreq = PROXYREQ_RESPONSE;
1346 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1350 apr_brigade_cleanup(bb);
1352 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1354 /* handle one potential stray CRLF */
1355 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1358 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1359 "proxy: error reading status line from remote "
1360 "server %s", backend->hostname);
1361 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1362 "Error reading from remote server");
1364 /* XXX: Is this a real headers length send from remote? */
1365 backend->worker->s->read += len;
1367 /* Is it an HTTP/1 response?
1368 * This is buggy if we ever see an HTTP/1.10
1370 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1373 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1377 /* If not an HTTP/1 message or
1378 * if the status line was > 8192 bytes
1380 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1381 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1382 apr_pstrcat(p, "Corrupt status line returned by remote "
1383 "server: ", buffer, NULL));
1387 keepchar = buffer[12];
1389 r->status = atoi(&buffer[9]);
1391 if (keepchar != '\0') {
1392 buffer[12] = keepchar;
1394 /* 2616 requires the space in Status-Line; the origin
1395 * server may have sent one but ap_rgetline_core will
1396 * have stripped it. */
1400 r->status_line = apr_pstrdup(p, &buffer[9]);
1403 /* read the headers. */
1404 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1405 /* Also, take care with headers with multiple occurences. */
1407 /* First, tuck away all already existing cookies */
1408 save_table = apr_table_make(r->pool, 2);
1409 apr_table_do(addit_dammit, save_table, r->headers_out,
1410 "Set-Cookie", NULL);
1412 /* shove the headers direct into r->headers_out */
1413 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1416 if (r->headers_out == NULL) {
1417 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1418 r->server, "proxy: bad HTTP/%d.%d header "
1419 "returned by %s (%s)", major, minor, r->uri,
1421 backend->close += 1;
1423 * ap_send_error relies on a headers_out to be present. we
1424 * are in a bad position here.. so force everything we send out
1425 * to have nothing to do with the incoming packet
1427 r->headers_out = apr_table_make(r->pool,1);
1428 r->status = HTTP_BAD_GATEWAY;
1429 r->status_line = "bad gateway";
1433 /* Now, add in the just read cookies */
1434 apr_table_do(addit_dammit, save_table, r->headers_out,
1435 "Set-Cookie", NULL);
1437 /* and now load 'em all in */
1438 if (!apr_is_empty_table(save_table)) {
1439 apr_table_unset(r->headers_out, "Set-Cookie");
1440 r->headers_out = apr_table_overlay(r->pool,
1445 /* can't have both Content-Length and Transfer-Encoding */
1446 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1447 && apr_table_get(r->headers_out, "Content-Length")) {
1449 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1450 * and Content-Length are received, the latter MUST be
1453 * To help mitigate HTTP Splitting, unset Content-Length
1454 * and shut down the backend server connection
1455 * XXX: We aught to treat such a response as uncachable
1457 apr_table_unset(r->headers_out, "Content-Length");
1458 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1459 "proxy: server %s returned Transfer-Encoding"
1460 " and Content-Length", backend->hostname);
1461 backend->close += 1;
1464 /* strip connection listed hop-by-hop headers from response */
1465 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1468 ap_proxy_clear_connection(p, r->headers_out);
1469 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1470 ap_set_content_type(r, apr_pstrdup(p, buf));
1472 ap_proxy_pre_http_request(origin,rp);
1474 /* Clear hop-by-hop headers */
1475 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1476 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1478 /* Delete warnings with wrong date */
1479 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1481 /* handle Via header in response */
1482 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1483 const char *server_name = ap_get_server_name(r);
1484 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1485 * then the server name returned by ap_get_server_name() is the
1486 * origin server name (which does make too much sense with Via: headers)
1487 * so we use the proxy vhost's name instead.
1489 if (server_name == r->hostname)
1490 server_name = r->server->server_hostname;
1491 /* create a "Via:" response header entry and merge it */
1492 apr_table_addn(r->headers_out, "Via",
1493 (conf->viaopt == via_full)
1494 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1495 HTTP_VERSION_MAJOR(r->proto_num),
1496 HTTP_VERSION_MINOR(r->proto_num),
1499 AP_SERVER_BASEVERSION)
1500 : apr_psprintf(p, "%d.%d %s%s",
1501 HTTP_VERSION_MAJOR(r->proto_num),
1502 HTTP_VERSION_MINOR(r->proto_num),
1508 /* cancel keepalive if HTTP/1.0 or less */
1509 if ((major < 1) || (minor < 1)) {
1510 backend->close += 1;
1511 origin->keepalive = AP_CONN_CLOSE;
1514 /* an http/0.9 response */
1517 r->status_line = "200 OK";
1518 backend->close += 1;
1521 interim_response = ap_is_HTTP_INFO(r->status);
1522 if (interim_response) {
1523 /* RFC2616 tells us to forward this.
1525 * OTOH, an interim response here may mean the backend
1526 * is playing sillybuggers. The Client didn't ask for
1527 * it within the defined HTTP/1.1 mechanisms, and if
1528 * it's an extension, it may also be unsupported by us.
1530 * There's also the possibility that changing existing
1531 * behaviour here might break something.
1533 * So let's make it configurable.
1535 const char *policy = apr_table_get(r->subprocess_env,
1536 "proxy-interim-response");
1537 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1538 "proxy: HTTP: received interim %d response",
1540 if (!policy || !strcasecmp(policy, "RFC")) {
1541 ap_send_interim_response(r);
1543 /* FIXME: refine this to be able to specify per-response-status
1544 * policies and maybe also add option to bail out with 502
1546 else if (strcasecmp(policy, "Suppress")) {
1547 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1548 "undefined proxy interim response policy");
1551 /* Moved the fixups of Date headers and those affected by
1552 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1555 if ((r->status == 401) && (conf->error_override)) {
1557 const char *wa = "WWW-Authenticate";
1558 if ((buf = apr_table_get(r->headers_out, wa))) {
1559 apr_table_set(r->err_headers_out, wa, buf);
1561 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1562 "proxy: origin server sent 401 without WWW-Authenticate header");
1568 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1569 * the response? If so, load the extra data. These are 2 mutually
1570 * exclusive possibilities, that just happen to require very
1573 if (backasswards || pread_len) {
1574 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1577 * At this point in response processing of a 0.9 response,
1578 * we don't know yet whether data is binary or not.
1579 * mod_charset_lite will get control later on, so it cannot
1580 * decide on the conversion of this buffer full of data.
1581 * However, chances are that we are not really talking to an
1582 * HTTP/0.9 server, but to some different protocol, therefore
1583 * the best guess IMHO is to always treat the buffer as "text/x":
1585 ap_xlate_proto_to_ascii(buffer, len);
1586 cntr = (apr_ssize_t)len;
1588 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1589 APR_BRIGADE_INSERT_TAIL(bb, e);
1592 /* send body - but only if a body is expected */
1593 if ((!r->header_only) && /* not HEAD request */
1594 !interim_response && /* not any 1xx response */
1595 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1596 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1598 /* We need to copy the output headers and treat them as input
1599 * headers as well. BUT, we need to do this before we remove
1600 * TE, so that they are preserved accordingly for
1601 * ap_http_filter to know where to end.
1603 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1605 apr_table_unset(r->headers_out,"Transfer-Encoding");
1607 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1608 "proxy: start body send");
1611 * if we are overriding the errors, we can't put the content
1612 * of the page into the brigade
1614 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1615 /* read the body, pass it to the output filters */
1616 apr_read_type_e mode = APR_NONBLOCK_READ;
1620 apr_off_t readbytes;
1623 rv = ap_get_brigade(rp->input_filters, bb,
1624 AP_MODE_READBYTES, mode,
1625 conf->io_buffer_size);
1627 /* ap_get_brigade will return success with an empty brigade
1628 * for a non-blocking read which would block: */
1629 if (APR_STATUS_IS_EAGAIN(rv)
1630 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1631 /* flush to the client and switch to blocking mode */
1632 e = apr_bucket_flush_create(c->bucket_alloc);
1633 APR_BRIGADE_INSERT_TAIL(bb, e);
1634 if (ap_pass_brigade(r->output_filters, bb)
1639 apr_brigade_cleanup(bb);
1640 mode = APR_BLOCK_READ;
1643 else if (rv == APR_EOF) {
1646 else if (rv != APR_SUCCESS) {
1647 /* In this case, we are in real trouble because
1648 * our backend bailed on us. Pass along a 502 error
1651 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1652 "proxy: error reading response");
1653 ap_proxy_backend_broke(r, bb);
1654 ap_pass_brigade(r->output_filters, bb);
1659 /* next time try a non-blocking read */
1660 mode = APR_NONBLOCK_READ;
1662 apr_brigade_length(bb, 0, &readbytes);
1663 backend->worker->s->read += readbytes;
1666 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1667 r->server, "proxy (PID %d): readbytes: %#x",
1668 getpid(), readbytes);
1672 if (APR_BRIGADE_EMPTY(bb)) {
1673 apr_brigade_cleanup(bb);
1677 /* found the last brigade? */
1678 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1679 /* signal that we must leave */
1683 /* try send what we read */
1684 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1686 /* Ack! Phbtt! Die! User aborted! */
1687 backend->close = 1; /* this causes socket close below */
1691 /* make sure we always clean up after ourselves */
1692 apr_brigade_cleanup(bb);
1696 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1697 "proxy: end body send");
1699 else if (!interim_response) {
1700 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1701 "proxy: header only");
1703 /* Pass EOS bucket down the filter chain. */
1704 e = apr_bucket_eos_create(c->bucket_alloc);
1705 APR_BRIGADE_INSERT_TAIL(bb, e);
1706 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1708 /* Ack! Phbtt! Die! User aborted! */
1709 backend->close = 1; /* this causes socket close below */
1712 apr_brigade_cleanup(bb);
1714 } while (interim_response);
1716 /* If our connection with the client is to be aborted, return DONE. */
1717 if (c->aborted || backend_broke) {
1721 if (conf->error_override) {
1722 /* the code above this checks for 'OK' which is what the hook expects */
1723 if (!ap_is_HTTP_ERROR(r->status))
1726 /* clear r->status for override error, otherwise ErrorDocument
1727 * thinks that this is a recursive error, and doesn't find the
1730 int status = r->status;
1731 r->status = HTTP_OK;
1732 /* Discard body, if one is expected */
1733 if (!r->header_only && /* not HEAD request */
1734 (status != HTTP_NO_CONTENT) && /* not 204 */
1735 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1736 ap_discard_request_body(rp);
1745 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1746 proxy_conn_rec *backend)
1748 ap_proxy_release_connection(scheme, backend, r->server);
1753 * This handles http:// URLs, and other URLs using a remote proxy over http
1754 * If proxyhost is NULL, then contact the server directly, otherwise
1756 * Note that if a proxy is used, then URLs other than http: can be accessed,
1757 * also, if we have trouble which is clearly specific to the proxy, then
1758 * we return DECLINED so that we can try another proxy. (Or the direct
1761 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1762 proxy_server_conf *conf,
1763 char *url, const char *proxyname,
1764 apr_port_t proxyport)
1767 char server_portstr[32];
1769 const char *proxy_function;
1771 proxy_conn_rec *backend = NULL;
1774 /* Note: Memory pool allocation.
1775 * A downstream keepalive connection is always connected to the existence
1776 * (or not) of an upstream keepalive connection. If this is not done then
1777 * load balancing against multiple backend servers breaks (one backend
1778 * server ends up taking 100% of the load), and the risk is run of
1779 * downstream keepalive connections being kept open unnecessarily. This
1780 * keeps webservers busy and ties up resources.
1782 * As a result, we allocate all sockets out of the upstream connection
1783 * pool, and when we want to reuse a socket, we check first whether the
1784 * connection ID of the current upstream connection is the same as that
1785 * of the connection when the socket was opened.
1787 apr_pool_t *p = r->connection->pool;
1788 conn_rec *c = r->connection;
1789 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1791 /* find the scheme */
1792 u = strchr(url, ':');
1793 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1796 return HTTP_BAD_REQUEST;
1797 scheme = apr_pstrndup(c->pool, url, u - url);
1798 /* scheme is lowercase */
1799 ap_str_tolower(scheme);
1801 if (strcmp(scheme, "https") == 0) {
1802 if (!ap_proxy_ssl_enable(NULL)) {
1803 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1804 "proxy: HTTPS: declining URL %s"
1805 " (mod_ssl not configured?)", url);
1809 proxy_function = "HTTPS";
1811 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1812 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1813 "proxy: HTTP: declining URL %s", url);
1814 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1818 proxy_function = "HTTP";
1820 proxy_function = "FTP";
1822 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1823 "proxy: HTTP: serving URL %s", url);
1826 /* create space for state information */
1827 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1828 worker, r->server)) != OK)
1832 backend->is_ssl = is_ssl;
1834 * TODO: Currently we cannot handle persistent SSL backend connections,
1835 * because we recreate backend->connection for each request and thus
1836 * try to initialize an already existing SSL connection. This does
1842 /* Step One: Determine Who To Connect To */
1843 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1844 uri, &url, proxyname,
1845 proxyport, server_portstr,
1846 sizeof(server_portstr))) != OK)
1849 /* Step Two: Make the Connection */
1850 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1851 if (r->proxyreq == PROXYREQ_PROXY)
1852 status = HTTP_NOT_FOUND;
1854 status = HTTP_SERVICE_UNAVAILABLE;
1858 /* Step Three: Create conn_rec */
1859 if (!backend->connection) {
1860 if ((status = ap_proxy_connection_create(proxy_function, backend,
1861 c, r->server)) != OK)
1865 /* Step Four: Send the Request */
1866 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1867 conf, uri, url, server_portstr)) != OK)
1870 /* Step Five: Receive the Response */
1871 if ((status = ap_proxy_http_process_response(p, r, backend,
1872 backend->connection,
1873 conf, server_portstr)) != OK)
1876 /* Step Six: Clean Up */
1882 ap_proxy_http_cleanup(proxy_function, r, backend);
1886 static apr_status_t warn_rx_free(void *p)
1888 ap_pregfree((apr_pool_t*)p, warn_rx);
1891 static void ap_proxy_http_register_hook(apr_pool_t *p)
1893 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1894 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1895 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1896 apr_pool_cleanup_register(p, p, warn_rx_free, NULL);
1899 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1900 STANDARD20_MODULE_STUFF,
1901 NULL, /* create per-directory config structure */
1902 NULL, /* merge per-directory config structures */
1903 NULL, /* create per-server config structure */
1904 NULL, /* merge per-server config structures */
1905 NULL, /* command apr_table_t */
1906 ap_proxy_http_register_hook/* register hooks */