1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* HTTP routines for Apache proxy */
19 #include "mod_proxy.h"
22 module AP_MODULE_DECLARE_DATA proxy_http_module;
24 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
26 proxy_conn_rec *backend);
29 * Canonicalise http-like URLs.
30 * scheme is the scheme for the URL
31 * url is the URL starting with the first '/'
32 * def_port is the default port for this scheme.
34 static int proxy_http_canon(request_rec *r, char *url)
36 char *host, *path, *search, sport[7];
39 apr_port_t port, def_port;
41 /* ap_port_of_scheme() */
42 if (strncasecmp(url, "http:", 5) == 0) {
46 else if (strncasecmp(url, "https:", 6) == 0) {
53 def_port = apr_uri_port_of_scheme(scheme);
55 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
56 "proxy: HTTP: canonicalising URL %s", url);
59 * We break the URL into host, port, path, search
62 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
64 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
65 "error parsing URL %s: %s",
67 return HTTP_BAD_REQUEST;
70 /* now parse path/search args, according to rfc1738 */
74 /* In a reverse proxy, our URL has been processed, so canonicalise
75 * unless proxy-nocanon is set to say it's raw
76 * In a forward proxy, we have and MUST NOT MANGLE the original.
78 switch (r->proxyreq) {
79 default: /* wtf are we doing here? */
80 case PROXYREQ_REVERSE:
81 if (apr_table_get(r->notes, "proxy-nocanon")) {
82 path = url; /* this is the raw path */
85 path = ap_proxy_canonenc(r->pool, url, strlen(url),
86 enc_path, 0, r->proxyreq);
96 return HTTP_BAD_REQUEST;
99 apr_snprintf(sport, sizeof(sport), ":%d", port);
103 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
104 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
106 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
107 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
111 /* Clear all connection-based headers from the incoming headers table */
112 typedef struct header_dptr {
117 static ap_regex_t *warn_rx;
118 static int clean_warning_headers(void *data, const char *key, const char *val)
120 apr_table_t *headers = ((header_dptr*)data)->table;
121 apr_pool_t *pool = ((header_dptr*)data)->pool;
124 apr_time_t warn_time;
125 const int nmatch = 3;
126 ap_regmatch_t pmatch[3];
128 if (headers == NULL) {
129 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
132 * Parse this, suckers!
134 * Warning = "Warning" ":" 1#warning-value
136 * warning-value = warn-code SP warn-agent SP warn-text
140 * warn-agent = ( host [ ":" port ] ) | pseudonym
141 * ; the name or pseudonym of the server adding
142 * ; the Warning header, for use in debugging
143 * warn-text = quoted-string
144 * warn-date = <"> HTTP-date <">
146 * Buggrit, use a bloomin' regexp!
147 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
149 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
150 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
151 pmatch[0].rm_eo - pmatch[0].rm_so);
153 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
154 /* OK, we have a date here */
155 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
156 pmatch[2].rm_eo - pmatch[2].rm_so);
157 warn_time = apr_date_parse_http(date);
159 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
160 apr_table_addn(headers, key, warning);
162 val += pmatch[0].rm_eo;
166 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
171 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
172 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
173 if (x.table != NULL) {
174 apr_table_unset(headers, "Warning");
175 return apr_table_overlay(p, headers, x.table);
181 static int clear_conn_headers(void *data, const char *key, const char *val)
183 apr_table_t *headers = ((header_dptr*)data)->table;
184 apr_pool_t *pool = ((header_dptr*)data)->pool;
186 char *next = apr_pstrdup(pool, val);
189 while (*next && !apr_isspace(*next) && (*next != ',')) {
192 while (*next && (apr_isspace(*next) || (*next == ','))) {
195 apr_table_unset(headers, name);
199 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
204 apr_table_unset(headers, "Proxy-Connection");
205 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
206 apr_table_unset(headers, "Connection");
208 static void add_te_chunked(apr_pool_t *p,
209 apr_bucket_alloc_t *bucket_alloc,
210 apr_bucket_brigade *header_brigade)
214 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
216 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
217 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
219 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
220 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
223 static void add_cl(apr_pool_t *p,
224 apr_bucket_alloc_t *bucket_alloc,
225 apr_bucket_brigade *header_brigade,
231 buf = apr_pstrcat(p, "Content-Length: ",
235 ap_xlate_proto_to_ascii(buf, strlen(buf));
236 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
237 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
240 #define ASCII_CRLF "\015\012"
241 #define ASCII_ZERO "\060"
243 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
244 apr_bucket_brigade *header_brigade)
248 /* add empty line at the end of the headers */
249 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
250 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
253 static int pass_brigade(apr_bucket_alloc_t *bucket_alloc,
254 request_rec *r, proxy_conn_rec *conn,
255 conn_rec *origin, apr_bucket_brigade *bb,
259 apr_off_t transferred;
262 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
263 APR_BRIGADE_INSERT_TAIL(bb, e);
265 apr_brigade_length(bb, 0, &transferred);
266 if (transferred != -1)
267 conn->worker->s->transferred += transferred;
268 status = ap_pass_brigade(origin->output_filters, bb);
269 if (status != APR_SUCCESS) {
270 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
271 "proxy: pass request body failed to %pI (%s)",
272 conn->addr, conn->hostname);
273 if (origin->aborted) {
274 return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY;
277 return HTTP_BAD_REQUEST;
280 apr_brigade_cleanup(bb);
284 #define MAX_MEM_SPOOL 16384
286 static int stream_reqbody_chunked(apr_pool_t *p,
288 proxy_conn_rec *p_conn,
290 apr_bucket_brigade *header_brigade,
291 apr_bucket_brigade *input_brigade)
293 int seen_eos = 0, rv = OK;
297 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
298 apr_bucket_brigade *bb;
301 add_te_chunked(p, bucket_alloc, header_brigade);
302 terminate_headers(bucket_alloc, header_brigade);
304 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
306 char chunk_hdr[20]; /* must be here due to transient bucket. */
308 /* If this brigade contains EOS, either stop or remove it. */
309 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
312 /* We can't pass this EOS to the output_filters. */
313 e = APR_BRIGADE_LAST(input_brigade);
314 apr_bucket_delete(e);
317 apr_brigade_length(input_brigade, 1, &bytes);
319 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
320 "%" APR_UINT64_T_HEX_FMT CRLF,
321 (apr_uint64_t)bytes);
323 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
324 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
326 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
329 * Append the end-of-chunk CRLF
331 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
332 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
334 if (header_brigade) {
335 /* we never sent the header brigade, so go ahead and
336 * take care of that now
341 * Save input_brigade in bb brigade. (At least) in the SSL case
342 * input_brigade contains transient buckets whose data would get
343 * overwritten during the next call of ap_get_brigade in the loop.
344 * ap_save_brigade ensures these buckets to be set aside.
345 * Calling ap_save_brigade with NULL as filter is OK, because
346 * bb brigade already has been created and does not need to get
347 * created by ap_save_brigade.
349 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
350 if (status != APR_SUCCESS) {
351 return HTTP_INTERNAL_SERVER_ERROR;
354 header_brigade = NULL;
360 /* The request is flushed below this loop with chunk EOS header */
361 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
370 status = ap_get_brigade(r->input_filters, input_brigade,
371 AP_MODE_READBYTES, APR_BLOCK_READ,
374 if (status != APR_SUCCESS) {
375 return HTTP_BAD_REQUEST;
379 if (header_brigade) {
380 /* we never sent the header brigade because there was no request body;
386 if (!APR_BRIGADE_EMPTY(input_brigade)) {
387 /* input brigade still has an EOS which we can't pass to the output_filters. */
388 e = APR_BRIGADE_LAST(input_brigade);
389 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
390 apr_bucket_delete(e);
395 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
399 APR_BRIGADE_INSERT_TAIL(bb, e);
401 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
402 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
403 APR_BRIGADE_INSERT_TAIL(bb, e);
406 /* Now we have headers-only, or the chunk EOS mark; flush it */
407 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
411 static int stream_reqbody_cl(apr_pool_t *p,
413 proxy_conn_rec *p_conn,
415 apr_bucket_brigade *header_brigade,
416 apr_bucket_brigade *input_brigade,
417 const char *old_cl_val)
419 int seen_eos = 0, rv = 0;
420 apr_status_t status = APR_SUCCESS;
421 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
422 apr_bucket_brigade *bb;
424 apr_off_t cl_val = 0;
426 apr_off_t bytes_streamed = 0;
429 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
430 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
432 return HTTP_INTERNAL_SERVER_ERROR;
435 terminate_headers(bucket_alloc, header_brigade);
437 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
439 apr_brigade_length(input_brigade, 1, &bytes);
440 bytes_streamed += bytes;
442 /* If this brigade contains EOS, either stop or remove it. */
443 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
446 /* We can't pass this EOS to the output_filters. */
447 e = APR_BRIGADE_LAST(input_brigade);
448 apr_bucket_delete(e);
450 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
451 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
452 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
456 /* C-L < bytes streamed?!?
457 * We will error out after the body is completely
458 * consumed, but we can't stream more bytes at the
459 * back end since they would in part be interpreted
460 * as another request! If nothing is sent, then
463 * Prevents HTTP Response Splitting.
465 if (bytes_streamed > cl_val)
468 if (header_brigade) {
469 /* we never sent the header brigade, so go ahead and
470 * take care of that now
475 * Save input_brigade in bb brigade. (At least) in the SSL case
476 * input_brigade contains transient buckets whose data would get
477 * overwritten during the next call of ap_get_brigade in the loop.
478 * ap_save_brigade ensures these buckets to be set aside.
479 * Calling ap_save_brigade with NULL as filter is OK, because
480 * bb brigade already has been created and does not need to get
481 * created by ap_save_brigade.
483 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
484 if (status != APR_SUCCESS) {
485 return HTTP_INTERNAL_SERVER_ERROR;
488 header_brigade = NULL;
494 /* Once we hit EOS, we are ready to flush. */
495 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
504 status = ap_get_brigade(r->input_filters, input_brigade,
505 AP_MODE_READBYTES, APR_BLOCK_READ,
508 if (status != APR_SUCCESS) {
509 return HTTP_BAD_REQUEST;
513 if (bytes_streamed != cl_val) {
514 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
515 "proxy: client %s given Content-Length did not match"
516 " number of body bytes read", r->connection->remote_ip);
517 return HTTP_BAD_REQUEST;
520 if (header_brigade) {
521 /* we never sent the header brigade since there was no request
522 * body; send it now with the flush flag
525 return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
531 static int spool_reqbody_cl(apr_pool_t *p,
533 proxy_conn_rec *p_conn,
535 apr_bucket_brigade *header_brigade,
536 apr_bucket_brigade *input_brigade,
541 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
542 apr_bucket_brigade *body_brigade;
544 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
545 apr_file_t *tmpfile = NULL;
547 body_brigade = apr_brigade_create(p, bucket_alloc);
549 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
551 /* If this brigade contains EOS, either stop or remove it. */
552 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
555 /* We can't pass this EOS to the output_filters. */
556 e = APR_BRIGADE_LAST(input_brigade);
557 apr_bucket_delete(e);
560 apr_brigade_length(input_brigade, 1, &bytes);
562 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
563 /* can't spool any more in memory; write latest brigade to disk */
564 if (tmpfile == NULL) {
565 const char *temp_dir;
568 status = apr_temp_dir_get(&temp_dir, p);
569 if (status != APR_SUCCESS) {
570 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
571 "proxy: search for temporary directory failed");
572 return HTTP_INTERNAL_SERVER_ERROR;
574 apr_filepath_merge(&template, temp_dir,
575 "modproxy.tmp.XXXXXX",
576 APR_FILEPATH_NATIVE, p);
577 status = apr_file_mktemp(&tmpfile, template, 0, p);
578 if (status != APR_SUCCESS) {
579 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
580 "proxy: creation of temporary file in directory %s failed",
582 return HTTP_INTERNAL_SERVER_ERROR;
585 for (e = APR_BRIGADE_FIRST(input_brigade);
586 e != APR_BRIGADE_SENTINEL(input_brigade);
587 e = APR_BUCKET_NEXT(e)) {
589 apr_size_t bytes_read, bytes_written;
591 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
592 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
593 if (status != APR_SUCCESS) {
594 const char *tmpfile_name;
596 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
597 tmpfile_name = "(unknown)";
599 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
600 "proxy: write to temporary file %s failed",
602 return HTTP_INTERNAL_SERVER_ERROR;
604 AP_DEBUG_ASSERT(bytes_read == bytes_written);
605 fsize += bytes_written;
607 apr_brigade_cleanup(input_brigade);
612 * Save input_brigade in body_brigade. (At least) in the SSL case
613 * input_brigade contains transient buckets whose data would get
614 * overwritten during the next call of ap_get_brigade in the loop.
615 * ap_save_brigade ensures these buckets to be set aside.
616 * Calling ap_save_brigade with NULL as filter is OK, because
617 * body_brigade already has been created and does not need to get
618 * created by ap_save_brigade.
620 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
621 if (status != APR_SUCCESS) {
622 return HTTP_INTERNAL_SERVER_ERROR;
627 bytes_spooled += bytes;
633 status = ap_get_brigade(r->input_filters, input_brigade,
634 AP_MODE_READBYTES, APR_BLOCK_READ,
637 if (status != APR_SUCCESS) {
638 return HTTP_BAD_REQUEST;
642 if (bytes_spooled || force_cl) {
643 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
645 terminate_headers(bucket_alloc, header_brigade);
646 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
648 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
650 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
651 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
652 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
654 /* This is all a single brigade, pass with flush flagged */
655 return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
659 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
660 proxy_conn_rec *p_conn, conn_rec *origin,
661 proxy_server_conf *conf,
663 char *url, char *server_portstr)
665 conn_rec *c = r->connection;
666 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
667 apr_bucket_brigade *header_brigade;
668 apr_bucket_brigade *input_brigade;
669 apr_bucket_brigade *temp_brigade;
672 const apr_array_header_t *headers_in_array;
673 const apr_table_entry_t *headers_in;
676 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
677 enum rb_methods rb_method = RB_INIT;
678 const char *old_cl_val = NULL;
679 const char *old_te_val = NULL;
680 apr_off_t bytes_read = 0;
683 apr_table_t *headers_in_copy;
685 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
688 * Send the HTTP/1.1 request to the remote server
691 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
692 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
696 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
699 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
700 origin->keepalive = AP_CONN_CLOSE;
703 ap_xlate_proto_to_ascii(buf, strlen(buf));
704 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
705 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
706 if (conf->preserve_host == 0) {
707 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
708 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
711 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
715 /* don't want to use r->hostname, as the incoming header might have a
718 const char* hostname = apr_table_get(r->headers_in,"Host");
720 hostname = r->server->server_hostname;
721 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
722 "proxy: no HTTP 0.9 request (with no host line) "
723 "on incoming request and preserve host set "
724 "forcing hostname to be %s for uri %s",
728 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
730 ap_xlate_proto_to_ascii(buf, strlen(buf));
731 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
732 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
735 if (conf->viaopt == via_block) {
736 /* Block all outgoing Via: headers */
737 apr_table_unset(r->headers_in, "Via");
738 } else if (conf->viaopt != via_off) {
739 const char *server_name = ap_get_server_name(r);
740 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
741 * then the server name returned by ap_get_server_name() is the
742 * origin server name (which does make too much sense with Via: headers)
743 * so we use the proxy vhost's name instead.
745 if (server_name == r->hostname)
746 server_name = r->server->server_hostname;
747 /* Create a "Via:" request header entry and merge it */
748 /* Generate outgoing Via: header with/without server comment: */
749 apr_table_mergen(r->headers_in, "Via",
750 (conf->viaopt == via_full)
751 ? apr_psprintf(p, "%d.%d %s%s (%s)",
752 HTTP_VERSION_MAJOR(r->proto_num),
753 HTTP_VERSION_MINOR(r->proto_num),
754 server_name, server_portstr,
755 AP_SERVER_BASEVERSION)
756 : apr_psprintf(p, "%d.%d %s%s",
757 HTTP_VERSION_MAJOR(r->proto_num),
758 HTTP_VERSION_MINOR(r->proto_num),
759 server_name, server_portstr)
763 /* X-Forwarded-*: handling
768 * These request headers are only really useful when the mod_proxy
769 * is used in a reverse proxy configuration, so that useful info
770 * about the client can be passed through the reverse proxy and on
771 * to the backend server, which may require the information to
774 * In a forward proxy situation, these options are a potential
775 * privacy violation, as information about clients behind the proxy
776 * are revealed to arbitrary servers out there on the internet.
778 * The HTTP/1.1 Via: header is designed for passing client
779 * information through proxies to a server, and should be used in
780 * a forward proxy configuation instead of X-Forwarded-*. See the
781 * ProxyVia option for details.
784 if (PROXYREQ_REVERSE == r->proxyreq) {
787 /* Add X-Forwarded-For: so that the upstream has a chance to
788 * determine, where the original request came from.
790 apr_table_mergen(r->headers_in, "X-Forwarded-For",
793 /* Add X-Forwarded-Host: so that upstream knows what the
794 * original request hostname was.
796 if ((buf = apr_table_get(r->headers_in, "Host"))) {
797 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
800 /* Add X-Forwarded-Server: so that upstream knows what the
801 * name of this proxy server is (if there are more than one)
802 * XXX: This duplicates Via: - do we strictly need it?
804 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
805 r->server->server_hostname);
810 * Make a copy of the headers_in table before clearing the connection
811 * headers as we need the connection headers later in the http output
812 * filter to prepare the correct response headers.
814 * Note: We need to take r->pool for apr_table_copy as the key / value
815 * pairs in r->headers_in have been created out of r->pool and
816 * p might be (and actually is) a longer living pool.
817 * This would trigger the bad pool ancestry abort in apr_table_copy if
818 * apr is compiled with APR_POOL_DEBUG.
820 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
821 ap_proxy_clear_connection(p, headers_in_copy);
822 /* send request headers */
823 headers_in_array = apr_table_elts(headers_in_copy);
824 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
825 for (counter = 0; counter < headers_in_array->nelts; counter++) {
826 if (headers_in[counter].key == NULL
827 || headers_in[counter].val == NULL
830 || !strcasecmp(headers_in[counter].key, "Host")
832 /* Clear out hop-by-hop request headers not to send
833 * RFC2616 13.5.1 says we should strip these headers
835 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
836 || !strcasecmp(headers_in[counter].key, "TE")
837 || !strcasecmp(headers_in[counter].key, "Trailer")
838 || !strcasecmp(headers_in[counter].key, "Upgrade")
843 /* Do we want to strip Proxy-Authorization ?
844 * If we haven't used it, then NO
845 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
846 * So let's make it configurable by env.
848 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
849 if (r->user != NULL) { /* we've authenticated */
850 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
857 /* Skip Transfer-Encoding and Content-Length for now.
859 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
860 old_te_val = headers_in[counter].val;
863 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
864 old_cl_val = headers_in[counter].val;
868 /* for sub-requests, ignore freshness/expiry headers */
870 if ( !strcasecmp(headers_in[counter].key, "If-Match")
871 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
872 || !strcasecmp(headers_in[counter].key, "If-Range")
873 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
874 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
879 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
880 headers_in[counter].val, CRLF,
882 ap_xlate_proto_to_ascii(buf, strlen(buf));
883 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
884 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
887 /* We have headers, let's figure out our request body... */
888 input_brigade = apr_brigade_create(p, bucket_alloc);
890 /* sub-requests never use keepalives, and mustn't pass request bodies.
891 * Because the new logic looks at input_brigade, we will self-terminate
892 * input_brigade and jump past all of the request body logic...
893 * Reading anything with ap_get_brigade is likely to consume the
894 * main request's body or read beyond EOS - which would be unplesant.
897 /* XXX: Why DON'T sub-requests use keepalives? */
901 apr_table_unset(r->headers_in, "Content-Length");
905 apr_table_unset(r->headers_in, "Transfer-Encoding");
907 rb_method = RB_STREAM_CL;
908 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
909 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
913 /* WE only understand chunked. Other modules might inject
914 * (and therefore, decode) other flavors but we don't know
915 * that the can and have done so unless they they remove
916 * their decoding from the headers_in T-E list.
917 * XXX: Make this extensible, but in doing so, presume the
918 * encoding has been done by the extensions' handler, and
919 * do not modify add_te_chunked's logic
921 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
922 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
923 "proxy: %s Transfer-Encoding is not supported",
925 return HTTP_INTERNAL_SERVER_ERROR;
928 if (old_cl_val && old_te_val) {
929 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
930 "proxy: client %s (%s) requested Transfer-Encoding "
931 "chunked body with Content-Length (C-L ignored)",
932 c->remote_ip, c->remote_host ? c->remote_host: "");
933 apr_table_unset(r->headers_in, "Content-Length");
935 origin->keepalive = AP_CONN_CLOSE;
939 /* Prefetch MAX_MEM_SPOOL bytes
941 * This helps us avoid any election of C-L v.s. T-E
942 * request bodies, since we are willing to keep in
943 * memory this much data, in any case. This gives
944 * us an instant C-L election if the body is of some
947 temp_brigade = apr_brigade_create(p, bucket_alloc);
949 status = ap_get_brigade(r->input_filters, temp_brigade,
950 AP_MODE_READBYTES, APR_BLOCK_READ,
951 MAX_MEM_SPOOL - bytes_read);
952 if (status != APR_SUCCESS) {
953 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
954 "proxy: prefetch request body failed to %pI (%s)"
956 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
957 c->remote_ip, c->remote_host ? c->remote_host: "");
958 return HTTP_BAD_REQUEST;
961 apr_brigade_length(temp_brigade, 1, &bytes);
965 * Save temp_brigade in input_brigade. (At least) in the SSL case
966 * temp_brigade contains transient buckets whose data would get
967 * overwritten during the next call of ap_get_brigade in the loop.
968 * ap_save_brigade ensures these buckets to be set aside.
969 * Calling ap_save_brigade with NULL as filter is OK, because
970 * input_brigade already has been created and does not need to get
971 * created by ap_save_brigade.
973 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
974 if (status != APR_SUCCESS) {
975 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
976 "proxy: processing prefetched request body failed"
977 " to %pI (%s) from %s (%s)",
978 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
979 c->remote_ip, c->remote_host ? c->remote_host: "");
980 return HTTP_INTERNAL_SERVER_ERROR;
983 /* Ensure we don't hit a wall where we have a buffer too small
984 * for ap_get_brigade's filters to fetch us another bucket,
985 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
986 * (an arbitrary value.)
988 } while ((bytes_read < MAX_MEM_SPOOL - 80)
989 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
991 /* Use chunked request body encoding or send a content-length body?
995 * We have no request body (handled by RB_STREAM_CL)
997 * We have a request body length <= MAX_MEM_SPOOL
999 * The administrator has setenv force-proxy-request-1.0
1001 * The client sent a C-L body, and the administrator has
1002 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1004 * The client sent a T-E body, and the administrator has
1005 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1007 * If both proxy-sendcl and proxy-sendchunked are set, the
1008 * behavior is the same as if neither were set, large bodies
1009 * that can't be read will be forwarded in their original
1010 * form of C-L, or T-E.
1012 * To ensure maximum compatibility, setenv proxy-sendcl
1013 * To reduce server resource use, setenv proxy-sendchunked
1015 * Then address specific servers with conditional setenv
1016 * options to restore the default behavior where desireable.
1018 * We have to compute content length by reading the entire request
1019 * body; if request body is not small, we'll spool the remaining
1020 * input to a temporary file. Chunked is always preferable.
1022 * We can only trust the client-provided C-L if the T-E header
1023 * is absent, and the filters are unchanged (the body won't
1024 * be resized by another content filter).
1026 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1027 /* The whole thing fit, so our decision is trivial, use
1028 * the filtered bytes read from the client for the request
1029 * body Content-Length.
1031 * If we expected no body, and read no body, do not set
1032 * the Content-Length.
1034 if (old_cl_val || old_te_val || bytes_read) {
1035 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1037 rb_method = RB_STREAM_CL;
1039 else if (old_te_val) {
1041 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1042 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1043 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1044 rb_method = RB_SPOOL_CL;
1047 rb_method = RB_STREAM_CHUNKED;
1050 else if (old_cl_val) {
1051 if (r->input_filters == r->proto_input_filters) {
1052 rb_method = RB_STREAM_CL;
1055 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1056 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1057 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1058 rb_method = RB_STREAM_CHUNKED;
1061 rb_method = RB_SPOOL_CL;
1065 /* This is an appropriate default; very efficient for no-body
1066 * requests, and has the behavior that it will not add any C-L
1067 * when the old_cl_val is NULL.
1069 rb_method = RB_SPOOL_CL;
1072 /* Yes I hate gotos. This is the subrequest shortcut */
1075 * Handle Connection: header if we do HTTP/1.1 request:
1076 * If we plan to close the backend connection sent Connection: close
1077 * otherwise sent Connection: Keep-Alive.
1080 if (p_conn->close) {
1081 buf = apr_pstrdup(p, "Connection: close" CRLF);
1084 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1086 ap_xlate_proto_to_ascii(buf, strlen(buf));
1087 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1088 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1091 /* send the request body, if any. */
1093 case RB_STREAM_CHUNKED:
1094 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1098 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1099 input_brigade, old_cl_val);
1102 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1103 input_brigade, (old_cl_val != NULL)
1104 || (old_te_val != NULL)
1105 || (bytes_read > 0));
1108 /* shouldn't be possible */
1109 rv = HTTP_INTERNAL_SERVER_ERROR ;
1114 /* apr_errno value has been logged in lower level method */
1115 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
1116 "proxy: pass request body failed to %pI (%s)"
1119 p_conn->hostname ? p_conn->hostname: "",
1121 c->remote_host ? c->remote_host: "");
1128 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1129 const char *key, const char *value)
1131 static const char *date_hdrs[]
1132 = { "Date", "Expires", "Last-Modified", NULL };
1133 static const struct {
1135 ap_proxy_header_reverse_map_fn func;
1136 } transform_hdrs[] = {
1137 { "Location", ap_proxy_location_reverse_map },
1138 { "Content-Location", ap_proxy_location_reverse_map },
1139 { "URI", ap_proxy_location_reverse_map },
1140 { "Destination", ap_proxy_location_reverse_map },
1141 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1145 for (i = 0; date_hdrs[i]; ++i) {
1146 if (!strcasecmp(date_hdrs[i], key)) {
1147 apr_table_add(r->headers_out, key,
1148 ap_proxy_date_canon(r->pool, value));
1152 for (i = 0; transform_hdrs[i].name; ++i) {
1153 if (!strcasecmp(transform_hdrs[i].name, key)) {
1154 apr_table_add(r->headers_out, key,
1155 (*transform_hdrs[i].func)(r, c, value));
1159 apr_table_add(r->headers_out, key, value);
1164 * Note: pread_len is the length of the response that we've mistakenly
1165 * read (assuming that we don't consider that an error via
1166 * ProxyBadHeader StartBody). This depends on buffer actually being
1167 * local storage to the calling code in order for pread_len to make
1168 * any sense at all, since we depend on buffer still containing
1169 * what was read by ap_getline() upon return.
1171 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1172 char *buffer, int size,
1173 conn_rec *c, int *pread_len)
1177 char field[MAX_STRING_LEN];
1178 int saw_headers = 0;
1179 void *sconf = r->server->module_config;
1180 proxy_server_conf *psc;
1181 proxy_dir_conf *dconf;
1183 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1184 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1186 r->headers_out = apr_table_make(r->pool, 20);
1190 * Read header lines until we get the empty separator line, a read error,
1191 * the connection closes (EOF), or we timeout.
1193 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1195 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1197 /* We may encounter invalid headers, usually from buggy
1198 * MS IIS servers, so we need to determine just how to handle
1199 * them. We can either ignore them, assume that they mark the
1200 * start-of-body (eg: a missing CRLF) or (the default) mark
1201 * the headers as totally bogus and return a 500. The sole
1202 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1203 * in between the usual MIME headers, which is a favorite
1206 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1208 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1209 if (psc->badopt == bad_error) {
1210 /* Nope, it wasn't even an extra HTTP header. Give up. */
1211 r->headers_out = NULL;
1214 else if (psc->badopt == bad_body) {
1215 /* if we've already started loading headers_out, then
1216 * return what we've accumulated so far, in the hopes
1217 * that they are useful; also note that we likely pre-read
1218 * the first line of the response.
1221 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1222 "proxy: Starting body due to bogus non-header in headers "
1223 "returned by %s (%s)", r->uri, r->method);
1227 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1228 "proxy: No HTTP headers "
1229 "returned by %s (%s)", r->uri, r->method);
1234 /* this is the psc->badopt == bad_ignore case */
1235 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1236 "proxy: Ignoring bogus HTTP header "
1237 "returned by %s (%s)", r->uri, r->method);
1243 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1244 * wrong... and so are many others probably.
1246 while (apr_isspace(*value))
1247 ++value; /* Skip to start of value */
1249 /* should strip trailing whitespace as well */
1250 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1254 /* make sure we add so as not to destroy duplicated headers
1255 * Modify headers requiring canonicalisation and/or affected
1256 * by ProxyPassReverse and family with process_proxy_header
1258 process_proxy_header(r, dconf, buffer, value) ;
1261 /* the header was too long; at the least we should skip extra data */
1262 if (len >= size - 1) {
1263 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1264 >= MAX_STRING_LEN - 1) {
1265 /* soak up the extra data */
1267 if (len == 0) /* time to exit the larger loop as well */
1275 static int addit_dammit(void *v, const char *key, const char *val)
1277 apr_table_addn(v, key, val);
1282 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1283 int fold, int *writen)
1289 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1290 apr_brigade_cleanup(bb);
1292 if (rv == APR_SUCCESS) {
1293 *writen = (int) len;
1294 } else if (rv == APR_ENOSPC) {
1304 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1305 proxy_conn_rec *backend,
1307 proxy_server_conf *conf,
1308 char *server_portstr) {
1309 conn_rec *c = r->connection;
1310 char buffer[HUGE_STRING_LEN];
1315 apr_bucket_brigade *bb, *tmp_bb;
1316 int len, backasswards;
1317 int interim_response; /* non-zero whilst interim 1xx responses
1318 * are being read. */
1320 apr_table_t *save_table;
1321 int backend_broke = 0;
1322 static const char *hop_by_hop_hdrs[] =
1323 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1325 const char *te = NULL;
1327 bb = apr_brigade_create(p, c->bucket_alloc);
1329 /* Get response from the remote server, and pass it up the
1333 rp = ap_proxy_make_fake_req(origin, r);
1334 /* In case anyone needs to know, this is a fake request that is really a
1337 rp->proxyreq = PROXYREQ_RESPONSE;
1338 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1342 apr_brigade_cleanup(bb);
1344 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1346 /* handle one potential stray CRLF */
1347 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1350 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1351 "proxy: error reading status line from remote "
1352 "server %s", backend->hostname);
1354 * If we are a reverse proxy request shutdown the connection
1355 * WITHOUT ANY response to trigger a retry by the client
1356 * if allowed (as for idempotent requests).
1357 * BUT currently we should not do this if the request is the
1358 * first request on a keepalive connection as browsers like
1359 * seamonkey only display an empty page in this case and do
1362 if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives) {
1363 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1364 "proxy: Closing connection to client because"
1365 " reading from backend server %s failed. Number"
1366 " of keepalives %i", backend->hostname,
1368 ap_proxy_backend_broke(r, bb);
1370 * Add an EOC bucket to signal the ap_http_header_filter
1371 * that it should get out of our way
1373 e = ap_bucket_eoc_create(c->bucket_alloc);
1374 APR_BRIGADE_INSERT_TAIL(bb, e);
1375 ap_pass_brigade(r->output_filters, bb);
1376 /* Need to return OK to avoid sending an error message */
1379 else if (!c->keepalives) {
1380 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1381 "proxy: NOT Closing connection to client"
1382 " although reading from backend server %s"
1383 " failed.", backend->hostname);
1385 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1386 "Error reading from remote server");
1388 /* XXX: Is this a real headers length send from remote? */
1389 backend->worker->s->read += len;
1391 /* Is it an HTTP/1 response?
1392 * This is buggy if we ever see an HTTP/1.10
1394 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1397 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1401 /* If not an HTTP/1 message or
1402 * if the status line was > 8192 bytes
1404 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1405 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1406 apr_pstrcat(p, "Corrupt status line returned by remote "
1407 "server: ", buffer, NULL));
1411 keepchar = buffer[12];
1413 r->status = atoi(&buffer[9]);
1415 if (keepchar != '\0') {
1416 buffer[12] = keepchar;
1418 /* 2616 requires the space in Status-Line; the origin
1419 * server may have sent one but ap_rgetline_core will
1420 * have stripped it. */
1424 r->status_line = apr_pstrdup(p, &buffer[9]);
1427 /* read the headers. */
1428 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1429 /* Also, take care with headers with multiple occurences. */
1431 /* First, tuck away all already existing cookies */
1432 save_table = apr_table_make(r->pool, 2);
1433 apr_table_do(addit_dammit, save_table, r->headers_out,
1434 "Set-Cookie", NULL);
1436 /* shove the headers direct into r->headers_out */
1437 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1440 if (r->headers_out == NULL) {
1441 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1442 r->server, "proxy: bad HTTP/%d.%d header "
1443 "returned by %s (%s)", major, minor, r->uri,
1445 backend->close += 1;
1447 * ap_send_error relies on a headers_out to be present. we
1448 * are in a bad position here.. so force everything we send out
1449 * to have nothing to do with the incoming packet
1451 r->headers_out = apr_table_make(r->pool,1);
1452 r->status = HTTP_BAD_GATEWAY;
1453 r->status_line = "bad gateway";
1457 /* Now, add in the just read cookies */
1458 apr_table_do(addit_dammit, save_table, r->headers_out,
1459 "Set-Cookie", NULL);
1461 /* and now load 'em all in */
1462 if (!apr_is_empty_table(save_table)) {
1463 apr_table_unset(r->headers_out, "Set-Cookie");
1464 r->headers_out = apr_table_overlay(r->pool,
1469 /* can't have both Content-Length and Transfer-Encoding */
1470 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1471 && apr_table_get(r->headers_out, "Content-Length")) {
1473 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1474 * and Content-Length are received, the latter MUST be
1477 * To help mitigate HTTP Splitting, unset Content-Length
1478 * and shut down the backend server connection
1479 * XXX: We aught to treat such a response as uncachable
1481 apr_table_unset(r->headers_out, "Content-Length");
1482 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1483 "proxy: server %s returned Transfer-Encoding"
1484 " and Content-Length", backend->hostname);
1485 backend->close += 1;
1489 * Save a possible Transfer-Encoding header as we need it later for
1490 * ap_http_filter to know where to end.
1492 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1493 /* strip connection listed hop-by-hop headers from response */
1494 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1497 ap_proxy_clear_connection(p, r->headers_out);
1498 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1499 ap_set_content_type(r, apr_pstrdup(p, buf));
1501 ap_proxy_pre_http_request(origin,rp);
1503 /* Clear hop-by-hop headers */
1504 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1505 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1507 /* Delete warnings with wrong date */
1508 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1510 /* handle Via header in response */
1511 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1512 const char *server_name = ap_get_server_name(r);
1513 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1514 * then the server name returned by ap_get_server_name() is the
1515 * origin server name (which does make too much sense with Via: headers)
1516 * so we use the proxy vhost's name instead.
1518 if (server_name == r->hostname)
1519 server_name = r->server->server_hostname;
1520 /* create a "Via:" response header entry and merge it */
1521 apr_table_addn(r->headers_out, "Via",
1522 (conf->viaopt == via_full)
1523 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1524 HTTP_VERSION_MAJOR(r->proto_num),
1525 HTTP_VERSION_MINOR(r->proto_num),
1528 AP_SERVER_BASEVERSION)
1529 : apr_psprintf(p, "%d.%d %s%s",
1530 HTTP_VERSION_MAJOR(r->proto_num),
1531 HTTP_VERSION_MINOR(r->proto_num),
1537 /* cancel keepalive if HTTP/1.0 or less */
1538 if ((major < 1) || (minor < 1)) {
1539 backend->close += 1;
1540 origin->keepalive = AP_CONN_CLOSE;
1543 /* an http/0.9 response */
1546 r->status_line = "200 OK";
1547 backend->close += 1;
1550 interim_response = ap_is_HTTP_INFO(r->status);
1551 if (interim_response) {
1552 /* RFC2616 tells us to forward this.
1554 * OTOH, an interim response here may mean the backend
1555 * is playing sillybuggers. The Client didn't ask for
1556 * it within the defined HTTP/1.1 mechanisms, and if
1557 * it's an extension, it may also be unsupported by us.
1559 * There's also the possibility that changing existing
1560 * behaviour here might break something.
1562 * So let's make it configurable.
1564 const char *policy = apr_table_get(r->subprocess_env,
1565 "proxy-interim-response");
1566 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1567 "proxy: HTTP: received interim %d response",
1569 if (!policy || !strcasecmp(policy, "RFC")) {
1570 ap_send_interim_response(r, 1);
1572 /* FIXME: refine this to be able to specify per-response-status
1573 * policies and maybe also add option to bail out with 502
1575 else if (strcasecmp(policy, "Suppress")) {
1576 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1577 "undefined proxy interim response policy");
1580 /* Moved the fixups of Date headers and those affected by
1581 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1584 if ((r->status == 401) && (conf->error_override)) {
1586 const char *wa = "WWW-Authenticate";
1587 if ((buf = apr_table_get(r->headers_out, wa))) {
1588 apr_table_set(r->err_headers_out, wa, buf);
1590 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1591 "proxy: origin server sent 401 without WWW-Authenticate header");
1597 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1598 * the response? If so, load the extra data. These are 2 mutually
1599 * exclusive possibilities, that just happen to require very
1602 if (backasswards || pread_len) {
1603 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1606 * At this point in response processing of a 0.9 response,
1607 * we don't know yet whether data is binary or not.
1608 * mod_charset_lite will get control later on, so it cannot
1609 * decide on the conversion of this buffer full of data.
1610 * However, chances are that we are not really talking to an
1611 * HTTP/0.9 server, but to some different protocol, therefore
1612 * the best guess IMHO is to always treat the buffer as "text/x":
1614 ap_xlate_proto_to_ascii(buffer, len);
1615 cntr = (apr_ssize_t)len;
1617 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1618 APR_BRIGADE_INSERT_TAIL(bb, e);
1621 /* send body - but only if a body is expected */
1622 if ((!r->header_only) && /* not HEAD request */
1623 !interim_response && /* not any 1xx response */
1624 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1625 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1627 /* We need to copy the output headers and treat them as input
1628 * headers as well. BUT, we need to do this before we remove
1629 * TE, so that they are preserved accordingly for
1630 * ap_http_filter to know where to end.
1632 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1634 * Restore Transfer-Encoding header from response if we saved
1635 * one before and there is none left. We need it for the
1636 * ap_http_filter. See above.
1638 if (te && !apr_table_get(rp->headers_in, "Transfer-Encoding")) {
1639 apr_table_add(rp->headers_in, "Transfer-Encoding", te);
1642 apr_table_unset(r->headers_out,"Transfer-Encoding");
1644 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1645 "proxy: start body send");
1648 * if we are overriding the errors, we can't put the content
1649 * of the page into the brigade
1651 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1652 /* read the body, pass it to the output filters */
1653 apr_read_type_e mode = APR_NONBLOCK_READ;
1657 apr_off_t readbytes;
1660 rv = ap_get_brigade(rp->input_filters, bb,
1661 AP_MODE_READBYTES, mode,
1662 conf->io_buffer_size);
1664 /* ap_get_brigade will return success with an empty brigade
1665 * for a non-blocking read which would block: */
1666 if (APR_STATUS_IS_EAGAIN(rv)
1667 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1668 /* flush to the client and switch to blocking mode */
1669 e = apr_bucket_flush_create(c->bucket_alloc);
1670 APR_BRIGADE_INSERT_TAIL(bb, e);
1671 if (ap_pass_brigade(r->output_filters, bb)
1676 apr_brigade_cleanup(bb);
1677 mode = APR_BLOCK_READ;
1680 else if (rv == APR_EOF) {
1683 else if (rv != APR_SUCCESS) {
1684 /* In this case, we are in real trouble because
1685 * our backend bailed on us. Pass along a 502 error
1688 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1689 "proxy: error reading response");
1690 ap_proxy_backend_broke(r, bb);
1691 ap_pass_brigade(r->output_filters, bb);
1696 /* next time try a non-blocking read */
1697 mode = APR_NONBLOCK_READ;
1699 apr_brigade_length(bb, 0, &readbytes);
1700 backend->worker->s->read += readbytes;
1703 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1704 r->server, "proxy (PID %d): readbytes: %#x",
1705 getpid(), readbytes);
1709 if (APR_BRIGADE_EMPTY(bb)) {
1710 apr_brigade_cleanup(bb);
1714 /* found the last brigade? */
1715 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1716 /* signal that we must leave */
1720 /* try send what we read */
1721 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1723 /* Ack! Phbtt! Die! User aborted! */
1724 backend->close = 1; /* this causes socket close below */
1728 /* make sure we always clean up after ourselves */
1729 apr_brigade_cleanup(bb);
1733 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1734 "proxy: end body send");
1736 else if (!interim_response) {
1737 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1738 "proxy: header only");
1740 /* Pass EOS bucket down the filter chain. */
1741 e = apr_bucket_eos_create(c->bucket_alloc);
1742 APR_BRIGADE_INSERT_TAIL(bb, e);
1743 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1745 /* Ack! Phbtt! Die! User aborted! */
1746 backend->close = 1; /* this causes socket close below */
1749 apr_brigade_cleanup(bb);
1751 } while (interim_response);
1753 /* If our connection with the client is to be aborted, return DONE. */
1754 if (c->aborted || backend_broke) {
1758 if (conf->error_override) {
1759 /* the code above this checks for 'OK' which is what the hook expects */
1760 if (!ap_is_HTTP_ERROR(r->status))
1763 /* clear r->status for override error, otherwise ErrorDocument
1764 * thinks that this is a recursive error, and doesn't find the
1767 int status = r->status;
1768 r->status = HTTP_OK;
1769 /* Discard body, if one is expected */
1770 if (!r->header_only && /* not HEAD request */
1771 (status != HTTP_NO_CONTENT) && /* not 204 */
1772 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1773 ap_discard_request_body(rp);
1782 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1783 proxy_conn_rec *backend)
1785 ap_proxy_release_connection(scheme, backend, r->server);
1790 * This handles http:// URLs, and other URLs using a remote proxy over http
1791 * If proxyhost is NULL, then contact the server directly, otherwise
1793 * Note that if a proxy is used, then URLs other than http: can be accessed,
1794 * also, if we have trouble which is clearly specific to the proxy, then
1795 * we return DECLINED so that we can try another proxy. (Or the direct
1798 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1799 proxy_server_conf *conf,
1800 char *url, const char *proxyname,
1801 apr_port_t proxyport)
1804 char server_portstr[32];
1806 const char *proxy_function;
1808 proxy_conn_rec *backend = NULL;
1811 /* Note: Memory pool allocation.
1812 * A downstream keepalive connection is always connected to the existence
1813 * (or not) of an upstream keepalive connection. If this is not done then
1814 * load balancing against multiple backend servers breaks (one backend
1815 * server ends up taking 100% of the load), and the risk is run of
1816 * downstream keepalive connections being kept open unnecessarily. This
1817 * keeps webservers busy and ties up resources.
1819 * As a result, we allocate all sockets out of the upstream connection
1820 * pool, and when we want to reuse a socket, we check first whether the
1821 * connection ID of the current upstream connection is the same as that
1822 * of the connection when the socket was opened.
1824 apr_pool_t *p = r->connection->pool;
1825 conn_rec *c = r->connection;
1826 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1828 /* find the scheme */
1829 u = strchr(url, ':');
1830 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1833 return HTTP_BAD_REQUEST;
1834 scheme = apr_pstrndup(c->pool, url, u - url);
1835 /* scheme is lowercase */
1836 ap_str_tolower(scheme);
1838 if (strcmp(scheme, "https") == 0) {
1839 if (!ap_proxy_ssl_enable(NULL)) {
1840 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1841 "proxy: HTTPS: declining URL %s"
1842 " (mod_ssl not configured?)", url);
1846 proxy_function = "HTTPS";
1848 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1849 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1850 "proxy: HTTP: declining URL %s", url);
1851 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1855 proxy_function = "HTTP";
1857 proxy_function = "FTP";
1859 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1860 "proxy: HTTP: serving URL %s", url);
1863 /* create space for state information */
1864 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1865 worker, r->server)) != OK)
1869 backend->is_ssl = is_ssl;
1872 ap_proxy_ssl_connection_cleanup(backend, r);
1875 /* Step One: Determine Who To Connect To */
1876 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1877 uri, &url, proxyname,
1878 proxyport, server_portstr,
1879 sizeof(server_portstr))) != OK)
1882 /* Step Two: Make the Connection */
1883 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1884 if (r->proxyreq == PROXYREQ_PROXY)
1885 status = HTTP_NOT_FOUND;
1887 status = HTTP_SERVICE_UNAVAILABLE;
1891 /* Step Three: Create conn_rec */
1892 if (!backend->connection) {
1893 if ((status = ap_proxy_connection_create(proxy_function, backend,
1894 c, r->server)) != OK)
1898 /* Step Four: Send the Request */
1899 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1900 conf, uri, url, server_portstr)) != OK)
1903 /* Step Five: Receive the Response */
1904 if ((status = ap_proxy_http_process_response(p, r, backend,
1905 backend->connection,
1906 conf, server_portstr)) != OK)
1909 /* Step Six: Clean Up */
1915 ap_proxy_http_cleanup(proxy_function, r, backend);
1919 static apr_status_t warn_rx_free(void *p)
1921 ap_pregfree((apr_pool_t*)p, warn_rx);
1924 static void ap_proxy_http_register_hook(apr_pool_t *p)
1926 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1927 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1928 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1929 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1932 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1933 STANDARD20_MODULE_STUFF,
1934 NULL, /* create per-directory config structure */
1935 NULL, /* merge per-directory config structures */
1936 NULL, /* create per-server config structure */
1937 NULL, /* merge per-server config structures */
1938 NULL, /* command apr_table_t */
1939 ap_proxy_http_register_hook/* register hooks */