1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* HTTP routines for Apache proxy */
19 #include "mod_proxy.h"
22 module AP_MODULE_DECLARE_DATA proxy_http_module;
24 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
26 proxy_conn_rec *backend);
29 * Canonicalise http-like URLs.
30 * scheme is the scheme for the URL
31 * url is the URL starting with the first '/'
32 * def_port is the default port for this scheme.
34 static int proxy_http_canon(request_rec *r, char *url)
36 char *host, *path, *search, sport[7];
39 apr_port_t port, def_port;
41 /* ap_port_of_scheme() */
42 if (strncasecmp(url, "http:", 5) == 0) {
46 else if (strncasecmp(url, "https:", 6) == 0) {
53 def_port = apr_uri_port_of_scheme(scheme);
55 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
56 "proxy: HTTP: canonicalising URL %s", url);
59 * We break the URL into host, port, path, search
62 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
64 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
65 "error parsing URL %s: %s",
67 return HTTP_BAD_REQUEST;
70 /* now parse path/search args, according to rfc1738 */
71 /* N.B. if this isn't a true proxy request, then the URL _path_
72 * has already been decoded. True proxy requests have r->uri
73 * == r->unparsed_uri, and no others have that property.
75 if (r->uri == r->unparsed_uri) {
76 search = strchr(url, '?');
84 /* In a reverse proxy, our URL has been processed, so canonicalise
85 * unless proxy-nocanon is set to say it's raw
86 * In a forward proxy, we have and MUST NOT MANGLE the original.
88 switch (r->proxyreq) {
89 default: /* wtf are we doing here? */
90 case PROXYREQ_REVERSE:
91 if (apr_table_get(r->notes, "proxy-nocanon")) {
92 path = url; /* this is the raw path */
95 path = ap_proxy_canonenc(r->pool, url, strlen(url),
96 enc_path, 0, r->proxyreq);
105 return HTTP_BAD_REQUEST;
107 if (port != def_port)
108 apr_snprintf(sport, sizeof(sport), ":%d", port);
112 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
113 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
115 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
116 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
120 /* Clear all connection-based headers from the incoming headers table */
121 typedef struct header_dptr {
126 static ap_regex_t *warn_rx;
127 static int clean_warning_headers(void *data, const char *key, const char *val)
129 apr_table_t *headers = ((header_dptr*)data)->table;
130 apr_pool_t *pool = ((header_dptr*)data)->pool;
133 apr_time_t warn_time;
134 const int nmatch = 3;
135 ap_regmatch_t pmatch[3];
137 if (headers == NULL) {
138 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
141 * Parse this, suckers!
143 * Warning = "Warning" ":" 1#warning-value
145 * warning-value = warn-code SP warn-agent SP warn-text
149 * warn-agent = ( host [ ":" port ] ) | pseudonym
150 * ; the name or pseudonym of the server adding
151 * ; the Warning header, for use in debugging
152 * warn-text = quoted-string
153 * warn-date = <"> HTTP-date <">
155 * Buggrit, use a bloomin' regexp!
156 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
158 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
159 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
160 pmatch[0].rm_eo - pmatch[0].rm_so);
162 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
163 /* OK, we have a date here */
164 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
165 pmatch[2].rm_eo - pmatch[2].rm_so);
166 warn_time = apr_date_parse_http(date);
168 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
169 apr_table_addn(headers, key, warning);
171 val += pmatch[0].rm_eo;
175 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
180 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
181 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
182 if (x.table != NULL) {
183 apr_table_unset(headers, "Warning");
184 return apr_table_overlay(p, headers, x.table);
190 static int clear_conn_headers(void *data, const char *key, const char *val)
192 apr_table_t *headers = ((header_dptr*)data)->table;
193 apr_pool_t *pool = ((header_dptr*)data)->pool;
195 char *next = apr_pstrdup(pool, val);
198 while (*next && !apr_isspace(*next) && (*next != ',')) {
201 while (*next && (apr_isspace(*next) || (*next == ','))) {
204 apr_table_unset(headers, name);
208 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
213 apr_table_unset(headers, "Proxy-Connection");
214 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
215 apr_table_unset(headers, "Connection");
217 static void add_te_chunked(apr_pool_t *p,
218 apr_bucket_alloc_t *bucket_alloc,
219 apr_bucket_brigade *header_brigade)
223 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
225 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
226 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
228 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
229 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
232 static void add_cl(apr_pool_t *p,
233 apr_bucket_alloc_t *bucket_alloc,
234 apr_bucket_brigade *header_brigade,
240 buf = apr_pstrcat(p, "Content-Length: ",
244 ap_xlate_proto_to_ascii(buf, strlen(buf));
245 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
246 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
249 #define ASCII_CRLF "\015\012"
250 #define ASCII_ZERO "\060"
252 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
253 apr_bucket_brigade *header_brigade)
257 /* add empty line at the end of the headers */
258 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
259 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
262 static int pass_brigade(apr_bucket_alloc_t *bucket_alloc,
263 request_rec *r, proxy_conn_rec *conn,
264 conn_rec *origin, apr_bucket_brigade *bb,
268 apr_off_t transferred;
271 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
272 APR_BRIGADE_INSERT_TAIL(bb, e);
274 apr_brigade_length(bb, 0, &transferred);
275 if (transferred != -1)
276 conn->worker->s->transferred += transferred;
277 status = ap_pass_brigade(origin->output_filters, bb);
278 if (status != APR_SUCCESS) {
279 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
280 "proxy: pass request body failed to %pI (%s)",
281 conn->addr, conn->hostname);
282 if (origin->aborted) {
283 return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY;
286 return HTTP_BAD_REQUEST;
289 apr_brigade_cleanup(bb);
293 #define MAX_MEM_SPOOL 16384
295 static int stream_reqbody_chunked(apr_pool_t *p,
297 proxy_conn_rec *p_conn,
299 apr_bucket_brigade *header_brigade,
300 apr_bucket_brigade *input_brigade)
302 int seen_eos = 0, rv = OK;
306 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
307 apr_bucket_brigade *bb;
310 add_te_chunked(p, bucket_alloc, header_brigade);
311 terminate_headers(bucket_alloc, header_brigade);
313 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
315 char chunk_hdr[20]; /* must be here due to transient bucket. */
317 /* If this brigade contains EOS, either stop or remove it. */
318 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
321 /* We can't pass this EOS to the output_filters. */
322 e = APR_BRIGADE_LAST(input_brigade);
323 apr_bucket_delete(e);
326 apr_brigade_length(input_brigade, 1, &bytes);
328 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
329 "%" APR_UINT64_T_HEX_FMT CRLF,
330 (apr_uint64_t)bytes);
332 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
333 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
335 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
338 * Append the end-of-chunk CRLF
340 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
341 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
343 if (header_brigade) {
344 /* we never sent the header brigade, so go ahead and
345 * take care of that now
350 * Save input_brigade in bb brigade. (At least) in the SSL case
351 * input_brigade contains transient buckets whose data would get
352 * overwritten during the next call of ap_get_brigade in the loop.
353 * ap_save_brigade ensures these buckets to be set aside.
354 * Calling ap_save_brigade with NULL as filter is OK, because
355 * bb brigade already has been created and does not need to get
356 * created by ap_save_brigade.
358 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
359 if (status != APR_SUCCESS) {
360 return HTTP_INTERNAL_SERVER_ERROR;
363 header_brigade = NULL;
369 /* The request is flushed below this loop with chunk EOS header */
370 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
379 status = ap_get_brigade(r->input_filters, input_brigade,
380 AP_MODE_READBYTES, APR_BLOCK_READ,
383 if (status != APR_SUCCESS) {
384 return HTTP_BAD_REQUEST;
388 if (header_brigade) {
389 /* we never sent the header brigade because there was no request body;
395 if (!APR_BRIGADE_EMPTY(input_brigade)) {
396 /* input brigade still has an EOS which we can't pass to the output_filters. */
397 e = APR_BRIGADE_LAST(input_brigade);
398 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
399 apr_bucket_delete(e);
404 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
408 APR_BRIGADE_INSERT_TAIL(bb, e);
410 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
411 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
412 APR_BRIGADE_INSERT_TAIL(bb, e);
415 /* Now we have headers-only, or the chunk EOS mark; flush it */
416 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
420 static int stream_reqbody_cl(apr_pool_t *p,
422 proxy_conn_rec *p_conn,
424 apr_bucket_brigade *header_brigade,
425 apr_bucket_brigade *input_brigade,
426 const char *old_cl_val)
428 int seen_eos = 0, rv = 0;
429 apr_status_t status = APR_SUCCESS;
430 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
431 apr_bucket_brigade *bb;
433 apr_off_t cl_val = 0;
435 apr_off_t bytes_streamed = 0;
438 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
439 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
441 return HTTP_INTERNAL_SERVER_ERROR;
444 terminate_headers(bucket_alloc, header_brigade);
446 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
448 apr_brigade_length(input_brigade, 1, &bytes);
449 bytes_streamed += bytes;
451 /* If this brigade contains EOS, either stop or remove it. */
452 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
455 /* We can't pass this EOS to the output_filters. */
456 e = APR_BRIGADE_LAST(input_brigade);
457 apr_bucket_delete(e);
459 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
460 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
461 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
465 /* C-L < bytes streamed?!?
466 * We will error out after the body is completely
467 * consumed, but we can't stream more bytes at the
468 * back end since they would in part be interpreted
469 * as another request! If nothing is sent, then
472 * Prevents HTTP Response Splitting.
474 if (bytes_streamed > cl_val)
477 if (header_brigade) {
478 /* we never sent the header brigade, so go ahead and
479 * take care of that now
484 * Save input_brigade in bb brigade. (At least) in the SSL case
485 * input_brigade contains transient buckets whose data would get
486 * overwritten during the next call of ap_get_brigade in the loop.
487 * ap_save_brigade ensures these buckets to be set aside.
488 * Calling ap_save_brigade with NULL as filter is OK, because
489 * bb brigade already has been created and does not need to get
490 * created by ap_save_brigade.
492 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
493 if (status != APR_SUCCESS) {
494 return HTTP_INTERNAL_SERVER_ERROR;
497 header_brigade = NULL;
503 /* Once we hit EOS, we are ready to flush. */
504 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
513 status = ap_get_brigade(r->input_filters, input_brigade,
514 AP_MODE_READBYTES, APR_BLOCK_READ,
517 if (status != APR_SUCCESS) {
518 return HTTP_BAD_REQUEST;
522 if (bytes_streamed != cl_val) {
523 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
524 "proxy: client %s given Content-Length did not match"
525 " number of body bytes read", r->connection->remote_ip);
526 return HTTP_BAD_REQUEST;
529 if (header_brigade) {
530 /* we never sent the header brigade since there was no request
531 * body; send it now with the flush flag
534 return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
540 static int spool_reqbody_cl(apr_pool_t *p,
542 proxy_conn_rec *p_conn,
544 apr_bucket_brigade *header_brigade,
545 apr_bucket_brigade *input_brigade,
550 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
551 apr_bucket_brigade *body_brigade;
553 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
554 apr_file_t *tmpfile = NULL;
556 body_brigade = apr_brigade_create(p, bucket_alloc);
558 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
560 /* If this brigade contains EOS, either stop or remove it. */
561 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
564 /* We can't pass this EOS to the output_filters. */
565 e = APR_BRIGADE_LAST(input_brigade);
566 apr_bucket_delete(e);
569 apr_brigade_length(input_brigade, 1, &bytes);
571 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
572 /* can't spool any more in memory; write latest brigade to disk */
573 if (tmpfile == NULL) {
574 const char *temp_dir;
577 status = apr_temp_dir_get(&temp_dir, p);
578 if (status != APR_SUCCESS) {
579 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
580 "proxy: search for temporary directory failed");
581 return HTTP_INTERNAL_SERVER_ERROR;
583 apr_filepath_merge(&template, temp_dir,
584 "modproxy.tmp.XXXXXX",
585 APR_FILEPATH_NATIVE, p);
586 status = apr_file_mktemp(&tmpfile, template, 0, p);
587 if (status != APR_SUCCESS) {
588 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
589 "proxy: creation of temporary file in directory %s failed",
591 return HTTP_INTERNAL_SERVER_ERROR;
594 for (e = APR_BRIGADE_FIRST(input_brigade);
595 e != APR_BRIGADE_SENTINEL(input_brigade);
596 e = APR_BUCKET_NEXT(e)) {
598 apr_size_t bytes_read, bytes_written;
600 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
601 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
602 if (status != APR_SUCCESS) {
603 const char *tmpfile_name;
605 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
606 tmpfile_name = "(unknown)";
608 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
609 "proxy: write to temporary file %s failed",
611 return HTTP_INTERNAL_SERVER_ERROR;
613 AP_DEBUG_ASSERT(bytes_read == bytes_written);
614 fsize += bytes_written;
616 apr_brigade_cleanup(input_brigade);
621 * Save input_brigade in body_brigade. (At least) in the SSL case
622 * input_brigade contains transient buckets whose data would get
623 * overwritten during the next call of ap_get_brigade in the loop.
624 * ap_save_brigade ensures these buckets to be set aside.
625 * Calling ap_save_brigade with NULL as filter is OK, because
626 * body_brigade already has been created and does not need to get
627 * created by ap_save_brigade.
629 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
630 if (status != APR_SUCCESS) {
631 return HTTP_INTERNAL_SERVER_ERROR;
636 bytes_spooled += bytes;
642 status = ap_get_brigade(r->input_filters, input_brigade,
643 AP_MODE_READBYTES, APR_BLOCK_READ,
646 if (status != APR_SUCCESS) {
647 return HTTP_BAD_REQUEST;
651 if (bytes_spooled || force_cl) {
652 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
654 terminate_headers(bucket_alloc, header_brigade);
655 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
657 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
659 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
660 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
661 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
663 /* This is all a single brigade, pass with flush flagged */
664 return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
668 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
669 proxy_conn_rec *p_conn, conn_rec *origin,
670 proxy_server_conf *conf,
672 char *url, char *server_portstr)
674 conn_rec *c = r->connection;
675 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
676 apr_bucket_brigade *header_brigade;
677 apr_bucket_brigade *input_brigade;
678 apr_bucket_brigade *temp_brigade;
681 const apr_array_header_t *headers_in_array;
682 const apr_table_entry_t *headers_in;
685 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
686 enum rb_methods rb_method = RB_INIT;
687 const char *old_cl_val = NULL;
688 const char *old_te_val = NULL;
689 apr_off_t bytes_read = 0;
692 apr_table_t *headers_in_copy;
694 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
697 * Send the HTTP/1.1 request to the remote server
700 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
701 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
705 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
708 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
709 origin->keepalive = AP_CONN_CLOSE;
712 ap_xlate_proto_to_ascii(buf, strlen(buf));
713 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
714 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
715 if (conf->preserve_host == 0) {
716 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
717 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
720 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
724 /* don't want to use r->hostname, as the incoming header might have a
727 const char* hostname = apr_table_get(r->headers_in,"Host");
729 hostname = r->server->server_hostname;
730 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
731 "proxy: no HTTP 0.9 request (with no host line) "
732 "on incoming request and preserve host set "
733 "forcing hostname to be %s for uri %s",
737 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
739 ap_xlate_proto_to_ascii(buf, strlen(buf));
740 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
741 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
744 if (conf->viaopt == via_block) {
745 /* Block all outgoing Via: headers */
746 apr_table_unset(r->headers_in, "Via");
747 } else if (conf->viaopt != via_off) {
748 const char *server_name = ap_get_server_name(r);
749 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
750 * then the server name returned by ap_get_server_name() is the
751 * origin server name (which does make too much sense with Via: headers)
752 * so we use the proxy vhost's name instead.
754 if (server_name == r->hostname)
755 server_name = r->server->server_hostname;
756 /* Create a "Via:" request header entry and merge it */
757 /* Generate outgoing Via: header with/without server comment: */
758 apr_table_mergen(r->headers_in, "Via",
759 (conf->viaopt == via_full)
760 ? apr_psprintf(p, "%d.%d %s%s (%s)",
761 HTTP_VERSION_MAJOR(r->proto_num),
762 HTTP_VERSION_MINOR(r->proto_num),
763 server_name, server_portstr,
764 AP_SERVER_BASEVERSION)
765 : apr_psprintf(p, "%d.%d %s%s",
766 HTTP_VERSION_MAJOR(r->proto_num),
767 HTTP_VERSION_MINOR(r->proto_num),
768 server_name, server_portstr)
772 /* X-Forwarded-*: handling
777 * These request headers are only really useful when the mod_proxy
778 * is used in a reverse proxy configuration, so that useful info
779 * about the client can be passed through the reverse proxy and on
780 * to the backend server, which may require the information to
783 * In a forward proxy situation, these options are a potential
784 * privacy violation, as information about clients behind the proxy
785 * are revealed to arbitrary servers out there on the internet.
787 * The HTTP/1.1 Via: header is designed for passing client
788 * information through proxies to a server, and should be used in
789 * a forward proxy configuation instead of X-Forwarded-*. See the
790 * ProxyVia option for details.
793 if (PROXYREQ_REVERSE == r->proxyreq) {
796 /* Add X-Forwarded-For: so that the upstream has a chance to
797 * determine, where the original request came from.
799 apr_table_mergen(r->headers_in, "X-Forwarded-For",
802 /* Add X-Forwarded-Host: so that upstream knows what the
803 * original request hostname was.
805 if ((buf = apr_table_get(r->headers_in, "Host"))) {
806 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
809 /* Add X-Forwarded-Server: so that upstream knows what the
810 * name of this proxy server is (if there are more than one)
811 * XXX: This duplicates Via: - do we strictly need it?
813 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
814 r->server->server_hostname);
819 * Make a copy of the headers_in table before clearing the connection
820 * headers as we need the connection headers later in the http output
821 * filter to prepare the correct response headers.
823 * Note: We need to take r->pool for apr_table_copy as the key / value
824 * pairs in r->headers_in have been created out of r->pool and
825 * p might be (and actually is) a longer living pool.
826 * This would trigger the bad pool ancestry abort in apr_table_copy if
827 * apr is compiled with APR_POOL_DEBUG.
829 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
830 ap_proxy_clear_connection(p, headers_in_copy);
831 /* send request headers */
832 headers_in_array = apr_table_elts(headers_in_copy);
833 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
834 for (counter = 0; counter < headers_in_array->nelts; counter++) {
835 if (headers_in[counter].key == NULL
836 || headers_in[counter].val == NULL
839 || !strcasecmp(headers_in[counter].key, "Host")
841 /* Clear out hop-by-hop request headers not to send
842 * RFC2616 13.5.1 says we should strip these headers
844 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
845 || !strcasecmp(headers_in[counter].key, "TE")
846 || !strcasecmp(headers_in[counter].key, "Trailer")
847 || !strcasecmp(headers_in[counter].key, "Upgrade")
852 /* Do we want to strip Proxy-Authorization ?
853 * If we haven't used it, then NO
854 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
855 * So let's make it configurable by env.
857 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
858 if (r->user != NULL) { /* we've authenticated */
859 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
866 /* Skip Transfer-Encoding and Content-Length for now.
868 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
869 old_te_val = headers_in[counter].val;
872 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
873 old_cl_val = headers_in[counter].val;
877 /* for sub-requests, ignore freshness/expiry headers */
879 if ( !strcasecmp(headers_in[counter].key, "If-Match")
880 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
881 || !strcasecmp(headers_in[counter].key, "If-Range")
882 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
883 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
888 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
889 headers_in[counter].val, CRLF,
891 ap_xlate_proto_to_ascii(buf, strlen(buf));
892 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
893 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
896 /* We have headers, let's figure out our request body... */
897 input_brigade = apr_brigade_create(p, bucket_alloc);
899 /* sub-requests never use keepalives, and mustn't pass request bodies.
900 * Because the new logic looks at input_brigade, we will self-terminate
901 * input_brigade and jump past all of the request body logic...
902 * Reading anything with ap_get_brigade is likely to consume the
903 * main request's body or read beyond EOS - which would be unplesant.
906 /* XXX: Why DON'T sub-requests use keepalives? */
910 apr_table_unset(r->headers_in, "Content-Length");
914 apr_table_unset(r->headers_in, "Transfer-Encoding");
916 rb_method = RB_STREAM_CL;
917 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
918 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
922 /* WE only understand chunked. Other modules might inject
923 * (and therefore, decode) other flavors but we don't know
924 * that the can and have done so unless they they remove
925 * their decoding from the headers_in T-E list.
926 * XXX: Make this extensible, but in doing so, presume the
927 * encoding has been done by the extensions' handler, and
928 * do not modify add_te_chunked's logic
930 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
931 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
932 "proxy: %s Transfer-Encoding is not supported",
934 return HTTP_INTERNAL_SERVER_ERROR;
937 if (old_cl_val && old_te_val) {
938 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
939 "proxy: client %s (%s) requested Transfer-Encoding "
940 "chunked body with Content-Length (C-L ignored)",
941 c->remote_ip, c->remote_host ? c->remote_host: "");
942 apr_table_unset(r->headers_in, "Content-Length");
944 origin->keepalive = AP_CONN_CLOSE;
948 /* Prefetch MAX_MEM_SPOOL bytes
950 * This helps us avoid any election of C-L v.s. T-E
951 * request bodies, since we are willing to keep in
952 * memory this much data, in any case. This gives
953 * us an instant C-L election if the body is of some
956 temp_brigade = apr_brigade_create(p, bucket_alloc);
958 status = ap_get_brigade(r->input_filters, temp_brigade,
959 AP_MODE_READBYTES, APR_BLOCK_READ,
960 MAX_MEM_SPOOL - bytes_read);
961 if (status != APR_SUCCESS) {
962 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
963 "proxy: prefetch request body failed to %pI (%s)"
965 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
966 c->remote_ip, c->remote_host ? c->remote_host: "");
967 return HTTP_BAD_REQUEST;
970 apr_brigade_length(temp_brigade, 1, &bytes);
974 * Save temp_brigade in input_brigade. (At least) in the SSL case
975 * temp_brigade contains transient buckets whose data would get
976 * overwritten during the next call of ap_get_brigade in the loop.
977 * ap_save_brigade ensures these buckets to be set aside.
978 * Calling ap_save_brigade with NULL as filter is OK, because
979 * input_brigade already has been created and does not need to get
980 * created by ap_save_brigade.
982 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
983 if (status != APR_SUCCESS) {
984 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
985 "proxy: processing prefetched request body failed"
986 " to %pI (%s) from %s (%s)",
987 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
988 c->remote_ip, c->remote_host ? c->remote_host: "");
989 return HTTP_INTERNAL_SERVER_ERROR;
992 /* Ensure we don't hit a wall where we have a buffer too small
993 * for ap_get_brigade's filters to fetch us another bucket,
994 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
995 * (an arbitrary value.)
997 } while ((bytes_read < MAX_MEM_SPOOL - 80)
998 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1000 /* Use chunked request body encoding or send a content-length body?
1004 * We have no request body (handled by RB_STREAM_CL)
1006 * We have a request body length <= MAX_MEM_SPOOL
1008 * The administrator has setenv force-proxy-request-1.0
1010 * The client sent a C-L body, and the administrator has
1011 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1013 * The client sent a T-E body, and the administrator has
1014 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1016 * If both proxy-sendcl and proxy-sendchunked are set, the
1017 * behavior is the same as if neither were set, large bodies
1018 * that can't be read will be forwarded in their original
1019 * form of C-L, or T-E.
1021 * To ensure maximum compatibility, setenv proxy-sendcl
1022 * To reduce server resource use, setenv proxy-sendchunked
1024 * Then address specific servers with conditional setenv
1025 * options to restore the default behavior where desireable.
1027 * We have to compute content length by reading the entire request
1028 * body; if request body is not small, we'll spool the remaining
1029 * input to a temporary file. Chunked is always preferable.
1031 * We can only trust the client-provided C-L if the T-E header
1032 * is absent, and the filters are unchanged (the body won't
1033 * be resized by another content filter).
1035 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1036 /* The whole thing fit, so our decision is trivial, use
1037 * the filtered bytes read from the client for the request
1038 * body Content-Length.
1040 * If we expected no body, and read no body, do not set
1041 * the Content-Length.
1043 if (old_cl_val || old_te_val || bytes_read) {
1044 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1046 rb_method = RB_STREAM_CL;
1048 else if (old_te_val) {
1050 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1051 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1052 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1053 rb_method = RB_SPOOL_CL;
1056 rb_method = RB_STREAM_CHUNKED;
1059 else if (old_cl_val) {
1060 if (r->input_filters == r->proto_input_filters) {
1061 rb_method = RB_STREAM_CL;
1064 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1065 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1066 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1067 rb_method = RB_STREAM_CHUNKED;
1070 rb_method = RB_SPOOL_CL;
1074 /* This is an appropriate default; very efficient for no-body
1075 * requests, and has the behavior that it will not add any C-L
1076 * when the old_cl_val is NULL.
1078 rb_method = RB_SPOOL_CL;
1081 /* Yes I hate gotos. This is the subrequest shortcut */
1084 * Handle Connection: header if we do HTTP/1.1 request:
1085 * If we plan to close the backend connection sent Connection: close
1086 * otherwise sent Connection: Keep-Alive.
1089 if (p_conn->close) {
1090 buf = apr_pstrdup(p, "Connection: close" CRLF);
1093 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1095 ap_xlate_proto_to_ascii(buf, strlen(buf));
1096 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1097 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1100 /* send the request body, if any. */
1102 case RB_STREAM_CHUNKED:
1103 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1107 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1108 input_brigade, old_cl_val);
1111 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1112 input_brigade, (old_cl_val != NULL)
1113 || (old_te_val != NULL)
1114 || (bytes_read > 0));
1117 /* shouldn't be possible */
1118 rv = HTTP_INTERNAL_SERVER_ERROR ;
1123 /* apr_errno value has been logged in lower level method */
1124 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
1125 "proxy: pass request body failed to %pI (%s)"
1128 p_conn->hostname ? p_conn->hostname: "",
1130 c->remote_host ? c->remote_host: "");
1137 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1138 const char *key, const char *value)
1140 static const char *date_hdrs[]
1141 = { "Date", "Expires", "Last-Modified", NULL };
1142 static const struct {
1144 ap_proxy_header_reverse_map_fn func;
1145 } transform_hdrs[] = {
1146 { "Location", ap_proxy_location_reverse_map },
1147 { "Content-Location", ap_proxy_location_reverse_map },
1148 { "URI", ap_proxy_location_reverse_map },
1149 { "Destination", ap_proxy_location_reverse_map },
1150 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1154 for (i = 0; date_hdrs[i]; ++i) {
1155 if (!strcasecmp(date_hdrs[i], key)) {
1156 apr_table_add(r->headers_out, key,
1157 ap_proxy_date_canon(r->pool, value));
1161 for (i = 0; transform_hdrs[i].name; ++i) {
1162 if (!strcasecmp(transform_hdrs[i].name, key)) {
1163 apr_table_add(r->headers_out, key,
1164 (*transform_hdrs[i].func)(r, c, value));
1168 apr_table_add(r->headers_out, key, value);
1173 * Note: pread_len is the length of the response that we've mistakenly
1174 * read (assuming that we don't consider that an error via
1175 * ProxyBadHeader StartBody). This depends on buffer actually being
1176 * local storage to the calling code in order for pread_len to make
1177 * any sense at all, since we depend on buffer still containing
1178 * what was read by ap_getline() upon return.
1180 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1181 char *buffer, int size,
1182 conn_rec *c, int *pread_len)
1186 char field[MAX_STRING_LEN];
1187 int saw_headers = 0;
1188 void *sconf = r->server->module_config;
1189 proxy_server_conf *psc;
1190 proxy_dir_conf *dconf;
1192 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1193 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1195 r->headers_out = apr_table_make(r->pool, 20);
1199 * Read header lines until we get the empty separator line, a read error,
1200 * the connection closes (EOF), or we timeout.
1202 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1204 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1206 /* We may encounter invalid headers, usually from buggy
1207 * MS IIS servers, so we need to determine just how to handle
1208 * them. We can either ignore them, assume that they mark the
1209 * start-of-body (eg: a missing CRLF) or (the default) mark
1210 * the headers as totally bogus and return a 500. The sole
1211 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1212 * in between the usual MIME headers, which is a favorite
1215 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1217 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1218 if (psc->badopt == bad_error) {
1219 /* Nope, it wasn't even an extra HTTP header. Give up. */
1220 r->headers_out = NULL;
1223 else if (psc->badopt == bad_body) {
1224 /* if we've already started loading headers_out, then
1225 * return what we've accumulated so far, in the hopes
1226 * that they are useful; also note that we likely pre-read
1227 * the first line of the response.
1230 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1231 "proxy: Starting body due to bogus non-header in headers "
1232 "returned by %s (%s)", r->uri, r->method);
1236 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1237 "proxy: No HTTP headers "
1238 "returned by %s (%s)", r->uri, r->method);
1243 /* this is the psc->badopt == bad_ignore case */
1244 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1245 "proxy: Ignoring bogus HTTP header "
1246 "returned by %s (%s)", r->uri, r->method);
1252 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1253 * wrong... and so are many others probably.
1255 while (apr_isspace(*value))
1256 ++value; /* Skip to start of value */
1258 /* should strip trailing whitespace as well */
1259 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1263 /* make sure we add so as not to destroy duplicated headers
1264 * Modify headers requiring canonicalisation and/or affected
1265 * by ProxyPassReverse and family with process_proxy_header
1267 process_proxy_header(r, dconf, buffer, value) ;
1270 /* the header was too long; at the least we should skip extra data */
1271 if (len >= size - 1) {
1272 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1273 >= MAX_STRING_LEN - 1) {
1274 /* soak up the extra data */
1276 if (len == 0) /* time to exit the larger loop as well */
1284 static int addit_dammit(void *v, const char *key, const char *val)
1286 apr_table_addn(v, key, val);
1291 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1292 int fold, int *writen)
1298 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1299 apr_brigade_cleanup(bb);
1301 if (rv == APR_SUCCESS) {
1302 *writen = (int) len;
1303 } else if (rv == APR_ENOSPC) {
1313 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1314 proxy_conn_rec *backend,
1316 proxy_server_conf *conf,
1317 char *server_portstr) {
1318 conn_rec *c = r->connection;
1319 char buffer[HUGE_STRING_LEN];
1324 apr_bucket_brigade *bb, *tmp_bb;
1325 int len, backasswards;
1326 int interim_response; /* non-zero whilst interim 1xx responses
1327 * are being read. */
1329 apr_table_t *save_table;
1330 int backend_broke = 0;
1331 static const char *hop_by_hop_hdrs[] =
1332 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1335 bb = apr_brigade_create(p, c->bucket_alloc);
1337 /* Get response from the remote server, and pass it up the
1341 rp = ap_proxy_make_fake_req(origin, r);
1342 /* In case anyone needs to know, this is a fake request that is really a
1345 rp->proxyreq = PROXYREQ_RESPONSE;
1346 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1350 apr_brigade_cleanup(bb);
1352 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1354 /* handle one potential stray CRLF */
1355 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1358 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1359 "proxy: error reading status line from remote "
1360 "server %s", backend->hostname);
1361 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1362 "Error reading from remote server");
1364 /* XXX: Is this a real headers length send from remote? */
1365 backend->worker->s->read += len;
1367 /* Is it an HTTP/1 response?
1368 * This is buggy if we ever see an HTTP/1.10
1370 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1373 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1377 /* If not an HTTP/1 message or
1378 * if the status line was > 8192 bytes
1380 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1381 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1382 apr_pstrcat(p, "Corrupt status line returned by remote "
1383 "server: ", buffer, NULL));
1387 keepchar = buffer[12];
1389 r->status = atoi(&buffer[9]);
1391 if (keepchar != '\0') {
1392 buffer[12] = keepchar;
1394 /* 2616 requires the space in Status-Line; the origin
1395 * server may have sent one but ap_rgetline_core will
1396 * have stripped it. */
1400 r->status_line = apr_pstrdup(p, &buffer[9]);
1403 /* read the headers. */
1404 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1405 /* Also, take care with headers with multiple occurences. */
1407 /* First, tuck away all already existing cookies */
1408 save_table = apr_table_make(r->pool, 2);
1409 apr_table_do(addit_dammit, save_table, r->headers_out,
1410 "Set-Cookie", NULL);
1412 /* shove the headers direct into r->headers_out */
1413 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1416 if (r->headers_out == NULL) {
1417 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1418 r->server, "proxy: bad HTTP/%d.%d header "
1419 "returned by %s (%s)", major, minor, r->uri,
1421 backend->close += 1;
1423 * ap_send_error relies on a headers_out to be present. we
1424 * are in a bad position here.. so force everything we send out
1425 * to have nothing to do with the incoming packet
1427 r->headers_out = apr_table_make(r->pool,1);
1428 r->status = HTTP_BAD_GATEWAY;
1429 r->status_line = "bad gateway";
1433 /* Now, add in the just read cookies */
1434 apr_table_do(addit_dammit, save_table, r->headers_out,
1435 "Set-Cookie", NULL);
1437 /* and now load 'em all in */
1438 if (!apr_is_empty_table(save_table)) {
1439 apr_table_unset(r->headers_out, "Set-Cookie");
1440 r->headers_out = apr_table_overlay(r->pool,
1445 /* can't have both Content-Length and Transfer-Encoding */
1446 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1447 && apr_table_get(r->headers_out, "Content-Length")) {
1449 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1450 * and Content-Length are received, the latter MUST be
1453 * To help mitigate HTTP Splitting, unset Content-Length
1454 * and shut down the backend server connection
1455 * XXX: We aught to treat such a response as uncachable
1457 apr_table_unset(r->headers_out, "Content-Length");
1458 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1459 "proxy: server %s returned Transfer-Encoding"
1460 " and Content-Length", backend->hostname);
1461 backend->close += 1;
1464 /* strip connection listed hop-by-hop headers from response */
1465 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1468 ap_proxy_clear_connection(p, r->headers_out);
1469 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1470 ap_set_content_type(r, apr_pstrdup(p, buf));
1472 ap_proxy_pre_http_request(origin,rp);
1474 /* Clear hop-by-hop headers */
1475 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1476 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1478 /* Delete warnings with wrong date */
1479 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1481 /* handle Via header in response */
1482 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1483 const char *server_name = ap_get_server_name(r);
1484 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1485 * then the server name returned by ap_get_server_name() is the
1486 * origin server name (which does make too much sense with Via: headers)
1487 * so we use the proxy vhost's name instead.
1489 if (server_name == r->hostname)
1490 server_name = r->server->server_hostname;
1491 /* create a "Via:" response header entry and merge it */
1492 apr_table_addn(r->headers_out, "Via",
1493 (conf->viaopt == via_full)
1494 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1495 HTTP_VERSION_MAJOR(r->proto_num),
1496 HTTP_VERSION_MINOR(r->proto_num),
1499 AP_SERVER_BASEVERSION)
1500 : apr_psprintf(p, "%d.%d %s%s",
1501 HTTP_VERSION_MAJOR(r->proto_num),
1502 HTTP_VERSION_MINOR(r->proto_num),
1508 /* cancel keepalive if HTTP/1.0 or less */
1509 if ((major < 1) || (minor < 1)) {
1510 backend->close += 1;
1511 origin->keepalive = AP_CONN_CLOSE;
1514 /* an http/0.9 response */
1517 r->status_line = "200 OK";
1518 backend->close += 1;
1521 interim_response = ap_is_HTTP_INFO(r->status);
1522 if (interim_response) {
1523 /* RFC2616 tells us to forward this.
1525 * OTOH, an interim response here may mean the backend
1526 * is playing sillybuggers. The Client didn't ask for
1527 * it within the defined HTTP/1.1 mechanisms, and if
1528 * it's an extension, it may also be unsupported by us.
1530 * There's also the possibility that changing existing
1531 * behaviour here might break something.
1533 * So let's make it configurable.
1535 const char *policy = apr_table_get(r->subprocess_env,
1536 "proxy-interim-response");
1537 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1538 "proxy: HTTP: received interim %d response",
1540 if (!policy || !strcasecmp(policy, "RFC")) {
1541 ap_send_interim_response(r, 1);
1543 /* FIXME: refine this to be able to specify per-response-status
1544 * policies and maybe also add option to bail out with 502
1546 else if (strcasecmp(policy, "Suppress")) {
1547 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1548 "undefined proxy interim response policy");
1551 /* Moved the fixups of Date headers and those affected by
1552 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1555 if ((r->status == 401) && (conf->error_override)) {
1557 const char *wa = "WWW-Authenticate";
1558 if ((buf = apr_table_get(r->headers_out, wa))) {
1559 apr_table_set(r->err_headers_out, wa, buf);
1561 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1562 "proxy: origin server sent 401 without WWW-Authenticate header");
1568 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1569 * the response? If so, load the extra data. These are 2 mutually
1570 * exclusive possibilities, that just happen to require very
1573 if (backasswards || pread_len) {
1574 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1577 * At this point in response processing of a 0.9 response,
1578 * we don't know yet whether data is binary or not.
1579 * mod_charset_lite will get control later on, so it cannot
1580 * decide on the conversion of this buffer full of data.
1581 * However, chances are that we are not really talking to an
1582 * HTTP/0.9 server, but to some different protocol, therefore
1583 * the best guess IMHO is to always treat the buffer as "text/x":
1585 ap_xlate_proto_to_ascii(buffer, len);
1586 cntr = (apr_ssize_t)len;
1588 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1589 APR_BRIGADE_INSERT_TAIL(bb, e);
1592 /* send body - but only if a body is expected */
1593 if ((!r->header_only) && /* not HEAD request */
1594 !interim_response && /* not any 1xx response */
1595 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1596 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1598 /* We need to copy the output headers and treat them as input
1599 * headers as well. BUT, we need to do this before we remove
1600 * TE, so that they are preserved accordingly for
1601 * ap_http_filter to know where to end.
1603 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1605 apr_table_unset(r->headers_out,"Transfer-Encoding");
1607 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1608 "proxy: start body send");
1611 * if we are overriding the errors, we can't put the content
1612 * of the page into the brigade
1614 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1615 /* read the body, pass it to the output filters */
1616 apr_read_type_e mode = APR_NONBLOCK_READ;
1620 apr_off_t readbytes;
1623 rv = ap_get_brigade(rp->input_filters, bb,
1624 AP_MODE_READBYTES, mode,
1625 conf->io_buffer_size);
1627 /* ap_get_brigade will return success with an empty brigade
1628 * for a non-blocking read which would block: */
1629 if (APR_STATUS_IS_EAGAIN(rv)
1630 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1631 /* flush to the client and switch to blocking mode */
1632 e = apr_bucket_flush_create(c->bucket_alloc);
1633 APR_BRIGADE_INSERT_TAIL(bb, e);
1634 if (ap_pass_brigade(r->output_filters, bb)
1639 apr_brigade_cleanup(bb);
1640 mode = APR_BLOCK_READ;
1643 else if (rv == APR_EOF) {
1646 else if (rv != APR_SUCCESS) {
1647 /* In this case, we are in real trouble because
1648 * our backend bailed on us. Pass along a 502 error
1651 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1652 "proxy: error reading response");
1653 ap_proxy_backend_broke(r, bb);
1654 ap_pass_brigade(r->output_filters, bb);
1659 /* next time try a non-blocking read */
1660 mode = APR_NONBLOCK_READ;
1662 apr_brigade_length(bb, 0, &readbytes);
1663 backend->worker->s->read += readbytes;
1666 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1667 r->server, "proxy (PID %d): readbytes: %#x",
1668 getpid(), readbytes);
1672 if (APR_BRIGADE_EMPTY(bb)) {
1673 apr_brigade_cleanup(bb);
1677 /* found the last brigade? */
1678 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1679 /* signal that we must leave */
1683 /* try send what we read */
1684 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1686 /* Ack! Phbtt! Die! User aborted! */
1687 backend->close = 1; /* this causes socket close below */
1691 /* make sure we always clean up after ourselves */
1692 apr_brigade_cleanup(bb);
1696 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1697 "proxy: end body send");
1699 else if (!interim_response) {
1700 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1701 "proxy: header only");
1703 /* Pass EOS bucket down the filter chain. */
1704 e = apr_bucket_eos_create(c->bucket_alloc);
1705 APR_BRIGADE_INSERT_TAIL(bb, e);
1706 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1708 /* Ack! Phbtt! Die! User aborted! */
1709 backend->close = 1; /* this causes socket close below */
1712 apr_brigade_cleanup(bb);
1714 } while (interim_response);
1716 /* If our connection with the client is to be aborted, return DONE. */
1717 if (c->aborted || backend_broke) {
1721 if (conf->error_override) {
1722 /* the code above this checks for 'OK' which is what the hook expects */
1723 if (!ap_is_HTTP_ERROR(r->status))
1726 /* clear r->status for override error, otherwise ErrorDocument
1727 * thinks that this is a recursive error, and doesn't find the
1730 int status = r->status;
1731 r->status = HTTP_OK;
1732 /* Discard body, if one is expected */
1733 if (!r->header_only && /* not HEAD request */
1734 (status != HTTP_NO_CONTENT) && /* not 204 */
1735 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1736 ap_discard_request_body(rp);
1745 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1746 proxy_conn_rec *backend)
1748 ap_proxy_release_connection(scheme, backend, r->server);
1753 * This handles http:// URLs, and other URLs using a remote proxy over http
1754 * If proxyhost is NULL, then contact the server directly, otherwise
1756 * Note that if a proxy is used, then URLs other than http: can be accessed,
1757 * also, if we have trouble which is clearly specific to the proxy, then
1758 * we return DECLINED so that we can try another proxy. (Or the direct
1761 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1762 proxy_server_conf *conf,
1763 char *url, const char *proxyname,
1764 apr_port_t proxyport)
1767 char server_portstr[32];
1769 const char *proxy_function;
1771 proxy_conn_rec *backend = NULL;
1774 /* Note: Memory pool allocation.
1775 * A downstream keepalive connection is always connected to the existence
1776 * (or not) of an upstream keepalive connection. If this is not done then
1777 * load balancing against multiple backend servers breaks (one backend
1778 * server ends up taking 100% of the load), and the risk is run of
1779 * downstream keepalive connections being kept open unnecessarily. This
1780 * keeps webservers busy and ties up resources.
1782 * As a result, we allocate all sockets out of the upstream connection
1783 * pool, and when we want to reuse a socket, we check first whether the
1784 * connection ID of the current upstream connection is the same as that
1785 * of the connection when the socket was opened.
1787 apr_pool_t *p = r->connection->pool;
1788 conn_rec *c = r->connection;
1789 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1791 /* find the scheme */
1792 u = strchr(url, ':');
1793 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1796 return HTTP_BAD_REQUEST;
1797 scheme = apr_pstrndup(c->pool, url, u - url);
1798 /* scheme is lowercase */
1799 ap_str_tolower(scheme);
1801 if (strcmp(scheme, "https") == 0) {
1802 if (!ap_proxy_ssl_enable(NULL)) {
1803 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1804 "proxy: HTTPS: declining URL %s"
1805 " (mod_ssl not configured?)", url);
1809 proxy_function = "HTTPS";
1811 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1812 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1813 "proxy: HTTP: declining URL %s", url);
1814 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1818 proxy_function = "HTTP";
1820 proxy_function = "FTP";
1822 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1823 "proxy: HTTP: serving URL %s", url);
1826 /* create space for state information */
1827 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1828 worker, r->server)) != OK)
1832 backend->is_ssl = is_ssl;
1835 ap_proxy_ssl_connection_cleanup(backend, r);
1838 /* Step One: Determine Who To Connect To */
1839 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1840 uri, &url, proxyname,
1841 proxyport, server_portstr,
1842 sizeof(server_portstr))) != OK)
1845 /* Step Two: Make the Connection */
1846 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1847 if (r->proxyreq == PROXYREQ_PROXY)
1848 status = HTTP_NOT_FOUND;
1850 status = HTTP_SERVICE_UNAVAILABLE;
1854 /* Step Three: Create conn_rec */
1855 if (!backend->connection) {
1856 if ((status = ap_proxy_connection_create(proxy_function, backend,
1857 c, r->server)) != OK)
1861 /* Step Four: Send the Request */
1862 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1863 conf, uri, url, server_portstr)) != OK)
1866 /* Step Five: Receive the Response */
1867 if ((status = ap_proxy_http_process_response(p, r, backend,
1868 backend->connection,
1869 conf, server_portstr)) != OK)
1872 /* Step Six: Clean Up */
1878 ap_proxy_http_cleanup(proxy_function, r, backend);
1882 static apr_status_t warn_rx_free(void *p)
1884 ap_pregfree((apr_pool_t*)p, warn_rx);
1887 static void ap_proxy_http_register_hook(apr_pool_t *p)
1889 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1890 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1891 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1892 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1895 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1896 STANDARD20_MODULE_STUFF,
1897 NULL, /* create per-directory config structure */
1898 NULL, /* merge per-directory config structures */
1899 NULL, /* create per-server config structure */
1900 NULL, /* merge per-server config structures */
1901 NULL, /* command apr_table_t */
1902 ap_proxy_http_register_hook/* register hooks */