1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* HTTP routines for Apache proxy */
19 #include "mod_proxy.h"
22 module AP_MODULE_DECLARE_DATA proxy_http_module;
24 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
26 proxy_conn_rec *backend);
29 * Canonicalise http-like URLs.
30 * scheme is the scheme for the URL
31 * url is the URL starting with the first '/'
32 * def_port is the default port for this scheme.
34 static int proxy_http_canon(request_rec *r, char *url)
36 char *host, *path, *search, sport[7];
39 apr_port_t port, def_port;
41 const char *allowed = "~$-_.+!*'(),;:@&=/"; /* allowed+reserved from
44 /* ap_port_of_scheme() */
45 if (strncasecmp(url, "http:", 5) == 0) {
49 else if (strncasecmp(url, "https:", 6) == 0) {
56 def_port = apr_uri_port_of_scheme(scheme);
58 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
59 "proxy: HTTP: canonicalising URL %s", url);
62 * We break the URL into host, port, path, search
65 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
67 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
68 "error parsing URL %s: %s",
70 return HTTP_BAD_REQUEST;
73 /* now parse path/search args, according to rfc1738 */
74 /* N.B. if this isn't a true proxy request, then the URL _path_
75 * has already been decoded. True proxy requests have r->uri
76 * == r->unparsed_uri, and no others have that property.
78 if (r->uri == r->unparsed_uri) {
79 search = strchr(url, '?');
87 /* In a reverse proxy, our URL has been processed, so canonicalise
88 * In a forward proxy, we have and MUST NOT MANGLE the original,
89 * so just check it for disallowed chars.
91 switch (r->proxyreq) {
92 default: /* wtf are we doing here? */
93 case PROXYREQ_REVERSE:
94 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
97 for (p = url; *p; ++p) {
98 if (!apr_isalnum(*p) && !strchr(allowed, *p)) {
99 if (*p == '%' && apr_isxdigit(p[1]) && apr_isxdigit(p[2])) {
100 p += 2; /* an encoded char */
103 return HTTP_BAD_REQUEST; /* reject bad char in URL */
112 return HTTP_BAD_REQUEST;
114 if (port != def_port)
115 apr_snprintf(sport, sizeof(sport), ":%d", port);
119 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
120 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
122 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
123 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
127 /* Clear all connection-based headers from the incoming headers table */
128 typedef struct header_dptr {
133 static ap_regex_t *warn_rx;
134 static int clean_warning_headers(void *data, const char *key, const char *val)
136 apr_table_t *headers = ((header_dptr*)data)->table;
137 apr_pool_t *pool = ((header_dptr*)data)->pool;
140 apr_time_t warn_time;
141 const int nmatch = 3;
142 ap_regmatch_t pmatch[3];
144 if (headers == NULL) {
145 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
148 * Parse this, suckers!
150 * Warning = "Warning" ":" 1#warning-value
152 * warning-value = warn-code SP warn-agent SP warn-text
156 * warn-agent = ( host [ ":" port ] ) | pseudonym
157 * ; the name or pseudonym of the server adding
158 * ; the Warning header, for use in debugging
159 * warn-text = quoted-string
160 * warn-date = <"> HTTP-date <">
162 * Buggrit, use a bloomin' regexp!
163 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
165 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
166 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
167 pmatch[0].rm_eo - pmatch[0].rm_so);
169 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
170 /* OK, we have a date here */
171 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
172 pmatch[2].rm_eo - pmatch[2].rm_so);
173 warn_time = apr_date_parse_http(date);
175 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
176 apr_table_addn(headers, key, warning);
178 val += pmatch[0].rm_eo;
182 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
187 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
188 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
189 if (x.table != NULL) {
190 apr_table_unset(headers, "Warning");
191 return apr_table_overlay(p, headers, x.table);
197 static int clear_conn_headers(void *data, const char *key, const char *val)
199 apr_table_t *headers = ((header_dptr*)data)->table;
200 apr_pool_t *pool = ((header_dptr*)data)->pool;
202 char *next = apr_pstrdup(pool, val);
205 while (*next && !apr_isspace(*next) && (*next != ',')) {
208 while (*next && (apr_isspace(*next) || (*next == ','))) {
211 apr_table_unset(headers, name);
215 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
220 apr_table_unset(headers, "Proxy-Connection");
221 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
222 apr_table_unset(headers, "Connection");
224 static void add_te_chunked(apr_pool_t *p,
225 apr_bucket_alloc_t *bucket_alloc,
226 apr_bucket_brigade *header_brigade)
230 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
232 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
233 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
235 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
236 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
239 static void add_cl(apr_pool_t *p,
240 apr_bucket_alloc_t *bucket_alloc,
241 apr_bucket_brigade *header_brigade,
247 buf = apr_pstrcat(p, "Content-Length: ",
251 ap_xlate_proto_to_ascii(buf, strlen(buf));
252 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
253 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
256 #define ASCII_CRLF "\015\012"
257 #define ASCII_ZERO "\060"
259 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
260 apr_bucket_brigade *header_brigade)
264 /* add empty line at the end of the headers */
265 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
266 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
269 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
270 request_rec *r, proxy_conn_rec *conn,
271 conn_rec *origin, apr_bucket_brigade *bb,
275 apr_off_t transferred;
278 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
279 APR_BRIGADE_INSERT_TAIL(bb, e);
281 apr_brigade_length(bb, 0, &transferred);
282 if (transferred != -1)
283 conn->worker->s->transferred += transferred;
284 status = ap_pass_brigade(origin->output_filters, bb);
285 if (status != APR_SUCCESS) {
286 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
287 "proxy: pass request body failed to %pI (%s)",
288 conn->addr, conn->hostname);
291 apr_brigade_cleanup(bb);
295 #define MAX_MEM_SPOOL 16384
297 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
299 proxy_conn_rec *p_conn,
301 apr_bucket_brigade *header_brigade,
302 apr_bucket_brigade *input_brigade)
308 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
309 apr_bucket_brigade *bb;
312 add_te_chunked(p, bucket_alloc, header_brigade);
313 terminate_headers(bucket_alloc, header_brigade);
315 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
317 char chunk_hdr[20]; /* must be here due to transient bucket. */
319 /* If this brigade contains EOS, either stop or remove it. */
320 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
323 /* We can't pass this EOS to the output_filters. */
324 e = APR_BRIGADE_LAST(input_brigade);
325 apr_bucket_delete(e);
328 apr_brigade_length(input_brigade, 1, &bytes);
330 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
331 "%" APR_UINT64_T_HEX_FMT CRLF,
332 (apr_uint64_t)bytes);
334 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
335 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
337 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
340 * Append the end-of-chunk CRLF
342 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
343 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
345 if (header_brigade) {
346 /* we never sent the header brigade, so go ahead and
347 * take care of that now
352 * Save input_brigade in bb brigade. (At least) in the SSL case
353 * input_brigade contains transient buckets whose data would get
354 * overwritten during the next call of ap_get_brigade in the loop.
355 * ap_save_brigade ensures these buckets to be set aside.
356 * Calling ap_save_brigade with NULL as filter is OK, because
357 * bb brigade already has been created and does not need to get
358 * created by ap_save_brigade.
360 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
361 if (status != APR_SUCCESS) {
365 header_brigade = NULL;
371 /* The request is flushed below this loop with chunk EOS header */
372 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
373 if (status != APR_SUCCESS) {
381 status = ap_get_brigade(r->input_filters, input_brigade,
382 AP_MODE_READBYTES, APR_BLOCK_READ,
385 if (status != APR_SUCCESS) {
390 if (header_brigade) {
391 /* we never sent the header brigade because there was no request body;
397 if (!APR_BRIGADE_EMPTY(input_brigade)) {
398 /* input brigade still has an EOS which we can't pass to the output_filters. */
399 e = APR_BRIGADE_LAST(input_brigade);
400 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
401 apr_bucket_delete(e);
406 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
410 APR_BRIGADE_INSERT_TAIL(bb, e);
412 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
413 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
414 APR_BRIGADE_INSERT_TAIL(bb, e);
417 /* Now we have headers-only, or the chunk EOS mark; flush it */
418 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
422 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
424 proxy_conn_rec *p_conn,
426 apr_bucket_brigade *header_brigade,
427 apr_bucket_brigade *input_brigade,
428 const char *old_cl_val)
431 apr_status_t status = APR_SUCCESS;
432 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
433 apr_bucket_brigade *bb;
435 apr_off_t cl_val = 0;
437 apr_off_t bytes_streamed = 0;
440 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
441 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
446 terminate_headers(bucket_alloc, header_brigade);
448 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
450 apr_brigade_length(input_brigade, 1, &bytes);
451 bytes_streamed += bytes;
453 /* If this brigade contains EOS, either stop or remove it. */
454 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
457 /* We can't pass this EOS to the output_filters. */
458 e = APR_BRIGADE_LAST(input_brigade);
459 apr_bucket_delete(e);
461 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
462 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
463 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
467 /* C-L < bytes streamed?!?
468 * We will error out after the body is completely
469 * consumed, but we can't stream more bytes at the
470 * back end since they would in part be interpreted
471 * as another request! If nothing is sent, then
474 * Prevents HTTP Response Splitting.
476 if (bytes_streamed > cl_val)
479 if (header_brigade) {
480 /* we never sent the header brigade, so go ahead and
481 * take care of that now
486 * Save input_brigade in bb brigade. (At least) in the SSL case
487 * input_brigade contains transient buckets whose data would get
488 * overwritten during the next call of ap_get_brigade in the loop.
489 * ap_save_brigade ensures these buckets to be set aside.
490 * Calling ap_save_brigade with NULL as filter is OK, because
491 * bb brigade already has been created and does not need to get
492 * created by ap_save_brigade.
494 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
495 if (status != APR_SUCCESS) {
499 header_brigade = NULL;
505 /* Once we hit EOS, we are ready to flush. */
506 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
507 if (status != APR_SUCCESS) {
515 status = ap_get_brigade(r->input_filters, input_brigade,
516 AP_MODE_READBYTES, APR_BLOCK_READ,
519 if (status != APR_SUCCESS) {
524 if (bytes_streamed != cl_val) {
525 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
526 "proxy: client %s given Content-Length did not match"
527 " number of body bytes read", r->connection->remote_ip);
531 if (header_brigade) {
532 /* we never sent the header brigade since there was no request
533 * body; send it now with the flush flag
536 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
541 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
543 proxy_conn_rec *p_conn,
545 apr_bucket_brigade *header_brigade,
546 apr_bucket_brigade *input_brigade,
551 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
552 apr_bucket_brigade *body_brigade;
554 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
555 apr_file_t *tmpfile = NULL;
557 body_brigade = apr_brigade_create(p, bucket_alloc);
559 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
561 /* If this brigade contains EOS, either stop or remove it. */
562 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
565 /* We can't pass this EOS to the output_filters. */
566 e = APR_BRIGADE_LAST(input_brigade);
567 apr_bucket_delete(e);
570 apr_brigade_length(input_brigade, 1, &bytes);
572 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
573 /* can't spool any more in memory; write latest brigade to disk */
574 if (tmpfile == NULL) {
575 const char *temp_dir;
578 status = apr_temp_dir_get(&temp_dir, p);
579 if (status != APR_SUCCESS) {
580 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
581 "proxy: search for temporary directory failed");
584 apr_filepath_merge(&template, temp_dir,
585 "modproxy.tmp.XXXXXX",
586 APR_FILEPATH_NATIVE, p);
587 status = apr_file_mktemp(&tmpfile, template, 0, p);
588 if (status != APR_SUCCESS) {
589 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
590 "proxy: creation of temporary file in directory %s failed",
595 for (e = APR_BRIGADE_FIRST(input_brigade);
596 e != APR_BRIGADE_SENTINEL(input_brigade);
597 e = APR_BUCKET_NEXT(e)) {
599 apr_size_t bytes_read, bytes_written;
601 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
602 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
603 if (status != APR_SUCCESS) {
604 const char *tmpfile_name;
606 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
607 tmpfile_name = "(unknown)";
609 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
610 "proxy: write to temporary file %s failed",
614 AP_DEBUG_ASSERT(bytes_read == bytes_written);
615 fsize += bytes_written;
617 apr_brigade_cleanup(input_brigade);
622 * Save input_brigade in body_brigade. (At least) in the SSL case
623 * input_brigade contains transient buckets whose data would get
624 * overwritten during the next call of ap_get_brigade in the loop.
625 * ap_save_brigade ensures these buckets to be set aside.
626 * Calling ap_save_brigade with NULL as filter is OK, because
627 * body_brigade already has been created and does not need to get
628 * created by ap_save_brigade.
630 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
631 if (status != APR_SUCCESS) {
637 bytes_spooled += bytes;
643 status = ap_get_brigade(r->input_filters, input_brigade,
644 AP_MODE_READBYTES, APR_BLOCK_READ,
647 if (status != APR_SUCCESS) {
652 if (bytes_spooled || force_cl) {
653 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
655 terminate_headers(bucket_alloc, header_brigade);
656 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
658 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
660 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
661 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
662 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
664 /* This is all a single brigade, pass with flush flagged */
665 status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
670 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
671 proxy_conn_rec *p_conn, conn_rec *origin,
672 proxy_server_conf *conf,
674 char *url, char *server_portstr)
676 conn_rec *c = r->connection;
677 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
678 apr_bucket_brigade *header_brigade;
679 apr_bucket_brigade *input_brigade;
680 apr_bucket_brigade *temp_brigade;
683 const apr_array_header_t *headers_in_array;
684 const apr_table_entry_t *headers_in;
687 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
688 enum rb_methods rb_method = RB_INIT;
689 const char *old_cl_val = NULL;
690 const char *old_te_val = NULL;
691 apr_off_t bytes_read = 0;
694 apr_table_t *headers_in_copy;
696 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
699 * Send the HTTP/1.1 request to the remote server
702 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
703 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
707 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
710 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
711 origin->keepalive = AP_CONN_CLOSE;
714 ap_xlate_proto_to_ascii(buf, strlen(buf));
715 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
716 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
717 if (conf->preserve_host == 0) {
718 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
719 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
722 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
726 /* don't want to use r->hostname, as the incoming header might have a
729 const char* hostname = apr_table_get(r->headers_in,"Host");
731 hostname = r->server->server_hostname;
732 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
733 "proxy: no HTTP 0.9 request (with no host line) "
734 "on incoming request and preserve host set "
735 "forcing hostname to be %s for uri %s",
739 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
741 ap_xlate_proto_to_ascii(buf, strlen(buf));
742 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
743 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
746 if (conf->viaopt == via_block) {
747 /* Block all outgoing Via: headers */
748 apr_table_unset(r->headers_in, "Via");
749 } else if (conf->viaopt != via_off) {
750 const char *server_name = ap_get_server_name(r);
751 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
752 * then the server name returned by ap_get_server_name() is the
753 * origin server name (which does make too much sense with Via: headers)
754 * so we use the proxy vhost's name instead.
756 if (server_name == r->hostname)
757 server_name = r->server->server_hostname;
758 /* Create a "Via:" request header entry and merge it */
759 /* Generate outgoing Via: header with/without server comment: */
760 apr_table_mergen(r->headers_in, "Via",
761 (conf->viaopt == via_full)
762 ? apr_psprintf(p, "%d.%d %s%s (%s)",
763 HTTP_VERSION_MAJOR(r->proto_num),
764 HTTP_VERSION_MINOR(r->proto_num),
765 server_name, server_portstr,
766 AP_SERVER_BASEVERSION)
767 : apr_psprintf(p, "%d.%d %s%s",
768 HTTP_VERSION_MAJOR(r->proto_num),
769 HTTP_VERSION_MINOR(r->proto_num),
770 server_name, server_portstr)
774 /* X-Forwarded-*: handling
779 * These request headers are only really useful when the mod_proxy
780 * is used in a reverse proxy configuration, so that useful info
781 * about the client can be passed through the reverse proxy and on
782 * to the backend server, which may require the information to
785 * In a forward proxy situation, these options are a potential
786 * privacy violation, as information about clients behind the proxy
787 * are revealed to arbitrary servers out there on the internet.
789 * The HTTP/1.1 Via: header is designed for passing client
790 * information through proxies to a server, and should be used in
791 * a forward proxy configuation instead of X-Forwarded-*. See the
792 * ProxyVia option for details.
795 if (PROXYREQ_REVERSE == r->proxyreq) {
798 /* Add X-Forwarded-For: so that the upstream has a chance to
799 * determine, where the original request came from.
801 apr_table_mergen(r->headers_in, "X-Forwarded-For",
804 /* Add X-Forwarded-Host: so that upstream knows what the
805 * original request hostname was.
807 if ((buf = apr_table_get(r->headers_in, "Host"))) {
808 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
811 /* Add X-Forwarded-Server: so that upstream knows what the
812 * name of this proxy server is (if there are more than one)
813 * XXX: This duplicates Via: - do we strictly need it?
815 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
816 r->server->server_hostname);
821 * Make a copy of the headers_in table before clearing the connection
822 * headers as we need the connection headers later in the http output
823 * filter to prepare the correct response headers.
825 * Note: We need to take r->pool for apr_table_copy as the key / value
826 * pairs in r->headers_in have been created out of r->pool and
827 * p might be (and actually is) a longer living pool.
828 * This would trigger the bad pool ancestry abort in apr_table_copy if
829 * apr is compiled with APR_POOL_DEBUG.
831 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
832 ap_proxy_clear_connection(p, headers_in_copy);
833 /* send request headers */
834 headers_in_array = apr_table_elts(headers_in_copy);
835 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
836 for (counter = 0; counter < headers_in_array->nelts; counter++) {
837 if (headers_in[counter].key == NULL
838 || headers_in[counter].val == NULL
841 || !strcasecmp(headers_in[counter].key, "Host")
843 /* Clear out hop-by-hop request headers not to send
844 * RFC2616 13.5.1 says we should strip these headers
846 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
847 || !strcasecmp(headers_in[counter].key, "TE")
848 || !strcasecmp(headers_in[counter].key, "Trailer")
849 || !strcasecmp(headers_in[counter].key, "Upgrade")
854 /* Do we want to strip Proxy-Authorization ?
855 * If we haven't used it, then NO
856 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
857 * So let's make it configurable by env.
859 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
860 if (r->user != NULL) { /* we've authenticated */
861 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
868 /* Skip Transfer-Encoding and Content-Length for now.
870 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
871 old_te_val = headers_in[counter].val;
874 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
875 old_cl_val = headers_in[counter].val;
879 /* for sub-requests, ignore freshness/expiry headers */
881 if ( !strcasecmp(headers_in[counter].key, "If-Match")
882 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
883 || !strcasecmp(headers_in[counter].key, "If-Range")
884 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
885 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
890 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
891 headers_in[counter].val, CRLF,
893 ap_xlate_proto_to_ascii(buf, strlen(buf));
894 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
895 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
898 /* We have headers, let's figure out our request body... */
899 input_brigade = apr_brigade_create(p, bucket_alloc);
901 /* sub-requests never use keepalives, and mustn't pass request bodies.
902 * Because the new logic looks at input_brigade, we will self-terminate
903 * input_brigade and jump past all of the request body logic...
904 * Reading anything with ap_get_brigade is likely to consume the
905 * main request's body or read beyond EOS - which would be unplesant.
908 /* XXX: Why DON'T sub-requests use keepalives? */
912 apr_table_unset(r->headers_in, "Content-Length");
916 apr_table_unset(r->headers_in, "Transfer-Encoding");
918 rb_method = RB_STREAM_CL;
919 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
920 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
924 /* WE only understand chunked. Other modules might inject
925 * (and therefore, decode) other flavors but we don't know
926 * that the can and have done so unless they they remove
927 * their decoding from the headers_in T-E list.
928 * XXX: Make this extensible, but in doing so, presume the
929 * encoding has been done by the extensions' handler, and
930 * do not modify add_te_chunked's logic
932 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
933 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
934 "proxy: %s Transfer-Encoding is not supported",
939 if (old_cl_val && old_te_val) {
940 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
941 "proxy: client %s (%s) requested Transfer-Encoding "
942 "chunked body with Content-Length (C-L ignored)",
943 c->remote_ip, c->remote_host ? c->remote_host: "");
944 apr_table_unset(r->headers_in, "Content-Length");
946 origin->keepalive = AP_CONN_CLOSE;
950 /* Prefetch MAX_MEM_SPOOL bytes
952 * This helps us avoid any election of C-L v.s. T-E
953 * request bodies, since we are willing to keep in
954 * memory this much data, in any case. This gives
955 * us an instant C-L election if the body is of some
958 temp_brigade = apr_brigade_create(p, bucket_alloc);
960 status = ap_get_brigade(r->input_filters, temp_brigade,
961 AP_MODE_READBYTES, APR_BLOCK_READ,
962 MAX_MEM_SPOOL - bytes_read);
963 if (status != APR_SUCCESS) {
964 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
965 "proxy: prefetch request body failed to %pI (%s)"
967 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
968 c->remote_ip, c->remote_host ? c->remote_host: "");
972 apr_brigade_length(temp_brigade, 1, &bytes);
976 * Save temp_brigade in input_brigade. (At least) in the SSL case
977 * temp_brigade contains transient buckets whose data would get
978 * overwritten during the next call of ap_get_brigade in the loop.
979 * ap_save_brigade ensures these buckets to be set aside.
980 * Calling ap_save_brigade with NULL as filter is OK, because
981 * input_brigade already has been created and does not need to get
982 * created by ap_save_brigade.
984 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
985 if (status != APR_SUCCESS) {
986 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
987 "proxy: processing prefetched request body failed"
988 " to %pI (%s) from %s (%s)",
989 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
990 c->remote_ip, c->remote_host ? c->remote_host: "");
994 /* Ensure we don't hit a wall where we have a buffer too small
995 * for ap_get_brigade's filters to fetch us another bucket,
996 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
997 * (an arbitrary value.)
999 } while ((bytes_read < MAX_MEM_SPOOL - 80)
1000 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1002 /* Use chunked request body encoding or send a content-length body?
1006 * We have no request body (handled by RB_STREAM_CL)
1008 * We have a request body length <= MAX_MEM_SPOOL
1010 * The administrator has setenv force-proxy-request-1.0
1012 * The client sent a C-L body, and the administrator has
1013 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1015 * The client sent a T-E body, and the administrator has
1016 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1018 * If both proxy-sendcl and proxy-sendchunked are set, the
1019 * behavior is the same as if neither were set, large bodies
1020 * that can't be read will be forwarded in their original
1021 * form of C-L, or T-E.
1023 * To ensure maximum compatibility, setenv proxy-sendcl
1024 * To reduce server resource use, setenv proxy-sendchunked
1026 * Then address specific servers with conditional setenv
1027 * options to restore the default behavior where desireable.
1029 * We have to compute content length by reading the entire request
1030 * body; if request body is not small, we'll spool the remaining
1031 * input to a temporary file. Chunked is always preferable.
1033 * We can only trust the client-provided C-L if the T-E header
1034 * is absent, and the filters are unchanged (the body won't
1035 * be resized by another content filter).
1037 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1038 /* The whole thing fit, so our decision is trivial, use
1039 * the filtered bytes read from the client for the request
1040 * body Content-Length.
1042 * If we expected no body, and read no body, do not set
1043 * the Content-Length.
1045 if (old_cl_val || old_te_val || bytes_read) {
1046 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1048 rb_method = RB_STREAM_CL;
1050 else if (old_te_val) {
1052 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1053 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1054 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1055 rb_method = RB_SPOOL_CL;
1058 rb_method = RB_STREAM_CHUNKED;
1061 else if (old_cl_val) {
1062 if (r->input_filters == r->proto_input_filters) {
1063 rb_method = RB_STREAM_CL;
1066 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1067 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1068 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1069 rb_method = RB_STREAM_CHUNKED;
1072 rb_method = RB_SPOOL_CL;
1076 /* This is an appropriate default; very efficient for no-body
1077 * requests, and has the behavior that it will not add any C-L
1078 * when the old_cl_val is NULL.
1080 rb_method = RB_SPOOL_CL;
1083 /* Yes I hate gotos. This is the subrequest shortcut */
1086 * Handle Connection: header if we do HTTP/1.1 request:
1087 * If we plan to close the backend connection sent Connection: close
1088 * otherwise sent Connection: Keep-Alive.
1091 if (p_conn->close) {
1092 buf = apr_pstrdup(p, "Connection: close" CRLF);
1095 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1097 ap_xlate_proto_to_ascii(buf, strlen(buf));
1098 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1099 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1102 /* send the request body, if any. */
1104 case RB_STREAM_CHUNKED:
1105 status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1109 status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1110 input_brigade, old_cl_val);
1113 status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1114 input_brigade, (old_cl_val != NULL)
1115 || (old_te_val != NULL)
1116 || (bytes_read > 0));
1119 /* shouldn't be possible */
1120 status = APR_EINVAL;
1124 if (status != APR_SUCCESS) {
1125 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1126 "proxy: pass request body failed to %pI (%s)"
1129 p_conn->hostname ? p_conn->hostname: "",
1131 c->remote_host ? c->remote_host: "");
1138 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1139 const char *key, const char *value)
1141 static const char *date_hdrs[]
1142 = { "Date", "Expires", "Last-Modified", NULL };
1143 static const struct {
1145 ap_proxy_header_reverse_map_fn func;
1146 } transform_hdrs[] = {
1147 { "Location", ap_proxy_location_reverse_map },
1148 { "Content-Location", ap_proxy_location_reverse_map },
1149 { "URI", ap_proxy_location_reverse_map },
1150 { "Destination", ap_proxy_location_reverse_map },
1151 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1155 for (i = 0; date_hdrs[i]; ++i) {
1156 if (!strcasecmp(date_hdrs[i], key)) {
1157 apr_table_add(r->headers_out, key,
1158 ap_proxy_date_canon(r->pool, value));
1162 for (i = 0; transform_hdrs[i].name; ++i) {
1163 if (!strcasecmp(transform_hdrs[i].name, key)) {
1164 apr_table_add(r->headers_out, key,
1165 (*transform_hdrs[i].func)(r, c, value));
1169 apr_table_add(r->headers_out, key, value);
1174 * Note: pread_len is the length of the response that we've mistakenly
1175 * read (assuming that we don't consider that an error via
1176 * ProxyBadHeader StartBody). This depends on buffer actually being
1177 * local storage to the calling code in order for pread_len to make
1178 * any sense at all, since we depend on buffer still containing
1179 * what was read by ap_getline() upon return.
1181 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1182 char *buffer, int size,
1183 conn_rec *c, int *pread_len)
1187 char field[MAX_STRING_LEN];
1188 int saw_headers = 0;
1189 void *sconf = r->server->module_config;
1190 proxy_server_conf *psc;
1191 proxy_dir_conf *dconf;
1193 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1194 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1196 r->headers_out = apr_table_make(r->pool, 20);
1200 * Read header lines until we get the empty separator line, a read error,
1201 * the connection closes (EOF), or we timeout.
1203 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1205 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1207 /* We may encounter invalid headers, usually from buggy
1208 * MS IIS servers, so we need to determine just how to handle
1209 * them. We can either ignore them, assume that they mark the
1210 * start-of-body (eg: a missing CRLF) or (the default) mark
1211 * the headers as totally bogus and return a 500. The sole
1212 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1213 * in between the usual MIME headers, which is a favorite
1216 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1218 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1219 if (psc->badopt == bad_error) {
1220 /* Nope, it wasn't even an extra HTTP header. Give up. */
1221 r->headers_out = NULL;
1224 else if (psc->badopt == bad_body) {
1225 /* if we've already started loading headers_out, then
1226 * return what we've accumulated so far, in the hopes
1227 * that they are useful; also note that we likely pre-read
1228 * the first line of the response.
1231 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1232 "proxy: Starting body due to bogus non-header in headers "
1233 "returned by %s (%s)", r->uri, r->method);
1237 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1238 "proxy: No HTTP headers "
1239 "returned by %s (%s)", r->uri, r->method);
1244 /* this is the psc->badopt == bad_ignore case */
1245 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1246 "proxy: Ignoring bogus HTTP header "
1247 "returned by %s (%s)", r->uri, r->method);
1253 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1254 * wrong... and so are many others probably.
1256 while (apr_isspace(*value))
1257 ++value; /* Skip to start of value */
1259 /* should strip trailing whitespace as well */
1260 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1264 /* make sure we add so as not to destroy duplicated headers
1265 * Modify headers requiring canonicalisation and/or affected
1266 * by ProxyPassReverse and family with process_proxy_header
1268 process_proxy_header(r, dconf, buffer, value) ;
1271 /* the header was too long; at the least we should skip extra data */
1272 if (len >= size - 1) {
1273 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1274 >= MAX_STRING_LEN - 1) {
1275 /* soak up the extra data */
1277 if (len == 0) /* time to exit the larger loop as well */
1285 static int addit_dammit(void *v, const char *key, const char *val)
1287 apr_table_addn(v, key, val);
1292 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1293 int fold, int *writen)
1299 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1300 apr_brigade_cleanup(bb);
1302 if (rv == APR_SUCCESS) {
1303 *writen = (int) len;
1304 } else if (rv == APR_ENOSPC) {
1314 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1315 proxy_conn_rec *backend,
1317 proxy_server_conf *conf,
1318 char *server_portstr) {
1319 conn_rec *c = r->connection;
1320 char buffer[HUGE_STRING_LEN];
1325 apr_bucket_brigade *bb, *tmp_bb;
1326 int len, backasswards;
1327 int interim_response; /* non-zero whilst interim 1xx responses
1328 * are being read. */
1330 apr_table_t *save_table;
1331 int backend_broke = 0;
1332 static const char *hop_by_hop_hdrs[] =
1333 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1336 bb = apr_brigade_create(p, c->bucket_alloc);
1338 /* Get response from the remote server, and pass it up the
1342 rp = ap_proxy_make_fake_req(origin, r);
1343 /* In case anyone needs to know, this is a fake request that is really a
1346 rp->proxyreq = PROXYREQ_RESPONSE;
1347 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1351 apr_brigade_cleanup(bb);
1353 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1355 /* handle one potential stray CRLF */
1356 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1359 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1360 "proxy: error reading status line from remote "
1361 "server %s", backend->hostname);
1362 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1363 "Error reading from remote server");
1365 /* XXX: Is this a real headers length send from remote? */
1366 backend->worker->s->read += len;
1368 /* Is it an HTTP/1 response?
1369 * This is buggy if we ever see an HTTP/1.10
1371 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1374 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1378 /* If not an HTTP/1 message or
1379 * if the status line was > 8192 bytes
1381 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1382 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1383 apr_pstrcat(p, "Corrupt status line returned by remote "
1384 "server: ", buffer, NULL));
1388 keepchar = buffer[12];
1390 r->status = atoi(&buffer[9]);
1392 if (keepchar != '\0') {
1393 buffer[12] = keepchar;
1395 /* 2616 requires the space in Status-Line; the origin
1396 * server may have sent one but ap_rgetline_core will
1397 * have stripped it. */
1401 r->status_line = apr_pstrdup(p, &buffer[9]);
1404 /* read the headers. */
1405 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1406 /* Also, take care with headers with multiple occurences. */
1408 /* First, tuck away all already existing cookies */
1409 save_table = apr_table_make(r->pool, 2);
1410 apr_table_do(addit_dammit, save_table, r->headers_out,
1411 "Set-Cookie", NULL);
1413 /* shove the headers direct into r->headers_out */
1414 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1417 if (r->headers_out == NULL) {
1418 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1419 r->server, "proxy: bad HTTP/%d.%d header "
1420 "returned by %s (%s)", major, minor, r->uri,
1422 backend->close += 1;
1424 * ap_send_error relies on a headers_out to be present. we
1425 * are in a bad position here.. so force everything we send out
1426 * to have nothing to do with the incoming packet
1428 r->headers_out = apr_table_make(r->pool,1);
1429 r->status = HTTP_BAD_GATEWAY;
1430 r->status_line = "bad gateway";
1434 /* Now, add in the just read cookies */
1435 apr_table_do(addit_dammit, save_table, r->headers_out,
1436 "Set-Cookie", NULL);
1438 /* and now load 'em all in */
1439 if (!apr_is_empty_table(save_table)) {
1440 apr_table_unset(r->headers_out, "Set-Cookie");
1441 r->headers_out = apr_table_overlay(r->pool,
1446 /* can't have both Content-Length and Transfer-Encoding */
1447 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1448 && apr_table_get(r->headers_out, "Content-Length")) {
1450 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1451 * and Content-Length are received, the latter MUST be
1454 * To help mitigate HTTP Splitting, unset Content-Length
1455 * and shut down the backend server connection
1456 * XXX: We aught to treat such a response as uncachable
1458 apr_table_unset(r->headers_out, "Content-Length");
1459 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1460 "proxy: server %s returned Transfer-Encoding"
1461 " and Content-Length", backend->hostname);
1462 backend->close += 1;
1465 /* strip connection listed hop-by-hop headers from response */
1466 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1469 ap_proxy_clear_connection(p, r->headers_out);
1470 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1471 ap_set_content_type(r, apr_pstrdup(p, buf));
1473 ap_proxy_pre_http_request(origin,rp);
1475 /* Clear hop-by-hop headers */
1476 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1477 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1479 /* Delete warnings with wrong date */
1480 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1482 /* handle Via header in response */
1483 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1484 const char *server_name = ap_get_server_name(r);
1485 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1486 * then the server name returned by ap_get_server_name() is the
1487 * origin server name (which does make too much sense with Via: headers)
1488 * so we use the proxy vhost's name instead.
1490 if (server_name == r->hostname)
1491 server_name = r->server->server_hostname;
1492 /* create a "Via:" response header entry and merge it */
1493 apr_table_addn(r->headers_out, "Via",
1494 (conf->viaopt == via_full)
1495 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1496 HTTP_VERSION_MAJOR(r->proto_num),
1497 HTTP_VERSION_MINOR(r->proto_num),
1500 AP_SERVER_BASEVERSION)
1501 : apr_psprintf(p, "%d.%d %s%s",
1502 HTTP_VERSION_MAJOR(r->proto_num),
1503 HTTP_VERSION_MINOR(r->proto_num),
1509 /* cancel keepalive if HTTP/1.0 or less */
1510 if ((major < 1) || (minor < 1)) {
1511 backend->close += 1;
1512 origin->keepalive = AP_CONN_CLOSE;
1515 /* an http/0.9 response */
1518 r->status_line = "200 OK";
1519 backend->close += 1;
1522 interim_response = ap_is_HTTP_INFO(r->status);
1523 if (interim_response) {
1524 /* RFC2616 tells us to forward this.
1526 * OTOH, an interim response here may mean the backend
1527 * is playing sillybuggers. The Client didn't ask for
1528 * it within the defined HTTP/1.1 mechanisms, and if
1529 * it's an extension, it may also be unsupported by us.
1531 * There's also the possibility that changing existing
1532 * behaviour here might break something.
1534 * So let's make it configurable.
1536 const char *policy = apr_table_get(r->subprocess_env,
1537 "proxy-interim-response");
1538 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1539 "proxy: HTTP: received interim %d response",
1541 if (!policy || !strcasecmp(policy, "RFC")) {
1542 ap_send_interim_response(r);
1544 /* FIXME: refine this to be able to specify per-response-status
1545 * policies and maybe also add option to bail out with 502
1547 else if (strcasecmp(policy, "Suppress")) {
1548 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1549 "undefined proxy interim response policy");
1552 /* Moved the fixups of Date headers and those affected by
1553 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1556 if ((r->status == 401) && (conf->error_override)) {
1558 const char *wa = "WWW-Authenticate";
1559 if ((buf = apr_table_get(r->headers_out, wa))) {
1560 apr_table_set(r->err_headers_out, wa, buf);
1562 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1563 "proxy: origin server sent 401 without WWW-Authenticate header");
1569 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1570 * the response? If so, load the extra data. These are 2 mutually
1571 * exclusive possibilities, that just happen to require very
1574 if (backasswards || pread_len) {
1575 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1578 * At this point in response processing of a 0.9 response,
1579 * we don't know yet whether data is binary or not.
1580 * mod_charset_lite will get control later on, so it cannot
1581 * decide on the conversion of this buffer full of data.
1582 * However, chances are that we are not really talking to an
1583 * HTTP/0.9 server, but to some different protocol, therefore
1584 * the best guess IMHO is to always treat the buffer as "text/x":
1586 ap_xlate_proto_to_ascii(buffer, len);
1587 cntr = (apr_ssize_t)len;
1589 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1590 APR_BRIGADE_INSERT_TAIL(bb, e);
1593 /* send body - but only if a body is expected */
1594 if ((!r->header_only) && /* not HEAD request */
1595 !interim_response && /* not any 1xx response */
1596 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1597 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1599 /* We need to copy the output headers and treat them as input
1600 * headers as well. BUT, we need to do this before we remove
1601 * TE, so that they are preserved accordingly for
1602 * ap_http_filter to know where to end.
1604 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1606 apr_table_unset(r->headers_out,"Transfer-Encoding");
1608 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1609 "proxy: start body send");
1612 * if we are overriding the errors, we can't put the content
1613 * of the page into the brigade
1615 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1616 /* read the body, pass it to the output filters */
1617 apr_read_type_e mode = APR_NONBLOCK_READ;
1621 apr_off_t readbytes;
1624 rv = ap_get_brigade(rp->input_filters, bb,
1625 AP_MODE_READBYTES, mode,
1626 conf->io_buffer_size);
1628 /* ap_get_brigade will return success with an empty brigade
1629 * for a non-blocking read which would block: */
1630 if (APR_STATUS_IS_EAGAIN(rv)
1631 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1632 /* flush to the client and switch to blocking mode */
1633 e = apr_bucket_flush_create(c->bucket_alloc);
1634 APR_BRIGADE_INSERT_TAIL(bb, e);
1635 if (ap_pass_brigade(r->output_filters, bb)
1640 apr_brigade_cleanup(bb);
1641 mode = APR_BLOCK_READ;
1644 else if (rv == APR_EOF) {
1647 else if (rv != APR_SUCCESS) {
1648 /* In this case, we are in real trouble because
1649 * our backend bailed on us. Pass along a 502 error
1652 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1653 "proxy: error reading response");
1654 ap_proxy_backend_broke(r, bb);
1655 ap_pass_brigade(r->output_filters, bb);
1660 /* next time try a non-blocking read */
1661 mode = APR_NONBLOCK_READ;
1663 apr_brigade_length(bb, 0, &readbytes);
1664 backend->worker->s->read += readbytes;
1667 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1668 r->server, "proxy (PID %d): readbytes: %#x",
1669 getpid(), readbytes);
1673 if (APR_BRIGADE_EMPTY(bb)) {
1674 apr_brigade_cleanup(bb);
1678 /* found the last brigade? */
1679 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1680 /* signal that we must leave */
1684 /* try send what we read */
1685 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1687 /* Ack! Phbtt! Die! User aborted! */
1688 backend->close = 1; /* this causes socket close below */
1692 /* make sure we always clean up after ourselves */
1693 apr_brigade_cleanup(bb);
1697 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1698 "proxy: end body send");
1700 else if (!interim_response) {
1701 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1702 "proxy: header only");
1704 /* Pass EOS bucket down the filter chain. */
1705 e = apr_bucket_eos_create(c->bucket_alloc);
1706 APR_BRIGADE_INSERT_TAIL(bb, e);
1707 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1709 /* Ack! Phbtt! Die! User aborted! */
1710 backend->close = 1; /* this causes socket close below */
1713 apr_brigade_cleanup(bb);
1715 } while (interim_response);
1717 /* If our connection with the client is to be aborted, return DONE. */
1718 if (c->aborted || backend_broke) {
1722 if (conf->error_override) {
1723 /* the code above this checks for 'OK' which is what the hook expects */
1724 if (!ap_is_HTTP_ERROR(r->status))
1727 /* clear r->status for override error, otherwise ErrorDocument
1728 * thinks that this is a recursive error, and doesn't find the
1731 int status = r->status;
1732 r->status = HTTP_OK;
1733 /* Discard body, if one is expected */
1734 if (!r->header_only && /* not HEAD request */
1735 (status != HTTP_NO_CONTENT) && /* not 204 */
1736 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1737 ap_discard_request_body(rp);
1746 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1747 proxy_conn_rec *backend)
1749 ap_proxy_release_connection(scheme, backend, r->server);
1754 * This handles http:// URLs, and other URLs using a remote proxy over http
1755 * If proxyhost is NULL, then contact the server directly, otherwise
1757 * Note that if a proxy is used, then URLs other than http: can be accessed,
1758 * also, if we have trouble which is clearly specific to the proxy, then
1759 * we return DECLINED so that we can try another proxy. (Or the direct
1762 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1763 proxy_server_conf *conf,
1764 char *url, const char *proxyname,
1765 apr_port_t proxyport)
1768 char server_portstr[32];
1770 const char *proxy_function;
1772 proxy_conn_rec *backend = NULL;
1775 /* Note: Memory pool allocation.
1776 * A downstream keepalive connection is always connected to the existence
1777 * (or not) of an upstream keepalive connection. If this is not done then
1778 * load balancing against multiple backend servers breaks (one backend
1779 * server ends up taking 100% of the load), and the risk is run of
1780 * downstream keepalive connections being kept open unnecessarily. This
1781 * keeps webservers busy and ties up resources.
1783 * As a result, we allocate all sockets out of the upstream connection
1784 * pool, and when we want to reuse a socket, we check first whether the
1785 * connection ID of the current upstream connection is the same as that
1786 * of the connection when the socket was opened.
1788 apr_pool_t *p = r->connection->pool;
1789 conn_rec *c = r->connection;
1790 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1792 /* find the scheme */
1793 u = strchr(url, ':');
1794 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1797 return HTTP_BAD_REQUEST;
1798 scheme = apr_pstrndup(c->pool, url, u - url);
1799 /* scheme is lowercase */
1800 ap_str_tolower(scheme);
1802 if (strcmp(scheme, "https") == 0) {
1803 if (!ap_proxy_ssl_enable(NULL)) {
1804 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1805 "proxy: HTTPS: declining URL %s"
1806 " (mod_ssl not configured?)", url);
1810 proxy_function = "HTTPS";
1812 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1813 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1814 "proxy: HTTP: declining URL %s", url);
1815 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1819 proxy_function = "HTTP";
1821 proxy_function = "FTP";
1823 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1824 "proxy: HTTP: serving URL %s", url);
1827 /* create space for state information */
1828 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1829 worker, r->server)) != OK)
1833 backend->is_ssl = is_ssl;
1835 * TODO: Currently we cannot handle persistent SSL backend connections,
1836 * because we recreate backend->connection for each request and thus
1837 * try to initialize an already existing SSL connection. This does
1843 /* Step One: Determine Who To Connect To */
1844 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1845 uri, &url, proxyname,
1846 proxyport, server_portstr,
1847 sizeof(server_portstr))) != OK)
1850 /* Step Two: Make the Connection */
1851 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1852 if (r->proxyreq == PROXYREQ_PROXY)
1853 status = HTTP_NOT_FOUND;
1855 status = HTTP_SERVICE_UNAVAILABLE;
1859 /* Step Three: Create conn_rec */
1860 if (!backend->connection) {
1861 if ((status = ap_proxy_connection_create(proxy_function, backend,
1862 c, r->server)) != OK)
1866 /* Step Four: Send the Request */
1867 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1868 conf, uri, url, server_portstr)) != OK)
1871 /* Step Five: Receive the Response */
1872 if ((status = ap_proxy_http_process_response(p, r, backend,
1873 backend->connection,
1874 conf, server_portstr)) != OK)
1877 /* Step Six: Clean Up */
1883 ap_proxy_http_cleanup(proxy_function, r, backend);
1887 static apr_status_t warn_rx_free(void *p)
1889 ap_pregfree((apr_pool_t*)p, warn_rx);
1892 static void ap_proxy_http_register_hook(apr_pool_t *p)
1894 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1895 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1896 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1897 apr_pool_cleanup_register(p, p, warn_rx_free, NULL);
1900 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1901 STANDARD20_MODULE_STUFF,
1902 NULL, /* create per-directory config structure */
1903 NULL, /* merge per-directory config structures */
1904 NULL, /* create per-server config structure */
1905 NULL, /* merge per-server config structures */
1906 NULL, /* command apr_table_t */
1907 ap_proxy_http_register_hook/* register hooks */