1 #ifdef MOP_HERE_ONLY_FOR_EXAMPLE
2 /* Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 /* 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;
46 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
47 sprintf(mop_bf, "proxy_http_canon: start\n");
48 write(mop_fd, mop_bf, strlen(mop_bf));
52 /* ap_port_of_scheme() */
53 if (strncasecmp(url, "http:", 5) == 0) {
57 else if (strncasecmp(url, "https:", 6) == 0) {
64 def_port = apr_uri_port_of_scheme(scheme);
66 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
67 "proxy: HTTP: canonicalising URL %s", url);
70 * We break the URL into host, port, path, search
73 err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
75 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
76 "error parsing URL %s: %s",
78 return HTTP_BAD_REQUEST;
82 * now parse path/search args, according to rfc1738:
85 * In a reverse proxy, our URL has been processed, so canonicalise
86 * unless proxy-nocanon is set to say it's raw
87 * In a forward proxy, we have and MUST NOT MANGLE the original.
89 switch (r->proxyreq) {
90 default: /* wtf are we doing here? */
91 case PROXYREQ_REVERSE:
92 if (apr_table_get(r->notes, "proxy-nocanon")) {
93 path = url; /* this is the raw path */
96 path = ap_proxy_canonenc(r->pool, url, strlen(url),
97 enc_path, 0, r->proxyreq);
107 return HTTP_BAD_REQUEST;
109 if (port != def_port)
110 apr_snprintf(sport, sizeof(sport), ":%d", port);
114 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
115 host = apr_pstrcat(r->pool, "[", host, "]", NULL);
117 r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
118 "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
122 /* Clear all connection-based headers from the incoming headers table */
123 typedef struct header_dptr {
128 static ap_regex_t *warn_rx;
129 static int clean_warning_headers(void *data, const char *key, const char *val)
131 apr_table_t *headers = ((header_dptr*)data)->table;
132 apr_pool_t *pool = ((header_dptr*)data)->pool;
135 apr_time_t warn_time;
136 const int nmatch = 3;
137 ap_regmatch_t pmatch[3];
139 if (headers == NULL) {
140 ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
143 * Parse this, suckers!
145 * Warning = "Warning" ":" 1#warning-value
147 * warning-value = warn-code SP warn-agent SP warn-text
151 * warn-agent = ( host [ ":" port ] ) | pseudonym
152 * ; the name or pseudonym of the server adding
153 * ; the Warning header, for use in debugging
154 * warn-text = quoted-string
155 * warn-date = <"> HTTP-date <">
157 * Buggrit, use a bloomin' regexp!
158 * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?) --> whole in $1, date in $3
160 while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
161 warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
162 pmatch[0].rm_eo - pmatch[0].rm_so);
164 if (pmatch[2].rm_eo > pmatch[2].rm_so) {
165 /* OK, we have a date here */
166 date = apr_pstrndup(pool, val+pmatch[2].rm_so,
167 pmatch[2].rm_eo - pmatch[2].rm_so);
168 warn_time = apr_date_parse_http(date);
170 if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
171 apr_table_addn(headers, key, warning);
173 val += pmatch[0].rm_eo;
177 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
182 x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
183 apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
184 if (x.table != NULL) {
185 apr_table_unset(headers, "Warning");
186 return apr_table_overlay(p, headers, x.table);
192 static int clear_conn_headers(void *data, const char *key, const char *val)
194 apr_table_t *headers = ((header_dptr*)data)->table;
195 apr_pool_t *pool = ((header_dptr*)data)->pool;
197 char *next = apr_pstrdup(pool, val);
200 while (*next && !apr_isspace(*next) && (*next != ',')) {
203 while (*next && (apr_isspace(*next) || (*next == ','))) {
206 apr_table_unset(headers, name);
210 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
215 apr_table_unset(headers, "Proxy-Connection");
216 apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
217 apr_table_unset(headers, "Connection");
219 static void add_te_chunked(apr_pool_t *p,
220 apr_bucket_alloc_t *bucket_alloc,
221 apr_bucket_brigade *header_brigade)
225 const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
227 buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
228 ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
230 e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
231 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
234 static void add_cl(apr_pool_t *p,
235 apr_bucket_alloc_t *bucket_alloc,
236 apr_bucket_brigade *header_brigade,
242 buf = apr_pstrcat(p, "Content-Length: ",
246 ap_xlate_proto_to_ascii(buf, strlen(buf));
247 e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
248 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
251 #define ASCII_CRLF "\015\012"
252 #define ASCII_ZERO "\060"
254 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
255 apr_bucket_brigade *header_brigade)
259 /* add empty line at the end of the headers */
260 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
261 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
264 static int pass_brigade(apr_bucket_alloc_t *bucket_alloc,
265 request_rec *r, proxy_conn_rec *conn,
266 conn_rec *origin, apr_bucket_brigade *bb,
270 apr_off_t transferred;
273 apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
274 APR_BRIGADE_INSERT_TAIL(bb, e);
276 apr_brigade_length(bb, 0, &transferred);
277 if (transferred != -1)
278 conn->worker->s->transferred += transferred;
279 status = ap_pass_brigade(origin->output_filters, bb);
280 if (status != APR_SUCCESS) {
281 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
282 "proxy: pass request body failed to %pI (%s)",
283 conn->addr, conn->hostname);
284 if (origin->aborted) {
285 return APR_STATUS_IS_TIMEUP(status) ? HTTP_GATEWAY_TIME_OUT : HTTP_BAD_GATEWAY;
288 return HTTP_BAD_REQUEST;
291 apr_brigade_cleanup(bb);
295 #define MAX_MEM_SPOOL 16384
297 static int stream_reqbody_chunked(apr_pool_t *p,
299 proxy_conn_rec *p_conn,
301 apr_bucket_brigade *header_brigade,
302 apr_bucket_brigade *input_brigade)
304 int seen_eos = 0, rv = OK;
308 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
309 apr_bucket_brigade *bb;
312 add_te_chunked(p, bucket_alloc, header_brigade);
313 terminate_headers(bucket_alloc, header_brigade);
315 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
317 char chunk_hdr[20]; /* must be here due to transient bucket. */
319 /* If this brigade contains EOS, either stop or remove it. */
320 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
323 /* We can't pass this EOS to the output_filters. */
324 e = APR_BRIGADE_LAST(input_brigade);
325 apr_bucket_delete(e);
328 apr_brigade_length(input_brigade, 1, &bytes);
330 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
331 "%" APR_UINT64_T_HEX_FMT CRLF,
332 (apr_uint64_t)bytes);
334 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
335 e = apr_bucket_transient_create(chunk_hdr, hdr_len,
337 APR_BRIGADE_INSERT_HEAD(input_brigade, e);
340 * Append the end-of-chunk CRLF
342 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
343 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
345 if (header_brigade) {
346 /* we never sent the header brigade, so go ahead and
347 * take care of that now
352 * Save input_brigade in bb brigade. (At least) in the SSL case
353 * input_brigade contains transient buckets whose data would get
354 * overwritten during the next call of ap_get_brigade in the loop.
355 * ap_save_brigade ensures these buckets to be set aside.
356 * Calling ap_save_brigade with NULL as filter is OK, because
357 * bb brigade already has been created and does not need to get
358 * created by ap_save_brigade.
360 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
361 if (status != APR_SUCCESS) {
362 return HTTP_INTERNAL_SERVER_ERROR;
365 header_brigade = NULL;
371 /* The request is flushed below this loop with chunk EOS header */
372 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
381 status = ap_get_brigade(r->input_filters, input_brigade,
382 AP_MODE_READBYTES, APR_BLOCK_READ,
385 if (status != APR_SUCCESS) {
386 return HTTP_BAD_REQUEST;
390 if (header_brigade) {
391 /* we never sent the header brigade because there was no request body;
397 if (!APR_BRIGADE_EMPTY(input_brigade)) {
398 /* input brigade still has an EOS which we can't pass to the output_filters. */
399 e = APR_BRIGADE_LAST(input_brigade);
400 AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
401 apr_bucket_delete(e);
406 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
410 APR_BRIGADE_INSERT_TAIL(bb, e);
412 /* Now we have headers-only, or the chunk EOS mark; flush it */
413 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
417 static int stream_reqbody_cl(apr_pool_t *p,
419 proxy_conn_rec *p_conn,
421 apr_bucket_brigade *header_brigade,
422 apr_bucket_brigade *input_brigade,
423 const char *old_cl_val)
425 int seen_eos = 0, rv = 0;
426 apr_status_t status = APR_SUCCESS;
427 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
428 apr_bucket_brigade *bb;
430 apr_off_t cl_val = 0;
432 apr_off_t bytes_streamed = 0;
437 add_cl(p, bucket_alloc, header_brigade, old_cl_val);
438 status = apr_strtoff(&cl_val, old_cl_val, &endstr, 10);
440 if (status || *endstr || endstr == old_cl_val || cl_val < 0) {
441 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
442 "proxy: could not parse request Content-Length (%s)",
444 return HTTP_BAD_REQUEST;
447 terminate_headers(bucket_alloc, header_brigade);
449 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
451 apr_brigade_length(input_brigade, 1, &bytes);
452 bytes_streamed += bytes;
454 /* If this brigade contains EOS, either stop or remove it. */
455 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
458 /* We can't pass this EOS to the output_filters. */
459 e = APR_BRIGADE_LAST(input_brigade);
460 apr_bucket_delete(e);
463 /* C-L < bytes streamed?!?
464 * We will error out after the body is completely
465 * consumed, but we can't stream more bytes at the
466 * back end since they would in part be interpreted
467 * as another request! If nothing is sent, then
470 * Prevents HTTP Response Splitting.
472 if (bytes_streamed > cl_val) {
473 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
474 "proxy: read more bytes of request body than expected "
475 "(got %" APR_OFF_T_FMT ", expected %" APR_OFF_T_FMT ")",
476 bytes_streamed, cl_val);
477 return HTTP_INTERNAL_SERVER_ERROR;
480 if (header_brigade) {
481 /* we never sent the header brigade, so go ahead and
482 * take care of that now
487 * Save input_brigade in bb brigade. (At least) in the SSL case
488 * input_brigade contains transient buckets whose data would get
489 * overwritten during the next call of ap_get_brigade in the loop.
490 * ap_save_brigade ensures these buckets to be set aside.
491 * Calling ap_save_brigade with NULL as filter is OK, because
492 * bb brigade already has been created and does not need to get
493 * created by ap_save_brigade.
495 status = ap_save_brigade(NULL, &bb, &input_brigade, p);
496 if (status != APR_SUCCESS) {
497 return HTTP_INTERNAL_SERVER_ERROR;
500 header_brigade = NULL;
506 /* Once we hit EOS, we are ready to flush. */
507 rv = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
516 status = ap_get_brigade(r->input_filters, input_brigade,
517 AP_MODE_READBYTES, APR_BLOCK_READ,
520 if (status != APR_SUCCESS) {
521 return HTTP_BAD_REQUEST;
525 if (bytes_streamed != cl_val) {
526 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
527 "proxy: client %s given Content-Length did not match"
528 " number of body bytes read", r->connection->remote_ip);
529 return HTTP_BAD_REQUEST;
532 if (header_brigade) {
533 /* we never sent the header brigade since there was no request
534 * body; send it now with the flush flag
537 return(pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1));
543 static int spool_reqbody_cl(apr_pool_t *p,
545 proxy_conn_rec *p_conn,
547 apr_bucket_brigade *header_brigade,
548 apr_bucket_brigade *input_brigade,
553 apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
554 apr_bucket_brigade *body_brigade;
556 apr_off_t bytes, bytes_spooled = 0, fsize = 0;
557 apr_file_t *tmpfile = NULL;
559 body_brigade = apr_brigade_create(p, bucket_alloc);
561 while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
563 /* If this brigade contains EOS, either stop or remove it. */
564 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
567 /* We can't pass this EOS to the output_filters. */
568 e = APR_BRIGADE_LAST(input_brigade);
569 apr_bucket_delete(e);
572 apr_brigade_length(input_brigade, 1, &bytes);
574 if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
575 /* can't spool any more in memory; write latest brigade to disk */
576 if (tmpfile == NULL) {
577 const char *temp_dir;
580 status = apr_temp_dir_get(&temp_dir, p);
581 if (status != APR_SUCCESS) {
582 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
583 "proxy: search for temporary directory failed");
584 return HTTP_INTERNAL_SERVER_ERROR;
586 apr_filepath_merge(&template, temp_dir,
587 "modproxy.tmp.XXXXXX",
588 APR_FILEPATH_NATIVE, p);
589 status = apr_file_mktemp(&tmpfile, template, 0, p);
590 if (status != APR_SUCCESS) {
591 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
592 "proxy: creation of temporary file in directory %s failed",
594 return HTTP_INTERNAL_SERVER_ERROR;
597 for (e = APR_BRIGADE_FIRST(input_brigade);
598 e != APR_BRIGADE_SENTINEL(input_brigade);
599 e = APR_BUCKET_NEXT(e)) {
601 apr_size_t bytes_read, bytes_written;
603 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
604 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
605 if (status != APR_SUCCESS) {
606 const char *tmpfile_name;
608 if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
609 tmpfile_name = "(unknown)";
611 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
612 "proxy: write to temporary file %s failed",
614 return HTTP_INTERNAL_SERVER_ERROR;
616 AP_DEBUG_ASSERT(bytes_read == bytes_written);
617 fsize += bytes_written;
619 apr_brigade_cleanup(input_brigade);
624 * Save input_brigade in body_brigade. (At least) in the SSL case
625 * input_brigade contains transient buckets whose data would get
626 * overwritten during the next call of ap_get_brigade in the loop.
627 * ap_save_brigade ensures these buckets to be set aside.
628 * Calling ap_save_brigade with NULL as filter is OK, because
629 * body_brigade already has been created and does not need to get
630 * created by ap_save_brigade.
632 status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
633 if (status != APR_SUCCESS) {
634 return HTTP_INTERNAL_SERVER_ERROR;
639 bytes_spooled += bytes;
645 status = ap_get_brigade(r->input_filters, input_brigade,
646 AP_MODE_READBYTES, APR_BLOCK_READ,
649 if (status != APR_SUCCESS) {
650 return HTTP_BAD_REQUEST;
654 if (bytes_spooled || force_cl) {
655 add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
657 terminate_headers(bucket_alloc, header_brigade);
658 APR_BRIGADE_CONCAT(header_brigade, body_brigade);
660 /* For platforms where the size of the file may be larger than
661 * that which can be stored in a single bucket (where the
662 * length field is an apr_size_t), split it into several
664 if (sizeof(apr_off_t) > sizeof(apr_size_t)
665 && fsize > AP_MAX_SENDFILE) {
666 e = apr_bucket_file_create(tmpfile, 0, AP_MAX_SENDFILE, p,
668 while (fsize > AP_MAX_SENDFILE) {
670 apr_bucket_copy(e, &ce);
671 APR_BRIGADE_INSERT_TAIL(header_brigade, ce);
672 e->start += AP_MAX_SENDFILE;
673 fsize -= AP_MAX_SENDFILE;
675 e->length = (apr_size_t)fsize; /* Resize just the last bucket */
678 e = apr_bucket_file_create(tmpfile, 0, (apr_size_t)fsize, p,
681 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
683 /* This is all a single brigade, pass with flush flagged */
684 return(pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1));
688 int ap_proxy_http_request(apr_pool_t *p, request_rec *r,
689 proxy_conn_rec *p_conn, conn_rec *origin,
690 proxy_server_conf *conf,
692 char *url, char *server_portstr)
694 conn_rec *c = r->connection;
695 apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
696 apr_bucket_brigade *header_brigade;
697 apr_bucket_brigade *input_brigade;
698 apr_bucket_brigade *temp_brigade;
701 const apr_array_header_t *headers_in_array;
702 const apr_table_entry_t *headers_in;
705 enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
706 enum rb_methods rb_method = RB_INIT;
707 const char *old_cl_val = NULL;
708 const char *old_te_val = NULL;
709 apr_off_t bytes_read = 0;
712 apr_table_t *headers_in_copy;
714 header_brigade = apr_brigade_create(p, origin->bucket_alloc);
717 * Send the HTTP/1.1 request to the remote server
720 if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
721 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
724 * According to RFC 2616 8.2.3 we are not allowed to forward an
725 * Expect: 100-continue to an HTTP/1.0 server. Instead we MUST return
726 * a HTTP_EXPECTATION_FAILED
728 if (r->expecting_100) {
729 return HTTP_EXPECTATION_FAILED;
733 buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
736 if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
737 origin->keepalive = AP_CONN_CLOSE;
740 ap_xlate_proto_to_ascii(buf, strlen(buf));
741 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
742 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
743 if (conf->preserve_host == 0) {
744 if (ap_strchr_c(uri->hostname, ':')) { /* if literal IPv6 address */
745 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
746 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]:",
747 uri->port_str, CRLF, NULL);
749 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]", CRLF, NULL);
752 if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
753 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":",
754 uri->port_str, CRLF, NULL);
756 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
761 /* don't want to use r->hostname, as the incoming header might have a
764 const char* hostname = apr_table_get(r->headers_in,"Host");
766 hostname = r->server->server_hostname;
767 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
768 "proxy: no HTTP 0.9 request (with no host line) "
769 "on incoming request and preserve host set "
770 "forcing hostname to be %s for uri %s",
774 buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
776 ap_xlate_proto_to_ascii(buf, strlen(buf));
777 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
778 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
781 if (conf->viaopt == via_block) {
782 /* Block all outgoing Via: headers */
783 apr_table_unset(r->headers_in, "Via");
784 } else if (conf->viaopt != via_off) {
785 const char *server_name = ap_get_server_name(r);
786 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
787 * then the server name returned by ap_get_server_name() is the
788 * origin server name (which does make too much sense with Via: headers)
789 * so we use the proxy vhost's name instead.
791 if (server_name == r->hostname)
792 server_name = r->server->server_hostname;
793 /* Create a "Via:" request header entry and merge it */
794 /* Generate outgoing Via: header with/without server comment: */
795 apr_table_mergen(r->headers_in, "Via",
796 (conf->viaopt == via_full)
797 ? apr_psprintf(p, "%d.%d %s%s (%s)",
798 HTTP_VERSION_MAJOR(r->proto_num),
799 HTTP_VERSION_MINOR(r->proto_num),
800 server_name, server_portstr,
801 AP_SERVER_BASEVERSION)
802 : apr_psprintf(p, "%d.%d %s%s",
803 HTTP_VERSION_MAJOR(r->proto_num),
804 HTTP_VERSION_MINOR(r->proto_num),
805 server_name, server_portstr)
809 /* X-Forwarded-*: handling
814 * These request headers are only really useful when the mod_proxy
815 * is used in a reverse proxy configuration, so that useful info
816 * about the client can be passed through the reverse proxy and on
817 * to the backend server, which may require the information to
820 * In a forward proxy situation, these options are a potential
821 * privacy violation, as information about clients behind the proxy
822 * are revealed to arbitrary servers out there on the internet.
824 * The HTTP/1.1 Via: header is designed for passing client
825 * information through proxies to a server, and should be used in
826 * a forward proxy configuation instead of X-Forwarded-*. See the
827 * ProxyVia option for details.
830 if (PROXYREQ_REVERSE == r->proxyreq) {
833 /* Add X-Forwarded-For: so that the upstream has a chance to
834 * determine, where the original request came from.
836 apr_table_mergen(r->headers_in, "X-Forwarded-For",
839 /* Add X-Forwarded-Host: so that upstream knows what the
840 * original request hostname was.
842 if ((buf = apr_table_get(r->headers_in, "Host"))) {
843 apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
846 /* Add X-Forwarded-Server: so that upstream knows what the
847 * name of this proxy server is (if there are more than one)
848 * XXX: This duplicates Via: - do we strictly need it?
850 apr_table_mergen(r->headers_in, "X-Forwarded-Server",
851 r->server->server_hostname);
856 * Make a copy of the headers_in table before clearing the connection
857 * headers as we need the connection headers later in the http output
858 * filter to prepare the correct response headers.
860 * Note: We need to take r->pool for apr_table_copy as the key / value
861 * pairs in r->headers_in have been created out of r->pool and
862 * p might be (and actually is) a longer living pool.
863 * This would trigger the bad pool ancestry abort in apr_table_copy if
864 * apr is compiled with APR_POOL_DEBUG.
866 headers_in_copy = apr_table_copy(r->pool, r->headers_in);
867 ap_proxy_clear_connection(p, headers_in_copy);
868 /* send request headers */
869 headers_in_array = apr_table_elts(headers_in_copy);
870 headers_in = (const apr_table_entry_t *) headers_in_array->elts;
871 for (counter = 0; counter < headers_in_array->nelts; counter++) {
872 if (headers_in[counter].key == NULL
873 || headers_in[counter].val == NULL
876 || !strcasecmp(headers_in[counter].key, "Host")
878 /* Clear out hop-by-hop request headers not to send
879 * RFC2616 13.5.1 says we should strip these headers
881 || !strcasecmp(headers_in[counter].key, "Keep-Alive")
882 || !strcasecmp(headers_in[counter].key, "TE")
883 || !strcasecmp(headers_in[counter].key, "Trailer")
884 || !strcasecmp(headers_in[counter].key, "Upgrade")
889 /* Do we want to strip Proxy-Authorization ?
890 * If we haven't used it, then NO
891 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
892 * So let's make it configurable by env.
894 if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
895 if (r->user != NULL) { /* we've authenticated */
896 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
902 /* Skip Transfer-Encoding and Content-Length for now.
904 if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
905 old_te_val = headers_in[counter].val;
908 if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
909 old_cl_val = headers_in[counter].val;
913 /* for sub-requests, ignore freshness/expiry headers */
915 if ( !strcasecmp(headers_in[counter].key, "If-Match")
916 || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
917 || !strcasecmp(headers_in[counter].key, "If-Range")
918 || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
919 || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
924 buf = apr_pstrcat(p, headers_in[counter].key, ": ",
925 headers_in[counter].val, CRLF,
927 ap_xlate_proto_to_ascii(buf, strlen(buf));
928 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
929 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
932 /* We have headers, let's figure out our request body... */
933 input_brigade = apr_brigade_create(p, bucket_alloc);
935 /* sub-requests never use keepalives, and mustn't pass request bodies.
936 * Because the new logic looks at input_brigade, we will self-terminate
937 * input_brigade and jump past all of the request body logic...
938 * Reading anything with ap_get_brigade is likely to consume the
939 * main request's body or read beyond EOS - which would be unplesant.
942 /* XXX: Why DON'T sub-requests use keepalives? */
946 apr_table_unset(r->headers_in, "Content-Length");
950 apr_table_unset(r->headers_in, "Transfer-Encoding");
952 rb_method = RB_STREAM_CL;
953 e = apr_bucket_eos_create(input_brigade->bucket_alloc);
954 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
958 /* WE only understand chunked. Other modules might inject
959 * (and therefore, decode) other flavors but we don't know
960 * that the can and have done so unless they they remove
961 * their decoding from the headers_in T-E list.
962 * XXX: Make this extensible, but in doing so, presume the
963 * encoding has been done by the extensions' handler, and
964 * do not modify add_te_chunked's logic
966 if (old_te_val && strcasecmp(old_te_val, "chunked") != 0) {
967 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
968 "proxy: %s Transfer-Encoding is not supported",
970 return HTTP_INTERNAL_SERVER_ERROR;
973 if (old_cl_val && old_te_val) {
974 ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
975 "proxy: client %s (%s) requested Transfer-Encoding "
976 "chunked body with Content-Length (C-L ignored)",
977 c->remote_ip, c->remote_host ? c->remote_host: "");
978 apr_table_unset(r->headers_in, "Content-Length");
980 origin->keepalive = AP_CONN_CLOSE;
984 /* Prefetch MAX_MEM_SPOOL bytes
986 * This helps us avoid any election of C-L v.s. T-E
987 * request bodies, since we are willing to keep in
988 * memory this much data, in any case. This gives
989 * us an instant C-L election if the body is of some
992 temp_brigade = apr_brigade_create(p, bucket_alloc);
994 status = ap_get_brigade(r->input_filters, temp_brigade,
995 AP_MODE_READBYTES, APR_BLOCK_READ,
996 MAX_MEM_SPOOL - bytes_read);
997 if (status != APR_SUCCESS) {
998 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
999 "proxy: prefetch request body failed to %pI (%s)"
1001 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1002 c->remote_ip, c->remote_host ? c->remote_host: "");
1003 return HTTP_BAD_REQUEST;
1006 apr_brigade_length(temp_brigade, 1, &bytes);
1007 bytes_read += bytes;
1010 * Save temp_brigade in input_brigade. (At least) in the SSL case
1011 * temp_brigade contains transient buckets whose data would get
1012 * overwritten during the next call of ap_get_brigade in the loop.
1013 * ap_save_brigade ensures these buckets to be set aside.
1014 * Calling ap_save_brigade with NULL as filter is OK, because
1015 * input_brigade already has been created and does not need to get
1016 * created by ap_save_brigade.
1018 status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
1019 if (status != APR_SUCCESS) {
1020 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1021 "proxy: processing prefetched request body failed"
1022 " to %pI (%s) from %s (%s)",
1023 p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1024 c->remote_ip, c->remote_host ? c->remote_host: "");
1025 return HTTP_INTERNAL_SERVER_ERROR;
1028 /* Ensure we don't hit a wall where we have a buffer too small
1029 * for ap_get_brigade's filters to fetch us another bucket,
1030 * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
1031 * (an arbitrary value.)
1033 } while ((bytes_read < MAX_MEM_SPOOL - 80)
1034 && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1036 /* Use chunked request body encoding or send a content-length body?
1040 * We have no request body (handled by RB_STREAM_CL)
1042 * We have a request body length <= MAX_MEM_SPOOL
1044 * The administrator has setenv force-proxy-request-1.0
1046 * The client sent a C-L body, and the administrator has
1047 * not setenv proxy-sendchunked or has set setenv proxy-sendcl
1049 * The client sent a T-E body, and the administrator has
1050 * setenv proxy-sendcl, and not setenv proxy-sendchunked
1052 * If both proxy-sendcl and proxy-sendchunked are set, the
1053 * behavior is the same as if neither were set, large bodies
1054 * that can't be read will be forwarded in their original
1055 * form of C-L, or T-E.
1057 * To ensure maximum compatibility, setenv proxy-sendcl
1058 * To reduce server resource use, setenv proxy-sendchunked
1060 * Then address specific servers with conditional setenv
1061 * options to restore the default behavior where desireable.
1063 * We have to compute content length by reading the entire request
1064 * body; if request body is not small, we'll spool the remaining
1065 * input to a temporary file. Chunked is always preferable.
1067 * We can only trust the client-provided C-L if the T-E header
1068 * is absent, and the filters are unchanged (the body won't
1069 * be resized by another content filter).
1071 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1072 /* The whole thing fit, so our decision is trivial, use
1073 * the filtered bytes read from the client for the request
1074 * body Content-Length.
1076 * If we expected no body, and read no body, do not set
1077 * the Content-Length.
1079 if (old_cl_val || old_te_val || bytes_read) {
1080 old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1082 rb_method = RB_STREAM_CL;
1084 else if (old_te_val) {
1086 || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1087 && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1088 && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1089 rb_method = RB_SPOOL_CL;
1092 rb_method = RB_STREAM_CHUNKED;
1095 else if (old_cl_val) {
1096 if (r->input_filters == r->proto_input_filters) {
1097 rb_method = RB_STREAM_CL;
1100 && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1101 || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1102 && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1103 rb_method = RB_STREAM_CHUNKED;
1106 rb_method = RB_SPOOL_CL;
1110 /* This is an appropriate default; very efficient for no-body
1111 * requests, and has the behavior that it will not add any C-L
1112 * when the old_cl_val is NULL.
1114 rb_method = RB_SPOOL_CL;
1117 /* Yes I hate gotos. This is the subrequest shortcut */
1120 * Handle Connection: header if we do HTTP/1.1 request:
1121 * If we plan to close the backend connection sent Connection: close
1122 * otherwise sent Connection: Keep-Alive.
1128 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
1129 sprintf(mop_bf, "conn_close1: [%d][%d]\n", p_conn->close, p_conn->close_on_recycle);
1130 write(mop_fd, mop_bf, strlen(mop_bf));
1133 if (p_conn->close || p_conn->close_on_recycle) {
1134 buf = apr_pstrdup(p, "Connection: close" CRLF);
1137 buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1139 ap_xlate_proto_to_ascii(buf, strlen(buf));
1140 e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1141 APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1144 /* send the request body, if any. */
1146 case RB_STREAM_CHUNKED:
1147 rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1151 rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1152 input_brigade, old_cl_val);
1155 rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1156 input_brigade, (old_cl_val != NULL)
1157 || (old_te_val != NULL)
1158 || (bytes_read > 0));
1161 /* shouldn't be possible */
1162 rv = HTTP_INTERNAL_SERVER_ERROR ;
1167 /* apr_errno value has been logged in lower level method */
1168 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
1169 "proxy: pass request body failed to %pI (%s)"
1172 p_conn->hostname ? p_conn->hostname: "",
1174 c->remote_host ? c->remote_host: "");
1181 static void process_proxy_header(request_rec* r, proxy_dir_conf* c,
1182 const char* key, const char* value)
1184 static const char* date_hdrs[]
1185 = { "Date", "Expires", "Last-Modified", NULL } ;
1186 static const struct {
1188 ap_proxy_header_reverse_map_fn func;
1189 } transform_hdrs[] = {
1190 { "Location", ap_proxy_location_reverse_map } ,
1191 { "Content-Location", ap_proxy_location_reverse_map } ,
1192 { "URI", ap_proxy_location_reverse_map } ,
1193 { "Destination", ap_proxy_location_reverse_map } ,
1194 { "Set-Cookie", ap_proxy_cookie_reverse_map } ,
1198 for ( i = 0 ; date_hdrs[i] ; ++i ) {
1199 if ( !strcasecmp(date_hdrs[i], key) ) {
1200 apr_table_add(r->headers_out, key,
1201 ap_proxy_date_canon(r->pool, value)) ;
1205 for ( i = 0 ; transform_hdrs[i].name ; ++i ) {
1206 if ( !strcasecmp(transform_hdrs[i].name, key) ) {
1207 apr_table_add(r->headers_out, key,
1208 (*transform_hdrs[i].func)(r, c, value)) ;
1212 apr_table_add(r->headers_out, key, value) ;
1217 * Note: pread_len is the length of the response that we've mistakenly
1218 * read (assuming that we don't consider that an error via
1219 * ProxyBadHeader StartBody). This depends on buffer actually being
1220 * local storage to the calling code in order for pread_len to make
1221 * any sense at all, since we depend on buffer still containing
1222 * what was read by ap_getline() upon return.
1224 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1225 char *buffer, int size,
1226 conn_rec *c, int *pread_len)
1230 char field[MAX_STRING_LEN];
1231 int saw_headers = 0;
1232 void *sconf = r->server->module_config;
1233 proxy_server_conf *psc;
1234 proxy_dir_conf *dconf;
1236 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1237 psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1239 r->headers_out = apr_table_make(r->pool, 20);
1243 * Read header lines until we get the empty separator line, a read error,
1244 * the connection closes (EOF), or we timeout.
1246 while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1248 if (!(value = strchr(buffer, ':'))) { /* Find the colon separator */
1250 /* We may encounter invalid headers, usually from buggy
1251 * MS IIS servers, so we need to determine just how to handle
1252 * them. We can either ignore them, assume that they mark the
1253 * start-of-body (eg: a missing CRLF) or (the default) mark
1254 * the headers as totally bogus and return a 500. The sole
1255 * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1256 * in between the usual MIME headers, which is a favorite
1259 /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1261 if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1262 if (psc->badopt == bad_error) {
1263 /* Nope, it wasn't even an extra HTTP header. Give up. */
1264 r->headers_out = NULL;
1267 else if (psc->badopt == bad_body) {
1268 /* if we've already started loading headers_out, then
1269 * return what we've accumulated so far, in the hopes
1270 * that they are useful; also note that we likely pre-read
1271 * the first line of the response.
1274 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1275 "proxy: Starting body due to bogus non-header in headers "
1276 "returned by %s (%s)", r->uri, r->method);
1280 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1281 "proxy: No HTTP headers "
1282 "returned by %s (%s)", r->uri, r->method);
1287 /* this is the psc->badopt == bad_ignore case */
1288 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1289 "proxy: Ignoring bogus HTTP header "
1290 "returned by %s (%s)", r->uri, r->method);
1296 /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1297 * wrong... and so are many others probably.
1299 while (apr_isspace(*value))
1300 ++value; /* Skip to start of value */
1302 /* should strip trailing whitespace as well */
1303 for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1307 /* make sure we add so as not to destroy duplicated headers
1308 * Modify headers requiring canonicalisation and/or affected
1309 * by ProxyPassReverse and family with process_proxy_header
1311 process_proxy_header(r, dconf, buffer, value) ;
1314 /* the header was too long; at the least we should skip extra data */
1315 if (len >= size - 1) {
1316 while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1317 >= MAX_STRING_LEN - 1) {
1318 /* soak up the extra data */
1320 if (len == 0) /* time to exit the larger loop as well */
1328 static int addit_dammit(void *v, const char *key, const char *val)
1330 apr_table_addn(v, key, val);
1335 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1336 int fold, int *writen)
1342 rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1343 apr_brigade_cleanup(bb);
1345 if (rv == APR_SUCCESS) {
1346 *writen = (int) len;
1347 } else if (rv == APR_ENOSPC) {
1357 * Limit the number of interim respones we sent back to the client. Otherwise
1358 * we suffer from a memory build up. Besides there is NO sense in sending back
1359 * an unlimited number of interim responses to the client. Thus if we cross
1360 * this limit send back a 502 (Bad Gateway).
1362 #ifndef AP_MAX_INTERIM_RESPONSES
1363 #define AP_MAX_INTERIM_RESPONSES 10
1367 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1368 proxy_conn_rec *backend,
1370 proxy_server_conf *conf,
1371 char *server_portstr) {
1372 conn_rec *c = r->connection;
1373 char buffer[HUGE_STRING_LEN];
1378 apr_bucket_brigade *bb, *tmp_bb;
1379 apr_bucket_brigade *pass_bb;
1380 int len, backasswards;
1381 int interim_response = 0; /* non-zero whilst interim 1xx responses
1382 * are being read. */
1384 apr_table_t *save_table;
1385 int backend_broke = 0;
1386 static const char *hop_by_hop_hdrs[] =
1387 {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1389 const char *te = NULL;
1390 int original_status = r->status;
1391 int proxy_status = OK;
1392 const char *original_status_line = r->status_line;
1393 const char *proxy_status_line = NULL;
1395 bb = apr_brigade_create(p, c->bucket_alloc);
1396 pass_bb = apr_brigade_create(p, c->bucket_alloc);
1398 /* Get response from the remote server, and pass it up the
1402 rp = ap_proxy_make_fake_req(origin, r);
1403 /* In case anyone needs to know, this is a fake request that is really a
1406 rp->proxyreq = PROXYREQ_RESPONSE;
1407 tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1411 apr_brigade_cleanup(bb);
1413 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1415 /* handle one potential stray CRLF */
1416 rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1419 ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1420 "proxy: error reading status line from remote "
1421 "server %s:%d", backend->hostname, backend->port);
1422 if (APR_STATUS_IS_TIMEUP(rc)) {
1423 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1424 "proxy: read timeout");
1427 * If we are a reverse proxy request shutdown the connection
1428 * WITHOUT ANY response to trigger a retry by the client
1429 * if allowed (as for idempotent requests).
1430 * BUT currently we should not do this if the request is the
1431 * first request on a keepalive connection as browsers like
1432 * seamonkey only display an empty page in this case and do
1433 * not do a retry. We should also not do this on a
1434 * connection which times out; instead handle as
1435 * we normally would handle timeouts
1437 if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives &&
1438 !APR_STATUS_IS_TIMEUP(rc)) {
1441 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1442 "proxy: Closing connection to client because"
1443 " reading from backend server %s:%d failed."
1444 " Number of keepalives %i", backend->hostname,
1445 backend->port, c->keepalives);
1446 ap_proxy_backend_broke(r, bb);
1448 * Add an EOC bucket to signal the ap_http_header_filter
1449 * that it should get out of our way, BUT ensure that the
1450 * EOC bucket is inserted BEFORE an EOS bucket in bb as
1451 * some resource filters like mod_deflate pass everything
1452 * up to the EOS down the chain immediately and sent the
1453 * remainder of the brigade later (or even never). But in
1454 * this case the ap_http_header_filter does not get out of
1455 * our way soon enough.
1457 e = ap_bucket_eoc_create(c->bucket_alloc);
1458 eos = APR_BRIGADE_LAST(bb);
1459 while ((APR_BRIGADE_SENTINEL(bb) != eos)
1460 && !APR_BUCKET_IS_EOS(eos)) {
1461 eos = APR_BUCKET_PREV(eos);
1463 if (eos == APR_BRIGADE_SENTINEL(bb)) {
1464 APR_BRIGADE_INSERT_TAIL(bb, e);
1467 APR_BUCKET_INSERT_BEFORE(eos, e);
1469 ap_pass_brigade(r->output_filters, bb);
1470 /* Mark the backend connection for closing */
1472 /* Need to return OK to avoid sending an error message */
1475 else if (!c->keepalives) {
1476 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1477 "proxy: NOT Closing connection to client"
1478 " although reading from backend server %s:%d"
1479 " failed.", backend->hostname,
1482 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1483 "Error reading from remote server");
1485 /* XXX: Is this a real headers length send from remote? */
1486 backend->worker->s->read += len;
1488 /* Is it an HTTP/1 response?
1489 * This is buggy if we ever see an HTTP/1.10
1491 if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1494 if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1498 /* If not an HTTP/1 message or
1499 * if the status line was > 8192 bytes
1501 else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1502 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1503 apr_pstrcat(p, "Corrupt status line returned by remote "
1504 "server: ", buffer, NULL));
1508 keepchar = buffer[12];
1510 proxy_status = atoi(&buffer[9]);
1512 if (keepchar != '\0') {
1513 buffer[12] = keepchar;
1515 /* 2616 requires the space in Status-Line; the origin
1516 * server may have sent one but ap_rgetline_core will
1517 * have stripped it. */
1521 proxy_status_line = apr_pstrdup(p, &buffer[9]);
1523 /* The status out of the front is the same as the status coming in
1524 * from the back, until further notice.
1526 r->status = proxy_status;
1527 r->status_line = proxy_status_line;
1529 /* read the headers. */
1530 /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1531 /* Also, take care with headers with multiple occurences. */
1533 /* First, tuck away all already existing cookies */
1534 save_table = apr_table_make(r->pool, 2);
1535 apr_table_do(addit_dammit, save_table, r->headers_out,
1536 "Set-Cookie", NULL);
1538 /* shove the headers direct into r->headers_out */
1539 ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1542 if (r->headers_out == NULL) {
1543 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1544 r->server, "proxy: bad HTTP/%d.%d header "
1545 "returned by %s (%s)", major, minor, r->uri,
1547 backend->close += 1;
1549 * ap_send_error relies on a headers_out to be present. we
1550 * are in a bad position here.. so force everything we send out
1551 * to have nothing to do with the incoming packet
1553 r->headers_out = apr_table_make(r->pool,1);
1554 r->status = HTTP_BAD_GATEWAY;
1555 r->status_line = "bad gateway";
1559 /* Now, add in the just read cookies */
1560 apr_table_do(addit_dammit, save_table, r->headers_out,
1561 "Set-Cookie", NULL);
1563 /* and now load 'em all in */
1564 if (!apr_is_empty_table(save_table)) {
1565 apr_table_unset(r->headers_out, "Set-Cookie");
1566 r->headers_out = apr_table_overlay(r->pool,
1571 /* can't have both Content-Length and Transfer-Encoding */
1572 if (apr_table_get(r->headers_out, "Transfer-Encoding")
1573 && apr_table_get(r->headers_out, "Content-Length")) {
1575 * 2616 section 4.4, point 3: "if both Transfer-Encoding
1576 * and Content-Length are received, the latter MUST be
1579 * To help mitigate HTTP Splitting, unset Content-Length
1580 * and shut down the backend server connection
1581 * XXX: We aught to treat such a response as uncachable
1583 apr_table_unset(r->headers_out, "Content-Length");
1584 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1585 "proxy: server %s:%d returned Transfer-Encoding"
1586 " and Content-Length", backend->hostname,
1588 backend->close += 1;
1592 * Save a possible Transfer-Encoding header as we need it later for
1593 * ap_http_filter to know where to end.
1599 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
1600 sprintf(mop_bf, "conn_close2: [%d][%d]\n");
1601 write(mop_fd, mop_bf, strlen(mop_bf));
1604 te = apr_table_get(r->headers_out, "Transfer-Encoding");
1605 /* strip connection listed hop-by-hop headers from response */
1606 backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1609 ap_proxy_clear_connection(p, r->headers_out);
1610 if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1611 ap_set_content_type(r, apr_pstrdup(p, buf));
1613 if (!ap_is_HTTP_INFO(proxy_status)) {
1614 ap_proxy_pre_http_request(origin, rp);
1617 /* Clear hop-by-hop headers */
1618 for (i=0; hop_by_hop_hdrs[i]; ++i) {
1619 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1621 /* Delete warnings with wrong date */
1622 r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1624 /* handle Via header in response */
1625 if (conf->viaopt != via_off && conf->viaopt != via_block) {
1626 const char *server_name = ap_get_server_name(r);
1627 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1628 * then the server name returned by ap_get_server_name() is the
1629 * origin server name (which does make too much sense with Via: headers)
1630 * so we use the proxy vhost's name instead.
1632 if (server_name == r->hostname)
1633 server_name = r->server->server_hostname;
1634 /* create a "Via:" response header entry and merge it */
1635 apr_table_addn(r->headers_out, "Via",
1636 (conf->viaopt == via_full)
1637 ? apr_psprintf(p, "%d.%d %s%s (%s)",
1638 HTTP_VERSION_MAJOR(r->proto_num),
1639 HTTP_VERSION_MINOR(r->proto_num),
1642 AP_SERVER_BASEVERSION)
1643 : apr_psprintf(p, "%d.%d %s%s",
1644 HTTP_VERSION_MAJOR(r->proto_num),
1645 HTTP_VERSION_MINOR(r->proto_num),
1651 /* cancel keepalive if HTTP/1.0 or less */
1652 if ((major < 1) || (minor < 1)) {
1653 backend->close += 1;
1654 origin->keepalive = AP_CONN_CLOSE;
1657 /* an http/0.9 response */
1660 r->status_line = "200 OK";
1661 backend->close += 1;
1664 if (ap_is_HTTP_INFO(proxy_status)) {
1668 interim_response = 0;
1670 if (interim_response) {
1671 /* RFC2616 tells us to forward this.
1673 * OTOH, an interim response here may mean the backend
1674 * is playing sillybuggers. The Client didn't ask for
1675 * it within the defined HTTP/1.1 mechanisms, and if
1676 * it's an extension, it may also be unsupported by us.
1678 * There's also the possibility that changing existing
1679 * behaviour here might break something.
1681 * So let's make it configurable.
1683 const char *policy = apr_table_get(r->subprocess_env,
1684 "proxy-interim-response");
1685 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1686 "proxy: HTTP: received interim %d response",
1688 if (!policy || !strcasecmp(policy, "RFC")) {
1689 ap_send_interim_response(r, 1);
1691 /* FIXME: refine this to be able to specify per-response-status
1692 * policies and maybe also add option to bail out with 502
1694 else if (strcasecmp(policy, "Suppress")) {
1695 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1696 "undefined proxy interim response policy");
1699 /* Moved the fixups of Date headers and those affected by
1700 * ProxyPassReverse/etc from here to ap_proxy_read_headers
1703 if ((proxy_status == 401) && (conf->error_override)) {
1705 const char *wa = "WWW-Authenticate";
1706 if ((buf = apr_table_get(r->headers_out, wa))) {
1707 apr_table_set(r->err_headers_out, wa, buf);
1709 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1710 "proxy: origin server sent 401 without WWW-Authenticate header");
1716 * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1717 * the response? If so, load the extra data. These are 2 mutually
1718 * exclusive possibilities, that just happen to require very
1721 if (backasswards || pread_len) {
1722 apr_ssize_t cntr = (apr_ssize_t)pread_len;
1725 * At this point in response processing of a 0.9 response,
1726 * we don't know yet whether data is binary or not.
1727 * mod_charset_lite will get control later on, so it cannot
1728 * decide on the conversion of this buffer full of data.
1729 * However, chances are that we are not really talking to an
1730 * HTTP/0.9 server, but to some different protocol, therefore
1731 * the best guess IMHO is to always treat the buffer as "text/x":
1733 ap_xlate_proto_to_ascii(buffer, len);
1734 cntr = (apr_ssize_t)len;
1736 e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1737 APR_BRIGADE_INSERT_TAIL(bb, e);
1740 /* send body - but only if a body is expected */
1741 if ((!r->header_only) && /* not HEAD request */
1742 !interim_response && /* not any 1xx response */
1743 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1744 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1746 /* We need to copy the output headers and treat them as input
1747 * headers as well. BUT, we need to do this before we remove
1748 * TE, so that they are preserved accordingly for
1749 * ap_http_filter to know where to end.
1751 rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1753 * Restore Transfer-Encoding header from response if we saved
1754 * one before and there is none left. We need it for the
1755 * ap_http_filter. See above.
1757 if (te && !apr_table_get(rp->headers_in, "Transfer-Encoding")) {
1758 apr_table_add(rp->headers_in, "Transfer-Encoding", te);
1761 apr_table_unset(r->headers_out,"Transfer-Encoding");
1763 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1764 "proxy: start body send");
1767 * if we are overriding the errors, we can't put the content
1768 * of the page into the brigade
1770 if (!conf->error_override || !ap_is_HTTP_ERROR(proxy_status)) {
1771 /* read the body, pass it to the output filters */
1772 apr_read_type_e mode = APR_NONBLOCK_READ;
1775 /* Handle the case where the error document is itself reverse
1776 * proxied and was successful. We must maintain any previous
1777 * error status so that an underlying error (eg HTTP_NOT_FOUND)
1778 * doesn't become an HTTP_OK.
1780 if (conf->error_override && !ap_is_HTTP_ERROR(proxy_status)
1781 && ap_is_HTTP_ERROR(original_status)) {
1782 r->status = original_status;
1783 r->status_line = original_status_line;
1787 apr_off_t readbytes;
1790 rv = ap_get_brigade(rp->input_filters, bb,
1791 AP_MODE_READBYTES, mode,
1792 conf->io_buffer_size);
1794 /* ap_get_brigade will return success with an empty brigade
1795 * for a non-blocking read which would block: */
1796 if (APR_STATUS_IS_EAGAIN(rv)
1797 || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1798 /* flush to the client and switch to blocking mode */
1799 e = apr_bucket_flush_create(c->bucket_alloc);
1800 APR_BRIGADE_INSERT_TAIL(bb, e);
1801 if (ap_pass_brigade(r->output_filters, bb)
1806 apr_brigade_cleanup(bb);
1807 mode = APR_BLOCK_READ;
1810 else if (rv == APR_EOF) {
1813 else if (rv != APR_SUCCESS) {
1814 /* In this case, we are in real trouble because
1815 * our backend bailed on us. Pass along a 502 error
1818 ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1819 "proxy: error reading response");
1820 ap_proxy_backend_broke(r, bb);
1821 ap_pass_brigade(r->output_filters, bb);
1826 /* next time try a non-blocking read */
1827 mode = APR_NONBLOCK_READ;
1829 apr_brigade_length(bb, 0, &readbytes);
1830 backend->worker->s->read += readbytes;
1833 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1834 r->server, "proxy (PID %d): readbytes: %#x",
1835 getpid(), readbytes);
1839 if (APR_BRIGADE_EMPTY(bb)) {
1840 apr_brigade_cleanup(bb);
1844 /* Switch the allocator lifetime of the buckets */
1845 ap_proxy_buckets_lifetime_transform(r, bb, pass_bb);
1847 /* found the last brigade? */
1848 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1849 /* signal that we must leave */
1853 /* try send what we read */
1854 if (ap_pass_brigade(r->output_filters, pass_bb) != APR_SUCCESS
1856 /* Ack! Phbtt! Die! User aborted! */
1857 backend->close = 1; /* this causes socket close below */
1861 /* make sure we always clean up after ourselves */
1862 apr_brigade_cleanup(bb);
1863 apr_brigade_cleanup(pass_bb);
1867 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1868 "proxy: end body send");
1870 else if (!interim_response) {
1871 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1872 "proxy: header only");
1874 /* Pass EOS bucket down the filter chain. */
1875 e = apr_bucket_eos_create(c->bucket_alloc);
1876 APR_BRIGADE_INSERT_TAIL(bb, e);
1877 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1879 /* Ack! Phbtt! Die! User aborted! */
1880 backend->close = 1; /* this causes socket close below */
1883 apr_brigade_cleanup(bb);
1885 } while (interim_response && (interim_response < AP_MAX_INTERIM_RESPONSES));
1887 /* See define of AP_MAX_INTERIM_RESPONSES for why */
1888 if (interim_response >= AP_MAX_INTERIM_RESPONSES) {
1889 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1891 "Too many (%d) interim responses from origin server",
1895 /* If our connection with the client is to be aborted, return DONE. */
1896 if (c->aborted || backend_broke) {
1900 if (conf->error_override) {
1901 /* the code above this checks for 'OK' which is what the hook expects */
1902 if (!ap_is_HTTP_ERROR(proxy_status)) {
1906 /* clear r->status for override error, otherwise ErrorDocument
1907 * thinks that this is a recursive error, and doesn't find the
1910 r->status = HTTP_OK;
1911 /* Discard body, if one is expected */
1912 if (!r->header_only && /* not HEAD request */
1913 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1914 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1915 ap_discard_request_body(rp);
1917 return proxy_status;
1926 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1927 proxy_conn_rec *backend)
1929 ap_proxy_release_connection(scheme, backend, r->server);
1934 * This handles http:// URLs, and other URLs using a remote proxy over http
1935 * If proxyhost is NULL, then contact the server directly, otherwise
1937 * Note that if a proxy is used, then URLs other than http: can be accessed,
1938 * also, if we have trouble which is clearly specific to the proxy, then
1939 * we return DECLINED so that we can try another proxy. (Or the direct
1942 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1943 proxy_server_conf *conf,
1944 char *url, const char *proxyname,
1945 apr_port_t proxyport)
1948 char server_portstr[32];
1950 const char *proxy_function;
1952 proxy_conn_rec *backend = NULL;
1954 conn_rec *c = r->connection;
1956 * Use a shorter-lived pool to reduce memory usage
1957 * and avoid a memory leak
1959 apr_pool_t *p = r->pool;
1960 apr_uri_t *uri = apr_palloc(p, sizeof(*uri));
1962 /* find the scheme */
1963 u = strchr(url, ':');
1964 if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1967 return HTTP_BAD_REQUEST;
1968 scheme = apr_pstrndup(p, url, u - url);
1969 /* scheme is lowercase */
1970 ap_str_tolower(scheme);
1972 if (strcmp(scheme, "https") == 0) {
1973 if (!ap_proxy_ssl_enable(NULL)) {
1974 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1975 "proxy: HTTPS: declining URL %s"
1976 " (mod_ssl not configured?)", url);
1980 proxy_function = "HTTPS";
1982 else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1983 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1984 "proxy: HTTP: declining URL %s", url);
1985 return DECLINED; /* only interested in HTTP, or FTP via proxy */
1989 proxy_function = "HTTP";
1991 proxy_function = "FTP";
1993 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1994 "proxy: HTTP: serving URL %s", url);
1997 /* create space for state information */
1998 if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1999 worker, r->server)) != OK)
2003 backend->is_ssl = is_ssl;
2005 ap_proxy_ssl_connection_cleanup(backend, r);
2009 * In the case that we are handling a reverse proxy connection and this
2010 * is not a request that is coming over an already kept alive connection
2011 * with the client, do NOT reuse the connection to the backend, because
2012 * we cannot forward a failure to the client in this case as the client
2013 * does NOT expects this in this situation.
2014 * Yes, this creates a performance penalty.
2016 if ((r->proxyreq == PROXYREQ_REVERSE) && (!c->keepalives)
2017 && (apr_table_get(r->subprocess_env, "proxy-initial-not-pooled"))) {
2021 /* Step One: Determine Who To Connect To */
2022 if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
2023 uri, &url, proxyname,
2024 proxyport, server_portstr,
2025 sizeof(server_portstr))) != OK)
2028 /* Step Two: Make the Connection */
2029 if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
2030 status = HTTP_SERVICE_UNAVAILABLE;
2034 /* Step Three: Create conn_rec */
2035 if (!backend->connection) {
2036 if ((status = ap_proxy_connection_create(proxy_function, backend,
2037 c, r->server)) != OK)
2040 * On SSL connections set a note on the connection what CN is
2041 * requested, such that mod_ssl can check if it is requested to do
2045 apr_table_set(backend->connection->notes, "proxy-request-hostname",
2050 /* Step Four: Send the Request */
2051 if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
2052 conf, uri, url, server_portstr)) != OK)
2055 /* Step Five: Receive the Response */
2056 if ((status = ap_proxy_http_process_response(p, r, backend,
2057 backend->connection,
2058 conf, server_portstr)) != OK)
2061 /* Step Six: Clean Up */
2067 ap_proxy_http_cleanup(proxy_function, r, backend);
2071 static apr_status_t warn_rx_free(void *p)
2073 ap_pregfree((apr_pool_t*)p, warn_rx);
2076 static void ap_proxy_http_register_hook(apr_pool_t *p)
2078 proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
2079 proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
2080 warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
2081 apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
2084 module AP_MODULE_DECLARE_DATA proxy_http_module = {
2085 STANDARD20_MODULE_STUFF,
2086 NULL, /* create per-directory config structure */
2087 NULL, /* merge per-directory config structures */
2088 NULL, /* create per-server config structure */
2089 NULL, /* merge per-server config structures */
2090 NULL, /* command apr_table_t */
2091 ap_proxy_http_register_hook/* register hooks */
2095 #endif /* MOP_HERE_ONLY_FOR_EXAMPLE */
2098 /* Licensed to the Apache Software Foundation (ASF) under one or more
2099 * contributor license agreements. See the NOTICE file distributed with
2100 * this work for additional information regarding copyright ownership.
2101 * The ASF licenses this file to You under the Apache License, Version 2.0
2102 * (the "License"); you may not use this file except in compliance with
2103 * the License. You may obtain a copy of the License at
2105 * http://www.apache.org/licenses/LICENSE-2.0
2107 * Unless required by applicable law or agreed to in writing, software
2108 * distributed under the License is distributed on an "AS IS" BASIS,
2109 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2110 * See the License for the specific language governing permissions and
2111 * limitations under the License.
2114 #include "mod_proxy.h"
2116 #include <sys/types.h>
2117 #include <sys/socket.h>
2121 #error This module only works on unix platforms with the correct OS support
2124 #include "apr_version.h"
2125 #if APR_MAJOR_VERSION < 2
2126 /* for apr_wait_for_io_or_timeout */
2127 #include "apr_support.h"
2130 #include "mod_proxy_fdpass.h"
2132 module AP_MODULE_DECLARE_DATA proxy_fdpass_module;
2134 static int proxy_fdpass_canon(request_rec *r, char *url)
2142 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
2143 sprintf(mop_bf, "proxy_http_canon: start\n");
2144 write(mop_fd, mop_bf, strlen(mop_bf));
2149 if (strncasecmp(url, "fd://", 5) == 0) {
2156 path = ap_server_root_relative(r->pool, url);
2158 r->filename = apr_pstrcat(r->pool, "proxy:fd://", path, NULL);
2160 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2161 "proxy: FD: set r->filename to %s", r->filename);
2165 /* TODO: In APR 2.x: Extend apr_sockaddr_t to possibly be a path !!! */
2166 static apr_status_t socket_connect_un(request_rec *r, apr_socket_t *sock,
2167 struct sockaddr_un *sa)
2170 apr_os_sock_t rawsock;
2171 apr_interval_time_t t;
2173 rv = apr_os_sock_get(&rawsock, sock);
2174 if (rv != APR_SUCCESS) {
2175 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2176 "proxy: FD: apr_os_sock_get failed");
2180 rv = apr_socket_timeout_get(sock, &t);
2181 if (rv != APR_SUCCESS) {
2182 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2183 "proxy: FD: apr_socket_timeout_get failed");
2188 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2189 "proxy: FD: pre_connect");
2190 rv = connect(rawsock, (struct sockaddr*)sa,
2191 sizeof(*sa) /* + strlen(sa->sun_path)*/ );
2192 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2193 "proxy: FD: post_connect %d", rv);
2194 } while (rv == -1 && errno == EINTR);
2196 if ((rv == -1) && (errno == EINPROGRESS || errno == EALREADY)
2198 #if APR_MAJOR_VERSION < 2
2199 rv = apr_wait_for_io_or_timeout(NULL, sock, 0);
2201 rv = apr_socket_wait(sock, APR_WAIT_WRITE);
2204 if (rv != APR_SUCCESS) {
2205 ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL,
2206 "proxy: FD: apr_socket_wait failed");
2211 if (rv == -1 && errno != EISCONN) {
2212 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2213 "proxy: FD: socket_connect_un preexit %d", errno);
2220 static apr_status_t get_socket_from_path(request_rec *r, apr_pool_t *p,
2222 apr_socket_t **out_sock)
2224 struct sockaddr_un sa;
2230 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2231 "proxy: FD: Failed to connect to '%s' %d xxx",
2234 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2235 "proxy: FD: get_socket_from_path::START");
2237 rv = apr_socket_create(&s, AF_UNIX, SOCK_STREAM, 0, p);
2239 if (rv != APR_SUCCESS) {
2240 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2241 "proxy: FD: get_socket_from_path::create %d", rv);
2245 sa.sun_family = AF_UNIX;
2246 apr_cpystrn(sa.sun_path, path, sizeof(sa.sun_path));
2248 rv = socket_connect_un(r, s, &sa);
2249 if (rv != APR_SUCCESS) {
2250 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2251 "proxy: FD: get_socket_from_path::connect_un %d", rv);
2261 static apr_status_t send_socket(apr_pool_t *p,
2263 apr_socket_t *outbound)
2266 apr_os_sock_t rawsock;
2267 apr_os_sock_t srawsock;
2269 struct cmsghdr *cmsg;
2271 char b = '\0', *buf;
2277 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
2278 sprintf(mop_bf, "send_socket: start\n");
2279 write(mop_fd, mop_bf, strlen(mop_bf));
2284 rv = apr_os_sock_get(&rawsock, outbound);
2285 if (rv != APR_SUCCESS) {
2289 rv = apr_os_sock_get(&srawsock, s);
2290 if (rv != APR_SUCCESS) {
2294 memset(&msg, 0, sizeof(msg));
2302 cmsg = apr_palloc(p, sizeof(*cmsg) + sizeof(rawsock));
2303 cmsg->cmsg_len = sizeof(*cmsg) + sizeof(rawsock);
2304 cmsg->cmsg_level = SOL_SOCKET;
2305 cmsg->cmsg_type = SCM_RIGHTS;
2307 memcpy(CMSG_DATA(cmsg), &rawsock, sizeof(rawsock));
2309 msg.msg_control = cmsg;
2310 msg.msg_controllen = cmsg->cmsg_len;
2312 rv = sendmsg(srawsock, &msg, 0);
2322 static int proxy_fdpass_handler(request_rec *r, proxy_worker *worker,
2323 proxy_server_conf *conf,
2324 char *url, const char *proxyname,
2325 apr_port_t proxyport)
2329 apr_socket_t *clientsock;
2336 mop_fd = open("/tmp/apache_mop.log", O_WRONLY | O_APPEND);
2337 sprintf(mop_bf, "proxy_fdpass_handler: start\n");
2338 write(mop_fd, mop_bf, strlen(mop_bf));
2343 if (strncasecmp(url, "fd://", 5) == 0) {
2350 rv = get_socket_from_path(r, r->pool, url, &sock);
2352 if (rv != APR_SUCCESS) {
2353 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2354 "proxy: FD: Failed to connect to '%s' %d xxx",
2356 return HTTP_INTERNAL_SERVER_ERROR;
2361 /* const char *flush_method = worker->flusher ? worker->flusher : "flush"; */
2362 const char *flush_method = "flush";
2364 proxy_fdpass_flush *flush = ap_lookup_provider(PROXY_FDPASS_FLUSHER,
2368 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2369 "proxy: FD: Unable to find configured flush "
2370 "provider '%s'", flush_method);
2371 return HTTP_INTERNAL_SERVER_ERROR;
2374 status = flush->flusher(r);
2380 if ((buf = apr_table_get(r->headers_in, "Host"))) {
2381 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2382 "proxy: FD: Host is: [%s]", buf);
2385 /* XXXXX: THIS IS AN EVIL HACK */
2386 /* There should really be a (documented) public API for this ! */
2387 clientsock = ap_get_module_config(r->connection->conn_config, &core_module);
2389 rv = send_socket(r->pool, sock, clientsock);
2390 if (rv != APR_SUCCESS) {
2391 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2392 "proxy: FD: send_socket failed:");
2393 return HTTP_INTERNAL_SERVER_ERROR;
2397 apr_socket_t *dummy;
2398 /* Create a dummy unconnected socket, and set it as the one we were
2399 * connected to, so that when the core closes it, it doesn't close
2400 * the tcp connection to the client.
2402 rv = apr_socket_create(&dummy, APR_INET, SOCK_STREAM, APR_PROTO_TCP,
2403 r->connection->pool);
2404 if (rv != APR_SUCCESS) {
2405 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2406 "proxy: FD: failed to create dummy socket");
2407 return HTTP_INTERNAL_SERVER_ERROR;
2409 ap_set_module_config(r->connection->conn_config, &core_module, dummy);
2416 static int standard_flush(request_rec *r)
2419 apr_bucket_brigade *bb;
2422 r->connection->keepalive = AP_CONN_CLOSE;
2424 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2425 e = apr_bucket_flush_create(r->connection->bucket_alloc);
2427 APR_BRIGADE_INSERT_TAIL(bb, e);
2429 status = ap_pass_brigade(r->output_filters, bb);
2432 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2433 "proxy: FD: ap_pass_brigade failed:");
2441 static const proxy_fdpass_flush builtin_flush =
2448 static void ap_proxy_fdpass_register_hooks(apr_pool_t *p)
2450 ap_register_provider(p, PROXY_FDPASS_FLUSHER, "flush", "0", &builtin_flush);
2451 proxy_hook_scheme_handler(proxy_fdpass_handler, NULL, NULL, APR_HOOK_FIRST);
2452 proxy_hook_canon_handler(proxy_fdpass_canon, NULL, NULL, APR_HOOK_FIRST);
2455 module AP_MODULE_DECLARE_DATA proxy_fdpass_module = {
2456 STANDARD20_MODULE_STUFF,
2457 NULL, /* create per-directory config structure */
2458 NULL, /* merge per-directory config structures */
2459 NULL, /* create per-server config structure */
2460 NULL, /* merge per-server config structures */
2461 NULL, /* command apr_table_t */
2462 ap_proxy_fdpass_register_hooks /* register hooks */