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};
1334 const char *te = NULL;
1336 bb = apr_brigade_create(p, c->bucket_alloc);
1338 /* Get response from the remote server, and pass it up the
1342 rp = ap_proxy_make_fake_req(origin, r);
1343 /* In case anyone needs to know, this is a fake request that is really a
1346 rp->proxyreq = PROXYREQ_RESPONSE;
1347 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1351 apr_brigade_cleanup(bb);
1353 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1355 /* handle one potential stray CRLF */
1356 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1359 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1360 "proxy: error reading status line from remote "
1361 "server %s", backend->hostname);
1362 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1363 "Error reading from remote server");
1365 /* XXX: Is this a real headers length send from remote? */
1366 backend->worker->s->read += len;
1368 /* Is it an HTTP/1 response?
1369 * This is buggy if we ever see an HTTP/1.10
1371 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1374 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1378 /* If not an HTTP/1 message or
1379 * if the status line was > 8192 bytes
1381 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1382 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1383 apr_pstrcat(p, "Corrupt status line returned by remote "
1384 "server: ", buffer, NULL));
1388 keepchar = buffer[12];
1390 r->status = atoi(&buffer[9]);
1392 if (keepchar != '\0') {
1393 buffer[12] = keepchar;
1395 /* 2616 requires the space in Status-Line; the origin
1396 * server may have sent one but ap_rgetline_core will
1397 * have stripped it. */
1401 r->status_line = apr_pstrdup(p, &buffer[9]);
1404 /* read the headers. */
1405 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1406 /* Also, take care with headers with multiple occurences. */
1408 /* First, tuck away all already existing cookies */
1409 save_table = apr_table_make(r->pool, 2);
1410 apr_table_do(addit_dammit, save_table, r->headers_out,
1411 "Set-Cookie", NULL);
1413 /* shove the headers direct into r->headers_out */
1414 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1417 if (r->headers_out == NULL) {
1418 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1419 r->server, "proxy: bad HTTP/%d.%d header "
1420 "returned by %s (%s)", major, minor, r->uri,
1422 backend->close += 1;
1424 * ap_send_error relies on a headers_out to be present. we
1425 * are in a bad position here.. so force everything we send out
1426 * to have nothing to do with the incoming packet
1428 r->headers_out = apr_table_make(r->pool,1);
1429 r->status = HTTP_BAD_GATEWAY;
1430 r->status_line = "bad gateway";
1434 /* Now, add in the just read cookies */
1435 apr_table_do(addit_dammit, save_table, r->headers_out,
1436 "Set-Cookie", NULL);
1438 /* and now load 'em all in */
1439 if (!apr_is_empty_table(save_table)) {
1440 apr_table_unset(r->headers_out, "Set-Cookie");
1441 r->headers_out = apr_table_overlay(r->pool,
1446 /* can't have both Content-Length and Transfer-Encoding */
1447 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1448 && apr_table_get(r->headers_out, "Content-Length")) {
1450 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1451 * and Content-Length are received, the latter MUST be
1454 * To help mitigate HTTP Splitting, unset Content-Length
1455 * and shut down the backend server connection
1456 * XXX: We aught to treat such a response as uncachable
1458 apr_table_unset(r->headers_out, "Content-Length");
1459 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1460 "proxy: server %s returned Transfer-Encoding"
1461 " and Content-Length", backend->hostname);
1462 backend->close += 1;
1466 * Save a possible Transfer-Encoding header as we need it later for
1467 * ap_http_filter to know where to end.
1469 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1470 /* strip connection listed hop-by-hop headers from response */
1471 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1474 ap_proxy_clear_connection(p, r->headers_out);
1475 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1476 ap_set_content_type(r, apr_pstrdup(p, buf));
1478 ap_proxy_pre_http_request(origin,rp);
1480 /* Clear hop-by-hop headers */
1481 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1482 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1484 /* Delete warnings with wrong date */
1485 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1487 /* handle Via header in response */
1488 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1489 const char *server_name = ap_get_server_name(r);
1490 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1491 * then the server name returned by ap_get_server_name() is the
1492 * origin server name (which does make too much sense with Via: headers)
1493 * so we use the proxy vhost's name instead.
1495 if (server_name == r->hostname)
1496 server_name = r->server->server_hostname;
1497 /* create a "Via:" response header entry and merge it */
1498 apr_table_addn(r->headers_out, "Via",
1499 (conf->viaopt == via_full)
1500 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1501 HTTP_VERSION_MAJOR(r->proto_num),
1502 HTTP_VERSION_MINOR(r->proto_num),
1505 AP_SERVER_BASEVERSION)
1506 : apr_psprintf(p, "%d.%d %s%s",
1507 HTTP_VERSION_MAJOR(r->proto_num),
1508 HTTP_VERSION_MINOR(r->proto_num),
1514 /* cancel keepalive if HTTP/1.0 or less */
1515 if ((major < 1) || (minor < 1)) {
1516 backend->close += 1;
1517 origin->keepalive = AP_CONN_CLOSE;
1520 /* an http/0.9 response */
1523 r->status_line = "200 OK";
1524 backend->close += 1;
1527 interim_response = ap_is_HTTP_INFO(r->status);
1528 if (interim_response) {
1529 /* RFC2616 tells us to forward this.
1531 * OTOH, an interim response here may mean the backend
1532 * is playing sillybuggers. The Client didn't ask for
1533 * it within the defined HTTP/1.1 mechanisms, and if
1534 * it's an extension, it may also be unsupported by us.
1536 * There's also the possibility that changing existing
1537 * behaviour here might break something.
1539 * So let's make it configurable.
1541 const char *policy = apr_table_get(r->subprocess_env,
1542 "proxy-interim-response");
1543 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1544 "proxy: HTTP: received interim %d response",
1546 if (!policy || !strcasecmp(policy, "RFC")) {
1547 ap_send_interim_response(r, 1);
1549 /* FIXME: refine this to be able to specify per-response-status
1550 * policies and maybe also add option to bail out with 502
1552 else if (strcasecmp(policy, "Suppress")) {
1553 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1554 "undefined proxy interim response policy");
1557 /* Moved the fixups of Date headers and those affected by
1558 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1561 if ((r->status == 401) && (conf->error_override)) {
1563 const char *wa = "WWW-Authenticate";
1564 if ((buf = apr_table_get(r->headers_out, wa))) {
1565 apr_table_set(r->err_headers_out, wa, buf);
1567 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1568 "proxy: origin server sent 401 without WWW-Authenticate header");
1574 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1575 * the response? If so, load the extra data. These are 2 mutually
1576 * exclusive possibilities, that just happen to require very
1579 if (backasswards || pread_len) {
1580 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1583 * At this point in response processing of a 0.9 response,
1584 * we don't know yet whether data is binary or not.
1585 * mod_charset_lite will get control later on, so it cannot
1586 * decide on the conversion of this buffer full of data.
1587 * However, chances are that we are not really talking to an
1588 * HTTP/0.9 server, but to some different protocol, therefore
1589 * the best guess IMHO is to always treat the buffer as "text/x":
1591 ap_xlate_proto_to_ascii(buffer, len);
1592 cntr = (apr_ssize_t)len;
1594 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1595 APR_BRIGADE_INSERT_TAIL(bb, e);
1598 /* send body - but only if a body is expected */
1599 if ((!r->header_only) && /* not HEAD request */
1600 !interim_response && /* not any 1xx response */
1601 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1602 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1604 /* We need to copy the output headers and treat them as input
1605 * headers as well. BUT, we need to do this before we remove
1606 * TE, so that they are preserved accordingly for
1607 * ap_http_filter to know where to end.
1609 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1611 * Restore Transfer-Encoding header from response if we saved
1612 * one before and there is none left. We need it for the
1613 * ap_http_filter. See below.
1615 if (te && !apr_table_get(rp->headers_in, "Transfer-Encoding")) {
1616 apr_table_add(rp->headers_in, "Transfer-Encoding", te);
1619 apr_table_unset(r->headers_out,"Transfer-Encoding");
1621 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1622 "proxy: start body send");
1625 * if we are overriding the errors, we can't put the content
1626 * of the page into the brigade
1628 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1629 /* read the body, pass it to the output filters */
1630 apr_read_type_e mode = APR_NONBLOCK_READ;
1634 apr_off_t readbytes;
1637 rv = ap_get_brigade(rp->input_filters, bb,
1638 AP_MODE_READBYTES, mode,
1639 conf->io_buffer_size);
1641 /* ap_get_brigade will return success with an empty brigade
1642 * for a non-blocking read which would block: */
1643 if (APR_STATUS_IS_EAGAIN(rv)
1644 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1645 /* flush to the client and switch to blocking mode */
1646 e = apr_bucket_flush_create(c->bucket_alloc);
1647 APR_BRIGADE_INSERT_TAIL(bb, e);
1648 if (ap_pass_brigade(r->output_filters, bb)
1653 apr_brigade_cleanup(bb);
1654 mode = APR_BLOCK_READ;
1657 else if (rv == APR_EOF) {
1660 else if (rv != APR_SUCCESS) {
1661 /* In this case, we are in real trouble because
1662 * our backend bailed on us. Pass along a 502 error
1665 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1666 "proxy: error reading response");
1667 ap_proxy_backend_broke(r, bb);
1668 ap_pass_brigade(r->output_filters, bb);
1673 /* next time try a non-blocking read */
1674 mode = APR_NONBLOCK_READ;
1676 apr_brigade_length(bb, 0, &readbytes);
1677 backend->worker->s->read += readbytes;
1680 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1681 r->server, "proxy (PID %d): readbytes: %#x",
1682 getpid(), readbytes);
1686 if (APR_BRIGADE_EMPTY(bb)) {
1687 apr_brigade_cleanup(bb);
1691 /* found the last brigade? */
1692 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1693 /* signal that we must leave */
1697 /* try send what we read */
1698 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1700 /* Ack! Phbtt! Die! User aborted! */
1701 backend->close = 1; /* this causes socket close below */
1705 /* make sure we always clean up after ourselves */
1706 apr_brigade_cleanup(bb);
1710 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1711 "proxy: end body send");
1713 else if (!interim_response) {
1714 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1715 "proxy: header only");
1717 /* Pass EOS bucket down the filter chain. */
1718 e = apr_bucket_eos_create(c->bucket_alloc);
1719 APR_BRIGADE_INSERT_TAIL(bb, e);
1720 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1722 /* Ack! Phbtt! Die! User aborted! */
1723 backend->close = 1; /* this causes socket close below */
1726 apr_brigade_cleanup(bb);
1728 } while (interim_response);
1730 /* If our connection with the client is to be aborted, return DONE. */
1731 if (c->aborted || backend_broke) {
1735 if (conf->error_override) {
1736 /* the code above this checks for 'OK' which is what the hook expects */
1737 if (!ap_is_HTTP_ERROR(r->status))
1740 /* clear r->status for override error, otherwise ErrorDocument
1741 * thinks that this is a recursive error, and doesn't find the
1744 int status = r->status;
1745 r->status = HTTP_OK;
1746 /* Discard body, if one is expected */
1747 if (!r->header_only && /* not HEAD request */
1748 (status != HTTP_NO_CONTENT) && /* not 204 */
1749 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1750 ap_discard_request_body(rp);
1759 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1760 proxy_conn_rec *backend)
1762 ap_proxy_release_connection(scheme, backend, r->server);
1767 * This handles http:// URLs, and other URLs using a remote proxy over http
1768 * If proxyhost is NULL, then contact the server directly, otherwise
1770 * Note that if a proxy is used, then URLs other than http: can be accessed,
1771 * also, if we have trouble which is clearly specific to the proxy, then
1772 * we return DECLINED so that we can try another proxy. (Or the direct
1775 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1776 proxy_server_conf *conf,
1777 char *url, const char *proxyname,
1778 apr_port_t proxyport)
1781 char server_portstr[32];
1783 const char *proxy_function;
1785 proxy_conn_rec *backend = NULL;
1788 /* Note: Memory pool allocation.
1789 * A downstream keepalive connection is always connected to the existence
1790 * (or not) of an upstream keepalive connection. If this is not done then
1791 * load balancing against multiple backend servers breaks (one backend
1792 * server ends up taking 100% of the load), and the risk is run of
1793 * downstream keepalive connections being kept open unnecessarily. This
1794 * keeps webservers busy and ties up resources.
1796 * As a result, we allocate all sockets out of the upstream connection
1797 * pool, and when we want to reuse a socket, we check first whether the
1798 * connection ID of the current upstream connection is the same as that
1799 * of the connection when the socket was opened.
1801 apr_pool_t *p = r->connection->pool;
1802 conn_rec *c = r->connection;
1803 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1805 /* find the scheme */
1806 u = strchr(url, ':');
1807 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1810 return HTTP_BAD_REQUEST;
1811 scheme = apr_pstrndup(c->pool, url, u - url);
1812 /* scheme is lowercase */
1813 ap_str_tolower(scheme);
1815 if (strcmp(scheme, "https") == 0) {
1816 if (!ap_proxy_ssl_enable(NULL)) {
1817 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1818 "proxy: HTTPS: declining URL %s"
1819 " (mod_ssl not configured?)", url);
1823 proxy_function = "HTTPS";
1825 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1826 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1827 "proxy: HTTP: declining URL %s", url);
1828 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1832 proxy_function = "HTTP";
1834 proxy_function = "FTP";
1836 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1837 "proxy: HTTP: serving URL %s", url);
1840 /* create space for state information */
1841 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1842 worker, r->server)) != OK)
1846 backend->is_ssl = is_ssl;
1849 ap_proxy_ssl_connection_cleanup(backend, r);
1852 /* Step One: Determine Who To Connect To */
1853 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1854 uri, &url, proxyname,
1855 proxyport, server_portstr,
1856 sizeof(server_portstr))) != OK)
1859 /* Step Two: Make the Connection */
1860 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1861 if (r->proxyreq == PROXYREQ_PROXY)
1862 status = HTTP_NOT_FOUND;
1864 status = HTTP_SERVICE_UNAVAILABLE;
1868 /* Step Three: Create conn_rec */
1869 if (!backend->connection) {
1870 if ((status = ap_proxy_connection_create(proxy_function, backend,
1871 c, r->server)) != OK)
1875 /* Step Four: Send the Request */
1876 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1877 conf, uri, url, server_portstr)) != OK)
1880 /* Step Five: Receive the Response */
1881 if ((status = ap_proxy_http_process_response(p, r, backend,
1882 backend->connection,
1883 conf, server_portstr)) != OK)
1886 /* Step Six: Clean Up */
1892 ap_proxy_http_cleanup(proxy_function, r, backend);
1896 static apr_status_t warn_rx_free(void *p)
1898 ap_pregfree((apr_pool_t*)p, warn_rx);
1901 static void ap_proxy_http_register_hook(apr_pool_t *p)
1903 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1904 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1905 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1906 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1909 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1910 STANDARD20_MODULE_STUFF,
1911 NULL, /* create per-directory config structure */
1912 NULL, /* merge per-directory config structures */
1913 NULL, /* create per-server config structure */
1914 NULL, /* merge per-server config structures */
1915 NULL, /* command apr_table_t */
1916 ap_proxy_http_register_hook/* register hooks */