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);
254 #define MAX_MEM_SPOOL 16384
256 static int stream_reqbody_chunked(apr_pool_t *p,
258 proxy_conn_rec *p_conn,
260 apr_bucket_brigade *header_brigade,
261 apr_bucket_brigade *input_brigade)
263 int seen_eos = 0, rv = OK;
267 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
268 apr_bucket_brigade *bb;
271 add_te_chunked(p, bucket_alloc, header_brigade);
272 terminate_headers(bucket_alloc, header_brigade);
274 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
276 char chunk_hdr[20]; /* must be here due to transient bucket. */
278 /* If this brigade contains EOS, either stop or remove it. */
279 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
282 /* We can't pass this EOS to the output_filters. */
283 e = APR_BRIGADE_LAST(input_brigade);
284 apr_bucket_delete(e);
287 apr_brigade_length(input_brigade, 1, &bytes);
289 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
290 "%" APR_UINT64_T_HEX_FMT CRLF,
291 (apr_uint64_t)bytes);
293 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
294 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
296 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
299 * Append the end-of-chunk CRLF
301 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
302 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
304 if (header_brigade) {
305 /* we never sent the header brigade, so go ahead and
306 * take care of that now
311 * Save input_brigade in bb brigade. (At least) in the SSL case
312 * input_brigade contains transient buckets whose data would get
313 * overwritten during the next call of ap_get_brigade in the loop.
314 * ap_save_brigade ensures these buckets to be set aside.
315 * Calling ap_save_brigade with NULL as filter is OK, because
316 * bb brigade already has been created and does not need to get
317 * created by ap_save_brigade.
319 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
320 if (status != APR_SUCCESS) {
321 return HTTP_INTERNAL_SERVER_ERROR;
324 header_brigade = NULL;
330 /* The request is flushed below this loop with chunk EOS header */
331 rv = ap_proxy_pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
340 status = ap_get_brigade(r->input_filters, input_brigade,
341 AP_MODE_READBYTES, APR_BLOCK_READ,
344 if (status != APR_SUCCESS) {
345 return HTTP_BAD_REQUEST;
349 if (header_brigade) {
350 /* we never sent the header brigade because there was no request body;
356 if (!APR_BRIGADE_EMPTY(input_brigade)) {
357 /* input brigade still has an EOS which we can't pass to the output_filters. */
358 e = APR_BRIGADE_LAST(input_brigade);
359 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
360 apr_bucket_delete(e);
365 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
369 APR_BRIGADE_INSERT_TAIL(bb, e);
371 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
372 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
373 APR_BRIGADE_INSERT_TAIL(bb, e);
376 /* Now we have headers-only, or the chunk EOS mark; flush it */
377 rv = ap_proxy_pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
381 static int stream_reqbody_cl(apr_pool_t *p,
383 proxy_conn_rec *p_conn,
385 apr_bucket_brigade *header_brigade,
386 apr_bucket_brigade *input_brigade,
389 int seen_eos = 0, rv = 0;
390 apr_status_t status = APR_SUCCESS;
391 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
392 apr_bucket_brigade *bb;
394 apr_off_t cl_val = 0;
396 apr_off_t bytes_streamed = 0;
401 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
402 status = apr_strtoff(&cl_val, old_cl_val, &endstr, 10);
404 if (status || *endstr || endstr == old_cl_val || cl_val < 0) {
405 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01085)
406 "could not parse request Content-Length (%s)",
408 return HTTP_BAD_REQUEST;
411 terminate_headers(bucket_alloc, header_brigade);
413 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
415 apr_brigade_length(input_brigade, 1, &bytes);
416 bytes_streamed += bytes;
418 /* If this brigade contains EOS, either stop or remove it. */
419 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
422 /* We can't pass this EOS to the output_filters. */
423 e = APR_BRIGADE_LAST(input_brigade);
424 apr_bucket_delete(e);
426 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
427 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
428 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
432 /* C-L < bytes streamed?!?
433 * We will error out after the body is completely
434 * consumed, but we can't stream more bytes at the
435 * back end since they would in part be interpreted
436 * as another request! If nothing is sent, then
439 * Prevents HTTP Response Splitting.
441 if (bytes_streamed > cl_val) {
442 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01086)
443 "read more bytes of request body than expected "
444 "(got %" APR_OFF_T_FMT ", expected %" APR_OFF_T_FMT ")",
445 bytes_streamed, cl_val);
446 return HTTP_INTERNAL_SERVER_ERROR;
449 if (header_brigade) {
450 /* we never sent the header brigade, so go ahead and
451 * take care of that now
456 * Save input_brigade in bb brigade. (At least) in the SSL case
457 * input_brigade contains transient buckets whose data would get
458 * overwritten during the next call of ap_get_brigade in the loop.
459 * ap_save_brigade ensures these buckets to be set aside.
460 * Calling ap_save_brigade with NULL as filter is OK, because
461 * bb brigade already has been created and does not need to get
462 * created by ap_save_brigade.
464 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
465 if (status != APR_SUCCESS) {
466 return HTTP_INTERNAL_SERVER_ERROR;
469 header_brigade = NULL;
475 /* Once we hit EOS, we are ready to flush. */
476 rv = ap_proxy_pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
485 status = ap_get_brigade(r->input_filters, input_brigade,
486 AP_MODE_READBYTES, APR_BLOCK_READ,
489 if (status != APR_SUCCESS) {
490 return HTTP_BAD_REQUEST;
494 if (bytes_streamed != cl_val) {
495 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01087)
496 "client %s given Content-Length did not match"
497 " number of body bytes read", r->connection->client_ip);
498 return HTTP_BAD_REQUEST;
501 if (header_brigade) {
502 /* we never sent the header brigade since there was no request
503 * body; send it now with the flush flag
506 return(ap_proxy_pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
512 static int spool_reqbody_cl(apr_pool_t *p,
514 proxy_conn_rec *p_conn,
516 apr_bucket_brigade *header_brigade,
517 apr_bucket_brigade *input_brigade,
522 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
523 apr_bucket_brigade *body_brigade;
525 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
526 apr_file_t *tmpfile = NULL;
529 body_brigade = apr_brigade_create(p, bucket_alloc);
531 limit = ap_get_limit_req_body(r);
533 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
535 /* If this brigade contains EOS, either stop or remove it. */
536 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
539 /* We can't pass this EOS to the output_filters. */
540 e = APR_BRIGADE_LAST(input_brigade);
541 apr_bucket_delete(e);
544 apr_brigade_length(input_brigade, 1, &bytes);
546 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
548 * LimitRequestBody does not affect Proxy requests (Should it?).
549 * Let it take effect if we decide to store the body in a
550 * temporary file on disk.
552 if (limit && (bytes_spooled + bytes > limit)) {
553 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01088)
554 "Request body is larger than the configured "
555 "limit of %" APR_OFF_T_FMT, limit);
556 return HTTP_REQUEST_ENTITY_TOO_LARGE;
558 /* can't spool any more in memory; write latest brigade to disk */
559 if (tmpfile == NULL) {
560 const char *temp_dir;
563 status = apr_temp_dir_get(&temp_dir, p);
564 if (status != APR_SUCCESS) {
565 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01089)
566 "search for temporary directory failed");
567 return HTTP_INTERNAL_SERVER_ERROR;
569 apr_filepath_merge(&template, temp_dir,
570 "modproxy.tmp.XXXXXX",
571 APR_FILEPATH_NATIVE, p);
572 status = apr_file_mktemp(&tmpfile, template, 0, p);
573 if (status != APR_SUCCESS) {
574 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01090)
575 "creation of temporary file in directory "
576 "%s failed", temp_dir);
577 return HTTP_INTERNAL_SERVER_ERROR;
580 for (e = APR_BRIGADE_FIRST(input_brigade);
581 e != APR_BRIGADE_SENTINEL(input_brigade);
582 e = APR_BUCKET_NEXT(e)) {
584 apr_size_t bytes_read, bytes_written;
586 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
587 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
588 if (status != APR_SUCCESS) {
589 const char *tmpfile_name;
591 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
592 tmpfile_name = "(unknown)";
594 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01091)
595 "write to temporary file %s failed",
597 return HTTP_INTERNAL_SERVER_ERROR;
599 AP_DEBUG_ASSERT(bytes_read == bytes_written);
600 fsize += bytes_written;
602 apr_brigade_cleanup(input_brigade);
607 * Save input_brigade in body_brigade. (At least) in the SSL case
608 * input_brigade contains transient buckets whose data would get
609 * overwritten during the next call of ap_get_brigade in the loop.
610 * ap_save_brigade ensures these buckets to be set aside.
611 * Calling ap_save_brigade with NULL as filter is OK, because
612 * body_brigade already has been created and does not need to get
613 * created by ap_save_brigade.
615 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
616 if (status != APR_SUCCESS) {
617 return HTTP_INTERNAL_SERVER_ERROR;
622 bytes_spooled += bytes;
628 status = ap_get_brigade(r->input_filters, input_brigade,
629 AP_MODE_READBYTES, APR_BLOCK_READ,
632 if (status != APR_SUCCESS) {
633 return HTTP_BAD_REQUEST;
637 if (bytes_spooled || force_cl) {
638 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
640 terminate_headers(bucket_alloc, header_brigade);
641 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
643 apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
645 if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
646 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
647 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
649 /* This is all a single brigade, pass with flush flagged */
650 return(ap_proxy_pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
654 * Transform buckets from one bucket allocator to another one by creating a
655 * transient bucket for each data bucket and let it use the data read from
656 * the old bucket. Metabuckets are transformed by just recreating them.
657 * Attention: Currently only the following bucket types are handled:
663 * If an other bucket type is found its type is logged as a debug message
664 * and APR_EGENERAL is returned.
666 static apr_status_t proxy_buckets_lifetime_transform(request_rec *r,
667 apr_bucket_brigade *from, apr_bucket_brigade *to)
673 apr_status_t rv = APR_SUCCESS;
675 apr_brigade_cleanup(to);
676 for (e = APR_BRIGADE_FIRST(from);
677 e != APR_BRIGADE_SENTINEL(from);
678 e = APR_BUCKET_NEXT(e)) {
679 if (!APR_BUCKET_IS_METADATA(e)) {
680 apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
681 new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
682 APR_BRIGADE_INSERT_TAIL(to, new);
684 else if (APR_BUCKET_IS_FLUSH(e)) {
685 new = apr_bucket_flush_create(r->connection->bucket_alloc);
686 APR_BRIGADE_INSERT_TAIL(to, new);
688 else if (APR_BUCKET_IS_EOS(e)) {
689 new = apr_bucket_eos_create(r->connection->bucket_alloc);
690 APR_BRIGADE_INSERT_TAIL(to, new);
693 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00964)
694 "Unhandled bucket type of type %s in"
695 " proxy_buckets_lifetime_transform", e->type->name);
696 apr_bucket_delete(e);
704 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
705 proxy_conn_rec *p_conn, proxy_worker *worker,
706 proxy_server_conf *conf,
708 char *url, char *server_portstr)
710 conn_rec *c = r->connection;
711 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
712 apr_bucket_brigade *header_brigade;
713 apr_bucket_brigade *input_brigade;
714 apr_bucket_brigade *temp_brigade;
718 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
719 enum rb_methods rb_method = RB_INIT;
720 char *old_cl_val = NULL;
721 char *old_te_val = NULL;
722 apr_off_t bytes_read = 0;
725 conn_rec *origin = p_conn->connection;
727 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
728 if (r->expecting_100) {
729 return HTTP_EXPECTATION_FAILED;
736 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
737 rv = ap_proxy_create_hdrbrgd(p, header_brigade, r, p_conn,
738 worker, conf, uri, url, server_portstr,
739 &old_cl_val, &old_te_val);
744 /* We have headers, let's figure out our request body... */
745 input_brigade = apr_brigade_create(p, bucket_alloc);
747 /* sub-requests never use keepalives, and mustn't pass request bodies.
748 * Because the new logic looks at input_brigade, we will self-terminate
749 * input_brigade and jump past all of the request body logic...
750 * Reading anything with ap_get_brigade is likely to consume the
751 * main request's body or read beyond EOS - which would be unplesant.
753 * An exception: when a kept_body is present, then subrequest CAN use
754 * pass request bodies, and we DONT skip the body.
756 if (!r->kept_body && r->main) {
757 /* XXX: Why DON'T sub-requests use keepalives? */
761 apr_table_unset(r->headers_in, "Content-Length");
765 apr_table_unset(r->headers_in, "Transfer-Encoding");
767 rb_method = RB_STREAM_CL;
768 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
769 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
773 /* WE only understand chunked. Other modules might inject
774 * (and therefore, decode) other flavors but we don't know
775 * that the can and have done so unless they they remove
776 * their decoding from the headers_in T-E list.
777 * XXX: Make this extensible, but in doing so, presume the
778 * encoding has been done by the extensions' handler, and
779 * do not modify add_te_chunked's logic
781 if (old_te_val && strcasecmp(old_te_val, "chunked") != 0) {
782 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01093)
783 "%s Transfer-Encoding is not supported", old_te_val);
784 return HTTP_INTERNAL_SERVER_ERROR;
787 if (old_cl_val && old_te_val) {
788 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01094)
789 "client %s (%s) requested Transfer-Encoding "
790 "chunked body with Content-Length (C-L ignored)",
791 c->client_ip, c->remote_host ? c->remote_host: "");
792 apr_table_unset(r->headers_in, "Content-Length");
794 origin->keepalive = AP_CONN_CLOSE;
798 /* Prefetch MAX_MEM_SPOOL bytes
800 * This helps us avoid any election of C-L v.s. T-E
801 * request bodies, since we are willing to keep in
802 * memory this much data, in any case. This gives
803 * us an instant C-L election if the body is of some
806 temp_brigade = apr_brigade_create(p, bucket_alloc);
808 status = ap_get_brigade(r->input_filters, temp_brigade,
809 AP_MODE_READBYTES, APR_BLOCK_READ,
810 MAX_MEM_SPOOL - bytes_read);
811 if (status != APR_SUCCESS) {
812 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01095)
813 "prefetch request body failed to %pI (%s)"
815 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
816 c->client_ip, c->remote_host ? c->remote_host: "");
817 return HTTP_BAD_REQUEST;
820 apr_brigade_length(temp_brigade, 1, &bytes);
824 * Save temp_brigade in input_brigade. (At least) in the SSL case
825 * temp_brigade contains transient buckets whose data would get
826 * overwritten during the next call of ap_get_brigade in the loop.
827 * ap_save_brigade ensures these buckets to be set aside.
828 * Calling ap_save_brigade with NULL as filter is OK, because
829 * input_brigade already has been created and does not need to get
830 * created by ap_save_brigade.
832 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
833 if (status != APR_SUCCESS) {
834 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(01096)
835 "processing prefetched request body failed"
836 " to %pI (%s) from %s (%s)",
837 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
838 c->client_ip, c->remote_host ? c->remote_host: "");
839 return HTTP_INTERNAL_SERVER_ERROR;
842 /* Ensure we don't hit a wall where we have a buffer too small
843 * for ap_get_brigade's filters to fetch us another bucket,
844 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
845 * (an arbitrary value.)
847 } while ((bytes_read < MAX_MEM_SPOOL - 80)
848 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
850 /* Use chunked request body encoding or send a content-length body?
854 * We have no request body (handled by RB_STREAM_CL)
856 * We have a request body length <= MAX_MEM_SPOOL
858 * The administrator has setenv force-proxy-request-1.0
860 * The client sent a C-L body, and the administrator has
861 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
863 * The client sent a T-E body, and the administrator has
864 * setenv proxy-sendcl, and not setenv proxy-sendchunked
866 * If both proxy-sendcl and proxy-sendchunked are set, the
867 * behavior is the same as if neither were set, large bodies
868 * that can't be read will be forwarded in their original
869 * form of C-L, or T-E.
871 * To ensure maximum compatibility, setenv proxy-sendcl
872 * To reduce server resource use, setenv proxy-sendchunked
874 * Then address specific servers with conditional setenv
875 * options to restore the default behavior where desireable.
877 * We have to compute content length by reading the entire request
878 * body; if request body is not small, we'll spool the remaining
879 * input to a temporary file. Chunked is always preferable.
881 * We can only trust the client-provided C-L if the T-E header
882 * is absent, and the filters are unchanged (the body won't
883 * be resized by another content filter).
885 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
886 /* The whole thing fit, so our decision is trivial, use
887 * the filtered bytes read from the client for the request
888 * body Content-Length.
890 * If we expected no body, and read no body, do not set
891 * the Content-Length.
893 if (old_cl_val || old_te_val || bytes_read) {
894 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
896 rb_method = RB_STREAM_CL;
898 else if (old_te_val) {
900 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
901 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
902 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
903 rb_method = RB_SPOOL_CL;
906 rb_method = RB_STREAM_CHUNKED;
909 else if (old_cl_val) {
910 if (r->input_filters == r->proto_input_filters) {
911 rb_method = RB_STREAM_CL;
914 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
915 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
916 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
917 rb_method = RB_STREAM_CHUNKED;
920 rb_method = RB_SPOOL_CL;
924 /* This is an appropriate default; very efficient for no-body
925 * requests, and has the behavior that it will not add any C-L
926 * when the old_cl_val is NULL.
928 rb_method = RB_SPOOL_CL;
931 /* Yes I hate gotos. This is the subrequest shortcut */
934 * Handle Connection: header if we do HTTP/1.1 request:
935 * If we plan to close the backend connection sent Connection: close
936 * otherwise sent Connection: Keep-Alive.
940 buf = apr_pstrdup(p, "Connection: close" CRLF);
943 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
945 ap_xlate_proto_to_ascii(buf, strlen(buf));
946 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
947 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
950 /* send the request body, if any. */
952 case RB_STREAM_CHUNKED:
953 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
957 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
958 input_brigade, old_cl_val);
961 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
962 input_brigade, (old_cl_val != NULL)
963 || (old_te_val != NULL)
964 || (bytes_read > 0));
967 /* shouldn't be possible */
968 rv = HTTP_INTERNAL_SERVER_ERROR ;
973 /* apr_status_t value has been logged in lower level method */
974 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01097)
975 "pass request body failed to %pI (%s) from %s (%s)",
976 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
977 c->client_ip, c->remote_host ? c->remote_host: "");
985 * If the date is a valid RFC 850 date or asctime() date, then it
986 * is converted to the RFC 1123 format.
988 static const char *date_canon(apr_pool_t *p, const char *date)
993 apr_time_t time = apr_date_parse_http(date);
998 ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
999 rv = apr_rfc822_date(ndate, time);
1000 if (rv != APR_SUCCESS) {
1007 static request_rec *make_fake_req(conn_rec *c, request_rec *r)
1012 apr_pool_create(&pool, c->pool);
1014 rp = apr_pcalloc(pool, sizeof(*r));
1017 rp->status = HTTP_OK;
1019 rp->headers_in = apr_table_make(pool, 50);
1020 rp->subprocess_env = apr_table_make(pool, 50);
1021 rp->headers_out = apr_table_make(pool, 12);
1022 rp->err_headers_out = apr_table_make(pool, 5);
1023 rp->notes = apr_table_make(pool, 5);
1025 rp->server = r->server;
1027 rp->proxyreq = r->proxyreq;
1028 rp->request_time = r->request_time;
1030 rp->output_filters = c->output_filters;
1031 rp->input_filters = c->input_filters;
1032 rp->proto_output_filters = c->output_filters;
1033 rp->proto_input_filters = c->input_filters;
1034 rp->useragent_ip = c->client_ip;
1035 rp->useragent_addr = c->client_addr;
1037 rp->request_config = ap_create_request_config(pool);
1038 proxy_run_create_req(r, rp);
1043 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1044 const char *key, const char *value)
1046 static const char *date_hdrs[]
1047 = { "Date", "Expires", "Last-Modified", NULL };
1048 static const struct {
1050 ap_proxy_header_reverse_map_fn func;
1051 } transform_hdrs[] = {
1052 { "Location", ap_proxy_location_reverse_map },
1053 { "Content-Location", ap_proxy_location_reverse_map },
1054 { "URI", ap_proxy_location_reverse_map },
1055 { "Destination", ap_proxy_location_reverse_map },
1056 { "Set-Cookie", ap_proxy_cookie_reverse_map },
1060 for (i = 0; date_hdrs[i]; ++i) {
1061 if (!strcasecmp(date_hdrs[i], key)) {
1062 apr_table_add(r->headers_out, key,
1063 date_canon(r->pool, value));
1067 for (i = 0; transform_hdrs[i].name; ++i) {
1068 if (!strcasecmp(transform_hdrs[i].name, key)) {
1069 apr_table_add(r->headers_out, key,
1070 (*transform_hdrs[i].func)(r, c, value));
1074 apr_table_add(r->headers_out, key, value);
1079 * Note: pread_len is the length of the response that we've mistakenly
1080 * read (assuming that we don't consider that an error via
1081 * ProxyBadHeader StartBody). This depends on buffer actually being
1082 * local storage to the calling code in order for pread_len to make
1083 * any sense at all, since we depend on buffer still containing
1084 * what was read by ap_getline() upon return.
1086 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1087 char *buffer, int size,
1088 conn_rec *c, int *pread_len)
1092 char field[MAX_STRING_LEN];
1093 int saw_headers = 0;
1094 void *sconf = r->server->module_config;
1095 proxy_server_conf *psc;
1096 proxy_dir_conf *dconf;
1098 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1099 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1101 r->headers_out = apr_table_make(r->pool, 20);
1105 * Read header lines until we get the empty separator line, a read error,
1106 * the connection closes (EOF), or we timeout.
1108 ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r,
1109 "Headers received from backend:");
1110 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1111 ap_log_rerror(APLOG_MARK, APLOG_TRACE4, 0, r, "%s", buffer);
1113 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1115 /* We may encounter invalid headers, usually from buggy
1116 * MS IIS servers, so we need to determine just how to handle
1117 * them. We can either ignore them, assume that they mark the
1118 * start-of-body (eg: a missing CRLF) or (the default) mark
1119 * the headers as totally bogus and return a 500. The sole
1120 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1121 * in between the usual MIME headers, which is a favorite
1124 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1126 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1127 if (psc->badopt == bad_error) {
1128 /* Nope, it wasn't even an extra HTTP header. Give up. */
1129 r->headers_out = NULL;
1132 else if (psc->badopt == bad_body) {
1133 /* if we've already started loading headers_out, then
1134 * return what we've accumulated so far, in the hopes
1135 * that they are useful; also note that we likely pre-read
1136 * the first line of the response.
1139 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01098)
1140 "Starting body due to bogus non-header "
1141 "in headers returned by %s (%s)",
1146 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01099)
1147 "No HTTP headers returned by %s (%s)",
1153 /* this is the psc->badopt == bad_ignore case */
1154 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01100)
1155 "Ignoring bogus HTTP header returned by %s (%s)",
1162 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1163 * wrong... and so are many others probably.
1165 while (apr_isspace(*value))
1166 ++value; /* Skip to start of value */
1168 /* should strip trailing whitespace as well */
1169 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1173 /* make sure we add so as not to destroy duplicated headers
1174 * Modify headers requiring canonicalisation and/or affected
1175 * by ProxyPassReverse and family with process_proxy_header
1177 process_proxy_header(r, dconf, buffer, value) ;
1180 /* the header was too long; at the least we should skip extra data */
1181 if (len >= size - 1) {
1182 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1183 >= MAX_STRING_LEN - 1) {
1184 /* soak up the extra data */
1186 if (len == 0) /* time to exit the larger loop as well */
1194 static int addit_dammit(void *v, const char *key, const char *val)
1196 apr_table_addn(v, key, val);
1201 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1202 int fold, int *writen)
1208 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1209 apr_brigade_cleanup(bb);
1211 if (rv == APR_SUCCESS) {
1212 *writen = (int) len;
1213 } else if (APR_STATUS_IS_ENOSPC(rv)) {
1223 * Limit the number of interim respones we sent back to the client. Otherwise
1224 * we suffer from a memory build up. Besides there is NO sense in sending back
1225 * an unlimited number of interim responses to the client. Thus if we cross
1226 * this limit send back a 502 (Bad Gateway).
1228 #ifndef AP_MAX_INTERIM_RESPONSES
1229 #define AP_MAX_INTERIM_RESPONSES 10
1233 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1234 proxy_conn_rec **backend_ptr,
1235 proxy_worker *worker,
1236 proxy_server_conf *conf,
1237 char *server_portstr) {
1238 conn_rec *c = r->connection;
1239 char buffer[HUGE_STRING_LEN];
1243 apr_bucket_brigade *bb, *tmp_bb;
1244 apr_bucket_brigade *pass_bb;
1245 int len, backasswards;
1246 int interim_response = 0; /* non-zero whilst interim 1xx responses
1247 * are being read. */
1249 apr_table_t *save_table;
1250 int backend_broke = 0;
1251 static const char *hop_by_hop_hdrs[] =
1252 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1254 const char *te = NULL;
1255 int original_status = r->status;
1256 int proxy_status = OK;
1257 const char *original_status_line = r->status_line;
1258 const char *proxy_status_line = NULL;
1259 proxy_conn_rec *backend = *backend_ptr;
1260 conn_rec *origin = backend->connection;
1261 apr_interval_time_t old_timeout = 0;
1262 proxy_dir_conf *dconf;
1263 int do_100_continue;
1265 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1267 do_100_continue = (worker->s->ping_timeout_set
1268 && ap_request_has_body(r)
1269 && (PROXYREQ_REVERSE == r->proxyreq)
1270 && !(apr_table_get(r->subprocess_env, "force-proxy-request-1.0")));
1272 bb = apr_brigade_create(p, c->bucket_alloc);
1273 pass_bb = apr_brigade_create(p, c->bucket_alloc);
1275 /* Setup for 100-Continue timeout if appropriate */
1276 if (do_100_continue) {
1277 apr_socket_timeout_get(backend->sock, &old_timeout);
1278 if (worker->s->ping_timeout != old_timeout) {
1280 rc = apr_socket_timeout_set(backend->sock, worker->s->ping_timeout);
1281 if (rc != APR_SUCCESS) {
1282 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01101)
1283 "could not set 100-Continue timeout");
1288 /* Get response from the remote server, and pass it up the
1292 backend->r = make_fake_req(origin, r);
1293 /* In case anyone needs to know, this is a fake request that is really a
1296 backend->r->proxyreq = PROXYREQ_RESPONSE;
1297 apr_table_setn(r->notes, "proxy-source-port", apr_psprintf(r->pool, "%hu",
1298 origin->local_addr->port));
1299 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1303 apr_brigade_cleanup(bb);
1305 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len);
1307 /* handle one potential stray CRLF */
1308 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), backend->r, 0, &len);
1311 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r, APLOGNO(01102)
1312 "error reading status line from remote "
1313 "server %s:%d", backend->hostname, backend->port);
1314 if (APR_STATUS_IS_TIMEUP(rc)) {
1315 apr_table_set(r->notes, "proxy_timedout", "1");
1316 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01103) "read timeout");
1317 if (do_100_continue) {
1318 return ap_proxyerror(r, HTTP_SERVICE_UNAVAILABLE, "Timeout on 100-Continue");
1322 * If we are a reverse proxy request shutdown the connection
1323 * WITHOUT ANY response to trigger a retry by the client
1324 * if allowed (as for idempotent requests).
1325 * BUT currently we should not do this if the request is the
1326 * first request on a keepalive connection as browsers like
1327 * seamonkey only display an empty page in this case and do
1328 * not do a retry. We should also not do this on a
1329 * connection which times out; instead handle as
1330 * we normally would handle timeouts
1332 if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives &&
1333 !APR_STATUS_IS_TIMEUP(rc)) {
1336 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01104)
1337 "Closing connection to client because"
1338 " reading from backend server %s:%d failed."
1339 " Number of keepalives %i", backend->hostname,
1340 backend->port, c->keepalives);
1341 ap_proxy_backend_broke(r, bb);
1343 * Add an EOC bucket to signal the ap_http_header_filter
1344 * that it should get out of our way, BUT ensure that the
1345 * EOC bucket is inserted BEFORE an EOS bucket in bb as
1346 * some resource filters like mod_deflate pass everything
1347 * up to the EOS down the chain immediately and sent the
1348 * remainder of the brigade later (or even never). But in
1349 * this case the ap_http_header_filter does not get out of
1350 * our way soon enough.
1352 e = ap_bucket_eoc_create(c->bucket_alloc);
1353 eos = APR_BRIGADE_LAST(bb);
1354 while ((APR_BRIGADE_SENTINEL(bb) != eos)
1355 && !APR_BUCKET_IS_EOS(eos)) {
1356 eos = APR_BUCKET_PREV(eos);
1358 if (eos == APR_BRIGADE_SENTINEL(bb)) {
1359 APR_BRIGADE_INSERT_TAIL(bb, e);
1362 APR_BUCKET_INSERT_BEFORE(eos, e);
1364 ap_pass_brigade(r->output_filters, bb);
1365 /* Mark the backend connection for closing */
1367 /* Need to return OK to avoid sending an error message */
1370 else if (!c->keepalives) {
1371 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01105)
1372 "NOT Closing connection to client"
1373 " although reading from backend server %s:%d"
1375 backend->hostname, backend->port);
1377 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1378 "Error reading from remote server");
1380 /* XXX: Is this a real headers length send from remote? */
1381 backend->worker->s->read += len;
1383 /* Is it an HTTP/1 response?
1384 * This is buggy if we ever see an HTTP/1.10
1386 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1389 major = buffer[5] - '0';
1390 minor = buffer[7] - '0';
1392 /* If not an HTTP/1 message or
1393 * if the status line was > 8192 bytes
1395 if ((major != 1) || (len >= sizeof(buffer)-1)) {
1396 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1397 apr_pstrcat(p, "Corrupt status line returned by remote "
1398 "server: ", buffer, NULL));
1402 keepchar = buffer[12];
1404 proxy_status = atoi(&buffer[9]);
1405 apr_table_setn(r->notes, "proxy-status",
1406 apr_pstrdup(r->pool, &buffer[9]));
1408 if (keepchar != '\0') {
1409 buffer[12] = keepchar;
1411 /* 2616 requires the space in Status-Line; the origin
1412 * server may have sent one but ap_rgetline_core will
1413 * have stripped it. */
1417 proxy_status_line = apr_pstrdup(p, &buffer[9]);
1419 /* The status out of the front is the same as the status coming in
1420 * from the back, until further notice.
1422 r->status = proxy_status;
1423 r->status_line = proxy_status_line;
1425 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r,
1426 "Status from backend: %d", proxy_status);
1428 /* read the headers. */
1429 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1430 /* Also, take care with headers with multiple occurences. */
1432 /* First, tuck away all already existing cookies */
1433 save_table = apr_table_make(r->pool, 2);
1434 apr_table_do(addit_dammit, save_table, r->headers_out,
1435 "Set-Cookie", NULL);
1437 /* shove the headers direct into r->headers_out */
1438 ap_proxy_read_headers(r, backend->r, buffer, sizeof(buffer), origin,
1441 if (r->headers_out == NULL) {
1442 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01106)
1443 "bad HTTP/%d.%d header returned by %s (%s)",
1444 major, minor, r->uri, r->method);
1447 * ap_send_error relies on a headers_out to be present. we
1448 * are in a bad position here.. so force everything we send out
1449 * to have nothing to do with the incoming packet
1451 r->headers_out = apr_table_make(r->pool,1);
1452 r->status = HTTP_BAD_GATEWAY;
1453 r->status_line = "bad gateway";
1457 /* Now, add in the just read cookies */
1458 apr_table_do(addit_dammit, save_table, r->headers_out,
1459 "Set-Cookie", NULL);
1461 /* and now load 'em all in */
1462 if (!apr_is_empty_table(save_table)) {
1463 apr_table_unset(r->headers_out, "Set-Cookie");
1464 r->headers_out = apr_table_overlay(r->pool,
1469 /* can't have both Content-Length and Transfer-Encoding */
1470 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1471 && apr_table_get(r->headers_out, "Content-Length")) {
1473 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1474 * and Content-Length are received, the latter MUST be
1477 * To help mitigate HTTP Splitting, unset Content-Length
1478 * and shut down the backend server connection
1479 * XXX: We aught to treat such a response as uncachable
1481 apr_table_unset(r->headers_out, "Content-Length");
1482 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01107)
1483 "server %s:%d returned Transfer-Encoding"
1484 " and Content-Length",
1485 backend->hostname, backend->port);
1490 * Save a possible Transfer-Encoding header as we need it later for
1491 * ap_http_filter to know where to end.
1493 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1494 /* strip connection listed hop-by-hop headers from response */
1495 if (ap_find_token(p, apr_table_get(r->headers_out, "Connection"),
1498 ap_proxy_clear_connection(p, r->headers_out);
1499 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1500 ap_set_content_type(r, apr_pstrdup(p, buf));
1502 if (!ap_is_HTTP_INFO(proxy_status)) {
1503 ap_proxy_pre_http_request(origin, backend->r);
1506 /* Clear hop-by-hop headers */
1507 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1508 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1510 /* Delete warnings with wrong date */
1511 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1513 /* handle Via header in response */
1514 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1515 const char *server_name = ap_get_server_name(r);
1516 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1517 * then the server name returned by ap_get_server_name() is the
1518 * origin server name (which does make too much sense with Via: headers)
1519 * so we use the proxy vhost's name instead.
1521 if (server_name == r->hostname)
1522 server_name = r->server->server_hostname;
1523 /* create a "Via:" response header entry and merge it */
1524 apr_table_addn(r->headers_out, "Via",
1525 (conf->viaopt == via_full)
1526 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1527 HTTP_VERSION_MAJOR(r->proto_num),
1528 HTTP_VERSION_MINOR(r->proto_num),
1531 AP_SERVER_BASEVERSION)
1532 : apr_psprintf(p, "%d.%d %s%s",
1533 HTTP_VERSION_MAJOR(r->proto_num),
1534 HTTP_VERSION_MINOR(r->proto_num),
1540 /* cancel keepalive if HTTP/1.0 or less */
1541 if ((major < 1) || (minor < 1)) {
1543 origin->keepalive = AP_CONN_CLOSE;
1546 /* an http/0.9 response */
1549 r->status_line = "200 OK";
1553 if (ap_is_HTTP_INFO(proxy_status)) {
1555 /* Reset to old timeout iff we've adjusted it */
1557 && (r->status == HTTP_CONTINUE)
1558 && (worker->s->ping_timeout != old_timeout)) {
1559 apr_socket_timeout_set(backend->sock, old_timeout);
1563 interim_response = 0;
1565 if (interim_response) {
1566 /* RFC2616 tells us to forward this.
1568 * OTOH, an interim response here may mean the backend
1569 * is playing sillybuggers. The Client didn't ask for
1570 * it within the defined HTTP/1.1 mechanisms, and if
1571 * it's an extension, it may also be unsupported by us.
1573 * There's also the possibility that changing existing
1574 * behaviour here might break something.
1576 * So let's make it configurable.
1578 const char *policy = apr_table_get(r->subprocess_env,
1579 "proxy-interim-response");
1580 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1581 "HTTP: received interim %d response", r->status);
1582 if (!policy || !strcasecmp(policy, "RFC")) {
1583 ap_send_interim_response(r, 1);
1585 /* FIXME: refine this to be able to specify per-response-status
1586 * policies and maybe also add option to bail out with 502
1588 else if (strcasecmp(policy, "Suppress")) {
1589 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01108)
1590 "undefined proxy interim response policy");
1593 /* Moved the fixups of Date headers and those affected by
1594 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1597 if ((proxy_status == 401) && (dconf->error_override)) {
1599 const char *wa = "WWW-Authenticate";
1600 if ((buf = apr_table_get(r->headers_out, wa))) {
1601 apr_table_set(r->err_headers_out, wa, buf);
1603 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01109)
1604 "origin server sent 401 without "
1605 "WWW-Authenticate header");
1611 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1612 * the response? If so, load the extra data. These are 2 mutually
1613 * exclusive possibilities, that just happen to require very
1616 if (backasswards || pread_len) {
1617 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1620 * At this point in response processing of a 0.9 response,
1621 * we don't know yet whether data is binary or not.
1622 * mod_charset_lite will get control later on, so it cannot
1623 * decide on the conversion of this buffer full of data.
1624 * However, chances are that we are not really talking to an
1625 * HTTP/0.9 server, but to some different protocol, therefore
1626 * the best guess IMHO is to always treat the buffer as "text/x":
1628 ap_xlate_proto_to_ascii(buffer, len);
1629 cntr = (apr_ssize_t)len;
1631 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1632 APR_BRIGADE_INSERT_TAIL(bb, e);
1634 /* PR 41646: get HEAD right with ProxyErrorOverride */
1635 if (ap_is_HTTP_ERROR(r->status) && dconf->error_override) {
1636 /* clear r->status for override error, otherwise ErrorDocument
1637 * thinks that this is a recursive error, and doesn't find the
1640 r->status = HTTP_OK;
1641 /* Discard body, if one is expected */
1642 if (!r->header_only && /* not HEAD request */
1643 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1644 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1645 ap_discard_request_body(backend->r);
1647 return proxy_status;
1650 /* send body - but only if a body is expected */
1651 if ((!r->header_only) && /* not HEAD request */
1652 !interim_response && /* not any 1xx response */
1653 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1654 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1656 /* We need to copy the output headers and treat them as input
1657 * headers as well. BUT, we need to do this before we remove
1658 * TE, so that they are preserved accordingly for
1659 * ap_http_filter to know where to end.
1661 backend->r->headers_in = apr_table_clone(backend->r->pool, r->headers_out);
1663 * Restore Transfer-Encoding header from response if we saved
1664 * one before and there is none left. We need it for the
1665 * ap_http_filter. See above.
1667 if (te && !apr_table_get(backend->r->headers_in, "Transfer-Encoding")) {
1668 apr_table_add(backend->r->headers_in, "Transfer-Encoding", te);
1671 apr_table_unset(r->headers_out,"Transfer-Encoding");
1673 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, 0, r, "start body send");
1676 * if we are overriding the errors, we can't put the content
1677 * of the page into the brigade
1679 if (!dconf->error_override || !ap_is_HTTP_ERROR(proxy_status)) {
1680 /* read the body, pass it to the output filters */
1681 apr_read_type_e mode = APR_NONBLOCK_READ;
1684 /* Handle the case where the error document is itself reverse
1685 * proxied and was successful. We must maintain any previous
1686 * error status so that an underlying error (eg HTTP_NOT_FOUND)
1687 * doesn't become an HTTP_OK.
1689 if (dconf->error_override && !ap_is_HTTP_ERROR(proxy_status)
1690 && ap_is_HTTP_ERROR(original_status)) {
1691 r->status = original_status;
1692 r->status_line = original_status_line;
1696 apr_off_t readbytes;
1699 rv = ap_get_brigade(backend->r->input_filters, bb,
1700 AP_MODE_READBYTES, mode,
1701 conf->io_buffer_size);
1703 /* ap_get_brigade will return success with an empty brigade
1704 * for a non-blocking read which would block: */
1705 if (mode == APR_NONBLOCK_READ
1706 && (APR_STATUS_IS_EAGAIN(rv)
1707 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb)))) {
1708 /* flush to the client and switch to blocking mode */
1709 e = apr_bucket_flush_create(c->bucket_alloc);
1710 APR_BRIGADE_INSERT_TAIL(bb, e);
1711 if (ap_pass_brigade(r->output_filters, bb)
1716 apr_brigade_cleanup(bb);
1717 mode = APR_BLOCK_READ;
1720 else if (rv == APR_EOF) {
1723 else if (rv != APR_SUCCESS) {
1724 /* In this case, we are in real trouble because
1725 * our backend bailed on us. Pass along a 502 error
1728 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01110)
1729 "error reading response");
1730 ap_proxy_backend_broke(r, bb);
1731 ap_pass_brigade(r->output_filters, bb);
1736 /* next time try a non-blocking read */
1737 mode = APR_NONBLOCK_READ;
1739 apr_brigade_length(bb, 0, &readbytes);
1740 backend->worker->s->read += readbytes;
1743 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01111)
1744 "readbytes: %#x", readbytes);
1748 if (APR_BRIGADE_EMPTY(bb)) {
1749 apr_brigade_cleanup(bb);
1753 /* Switch the allocator lifetime of the buckets */
1754 proxy_buckets_lifetime_transform(r, bb, pass_bb);
1756 /* found the last brigade? */
1757 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(pass_bb))) {
1759 /* signal that we must leave */
1762 /* the brigade may contain transient buckets that contain
1763 * data that lives only as long as the backend connection.
1764 * Force a setaside so these transient buckets become heap
1765 * buckets that live as long as the request.
1767 for (e = APR_BRIGADE_FIRST(pass_bb); e
1768 != APR_BRIGADE_SENTINEL(pass_bb); e
1769 = APR_BUCKET_NEXT(e)) {
1770 apr_bucket_setaside(e, r->pool);
1773 /* finally it is safe to clean up the brigade from the
1774 * connection pool, as we have forced a setaside on all
1777 apr_brigade_cleanup(bb);
1779 /* make sure we release the backend connection as soon
1780 * as we know we are done, so that the backend isn't
1781 * left waiting for a slow client to eventually
1782 * acknowledge the data.
1784 ap_proxy_release_connection(backend->worker->s->scheme,
1785 backend, r->server);
1786 /* Ensure that the backend is not reused */
1787 *backend_ptr = NULL;
1791 /* try send what we read */
1792 if (ap_pass_brigade(r->output_filters, pass_bb) != APR_SUCCESS
1794 /* Ack! Phbtt! Die! User aborted! */
1795 /* Only close backend if we haven't got all from the
1796 * backend. Furthermore if *backend_ptr is NULL it is no
1797 * longer safe to fiddle around with backend as it might
1798 * be already in use by another thread.
1801 backend->close = 1; /* this causes socket close below */
1806 /* make sure we always clean up after ourselves */
1807 apr_brigade_cleanup(pass_bb);
1808 apr_brigade_cleanup(bb);
1812 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "end body send");
1814 else if (!interim_response) {
1815 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r, "header only");
1817 /* make sure we release the backend connection as soon
1818 * as we know we are done, so that the backend isn't
1819 * left waiting for a slow client to eventually
1820 * acknowledge the data.
1822 ap_proxy_release_connection(backend->worker->s->scheme,
1823 backend, r->server);
1824 *backend_ptr = NULL;
1826 /* Pass EOS bucket down the filter chain. */
1827 e = apr_bucket_eos_create(c->bucket_alloc);
1828 APR_BRIGADE_INSERT_TAIL(bb, e);
1829 ap_pass_brigade(r->output_filters, bb);
1831 apr_brigade_cleanup(bb);
1833 } while (interim_response && (interim_response < AP_MAX_INTERIM_RESPONSES));
1835 /* See define of AP_MAX_INTERIM_RESPONSES for why */
1836 if (interim_response >= AP_MAX_INTERIM_RESPONSES) {
1837 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1839 "Too many (%d) interim responses from origin server",
1843 /* If our connection with the client is to be aborted, return DONE. */
1844 if (c->aborted || backend_broke) {
1852 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1853 proxy_conn_rec *backend)
1855 ap_proxy_release_connection(scheme, backend, r->server);
1860 * This handles http:// URLs, and other URLs using a remote proxy over http
1861 * If proxyhost is NULL, then contact the server directly, otherwise
1863 * Note that if a proxy is used, then URLs other than http: can be accessed,
1864 * also, if we have trouble which is clearly specific to the proxy, then
1865 * we return DECLINED so that we can try another proxy. (Or the direct
1868 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1869 proxy_server_conf *conf,
1870 char *url, const char *proxyname,
1871 apr_port_t proxyport)
1874 char server_portstr[32];
1876 const char *proxy_function;
1878 proxy_conn_rec *backend = NULL;
1880 conn_rec *c = r->connection;
1883 * Use a shorter-lived pool to reduce memory usage
1884 * and avoid a memory leak
1886 apr_pool_t *p = r->pool;
1887 apr_uri_t *uri = apr_palloc(p, sizeof(*uri));
1889 /* find the scheme */
1890 u = strchr(url, ':');
1891 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1894 return HTTP_BAD_REQUEST;
1895 scheme = apr_pstrndup(p, url, u - url);
1896 /* scheme is lowercase */
1897 ap_str_tolower(scheme);
1899 if (strcmp(scheme, "https") == 0) {
1900 if (!ap_proxy_ssl_enable(NULL)) {
1901 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01112)
1902 "HTTPS: declining URL %s (mod_ssl not configured?)",
1907 proxy_function = "HTTPS";
1909 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1910 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01113) "HTTP: declining URL %s",
1912 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1916 proxy_function = "HTTP";
1918 proxy_function = "FTP";
1920 ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "HTTP: serving URL %s", url);
1923 /* create space for state information */
1924 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1925 worker, r->server)) != OK)
1929 backend->is_ssl = is_ssl;
1932 ap_proxy_ssl_connection_cleanup(backend, r);
1936 * In the case that we are handling a reverse proxy connection and this
1937 * is not a request that is coming over an already kept alive connection
1938 * with the client, do NOT reuse the connection to the backend, because
1939 * we cannot forward a failure to the client in this case as the client
1940 * does NOT expect this in this situation.
1941 * Yes, this creates a performance penalty.
1943 if ((r->proxyreq == PROXYREQ_REVERSE) && (!c->keepalives)
1944 && (apr_table_get(r->subprocess_env, "proxy-initial-not-pooled"))) {
1951 /* Step One: Determine Who To Connect To */
1952 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1953 uri, &locurl, proxyname,
1954 proxyport, server_portstr,
1955 sizeof(server_portstr))) != OK)
1958 /* Step Two: Make the Connection */
1959 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1960 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01114)
1961 "HTTP: failed to make connection to backend: %s",
1963 status = HTTP_SERVICE_UNAVAILABLE;
1967 /* Step Three: Create conn_rec */
1968 if (!backend->connection) {
1969 if ((status = ap_proxy_connection_create(proxy_function, backend,
1970 c, r->server)) != OK)
1973 * On SSL connections set a note on the connection what CN is
1974 * requested, such that mod_ssl can check if it is requested to do
1978 proxy_dir_conf *dconf;
1979 const char *ssl_hostname;
1982 * In the case of ProxyPreserveHost on use the hostname of
1983 * the request if present otherwise use the one from the
1984 * backend request URI.
1986 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1987 if ((dconf->preserve_host != 0) && (r->hostname != NULL)) {
1988 ssl_hostname = r->hostname;
1991 ssl_hostname = uri->hostname;
1994 apr_table_set(backend->connection->notes, "proxy-request-hostname",
1999 /* Step Four: Send the Request
2000 * On the off-chance that we forced a 100-Continue as a
2001 * kinda HTTP ping test, allow for retries
2003 if ((status = ap_proxy_http_request(p, r, backend, worker,
2004 conf, uri, locurl, server_portstr)) != OK) {
2005 if ((status == HTTP_SERVICE_UNAVAILABLE) && worker->s->ping_timeout_set) {
2007 ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r, APLOGNO(01115)
2008 "HTTP: 100-Continue failed to %pI (%s)",
2009 worker->cp->addr, worker->s->hostname);
2018 /* Step Five: Receive the Response... Fall thru to cleanup */
2019 status = ap_proxy_http_process_response(p, r, &backend, worker,
2020 conf, server_portstr);
2025 /* Step Six: Clean Up */
2030 ap_proxy_http_cleanup(proxy_function, r, backend);
2034 static void ap_proxy_http_register_hook(apr_pool_t *p)
2036 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
2037 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
2038 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
2041 AP_DECLARE_MODULE(proxy_http) = {
2042 STANDARD20_MODULE_STUFF,
2043 NULL, /* create per-directory config structure */
2044 NULL, /* merge per-directory config structures */
2045 NULL, /* create per-server config structure */
2046 NULL, /* merge per-server config structures */
2047 NULL, /* command apr_table_t */
2048 ap_proxy_http_register_hook/* register hooks */