1 /* Copyright 1999-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 /* Utility routines for Apache proxy */
17 #include "mod_proxy.h"
19 #include "scoreboard.h"
20 #include "apr_version.h"
23 #include <unistd.h> /* for getpid() */
26 #if (APR_MAJOR_VERSION < 1)
27 #undef apr_socket_create
28 #define apr_socket_create apr_socket_create_ex
31 /* Global balancer counter */
32 static int lb_workers = 0;
33 static int lb_workers_limit = 0;
35 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
36 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
37 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
38 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
40 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
41 (request_rec *r, request_rec *pr), (r, pr),
44 /* already called in the knowledge that the characters are hex digits */
45 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
49 #if !APR_CHARSET_EBCDIC
53 else if (apr_isupper(ch))
62 else if (apr_isupper(ch))
67 #else /*APR_CHARSET_EBCDIC*/
68 /* we assume that the hex value refers to an ASCII character
69 * so convert to EBCDIC so that it makes sense locally;
73 * client specifies %20 in URL to refer to a space char;
74 * at this point we're called with EBCDIC "20"; after turning
75 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
76 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
81 if (1 == sscanf(x, "%2x", &i)) {
83 ap_xlate_proto_from_ascii(buf, 1);
89 #endif /*APR_CHARSET_EBCDIC*/
92 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
94 #if !APR_CHARSET_EBCDIC
100 x[1] = ('A' - 10) + i;
106 x[2] = ('A' - 10) + i;
109 #else /*APR_CHARSET_EBCDIC*/
110 static const char ntoa[] = { "0123456789ABCDEF" };
116 ap_xlate_proto_to_ascii(buf, 1);
119 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
120 x[2] = ntoa[buf[0] & 0x0F];
122 #endif /*APR_CHARSET_EBCDIC*/
126 * canonicalise a URL-encoded string
130 * Convert a URL-encoded string to canonical form.
131 * It decodes characters which need not be encoded,
132 * and encodes those which must be encoded, and does not touch
133 * those which must not be touched.
135 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len, enum enctype t,
140 char *allowed; /* characters which should not be encoded */
141 char *reserved; /* characters which much not be en/de-coded */
143 /* N.B. in addition to :@&=, this allows ';' in an http path
144 * and '?' in an ftp path -- this may be revised
146 * Also, it makes a '+' character in a search string reserved, as
147 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
148 * it only permits ; / ? : @ = & as reserved chars.)
151 allowed = "$-_.+!*'(),;:@&=";
152 else if (t == enc_search)
153 allowed = "$-_.!*'(),;:@&=";
154 else if (t == enc_user)
155 allowed = "$-_.+!*'(),;@&=";
156 else if (t == enc_fpath)
157 allowed = "$-_.+!*'(),?:@&=";
158 else /* if (t == enc_parm) */
159 allowed = "$-_.+!*'(),?/:@&=";
163 else if (t == enc_search)
168 y = apr_palloc(p, 3 * len + 1);
170 for (i = 0, j = 0; i < len; i++, j++) {
171 /* always handle '/' first */
173 if (strchr(reserved, ch)) {
177 /* decode it if not already done */
178 if (isenc && ch == '%') {
179 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2]))
181 ch = ap_proxy_hex2c(&x[i + 1]);
183 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
184 ap_proxy_c2hex(ch, &y[j]);
189 /* recode it, if necessary */
190 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
191 ap_proxy_c2hex(ch, &y[j]);
202 * Parses network-location.
203 * urlp on input the URL; on output the path, after the leading /
204 * user NULL if no user/password permitted
205 * password holder for password
206 * host holder for host
207 * port port number; only set if one is supplied.
209 * Returns an error string.
211 PROXY_DECLARE(char *)
212 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
213 char **passwordp, char **hostp, apr_port_t *port)
215 char *addr, *scope_id, *strp, *host, *url = *urlp;
216 char *user = NULL, *password = NULL;
220 if (url[0] != '/' || url[1] != '/')
221 return "Malformed URL";
223 url = strchr(host, '/');
227 *(url++) = '\0'; /* skip seperating '/' */
229 /* find _last_ '@' since it might occur in user/password part */
230 strp = strrchr(host, '@');
238 strp = strchr(user, ':');
241 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1);
242 if (password == NULL)
243 return "Bad %-escape in URL (password)";
246 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1);
248 return "Bad %-escape in URL (username)";
253 if (passwordp != NULL) {
254 *passwordp = password;
257 /* Parse the host string to separate host portion from optional port.
258 * Perform range checking on port.
260 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
261 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
262 return "Invalid host/port";
264 if (tmp_port != 0) { /* only update caller's port if port was specified */
268 ap_str_tolower(addr); /* DNS names are case-insensitive */
276 static const char * const lwday[7] =
277 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
280 * If the date is a valid RFC 850 date or asctime() date, then it
281 * is converted to the RFC 1123 format, otherwise it is not modified.
282 * This routine is not very fast at doing conversions, as it uses
283 * sscanf and sprintf. However, if the date is already correctly
284 * formatted, then it exits very quickly.
286 PROXY_DECLARE(const char *)
287 ap_proxy_date_canon(apr_pool_t *p, const char *x1)
289 char *x = apr_pstrdup(p, x1);
290 int wk, mday, year, hour, min, sec, mon;
291 char *q, month[4], zone[4], week[4];
294 /* check for RFC 850 date */
295 if (q != NULL && q - x > 3 && q[1] == ' ') {
297 for (wk = 0; wk < 7; wk++)
298 if (strcmp(x, lwday[wk]) == 0)
302 return x; /* not a valid date */
303 if (q[4] != '-' || q[8] != '-' || q[11] != ' ' || q[14] != ':' ||
304 q[17] != ':' || strcmp(&q[20], " GMT") != 0)
306 if (sscanf(q + 2, "%u-%3s-%u %u:%u:%u %3s", &mday, month, &year,
307 &hour, &min, &sec, zone) != 7)
315 /* check for acstime() date */
316 if (x[3] != ' ' || x[7] != ' ' || x[10] != ' ' || x[13] != ':' ||
317 x[16] != ':' || x[19] != ' ' || x[24] != '\0')
319 if (sscanf(x, "%3s %3s %u %u:%u:%u %u", week, month, &mday, &hour,
320 &min, &sec, &year) != 7)
322 for (wk = 0; wk < 7; wk++)
323 if (strcmp(week, apr_day_snames[wk]) == 0)
330 for (mon = 0; mon < 12; mon++)
331 if (strcmp(month, apr_month_snames[mon]) == 0)
336 q = apr_palloc(p, 30);
337 apr_snprintf(q, 30, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", apr_day_snames[wk],
338 mday, apr_month_snames[mon], year, hour, min, sec);
342 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
344 request_rec *rp = apr_pcalloc(c->pool, sizeof(*r));
347 rp->status = HTTP_OK;
349 rp->headers_in = apr_table_make(c->pool, 50);
350 rp->subprocess_env = apr_table_make(c->pool, 50);
351 rp->headers_out = apr_table_make(c->pool, 12);
352 rp->err_headers_out = apr_table_make(c->pool, 5);
353 rp->notes = apr_table_make(c->pool, 5);
355 rp->server = r->server;
356 rp->proxyreq = r->proxyreq;
357 rp->request_time = r->request_time;
359 rp->output_filters = c->output_filters;
360 rp->input_filters = c->input_filters;
361 rp->proto_output_filters = c->output_filters;
362 rp->proto_input_filters = c->input_filters;
364 rp->request_config = ap_create_request_config(c->pool);
365 proxy_run_create_req(r, rp);
372 * list is a comma-separated list of case-insensitive tokens, with
373 * optional whitespace around the tokens.
374 * The return returns 1 if the token val is found in the list, or 0
377 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
384 while (list != NULL) {
385 p = ap_strchr_c(list, ',');
390 while (apr_isspace(*p));
395 while (i > 0 && apr_isspace(list[i - 1]))
397 if (i == len && strncasecmp(list, val, len) == 0)
405 * list is a comma-separated list of case-insensitive tokens, with
406 * optional whitespace around the tokens.
407 * if val appears on the list of tokens, it is removed from the list,
408 * and the new list is returned.
410 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
418 while (list != NULL) {
419 p = ap_strchr_c(list, ',');
424 while (apr_isspace(*p));
429 while (i > 0 && apr_isspace(list[i - 1]))
431 if (i == len && strncasecmp(list, val, len) == 0) {
436 new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
438 new = apr_pstrndup(pool, list, i);
446 * Converts 8 hex digits to a time integer
448 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
453 for (i = 0, j = 0; i < 8; i++) {
458 else if (apr_isupper(ch))
459 j |= ch - ('A' - 10);
461 j |= ch - ('a' - 10);
464 return -1; /* so that it works with 8-byte ints */
470 * Converts a time integer to 8 hex digits
472 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
477 for (i = 7; i >= 0; i--) {
481 y[i] = ch + ('A' - 10);
488 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
490 apr_table_setn(r->notes, "error-notes",
492 "The proxy server could not handle the request "
493 "<em><a href=\"", ap_escape_uri(r->pool, r->uri),
494 "\">", ap_escape_html(r->pool, r->method),
496 ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
498 ap_escape_html(r->pool, message),
499 "</strong></p>", NULL));
501 /* Allow "error-notes" string to be printed by ap_send_error_response() */
502 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
504 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
505 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
506 "proxy: %s returned by %s", message, r->uri);
511 proxy_get_host_of_request(request_rec *r)
513 char *url, *user = NULL, *password = NULL, *err, *host;
516 if (r->hostname != NULL)
519 /* Set url to the first char after "scheme://" */
520 if ((url = strchr(r->uri, ':')) == NULL
521 || url[1] != '/' || url[2] != '/')
524 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
526 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
529 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
534 return host; /* ought to return the port, too */
537 /* Return TRUE if addr represents an IP address (or an IP network address) */
538 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
540 const char *addr = This->name;
545 /* if the address is given with an explicit netmask, use that */
546 /* Due to a deficiency in apr_inet_addr(), it is impossible to parse */
547 /* "partial" addresses (with less than 4 quads) correctly, i.e. */
548 /* 192.168.123 is parsed as 192.168.0.123, which is not what I want. */
549 /* I therefore have to parse the IP address manually: */
550 /*if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0) */
551 /* addr and mask were set by proxy_readmask() */
554 /* Parse IP addr manually, optionally allowing */
555 /* abbreviated net addresses like 192.168. */
557 /* Iterate over up to 4 (dotted) quads. */
558 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
561 if (*addr == '/' && quads > 0) /* netmask starts here. */
564 if (!apr_isdigit(*addr))
565 return 0; /* no digit at start of quad */
567 ip_addr[quads] = strtol(addr, &tmp, 0);
569 if (tmp == addr) /* expected a digit, found something else */
572 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
579 if (*addr == '.' && quads != 3)
580 ++addr; /* after the 4th quad, a dot would be illegal */
583 for (This->addr.s_addr = 0, i = 0; i < quads; ++i)
584 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
586 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
591 bits = strtol(addr, &tmp, 0);
593 if (tmp == addr) /* expected a digit, found something else */
598 if (bits < 0 || bits > 32) /* netmask must be between 0 and 32 */
603 /* Determine (i.e., "guess") netmask by counting the */
604 /* number of trailing .0's; reduce #quads appropriately */
605 /* (so that 192.168.0.0 is equivalent to 192.168.) */
606 while (quads > 0 && ip_addr[quads - 1] == 0)
609 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
613 /* every zero-byte counts as 8 zero-bits */
616 if (bits != 32) /* no warning for fully qualified IP address */
617 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
618 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld\n",
619 inet_ntoa(This->addr), bits);
622 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
624 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
625 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
626 "Warning: NetMask and IP-Addr disagree in %s/%ld\n",
627 inet_ntoa(This->addr), bits);
628 This->addr.s_addr &= This->mask.s_addr;
629 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
631 inet_ntoa(This->addr), bits);
635 This->matcher = proxy_match_ipaddr;
639 return (*addr == '\0'); /* okay iff we've parsed the whole string */
642 /* Return TRUE if addr represents an IP address (or an IP network address) */
643 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
646 struct in_addr addr, *ip;
647 const char *host = proxy_get_host_of_request(r);
649 if (host == NULL) /* oops! */
652 memset(&addr, '\0', sizeof addr);
653 memset(ip_addr, '\0', sizeof ip_addr);
655 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
656 for (addr.s_addr = 0, i = 0; i < 4; ++i)
657 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
659 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
661 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
662 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
663 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
664 "%s/", inet_ntoa(This->addr));
665 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
666 "%s", inet_ntoa(This->mask));
672 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
673 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
674 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
675 "%s/", inet_ntoa(This->addr));
676 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
677 "%s", inet_ntoa(This->mask));
682 struct apr_sockaddr_t *reqaddr;
684 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
687 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
688 "2)IP-NoMatch: hostname=%s msg=Host not found",
694 /* Try to deal with multiple IP addr's for a host */
695 /* FIXME: This needs to be able to deal with IPv6 */
697 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
698 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
700 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701 "3)IP-Match: %s[%s] <-> ", host,
703 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
704 "%s/", inet_ntoa(This->addr));
705 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
706 "%s", inet_ntoa(This->mask));
712 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
713 "3)IP-NoMatch: %s[%s] <-> ", host,
715 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
716 "%s/", inet_ntoa(This->addr));
717 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
718 "%s", inet_ntoa(This->mask));
721 reqaddr = reqaddr->next;
728 /* Return TRUE if addr represents a domain name */
729 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
731 char *addr = This->name;
734 /* Domain name must start with a '.' */
738 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
739 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i)
743 if (addr[i] == ':') {
744 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
745 "@@@@ handle optional port in proxy_is_domainname()");
746 /* @@@@ handle optional port */
753 /* Strip trailing dots */
754 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
757 This->matcher = proxy_match_domainname;
761 /* Return TRUE if host "host" is in domain "domain" */
762 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
764 const char *host = proxy_get_host_of_request(r);
765 int d_len = strlen(This->name), h_len;
767 if (host == NULL) /* some error was logged already */
770 h_len = strlen(host);
772 /* @@@ do this within the setup? */
773 /* Ignore trailing dots in domain comparison: */
774 while (d_len > 0 && This->name[d_len - 1] == '.')
776 while (h_len > 0 && host[h_len - 1] == '.')
779 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
782 /* Return TRUE if host represents a host name */
783 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
785 struct apr_sockaddr_t *addr;
786 char *host = This->name;
789 /* Host names must not start with a '.' */
793 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
794 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
796 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS)
799 This->hostaddr = addr;
801 /* Strip trailing dots */
802 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i)
805 This->matcher = proxy_match_hostname;
809 /* Return TRUE if host "host" is equal to host2 "host2" */
810 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
812 char *host = This->name;
813 const char *host2 = proxy_get_host_of_request(r);
817 if (host == NULL || host2 == NULL)
818 return 0; /* oops! */
820 h2_len = strlen(host2);
821 h1_len = strlen(host);
824 struct apr_sockaddr_t *addr = *This->hostaddr;
826 /* Try to deal with multiple IP addr's for a host */
828 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
834 /* Ignore trailing dots in host2 comparison: */
835 while (h2_len > 0 && host2[h2_len - 1] == '.')
837 while (h1_len > 0 && host[h1_len - 1] == '.')
839 return h1_len == h2_len
840 && strncasecmp(host, host2, h1_len) == 0;
843 /* Return TRUE if addr is to be matched as a word */
844 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
846 This->matcher = proxy_match_word;
850 /* Return TRUE if string "str2" occurs literally in "str1" */
851 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
853 const char *host = proxy_get_host_of_request(r);
854 return host != NULL && ap_strstr_c(host, This->name) != NULL;
857 /* checks whether a host in uri_addr matches proxyblock */
858 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
859 apr_sockaddr_t *uri_addr)
862 apr_sockaddr_t * src_uri_addr = uri_addr;
863 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
864 for (j = 0; j < conf->noproxies->nelts; j++) {
865 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
866 struct apr_sockaddr_t *conf_addr = npent[j].addr;
867 uri_addr = src_uri_addr;
868 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
869 "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
870 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
871 || npent[j].name[0] == '*') {
872 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
873 "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
874 return HTTP_FORBIDDEN;
880 apr_sockaddr_ip_get(&conf_ip, conf_addr);
881 apr_sockaddr_ip_get(&uri_ip, uri_addr);
882 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
883 "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
884 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
885 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
886 "proxy: connect to remote machine %s blocked: IP %s matched", uri_addr->hostname, conf_ip);
887 return HTTP_FORBIDDEN;
889 uri_addr = uri_addr->next;
891 conf_addr = conf_addr->next;
897 /* set up the minimal filter set */
898 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
900 ap_add_input_filter("HTTP_IN", NULL, r, c);
904 /* converts a series of buckets into a string
905 * XXX: BillS says this function performs essentially the same function as
906 * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
907 * instead? I think ap_proxy_string_read() will not work properly on non ASCII
908 * (EBCDIC) machines either.
910 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
911 char *buff, apr_size_t bufflen, int *eos)
920 /* start with an empty string */
924 /* loop through each brigade */
926 /* get brigade from network one line at a time */
927 if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
933 /* loop through each bucket */
935 if (*eos || APR_BRIGADE_EMPTY(bb)) {
936 /* The connection aborted or timed out */
937 return APR_ECONNABORTED;
939 e = APR_BRIGADE_FIRST(bb);
940 if (APR_BUCKET_IS_EOS(e)) {
944 if (APR_SUCCESS != apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ)) {
947 /* is string LF terminated?
948 * XXX: This check can be made more efficient by simply checking
949 * if the last character in the 'response' buffer is an ASCII_LF.
950 * See ap_rgetline() for an example.
952 if (memchr(response, APR_ASCII_LF, len)) {
955 /* concat strings until buff is full - then throw the data away */
956 if (len > ((bufflen-1)-(pos-buff))) {
957 len = (bufflen-1)-(pos-buff);
960 pos = apr_cpystrn(pos, response, len);
963 APR_BUCKET_REMOVE(e);
964 apr_bucket_destroy(e);
971 /* unmerge an element in the table */
972 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
974 apr_off_t offset = 0;
978 /* get the value to unmerge */
979 const char *initial = apr_table_get(t, key);
983 value = apr_pstrdup(p, initial);
985 /* remove the value from the headers */
986 apr_table_unset(t, key);
988 /* find each comma */
989 while (value[count]) {
990 if (value[count] == ',') {
992 apr_table_add(t, key, value + offset);
997 apr_table_add(t, key, value + offset);
1000 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1001 proxy_server_conf *conf,
1004 proxy_balancer *balancer;
1005 char *c, *uri = apr_pstrdup(p, url);
1008 c = strchr(uri, ':');
1009 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1011 /* remove path from uri */
1012 if ((c = strchr(c + 3, '/')))
1014 balancer = (proxy_balancer *)conf->balancers->elts;
1015 for (i = 0; i < conf->balancers->nelts; i++) {
1016 if (strcasecmp(balancer->name, uri) == 0)
1023 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1025 proxy_server_conf *conf,
1028 char *c, *q, *uri = apr_pstrdup(p, url);
1029 apr_status_t rc = 0;
1031 c = strchr(uri, ':');
1032 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1033 return "Bad syntax for a balancer name";
1034 /* remove path from uri */
1035 if ((q = strchr(c + 3, '/')))
1038 ap_str_tolower(uri);
1039 *balancer = apr_array_push(conf->balancers);
1040 memset(*balancer, 0, sizeof(proxy_balancer));
1042 (*balancer)->name = uri;
1043 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_runtime_worker));
1044 /* XXX Is this a right place to create mutex */
1046 if ((rc = apr_thread_mutex_create(&((*balancer)->mutex),
1047 APR_THREAD_MUTEX_DEFAULT, p)) != APR_SUCCESS) {
1048 /* XXX: Do we need to log something here */
1049 return "can not create thread mutex";
1056 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1057 proxy_server_conf *conf,
1060 proxy_worker *worker;
1061 char *c, *uri = apr_pstrdup(p, url);
1064 c = strchr(uri, ':');
1065 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1067 /* remove path from uri */
1068 if ((c = strchr(c + 3, '/')))
1071 worker = (proxy_worker *)conf->workers->elts;
1072 for (i = 0; i < conf->workers->nelts; i++) {
1073 if (strcasecmp(worker->name, uri) == 0) {
1081 static apr_status_t conn_pool_cleanup(void *thepool)
1083 proxy_conn_pool *cp = (proxy_conn_pool *)thepool;
1084 /* Close the socket */
1089 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1092 proxy_conn_pool *cp;
1094 /* Create a connection pool's subpool.
1095 * This pool is used for connection recycling.
1096 * Once the worker is added it is never removed but
1097 * it can be disabled.
1099 apr_pool_create(&pool, p);
1100 /* Alloc from the same pool as worker.
1101 * proxy_conn_pool is permanently attached to the worker.
1103 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1106 apr_pool_cleanup_register(p, (void *)cp,
1108 apr_pool_cleanup_null);
1112 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1114 proxy_server_conf *conf,
1117 char *c, *q, *uri = apr_pstrdup(p, url);
1120 c = strchr(uri, ':');
1121 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1122 return "Bad syntax for a remote proxy server";
1123 /* remove path from uri */
1124 if ((q = strchr(c + 3, '/')))
1127 q = strchr(c + 3, ':');
1129 if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
1130 return "Bad syntax for a remote proxy server (bad port number)";
1135 ap_str_tolower(uri);
1136 *worker = apr_array_push(conf->workers);
1137 memset(*worker, 0, sizeof(proxy_worker));
1138 (*worker)->name = apr_pstrdup(p, uri);
1140 (*worker)->scheme = uri;
1141 (*worker)->hostname = c + 3;
1144 port = apr_uri_port_of_scheme((*worker)->scheme);
1145 (*worker)->port = port;
1147 init_conn_pool(p, *worker);
1153 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer, proxy_worker *worker)
1155 proxy_runtime_worker *runtime;
1157 #if PROXY_HAS_SCOREBOARD
1160 ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &mpm_daemons);
1161 /* Check if we are prefork or single child */
1162 if (worker->hmax && mpm_daemons > 1) {
1163 /* Check only if workers_limit is set */
1164 if (lb_workers_limit && (lb_workers + 1) > lb_workers_limit) {
1165 ap_log_perror(APLOG_MARK, APLOG_ERR, 0, pool,
1166 "proxy: Can not add worker (%s) to balancer (%s)."
1167 " Dynamic limit reached.",
1168 worker->name, balancer->name);
1173 runtime = apr_array_push(balancer->workers);
1174 runtime->w = worker;
1175 runtime->b = balancer;
1176 runtime->id = lb_workers;
1178 /* Increase the total runtime count */
1183 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1184 proxy_balancer **balancer,
1186 proxy_server_conf *conf, char **url)
1190 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1191 if (access_status == DECLINED && *balancer == NULL) {
1192 *worker = ap_proxy_get_worker(r->pool, conf, *url);
1197 else if (r->proxyreq == PROXYREQ_PROXY) {
1198 if (conf->forward) {
1200 *worker = conf->forward;
1205 else if (access_status == DECLINED && balancer != NULL) {
1206 /* All the workers are busy */
1207 access_status = HTTP_SERVICE_UNAVAILABLE;
1209 return access_status;
1212 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1213 proxy_balancer *balancer,
1215 proxy_server_conf *conf)
1219 access_status = proxy_run_post_request(worker, balancer, r, conf);
1226 return access_status;
1230 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1231 const char *proxy_function,
1232 apr_sockaddr_t *backend_addr,
1233 const char *backend_name,
1234 proxy_server_conf *conf,
1242 while (backend_addr && !connected) {
1243 if ((rv = apr_socket_create(newsock, backend_addr->family,
1244 SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1245 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1246 ap_log_error(APLOG_MARK, loglevel, rv, s,
1247 "proxy: %s: error creating fam %d socket for target %s",
1249 backend_addr->family,
1251 /* this could be an IPv6 address from the DNS but the
1252 * local machine won't give us an IPv6 socket; hopefully the
1253 * DNS returned an additional address to try
1255 backend_addr = backend_addr->next;
1259 #if !defined(TPF) && !defined(BEOS)
1260 if (conf->recv_buffer_size > 0 &&
1261 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1262 conf->recv_buffer_size))) {
1263 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1264 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1265 "ProxyReceiveBufferSize, using default");
1269 /* Set a timeout on the socket */
1270 if (conf->timeout_set == 1) {
1271 apr_socket_timeout_set(*newsock, conf->timeout);
1274 apr_socket_timeout_set(*newsock, s->timeout);
1277 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1278 "proxy: %s: fam %d socket created to connect to %s",
1279 proxy_function, backend_addr->family, backend_name);
1281 /* make the connection out of the socket */
1282 rv = apr_socket_connect(*newsock, backend_addr);
1284 /* if an error occurred, loop round and try again */
1285 if (rv != APR_SUCCESS) {
1286 apr_socket_close(*newsock);
1287 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1288 ap_log_error(APLOG_MARK, loglevel, rv, s,
1289 "proxy: %s: attempt to connect to %pI (%s) failed",
1293 backend_addr = backend_addr->next;
1298 return connected ? 0 : 1;
1301 static apr_status_t proxy_conn_cleanup(void *theconn)
1303 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1304 /* Close the socket */
1306 apr_socket_close(conn->sock);
1312 static apr_status_t connection_cleanup(void *theconn)
1314 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1315 proxy_worker *worker = conn->worker;
1317 /* deterimine if the connection need to be closed */
1318 if (conn->close_on_recycle) {
1320 apr_socket_close(conn->sock);
1324 if (worker->hmax && worker->cp->res) {
1325 apr_reslist_release(worker->cp->res, (void *)conn);
1330 worker->cp->conn = conn;
1333 /* Allways return the SUCCESS */
1337 /* reslist constructor */
1338 static apr_status_t connection_constructor(void **resource, void *params,
1342 proxy_conn_rec *conn;
1343 server_rec *s = (server_rec *)params;
1345 /* Create the subpool for each connection
1346 * This keeps the memory consumption constant
1347 * when disconnecting from backend.
1349 apr_pool_create(&ctx, pool);
1350 conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1354 /* register the pool cleanup */
1355 apr_pool_cleanup_register(ctx, (void *)conn,
1357 apr_pool_cleanup_null);
1359 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1360 "proxy: socket is constructed");
1365 /* reslist destructor */
1366 static apr_status_t connection_destructor(void *resource, void *params,
1369 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1373 apr_socket_close(conn->sock);
1375 apr_pool_cleanup_kill(conn->pool, conn, proxy_conn_cleanup);
1378 apr_pool_destroy(conn->pool);
1382 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1383 "proxy: socket is destructed");
1388 /* Close the connection
1389 * The proxy_conn_rec from now on can not be used
1391 PROXY_DECLARE(apr_status_t) ap_proxy_close_connection(proxy_conn_rec *conn)
1394 if (conn->worker && conn->worker->cp)
1395 conn->worker->cp->conn = NULL;
1396 return connection_destructor(conn, NULL, NULL);
1399 static apr_status_t init_conn_worker(proxy_worker *worker, server_rec *s)
1406 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1407 if (mpm_threads > 1) {
1408 /* Set hard max to no more then mpm_threads */
1409 if (worker->hmax == 0 || worker->hmax > mpm_threads)
1410 worker->hmax = mpm_threads;
1411 if (worker->smax == 0 || worker->smax > worker->hmax)
1412 worker->smax = worker->hmax;
1413 /* Set min to be lower then smax */
1414 if (worker->min > worker->smax)
1415 worker->min = worker->smax;
1416 worker->cp->nfree = worker->hmax;
1419 /* This will supress the apr_reslist creation */
1420 worker->min = worker->smax = worker->hmax = 0;
1423 rv = apr_reslist_create(&(worker->cp->res),
1424 worker->min, worker->smax,
1425 worker->hmax, worker->ttl,
1426 connection_constructor, connection_destructor,
1427 s, worker->cp->pool);
1428 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1429 "proxy: initialized worker for (%s) min=%d max=%d smax=%d",
1430 worker->hostname, worker->min, worker->hmax, worker->smax);
1432 #if (APR_MAJOR_VERSION > 0)
1433 /* Set the acquire timeout */
1434 if (rv == APR_SUCCESS && worker->acquire_set)
1435 apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1442 connection_constructor((void **)&(worker->cp->conn), s, worker->cp->pool);
1444 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1445 "proxy: initialized single connection worker for (%s)",
1452 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1453 proxy_worker *worker,
1456 if (worker->status & PROXY_WORKER_IN_ERROR) {
1457 apr_interval_time_t diff;
1458 apr_time_t now = apr_time_now();
1459 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1460 "proxy: %s: retrying the worker for (%s)",
1461 proxy_function, worker->hostname);
1463 diff = worker->retry;
1465 diff = apr_time_from_sec((60 + 60 * worker->retries++));
1466 if (now > worker->error_time + diff) {
1467 worker->status &= ~PROXY_WORKER_IN_ERROR;
1468 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1469 "proxy: %s: worker for (%s) has been marked for retry",
1470 proxy_function, worker->hostname);
1480 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
1481 proxy_conn_rec **conn,
1482 proxy_worker *worker,
1487 if (!(worker->status & PROXY_WORKER_INITIALIZED)) {
1488 if ((rv = init_conn_worker(worker, s)) != APR_SUCCESS) {
1489 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1490 "proxy: %s: failed to initialize worker for (%s)",
1491 proxy_function, worker->hostname);
1492 return HTTP_INTERNAL_SERVER_ERROR;
1494 worker->status |= PROXY_WORKER_INITIALIZED;
1497 if (!PROXY_WORKER_IS_USABLE(worker)) {
1498 /* Retry the worker */
1499 ap_proxy_retry_worker(proxy_function, worker, s);
1501 if (!PROXY_WORKER_IS_USABLE(worker)) {
1502 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1503 "proxy: %s: disabled connection for (%s)",
1504 proxy_function, worker->hostname);
1505 return HTTP_SERVICE_UNAVAILABLE;
1510 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
1515 /* create the new connection if the previous was destroyed */
1516 if (!worker->cp->conn)
1517 connection_constructor((void **)conn, s, worker->cp->pool);
1519 *conn = worker->cp->conn;
1520 worker->cp->conn = NULL;
1525 if (rv != APR_SUCCESS) {
1526 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1527 "proxy: %s: failed to acquire connection for (%s)",
1528 proxy_function, worker->hostname);
1529 return HTTP_SERVICE_UNAVAILABLE;
1531 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1532 "proxy: %s: has acquired connection for (%s)",
1533 proxy_function, worker->hostname);
1535 (*conn)->worker = worker;
1540 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
1541 proxy_conn_rec *conn,
1544 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1545 "proxy: %s: has released connection for (%s)",
1546 proxy_function, conn->worker->hostname);
1547 /* If there is a connection kill it's cleanup */
1548 if (conn->connection)
1549 apr_pool_cleanup_kill(conn->connection->pool, conn, connection_cleanup);
1550 connection_cleanup(conn);
1551 conn->connection = NULL;
1557 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
1558 proxy_server_conf *conf,
1559 proxy_worker *worker,
1560 proxy_conn_rec *conn,
1564 const char *proxyname,
1565 apr_port_t proxyport,
1566 char *server_portstr,
1567 int server_portstr_size)
1570 apr_status_t err = APR_SUCCESS;
1572 * Break up the URL to determine the host to connect to
1575 /* we break the URL into host, port, uri */
1576 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
1577 return ap_proxyerror(r, HTTP_BAD_REQUEST,
1578 apr_pstrcat(p,"URI cannot be parsed: ", *url,
1582 uri->port = apr_uri_port_of_scheme(uri->scheme);
1585 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1586 "proxy: connecting %s to %s:%d", *url, uri->hostname,
1589 /* allocate these out of the specified connection pool
1590 * The scheme handler decides if this is permanent or
1591 * short living pool.
1593 /* are we connecting directly, or via a proxy? */
1595 conn->hostname = apr_pstrdup(ppool, proxyname);
1596 conn->port = proxyport;
1598 conn->hostname = apr_pstrdup(ppool, uri->hostname);
1599 conn->port = uri->port;
1600 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
1601 uri->query ? uri->query : "",
1602 uri->fragment ? "#" : "",
1603 uri->fragment ? uri->fragment : "", NULL);
1606 /* TODO: add address cache for forward proxies */
1607 conn->addr = worker->cp->addr;
1608 if (r->proxyreq == PROXYREQ_PROXY) {
1609 err = apr_sockaddr_info_get(&(conn->addr),
1610 conn->hostname, APR_UNSPEC,
1614 else if (!worker->cp->addr) {
1615 /* Worker can have the single constant backend adress.
1616 * The single DNS lookup is used once per worker.
1617 * If dynamic change is needed then set the addr to NULL
1618 * inside dynamic config to force the lookup.
1620 err = apr_sockaddr_info_get(&(worker->cp->addr),
1621 conn->hostname, APR_UNSPEC,
1624 conn->addr = worker->cp->addr;
1626 if (err != APR_SUCCESS) {
1627 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1628 apr_pstrcat(p, "DNS lookup failure for: ",
1629 conn->hostname, NULL));
1632 /* Get the server port for the Via headers */
1634 server_port = ap_get_server_port(r);
1635 if (ap_is_default_port(server_port, r)) {
1636 strcpy(server_portstr,"");
1638 apr_snprintf(server_portstr, server_portstr_size, ":%d",
1643 /* check if ProxyBlock directive on this host */
1644 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
1645 return ap_proxyerror(r, HTTP_FORBIDDEN,
1646 "Connect to remote machine blocked");
1651 static int is_socket_connected(apr_socket_t *sock)
1654 apr_size_t buffer_len = 1;
1655 char test_buffer[1];
1656 apr_status_t socket_status;
1657 apr_interval_time_t current_timeout;
1660 apr_socket_timeout_get(sock, ¤t_timeout);
1661 /* set no timeout */
1662 apr_socket_timeout_set(sock, 0);
1663 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
1664 /* put back old timeout */
1665 apr_socket_timeout_set(sock, current_timeout);
1666 if (APR_STATUS_IS_EOF(socket_status))
1672 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
1673 proxy_conn_rec *conn,
1674 proxy_worker *worker,
1680 apr_sockaddr_t *backend_addr = conn->addr;
1681 apr_socket_t *newsock;
1684 /* This increases the connection pool size
1685 * but the number of dropped connections is
1686 * relatively small compared to connection lifetime
1688 if (!(connected = is_socket_connected(conn->sock))) {
1689 apr_socket_close(conn->sock);
1693 while (backend_addr && !connected) {
1694 if ((rv = apr_socket_create(&newsock, backend_addr->family,
1695 SOCK_STREAM, APR_PROTO_TCP,
1696 conn->pool)) != APR_SUCCESS) {
1697 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1698 ap_log_error(APLOG_MARK, loglevel, rv, s,
1699 "proxy: %s: error creating fam %d socket for target %s",
1701 backend_addr->family,
1703 /* this could be an IPv6 address from the DNS but the
1704 * local machine won't give us an IPv6 socket; hopefully the
1705 * DNS returned an additional address to try
1707 backend_addr = backend_addr->next;
1711 #if !defined(TPF) && !defined(BEOS)
1712 if (worker->recv_buffer_size > 0 &&
1713 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
1714 worker->recv_buffer_size))) {
1715 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1716 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1717 "ProxyReceiveBufferSize, using default");
1721 /* Set a timeout on the socket */
1722 if (worker->timeout_set == 1) {
1723 apr_socket_timeout_set(newsock, worker->timeout);
1726 apr_socket_timeout_set(newsock, s->timeout);
1728 /* Set a keepalive option */
1729 if (worker->keepalive) {
1730 if ((rv = apr_socket_opt_set(newsock,
1731 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
1732 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1733 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
1737 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1738 "proxy: %s: fam %d socket created to connect to %s",
1739 proxy_function, backend_addr->family, worker->hostname);
1741 /* make the connection out of the socket */
1742 rv = apr_socket_connect(newsock, backend_addr);
1744 /* if an error occurred, loop round and try again */
1745 if (rv != APR_SUCCESS) {
1746 apr_socket_close(newsock);
1747 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1748 ap_log_error(APLOG_MARK, loglevel, rv, s,
1749 "proxy: %s: attempt to connect to %pI (%s) failed",
1753 backend_addr = backend_addr->next;
1757 conn->sock = newsock;
1760 /* Put the entire worker to error state if
1761 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
1762 * Altrough some connections may be alive
1763 * no further connections to the worker could be made
1765 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
1766 !(worker->status & PROXY_WORKER_IGNORE_ERRORS)) {
1767 worker->status |= PROXY_WORKER_IN_ERROR;
1768 worker->error_time = apr_time_now();
1769 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1770 "ap_proxy_connect_backend disabling worker for (%s)",
1774 worker->error_time = 0;
1775 worker->retries = 0;
1777 return connected ? OK : DECLINED;
1780 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
1781 proxy_conn_rec *conn,
1785 apr_sockaddr_t *backend_addr = conn->addr;
1787 /* The socket is now open, create a new backend server connection
1790 conn->connection = ap_run_create_connection(c->pool, s, conn->sock,
1794 if (!conn->connection) {
1795 /* the peer reset the connection already; ap_run_create_connection()
1798 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1799 s, "proxy: %s: an error occurred creating a "
1800 "new connection to %pI (%s)", proxy_function,
1801 backend_addr, conn->hostname);
1802 /* XXX: Will be closed when proxy_conn is closed */
1803 apr_socket_close(conn->sock);
1805 return HTTP_INTERNAL_SERVER_ERROR;
1807 /* register the connection cleanup to client connection
1808 * so that the connection can be closed or reused
1810 apr_pool_cleanup_register(c->pool, (void *)conn,
1812 apr_pool_cleanup_null);
1814 /* For ssl connection to backend */
1816 if (!ap_proxy_ssl_enable(conn->connection)) {
1817 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
1818 s, "proxy: %s: failed to enable ssl support "
1819 "for %pI (%s)", proxy_function,
1820 backend_addr, conn->hostname);
1821 return HTTP_INTERNAL_SERVER_ERROR;
1825 /* TODO: See if this will break FTP */
1826 ap_proxy_ssl_disable(conn->connection);
1829 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1830 "proxy: %s: connection complete to %pI (%s)",
1831 proxy_function, backend_addr, conn->hostname);
1833 /* set up the connection filters */
1834 ap_run_pre_connection(conn->connection, conn->sock);
1839 PROXY_DECLARE(int) ap_proxy_lb_workers(void)
1841 /* Set the dynamic #workers limit */
1842 lb_workers_limit = lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
1843 return lb_workers_limit;