1 /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * 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
32 /* Global balancer counter */
33 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
34 static int lb_workers_limit = 0;
36 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
37 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
38 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
39 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
41 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
42 (request_rec *r, request_rec *pr), (r, pr),
45 /* already called in the knowledge that the characters are hex digits */
46 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
50 #if !APR_CHARSET_EBCDIC
54 else if (apr_isupper(ch))
63 else if (apr_isupper(ch))
68 #else /*APR_CHARSET_EBCDIC*/
70 * we assume that the hex value refers to an ASCII character
71 * so convert to EBCDIC so that it makes sense locally;
75 * client specifies %20 in URL to refer to a space char;
76 * at this point we're called with EBCDIC "20"; after turning
77 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
78 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
83 if (1 == sscanf(x, "%2x", &i)) {
85 ap_xlate_proto_from_ascii(buf, 1);
91 #endif /*APR_CHARSET_EBCDIC*/
94 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
96 #if !APR_CHARSET_EBCDIC
100 i = (ch & 0xF0) >> 4;
102 x[1] = ('A' - 10) + i;
108 x[2] = ('A' - 10) + i;
111 #else /*APR_CHARSET_EBCDIC*/
112 static const char ntoa[] = { "0123456789ABCDEF" };
118 ap_xlate_proto_to_ascii(buf, 1);
121 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
122 x[2] = ntoa[buf[0] & 0x0F];
124 #endif /*APR_CHARSET_EBCDIC*/
128 * canonicalise a URL-encoded string
132 * Convert a URL-encoded string to canonical form.
133 * It decodes characters which need not be encoded,
134 * and encodes those which must be encoded, and does not touch
135 * those which must not be touched.
137 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len, enum enctype t,
138 int forcedec, int proxyreq)
142 char *allowed; /* characters which should not be encoded */
143 char *reserved; /* characters which much not be en/de-coded */
146 * N.B. in addition to :@&=, this allows ';' in an http path
147 * and '?' in an ftp path -- this may be revised
149 * Also, it makes a '+' character in a search string reserved, as
150 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
151 * it only permits ; / ? : @ = & as reserved chars.)
154 allowed = "$-_.+!*'(),;:@&=";
155 else if (t == enc_search)
156 allowed = "$-_.!*'(),;:@&=";
157 else if (t == enc_user)
158 allowed = "$-_.+!*'(),;@&=";
159 else if (t == enc_fpath)
160 allowed = "$-_.+!*'(),?:@&=";
161 else /* if (t == enc_parm) */
162 allowed = "$-_.+!*'(),?/:@&=";
166 else if (t == enc_search)
171 y = apr_palloc(p, 3 * len + 1);
173 for (i = 0, j = 0; i < len; i++, j++) {
174 /* always handle '/' first */
176 if (strchr(reserved, ch)) {
181 * decode it if not already done. do not decode reverse proxied URLs
182 * unless specifically forced
184 if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
185 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2]))
187 ch = ap_proxy_hex2c(&x[i + 1]);
189 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
190 ap_proxy_c2hex(ch, &y[j]);
195 /* recode it, if necessary */
196 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
197 ap_proxy_c2hex(ch, &y[j]);
208 * Parses network-location.
209 * urlp on input the URL; on output the path, after the leading /
210 * user NULL if no user/password permitted
211 * password holder for password
212 * host holder for host
213 * port port number; only set if one is supplied.
215 * Returns an error string.
217 PROXY_DECLARE(char *)
218 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
219 char **passwordp, char **hostp, apr_port_t *port)
221 char *addr, *scope_id, *strp, *host, *url = *urlp;
222 char *user = NULL, *password = NULL;
226 if (url[0] != '/' || url[1] != '/')
227 return "Malformed URL";
229 url = strchr(host, '/');
233 *(url++) = '\0'; /* skip seperating '/' */
235 /* find _last_ '@' since it might occur in user/password part */
236 strp = strrchr(host, '@');
244 strp = strchr(user, ':');
247 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
248 if (password == NULL)
249 return "Bad %-escape in URL (password)";
252 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
254 return "Bad %-escape in URL (username)";
259 if (passwordp != NULL) {
260 *passwordp = password;
264 * Parse the host string to separate host portion from optional port.
265 * Perform range checking on port.
267 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
268 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
269 return "Invalid host/port";
271 if (tmp_port != 0) { /* only update caller's port if port was specified */
275 ap_str_tolower(addr); /* DNS names are case-insensitive */
283 static const char * const lwday[7] =
284 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
287 * If the date is a valid RFC 850 date or asctime() date, then it
288 * is converted to the RFC 1123 format, otherwise it is not modified.
289 * This routine is not very fast at doing conversions, as it uses
290 * sscanf and sprintf. However, if the date is already correctly
291 * formatted, then it exits very quickly.
293 PROXY_DECLARE(const char *)
294 ap_proxy_date_canon(apr_pool_t *p, const char *x1)
296 char *x = apr_pstrdup(p, x1);
297 int wk, mday, year, hour, min, sec, mon;
298 char *q, month[4], zone[4], week[4];
301 /* check for RFC 850 date */
302 if (q != NULL && q - x > 3 && q[1] == ' ') {
304 for (wk = 0; wk < 7; wk++)
305 if (strcmp(x, lwday[wk]) == 0)
309 return x; /* not a valid date */
310 if (q[4] != '-' || q[8] != '-' || q[11] != ' ' || q[14] != ':' ||
311 q[17] != ':' || strcmp(&q[20], " GMT") != 0)
313 if (sscanf(q + 2, "%u-%3s-%u %u:%u:%u %3s", &mday, month, &year,
314 &hour, &min, &sec, zone) != 7)
322 /* check for acstime() date */
323 if (x[3] != ' ' || x[7] != ' ' || x[10] != ' ' || x[13] != ':' ||
324 x[16] != ':' || x[19] != ' ' || x[24] != '\0')
326 if (sscanf(x, "%3s %3s %u %u:%u:%u %u", week, month, &mday, &hour,
327 &min, &sec, &year) != 7)
329 for (wk = 0; wk < 7; wk++)
330 if (strcmp(week, apr_day_snames[wk]) == 0)
337 for (mon = 0; mon < 12; mon++)
338 if (strcmp(month, apr_month_snames[mon]) == 0)
343 q = apr_palloc(p, 30);
344 apr_snprintf(q, 30, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", apr_day_snames[wk],
345 mday, apr_month_snames[mon], year, hour, min, sec);
349 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
351 request_rec *rp = apr_pcalloc(c->pool, sizeof(*r));
354 rp->status = HTTP_OK;
356 rp->headers_in = apr_table_make(c->pool, 50);
357 rp->subprocess_env = apr_table_make(c->pool, 50);
358 rp->headers_out = apr_table_make(c->pool, 12);
359 rp->err_headers_out = apr_table_make(c->pool, 5);
360 rp->notes = apr_table_make(c->pool, 5);
362 rp->server = r->server;
363 rp->proxyreq = r->proxyreq;
364 rp->request_time = r->request_time;
366 rp->output_filters = c->output_filters;
367 rp->input_filters = c->input_filters;
368 rp->proto_output_filters = c->output_filters;
369 rp->proto_input_filters = c->input_filters;
371 rp->request_config = ap_create_request_config(c->pool);
372 proxy_run_create_req(r, rp);
379 * list is a comma-separated list of case-insensitive tokens, with
380 * optional whitespace around the tokens.
381 * The return returns 1 if the token val is found in the list, or 0
384 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
391 while (list != NULL) {
392 p = ap_strchr_c(list, ',');
397 while (apr_isspace(*p));
402 while (i > 0 && apr_isspace(list[i - 1]))
404 if (i == len && strncasecmp(list, val, len) == 0)
412 * list is a comma-separated list of case-insensitive tokens, with
413 * optional whitespace around the tokens.
414 * if val appears on the list of tokens, it is removed from the list,
415 * and the new list is returned.
417 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
425 while (list != NULL) {
426 p = ap_strchr_c(list, ',');
431 while (apr_isspace(*p));
436 while (i > 0 && apr_isspace(list[i - 1]))
438 if (i == len && strncasecmp(list, val, len) == 0) {
443 new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
445 new = apr_pstrndup(pool, list, i);
453 * Converts 8 hex digits to a time integer
455 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
460 for (i = 0, j = 0; i < 8; i++) {
465 else if (apr_isupper(ch))
466 j |= ch - ('A' - 10);
468 j |= ch - ('a' - 10);
471 return -1; /* so that it works with 8-byte ints */
477 * Converts a time integer to 8 hex digits
479 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
484 for (i = 7; i >= 0; i--) {
488 y[i] = ch + ('A' - 10);
495 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
497 apr_table_setn(r->notes, "error-notes",
499 "The proxy server could not handle the request "
500 "<em><a href=\"", ap_escape_uri(r->pool, r->uri),
501 "\">", ap_escape_html(r->pool, r->method),
503 ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
505 ap_escape_html(r->pool, message),
506 "</strong></p>", NULL));
508 /* Allow "error-notes" string to be printed by ap_send_error_response() */
509 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
511 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
512 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
513 "proxy: %s returned by %s", message, r->uri);
518 proxy_get_host_of_request(request_rec *r)
520 char *url, *user = NULL, *password = NULL, *err, *host;
523 if (r->hostname != NULL)
526 /* Set url to the first char after "scheme://" */
527 if ((url = strchr(r->uri, ':')) == NULL
528 || url[1] != '/' || url[2] != '/')
531 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
533 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
536 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
541 return host; /* ought to return the port, too */
544 /* Return TRUE if addr represents an IP address (or an IP network address) */
545 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
547 const char *addr = This->name;
553 * if the address is given with an explicit netmask, use that
554 * Due to a deficiency in apr_inet_addr(), it is impossible to parse
555 * "partial" addresses (with less than 4 quads) correctly, i.e.
556 * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
557 * I therefore have to parse the IP address manually:
558 * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
559 * addr and mask were set by proxy_readmask()
564 * Parse IP addr manually, optionally allowing
565 * abbreviated net addresses like 192.168.
568 /* Iterate over up to 4 (dotted) quads. */
569 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
572 if (*addr == '/' && quads > 0) /* netmask starts here. */
575 if (!apr_isdigit(*addr))
576 return 0; /* no digit at start of quad */
578 ip_addr[quads] = strtol(addr, &tmp, 0);
580 if (tmp == addr) /* expected a digit, found something else */
583 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
590 if (*addr == '.' && quads != 3)
591 ++addr; /* after the 4th quad, a dot would be illegal */
594 for (This->addr.s_addr = 0, i = 0; i < quads; ++i)
595 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
597 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
602 bits = strtol(addr, &tmp, 0);
604 if (tmp == addr) /* expected a digit, found something else */
609 if (bits < 0 || bits > 32) /* netmask must be between 0 and 32 */
615 * Determine (i.e., "guess") netmask by counting the
616 * number of trailing .0's; reduce #quads appropriately
617 * (so that 192.168.0.0 is equivalent to 192.168.)
619 while (quads > 0 && ip_addr[quads - 1] == 0)
622 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
626 /* every zero-byte counts as 8 zero-bits */
629 if (bits != 32) /* no warning for fully qualified IP address */
630 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
631 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
632 inet_ntoa(This->addr), bits);
635 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
637 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
638 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
639 "Warning: NetMask and IP-Addr disagree in %s/%ld",
640 inet_ntoa(This->addr), bits);
641 This->addr.s_addr &= This->mask.s_addr;
642 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
644 inet_ntoa(This->addr), bits);
648 This->matcher = proxy_match_ipaddr;
652 return (*addr == '\0'); /* okay iff we've parsed the whole string */
655 /* Return TRUE if addr represents an IP address (or an IP network address) */
656 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
659 struct in_addr addr, *ip;
660 const char *host = proxy_get_host_of_request(r);
662 if (host == NULL) /* oops! */
665 memset(&addr, '\0', sizeof addr);
666 memset(ip_addr, '\0', sizeof ip_addr);
668 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
669 for (addr.s_addr = 0, i = 0; i < 4; ++i)
670 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
672 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
674 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
675 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
676 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
677 "%s/", inet_ntoa(This->addr));
678 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
679 "%s", inet_ntoa(This->mask));
685 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
686 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
687 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
688 "%s/", inet_ntoa(This->addr));
689 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
690 "%s", inet_ntoa(This->mask));
695 struct apr_sockaddr_t *reqaddr;
697 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
700 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701 "2)IP-NoMatch: hostname=%s msg=Host not found",
707 /* Try to deal with multiple IP addr's for a host */
708 /* FIXME: This needs to be able to deal with IPv6 */
710 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
711 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
713 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
714 "3)IP-Match: %s[%s] <-> ", host,
716 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
717 "%s/", inet_ntoa(This->addr));
718 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
719 "%s", inet_ntoa(This->mask));
725 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
726 "3)IP-NoMatch: %s[%s] <-> ", host,
728 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
729 "%s/", inet_ntoa(This->addr));
730 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
731 "%s", inet_ntoa(This->mask));
734 reqaddr = reqaddr->next;
741 /* Return TRUE if addr represents a domain name */
742 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
744 char *addr = This->name;
747 /* Domain name must start with a '.' */
751 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
752 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i)
756 if (addr[i] == ':') {
757 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
758 "@@@@ handle optional port in proxy_is_domainname()");
759 /* @@@@ handle optional port */
766 /* Strip trailing dots */
767 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
770 This->matcher = proxy_match_domainname;
774 /* Return TRUE if host "host" is in domain "domain" */
775 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
777 const char *host = proxy_get_host_of_request(r);
778 int d_len = strlen(This->name), h_len;
780 if (host == NULL) /* some error was logged already */
783 h_len = strlen(host);
785 /* @@@ do this within the setup? */
786 /* Ignore trailing dots in domain comparison: */
787 while (d_len > 0 && This->name[d_len - 1] == '.')
789 while (h_len > 0 && host[h_len - 1] == '.')
792 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
795 /* Return TRUE if host represents a host name */
796 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
798 struct apr_sockaddr_t *addr;
799 char *host = This->name;
802 /* Host names must not start with a '.' */
806 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
807 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
809 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS)
812 This->hostaddr = addr;
814 /* Strip trailing dots */
815 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i)
818 This->matcher = proxy_match_hostname;
822 /* Return TRUE if host "host" is equal to host2 "host2" */
823 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
825 char *host = This->name;
826 const char *host2 = proxy_get_host_of_request(r);
830 if (host == NULL || host2 == NULL)
831 return 0; /* oops! */
833 h2_len = strlen(host2);
834 h1_len = strlen(host);
837 struct apr_sockaddr_t *addr = *This->hostaddr;
839 /* Try to deal with multiple IP addr's for a host */
841 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
847 /* Ignore trailing dots in host2 comparison: */
848 while (h2_len > 0 && host2[h2_len - 1] == '.')
850 while (h1_len > 0 && host[h1_len - 1] == '.')
852 return h1_len == h2_len
853 && strncasecmp(host, host2, h1_len) == 0;
856 /* Return TRUE if addr is to be matched as a word */
857 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
859 This->matcher = proxy_match_word;
863 /* Return TRUE if string "str2" occurs literally in "str1" */
864 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
866 const char *host = proxy_get_host_of_request(r);
867 return host != NULL && ap_strstr_c(host, This->name) != NULL;
870 /* checks whether a host in uri_addr matches proxyblock */
871 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
872 apr_sockaddr_t *uri_addr)
875 apr_sockaddr_t * src_uri_addr = uri_addr;
876 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
877 for (j = 0; j < conf->noproxies->nelts; j++) {
878 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
879 struct apr_sockaddr_t *conf_addr = npent[j].addr;
880 uri_addr = src_uri_addr;
881 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
882 "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
883 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
884 || npent[j].name[0] == '*') {
885 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
886 "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
887 return HTTP_FORBIDDEN;
893 apr_sockaddr_ip_get(&conf_ip, conf_addr);
894 apr_sockaddr_ip_get(&uri_ip, uri_addr);
895 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
896 "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
897 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
898 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
899 "proxy: connect to remote machine %s blocked: IP %s matched", uri_addr->hostname, conf_ip);
900 return HTTP_FORBIDDEN;
902 uri_addr = uri_addr->next;
904 conf_addr = conf_addr->next;
910 /* set up the minimal filter set */
911 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
913 ap_add_input_filter("HTTP_IN", NULL, r, c);
918 * converts a series of buckets into a string
919 * XXX: BillS says this function performs essentially the same function as
920 * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
921 * instead? I think ap_proxy_string_read() will not work properly on non ASCII
922 * (EBCDIC) machines either.
924 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
925 char *buff, apr_size_t bufflen, int *eos)
934 /* start with an empty string */
938 /* loop through each brigade */
940 /* get brigade from network one line at a time */
941 if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
947 /* loop through each bucket */
949 if (*eos || APR_BRIGADE_EMPTY(bb)) {
950 /* The connection aborted or timed out */
951 return APR_ECONNABORTED;
953 e = APR_BRIGADE_FIRST(bb);
954 if (APR_BUCKET_IS_EOS(e)) {
958 if (APR_SUCCESS != apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ)) {
962 * is string LF terminated?
963 * XXX: This check can be made more efficient by simply checking
964 * if the last character in the 'response' buffer is an ASCII_LF.
965 * See ap_rgetline() for an example.
967 if (memchr(response, APR_ASCII_LF, len)) {
970 /* concat strings until buff is full - then throw the data away */
971 if (len > ((bufflen-1)-(pos-buff))) {
972 len = (bufflen-1)-(pos-buff);
975 pos = apr_cpystrn(pos, response, len);
978 APR_BUCKET_REMOVE(e);
979 apr_bucket_destroy(e);
986 /* unmerge an element in the table */
987 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
989 apr_off_t offset = 0;
993 /* get the value to unmerge */
994 const char *initial = apr_table_get(t, key);
998 value = apr_pstrdup(p, initial);
1000 /* remove the value from the headers */
1001 apr_table_unset(t, key);
1003 /* find each comma */
1004 while (value[count]) {
1005 if (value[count] == ',') {
1007 apr_table_add(t, key, value + offset);
1012 apr_table_add(t, key, value + offset);
1015 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1016 proxy_dir_conf *conf, const char *url)
1018 struct proxy_alias *ent;
1023 * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1024 * after the hostname
1028 ent = (struct proxy_alias *)conf->raliases->elts;
1029 for (i = 0; i < conf->raliases->nelts; i++) {
1030 l2 = strlen(ent[i].real);
1031 if (l1 >= l2 && strncasecmp(ent[i].real, url, l2) == 0) {
1032 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1033 return ap_construct_url(r->pool, u, r);
1041 * Cookies are a bit trickier to match: we've got two substrings to worry
1042 * about, and we can't just find them with strstr 'cos of case. Regexp
1043 * matching would be an easy fix, but for better consistency with all the
1044 * other matches we'll refrain and use apr_strmatch to find path=/domain=
1045 * and stick to plain strings for the config values.
1047 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1048 proxy_dir_conf *conf, const char *str)
1050 struct proxy_alias *ent;
1051 size_t len = strlen(str);
1052 const char *newpath = NULL;
1053 const char *newdomain = NULL;
1055 const char *domainp;
1056 const char *pathe = NULL;
1057 const char *domaine = NULL;
1058 size_t l1, l2, poffs = 0, doffs = 0;
1065 * Find the match and replacement, but save replacing until we've done
1066 * both path and domain so we know the new strlen
1068 if ((pathp = apr_strmatch(conf->cookie_path_str, str, len)) != NULL) {
1070 poffs = pathp - str;
1071 pathe = ap_strchr_c(pathp, ';');
1072 l1 = pathe ? (pathe - pathp) : strlen(pathp);
1073 pathe = pathp + l1 ;
1074 ent = (struct proxy_alias *)conf->cookie_paths->elts;
1075 for (i = 0; i < conf->cookie_paths->nelts; i++) {
1076 l2 = strlen(ent[i].fake);
1077 if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1078 newpath = ent[i].real;
1079 pdiff = strlen(newpath) - l1;
1085 if ((domainp = apr_strmatch(conf->cookie_domain_str, str, len)) != NULL) {
1087 doffs = domainp - str;
1088 domaine = ap_strchr_c(domainp, ';');
1089 l1 = domaine ? (domaine - domainp) : strlen(domainp);
1090 domaine = domainp + l1;
1091 ent = (struct proxy_alias *)conf->cookie_domains->elts;
1092 for (i = 0; i < conf->cookie_domains->nelts; i++) {
1093 l2 = strlen(ent[i].fake);
1094 if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1095 newdomain = ent[i].real;
1096 ddiff = strlen(newdomain) - l1;
1103 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1104 l1 = strlen(newpath);
1106 l2 = strlen(newdomain);
1107 if (doffs > poffs) {
1108 memcpy(ret, str, poffs);
1109 memcpy(ret + poffs, newpath, l1);
1110 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1111 memcpy(ret + doffs + pdiff, newdomain, l2);
1112 strcpy(ret + doffs + pdiff + l2, domaine);
1115 memcpy(ret, str, doffs) ;
1116 memcpy(ret + doffs, newdomain, l2);
1117 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1118 memcpy(ret + poffs + ddiff, newpath, l1);
1119 strcpy(ret + poffs + ddiff + l1, pathe);
1123 memcpy(ret, str, poffs);
1124 memcpy(ret + poffs, newpath, l1);
1125 strcpy(ret + poffs + l1, pathe);
1130 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1131 l2 = strlen(newdomain);
1132 memcpy(ret, str, doffs);
1133 memcpy(ret + doffs, newdomain, l2);
1134 strcpy(ret + doffs+l2, domaine);
1137 ret = (char *)str; /* no change */
1144 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1145 proxy_server_conf *conf,
1148 proxy_balancer *balancer;
1149 char *c, *uri = apr_pstrdup(p, url);
1152 c = strchr(uri, ':');
1153 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1155 /* remove path from uri */
1156 if ((c = strchr(c + 3, '/')))
1158 balancer = (proxy_balancer *)conf->balancers->elts;
1159 for (i = 0; i < conf->balancers->nelts; i++) {
1160 if (strcasecmp(balancer->name, uri) == 0)
1167 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1169 proxy_server_conf *conf,
1172 char *c, *q, *uri = apr_pstrdup(p, url);
1173 proxy_balancer_method *lbmethod;
1175 c = strchr(uri, ':');
1176 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1177 return "Bad syntax for a balancer name";
1178 /* remove path from uri */
1179 if ((q = strchr(c + 3, '/')))
1182 ap_str_tolower(uri);
1183 *balancer = apr_array_push(conf->balancers);
1184 memset(*balancer, 0, sizeof(proxy_balancer));
1187 * NOTE: The default method is byrequests, which we assume
1190 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1192 return "Can't find 'byrequests' lb method";
1195 (*balancer)->name = uri;
1196 (*balancer)->lbmethod = lbmethod;
1197 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker));
1198 /* XXX Is this a right place to create mutex */
1200 if (apr_thread_mutex_create(&((*balancer)->mutex),
1201 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1202 /* XXX: Do we need to log something here */
1203 return "can not create thread mutex";
1210 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1211 proxy_server_conf *conf,
1214 proxy_worker *worker;
1215 proxy_worker *max_worker = NULL;
1218 int worker_name_length;
1223 c = ap_strchr_c(url, ':');
1224 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1227 url_copy = apr_pstrdup(p, url);
1228 url_length = strlen(url);
1231 * We need to find the start of the path and
1232 * therefore we know the length of the scheme://hostname/
1233 * part to we can force-lowercase everything up to
1234 * the start of the path.
1236 c = ap_strchr_c(c+3, '/');
1239 pathstart = url_copy + (c - url);
1241 ap_str_tolower(url_copy);
1244 ap_str_tolower(url_copy);
1247 worker = (proxy_worker *)conf->workers->elts;
1250 * Do a "longest match" on the worker name to find the worker that
1251 * fits best to the URL.
1253 for (i = 0; i < conf->workers->nelts; i++) {
1254 if ( ((worker_name_length = strlen(worker->name)) <= url_length)
1255 && (worker_name_length > max_match)
1256 && (strncmp(url_copy, worker->name, worker_name_length) == 0) ) {
1257 max_worker = worker;
1258 max_match = worker_name_length;
1266 static apr_status_t conn_pool_cleanup(void *theworker)
1268 proxy_worker *worker = (proxy_worker *)theworker;
1269 if (worker->cp->res) {
1270 worker->cp->pool = NULL;
1271 apr_reslist_destroy(worker->cp->res);
1277 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1280 proxy_conn_pool *cp;
1283 * Create a connection pool's subpool.
1284 * This pool is used for connection recycling.
1285 * Once the worker is added it is never removed but
1286 * it can be disabled.
1288 apr_pool_create(&pool, p);
1290 * Alloc from the same pool as worker.
1291 * proxy_conn_pool is permanently attached to the worker.
1293 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1298 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1300 proxy_server_conf *conf,
1306 rv = apr_uri_parse(p, url, &uri);
1308 if (rv != APR_SUCCESS) {
1309 return "Unable to parse URL";
1312 ap_str_tolower(uri.hostname);
1313 ap_str_tolower(uri.scheme);
1314 *worker = apr_array_push(conf->workers);
1315 memset(*worker, 0, sizeof(proxy_worker));
1316 (*worker)->name = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1317 (*worker)->scheme = uri.scheme;
1318 (*worker)->hostname = uri.hostname;
1319 (*worker)->port = uri.port;
1320 (*worker)->id = proxy_lb_workers;
1321 /* Increase the total worker count */
1323 init_conn_pool(p, *worker);
1325 if (apr_thread_mutex_create(&((*worker)->mutex),
1326 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1327 /* XXX: Do we need to log something here */
1328 return "can not create thread mutex";
1335 PROXY_DECLARE(proxy_worker *) ap_proxy_create_worker(apr_pool_t *p)
1338 proxy_worker *worker;
1339 worker = (proxy_worker *)apr_pcalloc(p, sizeof(proxy_worker));
1340 worker->id = proxy_lb_workers;
1341 /* Increase the total worker count */
1343 init_conn_pool(p, worker);
1349 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer,
1350 proxy_worker *worker)
1352 proxy_worker *runtime;
1354 runtime = apr_array_push(balancer->workers);
1355 memcpy(runtime, worker, sizeof(proxy_worker));
1356 runtime->id = proxy_lb_workers;
1357 /* Increase the total runtime count */
1362 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1363 proxy_balancer **balancer,
1365 proxy_server_conf *conf, char **url)
1369 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1370 if (access_status == DECLINED && *balancer == NULL) {
1371 *worker = ap_proxy_get_worker(r->pool, conf, *url);
1373 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1374 "proxy: %s: found worker %s for %s",
1375 (*worker)->scheme, (*worker)->name, *url);
1380 else if (r->proxyreq == PROXYREQ_PROXY) {
1381 if (conf->forward) {
1382 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1383 "proxy: *: found forward proxy worker for %s",
1386 *worker = conf->forward;
1390 else if (r->proxyreq == PROXYREQ_REVERSE) {
1391 if (conf->reverse) {
1392 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1393 "proxy: *: found reverse proxy worker for %s",
1396 *worker = conf->reverse;
1401 else if (access_status == DECLINED && *balancer != NULL) {
1402 /* All the workers are busy */
1403 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1404 "proxy: all workers are busy. Unable to serve %s",
1406 access_status = HTTP_SERVICE_UNAVAILABLE;
1408 return access_status;
1411 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1412 proxy_balancer *balancer,
1414 proxy_server_conf *conf)
1418 access_status = proxy_run_post_request(worker, balancer, r, conf);
1425 return access_status;
1429 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1430 const char *proxy_function,
1431 apr_sockaddr_t *backend_addr,
1432 const char *backend_name,
1433 proxy_server_conf *conf,
1441 while (backend_addr && !connected) {
1442 if ((rv = apr_socket_create(newsock, backend_addr->family,
1443 SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1444 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1445 ap_log_error(APLOG_MARK, loglevel, rv, s,
1446 "proxy: %s: error creating fam %d socket for target %s",
1448 backend_addr->family,
1451 * this could be an IPv6 address from the DNS but the
1452 * local machine won't give us an IPv6 socket; hopefully the
1453 * DNS returned an additional address to try
1455 backend_addr = backend_addr->next;
1459 #if !defined(TPF) && !defined(BEOS)
1460 if (conf->recv_buffer_size > 0 &&
1461 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1462 conf->recv_buffer_size))) {
1463 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1464 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1465 "ProxyReceiveBufferSize, using default");
1469 /* Set a timeout on the socket */
1470 if (conf->timeout_set == 1) {
1471 apr_socket_timeout_set(*newsock, conf->timeout);
1474 apr_socket_timeout_set(*newsock, s->timeout);
1477 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1478 "proxy: %s: fam %d socket created to connect to %s",
1479 proxy_function, backend_addr->family, backend_name);
1481 /* make the connection out of the socket */
1482 rv = apr_socket_connect(*newsock, backend_addr);
1484 /* if an error occurred, loop round and try again */
1485 if (rv != APR_SUCCESS) {
1486 apr_socket_close(*newsock);
1487 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1488 ap_log_error(APLOG_MARK, loglevel, rv, s,
1489 "proxy: %s: attempt to connect to %pI (%s) failed",
1493 backend_addr = backend_addr->next;
1498 return connected ? 0 : 1;
1501 static apr_status_t connection_cleanup(void *theconn)
1503 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1504 proxy_worker *worker = conn->worker;
1507 * If the connection pool is NULL the worker
1508 * cleanup has been run. Just return.
1513 /* deterimine if the connection need to be closed */
1514 if (conn->close_on_recycle || conn->close) {
1515 apr_pool_t *p = conn->pool;
1516 apr_pool_clear(conn->pool);
1517 memset(conn, 0, sizeof(proxy_conn_rec));
1519 conn->worker = worker;
1522 if (worker->hmax && worker->cp->res) {
1523 apr_reslist_release(worker->cp->res, (void *)conn);
1528 worker->cp->conn = conn;
1531 /* Allways return the SUCCESS */
1535 /* reslist constructor */
1536 static apr_status_t connection_constructor(void **resource, void *params,
1540 proxy_conn_rec *conn;
1541 proxy_worker *worker = (proxy_worker *)params;
1544 * Create the subpool for each connection
1545 * This keeps the memory consumption constant
1546 * when disconnecting from backend.
1548 apr_pool_create(&ctx, pool);
1549 conn = apr_pcalloc(pool, sizeof(proxy_conn_rec));
1552 conn->worker = worker;
1558 #if APR_HAS_THREADS /* only needed when threads are used */
1559 /* reslist destructor */
1560 static apr_status_t connection_destructor(void *resource, void *params,
1563 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1565 /* Destroy the pool only if not called from reslist_destroy */
1566 if (conn->worker->cp->pool)
1567 apr_pool_destroy(conn->pool);
1573 PROXY_DECLARE(void) ap_proxy_initialize_worker_share(proxy_server_conf *conf,
1574 proxy_worker *worker,
1577 #if PROXY_HAS_SCOREBOARD
1578 lb_score *score = NULL;
1583 if (worker->s && (worker->s->status & PROXY_WORKER_INITIALIZED)) {
1584 /* The worker share is already initialized */
1585 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1586 "proxy: worker %s already initialized",
1590 #if PROXY_HAS_SCOREBOARD
1591 /* Get scoreboard slot */
1592 if (ap_scoreboard_image) {
1593 score = ap_get_scoreboard_lb(worker->id);
1595 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1596 "proxy: ap_get_scoreboard_lb(%d) failed for worker %s",
1597 worker->id, worker->name);
1600 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1601 "proxy: initialized scoreboard slot %d for worker %s",
1602 worker->id, worker->name);
1607 score = apr_pcalloc(conf->pool, sizeof(proxy_worker_stat));
1608 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1609 "proxy: initialized plain memory for worker %s",
1612 worker->s = (proxy_worker_stat *)score;
1614 strcpy(worker->s->route, worker->route);
1616 *worker->s->route = '\0';
1617 if (worker->redirect)
1618 strcpy(worker->s->redirect, worker->redirect);
1620 *worker->s->redirect = '\0';
1621 /* Set default parameters */
1623 worker->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1624 /* By default address is reusable */
1625 worker->is_address_reusable = 1;
1629 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s)
1637 if (worker->s->status & PROXY_WORKER_INITIALIZED) {
1638 /* The worker is already initialized */
1643 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1644 if (mpm_threads > 1) {
1645 /* Set hard max to no more then mpm_threads */
1646 if (worker->hmax == 0 || worker->hmax > mpm_threads)
1647 worker->hmax = mpm_threads;
1648 if (worker->smax == 0 || worker->smax > worker->hmax)
1649 worker->smax = worker->hmax;
1650 /* Set min to be lower then smax */
1651 if (worker->min > worker->smax)
1652 worker->min = worker->smax;
1655 /* This will supress the apr_reslist creation */
1656 worker->min = worker->smax = worker->hmax = 0;
1659 rv = apr_reslist_create(&(worker->cp->res),
1660 worker->min, worker->smax,
1661 worker->hmax, worker->ttl,
1662 connection_constructor, connection_destructor,
1663 worker, worker->cp->pool);
1665 apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1667 apr_pool_cleanup_null);
1669 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1670 "proxy: initialized worker %d in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1671 worker->id, getpid(), worker->hostname, worker->min,
1672 worker->hmax, worker->smax);
1674 #if (APR_MAJOR_VERSION > 0)
1675 /* Set the acquire timeout */
1676 if (rv == APR_SUCCESS && worker->acquire_set)
1677 apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1684 rv = connection_constructor((void **)&(worker->cp->conn), worker, worker->cp->pool);
1685 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1686 "proxy: initialized single connection worker %d in child %" APR_PID_T_FMT " for (%s)",
1687 worker->id, getpid(), worker->hostname);
1689 if (rv == APR_SUCCESS)
1690 worker->s->status |= (worker->status | PROXY_WORKER_INITIALIZED);
1694 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1695 proxy_worker *worker,
1698 if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1699 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1700 "proxy: %s: retrying the worker for (%s)",
1701 proxy_function, worker->hostname);
1702 if (apr_time_now() > worker->s->error_time + worker->retry) {
1703 ++worker->s->retries;
1704 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1705 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1706 "proxy: %s: worker for (%s) has been marked for retry",
1707 proxy_function, worker->hostname);
1717 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
1718 proxy_conn_rec **conn,
1719 proxy_worker *worker,
1724 if (!PROXY_WORKER_IS_USABLE(worker)) {
1725 /* Retry the worker */
1726 ap_proxy_retry_worker(proxy_function, worker, s);
1728 if (!PROXY_WORKER_IS_USABLE(worker)) {
1729 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1730 "proxy: %s: disabled connection for (%s)",
1731 proxy_function, worker->hostname);
1732 return HTTP_SERVICE_UNAVAILABLE;
1736 if (worker->hmax && worker->cp->res) {
1737 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
1742 /* create the new connection if the previous was destroyed */
1743 if (!worker->cp->conn)
1744 connection_constructor((void **)conn, worker, worker->cp->pool);
1746 *conn = worker->cp->conn;
1747 worker->cp->conn = NULL;
1752 if (rv != APR_SUCCESS) {
1753 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1754 "proxy: %s: failed to acquire connection for (%s)",
1755 proxy_function, worker->hostname);
1756 return HTTP_SERVICE_UNAVAILABLE;
1758 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1759 "proxy: %s: has acquired connection for (%s)",
1760 proxy_function, worker->hostname);
1762 (*conn)->worker = worker;
1764 (*conn)->close_on_recycle = 0;
1769 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
1770 proxy_conn_rec *conn,
1773 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1774 "proxy: %s: has released connection for (%s)",
1775 proxy_function, conn->worker->hostname);
1776 /* If there is a connection kill it's cleanup */
1777 if (conn->connection) {
1778 apr_pool_cleanup_kill(conn->connection->pool, conn, connection_cleanup);
1779 conn->connection = NULL;
1781 connection_cleanup(conn);
1787 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
1788 proxy_server_conf *conf,
1789 proxy_worker *worker,
1790 proxy_conn_rec *conn,
1793 const char *proxyname,
1794 apr_port_t proxyport,
1795 char *server_portstr,
1796 int server_portstr_size)
1799 apr_status_t err = APR_SUCCESS;
1802 * Break up the URL to determine the host to connect to
1805 /* we break the URL into host, port, uri */
1806 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
1807 return ap_proxyerror(r, HTTP_BAD_REQUEST,
1808 apr_pstrcat(p,"URI cannot be parsed: ", *url,
1812 uri->port = apr_uri_port_of_scheme(uri->scheme);
1815 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1816 "proxy: connecting %s to %s:%d", *url, uri->hostname,
1820 * allocate these out of the specified connection pool
1821 * The scheme handler decides if this is permanent or
1822 * short living pool.
1824 /* are we connecting directly, or via a proxy? */
1826 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
1827 uri->query ? uri->query : "",
1828 uri->fragment ? "#" : "",
1829 uri->fragment ? uri->fragment : "", NULL);
1832 * Make sure that we pick the the correct and valid worker.
1833 * If a single keepalive connection triggers different workers,
1834 * then we have a problem (we don't select the correct one).
1835 * Do an expensive check in this case, where we compare the
1836 * the hostnames associated between the two.
1838 * TODO: Handle this much better...
1840 if (!conn->hostname || !worker->is_address_reusable ||
1841 (r->connection->keepalives &&
1842 (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
1843 (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
1845 conn->hostname = apr_pstrdup(conn->pool, proxyname);
1846 conn->port = proxyport;
1848 conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
1849 conn->port = uri->port;
1853 * TODO: add address cache for generic forward proxies.
1854 * At least level 0 -> compare with previous hostname:port
1856 if (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE ||
1857 !worker->is_address_reusable) {
1859 * TODO: Check if the connection can be reused
1861 if (conn->connection) {
1863 apr_socket_close(conn->sock);
1866 apr_pool_cleanup_kill(conn->connection->pool, conn, connection_cleanup);
1867 conn->connection = NULL;
1869 err = apr_sockaddr_info_get(&(conn->addr),
1870 conn->hostname, APR_UNSPEC,
1874 else if (!worker->cp->addr) {
1875 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
1876 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
1878 return HTTP_INTERNAL_SERVER_ERROR;
1882 * Worker can have the single constant backend adress.
1883 * The single DNS lookup is used once per worker.
1884 * If dynamic change is needed then set the addr to NULL
1885 * inside dynamic config to force the lookup.
1887 err = apr_sockaddr_info_get(&(worker->cp->addr),
1888 conn->hostname, APR_UNSPEC,
1891 conn->addr = worker->cp->addr;
1892 PROXY_THREAD_UNLOCK(worker);
1895 conn->addr = worker->cp->addr;
1897 if (err != APR_SUCCESS) {
1898 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1899 apr_pstrcat(p, "DNS lookup failure for: ",
1900 conn->hostname, NULL));
1903 /* Get the server port for the Via headers */
1905 server_port = ap_get_server_port(r);
1906 if (ap_is_default_port(server_port, r)) {
1907 strcpy(server_portstr,"");
1909 apr_snprintf(server_portstr, server_portstr_size, ":%d",
1913 /* check if ProxyBlock directive on this host */
1914 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
1915 return ap_proxyerror(r, HTTP_FORBIDDEN,
1916 "Connect to remote machine blocked");
1918 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1919 "proxy: connected %s to %s:%d", *url, conn->hostname,
1924 static int is_socket_connected(apr_socket_t *sock)
1927 apr_size_t buffer_len = 1;
1928 char test_buffer[1];
1929 apr_status_t socket_status;
1930 apr_interval_time_t current_timeout;
1933 apr_socket_timeout_get(sock, ¤t_timeout);
1934 /* set no timeout */
1935 apr_socket_timeout_set(sock, 0);
1936 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
1937 /* put back old timeout */
1938 apr_socket_timeout_set(sock, current_timeout);
1939 if (APR_STATUS_IS_EOF(socket_status))
1945 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
1946 proxy_conn_rec *conn,
1947 proxy_worker *worker,
1953 apr_sockaddr_t *backend_addr = conn->addr;
1954 apr_socket_t *newsock;
1958 * This increases the connection pool size
1959 * but the number of dropped connections is
1960 * relatively small compared to connection lifetime
1962 if (!(connected = is_socket_connected(conn->sock))) {
1963 apr_socket_close(conn->sock);
1967 while (backend_addr && !connected) {
1968 if ((rv = apr_socket_create(&newsock, backend_addr->family,
1969 SOCK_STREAM, APR_PROTO_TCP,
1970 conn->pool)) != APR_SUCCESS) {
1971 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1972 ap_log_error(APLOG_MARK, loglevel, rv, s,
1973 "proxy: %s: error creating fam %d socket for target %s",
1975 backend_addr->family,
1978 * this could be an IPv6 address from the DNS but the
1979 * local machine won't give us an IPv6 socket; hopefully the
1980 * DNS returned an additional address to try
1982 backend_addr = backend_addr->next;
1986 #if !defined(TPF) && !defined(BEOS)
1987 if (worker->recv_buffer_size > 0 &&
1988 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
1989 worker->recv_buffer_size))) {
1990 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1991 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1992 "ProxyReceiveBufferSize, using default");
1996 /* Set a timeout on the socket */
1997 if (worker->timeout_set == 1) {
1998 apr_socket_timeout_set(newsock, worker->timeout);
2001 apr_socket_timeout_set(newsock, s->timeout);
2003 /* Set a keepalive option */
2004 if (worker->keepalive) {
2005 if ((rv = apr_socket_opt_set(newsock,
2006 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2007 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2008 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2012 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2013 "proxy: %s: fam %d socket created to connect to %s",
2014 proxy_function, backend_addr->family, worker->hostname);
2016 /* make the connection out of the socket */
2017 rv = apr_socket_connect(newsock, backend_addr);
2019 /* if an error occurred, loop round and try again */
2020 if (rv != APR_SUCCESS) {
2021 apr_socket_close(newsock);
2022 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2023 ap_log_error(APLOG_MARK, loglevel, rv, s,
2024 "proxy: %s: attempt to connect to %pI (%s) failed",
2028 backend_addr = backend_addr->next;
2032 conn->sock = newsock;
2036 * Put the entire worker to error state if
2037 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2038 * Altrough some connections may be alive
2039 * no further connections to the worker could be made
2041 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2042 !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2043 worker->s->status |= PROXY_WORKER_IN_ERROR;
2044 worker->s->error_time = apr_time_now();
2045 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2046 "ap_proxy_connect_backend disabling worker for (%s)",
2050 worker->s->error_time = 0;
2051 worker->s->retries = 0;
2053 return connected ? OK : DECLINED;
2056 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2057 proxy_conn_rec *conn,
2061 apr_sockaddr_t *backend_addr = conn->addr;
2065 * The socket is now open, create a new backend server connection
2067 conn->connection = ap_run_create_connection(c->pool, s, conn->sock,
2071 if (!conn->connection) {
2073 * the peer reset the connection already; ap_run_create_connection()
2076 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2077 s, "proxy: %s: an error occurred creating a "
2078 "new connection to %pI (%s)", proxy_function,
2079 backend_addr, conn->hostname);
2080 /* XXX: Will be closed when proxy_conn is closed */
2081 apr_socket_close(conn->sock);
2083 return HTTP_INTERNAL_SERVER_ERROR;
2086 * register the connection cleanup to client connection
2087 * so that the connection can be closed or reused
2089 apr_pool_cleanup_register(c->pool, (void *)conn,
2091 apr_pool_cleanup_null);
2093 /* For ssl connection to backend */
2095 if (!ap_proxy_ssl_enable(conn->connection)) {
2096 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2097 s, "proxy: %s: failed to enable ssl support "
2098 "for %pI (%s)", proxy_function,
2099 backend_addr, conn->hostname);
2100 return HTTP_INTERNAL_SERVER_ERROR;
2104 /* TODO: See if this will break FTP */
2105 ap_proxy_ssl_disable(conn->connection);
2108 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2109 "proxy: %s: connection complete to %pI (%s)",
2110 proxy_function, backend_addr, conn->hostname);
2112 /* set up the connection filters */
2113 rc = ap_run_pre_connection(conn->connection, conn->sock);
2114 if (rc != OK && rc != DONE) {
2115 conn->connection->aborted = 1;
2116 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2117 "proxy: %s: pre_connection setup failed (%d)",
2118 proxy_function, rc);
2125 int ap_proxy_lb_workers(void)
2128 * Since we can't resize the scoreboard when reconfiguring, we
2129 * have to impose a limit on the number of workers, we are
2130 * able to reconfigure to.
2132 if (!lb_workers_limit)
2133 lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2134 return lb_workers_limit;
2137 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2138 apr_bucket_brigade *brigade)
2141 conn_rec *c = r->connection;
2145 * If this is a subrequest, then prevent also caching of the main
2149 r->main->no_cache = 1;
2150 e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2152 APR_BRIGADE_INSERT_TAIL(brigade, e);
2153 e = apr_bucket_eos_create(c->bucket_alloc);
2154 APR_BRIGADE_INSERT_TAIL(brigade, e);