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 /* Utility routines for Apache proxy */
18 #include "mod_proxy.h"
20 #include "scoreboard.h"
21 #include "apr_version.h"
24 #include <unistd.h> /* for getpid() */
27 #if (APR_MAJOR_VERSION < 1)
28 #undef apr_socket_create
29 #define apr_socket_create apr_socket_create_ex
33 * Opaque structure containing target server info when
34 * using a forward proxy.
35 * Up to now only used in combination with HTTP CONNECT.
38 int use_http_connect; /* Use SSL Tunneling via HTTP CONNECT */
39 const char *target_host; /* Target hostname */
40 apr_port_t target_port; /* Target port */
41 const char *proxy_auth; /* Proxy authorization */
44 /* Global balancer counter */
45 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
46 static int lb_workers_limit = 0;
48 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
49 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
50 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
51 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
53 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
54 (request_rec *r, request_rec *pr), (r, pr),
57 /* already called in the knowledge that the characters are hex digits */
58 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
62 #if !APR_CHARSET_EBCDIC
64 if (apr_isdigit(ch)) {
67 else if (apr_isupper(ch)) {
76 if (apr_isdigit(ch)) {
79 else if (apr_isupper(ch)) {
86 #else /*APR_CHARSET_EBCDIC*/
88 * we assume that the hex value refers to an ASCII character
89 * so convert to EBCDIC so that it makes sense locally;
93 * client specifies %20 in URL to refer to a space char;
94 * at this point we're called with EBCDIC "20"; after turning
95 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
96 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
101 if (1 == sscanf(x, "%2x", &i)) {
103 ap_xlate_proto_from_ascii(buf, 1);
109 #endif /*APR_CHARSET_EBCDIC*/
112 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
114 #if !APR_CHARSET_EBCDIC
118 i = (ch & 0xF0) >> 4;
120 x[1] = ('A' - 10) + i;
128 x[2] = ('A' - 10) + i;
133 #else /*APR_CHARSET_EBCDIC*/
134 static const char ntoa[] = { "0123456789ABCDEF" };
140 ap_xlate_proto_to_ascii(buf, 1);
143 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
144 x[2] = ntoa[buf[0] & 0x0F];
146 #endif /*APR_CHARSET_EBCDIC*/
150 * canonicalise a URL-encoded string
154 * Convert a URL-encoded string to canonical form.
155 * It decodes characters which need not be encoded,
156 * and encodes those which must be encoded, and does not touch
157 * those which must not be touched.
159 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
160 enum enctype t, int forcedec,
165 char *allowed; /* characters which should not be encoded */
166 char *reserved; /* characters which much not be en/de-coded */
169 * N.B. in addition to :@&=, this allows ';' in an http path
170 * and '?' in an ftp path -- this may be revised
172 * Also, it makes a '+' character in a search string reserved, as
173 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
174 * it only permits ; / ? : @ = & as reserved chars.)
177 allowed = "~$-_.+!*'(),;:@&=";
179 else if (t == enc_search) {
180 allowed = "$-_.!*'(),;:@&=";
182 else if (t == enc_user) {
183 allowed = "$-_.+!*'(),;@&=";
185 else if (t == enc_fpath) {
186 allowed = "$-_.+!*'(),?:@&=";
188 else { /* if (t == enc_parm) */
189 allowed = "$-_.+!*'(),?/:@&=";
195 else if (t == enc_search) {
202 y = apr_palloc(p, 3 * len + 1);
204 for (i = 0, j = 0; i < len; i++, j++) {
205 /* always handle '/' first */
207 if (strchr(reserved, ch)) {
212 * decode it if not already done. do not decode reverse proxied URLs
213 * unless specifically forced
215 if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
216 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
219 ch = ap_proxy_hex2c(&x[i + 1]);
221 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
222 ap_proxy_c2hex(ch, &y[j]);
227 /* recode it, if necessary */
228 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
229 ap_proxy_c2hex(ch, &y[j]);
241 * Parses network-location.
242 * urlp on input the URL; on output the path, after the leading /
243 * user NULL if no user/password permitted
244 * password holder for password
245 * host holder for host
246 * port port number; only set if one is supplied.
248 * Returns an error string.
250 PROXY_DECLARE(char *)
251 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
252 char **passwordp, char **hostp, apr_port_t *port)
254 char *addr, *scope_id, *strp, *host, *url = *urlp;
255 char *user = NULL, *password = NULL;
259 if (url[0] != '/' || url[1] != '/') {
260 return "Malformed URL";
263 url = strchr(host, '/');
268 *(url++) = '\0'; /* skip seperating '/' */
271 /* find _last_ '@' since it might occur in user/password part */
272 strp = strrchr(host, '@');
280 strp = strchr(user, ':');
283 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
284 if (password == NULL) {
285 return "Bad %-escape in URL (password)";
289 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
291 return "Bad %-escape in URL (username)";
297 if (passwordp != NULL) {
298 *passwordp = password;
302 * Parse the host string to separate host portion from optional port.
303 * Perform range checking on port.
305 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
306 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
307 return "Invalid host/port";
309 if (tmp_port != 0) { /* only update caller's port if port was specified */
313 ap_str_tolower(addr); /* DNS names are case-insensitive */
322 * If the date is a valid RFC 850 date or asctime() date, then it
323 * is converted to the RFC 1123 format.
325 PROXY_DECLARE(const char *)
326 ap_proxy_date_canon(apr_pool_t *p, const char *date)
331 apr_time_t time = apr_date_parse_http(date);
336 ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
337 rv = apr_rfc822_date(ndate, time);
338 if (rv != APR_SUCCESS) {
345 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
347 request_rec *rp = apr_pcalloc(r->pool, sizeof(*r));
350 rp->status = HTTP_OK;
352 rp->headers_in = apr_table_make(r->pool, 50);
353 rp->subprocess_env = apr_table_make(r->pool, 50);
354 rp->headers_out = apr_table_make(r->pool, 12);
355 rp->err_headers_out = apr_table_make(r->pool, 5);
356 rp->notes = apr_table_make(r->pool, 5);
358 rp->server = r->server;
359 rp->proxyreq = r->proxyreq;
360 rp->request_time = r->request_time;
362 rp->output_filters = c->output_filters;
363 rp->input_filters = c->input_filters;
364 rp->proto_output_filters = c->output_filters;
365 rp->proto_input_filters = c->input_filters;
367 rp->request_config = ap_create_request_config(r->pool);
368 proxy_run_create_req(r, rp);
375 * list is a comma-separated list of case-insensitive tokens, with
376 * optional whitespace around the tokens.
377 * The return returns 1 if the token val is found in the list, or 0
380 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
387 while (list != NULL) {
388 p = ap_strchr_c(list, ',');
393 } while (apr_isspace(*p));
399 while (i > 0 && apr_isspace(list[i - 1])) {
402 if (i == len && strncasecmp(list, val, len) == 0) {
411 * list is a comma-separated list of case-insensitive tokens, with
412 * optional whitespace around the tokens.
413 * if val appears on the list of tokens, it is removed from the list,
414 * and the new list is returned.
416 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
424 while (list != NULL) {
425 p = ap_strchr_c(list, ',');
430 } while (apr_isspace(*p));
436 while (i > 0 && apr_isspace(list[i - 1])) {
439 if (i == len && strncasecmp(list, val, len) == 0) {
444 new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
447 new = apr_pstrndup(pool, list, i);
456 * Converts 8 hex digits to a time integer
458 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
463 for (i = 0, j = 0; i < 8; i++) {
466 if (apr_isdigit(ch)) {
469 else if (apr_isupper(ch)) {
470 j |= ch - ('A' - 10);
473 j |= ch - ('a' - 10);
476 if (j == 0xffffffff) {
477 return -1; /* so that it works with 8-byte ints */
485 * Converts a time integer to 8 hex digits
487 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
492 for (i = 7; i >= 0; i--) {
496 y[i] = ch + ('A' - 10);
505 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
507 apr_table_setn(r->notes, "error-notes",
509 "The proxy server could not handle the request "
510 "<em><a href=\"", ap_escape_html(r->pool, r->uri),
511 "\">", ap_escape_html(r->pool, r->method),
513 ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
515 ap_escape_html(r->pool, message),
516 "</strong></p>", NULL));
518 /* Allow "error-notes" string to be printed by ap_send_error_response() */
519 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
521 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
522 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
523 "proxy: %s returned by %s", message, r->uri);
528 proxy_get_host_of_request(request_rec *r)
530 char *url, *user = NULL, *password = NULL, *err, *host;
533 if (r->hostname != NULL) {
537 /* Set url to the first char after "scheme://" */
538 if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
542 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
544 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
547 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", err);
552 return host; /* ought to return the port, too */
555 /* Return TRUE if addr represents an IP address (or an IP network address) */
556 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
558 const char *addr = This->name;
564 * if the address is given with an explicit netmask, use that
565 * Due to a deficiency in apr_inet_addr(), it is impossible to parse
566 * "partial" addresses (with less than 4 quads) correctly, i.e.
567 * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
568 * I therefore have to parse the IP address manually:
569 * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
570 * addr and mask were set by proxy_readmask()
575 * Parse IP addr manually, optionally allowing
576 * abbreviated net addresses like 192.168.
579 /* Iterate over up to 4 (dotted) quads. */
580 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
583 if (*addr == '/' && quads > 0) { /* netmask starts here. */
587 if (!apr_isdigit(*addr)) {
588 return 0; /* no digit at start of quad */
591 ip_addr[quads] = strtol(addr, &tmp, 0);
593 if (tmp == addr) { /* expected a digit, found something else */
597 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
604 if (*addr == '.' && quads != 3) {
605 ++addr; /* after the 4th quad, a dot would be illegal */
609 for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
610 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
613 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
618 bits = strtol(addr, &tmp, 0);
620 if (tmp == addr) { /* expected a digit, found something else */
626 if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
633 * Determine (i.e., "guess") netmask by counting the
634 * number of trailing .0's; reduce #quads appropriately
635 * (so that 192.168.0.0 is equivalent to 192.168.)
637 while (quads > 0 && ip_addr[quads - 1] == 0) {
641 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
646 /* every zero-byte counts as 8 zero-bits */
649 if (bits != 32) { /* no warning for fully qualified IP address */
650 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
651 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
652 inet_ntoa(This->addr), bits);
656 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
658 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
659 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
660 "Warning: NetMask and IP-Addr disagree in %s/%ld",
661 inet_ntoa(This->addr), bits);
662 This->addr.s_addr &= This->mask.s_addr;
663 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
664 " Set to %s/%ld", inet_ntoa(This->addr), bits);
668 This->matcher = proxy_match_ipaddr;
672 return (*addr == '\0'); /* okay iff we've parsed the whole string */
676 /* Return TRUE if addr represents an IP address (or an IP network address) */
677 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
680 struct in_addr addr, *ip;
681 const char *host = proxy_get_host_of_request(r);
683 if (host == NULL) { /* oops! */
687 memset(&addr, '\0', sizeof addr);
688 memset(ip_addr, '\0', sizeof ip_addr);
690 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
691 for (addr.s_addr = 0, i = 0; i < 4; ++i) {
692 /* ap_proxy_is_ipaddr() already confirmed that we have
693 * a valid octet in ip_addr[i]
695 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
698 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
700 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
702 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
703 "%s/", inet_ntoa(This->addr));
704 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
705 "%s", inet_ntoa(This->mask));
711 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
712 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
713 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
714 "%s/", inet_ntoa(This->addr));
715 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
716 "%s", inet_ntoa(This->mask));
721 struct apr_sockaddr_t *reqaddr;
723 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
726 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
727 "2)IP-NoMatch: hostname=%s msg=Host not found", host);
732 /* Try to deal with multiple IP addr's for a host */
733 /* FIXME: This needs to be able to deal with IPv6 */
735 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
736 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
738 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
739 "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
740 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
741 "%s/", inet_ntoa(This->addr));
742 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
743 "%s", inet_ntoa(This->mask));
749 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
750 "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
751 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
752 "%s/", inet_ntoa(This->addr));
753 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
754 "%s", inet_ntoa(This->mask));
757 reqaddr = reqaddr->next;
764 /* Return TRUE if addr represents a domain name */
765 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
767 char *addr = This->name;
770 /* Domain name must start with a '.' */
771 if (addr[0] != '.') {
775 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
776 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
781 if (addr[i] == ':') {
782 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
783 "@@@@ handle optional port in proxy_is_domainname()");
784 /* @@@@ handle optional port */
788 if (addr[i] != '\0') {
792 /* Strip trailing dots */
793 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
797 This->matcher = proxy_match_domainname;
801 /* Return TRUE if host "host" is in domain "domain" */
802 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
804 const char *host = proxy_get_host_of_request(r);
805 int d_len = strlen(This->name), h_len;
807 if (host == NULL) { /* some error was logged already */
811 h_len = strlen(host);
813 /* @@@ do this within the setup? */
814 /* Ignore trailing dots in domain comparison: */
815 while (d_len > 0 && This->name[d_len - 1] == '.') {
818 while (h_len > 0 && host[h_len - 1] == '.') {
822 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
825 /* Return TRUE if host represents a host name */
826 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
828 struct apr_sockaddr_t *addr;
829 char *host = This->name;
832 /* Host names must not start with a '.' */
833 if (host[0] == '.') {
836 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
837 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
839 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
843 This->hostaddr = addr;
845 /* Strip trailing dots */
846 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
850 This->matcher = proxy_match_hostname;
854 /* Return TRUE if host "host" is equal to host2 "host2" */
855 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
857 char *host = This->name;
858 const char *host2 = proxy_get_host_of_request(r);
862 if (host == NULL || host2 == NULL) {
863 return 0; /* oops! */
866 h2_len = strlen(host2);
867 h1_len = strlen(host);
870 struct apr_sockaddr_t *addr = *This->hostaddr;
872 /* Try to deal with multiple IP addr's for a host */
874 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
880 /* Ignore trailing dots in host2 comparison: */
881 while (h2_len > 0 && host2[h2_len - 1] == '.') {
884 while (h1_len > 0 && host[h1_len - 1] == '.') {
887 return h1_len == h2_len
888 && strncasecmp(host, host2, h1_len) == 0;
891 /* Return TRUE if addr is to be matched as a word */
892 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
894 This->matcher = proxy_match_word;
898 /* Return TRUE if string "str2" occurs literally in "str1" */
899 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
901 const char *host = proxy_get_host_of_request(r);
902 return host != NULL && ap_strstr_c(host, This->name) != NULL;
905 /* checks whether a host in uri_addr matches proxyblock */
906 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
907 apr_sockaddr_t *uri_addr)
910 apr_sockaddr_t * src_uri_addr = uri_addr;
911 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
912 for (j = 0; j < conf->noproxies->nelts; j++) {
913 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
914 struct apr_sockaddr_t *conf_addr = npent[j].addr;
915 uri_addr = src_uri_addr;
916 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
917 "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
918 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
919 || npent[j].name[0] == '*') {
920 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
921 "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
922 return HTTP_FORBIDDEN;
925 uri_addr = src_uri_addr;
929 apr_sockaddr_ip_get(&conf_ip, conf_addr);
930 apr_sockaddr_ip_get(&uri_ip, uri_addr);
931 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
932 "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
933 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
934 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
935 "proxy: connect to remote machine %s blocked: IP %s matched", uri_addr->hostname, conf_ip);
936 return HTTP_FORBIDDEN;
938 uri_addr = uri_addr->next;
940 conf_addr = conf_addr->next;
946 /* set up the minimal filter set */
947 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
949 ap_add_input_filter("HTTP_IN", NULL, r, c);
954 * converts a series of buckets into a string
955 * XXX: BillS says this function performs essentially the same function as
956 * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
957 * instead? I think ap_proxy_string_read() will not work properly on non ASCII
958 * (EBCDIC) machines either.
960 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
961 char *buff, apr_size_t bufflen, int *eos)
970 /* start with an empty string */
974 /* loop through each brigade */
976 /* get brigade from network one line at a time */
977 if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
983 /* loop through each bucket */
985 if (*eos || APR_BRIGADE_EMPTY(bb)) {
986 /* The connection aborted or timed out */
987 return APR_ECONNABORTED;
989 e = APR_BRIGADE_FIRST(bb);
990 if (APR_BUCKET_IS_EOS(e)) {
994 if (APR_SUCCESS != (rv = apr_bucket_read(e,
995 (const char **)&response,
1001 * is string LF terminated?
1002 * XXX: This check can be made more efficient by simply checking
1003 * if the last character in the 'response' buffer is an ASCII_LF.
1004 * See ap_rgetline() for an example.
1006 if (memchr(response, APR_ASCII_LF, len)) {
1009 /* concat strings until buff is full - then throw the data away */
1010 if (len > ((bufflen-1)-(pos-buff))) {
1011 len = (bufflen-1)-(pos-buff);
1014 memcpy(pos, response, len);
1018 APR_BUCKET_REMOVE(e);
1019 apr_bucket_destroy(e);
1027 /* unmerge an element in the table */
1028 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
1030 apr_off_t offset = 0;
1031 apr_off_t count = 0;
1034 /* get the value to unmerge */
1035 const char *initial = apr_table_get(t, key);
1039 value = apr_pstrdup(p, initial);
1041 /* remove the value from the headers */
1042 apr_table_unset(t, key);
1044 /* find each comma */
1045 while (value[count]) {
1046 if (value[count] == ',') {
1048 apr_table_add(t, key, value + offset);
1053 apr_table_add(t, key, value + offset);
1056 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1057 proxy_dir_conf *conf, const char *url)
1059 proxy_req_conf *rconf;
1060 struct proxy_alias *ent;
1065 * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1066 * after the hostname
1067 * XXX FIXME: Ensure the /uri component is a case sensitive match
1069 if (r->proxyreq != PROXYREQ_REVERSE) {
1074 if (conf->interpolate_env == 1) {
1075 rconf = ap_get_module_config(r->request_config, &proxy_module);
1076 ent = (struct proxy_alias *)rconf->raliases->elts;
1079 ent = (struct proxy_alias *)conf->raliases->elts;
1081 for (i = 0; i < conf->raliases->nelts; i++) {
1082 proxy_server_conf *sconf = (proxy_server_conf *)
1083 ap_get_module_config(r->server->module_config, &proxy_module);
1084 proxy_balancer *balancer;
1085 const char *real = ent[i].real;
1087 * First check if mapping against a balancer and see
1088 * if we have such a entity. If so, then we need to
1089 * find the particulars of the actual worker which may
1090 * or may not be the right one... basically, we need
1091 * to find which member actually handled this request.
1093 if ((strncasecmp(real, "balancer://", 11) == 0) &&
1094 (balancer = ap_proxy_get_balancer(r->pool, sconf, real))) {
1096 proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
1097 const char *urlpart = ap_strchr_c(real + 11, '/');
1102 l3 = strlen(urlpart);
1104 /* The balancer comparison is a bit trickier. Given the context
1105 * BalancerMember balancer://alias http://example.com/foo
1106 * ProxyPassReverse /bash balancer://alias/bar
1107 * translate url http://example.com/foo/bar/that to /bash/that
1109 for (n = 0; n < balancer->workers->nelts; n++) {
1110 l2 = strlen((*worker)->name);
1112 /* urlpart (l3) assuredly starts with its own '/' */
1113 if ((*worker)->name[l2 - 1] == '/')
1116 && strncasecmp((*worker)->name, url, l2) == 0
1117 && strncmp(urlpart, url + l2, l3) == 0) {
1118 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2 + l3],
1120 return ap_construct_url(r->pool, u, r);
1123 else if (l1 >= l2 && strncasecmp((*worker)->name, url, l2) == 0) {
1124 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1125 return ap_construct_url(r->pool, u, r);
1131 const char *part = url;
1133 if (real[0] == '/') {
1134 part = ap_strstr_c(url, "://");
1136 part = ap_strchr_c(part+3, '/');
1148 if (l1 >= l2 && strncasecmp(real, part, l2) == 0) {
1149 u = apr_pstrcat(r->pool, ent[i].fake, &part[l2], NULL);
1150 return ap_construct_url(r->pool, u, r);
1159 * Cookies are a bit trickier to match: we've got two substrings to worry
1160 * about, and we can't just find them with strstr 'cos of case. Regexp
1161 * matching would be an easy fix, but for better consistency with all the
1162 * other matches we'll refrain and use apr_strmatch to find path=/domain=
1163 * and stick to plain strings for the config values.
1165 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1166 proxy_dir_conf *conf, const char *str)
1168 proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1170 struct proxy_alias *ent;
1171 size_t len = strlen(str);
1172 const char *newpath = NULL;
1173 const char *newdomain = NULL;
1175 const char *domainp;
1176 const char *pathe = NULL;
1177 const char *domaine = NULL;
1178 size_t l1, l2, poffs = 0, doffs = 0;
1184 if (r->proxyreq != PROXYREQ_REVERSE) {
1189 * Find the match and replacement, but save replacing until we've done
1190 * both path and domain so we know the new strlen
1192 if ((pathp = apr_strmatch(conf->cookie_path_str, str, len)) != NULL) {
1194 poffs = pathp - str;
1195 pathe = ap_strchr_c(pathp, ';');
1196 l1 = pathe ? (pathe - pathp) : strlen(pathp);
1197 pathe = pathp + l1 ;
1198 if (conf->interpolate_env == 1) {
1199 ent = (struct proxy_alias *)rconf->cookie_paths->elts;
1202 ent = (struct proxy_alias *)conf->cookie_paths->elts;
1204 for (i = 0; i < conf->cookie_paths->nelts; i++) {
1205 l2 = strlen(ent[i].fake);
1206 if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1207 newpath = ent[i].real;
1208 pdiff = strlen(newpath) - l1;
1214 if ((domainp = apr_strmatch(conf->cookie_domain_str, str, len)) != NULL) {
1216 doffs = domainp - str;
1217 domaine = ap_strchr_c(domainp, ';');
1218 l1 = domaine ? (domaine - domainp) : strlen(domainp);
1219 domaine = domainp + l1;
1220 if (conf->interpolate_env == 1) {
1221 ent = (struct proxy_alias *)rconf->cookie_domains->elts;
1224 ent = (struct proxy_alias *)conf->cookie_domains->elts;
1226 for (i = 0; i < conf->cookie_domains->nelts; i++) {
1227 l2 = strlen(ent[i].fake);
1228 if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1229 newdomain = ent[i].real;
1230 ddiff = strlen(newdomain) - l1;
1237 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1238 l1 = strlen(newpath);
1240 l2 = strlen(newdomain);
1241 if (doffs > poffs) {
1242 memcpy(ret, str, poffs);
1243 memcpy(ret + poffs, newpath, l1);
1244 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1245 memcpy(ret + doffs + pdiff, newdomain, l2);
1246 strcpy(ret + doffs + pdiff + l2, domaine);
1249 memcpy(ret, str, doffs) ;
1250 memcpy(ret + doffs, newdomain, l2);
1251 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1252 memcpy(ret + poffs + ddiff, newpath, l1);
1253 strcpy(ret + poffs + ddiff + l1, pathe);
1257 memcpy(ret, str, poffs);
1258 memcpy(ret + poffs, newpath, l1);
1259 strcpy(ret + poffs + l1, pathe);
1264 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1265 l2 = strlen(newdomain);
1266 memcpy(ret, str, doffs);
1267 memcpy(ret + doffs, newdomain, l2);
1268 strcpy(ret + doffs+l2, domaine);
1271 ret = (char *)str; /* no change */
1278 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1279 proxy_server_conf *conf,
1282 proxy_balancer *balancer;
1283 char *c, *uri = apr_pstrdup(p, url);
1286 c = strchr(uri, ':');
1287 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1290 /* remove path from uri */
1291 if ((c = strchr(c + 3, '/'))) {
1294 balancer = (proxy_balancer *)conf->balancers->elts;
1295 for (i = 0; i < conf->balancers->nelts; i++) {
1296 if (strcasecmp(balancer->name, uri) == 0) {
1304 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1306 proxy_server_conf *conf,
1309 char *c, *q, *uri = apr_pstrdup(p, url);
1310 proxy_balancer_method *lbmethod;
1312 c = strchr(uri, ':');
1313 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1314 return "Bad syntax for a balancer name";
1315 /* remove path from uri */
1316 if ((q = strchr(c + 3, '/')))
1319 ap_str_tolower(uri);
1320 *balancer = apr_array_push(conf->balancers);
1321 memset(*balancer, 0, sizeof(proxy_balancer));
1324 * NOTE: The default method is byrequests, which we assume
1327 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1329 return "Can't find 'byrequests' lb method";
1332 (*balancer)->name = uri;
1333 (*balancer)->lbmethod = lbmethod;
1334 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1335 /* XXX Is this a right place to create mutex */
1337 if (apr_thread_mutex_create(&((*balancer)->mutex),
1338 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1339 /* XXX: Do we need to log something here */
1340 return "can not create thread mutex";
1347 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1348 proxy_server_conf *conf,
1351 proxy_worker *worker;
1352 proxy_worker *max_worker = NULL;
1356 int worker_name_length;
1361 c = ap_strchr_c(url, ':');
1362 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1366 url_copy = apr_pstrdup(p, url);
1367 url_length = strlen(url);
1370 * We need to find the start of the path and
1371 * therefore we know the length of the scheme://hostname/
1372 * part to we can force-lowercase everything up to
1373 * the start of the path.
1375 c = ap_strchr_c(c+3, '/');
1378 pathstart = url_copy + (c - url);
1380 ap_str_tolower(url_copy);
1381 min_match = strlen(url_copy);
1385 ap_str_tolower(url_copy);
1386 min_match = strlen(url_copy);
1389 worker = (proxy_worker *)conf->workers->elts;
1392 * Do a "longest match" on the worker name to find the worker that
1393 * fits best to the URL, but keep in mind that we must have at least
1394 * a minimum matching of length min_match such that
1395 * scheme://hostname[:port] matches between worker and url.
1397 for (i = 0; i < conf->workers->nelts; i++) {
1398 if ( ((worker_name_length = strlen(worker->name)) <= url_length)
1399 && (worker_name_length >= min_match)
1400 && (worker_name_length > max_match)
1401 && (strncmp(url_copy, worker->name, worker_name_length) == 0) ) {
1402 max_worker = worker;
1403 max_match = worker_name_length;
1411 static apr_status_t conn_pool_cleanup(void *theworker)
1413 proxy_worker *worker = (proxy_worker *)theworker;
1414 if (worker->cp->res) {
1415 worker->cp->pool = NULL;
1421 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1424 proxy_conn_pool *cp;
1427 * Create a connection pool's subpool.
1428 * This pool is used for connection recycling.
1429 * Once the worker is added it is never removed but
1430 * it can be disabled.
1432 apr_pool_create(&pool, p);
1433 apr_pool_tag(pool, "proxy_worker_cp");
1435 * Alloc from the same pool as worker.
1436 * proxy_conn_pool is permanently attached to the worker.
1438 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1443 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1445 proxy_server_conf *conf,
1451 rv = apr_uri_parse(p, url, &uri);
1453 if (rv != APR_SUCCESS) {
1454 return "Unable to parse URL";
1456 if (!uri.hostname || !uri.scheme) {
1457 return "URL must be absolute!";
1460 ap_str_tolower(uri.hostname);
1461 ap_str_tolower(uri.scheme);
1462 *worker = apr_array_push(conf->workers);
1463 memset(*worker, 0, sizeof(proxy_worker));
1464 (*worker)->name = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1465 (*worker)->scheme = uri.scheme;
1466 (*worker)->hostname = uri.hostname;
1467 (*worker)->port = uri.port;
1468 (*worker)->id = proxy_lb_workers;
1469 (*worker)->flush_packets = flush_off;
1470 (*worker)->flush_wait = PROXY_FLUSH_WAIT;
1471 (*worker)->smax = -1;
1472 /* Increase the total worker count */
1474 (*worker)->cp = NULL;
1475 (*worker)->mutex = NULL;
1480 PROXY_DECLARE(proxy_worker *) ap_proxy_create_worker(apr_pool_t *p)
1483 proxy_worker *worker;
1484 worker = (proxy_worker *)apr_pcalloc(p, sizeof(proxy_worker));
1485 worker->id = proxy_lb_workers;
1487 /* Increase the total worker count */
1490 worker->mutex = NULL;
1496 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer,
1497 proxy_worker *worker)
1499 proxy_worker **runtime;
1501 runtime = apr_array_push(balancer->workers);
1503 (*runtime)->id = proxy_lb_workers;
1504 /* Increase the total runtime count */
1509 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1510 proxy_balancer **balancer,
1512 proxy_server_conf *conf, char **url)
1516 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1517 if (access_status == DECLINED && *balancer == NULL) {
1518 *worker = ap_proxy_get_worker(r->pool, conf, *url);
1520 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1521 "proxy: %s: found worker %s for %s",
1522 (*worker)->scheme, (*worker)->name, *url);
1527 else if (r->proxyreq == PROXYREQ_PROXY) {
1528 if (conf->forward) {
1529 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1530 "proxy: *: found forward proxy worker for %s",
1533 *worker = conf->forward;
1537 else if (r->proxyreq == PROXYREQ_REVERSE) {
1538 if (conf->reverse) {
1539 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1540 "proxy: *: found reverse proxy worker for %s",
1543 *worker = conf->reverse;
1548 else if (access_status == DECLINED && *balancer != NULL) {
1549 /* All the workers are busy */
1550 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1551 "proxy: all workers are busy. Unable to serve %s",
1553 access_status = HTTP_SERVICE_UNAVAILABLE;
1555 return access_status;
1558 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1559 proxy_balancer *balancer,
1561 proxy_server_conf *conf)
1563 int access_status = OK;
1565 access_status = proxy_run_post_request(worker, balancer, r, conf);
1566 if (access_status == DECLINED) {
1567 access_status = OK; /* no post_request handler available */
1568 /* TODO: recycle direct worker */
1572 return access_status;
1576 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1577 const char *proxy_function,
1578 apr_sockaddr_t *backend_addr,
1579 const char *backend_name,
1580 proxy_server_conf *conf,
1588 while (backend_addr && !connected) {
1589 if ((rv = apr_socket_create(newsock, backend_addr->family,
1590 SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1591 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1592 ap_log_error(APLOG_MARK, loglevel, rv, s,
1593 "proxy: %s: error creating fam %d socket for target %s",
1595 backend_addr->family,
1598 * this could be an IPv6 address from the DNS but the
1599 * local machine won't give us an IPv6 socket; hopefully the
1600 * DNS returned an additional address to try
1602 backend_addr = backend_addr->next;
1606 if (conf->recv_buffer_size > 0 &&
1607 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1608 conf->recv_buffer_size))) {
1609 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1610 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1611 "ProxyReceiveBufferSize, using default");
1614 rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
1615 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1616 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1617 "apr_socket_opt_set(APR_TCP_NODELAY): "
1621 /* Set a timeout on the socket */
1622 if (conf->timeout_set == 1) {
1623 apr_socket_timeout_set(*newsock, conf->timeout);
1626 apr_socket_timeout_set(*newsock, s->timeout);
1629 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1630 "proxy: %s: fam %d socket created to connect to %s",
1631 proxy_function, backend_addr->family, backend_name);
1633 /* make the connection out of the socket */
1634 rv = apr_socket_connect(*newsock, backend_addr);
1636 /* if an error occurred, loop round and try again */
1637 if (rv != APR_SUCCESS) {
1638 apr_socket_close(*newsock);
1639 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1640 ap_log_error(APLOG_MARK, loglevel, rv, s,
1641 "proxy: %s: attempt to connect to %pI (%s) failed",
1645 backend_addr = backend_addr->next;
1650 return connected ? 0 : 1;
1653 static apr_status_t connection_cleanup(void *theconn)
1655 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1656 proxy_worker *worker = conn->worker;
1659 * If the connection pool is NULL the worker
1660 * cleanup has been run. Just return.
1667 /* Sanity check: Did we already return the pooled connection? */
1668 if (conn->inreslist) {
1669 ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool,
1670 "proxy: Pooled connection 0x%pp for worker %s has been"
1671 " already returned to the connection pool.", conn,
1677 /* determine if the connection need to be closed */
1678 if (conn->close || !worker->is_address_reusable || worker->disablereuse) {
1679 apr_pool_t *p = conn->pool;
1681 conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1683 conn->worker = worker;
1684 apr_pool_create(&(conn->scpool), p);
1685 apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1688 if (worker->hmax && worker->cp->res) {
1689 conn->inreslist = 1;
1690 apr_reslist_release(worker->cp->res, (void *)conn);
1695 worker->cp->conn = conn;
1698 /* Always return the SUCCESS */
1702 static void socket_cleanup(proxy_conn_rec *conn)
1705 conn->connection = NULL;
1706 apr_pool_clear(conn->scpool);
1709 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1712 apr_bucket_brigade *bb;
1716 * If we have an existing SSL connection it might be possible that the
1717 * server sent some SSL message we have not read so far (e.g. a SSL
1718 * shutdown message if the server closed the keepalive connection while
1719 * the connection was held unused in our pool).
1720 * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1721 * processed. We don't expect any data to be in the returned brigade.
1723 if (conn->sock && conn->connection) {
1724 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1725 rv = ap_get_brigade(conn->connection->input_filters, bb,
1726 AP_MODE_READBYTES, APR_NONBLOCK_READ,
1728 if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1729 socket_cleanup(conn);
1731 if (!APR_BRIGADE_EMPTY(bb)) {
1734 rv = apr_brigade_length(bb, 0, &len);
1735 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r,
1736 "proxy: SSL cleanup brigade contained %"
1737 APR_OFF_T_FMT " bytes of data.", len);
1739 apr_brigade_destroy(bb);
1744 /* reslist constructor */
1745 static apr_status_t connection_constructor(void **resource, void *params,
1750 proxy_conn_rec *conn;
1751 proxy_worker *worker = (proxy_worker *)params;
1754 * Create the subpool for each connection
1755 * This keeps the memory consumption constant
1756 * when disconnecting from backend.
1758 apr_pool_create(&ctx, pool);
1759 apr_pool_tag(ctx, "proxy_conn_pool");
1761 * Create another subpool that manages the data for the
1762 * socket and the connection member of the proxy_conn_rec struct as we
1763 * destroy this data more frequently than other data in the proxy_conn_rec
1764 * struct like hostname and addr (at least in the case where we have
1765 * keepalive connections that timed out).
1767 apr_pool_create(&scpool, ctx);
1768 apr_pool_tag(scpool, "proxy_conn_scpool");
1769 conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1772 conn->scpool = scpool;
1773 conn->worker = worker;
1775 conn->inreslist = 1;
1782 #if APR_HAS_THREADS /* only needed when threads are used */
1783 /* reslist destructor */
1784 static apr_status_t connection_destructor(void *resource, void *params,
1787 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1789 /* Destroy the pool only if not called from reslist_destroy */
1790 if (conn->worker->cp->pool) {
1791 apr_pool_destroy(conn->pool);
1799 * ap_proxy_initialize_worker_share() concerns itself
1800 * with initializing those parts of worker which
1801 * are, or could be, shared. Basically worker->s
1803 PROXY_DECLARE(void) ap_proxy_initialize_worker_share(proxy_server_conf *conf,
1804 proxy_worker *worker,
1807 proxy_worker_stat *score = NULL;
1809 if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1810 /* The worker share is already initialized */
1811 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1812 "proxy: worker %s already initialized",
1817 /* Get scoreboard slot */
1818 if (ap_scoreboard_image) {
1819 score = (proxy_worker_stat *) ap_get_scoreboard_lb(worker->id);
1821 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1822 "proxy: ap_get_scoreboard_lb(%d) failed in child %" APR_PID_T_FMT " for worker %s",
1823 worker->id, getpid(), worker->name);
1826 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1827 "proxy: grabbed scoreboard slot %d in child %" APR_PID_T_FMT " for worker %s",
1828 worker->id, getpid(), worker->name);
1832 score = (proxy_worker_stat *) apr_pcalloc(conf->pool, sizeof(proxy_worker_stat));
1833 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1834 "proxy: initialized plain memory in child %" APR_PID_T_FMT " for worker %s",
1835 getpid(), worker->name);
1839 * recheck to see if we've already been here. Possible
1840 * if proxy is using scoreboard to hold shared stats
1842 if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1843 /* The worker share is already initialized */
1844 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1845 "proxy: worker %s already initialized",
1850 if (worker->route) {
1851 strcpy(worker->s->route, worker->route);
1854 *worker->s->route = '\0';
1856 if (worker->redirect) {
1857 strcpy(worker->s->redirect, worker->redirect);
1860 *worker->s->redirect = '\0';
1863 worker->s->status |= (worker->status | PROXY_WORKER_INITIALIZED);
1867 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1875 if (worker->status & PROXY_WORKER_INITIALIZED) {
1876 /* The worker is already initialized */
1880 /* Set default parameters */
1881 if (!worker->retry_set) {
1882 worker->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1884 /* By default address is reusable unless DisableReuse is set */
1885 if (worker->disablereuse) {
1886 worker->is_address_reusable = 0;
1889 worker->is_address_reusable = 1;
1892 if (worker->cp == NULL)
1893 init_conn_pool(p, worker);
1894 if (worker->cp == NULL) {
1895 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1896 "can not create connection pool");
1897 return APR_EGENERAL;
1901 if (worker->mutex == NULL) {
1902 rv = apr_thread_mutex_create(&(worker->mutex), APR_THREAD_MUTEX_DEFAULT, p);
1903 if (rv != APR_SUCCESS) {
1904 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1905 "can not create thread mutex");
1910 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1911 if (mpm_threads > 1) {
1912 /* Set hard max to no more then mpm_threads */
1913 if (worker->hmax == 0 || worker->hmax > mpm_threads) {
1914 worker->hmax = mpm_threads;
1916 if (worker->smax == -1 || worker->smax > worker->hmax) {
1917 worker->smax = worker->hmax;
1919 /* Set min to be lower then smax */
1920 if (worker->min > worker->smax) {
1921 worker->min = worker->smax;
1925 /* This will supress the apr_reslist creation */
1926 worker->min = worker->smax = worker->hmax = 0;
1929 rv = apr_reslist_create(&(worker->cp->res),
1930 worker->min, worker->smax,
1931 worker->hmax, worker->ttl,
1932 connection_constructor, connection_destructor,
1933 worker, worker->cp->pool);
1935 apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1937 apr_pool_cleanup_null);
1939 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1940 "proxy: initialized worker %d in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1941 worker->id, getpid(), worker->hostname, worker->min,
1942 worker->hmax, worker->smax);
1944 #if (APR_MAJOR_VERSION > 0)
1945 /* Set the acquire timeout */
1946 if (rv == APR_SUCCESS && worker->acquire_set) {
1947 apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1956 rv = connection_constructor(&conn, worker, worker->cp->pool);
1957 worker->cp->conn = conn;
1959 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1960 "proxy: initialized single connection worker %d in child %" APR_PID_T_FMT " for (%s)",
1961 worker->id, getpid(), worker->hostname);
1963 if (rv == APR_SUCCESS) {
1964 worker->status |= (PROXY_WORKER_INITIALIZED);
1969 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1970 proxy_worker *worker,
1973 if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1974 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1975 "proxy: %s: retrying the worker for (%s)",
1976 proxy_function, worker->hostname);
1977 if (apr_time_now() > worker->s->error_time + worker->retry) {
1978 ++worker->s->retries;
1979 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1980 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1981 "proxy: %s: worker for (%s) has been marked for retry",
1982 proxy_function, worker->hostname);
1994 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
1995 proxy_conn_rec **conn,
1996 proxy_worker *worker,
2001 if (!PROXY_WORKER_IS_USABLE(worker)) {
2002 /* Retry the worker */
2003 ap_proxy_retry_worker(proxy_function, worker, s);
2005 if (!PROXY_WORKER_IS_USABLE(worker)) {
2006 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2007 "proxy: %s: disabled connection for (%s)",
2008 proxy_function, worker->hostname);
2009 return HTTP_SERVICE_UNAVAILABLE;
2013 if (worker->hmax && worker->cp->res) {
2014 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2019 /* create the new connection if the previous was destroyed */
2020 if (!worker->cp->conn) {
2021 connection_constructor((void **)conn, worker, worker->cp->pool);
2024 *conn = worker->cp->conn;
2025 worker->cp->conn = NULL;
2030 if (rv != APR_SUCCESS) {
2031 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2032 "proxy: %s: failed to acquire connection for (%s)",
2033 proxy_function, worker->hostname);
2034 return HTTP_SERVICE_UNAVAILABLE;
2036 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2037 "proxy: %s: has acquired connection for (%s)",
2038 proxy_function, worker->hostname);
2040 (*conn)->worker = worker;
2043 (*conn)->inreslist = 0;
2049 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2050 proxy_conn_rec *conn,
2053 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2054 "proxy: %s: has released connection for (%s)",
2055 proxy_function, conn->worker->hostname);
2056 connection_cleanup(conn);
2062 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2063 proxy_server_conf *conf,
2064 proxy_worker *worker,
2065 proxy_conn_rec *conn,
2068 const char *proxyname,
2069 apr_port_t proxyport,
2070 char *server_portstr,
2071 int server_portstr_size)
2074 apr_status_t err = APR_SUCCESS;
2075 apr_status_t uerr = APR_SUCCESS;
2078 * Break up the URL to determine the host to connect to
2081 /* we break the URL into host, port, uri */
2082 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2083 return ap_proxyerror(r, HTTP_BAD_REQUEST,
2084 apr_pstrcat(p,"URI cannot be parsed: ", *url,
2088 uri->port = apr_uri_port_of_scheme(uri->scheme);
2091 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2092 "proxy: connecting %s to %s:%d", *url, uri->hostname,
2096 * allocate these out of the specified connection pool
2097 * The scheme handler decides if this is permanent or
2098 * short living pool.
2100 /* are we connecting directly, or via a proxy? */
2102 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2103 uri->query ? uri->query : "",
2104 uri->fragment ? "#" : "",
2105 uri->fragment ? uri->fragment : "", NULL);
2108 * Make sure that we pick the the correct and valid worker.
2109 * If a single keepalive connection triggers different workers,
2110 * then we have a problem (we don't select the correct one).
2111 * Do an expensive check in this case, where we compare the
2112 * the hostnames associated between the two.
2114 * TODO: Handle this much better...
2116 if (!conn->hostname || !worker->is_address_reusable ||
2117 worker->disablereuse ||
2118 (r->connection->keepalives &&
2119 (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2120 (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2122 conn->hostname = apr_pstrdup(conn->pool, proxyname);
2123 conn->port = proxyport;
2125 * If we have a forward proxy and the protocol is HTTPS,
2126 * then we need to prepend a HTTP CONNECT request before
2127 * sending our actual HTTPS requests.
2128 * Save our real backend data for using it later during HTTP CONNECT.
2131 const char *proxy_auth;
2133 forward_info *forward = apr_pcalloc(conn->pool, sizeof(forward_info));
2134 conn->forward = forward;
2135 forward->use_http_connect = 1;
2136 forward->target_host = apr_pstrdup(conn->pool, uri->hostname);
2137 forward->target_port = uri->port;
2138 /* Do we want to pass Proxy-Authorization along?
2139 * If we haven't used it, then YES
2140 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
2141 * So let's make it configurable by env.
2142 * The logic here is the same used in mod_proxy_http.
2144 proxy_auth = apr_table_get(r->headers_in, "Proxy-Authorization");
2145 if (proxy_auth != NULL &&
2146 proxy_auth[0] != '\0' &&
2147 r->user == NULL && /* we haven't yet authenticated */
2148 apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
2149 forward->proxy_auth = apr_pstrdup(conn->pool, proxy_auth);
2154 conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2155 conn->port = uri->port;
2157 socket_cleanup(conn);
2158 err = apr_sockaddr_info_get(&(conn->addr),
2159 conn->hostname, APR_UNSPEC,
2163 else if (!worker->cp->addr) {
2164 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2165 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
2167 return HTTP_INTERNAL_SERVER_ERROR;
2171 * Worker can have the single constant backend adress.
2172 * The single DNS lookup is used once per worker.
2173 * If dynamic change is needed then set the addr to NULL
2174 * inside dynamic config to force the lookup.
2176 err = apr_sockaddr_info_get(&(worker->cp->addr),
2177 conn->hostname, APR_UNSPEC,
2180 conn->addr = worker->cp->addr;
2181 if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2182 ap_log_error(APLOG_MARK, APLOG_ERR, uerr, r->server,
2187 conn->addr = worker->cp->addr;
2189 /* Close a possible existing socket if we are told to do so */
2191 socket_cleanup(conn);
2195 if (err != APR_SUCCESS) {
2196 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2197 apr_pstrcat(p, "DNS lookup failure for: ",
2198 conn->hostname, NULL));
2201 /* Get the server port for the Via headers */
2203 server_port = ap_get_server_port(r);
2204 if (ap_is_default_port(server_port, r)) {
2205 strcpy(server_portstr,"");
2208 apr_snprintf(server_portstr, server_portstr_size, ":%d",
2212 /* check if ProxyBlock directive on this host */
2213 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2214 return ap_proxyerror(r, HTTP_FORBIDDEN,
2215 "Connect to remote machine blocked");
2217 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2218 "proxy: connected %s to %s:%d", *url, conn->hostname,
2223 #define USE_ALTERNATE_IS_CONNECTED 1
2225 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2226 #define APR_MSG_PEEK MSG_PEEK
2229 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2230 static int is_socket_connected(apr_socket_t *socket)
2232 apr_pollfd_t pfds[1];
2233 apr_status_t status;
2236 pfds[0].reqevents = APR_POLLIN;
2237 pfds[0].desc_type = APR_POLL_SOCKET;
2238 pfds[0].desc.s = socket;
2241 status = apr_poll(&pfds[0], 1, &nfds, 0);
2242 } while (APR_STATUS_IS_EINTR(status));
2244 if (status == APR_SUCCESS && nfds == 1 &&
2245 pfds[0].rtnevents == APR_POLLIN) {
2246 apr_sockaddr_t unused;
2249 /* The socket might be closed in which case
2250 * the poll will return POLLIN.
2251 * If there is no data available the socket
2254 status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2256 if (status == APR_SUCCESS && len)
2261 else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2268 static int is_socket_connected(apr_socket_t *sock)
2271 apr_size_t buffer_len = 1;
2272 char test_buffer[1];
2273 apr_status_t socket_status;
2274 apr_interval_time_t current_timeout;
2277 apr_socket_timeout_get(sock, ¤t_timeout);
2278 /* set no timeout */
2279 apr_socket_timeout_set(sock, 0);
2280 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2281 /* put back old timeout */
2282 apr_socket_timeout_set(sock, current_timeout);
2283 if (APR_STATUS_IS_EOF(socket_status)
2284 || APR_STATUS_IS_ECONNRESET(socket_status)) {
2291 #endif /* USE_ALTERNATE_IS_CONNECTED */
2295 * Send a HTTP CONNECT request to a forward proxy.
2296 * The proxy is given by "backend", the target server
2297 * is contained in the "forward" member of "backend".
2299 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2306 char buffer[HUGE_STRING_LEN];
2307 char drain_buffer[HUGE_STRING_LEN];
2308 forward_info *forward = (forward_info *)backend->forward;
2311 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2312 "proxy: CONNECT: sending the CONNECT request for %s:%d "
2313 "to the remote proxy %pI (%s)",
2314 forward->target_host, forward->target_port,
2315 backend->addr, backend->hostname);
2316 /* Create the CONNECT request */
2317 nbytes = apr_snprintf(buffer, sizeof(buffer),
2318 "CONNECT %s:%d HTTP/1.0" CRLF,
2319 forward->target_host, forward->target_port);
2320 /* Add proxy authorization from the initial request if necessary */
2321 if (forward->proxy_auth != NULL) {
2322 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2323 "Proxy-Authorization: %s" CRLF,
2324 forward->proxy_auth);
2326 /* Set a reasonable agent and send everything */
2327 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2328 "Proxy-agent: %s" CRLF CRLF,
2329 ap_get_server_banner());
2330 apr_socket_send(backend->sock, buffer, &nbytes);
2332 /* Receive the whole CONNECT response */
2333 left = sizeof(buffer) - 1;
2334 /* Read until we find the end of the headers or run out of buffer */
2337 status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2341 if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2345 } while (status == APR_SUCCESS && left > 0);
2346 /* Drain what's left */
2348 nbytes = sizeof(drain_buffer) - 1;
2349 while (status == APR_SUCCESS && nbytes) {
2350 status = apr_socket_recv(backend->sock, drain_buffer, &nbytes);
2351 buffer[nbytes] = '\0';
2352 nbytes = sizeof(drain_buffer) - 1;
2353 if (strstr(drain_buffer, "\r\n\r\n") != NULL) {
2360 /* Check for HTTP_OK response status */
2361 if (status == APR_SUCCESS) {
2363 /* Only scan for three character status code */
2366 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2367 "send_http_connect: response from the forward proxy: %s",
2370 /* Extract the returned code */
2371 if (sscanf(buffer, "HTTP/%u.%u %3s", &major, &minor, code_str) == 3) {
2372 status = atoi(code_str);
2373 if (status == HTTP_OK) {
2374 status = APR_SUCCESS;
2377 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2378 "send_http_connect: the forward proxy returned code is '%s'",
2380 status = APR_INCOMPLETE;
2389 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2390 proxy_conn_rec *conn,
2391 proxy_worker *worker,
2397 apr_sockaddr_t *backend_addr = conn->addr;
2398 apr_socket_t *newsock;
2399 void *sconf = s->module_config;
2400 proxy_server_conf *conf =
2401 (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2404 if (!(connected = is_socket_connected(conn->sock))) {
2405 socket_cleanup(conn);
2406 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2407 "proxy: %s: backend socket is disconnected.",
2411 while (backend_addr && !connected) {
2412 if ((rv = apr_socket_create(&newsock, backend_addr->family,
2413 SOCK_STREAM, APR_PROTO_TCP,
2414 conn->scpool)) != APR_SUCCESS) {
2415 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2416 ap_log_error(APLOG_MARK, loglevel, rv, s,
2417 "proxy: %s: error creating fam %d socket for target %s",
2419 backend_addr->family,
2422 * this could be an IPv6 address from the DNS but the
2423 * local machine won't give us an IPv6 socket; hopefully the
2424 * DNS returned an additional address to try
2426 backend_addr = backend_addr->next;
2429 conn->connection = NULL;
2431 if (worker->recv_buffer_size > 0 &&
2432 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2433 worker->recv_buffer_size))) {
2434 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2435 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2436 "ProxyReceiveBufferSize, using default");
2439 rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2440 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2441 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2442 "apr_socket_opt_set(APR_TCP_NODELAY): "
2446 /* Set a timeout for connecting to the backend on the socket */
2447 if (worker->conn_timeout_set) {
2448 apr_socket_timeout_set(newsock, worker->conn_timeout);
2450 else if (worker->timeout_set == 1) {
2451 apr_socket_timeout_set(newsock, worker->timeout);
2453 else if (conf->timeout_set == 1) {
2454 apr_socket_timeout_set(newsock, conf->timeout);
2457 apr_socket_timeout_set(newsock, s->timeout);
2459 /* Set a keepalive option */
2460 if (worker->keepalive) {
2461 if ((rv = apr_socket_opt_set(newsock,
2462 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2463 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2464 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2468 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2469 "proxy: %s: fam %d socket created to connect to %s",
2470 proxy_function, backend_addr->family, worker->hostname);
2472 /* make the connection out of the socket */
2473 rv = apr_socket_connect(newsock, backend_addr);
2475 /* if an error occurred, loop round and try again */
2476 if (rv != APR_SUCCESS) {
2477 apr_socket_close(newsock);
2478 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2479 ap_log_error(APLOG_MARK, loglevel, rv, s,
2480 "proxy: %s: attempt to connect to %pI (%s) failed",
2484 backend_addr = backend_addr->next;
2488 /* Set a timeout on the socket */
2489 if (worker->timeout_set == 1) {
2490 apr_socket_timeout_set(newsock, worker->timeout);
2492 else if (conf->timeout_set == 1) {
2493 apr_socket_timeout_set(newsock, conf->timeout);
2496 apr_socket_timeout_set(newsock, s->timeout);
2499 conn->sock = newsock;
2501 if (conn->forward) {
2502 forward_info *forward = (forward_info *)conn->forward;
2504 * For HTTP CONNECT we need to prepend CONNECT request before
2505 * sending our actual HTTPS requests.
2507 if (forward->use_http_connect) {
2508 rv = send_http_connect(conn, s);
2509 /* If an error occurred, loop round and try again */
2510 if (rv != APR_SUCCESS) {
2512 apr_socket_close(newsock);
2513 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2514 ap_log_error(APLOG_MARK, loglevel, rv, s,
2515 "proxy: %s: attempt to connect to %s:%d "
2516 "via http CONNECT through %pI (%s) failed",
2518 forward->target_host, forward->target_port,
2519 backend_addr, worker->hostname);
2520 backend_addr = backend_addr->next;
2529 * Put the entire worker to error state if
2530 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2531 * Altrough some connections may be alive
2532 * no further connections to the worker could be made
2534 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2535 !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2536 worker->s->status |= PROXY_WORKER_IN_ERROR;
2537 worker->s->error_time = apr_time_now();
2538 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2539 "ap_proxy_connect_backend disabling worker for (%s)",
2543 if (worker->s->retries) {
2545 * A worker came back. So here is where we need to
2546 * either reset all params to initial conditions or
2547 * apply some sort of aging
2550 worker->s->error_time = 0;
2551 worker->s->retries = 0;
2553 return connected ? OK : DECLINED;
2556 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2557 proxy_conn_rec *conn,
2561 apr_sockaddr_t *backend_addr = conn->addr;
2563 apr_interval_time_t current_timeout;
2564 apr_bucket_alloc_t *bucket_alloc;
2566 if (conn->connection) {
2570 bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2572 * The socket is now open, create a new backend server connection
2574 conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2578 if (!conn->connection) {
2580 * the peer reset the connection already; ap_run_create_connection()
2583 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2584 s, "proxy: %s: an error occurred creating a "
2585 "new connection to %pI (%s)", proxy_function,
2586 backend_addr, conn->hostname);
2587 /* XXX: Will be closed when proxy_conn is closed */
2588 socket_cleanup(conn);
2589 return HTTP_INTERNAL_SERVER_ERROR;
2592 /* For ssl connection to backend */
2594 if (!ap_proxy_ssl_enable(conn->connection)) {
2595 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2596 s, "proxy: %s: failed to enable ssl support "
2597 "for %pI (%s)", proxy_function,
2598 backend_addr, conn->hostname);
2599 return HTTP_INTERNAL_SERVER_ERROR;
2603 /* TODO: See if this will break FTP */
2604 ap_proxy_ssl_disable(conn->connection);
2607 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2608 "proxy: %s: connection complete to %pI (%s)",
2609 proxy_function, backend_addr, conn->hostname);
2612 * save the timeout of the socket because core_pre_connection
2613 * will set it to base_server->timeout
2614 * (core TimeOut directive).
2616 apr_socket_timeout_get(conn->sock, ¤t_timeout);
2617 /* set up the connection filters */
2618 rc = ap_run_pre_connection(conn->connection, conn->sock);
2619 if (rc != OK && rc != DONE) {
2620 conn->connection->aborted = 1;
2621 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2622 "proxy: %s: pre_connection setup failed (%d)",
2623 proxy_function, rc);
2626 apr_socket_timeout_set(conn->sock, current_timeout);
2631 int ap_proxy_lb_workers(void)
2634 * Since we can't resize the scoreboard when reconfiguring, we
2635 * have to impose a limit on the number of workers, we are
2636 * able to reconfigure to.
2638 if (!lb_workers_limit)
2639 lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2640 return lb_workers_limit;
2643 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2644 apr_bucket_brigade *brigade)
2647 conn_rec *c = r->connection;
2651 * If this is a subrequest, then prevent also caching of the main
2655 r->main->no_cache = 1;
2656 e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2658 APR_BRIGADE_INSERT_TAIL(brigade, e);
2659 e = apr_bucket_eos_create(c->bucket_alloc);
2660 APR_BRIGADE_INSERT_TAIL(brigade, e);
2664 * Transform buckets from one bucket allocator to another one by creating a
2665 * transient bucket for each data bucket and let it use the data read from
2666 * the old bucket. Metabuckets are transformed by just recreating them.
2667 * Attention: Currently only the following bucket types are handled:
2673 * If an other bucket type is found its type is logged as a debug message
2674 * and APR_EGENERAL is returned.
2676 PROXY_DECLARE(apr_status_t)
2677 ap_proxy_buckets_lifetime_transform(request_rec *r, apr_bucket_brigade *from,
2678 apr_bucket_brigade *to)
2684 apr_status_t rv = APR_SUCCESS;
2686 apr_brigade_cleanup(to);
2687 for (e = APR_BRIGADE_FIRST(from);
2688 e != APR_BRIGADE_SENTINEL(from);
2689 e = APR_BUCKET_NEXT(e)) {
2690 if (!APR_BUCKET_IS_METADATA(e)) {
2691 apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
2692 new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
2693 APR_BRIGADE_INSERT_TAIL(to, new);
2695 else if (APR_BUCKET_IS_FLUSH(e)) {
2696 new = apr_bucket_flush_create(r->connection->bucket_alloc);
2697 APR_BRIGADE_INSERT_TAIL(to, new);
2699 else if (APR_BUCKET_IS_EOS(e)) {
2700 new = apr_bucket_eos_create(r->connection->bucket_alloc);
2701 APR_BRIGADE_INSERT_TAIL(to, new);
2704 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2705 "proxy: Unhandled bucket type of type %s in"
2706 " ap_proxy_buckets_lifetime_transform", e->type->name);