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, sport[7];
40 apr_port_t port, def_port;
42 /* ap_port_of_scheme() */
43 if (strncasecmp(url, "http:", 5) == 0) {
47 else if (strncasecmp(url, "https:", 6) == 0) {
54 def_port = apr_uri_port_of_scheme(scheme);
56 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
57 "proxy: HTTP: canonicalising URL %s", url);
60 * We break the URL into host, port, path, search
63 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
65 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
66 "error parsing URL %s: %s",
68 return HTTP_BAD_REQUEST;
72 * now parse path/search args, according to rfc1738:
75 * In a reverse proxy, our URL has been processed, so canonicalise
76 * unless proxy-nocanon is set to say it's raw
77 * In a forward proxy, we have and MUST NOT MANGLE the original.
79 switch (r->proxyreq) {
80 default: /* wtf are we doing here? */
81 case PROXYREQ_REVERSE:
82 if (apr_table_get(r->notes, "proxy-nocanon")) {
83 path = url; /* this is the raw path */
86 path = ap_proxy_canonenc(r->pool, url, strlen(url),
87 enc_path, 0, r->proxyreq);
97 return HTTP_BAD_REQUEST;
100 apr_snprintf(sport, sizeof(sport), ":%d", port);
104 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
105 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
107 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
108 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
112 /* Clear all connection-based headers from the incoming headers table */
113 typedef struct header_dptr {
118 static ap_regex_t *warn_rx;
119 static int clean_warning_headers(void *data, const char *key, const char *val)
121 apr_table_t *headers = ((header_dptr*)data)->table;
122 apr_pool_t *pool = ((header_dptr*)data)->pool;
125 apr_time_t warn_time;
126 const int nmatch = 3;
127 ap_regmatch_t pmatch[3];
129 if (headers == NULL) {
130 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
133 * Parse this, suckers!
135 * Warning = "Warning" ":" 1#warning-value
137 * warning-value = warn-code SP warn-agent SP warn-text
141 * warn-agent = ( host [ ":" port ] ) | pseudonym
142 * ; the name or pseudonym of the server adding
143 * ; the Warning header, for use in debugging
144 * warn-text = quoted-string
145 * warn-date = <"> HTTP-date <">
147 * Buggrit, use a bloomin' regexp!
148 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
150 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
151 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
152 pmatch[0].rm_eo - pmatch[0].rm_so);
154 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
155 /* OK, we have a date here */
156 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
157 pmatch[2].rm_eo - pmatch[2].rm_so);
158 warn_time = apr_date_parse_http(date);
160 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
161 apr_table_addn(headers, key, warning);
163 val += pmatch[0].rm_eo;
167 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
172 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
173 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
174 if (x.table != NULL) {
175 apr_table_unset(headers, "Warning");
176 return apr_table_overlay(p, headers, x.table);
182 static int clear_conn_headers(void *data, const char *key, const char *val)
184 apr_table_t *headers = ((header_dptr*)data)->table;
185 apr_pool_t *pool = ((header_dptr*)data)->pool;
187 char *next = apr_pstrdup(pool, val);
190 while (*next && !apr_isspace(*next) && (*next != ',')) {
193 while (*next && (apr_isspace(*next) || (*next == ','))) {
196 apr_table_unset(headers, name);
200 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
205 apr_table_unset(headers, "Proxy-Connection");
206 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
207 apr_table_unset(headers, "Connection");
209 static void add_te_chunked(apr_pool_t *p,
210 apr_bucket_alloc_t *bucket_alloc,
211 apr_bucket_brigade *header_brigade)
215 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
217 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
218 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
220 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
221 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
224 static void add_cl(apr_pool_t *p,
225 apr_bucket_alloc_t *bucket_alloc,
226 apr_bucket_brigade *header_brigade,
232 buf = apr_pstrcat(p, "Content-Length: ",
236 ap_xlate_proto_to_ascii(buf, strlen(buf));
237 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
238 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
241 #define ASCII_CRLF "\015\012"
242 #define ASCII_ZERO "\060"
244 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
245 apr_bucket_brigade *header_brigade)
249 /* add empty line at the end of the headers */
250 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
251 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
254 static int pass_brigade(apr_bucket_alloc_t *bucket_alloc,
255 request_rec *r, proxy_conn_rec *conn,
256 conn_rec *origin, apr_bucket_brigade *bb,
260 apr_off_t transferred;
263 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
264 APR_BRIGADE_INSERT_TAIL(bb, e);
266 apr_brigade_length(bb, 0, &transferred);
267 if (transferred != -1)
268 conn->worker->s->transferred += transferred;
269 status = ap_pass_brigade(origin->output_filters, bb);
270 if (status != APR_SUCCESS) {
271 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
272 "proxy: pass request body failed to %pI (%s)",
273 conn->addr, conn->hostname);
274 if (origin->aborted) {
275 return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY;
278 return HTTP_BAD_REQUEST;
281 apr_brigade_cleanup(bb);
285 #define MAX_MEM_SPOOL 16384
287 static int stream_reqbody_chunked(apr_pool_t *p,
289 proxy_conn_rec *p_conn,
291 apr_bucket_brigade *header_brigade,
292 apr_bucket_brigade *input_brigade)
294 int seen_eos = 0, rv = OK;
298 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
299 apr_bucket_brigade *bb;
302 add_te_chunked(p, bucket_alloc, header_brigade);
303 terminate_headers(bucket_alloc, header_brigade);
305 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
307 char chunk_hdr[20]; /* must be here due to transient bucket. */
309 /* If this brigade contains EOS, either stop or remove it. */
310 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
313 /* We can't pass this EOS to the output_filters. */
314 e = APR_BRIGADE_LAST(input_brigade);
315 apr_bucket_delete(e);
318 apr_brigade_length(input_brigade, 1, &bytes);
320 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
321 "%" APR_UINT64_T_HEX_FMT CRLF,
322 (apr_uint64_t)bytes);
324 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
325 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
327 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
330 * Append the end-of-chunk CRLF
332 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
333 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
335 if (header_brigade) {
336 /* we never sent the header brigade, so go ahead and
337 * take care of that now
342 * Save input_brigade in bb brigade. (At least) in the SSL case
343 * input_brigade contains transient buckets whose data would get
344 * overwritten during the next call of ap_get_brigade in the loop.
345 * ap_save_brigade ensures these buckets to be set aside.
346 * Calling ap_save_brigade with NULL as filter is OK, because
347 * bb brigade already has been created and does not need to get
348 * created by ap_save_brigade.
350 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
351 if (status != APR_SUCCESS) {
352 return HTTP_INTERNAL_SERVER_ERROR;
355 header_brigade = NULL;
361 /* The request is flushed below this loop with chunk EOS header */
362 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
371 status = ap_get_brigade(r->input_filters, input_brigade,
372 AP_MODE_READBYTES, APR_BLOCK_READ,
375 if (status != APR_SUCCESS) {
376 return HTTP_BAD_REQUEST;
380 if (header_brigade) {
381 /* we never sent the header brigade because there was no request body;
387 if (!APR_BRIGADE_EMPTY(input_brigade)) {
388 /* input brigade still has an EOS which we can't pass to the output_filters. */
389 e = APR_BRIGADE_LAST(input_brigade);
390 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
391 apr_bucket_delete(e);
396 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
400 APR_BRIGADE_INSERT_TAIL(bb, e);
402 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
403 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
404 APR_BRIGADE_INSERT_TAIL(bb, e);
407 /* Now we have headers-only, or the chunk EOS mark; flush it */
408 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
412 static int stream_reqbody_cl(apr_pool_t *p,
414 proxy_conn_rec *p_conn,
416 apr_bucket_brigade *header_brigade,
417 apr_bucket_brigade *input_brigade,
418 const char *old_cl_val)
420 int seen_eos = 0, rv = 0;
421 apr_status_t status = APR_SUCCESS;
422 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
423 apr_bucket_brigade *bb;
425 apr_off_t cl_val = 0;
427 apr_off_t bytes_streamed = 0;
430 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
431 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
433 return HTTP_INTERNAL_SERVER_ERROR;
436 terminate_headers(bucket_alloc, header_brigade);
438 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
440 apr_brigade_length(input_brigade, 1, &bytes);
441 bytes_streamed += bytes;
443 /* If this brigade contains EOS, either stop or remove it. */
444 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
447 /* We can't pass this EOS to the output_filters. */
448 e = APR_BRIGADE_LAST(input_brigade);
449 apr_bucket_delete(e);
451 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
452 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
453 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
457 /* C-L < bytes streamed?!?
458 * We will error out after the body is completely
459 * consumed, but we can't stream more bytes at the
460 * back end since they would in part be interpreted
461 * as another request! If nothing is sent, then
464 * Prevents HTTP Response Splitting.
466 if (bytes_streamed > cl_val)
469 if (header_brigade) {
470 /* we never sent the header brigade, so go ahead and
471 * take care of that now
476 * Save input_brigade in bb brigade. (At least) in the SSL case
477 * input_brigade contains transient buckets whose data would get
478 * overwritten during the next call of ap_get_brigade in the loop.
479 * ap_save_brigade ensures these buckets to be set aside.
480 * Calling ap_save_brigade with NULL as filter is OK, because
481 * bb brigade already has been created and does not need to get
482 * created by ap_save_brigade.
484 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
485 if (status != APR_SUCCESS) {
486 return HTTP_INTERNAL_SERVER_ERROR;
489 header_brigade = NULL;
495 /* Once we hit EOS, we are ready to flush. */
496 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
505 status = ap_get_brigade(r->input_filters, input_brigade,
506 AP_MODE_READBYTES, APR_BLOCK_READ,
509 if (status != APR_SUCCESS) {
510 return HTTP_BAD_REQUEST;
514 if (bytes_streamed != cl_val) {
515 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
516 "proxy: client %s given Content-Length did not match"
517 " number of body bytes read", r->connection->remote_ip);
518 return HTTP_BAD_REQUEST;
521 if (header_brigade) {
522 /* we never sent the header brigade since there was no request
523 * body; send it now with the flush flag
526 return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
532 static int spool_reqbody_cl(apr_pool_t *p,
534 proxy_conn_rec *p_conn,
536 apr_bucket_brigade *header_brigade,
537 apr_bucket_brigade *input_brigade,
542 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
543 apr_bucket_brigade *body_brigade;
545 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
546 apr_file_t *tmpfile = NULL;
548 body_brigade = apr_brigade_create(p, bucket_alloc);
550 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
552 /* If this brigade contains EOS, either stop or remove it. */
553 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
556 /* We can't pass this EOS to the output_filters. */
557 e = APR_BRIGADE_LAST(input_brigade);
558 apr_bucket_delete(e);
561 apr_brigade_length(input_brigade, 1, &bytes);
563 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
564 /* can't spool any more in memory; write latest brigade to disk */
565 if (tmpfile == NULL) {
566 const char *temp_dir;
569 status = apr_temp_dir_get(&temp_dir, p);
570 if (status != APR_SUCCESS) {
571 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
572 "proxy: search for temporary directory failed");
573 return HTTP_INTERNAL_SERVER_ERROR;
575 apr_filepath_merge(&template, temp_dir,
576 "modproxy.tmp.XXXXXX",
577 APR_FILEPATH_NATIVE, p);
578 status = apr_file_mktemp(&tmpfile, template, 0, p);
579 if (status != APR_SUCCESS) {
580 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
581 "proxy: creation of temporary file in directory %s failed",
583 return HTTP_INTERNAL_SERVER_ERROR;
586 for (e = APR_BRIGADE_FIRST(input_brigade);
587 e != APR_BRIGADE_SENTINEL(input_brigade);
588 e = APR_BUCKET_NEXT(e)) {
590 apr_size_t bytes_read, bytes_written;
592 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
593 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
594 if (status != APR_SUCCESS) {
595 const char *tmpfile_name;
597 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
598 tmpfile_name = "(unknown)";
600 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
601 "proxy: write to temporary file %s failed",
603 return HTTP_INTERNAL_SERVER_ERROR;
605 AP_DEBUG_ASSERT(bytes_read == bytes_written);
606 fsize += bytes_written;
608 apr_brigade_cleanup(input_brigade);
613 * Save input_brigade in body_brigade. (At least) in the SSL case
614 * input_brigade contains transient buckets whose data would get
615 * overwritten during the next call of ap_get_brigade in the loop.
616 * ap_save_brigade ensures these buckets to be set aside.
617 * Calling ap_save_brigade with NULL as filter is OK, because
618 * body_brigade already has been created and does not need to get
619 * created by ap_save_brigade.
621 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
622 if (status != APR_SUCCESS) {
623 return HTTP_INTERNAL_SERVER_ERROR;
628 bytes_spooled += bytes;
634 status = ap_get_brigade(r->input_filters, input_brigade,
635 AP_MODE_READBYTES, APR_BLOCK_READ,
638 if (status != APR_SUCCESS) {
639 return HTTP_BAD_REQUEST;
643 if (bytes_spooled || force_cl) {
644 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
646 terminate_headers(bucket_alloc, header_brigade);
647 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
649 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
651 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
652 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
653 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
655 /* This is all a single brigade, pass with flush flagged */
656 return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
660 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
661 proxy_conn_rec *p_conn, conn_rec *origin,
662 proxy_server_conf *conf,
664 char *url, char *server_portstr)
666 conn_rec *c = r->connection;
667 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
668 apr_bucket_brigade *header_brigade;
669 apr_bucket_brigade *input_brigade;
670 apr_bucket_brigade *temp_brigade;
673 const apr_array_header_t *headers_in_array;
674 const apr_table_entry_t *headers_in;
677 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
678 enum rb_methods rb_method = RB_INIT;
679 const char *old_cl_val = NULL;
680 const char *old_te_val = NULL;
681 apr_off_t bytes_read = 0;
684 apr_table_t *headers_in_copy;
686 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
689 * Send the HTTP/1.1 request to the remote server
692 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
693 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
697 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
700 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
701 origin->keepalive = AP_CONN_CLOSE;
704 ap_xlate_proto_to_ascii(buf, strlen(buf));
705 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
706 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
707 if (conf->preserve_host == 0) {
708 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
709 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
712 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
716 /* don't want to use r->hostname, as the incoming header might have a
719 const char* hostname = apr_table_get(r->headers_in,"Host");
721 hostname = r->server->server_hostname;
722 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
723 "proxy: no HTTP 0.9 request (with no host line) "
724 "on incoming request and preserve host set "
725 "forcing hostname to be %s for uri %s",
729 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
731 ap_xlate_proto_to_ascii(buf, strlen(buf));
732 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
733 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
736 if (conf->viaopt == via_block) {
737 /* Block all outgoing Via: headers */
738 apr_table_unset(r->headers_in, "Via");
739 } else if (conf->viaopt != via_off) {
740 const char *server_name = ap_get_server_name(r);
741 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
742 * then the server name returned by ap_get_server_name() is the
743 * origin server name (which does make too much sense with Via: headers)
744 * so we use the proxy vhost's name instead.
746 if (server_name == r->hostname)
747 server_name = r->server->server_hostname;
748 /* Create a "Via:" request header entry and merge it */
749 /* Generate outgoing Via: header with/without server comment: */
750 apr_table_mergen(r->headers_in, "Via",
751 (conf->viaopt == via_full)
752 ? apr_psprintf(p, "%d.%d %s%s (%s)",
753 HTTP_VERSION_MAJOR(r->proto_num),
754 HTTP_VERSION_MINOR(r->proto_num),
755 server_name, server_portstr,
756 AP_SERVER_BASEVERSION)
757 : apr_psprintf(p, "%d.%d %s%s",
758 HTTP_VERSION_MAJOR(r->proto_num),
759 HTTP_VERSION_MINOR(r->proto_num),
760 server_name, server_portstr)
764 /* X-Forwarded-*: handling
769 * These request headers are only really useful when the mod_proxy
770 * is used in a reverse proxy configuration, so that useful info
771 * about the client can be passed through the reverse proxy and on
772 * to the backend server, which may require the information to
775 * In a forward proxy situation, these options are a potential
776 * privacy violation, as information about clients behind the proxy
777 * are revealed to arbitrary servers out there on the internet.
779 * The HTTP/1.1 Via: header is designed for passing client
780 * information through proxies to a server, and should be used in
781 * a forward proxy configuation instead of X-Forwarded-*. See the
782 * ProxyVia option for details.
785 if (PROXYREQ_REVERSE == r->proxyreq) {
788 /* Add X-Forwarded-For: so that the upstream has a chance to
789 * determine, where the original request came from.
791 apr_table_mergen(r->headers_in, "X-Forwarded-For",
794 /* Add X-Forwarded-Host: so that upstream knows what the
795 * original request hostname was.
797 if ((buf = apr_table_get(r->headers_in, "Host"))) {
798 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
801 /* Add X-Forwarded-Server: so that upstream knows what the
802 * name of this proxy server is (if there are more than one)
803 * XXX: This duplicates Via: - do we strictly need it?
805 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
806 r->server->server_hostname);
811 * Make a copy of the headers_in table before clearing the connection
812 * headers as we need the connection headers later in the http output
813 * filter to prepare the correct response headers.
815 * Note: We need to take r->pool for apr_table_copy as the key / value
816 * pairs in r->headers_in have been created out of r->pool and
817 * p might be (and actually is) a longer living pool.
818 * This would trigger the bad pool ancestry abort in apr_table_copy if
819 * apr is compiled with APR_POOL_DEBUG.
821 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
822 ap_proxy_clear_connection(p, headers_in_copy);
823 /* send request headers */
824 headers_in_array = apr_table_elts(headers_in_copy);
825 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
826 for (counter = 0; counter < headers_in_array->nelts; counter++) {
827 if (headers_in[counter].key == NULL
828 || headers_in[counter].val == NULL
831 || !strcasecmp(headers_in[counter].key, "Host")
833 /* Clear out hop-by-hop request headers not to send
834 * RFC2616 13.5.1 says we should strip these headers
836 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
837 || !strcasecmp(headers_in[counter].key, "TE")
838 || !strcasecmp(headers_in[counter].key, "Trailer")
839 || !strcasecmp(headers_in[counter].key, "Upgrade")
844 /* Do we want to strip Proxy-Authorization ?
845 * If we haven't used it, then NO
846 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
847 * So let's make it configurable by env.
849 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
850 if (r->user != NULL) { /* we've authenticated */
851 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
858 /* Skip Transfer-Encoding and Content-Length for now.
860 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
861 old_te_val = headers_in[counter].val;
864 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
865 old_cl_val = headers_in[counter].val;
869 /* for sub-requests, ignore freshness/expiry headers */
871 if ( !strcasecmp(headers_in[counter].key, "If-Match")
872 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
873 || !strcasecmp(headers_in[counter].key, "If-Range")
874 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
875 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
880 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
881 headers_in[counter].val, CRLF,
883 ap_xlate_proto_to_ascii(buf, strlen(buf));
884 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
885 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
888 /* We have headers, let's figure out our request body... */
889 input_brigade = apr_brigade_create(p, bucket_alloc);
891 /* sub-requests never use keepalives, and mustn't pass request bodies.
892 * Because the new logic looks at input_brigade, we will self-terminate
893 * input_brigade and jump past all of the request body logic...
894 * Reading anything with ap_get_brigade is likely to consume the
895 * main request's body or read beyond EOS - which would be unplesant.
897 * An exception: when a kept_body is present, then subrequest CAN use
898 * pass request bodies, and we DONT skip the body.
900 if (!r->kept_body && r->main) {
901 /* XXX: Why DON'T sub-requests use keepalives? */
905 apr_table_unset(r->headers_in, "Content-Length");
909 apr_table_unset(r->headers_in, "Transfer-Encoding");
911 rb_method = RB_STREAM_CL;
912 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
913 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
917 /* WE only understand chunked. Other modules might inject
918 * (and therefore, decode) other flavors but we don't know
919 * that the can and have done so unless they they remove
920 * their decoding from the headers_in T-E list.
921 * XXX: Make this extensible, but in doing so, presume the
922 * encoding has been done by the extensions' handler, and
923 * do not modify add_te_chunked's logic
925 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
926 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
927 "proxy: %s Transfer-Encoding is not supported",
929 return HTTP_INTERNAL_SERVER_ERROR;
932 if (old_cl_val && old_te_val) {
933 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
934 "proxy: client %s (%s) requested Transfer-Encoding "
935 "chunked body with Content-Length (C-L ignored)",
936 c->remote_ip, c->remote_host ? c->remote_host: "");
937 apr_table_unset(r->headers_in, "Content-Length");
939 origin->keepalive = AP_CONN_CLOSE;
943 /* Prefetch MAX_MEM_SPOOL bytes
945 * This helps us avoid any election of C-L v.s. T-E
946 * request bodies, since we are willing to keep in
947 * memory this much data, in any case. This gives
948 * us an instant C-L election if the body is of some
951 temp_brigade = apr_brigade_create(p, bucket_alloc);
953 status = ap_get_brigade(r->input_filters, temp_brigade,
954 AP_MODE_READBYTES, APR_BLOCK_READ,
955 MAX_MEM_SPOOL - bytes_read);
956 if (status != APR_SUCCESS) {
957 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
958 "proxy: prefetch request body failed to %pI (%s)"
960 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
961 c->remote_ip, c->remote_host ? c->remote_host: "");
962 return HTTP_BAD_REQUEST;
965 apr_brigade_length(temp_brigade, 1, &bytes);
969 * Save temp_brigade in input_brigade. (At least) in the SSL case
970 * temp_brigade contains transient buckets whose data would get
971 * overwritten during the next call of ap_get_brigade in the loop.
972 * ap_save_brigade ensures these buckets to be set aside.
973 * Calling ap_save_brigade with NULL as filter is OK, because
974 * input_brigade already has been created and does not need to get
975 * created by ap_save_brigade.
977 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
978 if (status != APR_SUCCESS) {
979 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
980 "proxy: processing prefetched request body failed"
981 " to %pI (%s) from %s (%s)",
982 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
983 c->remote_ip, c->remote_host ? c->remote_host: "");
984 return HTTP_INTERNAL_SERVER_ERROR;
987 /* Ensure we don't hit a wall where we have a buffer too small
988 * for ap_get_brigade's filters to fetch us another bucket,
989 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
990 * (an arbitrary value.)
992 } while ((bytes_read < MAX_MEM_SPOOL - 80)
993 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
995 /* Use chunked request body encoding or send a content-length body?
999 * We have no request body (handled by RB_STREAM_CL)
1001 * We have a request body length <= MAX_MEM_SPOOL
1003 * The administrator has setenv force-proxy-request-1.0
1005 * The client sent a C-L body, and the administrator has
1006 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1008 * The client sent a T-E body, and the administrator has
1009 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1011 * If both proxy-sendcl and proxy-sendchunked are set, the
1012 * behavior is the same as if neither were set, large bodies
1013 * that can't be read will be forwarded in their original
1014 * form of C-L, or T-E.
1016 * To ensure maximum compatibility, setenv proxy-sendcl
1017 * To reduce server resource use, setenv proxy-sendchunked
1019 * Then address specific servers with conditional setenv
1020 * options to restore the default behavior where desireable.
1022 * We have to compute content length by reading the entire request
1023 * body; if request body is not small, we'll spool the remaining
1024 * input to a temporary file. Chunked is always preferable.
1026 * We can only trust the client-provided C-L if the T-E header
1027 * is absent, and the filters are unchanged (the body won't
1028 * be resized by another content filter).
1030 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1031 /* The whole thing fit, so our decision is trivial, use
1032 * the filtered bytes read from the client for the request
1033 * body Content-Length.
1035 * If we expected no body, and read no body, do not set
1036 * the Content-Length.
1038 if (old_cl_val || old_te_val || bytes_read) {
1039 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1041 rb_method = RB_STREAM_CL;
1043 else if (old_te_val) {
1045 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1046 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1047 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1048 rb_method = RB_SPOOL_CL;
1051 rb_method = RB_STREAM_CHUNKED;
1054 else if (old_cl_val) {
1055 if (r->input_filters == r->proto_input_filters) {
1056 rb_method = RB_STREAM_CL;
1059 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1060 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1061 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1062 rb_method = RB_STREAM_CHUNKED;
1065 rb_method = RB_SPOOL_CL;
1069 /* This is an appropriate default; very efficient for no-body
1070 * requests, and has the behavior that it will not add any C-L
1071 * when the old_cl_val is NULL.
1073 rb_method = RB_SPOOL_CL;
1076 /* Yes I hate gotos. This is the subrequest shortcut */
1079 * Handle Connection: header if we do HTTP/1.1 request:
1080 * If we plan to close the backend connection sent Connection: close
1081 * otherwise sent Connection: Keep-Alive.
1084 if (p_conn->close) {
1085 buf = apr_pstrdup(p, "Connection: close" CRLF);
1088 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1090 ap_xlate_proto_to_ascii(buf, strlen(buf));
1091 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1092 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1095 /* send the request body, if any. */
1097 case RB_STREAM_CHUNKED:
1098 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1102 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1103 input_brigade, old_cl_val);
1106 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1107 input_brigade, (old_cl_val != NULL)
1108 || (old_te_val != NULL)
1109 || (bytes_read > 0));
1112 /* shouldn't be possible */
1113 rv = HTTP_INTERNAL_SERVER_ERROR ;
1118 /* apr_errno value has been logged in lower level method */
1119 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
1120 "proxy: pass request body failed to %pI (%s)"
1123 p_conn->hostname ? p_conn->hostname: "",
1125 c->remote_host ? c->remote_host: "");
1132 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1133 const char *key, const char *value)
1135 static const char *date_hdrs[]
1136 = { "Date", "Expires", "Last-Modified", NULL };
1137 static const struct {
1139 ap_proxy_header_reverse_map_fn func;
1140 } transform_hdrs[] = {
1141 { "Location", ap_proxy_location_reverse_map },
1142 { "Content-Location", ap_proxy_location_reverse_map },
1143 { "URI", ap_proxy_location_reverse_map },
1144 { "Destination", ap_proxy_location_reverse_map },
1145 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1149 for (i = 0; date_hdrs[i]; ++i) {
1150 if (!strcasecmp(date_hdrs[i], key)) {
1151 apr_table_add(r->headers_out, key,
1152 ap_proxy_date_canon(r->pool, value));
1156 for (i = 0; transform_hdrs[i].name; ++i) {
1157 if (!strcasecmp(transform_hdrs[i].name, key)) {
1158 apr_table_add(r->headers_out, key,
1159 (*transform_hdrs[i].func)(r, c, value));
1163 apr_table_add(r->headers_out, key, value);
1168 * Note: pread_len is the length of the response that we've mistakenly
1169 * read (assuming that we don't consider that an error via
1170 * ProxyBadHeader StartBody). This depends on buffer actually being
1171 * local storage to the calling code in order for pread_len to make
1172 * any sense at all, since we depend on buffer still containing
1173 * what was read by ap_getline() upon return.
1175 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1176 char *buffer, int size,
1177 conn_rec *c, int *pread_len)
1181 char field[MAX_STRING_LEN];
1182 int saw_headers = 0;
1183 void *sconf = r->server->module_config;
1184 proxy_server_conf *psc;
1185 proxy_dir_conf *dconf;
1187 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1188 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1190 r->headers_out = apr_table_make(r->pool, 20);
1194 * Read header lines until we get the empty separator line, a read error,
1195 * the connection closes (EOF), or we timeout.
1197 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1199 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1201 /* We may encounter invalid headers, usually from buggy
1202 * MS IIS servers, so we need to determine just how to handle
1203 * them. We can either ignore them, assume that they mark the
1204 * start-of-body (eg: a missing CRLF) or (the default) mark
1205 * the headers as totally bogus and return a 500. The sole
1206 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1207 * in between the usual MIME headers, which is a favorite
1210 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1212 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1213 if (psc->badopt == bad_error) {
1214 /* Nope, it wasn't even an extra HTTP header. Give up. */
1215 r->headers_out = NULL;
1218 else if (psc->badopt == bad_body) {
1219 /* if we've already started loading headers_out, then
1220 * return what we've accumulated so far, in the hopes
1221 * that they are useful; also note that we likely pre-read
1222 * the first line of the response.
1225 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1226 "proxy: Starting body due to bogus non-header in headers "
1227 "returned by %s (%s)", r->uri, r->method);
1231 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1232 "proxy: No HTTP headers "
1233 "returned by %s (%s)", r->uri, r->method);
1238 /* this is the psc->badopt == bad_ignore case */
1239 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1240 "proxy: Ignoring bogus HTTP header "
1241 "returned by %s (%s)", r->uri, r->method);
1247 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1248 * wrong... and so are many others probably.
1250 while (apr_isspace(*value))
1251 ++value; /* Skip to start of value */
1253 /* should strip trailing whitespace as well */
1254 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1258 /* make sure we add so as not to destroy duplicated headers
1259 * Modify headers requiring canonicalisation and/or affected
1260 * by ProxyPassReverse and family with process_proxy_header
1262 process_proxy_header(r, dconf, buffer, value) ;
1265 /* the header was too long; at the least we should skip extra data */
1266 if (len >= size - 1) {
1267 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1268 >= MAX_STRING_LEN - 1) {
1269 /* soak up the extra data */
1271 if (len == 0) /* time to exit the larger loop as well */
1279 static int addit_dammit(void *v, const char *key, const char *val)
1281 apr_table_addn(v, key, val);
1286 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1287 int fold, int *writen)
1293 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1294 apr_brigade_cleanup(bb);
1296 if (rv == APR_SUCCESS) {
1297 *writen = (int) len;
1298 } else if (rv == APR_ENOSPC) {
1308 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1309 proxy_conn_rec *backend,
1311 proxy_server_conf *conf,
1312 char *server_portstr) {
1313 conn_rec *c = r->connection;
1314 char buffer[HUGE_STRING_LEN];
1319 apr_bucket_brigade *bb, *tmp_bb;
1320 int len, backasswards;
1321 int interim_response; /* non-zero whilst interim 1xx responses
1322 * are being read. */
1324 apr_table_t *save_table;
1325 int backend_broke = 0;
1326 static const char *hop_by_hop_hdrs[] =
1327 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1329 const char *te = NULL;
1331 bb = apr_brigade_create(p, c->bucket_alloc);
1333 /* Get response from the remote server, and pass it up the
1337 rp = ap_proxy_make_fake_req(origin, r);
1338 /* In case anyone needs to know, this is a fake request that is really a
1341 rp->proxyreq = PROXYREQ_RESPONSE;
1342 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1346 apr_brigade_cleanup(bb);
1348 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1350 /* handle one potential stray CRLF */
1351 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1354 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1355 "proxy: error reading status line from remote "
1356 "server %s", backend->hostname);
1358 * If we are a reverse proxy request shutdown the connection
1359 * WITHOUT ANY response to trigger a retry by the client
1360 * if allowed (as for idempotent requests).
1361 * BUT currently we should not do this if the request is the
1362 * first request on a keepalive connection as browsers like
1363 * seamonkey only display an empty page in this case and do
1366 if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives) {
1367 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1368 "proxy: Closing connection to client because"
1369 " reading from backend server %s failed. Number"
1370 " of keepalives %i", backend->hostname,
1372 ap_proxy_backend_broke(r, bb);
1374 * Add an EOC bucket to signal the ap_http_header_filter
1375 * that it should get out of our way
1377 e = ap_bucket_eoc_create(c->bucket_alloc);
1378 APR_BRIGADE_INSERT_TAIL(bb, e);
1379 ap_pass_brigade(r->output_filters, bb);
1380 /* Need to return OK to avoid sending an error message */
1383 else if (!c->keepalives) {
1384 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1385 "proxy: NOT Closing connection to client"
1386 " although reading from backend server %s"
1387 " failed.", backend->hostname);
1389 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1390 "Error reading from remote server");
1392 /* XXX: Is this a real headers length send from remote? */
1393 backend->worker->s->read += len;
1395 /* Is it an HTTP/1 response?
1396 * This is buggy if we ever see an HTTP/1.10
1398 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1401 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1405 /* If not an HTTP/1 message or
1406 * if the status line was > 8192 bytes
1408 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1409 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1410 apr_pstrcat(p, "Corrupt status line returned by remote "
1411 "server: ", buffer, NULL));
1415 keepchar = buffer[12];
1417 r->status = atoi(&buffer[9]);
1419 if (keepchar != '\0') {
1420 buffer[12] = keepchar;
1422 /* 2616 requires the space in Status-Line; the origin
1423 * server may have sent one but ap_rgetline_core will
1424 * have stripped it. */
1428 r->status_line = apr_pstrdup(p, &buffer[9]);
1431 /* read the headers. */
1432 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1433 /* Also, take care with headers with multiple occurences. */
1435 /* First, tuck away all already existing cookies */
1436 save_table = apr_table_make(r->pool, 2);
1437 apr_table_do(addit_dammit, save_table, r->headers_out,
1438 "Set-Cookie", NULL);
1440 /* shove the headers direct into r->headers_out */
1441 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1444 if (r->headers_out == NULL) {
1445 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1446 r->server, "proxy: bad HTTP/%d.%d header "
1447 "returned by %s (%s)", major, minor, r->uri,
1449 backend->close += 1;
1451 * ap_send_error relies on a headers_out to be present. we
1452 * are in a bad position here.. so force everything we send out
1453 * to have nothing to do with the incoming packet
1455 r->headers_out = apr_table_make(r->pool,1);
1456 r->status = HTTP_BAD_GATEWAY;
1457 r->status_line = "bad gateway";
1461 /* Now, add in the just read cookies */
1462 apr_table_do(addit_dammit, save_table, r->headers_out,
1463 "Set-Cookie", NULL);
1465 /* and now load 'em all in */
1466 if (!apr_is_empty_table(save_table)) {
1467 apr_table_unset(r->headers_out, "Set-Cookie");
1468 r->headers_out = apr_table_overlay(r->pool,
1473 /* can't have both Content-Length and Transfer-Encoding */
1474 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1475 && apr_table_get(r->headers_out, "Content-Length")) {
1477 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1478 * and Content-Length are received, the latter MUST be
1481 * To help mitigate HTTP Splitting, unset Content-Length
1482 * and shut down the backend server connection
1483 * XXX: We aught to treat such a response as uncachable
1485 apr_table_unset(r->headers_out, "Content-Length");
1486 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1487 "proxy: server %s returned Transfer-Encoding"
1488 " and Content-Length", backend->hostname);
1489 backend->close += 1;
1493 * Save a possible Transfer-Encoding header as we need it later for
1494 * ap_http_filter to know where to end.
1496 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1497 /* strip connection listed hop-by-hop headers from response */
1498 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1501 ap_proxy_clear_connection(p, r->headers_out);
1502 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1503 ap_set_content_type(r, apr_pstrdup(p, buf));
1505 ap_proxy_pre_http_request(origin,rp);
1507 /* Clear hop-by-hop headers */
1508 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1509 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1511 /* Delete warnings with wrong date */
1512 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1514 /* handle Via header in response */
1515 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1516 const char *server_name = ap_get_server_name(r);
1517 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1518 * then the server name returned by ap_get_server_name() is the
1519 * origin server name (which does make too much sense with Via: headers)
1520 * so we use the proxy vhost's name instead.
1522 if (server_name == r->hostname)
1523 server_name = r->server->server_hostname;
1524 /* create a "Via:" response header entry and merge it */
1525 apr_table_addn(r->headers_out, "Via",
1526 (conf->viaopt == via_full)
1527 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1528 HTTP_VERSION_MAJOR(r->proto_num),
1529 HTTP_VERSION_MINOR(r->proto_num),
1532 AP_SERVER_BASEVERSION)
1533 : apr_psprintf(p, "%d.%d %s%s",
1534 HTTP_VERSION_MAJOR(r->proto_num),
1535 HTTP_VERSION_MINOR(r->proto_num),
1541 /* cancel keepalive if HTTP/1.0 or less */
1542 if ((major < 1) || (minor < 1)) {
1543 backend->close += 1;
1544 origin->keepalive = AP_CONN_CLOSE;
1547 /* an http/0.9 response */
1550 r->status_line = "200 OK";
1551 backend->close += 1;
1554 interim_response = ap_is_HTTP_INFO(r->status);
1555 if (interim_response) {
1556 /* RFC2616 tells us to forward this.
1558 * OTOH, an interim response here may mean the backend
1559 * is playing sillybuggers. The Client didn't ask for
1560 * it within the defined HTTP/1.1 mechanisms, and if
1561 * it's an extension, it may also be unsupported by us.
1563 * There's also the possibility that changing existing
1564 * behaviour here might break something.
1566 * So let's make it configurable.
1568 const char *policy = apr_table_get(r->subprocess_env,
1569 "proxy-interim-response");
1570 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1571 "proxy: HTTP: received interim %d response",
1573 if (!policy || !strcasecmp(policy, "RFC")) {
1574 ap_send_interim_response(r, 1);
1576 /* FIXME: refine this to be able to specify per-response-status
1577 * policies and maybe also add option to bail out with 502
1579 else if (strcasecmp(policy, "Suppress")) {
1580 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1581 "undefined proxy interim response policy");
1584 /* Moved the fixups of Date headers and those affected by
1585 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1588 if ((r->status == 401) && (conf->error_override)) {
1590 const char *wa = "WWW-Authenticate";
1591 if ((buf = apr_table_get(r->headers_out, wa))) {
1592 apr_table_set(r->err_headers_out, wa, buf);
1594 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1595 "proxy: origin server sent 401 without WWW-Authenticate header");
1601 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1602 * the response? If so, load the extra data. These are 2 mutually
1603 * exclusive possibilities, that just happen to require very
1606 if (backasswards || pread_len) {
1607 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1610 * At this point in response processing of a 0.9 response,
1611 * we don't know yet whether data is binary or not.
1612 * mod_charset_lite will get control later on, so it cannot
1613 * decide on the conversion of this buffer full of data.
1614 * However, chances are that we are not really talking to an
1615 * HTTP/0.9 server, but to some different protocol, therefore
1616 * the best guess IMHO is to always treat the buffer as "text/x":
1618 ap_xlate_proto_to_ascii(buffer, len);
1619 cntr = (apr_ssize_t)len;
1621 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1622 APR_BRIGADE_INSERT_TAIL(bb, e);
1625 /* send body - but only if a body is expected */
1626 if ((!r->header_only) && /* not HEAD request */
1627 !interim_response && /* not any 1xx response */
1628 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1629 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1631 /* We need to copy the output headers and treat them as input
1632 * headers as well. BUT, we need to do this before we remove
1633 * TE, so that they are preserved accordingly for
1634 * ap_http_filter to know where to end.
1636 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1638 * Restore Transfer-Encoding header from response if we saved
1639 * one before and there is none left. We need it for the
1640 * ap_http_filter. See above.
1642 if (te && !apr_table_get(rp->headers_in, "Transfer-Encoding")) {
1643 apr_table_add(rp->headers_in, "Transfer-Encoding", te);
1646 apr_table_unset(r->headers_out,"Transfer-Encoding");
1648 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1649 "proxy: start body send");
1652 * if we are overriding the errors, we can't put the content
1653 * of the page into the brigade
1655 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1656 /* read the body, pass it to the output filters */
1657 apr_read_type_e mode = APR_NONBLOCK_READ;
1661 apr_off_t readbytes;
1664 rv = ap_get_brigade(rp->input_filters, bb,
1665 AP_MODE_READBYTES, mode,
1666 conf->io_buffer_size);
1668 /* ap_get_brigade will return success with an empty brigade
1669 * for a non-blocking read which would block: */
1670 if (APR_STATUS_IS_EAGAIN(rv)
1671 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1672 /* flush to the client and switch to blocking mode */
1673 e = apr_bucket_flush_create(c->bucket_alloc);
1674 APR_BRIGADE_INSERT_TAIL(bb, e);
1675 if (ap_pass_brigade(r->output_filters, bb)
1680 apr_brigade_cleanup(bb);
1681 mode = APR_BLOCK_READ;
1684 else if (rv == APR_EOF) {
1687 else if (rv != APR_SUCCESS) {
1688 /* In this case, we are in real trouble because
1689 * our backend bailed on us. Pass along a 502 error
1692 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1693 "proxy: error reading response");
1694 ap_proxy_backend_broke(r, bb);
1695 ap_pass_brigade(r->output_filters, bb);
1700 /* next time try a non-blocking read */
1701 mode = APR_NONBLOCK_READ;
1703 apr_brigade_length(bb, 0, &readbytes);
1704 backend->worker->s->read += readbytes;
1707 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1708 r->server, "proxy (PID %d): readbytes: %#x",
1709 getpid(), readbytes);
1713 if (APR_BRIGADE_EMPTY(bb)) {
1714 apr_brigade_cleanup(bb);
1718 /* found the last brigade? */
1719 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1720 /* signal that we must leave */
1724 /* try send what we read */
1725 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1727 /* Ack! Phbtt! Die! User aborted! */
1728 backend->close = 1; /* this causes socket close below */
1732 /* make sure we always clean up after ourselves */
1733 apr_brigade_cleanup(bb);
1737 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1738 "proxy: end body send");
1740 else if (!interim_response) {
1741 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1742 "proxy: header only");
1744 /* Pass EOS bucket down the filter chain. */
1745 e = apr_bucket_eos_create(c->bucket_alloc);
1746 APR_BRIGADE_INSERT_TAIL(bb, e);
1747 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1749 /* Ack! Phbtt! Die! User aborted! */
1750 backend->close = 1; /* this causes socket close below */
1753 apr_brigade_cleanup(bb);
1755 } while (interim_response);
1757 /* If our connection with the client is to be aborted, return DONE. */
1758 if (c->aborted || backend_broke) {
1762 if (conf->error_override) {
1763 /* the code above this checks for 'OK' which is what the hook expects */
1764 if (!ap_is_HTTP_ERROR(r->status))
1767 /* clear r->status for override error, otherwise ErrorDocument
1768 * thinks that this is a recursive error, and doesn't find the
1771 int status = r->status;
1772 r->status = HTTP_OK;
1773 /* Discard body, if one is expected */
1774 if (!r->header_only && /* not HEAD request */
1775 (status != HTTP_NO_CONTENT) && /* not 204 */
1776 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1777 ap_discard_request_body(rp);
1786 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1787 proxy_conn_rec *backend)
1789 ap_proxy_release_connection(scheme, backend, r->server);
1794 * This handles http:// URLs, and other URLs using a remote proxy over http
1795 * If proxyhost is NULL, then contact the server directly, otherwise
1797 * Note that if a proxy is used, then URLs other than http: can be accessed,
1798 * also, if we have trouble which is clearly specific to the proxy, then
1799 * we return DECLINED so that we can try another proxy. (Or the direct
1802 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1803 proxy_server_conf *conf,
1804 char *url, const char *proxyname,
1805 apr_port_t proxyport)
1808 char server_portstr[32];
1810 const char *proxy_function;
1812 proxy_conn_rec *backend = NULL;
1815 /* Note: Memory pool allocation.
1816 * A downstream keepalive connection is always connected to the existence
1817 * (or not) of an upstream keepalive connection. If this is not done then
1818 * load balancing against multiple backend servers breaks (one backend
1819 * server ends up taking 100% of the load), and the risk is run of
1820 * downstream keepalive connections being kept open unnecessarily. This
1821 * keeps webservers busy and ties up resources.
1823 * As a result, we allocate all sockets out of the upstream connection
1824 * pool, and when we want to reuse a socket, we check first whether the
1825 * connection ID of the current upstream connection is the same as that
1826 * of the connection when the socket was opened.
1828 apr_pool_t *p = r->connection->pool;
1829 conn_rec *c = r->connection;
1830 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1832 /* find the scheme */
1833 u = strchr(url, ':');
1834 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1837 return HTTP_BAD_REQUEST;
1838 scheme = apr_pstrndup(c->pool, url, u - url);
1839 /* scheme is lowercase */
1840 ap_str_tolower(scheme);
1842 if (strcmp(scheme, "https") == 0) {
1843 if (!ap_proxy_ssl_enable(NULL)) {
1844 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1845 "proxy: HTTPS: declining URL %s"
1846 " (mod_ssl not configured?)", url);
1850 proxy_function = "HTTPS";
1852 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1853 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1854 "proxy: HTTP: declining URL %s", url);
1855 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1859 proxy_function = "HTTP";
1861 proxy_function = "FTP";
1863 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1864 "proxy: HTTP: serving URL %s", url);
1867 /* create space for state information */
1868 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1869 worker, r->server)) != OK)
1873 backend->is_ssl = is_ssl;
1876 ap_proxy_ssl_connection_cleanup(backend, r);
1879 /* Step One: Determine Who To Connect To */
1880 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1881 uri, &url, proxyname,
1882 proxyport, server_portstr,
1883 sizeof(server_portstr))) != OK)
1886 /* Step Two: Make the Connection */
1887 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1888 if (r->proxyreq == PROXYREQ_PROXY)
1889 status = HTTP_NOT_FOUND;
1891 status = HTTP_SERVICE_UNAVAILABLE;
1895 /* Step Three: Create conn_rec */
1896 if (!backend->connection) {
1897 if ((status = ap_proxy_connection_create(proxy_function, backend,
1898 c, r->server)) != OK)
1902 /* Step Four: Send the Request */
1903 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1904 conf, uri, url, server_portstr)) != OK)
1907 /* Step Five: Receive the Response */
1908 if ((status = ap_proxy_http_process_response(p, r, backend,
1909 backend->connection,
1910 conf, server_portstr)) != OK)
1913 /* Step Six: Clean Up */
1919 ap_proxy_http_cleanup(proxy_function, r, backend);
1923 static apr_status_t warn_rx_free(void *p)
1925 ap_pregfree((apr_pool_t*)p, warn_rx);
1928 static void ap_proxy_http_register_hook(apr_pool_t *p)
1930 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1931 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1932 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1933 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1936 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1937 STANDARD20_MODULE_STUFF,
1938 NULL, /* create per-directory config structure */
1939 NULL, /* merge per-directory config structures */
1940 NULL, /* create per-server config structure */
1941 NULL, /* merge per-server config structures */
1942 NULL, /* command apr_table_t */
1943 ap_proxy_http_register_hook/* register hooks */