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, sport[7];
40 apr_port_t port, def_port;
42 /* ap_port_of_scheme() */
43 if (strncasecmp(url, "http:", 5) == 0) {
47 else if (strncasecmp(url, "https:", 6) == 0) {
54 def_port = apr_uri_port_of_scheme(scheme);
56 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
57 "HTTP: canonicalising URL %s", url);
60 * We break the URL into host, port, path, search
63 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
65 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01083)
66 "error parsing URL %s: %s", url, err);
67 return HTTP_BAD_REQUEST;
71 * now parse path/search args, according to rfc1738:
74 * In a reverse proxy, our URL has been processed, so canonicalise
75 * unless proxy-nocanon is set to say it's raw
76 * In a forward proxy, we have and MUST NOT MANGLE the original.
78 switch (r->proxyreq) {
79 default: /* wtf are we doing here? */
80 case PROXYREQ_REVERSE:
81 if (apr_table_get(r->notes, "proxy-nocanon")) {
82 path = url; /* this is the raw path */
85 path = ap_proxy_canonenc(r->pool, url, strlen(url),
86 enc_path, 0, r->proxyreq);
96 return HTTP_BAD_REQUEST;
99 apr_snprintf(sport, sizeof(sport), ":%d", port);
103 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
104 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
106 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
107 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
111 /* Clear all connection-based headers from the incoming headers table */
112 typedef struct header_dptr {
117 static ap_regex_t *warn_rx;
118 static int clean_warning_headers(void *data, const char *key, const char *val)
120 apr_table_t *headers = ((header_dptr*)data)->table;
121 apr_pool_t *pool = ((header_dptr*)data)->pool;
124 apr_time_t warn_time;
125 const int nmatch = 3;
126 ap_regmatch_t pmatch[3];
128 if (headers == NULL) {
129 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
132 * Parse this, suckers!
134 * Warning = "Warning" ":" 1#warning-value
136 * warning-value = warn-code SP warn-agent SP warn-text
140 * warn-agent = ( host [ ":" port ] ) | pseudonym
141 * ; the name or pseudonym of the server adding
142 * ; the Warning header, for use in debugging
143 * warn-text = quoted-string
144 * warn-date = <"> HTTP-date <">
146 * Buggrit, use a bloomin' regexp!
147 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
149 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
150 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
151 pmatch[0].rm_eo - pmatch[0].rm_so);
153 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
154 /* OK, we have a date here */
155 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
156 pmatch[2].rm_eo - pmatch[2].rm_so);
157 warn_time = apr_date_parse_http(date);
159 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
160 apr_table_addn(headers, key, warning);
162 val += pmatch[0].rm_eo;
166 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
171 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
172 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
173 if (x.table != NULL) {
174 apr_table_unset(headers, "Warning");
175 return apr_table_overlay(p, headers, x.table);
181 static int clear_conn_headers(void *data, const char *key, const char *val)
183 apr_table_t *headers = ((header_dptr*)data)->table;
184 apr_pool_t *pool = ((header_dptr*)data)->pool;
186 char *next = apr_pstrdup(pool, val);
189 while (*next && !apr_isspace(*next) && (*next != ',')) {
192 while (*next && (apr_isspace(*next) || (*next == ','))) {
195 apr_table_unset(headers, name);
199 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
204 apr_table_unset(headers, "Proxy-Connection");
205 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
206 apr_table_unset(headers, "Connection");
208 static void add_te_chunked(apr_pool_t *p,
209 apr_bucket_alloc_t *bucket_alloc,
210 apr_bucket_brigade *header_brigade)
214 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
216 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
217 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
219 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
220 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
223 static void add_cl(apr_pool_t *p,
224 apr_bucket_alloc_t *bucket_alloc,
225 apr_bucket_brigade *header_brigade,
231 buf = apr_pstrcat(p, "Content-Length: ",
235 ap_xlate_proto_to_ascii(buf, strlen(buf));
236 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
237 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
240 #define ASCII_CRLF "\015\012"
241 #define ASCII_ZERO "\060"
243 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
244 apr_bucket_brigade *header_brigade)
248 /* add empty line at the end of the headers */
249 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
250 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
253 static int pass_brigade(apr_bucket_alloc_t *bucket_alloc,
254 request_rec *r, proxy_conn_rec *p_conn,
255 conn_rec *origin, apr_bucket_brigade *bb,
259 apr_off_t transferred;
262 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
263 APR_BRIGADE_INSERT_TAIL(bb, e);
265 apr_brigade_length(bb, 0, &transferred);
266 if (transferred != -1)
267 p_conn->worker->s->transferred += transferred;
268 status = ap_pass_brigade(origin->output_filters, bb);
269 if (status != APR_SUCCESS) {
270 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01084)
271 "pass request body failed to %pI (%s)",
272 p_conn->addr, p_conn->hostname);
273 if (origin->aborted) {
274 const char *ssl_note;
276 if (((ssl_note = apr_table_get(origin->notes, "SSL_connect_rv"))
277 != NULL) && (strcmp(ssl_note, "err") == 0)) {
278 return ap_proxyerror(r, HTTP_INTERNAL_SERVER_ERROR,
279 "Error during SSL Handshake with"
282 return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY;
285 return HTTP_BAD_REQUEST;
288 apr_brigade_cleanup(bb);
292 #define MAX_MEM_SPOOL 16384
294 static int stream_reqbody_chunked(apr_pool_t *p,
296 proxy_conn_rec *p_conn,
298 apr_bucket_brigade *header_brigade,
299 apr_bucket_brigade *input_brigade)
301 int seen_eos = 0, rv = OK;
305 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
306 apr_bucket_brigade *bb;
309 add_te_chunked(p, bucket_alloc, header_brigade);
310 terminate_headers(bucket_alloc, header_brigade);
312 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
314 char chunk_hdr[20]; /* must be here due to transient bucket. */
316 /* If this brigade contains EOS, either stop or remove it. */
317 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
320 /* We can't pass this EOS to the output_filters. */
321 e = APR_BRIGADE_LAST(input_brigade);
322 apr_bucket_delete(e);
325 apr_brigade_length(input_brigade, 1, &bytes);
327 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
328 "%" APR_UINT64_T_HEX_FMT CRLF,
329 (apr_uint64_t)bytes);
331 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
332 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
334 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
337 * Append the end-of-chunk CRLF
339 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
340 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
342 if (header_brigade) {
343 /* we never sent the header brigade, so go ahead and
344 * take care of that now
349 * Save input_brigade in bb brigade. (At least) in the SSL case
350 * input_brigade contains transient buckets whose data would get
351 * overwritten during the next call of ap_get_brigade in the loop.
352 * ap_save_brigade ensures these buckets to be set aside.
353 * Calling ap_save_brigade with NULL as filter is OK, because
354 * bb brigade already has been created and does not need to get
355 * created by ap_save_brigade.
357 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
358 if (status != APR_SUCCESS) {
359 return HTTP_INTERNAL_SERVER_ERROR;
362 header_brigade = NULL;
368 /* The request is flushed below this loop with chunk EOS header */
369 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
378 status = ap_get_brigade(r->input_filters, input_brigade,
379 AP_MODE_READBYTES, APR_BLOCK_READ,
382 if (status != APR_SUCCESS) {
383 return HTTP_BAD_REQUEST;
387 if (header_brigade) {
388 /* we never sent the header brigade because there was no request body;
394 if (!APR_BRIGADE_EMPTY(input_brigade)) {
395 /* input brigade still has an EOS which we can't pass to the output_filters. */
396 e = APR_BRIGADE_LAST(input_brigade);
397 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
398 apr_bucket_delete(e);
403 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
407 APR_BRIGADE_INSERT_TAIL(bb, e);
409 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
410 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
411 APR_BRIGADE_INSERT_TAIL(bb, e);
414 /* Now we have headers-only, or the chunk EOS mark; flush it */
415 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
419 static int stream_reqbody_cl(apr_pool_t *p,
421 proxy_conn_rec *p_conn,
423 apr_bucket_brigade *header_brigade,
424 apr_bucket_brigade *input_brigade,
425 const char *old_cl_val)
427 int seen_eos = 0, rv = 0;
428 apr_status_t status = APR_SUCCESS;
429 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
430 apr_bucket_brigade *bb;
432 apr_off_t cl_val = 0;
434 apr_off_t bytes_streamed = 0;
439 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
440 status = apr_strtoff(&cl_val, old_cl_val, &endstr, 10);
442 if (status || *endstr || endstr == old_cl_val || cl_val < 0) {
443 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01085)
444 "could not parse request Content-Length (%s)",
446 return HTTP_BAD_REQUEST;
449 terminate_headers(bucket_alloc, header_brigade);
451 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
453 apr_brigade_length(input_brigade, 1, &bytes);
454 bytes_streamed += bytes;
456 /* If this brigade contains EOS, either stop or remove it. */
457 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
460 /* We can't pass this EOS to the output_filters. */
461 e = APR_BRIGADE_LAST(input_brigade);
462 apr_bucket_delete(e);
464 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
465 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
466 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
470 /* C-L < bytes streamed?!?
471 * We will error out after the body is completely
472 * consumed, but we can't stream more bytes at the
473 * back end since they would in part be interpreted
474 * as another request! If nothing is sent, then
477 * Prevents HTTP Response Splitting.
479 if (bytes_streamed > cl_val) {
480 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01086)
481 "read more bytes of request body than expected "
482 "(got %" APR_OFF_T_FMT ", expected %" APR_OFF_T_FMT ")",
483 bytes_streamed, cl_val);
484 return HTTP_INTERNAL_SERVER_ERROR;
487 if (header_brigade) {
488 /* we never sent the header brigade, so go ahead and
489 * take care of that now
494 * Save input_brigade in bb brigade. (At least) in the SSL case
495 * input_brigade contains transient buckets whose data would get
496 * overwritten during the next call of ap_get_brigade in the loop.
497 * ap_save_brigade ensures these buckets to be set aside.
498 * Calling ap_save_brigade with NULL as filter is OK, because
499 * bb brigade already has been created and does not need to get
500 * created by ap_save_brigade.
502 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
503 if (status != APR_SUCCESS) {
504 return HTTP_INTERNAL_SERVER_ERROR;
507 header_brigade = NULL;
513 /* Once we hit EOS, we are ready to flush. */
514 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
523 status = ap_get_brigade(r->input_filters, input_brigade,
524 AP_MODE_READBYTES, APR_BLOCK_READ,
527 if (status != APR_SUCCESS) {
528 return HTTP_BAD_REQUEST;
532 if (bytes_streamed != cl_val) {
533 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01087)
534 "client %s given Content-Length did not match"
535 " number of body bytes read", r->connection->client_ip);
536 return HTTP_BAD_REQUEST;
539 if (header_brigade) {
540 /* we never sent the header brigade since there was no request
541 * body; send it now with the flush flag
544 return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
550 static int spool_reqbody_cl(apr_pool_t *p,
552 proxy_conn_rec *p_conn,
554 apr_bucket_brigade *header_brigade,
555 apr_bucket_brigade *input_brigade,
560 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
561 apr_bucket_brigade *body_brigade;
563 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
564 apr_file_t *tmpfile = NULL;
567 body_brigade = apr_brigade_create(p, bucket_alloc);
569 limit = ap_get_limit_req_body(r);
571 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
573 /* If this brigade contains EOS, either stop or remove it. */
574 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
577 /* We can't pass this EOS to the output_filters. */
578 e = APR_BRIGADE_LAST(input_brigade);
579 apr_bucket_delete(e);
582 apr_brigade_length(input_brigade, 1, &bytes);
584 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
586 * LimitRequestBody does not affect Proxy requests (Should it?).
587 * Let it take effect if we decide to store the body in a
588 * temporary file on disk.
590 if (bytes_spooled + bytes > limit) {
591 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01088)
592 "Request body is larger than the configured "
593 "limit of %" APR_OFF_T_FMT, limit);
594 return HTTP_REQUEST_ENTITY_TOO_LARGE;
596 /* can't spool any more in memory; write latest brigade to disk */
597 if (tmpfile == NULL) {
598 const char *temp_dir;
601 status = apr_temp_dir_get(&temp_dir, p);
602 if (status != APR_SUCCESS) {
603 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01089)
604 "search for temporary directory failed");
605 return HTTP_INTERNAL_SERVER_ERROR;
607 apr_filepath_merge(&template, temp_dir,
608 "modproxy.tmp.XXXXXX",
609 APR_FILEPATH_NATIVE, p);
610 status = apr_file_mktemp(&tmpfile, template, 0, p);
611 if (status != APR_SUCCESS) {
612 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01090)
613 "creation of temporary file in directory "
614 "%s failed", temp_dir);
615 return HTTP_INTERNAL_SERVER_ERROR;
618 for (e = APR_BRIGADE_FIRST(input_brigade);
619 e != APR_BRIGADE_SENTINEL(input_brigade);
620 e = APR_BUCKET_NEXT(e)) {
622 apr_size_t bytes_read, bytes_written;
624 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
625 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
626 if (status != APR_SUCCESS) {
627 const char *tmpfile_name;
629 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
630 tmpfile_name = "(unknown)";
632 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01091)
633 "write to temporary file %s failed",
635 return HTTP_INTERNAL_SERVER_ERROR;
637 AP_DEBUG_ASSERT(bytes_read == bytes_written);
638 fsize += bytes_written;
640 apr_brigade_cleanup(input_brigade);
645 * Save input_brigade in body_brigade. (At least) in the SSL case
646 * input_brigade contains transient buckets whose data would get
647 * overwritten during the next call of ap_get_brigade in the loop.
648 * ap_save_brigade ensures these buckets to be set aside.
649 * Calling ap_save_brigade with NULL as filter is OK, because
650 * body_brigade already has been created and does not need to get
651 * created by ap_save_brigade.
653 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
654 if (status != APR_SUCCESS) {
655 return HTTP_INTERNAL_SERVER_ERROR;
660 bytes_spooled += bytes;
666 status = ap_get_brigade(r->input_filters, input_brigade,
667 AP_MODE_READBYTES, APR_BLOCK_READ,
670 if (status != APR_SUCCESS) {
671 return HTTP_BAD_REQUEST;
675 if (bytes_spooled || force_cl) {
676 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
678 terminate_headers(bucket_alloc, header_brigade);
679 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
681 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
683 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
684 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
685 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
687 /* This is all a single brigade, pass with flush flagged */
688 return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
692 * Transform buckets from one bucket allocator to another one by creating a
693 * transient bucket for each data bucket and let it use the data read from
694 * the old bucket. Metabuckets are transformed by just recreating them.
695 * Attention: Currently only the following bucket types are handled:
701 * If an other bucket type is found its type is logged as a debug message
702 * and APR_EGENERAL is returned.
704 static apr_status_t proxy_buckets_lifetime_transform(request_rec *r,
705 apr_bucket_brigade *from, apr_bucket_brigade *to)
711 apr_status_t rv = APR_SUCCESS;
713 apr_brigade_cleanup(to);
714 for (e = APR_BRIGADE_FIRST(from);
715 e != APR_BRIGADE_SENTINEL(from);
716 e = APR_BUCKET_NEXT(e)) {
717 if (!APR_BUCKET_IS_METADATA(e)) {
718 apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
719 new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
720 APR_BRIGADE_INSERT_TAIL(to, new);
722 else if (APR_BUCKET_IS_FLUSH(e)) {
723 new = apr_bucket_flush_create(r->connection->bucket_alloc);
724 APR_BRIGADE_INSERT_TAIL(to, new);
726 else if (APR_BUCKET_IS_EOS(e)) {
727 new = apr_bucket_eos_create(r->connection->bucket_alloc);
728 APR_BRIGADE_INSERT_TAIL(to, new);
731 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00964)
732 "Unhandled bucket type of type %s in"
733 " proxy_buckets_lifetime_transform", e->type->name);
734 apr_bucket_delete(e);
742 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
743 proxy_conn_rec *p_conn, proxy_worker *worker,
744 proxy_server_conf *conf,
746 char *url, char *server_portstr)
748 conn_rec *c = r->connection;
749 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
750 apr_bucket_brigade *header_brigade;
751 apr_bucket_brigade *input_brigade;
752 apr_bucket_brigade *temp_brigade;
755 const apr_array_header_t *headers_in_array;
756 const apr_table_entry_t *headers_in;
759 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
760 enum rb_methods rb_method = RB_INIT;
761 const char *old_cl_val = NULL;
762 const char *old_te_val = NULL;
763 apr_off_t bytes_read = 0;
766 apr_table_t *headers_in_copy;
767 proxy_dir_conf *dconf;
768 conn_rec *origin = p_conn->connection;
771 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
772 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
775 * Send the HTTP/1.1 request to the remote server
779 * To be compliant, we only use 100-Continue for requests with bodies.
780 * We also make sure we won't be talking HTTP/1.0 as well.
782 do_100_continue = (worker->s->ping_timeout_set
783 && ap_request_has_body(r)
784 && (PROXYREQ_REVERSE == r->proxyreq)
785 && !(apr_table_get(r->subprocess_env, "force-proxy-request-1.0")));
787 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
789 * According to RFC 2616 8.2.3 we are not allowed to forward an
790 * Expect: 100-continue to an HTTP/1.0 server. Instead we MUST return
791 * a HTTP_EXPECTATION_FAILED
793 if (r->expecting_100) {
794 return HTTP_EXPECTATION_FAILED;
796 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
800 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
803 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
804 origin->keepalive = AP_CONN_CLOSE;
807 ap_xlate_proto_to_ascii(buf, strlen(buf));
808 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
809 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
810 if (dconf->preserve_host == 0) {
811 if (ap_strchr_c(uri->hostname, ':')) { /* if literal IPv6 address */
812 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
813 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]:",
814 uri->port_str, CRLF, NULL);
816 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]", CRLF, NULL);
819 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
820 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":",
821 uri->port_str, CRLF, NULL);
823 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
828 /* don't want to use r->hostname, as the incoming header might have a
831 const char* hostname = apr_table_get(r->headers_in,"Host");
833 hostname = r->server->server_hostname;
834 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01092)
835 "no HTTP 0.9 request (with no host line) "
836 "on incoming request and preserve host set "
837 "forcing hostname to be %s for uri %s",
840 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
842 ap_xlate_proto_to_ascii(buf, strlen(buf));
843 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
844 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
847 if (conf->viaopt == via_block) {
848 /* Block all outgoing Via: headers */
849 apr_table_unset(r->headers_in, "Via");
850 } else if (conf->viaopt != via_off) {
851 const char *server_name = ap_get_server_name(r);
852 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
853 * then the server name returned by ap_get_server_name() is the
854 * origin server name (which does make too much sense with Via: headers)
855 * so we use the proxy vhost's name instead.
857 if (server_name == r->hostname)
858 server_name = r->server->server_hostname;
859 /* Create a "Via:" request header entry and merge it */
860 /* Generate outgoing Via: header with/without server comment: */
861 apr_table_mergen(r->headers_in, "Via",
862 (conf->viaopt == via_full)
863 ? apr_psprintf(p, "%d.%d %s%s (%s)",
864 HTTP_VERSION_MAJOR(r->proto_num),
865 HTTP_VERSION_MINOR(r->proto_num),
866 server_name, server_portstr,
867 AP_SERVER_BASEVERSION)
868 : apr_psprintf(p, "%d.%d %s%s",
869 HTTP_VERSION_MAJOR(r->proto_num),
870 HTTP_VERSION_MINOR(r->proto_num),
871 server_name, server_portstr)
875 /* Use HTTP/1.1 100-Continue as quick "HTTP ping" test
878 if (do_100_continue) {
879 apr_table_mergen(r->headers_in, "Expect", "100-Continue");
880 r->expecting_100 = 1;
883 /* X-Forwarded-*: handling
888 * These request headers are only really useful when the mod_proxy
889 * is used in a reverse proxy configuration, so that useful info
890 * about the client can be passed through the reverse proxy and on
891 * to the backend server, which may require the information to
894 * In a forward proxy situation, these options are a potential
895 * privacy violation, as information about clients behind the proxy
896 * are revealed to arbitrary servers out there on the internet.
898 * The HTTP/1.1 Via: header is designed for passing client
899 * information through proxies to a server, and should be used in
900 * a forward proxy configuation instead of X-Forwarded-*. See the
901 * ProxyVia option for details.
903 if (dconf->add_forwarded_headers) {
904 if (PROXYREQ_REVERSE == r->proxyreq) {
907 /* Add X-Forwarded-For: so that the upstream has a chance to
908 * determine, where the original request came from.
910 apr_table_mergen(r->headers_in, "X-Forwarded-For",
913 /* Add X-Forwarded-Host: so that upstream knows what the
914 * original request hostname was.
916 if ((buf = apr_table_get(r->headers_in, "Host"))) {
917 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
920 /* Add X-Forwarded-Server: so that upstream knows what the
921 * name of this proxy server is (if there are more than one)
922 * XXX: This duplicates Via: - do we strictly need it?
924 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
925 r->server->server_hostname);
931 * Make a copy of the headers_in table before clearing the connection
932 * headers as we need the connection headers later in the http output
933 * filter to prepare the correct response headers.
935 * Note: We need to take r->pool for apr_table_copy as the key / value
936 * pairs in r->headers_in have been created out of r->pool and
937 * p might be (and actually is) a longer living pool.
938 * This would trigger the bad pool ancestry abort in apr_table_copy if
939 * apr is compiled with APR_POOL_DEBUG.
941 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
942 ap_proxy_clear_connection(p, headers_in_copy);
943 /* send request headers */
944 headers_in_array = apr_table_elts(headers_in_copy);
945 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
946 for (counter = 0; counter < headers_in_array->nelts; counter++) {
947 if (headers_in[counter].key == NULL
948 || headers_in[counter].val == NULL
951 || !strcasecmp(headers_in[counter].key, "Host")
953 /* Clear out hop-by-hop request headers not to send
954 * RFC2616 13.5.1 says we should strip these headers
956 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
957 || !strcasecmp(headers_in[counter].key, "TE")
958 || !strcasecmp(headers_in[counter].key, "Trailer")
959 || !strcasecmp(headers_in[counter].key, "Upgrade")
964 /* Do we want to strip Proxy-Authorization ?
965 * If we haven't used it, then NO
966 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
967 * So let's make it configurable by env.
969 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
970 if (r->user != NULL) { /* we've authenticated */
971 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
978 /* Skip Transfer-Encoding and Content-Length for now.
980 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
981 old_te_val = headers_in[counter].val;
984 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
985 old_cl_val = headers_in[counter].val;
989 /* for sub-requests, ignore freshness/expiry headers */
991 if ( !strcasecmp(headers_in[counter].key, "If-Match")
992 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
993 || !strcasecmp(headers_in[counter].key, "If-Range")
994 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
995 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
1000 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
1001 headers_in[counter].val, CRLF,
1003 ap_xlate_proto_to_ascii(buf, strlen(buf));
1004 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1005 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1008 /* We have headers, let's figure out our request body... */
1009 input_brigade = apr_brigade_create(p, bucket_alloc);
1011 /* sub-requests never use keepalives, and mustn't pass request bodies.
1012 * Because the new logic looks at input_brigade, we will self-terminate
1013 * input_brigade and jump past all of the request body logic...
1014 * Reading anything with ap_get_brigade is likely to consume the
1015 * main request's body or read beyond EOS - which would be unplesant.
1017 * An exception: when a kept_body is present, then subrequest CAN use
1018 * pass request bodies, and we DONT skip the body.
1020 if (!r->kept_body && r->main) {
1021 /* XXX: Why DON'T sub-requests use keepalives? */
1025 apr_table_unset(r->headers_in, "Content-Length");
1029 apr_table_unset(r->headers_in, "Transfer-Encoding");
1031 rb_method = RB_STREAM_CL;
1032 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
1033 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
1037 /* WE only understand chunked. Other modules might inject
1038 * (and therefore, decode) other flavors but we don't know
1039 * that the can and have done so unless they they remove
1040 * their decoding from the headers_in T-E list.
1041 * XXX: Make this extensible, but in doing so, presume the
1042 * encoding has been done by the extensions' handler, and
1043 * do not modify add_te_chunked's logic
1045 if (old_te_val && strcasecmp(old_te_val, "chunked") != 0) {
1046 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01093)
1047 "%s Transfer-Encoding is not supported", old_te_val);
1048 return HTTP_INTERNAL_SERVER_ERROR;
1051 if (old_cl_val && old_te_val) {
1052 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01094)
1053 "client %s (%s) requested Transfer-Encoding "
1054 "chunked body with Content-Length (C-L ignored)",
1055 c->client_ip, c->remote_host ? c->remote_host: "");
1056 apr_table_unset(r->headers_in, "Content-Length");
1058 origin->keepalive = AP_CONN_CLOSE;
1062 /* Prefetch MAX_MEM_SPOOL bytes
1064 * This helps us avoid any election of C-L v.s. T-E
1065 * request bodies, since we are willing to keep in
1066 * memory this much data, in any case. This gives
1067 * us an instant C-L election if the body is of some
1070 temp_brigade = apr_brigade_create(p, bucket_alloc);
1072 status = ap_get_brigade(r->input_filters, temp_brigade,
1073 AP_MODE_READBYTES, APR_BLOCK_READ,
1074 MAX_MEM_SPOOL - bytes_read);
1075 if (status != APR_SUCCESS) {
1076 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01095)
1077 "prefetch request body failed to %pI (%s)"
1079 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1080 c->client_ip, c->remote_host ? c->remote_host: "");
1081 return HTTP_BAD_REQUEST;
1084 apr_brigade_length(temp_brigade, 1, &bytes);
1085 bytes_read += bytes;
1088 * Save temp_brigade in input_brigade. (At least) in the SSL case
1089 * temp_brigade contains transient buckets whose data would get
1090 * overwritten during the next call of ap_get_brigade in the loop.
1091 * ap_save_brigade ensures these buckets to be set aside.
1092 * Calling ap_save_brigade with NULL as filter is OK, because
1093 * input_brigade already has been created and does not need to get
1094 * created by ap_save_brigade.
1096 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
1097 if (status != APR_SUCCESS) {
1098 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01096)
1099 "processing prefetched request body failed"
1100 " to %pI (%s) from %s (%s)",
1101 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1102 c->client_ip, c->remote_host ? c->remote_host: "");
1103 return HTTP_INTERNAL_SERVER_ERROR;
1106 /* Ensure we don't hit a wall where we have a buffer too small
1107 * for ap_get_brigade's filters to fetch us another bucket,
1108 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
1109 * (an arbitrary value.)
1111 } while ((bytes_read < MAX_MEM_SPOOL - 80)
1112 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1114 /* Use chunked request body encoding or send a content-length body?
1118 * We have no request body (handled by RB_STREAM_CL)
1120 * We have a request body length <= MAX_MEM_SPOOL
1122 * The administrator has setenv force-proxy-request-1.0
1124 * The client sent a C-L body, and the administrator has
1125 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1127 * The client sent a T-E body, and the administrator has
1128 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1130 * If both proxy-sendcl and proxy-sendchunked are set, the
1131 * behavior is the same as if neither were set, large bodies
1132 * that can't be read will be forwarded in their original
1133 * form of C-L, or T-E.
1135 * To ensure maximum compatibility, setenv proxy-sendcl
1136 * To reduce server resource use, setenv proxy-sendchunked
1138 * Then address specific servers with conditional setenv
1139 * options to restore the default behavior where desireable.
1141 * We have to compute content length by reading the entire request
1142 * body; if request body is not small, we'll spool the remaining
1143 * input to a temporary file. Chunked is always preferable.
1145 * We can only trust the client-provided C-L if the T-E header
1146 * is absent, and the filters are unchanged (the body won't
1147 * be resized by another content filter).
1149 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1150 /* The whole thing fit, so our decision is trivial, use
1151 * the filtered bytes read from the client for the request
1152 * body Content-Length.
1154 * If we expected no body, and read no body, do not set
1155 * the Content-Length.
1157 if (old_cl_val || old_te_val || bytes_read) {
1158 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1160 rb_method = RB_STREAM_CL;
1162 else if (old_te_val) {
1164 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1165 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1166 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1167 rb_method = RB_SPOOL_CL;
1170 rb_method = RB_STREAM_CHUNKED;
1173 else if (old_cl_val) {
1174 if (r->input_filters == r->proto_input_filters) {
1175 rb_method = RB_STREAM_CL;
1178 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1179 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1180 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1181 rb_method = RB_STREAM_CHUNKED;
1184 rb_method = RB_SPOOL_CL;
1188 /* This is an appropriate default; very efficient for no-body
1189 * requests, and has the behavior that it will not add any C-L
1190 * when the old_cl_val is NULL.
1192 rb_method = RB_SPOOL_CL;
1195 /* Yes I hate gotos. This is the subrequest shortcut */
1198 * Handle Connection: header if we do HTTP/1.1 request:
1199 * If we plan to close the backend connection sent Connection: close
1200 * otherwise sent Connection: Keep-Alive.
1203 if (p_conn->close) {
1204 buf = apr_pstrdup(p, "Connection: close" CRLF);
1207 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1209 ap_xlate_proto_to_ascii(buf, strlen(buf));
1210 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1211 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1214 /* send the request body, if any. */
1216 case RB_STREAM_CHUNKED:
1217 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1221 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1222 input_brigade, old_cl_val);
1225 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1226 input_brigade, (old_cl_val != NULL)
1227 || (old_te_val != NULL)
1228 || (bytes_read > 0));
1231 /* shouldn't be possible */
1232 rv = HTTP_INTERNAL_SERVER_ERROR ;
1237 /* apr_status_t value has been logged in lower level method */
1238 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01097)
1239 "pass request body failed to %pI (%s) from %s (%s)",
1240 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1241 c->client_ip, c->remote_host ? c->remote_host: "");
1249 * If the date is a valid RFC 850 date or asctime() date, then it
1250 * is converted to the RFC 1123 format.
1252 static const char *date_canon(apr_pool_t *p, const char *date)
1257 apr_time_t time = apr_date_parse_http(date);
1262 ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
1263 rv = apr_rfc822_date(ndate, time);
1264 if (rv != APR_SUCCESS) {
1271 static request_rec *make_fake_req(conn_rec *c, request_rec *r)
1276 apr_pool_create(&pool, c->pool);
1278 rp = apr_pcalloc(pool, sizeof(*r));
1281 rp->status = HTTP_OK;
1283 rp->headers_in = apr_table_make(pool, 50);
1284 rp->subprocess_env = apr_table_make(pool, 50);
1285 rp->headers_out = apr_table_make(pool, 12);
1286 rp->err_headers_out = apr_table_make(pool, 5);
1287 rp->notes = apr_table_make(pool, 5);
1289 rp->server = r->server;
1291 rp->proxyreq = r->proxyreq;
1292 rp->request_time = r->request_time;
1294 rp->output_filters = c->output_filters;
1295 rp->input_filters = c->input_filters;
1296 rp->proto_output_filters = c->output_filters;
1297 rp->proto_input_filters = c->input_filters;
1298 rp->useragent_ip = c->client_ip;
1299 rp->useragent_addr = c->client_addr;
1301 rp->request_config = ap_create_request_config(pool);
1302 proxy_run_create_req(r, rp);
1307 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1308 const char *key, const char *value)
1310 static const char *date_hdrs[]
1311 = { "Date", "Expires", "Last-Modified", NULL };
1312 static const struct {
1314 ap_proxy_header_reverse_map_fn func;
1315 } transform_hdrs[] = {
1316 { "Location", ap_proxy_location_reverse_map },
1317 { "Content-Location", ap_proxy_location_reverse_map },
1318 { "URI", ap_proxy_location_reverse_map },
1319 { "Destination", ap_proxy_location_reverse_map },
1320 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1324 for (i = 0; date_hdrs[i]; ++i) {
1325 if (!strcasecmp(date_hdrs[i], key)) {
1326 apr_table_add(r->headers_out, key,
1327 date_canon(r->pool, value));
1331 for (i = 0; transform_hdrs[i].name; ++i) {
1332 if (!strcasecmp(transform_hdrs[i].name, key)) {
1333 apr_table_add(r->headers_out, key,
1334 (*transform_hdrs[i].func)(r, c, value));
1338 apr_table_add(r->headers_out, key, value);
1343 * Note: pread_len is the length of the response that we've mistakenly
1344 * read (assuming that we don't consider that an error via
1345 * ProxyBadHeader StartBody). This depends on buffer actually being
1346 * local storage to the calling code in order for pread_len to make
1347 * any sense at all, since we depend on buffer still containing
1348 * what was read by ap_getline() upon return.
1350 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1351 char *buffer, int size,
1352 conn_rec *c, int *pread_len)
1356 char field[MAX_STRING_LEN];
1357 int saw_headers = 0;
1358 void *sconf = r->server->module_config;
1359 proxy_server_conf *psc;
1360 proxy_dir_conf *dconf;
1362 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1363 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1365 r->headers_out = apr_table_make(r->pool, 20);
1369 * Read header lines until we get the empty separator line, a read error,
1370 * the connection closes (EOF), or we timeout.
1372 ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r,
1373 "Headers received from backend:");
1374 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1375 ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, "%s", buffer);
1377 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1379 /* We may encounter invalid headers, usually from buggy
1380 * MS IIS servers, so we need to determine just how to handle
1381 * them. We can either ignore them, assume that they mark the
1382 * start-of-body (eg: a missing CRLF) or (the default) mark
1383 * the headers as totally bogus and return a 500. The sole
1384 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1385 * in between the usual MIME headers, which is a favorite
1388 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1390 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1391 if (psc->badopt == bad_error) {
1392 /* Nope, it wasn't even an extra HTTP header. Give up. */
1393 r->headers_out = NULL;
1396 else if (psc->badopt == bad_body) {
1397 /* if we've already started loading headers_out, then
1398 * return what we've accumulated so far, in the hopes
1399 * that they are useful; also note that we likely pre-read
1400 * the first line of the response.
1403 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01098)
1404 "Starting body due to bogus non-header "
1405 "in headers returned by %s (%s)",
1410 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01099)
1411 "No HTTP headers returned by %s (%s)",
1417 /* this is the psc->badopt == bad_ignore case */
1418 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01100)
1419 "Ignoring bogus HTTP header returned by %s (%s)",
1426 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1427 * wrong... and so are many others probably.
1429 while (apr_isspace(*value))
1430 ++value; /* Skip to start of value */
1432 /* should strip trailing whitespace as well */
1433 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1437 /* make sure we add so as not to destroy duplicated headers
1438 * Modify headers requiring canonicalisation and/or affected
1439 * by ProxyPassReverse and family with process_proxy_header
1441 process_proxy_header(r, dconf, buffer, value) ;
1444 /* the header was too long; at the least we should skip extra data */
1445 if (len >= size - 1) {
1446 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1447 >= MAX_STRING_LEN - 1) {
1448 /* soak up the extra data */
1450 if (len == 0) /* time to exit the larger loop as well */
1458 static int addit_dammit(void *v, const char *key, const char *val)
1460 apr_table_addn(v, key, val);
1465 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1466 int fold, int *writen)
1472 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1473 apr_brigade_cleanup(bb);
1475 if (rv == APR_SUCCESS) {
1476 *writen = (int) len;
1477 } else if (APR_STATUS_IS_ENOSPC(rv)) {
1487 * Limit the number of interim respones we sent back to the client. Otherwise
1488 * we suffer from a memory build up. Besides there is NO sense in sending back
1489 * an unlimited number of interim responses to the client. Thus if we cross
1490 * this limit send back a 502 (Bad Gateway).
1492 #ifndef AP_MAX_INTERIM_RESPONSES
1493 #define AP_MAX_INTERIM_RESPONSES 10
1497 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1498 proxy_conn_rec **backend_ptr,
1499 proxy_worker *worker,
1500 proxy_server_conf *conf,
1501 char *server_portstr) {
1502 conn_rec *c = r->connection;
1503 char buffer[HUGE_STRING_LEN];
1507 apr_bucket_brigade *bb, *tmp_bb;
1508 apr_bucket_brigade *pass_bb;
1509 int len, backasswards;
1510 int interim_response = 0; /* non-zero whilst interim 1xx responses
1511 * are being read. */
1513 apr_table_t *save_table;
1514 int backend_broke = 0;
1515 static const char *hop_by_hop_hdrs[] =
1516 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1518 const char *te = NULL;
1519 int original_status = r->status;
1520 int proxy_status = OK;
1521 const char *original_status_line = r->status_line;
1522 const char *proxy_status_line = NULL;
1523 proxy_conn_rec *backend = *backend_ptr;
1524 conn_rec *origin = backend->connection;
1525 apr_interval_time_t old_timeout = 0;
1526 proxy_dir_conf *dconf;
1527 int do_100_continue;
1529 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1531 do_100_continue = (worker->s->ping_timeout_set
1532 && ap_request_has_body(r)
1533 && (PROXYREQ_REVERSE == r->proxyreq)
1534 && !(apr_table_get(r->subprocess_env, "force-proxy-request-1.0")));
1536 bb = apr_brigade_create(p, c->bucket_alloc);
1537 pass_bb = apr_brigade_create(p, c->bucket_alloc);
1539 /* Setup for 100-Continue timeout if appropriate */
1540 if (do_100_continue) {
1541 apr_socket_timeout_get(backend->sock, &old_timeout);
1542 if (worker->s->ping_timeout != old_timeout) {
1544 rc = apr_socket_timeout_set(backend->sock, worker->s->ping_timeout);
1545 if (rc != APR_SUCCESS) {
1546 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01101)
1547 "could not set 100-Continue timeout");
1552 /* Get response from the remote server, and pass it up the
1556 backend->r = make_fake_req(origin, r);
1557 /* In case anyone needs to know, this is a fake request that is really a
1560 backend->r->proxyreq = PROXYREQ_RESPONSE;
1561 apr_table_setn(r->notes, "proxy-source-port", apr_psprintf(r->pool, "%hu",
1562 origin->local_addr->port));
1563 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1567 apr_brigade_cleanup(bb);
1569 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len);
1571 /* handle one potential stray CRLF */
1572 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len);
1575 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01102)
1576 "error reading status line from remote "
1577 "server %s:%d", backend->hostname, backend->port);
1578 if (APR_STATUS_IS_TIMEUP(rc)) {
1579 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01103) "read timeout");
1580 if (do_100_continue) {
1581 return ap_proxyerror(r, HTTP_SERVICE_UNAVAILABLE, "Timeout on 100-Continue");
1585 * If we are a reverse proxy request shutdown the connection
1586 * WITHOUT ANY response to trigger a retry by the client
1587 * if allowed (as for idempotent requests).
1588 * BUT currently we should not do this if the request is the
1589 * first request on a keepalive connection as browsers like
1590 * seamonkey only display an empty page in this case and do
1591 * not do a retry. We should also not do this on a
1592 * connection which times out; instead handle as
1593 * we normally would handle timeouts
1595 if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives &&
1596 !APR_STATUS_IS_TIMEUP(rc)) {
1599 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01104)
1600 "Closing connection to client because"
1601 " reading from backend server %s:%d failed."
1602 " Number of keepalives %i", backend->hostname,
1603 backend->port, c->keepalives);
1604 ap_proxy_backend_broke(r, bb);
1606 * Add an EOC bucket to signal the ap_http_header_filter
1607 * that it should get out of our way, BUT ensure that the
1608 * EOC bucket is inserted BEFORE an EOS bucket in bb as
1609 * some resource filters like mod_deflate pass everything
1610 * up to the EOS down the chain immediately and sent the
1611 * remainder of the brigade later (or even never). But in
1612 * this case the ap_http_header_filter does not get out of
1613 * our way soon enough.
1615 e = ap_bucket_eoc_create(c->bucket_alloc);
1616 eos = APR_BRIGADE_LAST(bb);
1617 while ((APR_BRIGADE_SENTINEL(bb) != eos)
1618 && !APR_BUCKET_IS_EOS(eos)) {
1619 eos = APR_BUCKET_PREV(eos);
1621 if (eos == APR_BRIGADE_SENTINEL(bb)) {
1622 APR_BRIGADE_INSERT_TAIL(bb, e);
1625 APR_BUCKET_INSERT_BEFORE(eos, e);
1627 ap_pass_brigade(r->output_filters, bb);
1628 /* Mark the backend connection for closing */
1630 /* Need to return OK to avoid sending an error message */
1633 else if (!c->keepalives) {
1634 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01105)
1635 "NOT Closing connection to client"
1636 " although reading from backend server %s:%d"
1638 backend->hostname, backend->port);
1640 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1641 "Error reading from remote server");
1643 /* XXX: Is this a real headers length send from remote? */
1644 backend->worker->s->read += len;
1646 /* Is it an HTTP/1 response?
1647 * This is buggy if we ever see an HTTP/1.10
1649 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1652 major = buffer[5] - '0';
1653 minor = buffer[7] - '0';
1655 /* If not an HTTP/1 message or
1656 * if the status line was > 8192 bytes
1658 if ((major != 1) || (len >= sizeof(buffer)-1)) {
1659 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1660 apr_pstrcat(p, "Corrupt status line returned by remote "
1661 "server: ", buffer, NULL));
1665 keepchar = buffer[12];
1667 proxy_status = atoi(&buffer[9]);
1668 apr_table_setn(r->notes, "proxy-status",
1669 apr_pstrdup(r->pool, &buffer[9]));
1671 if (keepchar != '\0') {
1672 buffer[12] = keepchar;
1674 /* 2616 requires the space in Status-Line; the origin
1675 * server may have sent one but ap_rgetline_core will
1676 * have stripped it. */
1680 proxy_status_line = apr_pstrdup(p, &buffer[9]);
1682 /* The status out of the front is the same as the status coming in
1683 * from the back, until further notice.
1685 r->status = proxy_status;
1686 r->status_line = proxy_status_line;
1688 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
1689 "Status from backend: %d", proxy_status);
1691 /* read the headers. */
1692 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1693 /* Also, take care with headers with multiple occurences. */
1695 /* First, tuck away all already existing cookies */
1696 save_table = apr_table_make(r->pool, 2);
1697 apr_table_do(addit_dammit, save_table, r->headers_out,
1698 "Set-Cookie", NULL);
1700 /* shove the headers direct into r->headers_out */
1701 ap_proxy_read_headers(r, backend->r, buffer, sizeof(buffer), origin,
1704 if (r->headers_out == NULL) {
1705 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01106)
1706 "bad HTTP/%d.%d header returned by %s (%s)",
1707 major, minor, r->uri, r->method);
1708 backend->close += 1;
1710 * ap_send_error relies on a headers_out to be present. we
1711 * are in a bad position here.. so force everything we send out
1712 * to have nothing to do with the incoming packet
1714 r->headers_out = apr_table_make(r->pool,1);
1715 r->status = HTTP_BAD_GATEWAY;
1716 r->status_line = "bad gateway";
1720 /* Now, add in the just read cookies */
1721 apr_table_do(addit_dammit, save_table, r->headers_out,
1722 "Set-Cookie", NULL);
1724 /* and now load 'em all in */
1725 if (!apr_is_empty_table(save_table)) {
1726 apr_table_unset(r->headers_out, "Set-Cookie");
1727 r->headers_out = apr_table_overlay(r->pool,
1732 /* can't have both Content-Length and Transfer-Encoding */
1733 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1734 && apr_table_get(r->headers_out, "Content-Length")) {
1736 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1737 * and Content-Length are received, the latter MUST be
1740 * To help mitigate HTTP Splitting, unset Content-Length
1741 * and shut down the backend server connection
1742 * XXX: We aught to treat such a response as uncachable
1744 apr_table_unset(r->headers_out, "Content-Length");
1745 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01107)
1746 "server %s:%d returned Transfer-Encoding"
1747 " and Content-Length",
1748 backend->hostname, backend->port);
1749 backend->close += 1;
1753 * Save a possible Transfer-Encoding header as we need it later for
1754 * ap_http_filter to know where to end.
1756 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1757 /* strip connection listed hop-by-hop headers from response */
1758 backend->close += ap_find_token(p,
1759 apr_table_get(r->headers_out, "Connection"), "close");
1760 ap_proxy_clear_connection(p, r->headers_out);
1761 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1762 ap_set_content_type(r, apr_pstrdup(p, buf));
1764 if (!ap_is_HTTP_INFO(proxy_status)) {
1765 ap_proxy_pre_http_request(origin, backend->r);
1768 /* Clear hop-by-hop headers */
1769 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1770 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1772 /* Delete warnings with wrong date */
1773 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1775 /* handle Via header in response */
1776 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1777 const char *server_name = ap_get_server_name(r);
1778 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1779 * then the server name returned by ap_get_server_name() is the
1780 * origin server name (which does make too much sense with Via: headers)
1781 * so we use the proxy vhost's name instead.
1783 if (server_name == r->hostname)
1784 server_name = r->server->server_hostname;
1785 /* create a "Via:" response header entry and merge it */
1786 apr_table_addn(r->headers_out, "Via",
1787 (conf->viaopt == via_full)
1788 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1789 HTTP_VERSION_MAJOR(r->proto_num),
1790 HTTP_VERSION_MINOR(r->proto_num),
1793 AP_SERVER_BASEVERSION)
1794 : apr_psprintf(p, "%d.%d %s%s",
1795 HTTP_VERSION_MAJOR(r->proto_num),
1796 HTTP_VERSION_MINOR(r->proto_num),
1802 /* cancel keepalive if HTTP/1.0 or less */
1803 if ((major < 1) || (minor < 1)) {
1804 backend->close += 1;
1805 origin->keepalive = AP_CONN_CLOSE;
1808 /* an http/0.9 response */
1811 r->status_line = "200 OK";
1812 backend->close += 1;
1815 if (ap_is_HTTP_INFO(proxy_status)) {
1817 /* Reset to old timeout iff we've adjusted it */
1819 && (r->status == HTTP_CONTINUE)
1820 && (worker->s->ping_timeout != old_timeout)) {
1821 apr_socket_timeout_set(backend->sock, old_timeout);
1825 interim_response = 0;
1827 if (interim_response) {
1828 /* RFC2616 tells us to forward this.
1830 * OTOH, an interim response here may mean the backend
1831 * is playing sillybuggers. The Client didn't ask for
1832 * it within the defined HTTP/1.1 mechanisms, and if
1833 * it's an extension, it may also be unsupported by us.
1835 * There's also the possibility that changing existing
1836 * behaviour here might break something.
1838 * So let's make it configurable.
1840 const char *policy = apr_table_get(r->subprocess_env,
1841 "proxy-interim-response");
1842 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1843 "HTTP: received interim %d response", r->status);
1844 if (!policy || !strcasecmp(policy, "RFC")) {
1845 ap_send_interim_response(r, 1);
1847 /* FIXME: refine this to be able to specify per-response-status
1848 * policies and maybe also add option to bail out with 502
1850 else if (strcasecmp(policy, "Suppress")) {
1851 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01108)
1852 "undefined proxy interim response policy");
1855 /* Moved the fixups of Date headers and those affected by
1856 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1859 if ((proxy_status == 401) && (dconf->error_override)) {
1861 const char *wa = "WWW-Authenticate";
1862 if ((buf = apr_table_get(r->headers_out, wa))) {
1863 apr_table_set(r->err_headers_out, wa, buf);
1865 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01109)
1866 "origin server sent 401 without "
1867 "WWW-Authenticate header");
1873 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1874 * the response? If so, load the extra data. These are 2 mutually
1875 * exclusive possibilities, that just happen to require very
1878 if (backasswards || pread_len) {
1879 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1882 * At this point in response processing of a 0.9 response,
1883 * we don't know yet whether data is binary or not.
1884 * mod_charset_lite will get control later on, so it cannot
1885 * decide on the conversion of this buffer full of data.
1886 * However, chances are that we are not really talking to an
1887 * HTTP/0.9 server, but to some different protocol, therefore
1888 * the best guess IMHO is to always treat the buffer as "text/x":
1890 ap_xlate_proto_to_ascii(buffer, len);
1891 cntr = (apr_ssize_t)len;
1893 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1894 APR_BRIGADE_INSERT_TAIL(bb, e);
1896 /* PR 41646: get HEAD right with ProxyErrorOverride */
1897 if (ap_is_HTTP_ERROR(r->status) && dconf->error_override) {
1898 /* clear r->status for override error, otherwise ErrorDocument
1899 * thinks that this is a recursive error, and doesn't find the
1902 r->status = HTTP_OK;
1903 /* Discard body, if one is expected */
1904 if (!r->header_only && /* not HEAD request */
1905 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1906 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1907 ap_discard_request_body(backend->r);
1909 return proxy_status;
1912 /* send body - but only if a body is expected */
1913 if ((!r->header_only) && /* not HEAD request */
1914 !interim_response && /* not any 1xx response */
1915 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1916 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1918 /* We need to copy the output headers and treat them as input
1919 * headers as well. BUT, we need to do this before we remove
1920 * TE, so that they are preserved accordingly for
1921 * ap_http_filter to know where to end.
1923 backend->r->headers_in = apr_table_clone(backend->r->pool, r->headers_out);
1925 * Restore Transfer-Encoding header from response if we saved
1926 * one before and there is none left. We need it for the
1927 * ap_http_filter. See above.
1929 if (te && !apr_table_get(backend->r->headers_in, "Transfer-Encoding")) {
1930 apr_table_add(backend->r->headers_in, "Transfer-Encoding", te);
1933 apr_table_unset(r->headers_out,"Transfer-Encoding");
1935 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "start body send");
1938 * if we are overriding the errors, we can't put the content
1939 * of the page into the brigade
1941 if (!dconf->error_override || !ap_is_HTTP_ERROR(proxy_status)) {
1942 /* read the body, pass it to the output filters */
1943 apr_read_type_e mode = APR_NONBLOCK_READ;
1946 /* Handle the case where the error document is itself reverse
1947 * proxied and was successful. We must maintain any previous
1948 * error status so that an underlying error (eg HTTP_NOT_FOUND)
1949 * doesn't become an HTTP_OK.
1951 if (dconf->error_override && !ap_is_HTTP_ERROR(proxy_status)
1952 && ap_is_HTTP_ERROR(original_status)) {
1953 r->status = original_status;
1954 r->status_line = original_status_line;
1958 apr_off_t readbytes;
1961 rv = ap_get_brigade(backend->r->input_filters, bb,
1962 AP_MODE_READBYTES, mode,
1963 conf->io_buffer_size);
1965 /* ap_get_brigade will return success with an empty brigade
1966 * for a non-blocking read which would block: */
1967 if (mode == APR_NONBLOCK_READ
1968 && (APR_STATUS_IS_EAGAIN(rv)
1969 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb)))) {
1970 /* flush to the client and switch to blocking mode */
1971 e = apr_bucket_flush_create(c->bucket_alloc);
1972 APR_BRIGADE_INSERT_TAIL(bb, e);
1973 if (ap_pass_brigade(r->output_filters, bb)
1978 apr_brigade_cleanup(bb);
1979 mode = APR_BLOCK_READ;
1982 else if (rv == APR_EOF) {
1985 else if (rv != APR_SUCCESS) {
1986 /* In this case, we are in real trouble because
1987 * our backend bailed on us. Pass along a 502 error
1990 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01110)
1991 "error reading response");
1992 ap_proxy_backend_broke(r, bb);
1993 ap_pass_brigade(r->output_filters, bb);
1998 /* next time try a non-blocking read */
1999 mode = APR_NONBLOCK_READ;
2001 apr_brigade_length(bb, 0, &readbytes);
2002 backend->worker->s->read += readbytes;
2005 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01111)
2006 "readbytes: %#x", readbytes);
2010 if (APR_BRIGADE_EMPTY(bb)) {
2011 apr_brigade_cleanup(bb);
2015 /* Switch the allocator lifetime of the buckets */
2016 proxy_buckets_lifetime_transform(r, bb, pass_bb);
2018 /* found the last brigade? */
2019 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(pass_bb))) {
2021 /* signal that we must leave */
2024 /* the brigade may contain transient buckets that contain
2025 * data that lives only as long as the backend connection.
2026 * Force a setaside so these transient buckets become heap
2027 * buckets that live as long as the request.
2029 for (e = APR_BRIGADE_FIRST(pass_bb); e
2030 != APR_BRIGADE_SENTINEL(pass_bb); e
2031 = APR_BUCKET_NEXT(e)) {
2032 apr_bucket_setaside(e, r->pool);
2035 /* finally it is safe to clean up the brigade from the
2036 * connection pool, as we have forced a setaside on all
2039 apr_brigade_cleanup(bb);
2041 /* make sure we release the backend connection as soon
2042 * as we know we are done, so that the backend isn't
2043 * left waiting for a slow client to eventually
2044 * acknowledge the data.
2046 ap_proxy_release_connection(backend->worker->s->scheme,
2047 backend, r->server);
2048 /* Ensure that the backend is not reused */
2049 *backend_ptr = NULL;
2053 /* try send what we read */
2054 if (ap_pass_brigade(r->output_filters, pass_bb) != APR_SUCCESS
2056 /* Ack! Phbtt! Die! User aborted! */
2057 /* Only close backend if we haven't got all from the
2058 * backend. Furthermore if *backend_ptr is NULL it is no
2059 * longer safe to fiddle around with backend as it might
2060 * be already in use by another thread.
2063 backend->close = 1; /* this causes socket close below */
2068 /* make sure we always clean up after ourselves */
2069 apr_brigade_cleanup(pass_bb);
2070 apr_brigade_cleanup(bb);
2074 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "end body send");
2076 else if (!interim_response) {
2077 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "header only");
2079 /* make sure we release the backend connection as soon
2080 * as we know we are done, so that the backend isn't
2081 * left waiting for a slow client to eventually
2082 * acknowledge the data.
2084 ap_proxy_release_connection(backend->worker->s->scheme,
2085 backend, r->server);
2086 *backend_ptr = NULL;
2088 /* Pass EOS bucket down the filter chain. */
2089 e = apr_bucket_eos_create(c->bucket_alloc);
2090 APR_BRIGADE_INSERT_TAIL(bb, e);
2091 ap_pass_brigade(r->output_filters, bb);
2093 apr_brigade_cleanup(bb);
2095 } while (interim_response && (interim_response < AP_MAX_INTERIM_RESPONSES));
2097 /* See define of AP_MAX_INTERIM_RESPONSES for why */
2098 if (interim_response >= AP_MAX_INTERIM_RESPONSES) {
2099 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2101 "Too many (%d) interim responses from origin server",
2105 /* If our connection with the client is to be aborted, return DONE. */
2106 if (c->aborted || backend_broke) {
2114 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
2115 proxy_conn_rec *backend)
2117 ap_proxy_release_connection(scheme, backend, r->server);
2122 * This handles http:// URLs, and other URLs using a remote proxy over http
2123 * If proxyhost is NULL, then contact the server directly, otherwise
2125 * Note that if a proxy is used, then URLs other than http: can be accessed,
2126 * also, if we have trouble which is clearly specific to the proxy, then
2127 * we return DECLINED so that we can try another proxy. (Or the direct
2130 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
2131 proxy_server_conf *conf,
2132 char *url, const char *proxyname,
2133 apr_port_t proxyport)
2136 char server_portstr[32];
2138 const char *proxy_function;
2140 proxy_conn_rec *backend = NULL;
2142 conn_rec *c = r->connection;
2145 * Use a shorter-lived pool to reduce memory usage
2146 * and avoid a memory leak
2148 apr_pool_t *p = r->pool;
2149 apr_uri_t *uri = apr_palloc(p, sizeof(*uri));
2151 /* find the scheme */
2152 u = strchr(url, ':');
2153 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
2156 return HTTP_BAD_REQUEST;
2157 scheme = apr_pstrndup(p, url, u - url);
2158 /* scheme is lowercase */
2159 ap_str_tolower(scheme);
2161 if (strcmp(scheme, "https") == 0) {
2162 if (!ap_proxy_ssl_enable(NULL)) {
2163 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01112)
2164 "HTTPS: declining URL %s (mod_ssl not configured?)",
2169 proxy_function = "HTTPS";
2171 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
2172 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01113) "HTTP: declining URL %s",
2174 return DECLINED; /* only interested in HTTP, or FTP via proxy */
2178 proxy_function = "HTTP";
2180 proxy_function = "FTP";
2182 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "HTTP: serving URL %s", url);
2185 /* create space for state information */
2186 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
2187 worker, r->server)) != OK)
2191 backend->is_ssl = is_ssl;
2194 ap_proxy_ssl_connection_cleanup(backend, r);
2198 * In the case that we are handling a reverse proxy connection and this
2199 * is not a request that is coming over an already kept alive connection
2200 * with the client, do NOT reuse the connection to the backend, because
2201 * we cannot forward a failure to the client in this case as the client
2202 * does NOT expect this in this situation.
2203 * Yes, this creates a performance penalty.
2205 if ((r->proxyreq == PROXYREQ_REVERSE) && (!c->keepalives)
2206 && (apr_table_get(r->subprocess_env, "proxy-initial-not-pooled"))) {
2213 /* Step One: Determine Who To Connect To */
2214 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
2215 uri, &locurl, proxyname,
2216 proxyport, server_portstr,
2217 sizeof(server_portstr))) != OK)
2220 /* Step Two: Make the Connection */
2221 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
2222 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01114)
2223 "HTTP: failed to make connection to backend: %s",
2225 status = HTTP_SERVICE_UNAVAILABLE;
2229 /* Step Three: Create conn_rec */
2230 if (!backend->connection) {
2231 if ((status = ap_proxy_connection_create(proxy_function, backend,
2232 c, r->server)) != OK)
2235 * On SSL connections set a note on the connection what CN is
2236 * requested, such that mod_ssl can check if it is requested to do
2240 proxy_dir_conf *dconf;
2241 const char *ssl_hostname;
2244 * In the case of ProxyPreserveHost on use the hostname of
2245 * the request if present otherwise use the one from the
2246 * backend request URI.
2248 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
2249 if ((dconf->preserve_host != 0) && (r->hostname != NULL)) {
2250 ssl_hostname = r->hostname;
2253 ssl_hostname = uri->hostname;
2256 apr_table_set(backend->connection->notes, "proxy-request-hostname",
2261 /* Step Four: Send the Request
2262 * On the off-chance that we forced a 100-Continue as a
2263 * kinda HTTP ping test, allow for retries
2265 if ((status = ap_proxy_http_request(p, r, backend, worker,
2266 conf, uri, locurl, server_portstr)) != OK) {
2267 if ((status == HTTP_SERVICE_UNAVAILABLE) && worker->s->ping_timeout_set) {
2269 ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r, APLOGNO(01115)
2270 "HTTP: 100-Continue failed to %pI (%s)",
2271 worker->cp->addr, worker->s->hostname);
2280 /* Step Five: Receive the Response... Fall thru to cleanup */
2281 status = ap_proxy_http_process_response(p, r, &backend, worker,
2282 conf, server_portstr);
2287 /* Step Six: Clean Up */
2292 ap_proxy_http_cleanup(proxy_function, r, backend);
2296 static void ap_proxy_http_register_hook(apr_pool_t *p)
2298 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
2299 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
2300 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
2303 AP_DECLARE_MODULE(proxy_http) = {
2304 STANDARD20_MODULE_STUFF,
2305 NULL, /* create per-directory config structure */
2306 NULL, /* merge per-directory config structures */
2307 NULL, /* create per-server config structure */
2308 NULL, /* merge per-server config structures */
2309 NULL, /* command apr_table_t */
2310 ap_proxy_http_register_hook/* register hooks */