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"
21 module AP_MODULE_DECLARE_DATA proxy_http_module;
23 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
25 proxy_conn_rec *backend);
28 * Canonicalise http-like URLs.
29 * scheme is the scheme for the URL
30 * url is the URL starting with the first '/'
31 * def_port is the default port for this scheme.
33 static int proxy_http_canon(request_rec *r, char *url)
35 char *host, *path, *search, sport[7];
38 apr_port_t port, def_port;
40 /* ap_port_of_scheme() */
41 if (strncasecmp(url, "http:", 5) == 0) {
45 else if (strncasecmp(url, "https:", 6) == 0) {
52 def_port = apr_uri_port_of_scheme(scheme);
54 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
55 "proxy: HTTP: canonicalising URL %s", url);
58 * We break the URL into host, port, path, search
61 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
63 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
64 "error parsing URL %s: %s",
66 return HTTP_BAD_REQUEST;
69 /* now parse path/search args, according to rfc1738 */
70 /* N.B. if this isn't a true proxy request, then the URL _path_
71 * has already been decoded. True proxy requests have r->uri
72 * == r->unparsed_uri, and no others have that property.
74 if (r->uri == r->unparsed_uri) {
75 search = strchr(url, '?');
83 path = ap_proxy_canonenc(r->pool, url, strlen(url), enc_path, 0, r->proxyreq);
85 return HTTP_BAD_REQUEST;
88 apr_snprintf(sport, sizeof(sport), ":%d", port);
92 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
93 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
95 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
96 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
100 /* Clear all connection-based headers from the incoming headers table */
101 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
104 char *next = apr_pstrdup(p, apr_table_get(headers, "Connection"));
106 apr_table_unset(headers, "Proxy-Connection");
112 while (*next && !apr_isspace(*next) && (*next != ',')) {
115 while (*next && (apr_isspace(*next) || (*next == ','))) {
119 apr_table_unset(headers, name);
121 apr_table_unset(headers, "Connection");
124 static void add_te_chunked(apr_pool_t *p,
125 apr_bucket_alloc_t *bucket_alloc,
126 apr_bucket_brigade *header_brigade)
130 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
132 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
133 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
135 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
136 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
139 static void add_cl(apr_pool_t *p,
140 apr_bucket_alloc_t *bucket_alloc,
141 apr_bucket_brigade *header_brigade,
147 buf = apr_pstrcat(p, "Content-Length: ",
151 ap_xlate_proto_to_ascii(buf, strlen(buf));
152 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
153 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
156 #define ASCII_CRLF "\015\012"
157 #define ASCII_ZERO "\060"
159 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
160 apr_bucket_brigade *header_brigade)
164 /* add empty line at the end of the headers */
165 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
166 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
169 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
170 request_rec *r, proxy_conn_rec *conn,
171 conn_rec *origin, apr_bucket_brigade *bb,
175 apr_off_t transferred;
178 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
179 APR_BRIGADE_INSERT_TAIL(bb, e);
181 apr_brigade_length(bb, 0, &transferred);
182 if (transferred != -1)
183 conn->worker->s->transferred += transferred;
184 status = ap_pass_brigade(origin->output_filters, bb);
185 if (status != APR_SUCCESS) {
186 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
187 "proxy: pass request body failed to %pI (%s)",
188 conn->addr, conn->hostname);
191 apr_brigade_cleanup(bb);
195 #define MAX_MEM_SPOOL 16384
197 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
199 proxy_conn_rec *p_conn,
201 apr_bucket_brigade *header_brigade,
202 apr_bucket_brigade *input_brigade)
208 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
209 apr_bucket_brigade *bb;
212 add_te_chunked(p, bucket_alloc, header_brigade);
213 terminate_headers(bucket_alloc, header_brigade);
215 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
217 char chunk_hdr[20]; /* must be here due to transient bucket. */
219 /* If this brigade contains EOS, either stop or remove it. */
220 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
223 /* We can't pass this EOS to the output_filters. */
224 e = APR_BRIGADE_LAST(input_brigade);
225 apr_bucket_delete(e);
228 apr_brigade_length(input_brigade, 1, &bytes);
230 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
231 "%" APR_UINT64_T_HEX_FMT CRLF,
232 (apr_uint64_t)bytes);
234 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
235 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
237 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
240 * Append the end-of-chunk CRLF
242 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
243 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
245 if (header_brigade) {
246 /* we never sent the header brigade, so go ahead and
247 * take care of that now
252 * Save input_brigade in bb brigade. (At least) in the SSL case
253 * input_brigade contains transient buckets whose data would get
254 * overwritten during the next call of ap_get_brigade in the loop.
255 * ap_save_brigade ensures these buckets to be set aside.
256 * Calling ap_save_brigade with NULL as filter is OK, because
257 * bb brigade already has been created and does not need to get
258 * created by ap_save_brigade.
260 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
261 if (status != APR_SUCCESS) {
265 header_brigade = NULL;
271 /* The request is flushed below this loop with chunk EOS header */
272 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
273 if (status != APR_SUCCESS) {
281 status = ap_get_brigade(r->input_filters, input_brigade,
282 AP_MODE_READBYTES, APR_BLOCK_READ,
285 if (status != APR_SUCCESS) {
290 if (header_brigade) {
291 /* we never sent the header brigade because there was no request body;
297 if (!APR_BRIGADE_EMPTY(input_brigade)) {
298 /* input brigade still has an EOS which we can't pass to the output_filters. */
299 e = APR_BRIGADE_LAST(input_brigade);
300 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
301 apr_bucket_delete(e);
306 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
310 APR_BRIGADE_INSERT_TAIL(bb, e);
312 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
313 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
314 APR_BRIGADE_INSERT_TAIL(bb, e);
317 /* Now we have headers-only, or the chunk EOS mark; flush it */
318 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
322 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
324 proxy_conn_rec *p_conn,
326 apr_bucket_brigade *header_brigade,
327 apr_bucket_brigade *input_brigade,
328 const char *old_cl_val)
331 apr_status_t status = APR_SUCCESS;
332 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
333 apr_bucket_brigade *bb;
335 apr_off_t cl_val = 0;
337 apr_off_t bytes_streamed = 0;
340 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
341 if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
346 terminate_headers(bucket_alloc, header_brigade);
348 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
350 apr_brigade_length(input_brigade, 1, &bytes);
351 bytes_streamed += bytes;
353 /* If this brigade contains EOS, either stop or remove it. */
354 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
357 /* We can't pass this EOS to the output_filters. */
358 e = APR_BRIGADE_LAST(input_brigade);
359 apr_bucket_delete(e);
361 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
362 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
363 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
367 /* C-L < bytes streamed?!?
368 * We will error out after the body is completely
369 * consumed, but we can't stream more bytes at the
370 * back end since they would in part be interpreted
371 * as another request! If nothing is sent, then
374 * Prevents HTTP Response Splitting.
376 if (bytes_streamed > cl_val)
379 if (header_brigade) {
380 /* we never sent the header brigade, so go ahead and
381 * take care of that now
386 * Save input_brigade in bb brigade. (At least) in the SSL case
387 * input_brigade contains transient buckets whose data would get
388 * overwritten during the next call of ap_get_brigade in the loop.
389 * ap_save_brigade ensures these buckets to be set aside.
390 * Calling ap_save_brigade with NULL as filter is OK, because
391 * bb brigade already has been created and does not need to get
392 * created by ap_save_brigade.
394 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
395 if (status != APR_SUCCESS) {
399 header_brigade = NULL;
405 /* Once we hit EOS, we are ready to flush. */
406 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
407 if (status != APR_SUCCESS) {
415 status = ap_get_brigade(r->input_filters, input_brigade,
416 AP_MODE_READBYTES, APR_BLOCK_READ,
419 if (status != APR_SUCCESS) {
424 if (bytes_streamed != cl_val) {
425 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
426 "proxy: client %s given Content-Length did not match"
427 " number of body bytes read", r->connection->remote_ip);
431 if (header_brigade) {
432 /* we never sent the header brigade since there was no request
433 * body; send it now with the flush flag
436 status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
441 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
443 proxy_conn_rec *p_conn,
445 apr_bucket_brigade *header_brigade,
446 apr_bucket_brigade *input_brigade,
451 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
452 apr_bucket_brigade *body_brigade;
454 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
455 apr_file_t *tmpfile = NULL;
457 body_brigade = apr_brigade_create(p, bucket_alloc);
459 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
461 /* If this brigade contains EOS, either stop or remove it. */
462 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
465 /* We can't pass this EOS to the output_filters. */
466 e = APR_BRIGADE_LAST(input_brigade);
467 apr_bucket_delete(e);
470 apr_brigade_length(input_brigade, 1, &bytes);
472 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
473 /* can't spool any more in memory; write latest brigade to disk */
474 if (tmpfile == NULL) {
475 const char *temp_dir;
478 status = apr_temp_dir_get(&temp_dir, p);
479 if (status != APR_SUCCESS) {
480 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
481 "proxy: search for temporary directory failed");
484 apr_filepath_merge(&template, temp_dir,
485 "modproxy.tmp.XXXXXX",
486 APR_FILEPATH_NATIVE, p);
487 status = apr_file_mktemp(&tmpfile, template, 0, p);
488 if (status != APR_SUCCESS) {
489 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
490 "proxy: creation of temporary file in directory %s failed",
495 for (e = APR_BRIGADE_FIRST(input_brigade);
496 e != APR_BRIGADE_SENTINEL(input_brigade);
497 e = APR_BUCKET_NEXT(e)) {
499 apr_size_t bytes_read, bytes_written;
501 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
502 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
503 if (status != APR_SUCCESS) {
504 const char *tmpfile_name;
506 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
507 tmpfile_name = "(unknown)";
509 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
510 "proxy: write to temporary file %s failed",
514 AP_DEBUG_ASSERT(bytes_read == bytes_written);
515 fsize += bytes_written;
517 apr_brigade_cleanup(input_brigade);
522 * Save input_brigade in body_brigade. (At least) in the SSL case
523 * input_brigade contains transient buckets whose data would get
524 * overwritten during the next call of ap_get_brigade in the loop.
525 * ap_save_brigade ensures these buckets to be set aside.
526 * Calling ap_save_brigade with NULL as filter is OK, because
527 * body_brigade already has been created and does not need to get
528 * created by ap_save_brigade.
530 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
531 if (status != APR_SUCCESS) {
537 bytes_spooled += bytes;
543 status = ap_get_brigade(r->input_filters, input_brigade,
544 AP_MODE_READBYTES, APR_BLOCK_READ,
547 if (status != APR_SUCCESS) {
552 if (bytes_spooled || force_cl) {
553 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
555 terminate_headers(bucket_alloc, header_brigade);
556 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
558 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
560 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
561 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
562 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
564 /* This is all a single brigade, pass with flush flagged */
565 status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
570 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
571 proxy_conn_rec *p_conn, conn_rec *origin,
572 proxy_server_conf *conf,
574 char *url, char *server_portstr)
576 conn_rec *c = r->connection;
577 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
578 apr_bucket_brigade *header_brigade;
579 apr_bucket_brigade *input_brigade;
580 apr_bucket_brigade *temp_brigade;
583 const apr_array_header_t *headers_in_array;
584 const apr_table_entry_t *headers_in;
587 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
588 enum rb_methods rb_method = RB_INIT;
589 const char *old_cl_val = NULL;
590 const char *old_te_val = NULL;
591 apr_off_t bytes_read = 0;
594 apr_table_t *headers_in_copy;
596 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
599 * Send the HTTP/1.1 request to the remote server
602 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
603 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
607 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
610 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
611 origin->keepalive = AP_CONN_CLOSE;
614 ap_xlate_proto_to_ascii(buf, strlen(buf));
615 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
616 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
617 if (conf->preserve_host == 0) {
618 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
619 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
622 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
626 /* don't want to use r->hostname, as the incoming header might have a
629 const char* hostname = apr_table_get(r->headers_in,"Host");
631 hostname = r->server->server_hostname;
632 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
633 "proxy: no HTTP 0.9 request (with no host line) "
634 "on incoming request and preserve host set "
635 "forcing hostname to be %s for uri %s",
639 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
641 ap_xlate_proto_to_ascii(buf, strlen(buf));
642 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
643 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
646 if (conf->viaopt == via_block) {
647 /* Block all outgoing Via: headers */
648 apr_table_unset(r->headers_in, "Via");
649 } else if (conf->viaopt != via_off) {
650 const char *server_name = ap_get_server_name(r);
651 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
652 * then the server name returned by ap_get_server_name() is the
653 * origin server name (which does make too much sense with Via: headers)
654 * so we use the proxy vhost's name instead.
656 if (server_name == r->hostname)
657 server_name = r->server->server_hostname;
658 /* Create a "Via:" request header entry and merge it */
659 /* Generate outgoing Via: header with/without server comment: */
660 apr_table_mergen(r->headers_in, "Via",
661 (conf->viaopt == via_full)
662 ? apr_psprintf(p, "%d.%d %s%s (%s)",
663 HTTP_VERSION_MAJOR(r->proto_num),
664 HTTP_VERSION_MINOR(r->proto_num),
665 server_name, server_portstr,
666 AP_SERVER_BASEVERSION)
667 : apr_psprintf(p, "%d.%d %s%s",
668 HTTP_VERSION_MAJOR(r->proto_num),
669 HTTP_VERSION_MINOR(r->proto_num),
670 server_name, server_portstr)
674 /* X-Forwarded-*: handling
679 * These request headers are only really useful when the mod_proxy
680 * is used in a reverse proxy configuration, so that useful info
681 * about the client can be passed through the reverse proxy and on
682 * to the backend server, which may require the information to
685 * In a forward proxy situation, these options are a potential
686 * privacy violation, as information about clients behind the proxy
687 * are revealed to arbitrary servers out there on the internet.
689 * The HTTP/1.1 Via: header is designed for passing client
690 * information through proxies to a server, and should be used in
691 * a forward proxy configuation instead of X-Forwarded-*. See the
692 * ProxyVia option for details.
695 if (PROXYREQ_REVERSE == r->proxyreq) {
698 /* Add X-Forwarded-For: so that the upstream has a chance to
699 * determine, where the original request came from.
701 apr_table_mergen(r->headers_in, "X-Forwarded-For",
704 /* Add X-Forwarded-Host: so that upstream knows what the
705 * original request hostname was.
707 if ((buf = apr_table_get(r->headers_in, "Host"))) {
708 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
711 /* Add X-Forwarded-Server: so that upstream knows what the
712 * name of this proxy server is (if there are more than one)
713 * XXX: This duplicates Via: - do we strictly need it?
715 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
716 r->server->server_hostname);
721 * Make a copy of the headers_in table before clearing the connection
722 * headers as we need the connection headers later in the http output
723 * filter to prepare the correct response headers.
725 * Note: We need to take r->pool for apr_table_copy as the key / value
726 * pairs in r->headers_in have been created out of r->pool and
727 * p might be (and actually is) a longer living pool.
728 * This would trigger the bad pool ancestry abort in apr_table_copy if
729 * apr is compiled with APR_POOL_DEBUG.
731 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
732 ap_proxy_clear_connection(p, headers_in_copy);
733 /* send request headers */
734 headers_in_array = apr_table_elts(headers_in_copy);
735 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
736 for (counter = 0; counter < headers_in_array->nelts; counter++) {
737 if (headers_in[counter].key == NULL
738 || headers_in[counter].val == NULL
741 || !strcasecmp(headers_in[counter].key, "Host")
743 /* Clear out hop-by-hop request headers not to send
744 * RFC2616 13.5.1 says we should strip these headers
746 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
747 || !strcasecmp(headers_in[counter].key, "TE")
748 || !strcasecmp(headers_in[counter].key, "Trailer")
749 || !strcasecmp(headers_in[counter].key, "Upgrade")
751 /* XXX: @@@ FIXME: "Proxy-Authorization" should *only* be
752 * suppressed if THIS server requested the authentication,
753 * not when a frontend proxy requested it!
755 * The solution to this problem is probably to strip out
756 * the Proxy-Authorisation header in the authorisation
757 * code itself, not here. This saves us having to signal
758 * somehow whether this request was authenticated or not.
760 || !strcasecmp(headers_in[counter].key,"Proxy-Authorization")
761 || !strcasecmp(headers_in[counter].key,"Proxy-Authenticate")) {
765 /* Skip Transfer-Encoding and Content-Length for now.
767 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
768 old_te_val = headers_in[counter].val;
771 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
772 old_cl_val = headers_in[counter].val;
776 /* for sub-requests, ignore freshness/expiry headers */
778 if ( !strcasecmp(headers_in[counter].key, "If-Match")
779 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
780 || !strcasecmp(headers_in[counter].key, "If-Range")
781 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
782 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
787 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
788 headers_in[counter].val, CRLF,
790 ap_xlate_proto_to_ascii(buf, strlen(buf));
791 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
792 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
795 /* We have headers, let's figure out our request body... */
796 input_brigade = apr_brigade_create(p, bucket_alloc);
798 /* sub-requests never use keepalives, and mustn't pass request bodies.
799 * Because the new logic looks at input_brigade, we will self-terminate
800 * input_brigade and jump past all of the request body logic...
801 * Reading anything with ap_get_brigade is likely to consume the
802 * main request's body or read beyond EOS - which would be unplesant.
805 /* XXX: Why DON'T sub-requests use keepalives? */
809 apr_table_unset(r->headers_in, "Content-Length");
813 apr_table_unset(r->headers_in, "Transfer-Encoding");
815 rb_method = RB_STREAM_CL;
816 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
817 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
821 /* WE only understand chunked. Other modules might inject
822 * (and therefore, decode) other flavors but we don't know
823 * that the can and have done so unless they they remove
824 * their decoding from the headers_in T-E list.
825 * XXX: Make this extensible, but in doing so, presume the
826 * encoding has been done by the extensions' handler, and
827 * do not modify add_te_chunked's logic
829 if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
830 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
831 "proxy: %s Transfer-Encoding is not supported",
836 if (old_cl_val && old_te_val) {
837 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
838 "proxy: client %s (%s) requested Transfer-Encoding "
839 "chunked body with Content-Length (C-L ignored)",
840 c->remote_ip, c->remote_host ? c->remote_host: "");
841 apr_table_unset(r->headers_in, "Content-Length");
843 origin->keepalive = AP_CONN_CLOSE;
847 /* Prefetch MAX_MEM_SPOOL bytes
849 * This helps us avoid any election of C-L v.s. T-E
850 * request bodies, since we are willing to keep in
851 * memory this much data, in any case. This gives
852 * us an instant C-L election if the body is of some
855 temp_brigade = apr_brigade_create(p, bucket_alloc);
857 status = ap_get_brigade(r->input_filters, temp_brigade,
858 AP_MODE_READBYTES, APR_BLOCK_READ,
859 MAX_MEM_SPOOL - bytes_read);
860 if (status != APR_SUCCESS) {
861 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
862 "proxy: prefetch request body failed to %pI (%s)"
864 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
865 c->remote_ip, c->remote_host ? c->remote_host: "");
869 apr_brigade_length(temp_brigade, 1, &bytes);
873 * Save temp_brigade in input_brigade. (At least) in the SSL case
874 * temp_brigade contains transient buckets whose data would get
875 * overwritten during the next call of ap_get_brigade in the loop.
876 * ap_save_brigade ensures these buckets to be set aside.
877 * Calling ap_save_brigade with NULL as filter is OK, because
878 * input_brigade already has been created and does not need to get
879 * created by ap_save_brigade.
881 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
882 if (status != APR_SUCCESS) {
883 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
884 "proxy: processing prefetched request body failed"
885 " to %pI (%s) from %s (%s)",
886 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
887 c->remote_ip, c->remote_host ? c->remote_host: "");
891 /* Ensure we don't hit a wall where we have a buffer too small
892 * for ap_get_brigade's filters to fetch us another bucket,
893 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
894 * (an arbitrary value.)
896 } while ((bytes_read < MAX_MEM_SPOOL - 80)
897 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
899 /* Use chunked request body encoding or send a content-length body?
903 * We have no request body (handled by RB_STREAM_CL)
905 * We have a request body length <= MAX_MEM_SPOOL
907 * The administrator has setenv force-proxy-request-1.0
909 * The client sent a C-L body, and the administrator has
910 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
912 * The client sent a T-E body, and the administrator has
913 * setenv proxy-sendcl, and not setenv proxy-sendchunked
915 * If both proxy-sendcl and proxy-sendchunked are set, the
916 * behavior is the same as if neither were set, large bodies
917 * that can't be read will be forwarded in their original
918 * form of C-L, or T-E.
920 * To ensure maximum compatibility, setenv proxy-sendcl
921 * To reduce server resource use, setenv proxy-sendchunked
923 * Then address specific servers with conditional setenv
924 * options to restore the default behavior where desireable.
926 * We have to compute content length by reading the entire request
927 * body; if request body is not small, we'll spool the remaining
928 * input to a temporary file. Chunked is always preferable.
930 * We can only trust the client-provided C-L if the T-E header
931 * is absent, and the filters are unchanged (the body won't
932 * be resized by another content filter).
934 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
935 /* The whole thing fit, so our decision is trivial, use
936 * the filtered bytes read from the client for the request
937 * body Content-Length.
939 * If we expected no body, and read no body, do not set
940 * the Content-Length.
942 if (old_cl_val || old_te_val || bytes_read) {
943 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
945 rb_method = RB_STREAM_CL;
947 else if (old_te_val) {
949 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
950 && !apr_table_get(r->subprocess_env, "proxy-sendchunks"))) {
951 rb_method = RB_SPOOL_CL;
954 rb_method = RB_STREAM_CHUNKED;
957 else if (old_cl_val) {
958 if (r->input_filters == r->proto_input_filters) {
959 rb_method = RB_STREAM_CL;
962 && apr_table_get(r->subprocess_env, "proxy-sendchunks")
963 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
964 rb_method = RB_STREAM_CHUNKED;
967 rb_method = RB_SPOOL_CL;
971 /* This is an appropriate default; very efficient for no-body
972 * requests, and has the behavior that it will not add any C-L
973 * when the old_cl_val is NULL.
975 rb_method = RB_SPOOL_CL;
978 /* Yes I hate gotos. This is the subrequest shortcut */
981 * Handle Connection: header if we do HTTP/1.1 request:
982 * If we plan to close the backend connection sent Connection: close
983 * otherwise sent Connection: Keep-Alive.
987 buf = apr_pstrdup(p, "Connection: close" CRLF);
990 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
992 ap_xlate_proto_to_ascii(buf, strlen(buf));
993 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
994 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
997 /* send the request body, if any. */
999 case RB_STREAM_CHUNKED:
1000 status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1004 status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1005 input_brigade, old_cl_val);
1008 status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1009 input_brigade, (old_cl_val != NULL)
1010 || (old_te_val != NULL)
1011 || (bytes_read > 0));
1014 /* shouldn't be possible */
1015 status = APR_EINVAL;
1019 if (status != APR_SUCCESS) {
1020 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1021 "proxy: pass request body failed to %pI (%s)"
1024 p_conn->hostname ? p_conn->hostname: "",
1026 c->remote_host ? c->remote_host: "");
1033 static void process_proxy_header(request_rec* r, proxy_dir_conf* c,
1034 const char* key, const char* value)
1036 static const char* date_hdrs[]
1037 = { "Date", "Expires", "Last-Modified", NULL } ;
1038 static const struct {
1040 ap_proxy_header_reverse_map_fn func;
1041 } transform_hdrs[] = {
1042 { "Location", ap_proxy_location_reverse_map } ,
1043 { "Content-Location", ap_proxy_location_reverse_map } ,
1044 { "URI", ap_proxy_location_reverse_map } ,
1045 { "Destination", ap_proxy_location_reverse_map } ,
1046 { "Set-Cookie", ap_proxy_cookie_reverse_map } ,
1050 for ( i = 0 ; date_hdrs[i] ; ++i ) {
1051 if ( !strcasecmp(date_hdrs[i], key) ) {
1052 apr_table_add(r->headers_out, key,
1053 ap_proxy_date_canon(r->pool, value)) ;
1057 for ( i = 0 ; transform_hdrs[i].name ; ++i ) {
1058 if ( !strcasecmp(transform_hdrs[i].name, key) ) {
1059 apr_table_add(r->headers_out, key,
1060 (*transform_hdrs[i].func)(r, c, value)) ;
1064 apr_table_add(r->headers_out, key, value) ;
1069 * Note: pread_len is the length of the response that we've mistakenly
1070 * read (assuming that we don't consider that an error via
1071 * ProxyBadHeader StartBody). This depends on buffer actually being
1072 * local storage to the calling code in order for pread_len to make
1073 * any sense at all, since we depend on buffer still containing
1074 * what was read by ap_getline() upon return.
1076 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1077 char *buffer, int size,
1078 conn_rec *c, int *pread_len)
1082 char field[MAX_STRING_LEN];
1083 int saw_headers = 0;
1084 void *sconf = r->server->module_config;
1085 proxy_server_conf *psc;
1086 proxy_dir_conf *dconf;
1088 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1089 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1091 r->headers_out = apr_table_make(r->pool, 20);
1095 * Read header lines until we get the empty separator line, a read error,
1096 * the connection closes (EOF), or we timeout.
1098 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1100 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1102 /* We may encounter invalid headers, usually from buggy
1103 * MS IIS servers, so we need to determine just how to handle
1104 * them. We can either ignore them, assume that they mark the
1105 * start-of-body (eg: a missing CRLF) or (the default) mark
1106 * the headers as totally bogus and return a 500. The sole
1107 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1108 * in between the usual MIME headers, which is a favorite
1111 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1113 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1114 if (psc->badopt == bad_error) {
1115 /* Nope, it wasn't even an extra HTTP header. Give up. */
1116 r->headers_out = NULL;
1119 else if (psc->badopt == bad_body) {
1120 /* if we've already started loading headers_out, then
1121 * return what we've accumulated so far, in the hopes
1122 * that they are useful; also note that we likely pre-read
1123 * the first line of the response.
1126 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1127 "proxy: Starting body due to bogus non-header in headers "
1128 "returned by %s (%s)", r->uri, r->method);
1132 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1133 "proxy: No HTTP headers "
1134 "returned by %s (%s)", r->uri, r->method);
1139 /* this is the psc->badopt == bad_ignore case */
1140 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1141 "proxy: Ignoring bogus HTTP header "
1142 "returned by %s (%s)", r->uri, r->method);
1148 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1149 * wrong... and so are many others probably.
1151 while (apr_isspace(*value))
1152 ++value; /* Skip to start of value */
1154 /* should strip trailing whitespace as well */
1155 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1159 /* make sure we add so as not to destroy duplicated headers
1160 * Modify headers requiring canonicalisation and/or affected
1161 * by ProxyPassReverse and family with process_proxy_header
1163 process_proxy_header(r, dconf, buffer, value) ;
1166 /* the header was too long; at the least we should skip extra data */
1167 if (len >= size - 1) {
1168 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1169 >= MAX_STRING_LEN - 1) {
1170 /* soak up the extra data */
1172 if (len == 0) /* time to exit the larger loop as well */
1180 static int addit_dammit(void *v, const char *key, const char *val)
1182 apr_table_addn(v, key, val);
1187 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1188 proxy_conn_rec *backend,
1190 proxy_server_conf *conf,
1191 char *server_portstr) {
1192 conn_rec *c = r->connection;
1193 char buffer[HUGE_STRING_LEN];
1198 apr_bucket_brigade *bb;
1199 int len, backasswards;
1200 int interim_response; /* non-zero whilst interim 1xx responses
1201 * are being read. */
1203 apr_table_t *save_table;
1204 int backend_broke = 0;
1206 bb = apr_brigade_create(p, c->bucket_alloc);
1208 /* Get response from the remote server, and pass it up the
1212 rp = ap_proxy_make_fake_req(origin, r);
1213 /* In case anyone needs to know, this is a fake request that is really a
1216 rp->proxyreq = PROXYREQ_RESPONSE;
1218 apr_brigade_cleanup(bb);
1220 len = ap_getline(buffer, sizeof(buffer), rp, 0);
1222 /* handle one potential stray CRLF */
1223 len = ap_getline(buffer, sizeof(buffer), rp, 0);
1226 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1227 "proxy: error reading status line from remote "
1228 "server %s", backend->hostname);
1229 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1230 "Error reading from remote server");
1232 /* XXX: Is this a real headers length send from remote? */
1233 backend->worker->s->read += len;
1235 /* Is it an HTTP/1 response?
1236 * This is buggy if we ever see an HTTP/1.10
1238 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1241 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1245 /* If not an HTTP/1 message or
1246 * if the status line was > 8192 bytes
1248 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1249 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1250 apr_pstrcat(p, "Corrupt status line returned by remote "
1251 "server: ", buffer, NULL));
1255 keepchar = buffer[12];
1257 r->status = atoi(&buffer[9]);
1259 if (keepchar != '\0') {
1260 buffer[12] = keepchar;
1262 /* 2616 requires the space in Status-Line; the origin
1263 * server may have sent one but ap_rgetline_core will
1264 * have stripped it. */
1268 r->status_line = apr_pstrdup(p, &buffer[9]);
1271 /* read the headers. */
1272 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1273 /* Also, take care with headers with multiple occurences. */
1275 /* First, tuck away all already existing cookies */
1276 save_table = apr_table_make(r->pool, 2);
1277 apr_table_do(addit_dammit, save_table, r->headers_out,
1278 "Set-Cookie", NULL);
1280 /* shove the headers direct into r->headers_out */
1281 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1284 if (r->headers_out == NULL) {
1285 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1286 r->server, "proxy: bad HTTP/%d.%d header "
1287 "returned by %s (%s)", major, minor, r->uri,
1289 backend->close += 1;
1291 * ap_send_error relies on a headers_out to be present. we
1292 * are in a bad position here.. so force everything we send out
1293 * to have nothing to do with the incoming packet
1295 r->headers_out = apr_table_make(r->pool,1);
1296 r->status = HTTP_BAD_GATEWAY;
1297 r->status_line = "bad gateway";
1301 /* Now, add in the just read cookies */
1302 apr_table_do(addit_dammit, save_table, r->headers_out,
1303 "Set-Cookie", NULL);
1305 /* and now load 'em all in */
1306 if (!apr_is_empty_table(save_table)) {
1307 apr_table_unset(r->headers_out, "Set-Cookie");
1308 r->headers_out = apr_table_overlay(r->pool,
1313 /* can't have both Content-Length and Transfer-Encoding */
1314 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1315 && apr_table_get(r->headers_out, "Content-Length")) {
1317 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1318 * and Content-Length are received, the latter MUST be
1321 * To help mitigate HTTP Splitting, unset Content-Length
1322 * and shut down the backend server connection
1323 * XXX: We aught to treat such a response as uncachable
1325 apr_table_unset(r->headers_out, "Content-Length");
1326 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1327 "proxy: server %s returned Transfer-Encoding"
1328 " and Content-Length", backend->hostname);
1329 backend->close += 1;
1332 /* strip connection listed hop-by-hop headers from response */
1333 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1336 ap_proxy_clear_connection(p, r->headers_out);
1337 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1338 ap_set_content_type(r, apr_pstrdup(p, buf));
1340 ap_proxy_pre_http_request(origin,rp);
1342 /* handle Via header in response */
1343 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1344 const char *server_name = ap_get_server_name(r);
1345 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1346 * then the server name returned by ap_get_server_name() is the
1347 * origin server name (which does make too much sense with Via: headers)
1348 * so we use the proxy vhost's name instead.
1350 if (server_name == r->hostname)
1351 server_name = r->server->server_hostname;
1352 /* create a "Via:" response header entry and merge it */
1353 apr_table_mergen(r->headers_out, "Via",
1354 (conf->viaopt == via_full)
1355 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1356 HTTP_VERSION_MAJOR(r->proto_num),
1357 HTTP_VERSION_MINOR(r->proto_num),
1360 AP_SERVER_BASEVERSION)
1361 : apr_psprintf(p, "%d.%d %s%s",
1362 HTTP_VERSION_MAJOR(r->proto_num),
1363 HTTP_VERSION_MINOR(r->proto_num),
1369 /* cancel keepalive if HTTP/1.0 or less */
1370 if ((major < 1) || (minor < 1)) {
1371 backend->close += 1;
1372 origin->keepalive = AP_CONN_CLOSE;
1375 /* an http/0.9 response */
1378 r->status_line = "200 OK";
1379 backend->close += 1;
1382 interim_response = ap_is_HTTP_INFO(r->status);
1383 if (interim_response) {
1384 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1385 "proxy: HTTP: received interim %d response",
1388 /* Moved the fixups of Date headers and those affected by
1389 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1392 if ((r->status == 401) && (conf->error_override)) {
1394 const char *wa = "WWW-Authenticate";
1395 if ((buf = apr_table_get(r->headers_out, wa))) {
1396 apr_table_set(r->err_headers_out, wa, buf);
1398 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1399 "proxy: origin server sent 401 without WWW-Authenticate header");
1405 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1406 * the response? If so, load the extra data. These are 2 mutually
1407 * exclusive possibilities, that just happen to require very
1410 if (backasswards || pread_len) {
1411 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1414 * At this point in response processing of a 0.9 response,
1415 * we don't know yet whether data is binary or not.
1416 * mod_charset_lite will get control later on, so it cannot
1417 * decide on the conversion of this buffer full of data.
1418 * However, chances are that we are not really talking to an
1419 * HTTP/0.9 server, but to some different protocol, therefore
1420 * the best guess IMHO is to always treat the buffer as "text/x":
1422 ap_xlate_proto_to_ascii(buffer, len);
1423 cntr = (apr_ssize_t)len;
1425 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1426 APR_BRIGADE_INSERT_TAIL(bb, e);
1429 /* send body - but only if a body is expected */
1430 if ((!r->header_only) && /* not HEAD request */
1431 !interim_response && /* not any 1xx response */
1432 (r->status != HTTP_NO_CONTENT) && /* not 204 */
1433 (r->status != HTTP_NOT_MODIFIED)) { /* not 304 */
1435 /* We need to copy the output headers and treat them as input
1436 * headers as well. BUT, we need to do this before we remove
1437 * TE, so that they are preserved accordingly for
1438 * ap_http_filter to know where to end.
1440 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1442 apr_table_unset(r->headers_out,"Transfer-Encoding");
1444 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1445 "proxy: start body send");
1448 * if we are overriding the errors, we can't put the content
1449 * of the page into the brigade
1451 if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1452 /* read the body, pass it to the output filters */
1453 apr_read_type_e mode = APR_NONBLOCK_READ;
1457 apr_off_t readbytes;
1460 rv = ap_get_brigade(rp->input_filters, bb,
1461 AP_MODE_READBYTES, mode,
1462 conf->io_buffer_size);
1464 /* ap_get_brigade will return success with an empty brigade
1465 * for a non-blocking read which would block: */
1466 if (APR_STATUS_IS_EAGAIN(rv)
1467 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1468 /* flush to the client and switch to blocking mode */
1469 e = apr_bucket_flush_create(c->bucket_alloc);
1470 APR_BRIGADE_INSERT_TAIL(bb, e);
1471 if (ap_pass_brigade(r->output_filters, bb)
1476 apr_brigade_cleanup(bb);
1477 mode = APR_BLOCK_READ;
1480 else if (rv == APR_EOF) {
1483 else if (rv != APR_SUCCESS) {
1484 /* In this case, we are in real trouble because
1485 * our backend bailed on us. Pass along a 502 error
1488 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1489 "proxy: error reading response");
1490 ap_proxy_backend_broke(r, bb);
1491 ap_pass_brigade(r->output_filters, bb);
1496 /* next time try a non-blocking read */
1497 mode = APR_NONBLOCK_READ;
1499 apr_brigade_length(bb, 0, &readbytes);
1500 backend->worker->s->read += readbytes;
1503 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1504 r->server, "proxy (PID %d): readbytes: %#x",
1505 getpid(), readbytes);
1509 if (APR_BRIGADE_EMPTY(bb)) {
1510 apr_brigade_cleanup(bb);
1514 /* found the last brigade? */
1515 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1516 /* signal that we must leave */
1520 /* try send what we read */
1521 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1523 /* Ack! Phbtt! Die! User aborted! */
1524 backend->close = 1; /* this causes socket close below */
1528 /* make sure we always clean up after ourselves */
1529 apr_brigade_cleanup(bb);
1533 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1534 "proxy: end body send");
1536 else if (!interim_response) {
1537 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1538 "proxy: header only");
1540 /* Pass EOS bucket down the filter chain. */
1541 e = apr_bucket_eos_create(c->bucket_alloc);
1542 APR_BRIGADE_INSERT_TAIL(bb, e);
1543 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1545 /* Ack! Phbtt! Die! User aborted! */
1546 backend->close = 1; /* this causes socket close below */
1549 apr_brigade_cleanup(bb);
1551 } while (interim_response);
1553 /* If our connection with the client is to be aborted, return DONE. */
1554 if (c->aborted || backend_broke) {
1558 if (conf->error_override) {
1559 /* the code above this checks for 'OK' which is what the hook expects */
1560 if (!ap_is_HTTP_ERROR(r->status))
1563 /* clear r->status for override error, otherwise ErrorDocument
1564 * thinks that this is a recursive error, and doesn't find the
1567 int status = r->status;
1568 r->status = HTTP_OK;
1569 /* Discard body, if one is expected */
1570 if ((status != HTTP_NO_CONTENT) && /* not 204 */
1571 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1572 ap_discard_request_body(rp);
1581 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1582 proxy_conn_rec *backend)
1584 ap_proxy_release_connection(scheme, backend, r->server);
1589 * This handles http:// URLs, and other URLs using a remote proxy over http
1590 * If proxyhost is NULL, then contact the server directly, otherwise
1592 * Note that if a proxy is used, then URLs other than http: can be accessed,
1593 * also, if we have trouble which is clearly specific to the proxy, then
1594 * we return DECLINED so that we can try another proxy. (Or the direct
1597 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1598 proxy_server_conf *conf,
1599 char *url, const char *proxyname,
1600 apr_port_t proxyport)
1603 char server_portstr[32];
1605 const char *proxy_function;
1607 proxy_conn_rec *backend = NULL;
1610 /* Note: Memory pool allocation.
1611 * A downstream keepalive connection is always connected to the existence
1612 * (or not) of an upstream keepalive connection. If this is not done then
1613 * load balancing against multiple backend servers breaks (one backend
1614 * server ends up taking 100% of the load), and the risk is run of
1615 * downstream keepalive connections being kept open unnecessarily. This
1616 * keeps webservers busy and ties up resources.
1618 * As a result, we allocate all sockets out of the upstream connection
1619 * pool, and when we want to reuse a socket, we check first whether the
1620 * connection ID of the current upstream connection is the same as that
1621 * of the connection when the socket was opened.
1623 apr_pool_t *p = r->connection->pool;
1624 conn_rec *c = r->connection;
1625 apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1627 /* find the scheme */
1628 u = strchr(url, ':');
1629 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1632 return HTTP_BAD_REQUEST;
1633 scheme = apr_pstrndup(c->pool, url, u - url);
1634 /* scheme is lowercase */
1635 ap_str_tolower(scheme);
1637 if (strcmp(scheme, "https") == 0) {
1638 if (!ap_proxy_ssl_enable(NULL)) {
1639 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1640 "proxy: HTTPS: declining URL %s"
1641 " (mod_ssl not configured?)", url);
1645 proxy_function = "HTTPS";
1647 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1648 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1649 "proxy: HTTP: declining URL %s", url);
1650 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1654 proxy_function = "HTTP";
1656 proxy_function = "FTP";
1658 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1659 "proxy: HTTP: serving URL %s", url);
1662 /* create space for state information */
1663 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1664 worker, r->server)) != OK)
1668 backend->is_ssl = is_ssl;
1670 * TODO: Currently we cannot handle persistent SSL backend connections,
1671 * because we recreate backend->connection for each request and thus
1672 * try to initialize an already existing SSL connection. This does
1678 /* Step One: Determine Who To Connect To */
1679 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1680 uri, &url, proxyname,
1681 proxyport, server_portstr,
1682 sizeof(server_portstr))) != OK)
1685 /* Step Two: Make the Connection */
1686 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1687 if (r->proxyreq == PROXYREQ_PROXY)
1688 status = HTTP_NOT_FOUND;
1690 status = HTTP_SERVICE_UNAVAILABLE;
1694 /* Step Three: Create conn_rec */
1695 if (!backend->connection) {
1696 if ((status = ap_proxy_connection_create(proxy_function, backend,
1697 c, r->server)) != OK)
1701 /* Step Four: Send the Request */
1702 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1703 conf, uri, url, server_portstr)) != OK)
1706 /* Step Five: Receive the Response */
1707 if ((status = ap_proxy_http_process_response(p, r, backend,
1708 backend->connection,
1709 conf, server_portstr)) != OK)
1712 /* Step Six: Clean Up */
1718 ap_proxy_http_cleanup(proxy_function, r, backend);
1723 static void ap_proxy_http_register_hook(apr_pool_t *p)
1725 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1726 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1729 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1730 STANDARD20_MODULE_STUFF,
1731 NULL, /* create per-directory config structure */
1732 NULL, /* merge per-directory config structures */
1733 NULL, /* create per-server config structure */
1734 NULL, /* merge per-server config structures */
1735 NULL, /* command apr_table_t */
1736 ap_proxy_http_register_hook/* register hooks */