1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* Utility routines for Apache proxy */
18 #include "mod_proxy.h"
20 #include "scoreboard.h"
21 #include "apr_version.h"
24 #include <unistd.h> /* for getpid() */
27 #if (APR_MAJOR_VERSION < 1)
28 #undef apr_socket_create
29 #define apr_socket_create apr_socket_create_ex
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
52 if (apr_isdigit(ch)) {
55 else if (apr_isupper(ch)) {
64 if (apr_isdigit(ch)) {
67 else if (apr_isupper(ch)) {
74 #else /*APR_CHARSET_EBCDIC*/
76 * we assume that the hex value refers to an ASCII character
77 * so convert to EBCDIC so that it makes sense locally;
81 * client specifies %20 in URL to refer to a space char;
82 * at this point we're called with EBCDIC "20"; after turning
83 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
84 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
89 if (1 == sscanf(x, "%2x", &i)) {
91 ap_xlate_proto_from_ascii(buf, 1);
97 #endif /*APR_CHARSET_EBCDIC*/
100 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
102 #if !APR_CHARSET_EBCDIC
106 i = (ch & 0xF0) >> 4;
108 x[1] = ('A' - 10) + i;
116 x[2] = ('A' - 10) + i;
121 #else /*APR_CHARSET_EBCDIC*/
122 static const char ntoa[] = { "0123456789ABCDEF" };
128 ap_xlate_proto_to_ascii(buf, 1);
131 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
132 x[2] = ntoa[buf[0] & 0x0F];
134 #endif /*APR_CHARSET_EBCDIC*/
138 * canonicalise a URL-encoded string
142 * Convert a URL-encoded string to canonical form.
143 * It decodes characters which need not be encoded,
144 * and encodes those which must be encoded, and does not touch
145 * those which must not be touched.
147 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
148 enum enctype t, int forcedec,
153 char *allowed; /* characters which should not be encoded */
154 char *reserved; /* characters which much not be en/de-coded */
157 * N.B. in addition to :@&=, this allows ';' in an http path
158 * and '?' in an ftp path -- this may be revised
160 * Also, it makes a '+' character in a search string reserved, as
161 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
162 * it only permits ; / ? : @ = & as reserved chars.)
165 allowed = "~$-_.+!*'(),;:@&=";
167 else if (t == enc_search) {
168 allowed = "$-_.!*'(),;:@&=";
170 else if (t == enc_user) {
171 allowed = "$-_.+!*'(),;@&=";
173 else if (t == enc_fpath) {
174 allowed = "$-_.+!*'(),?:@&=";
176 else { /* if (t == enc_parm) */
177 allowed = "$-_.+!*'(),?/:@&=";
183 else if (t == enc_search) {
190 y = apr_palloc(p, 3 * len + 1);
192 for (i = 0, j = 0; i < len; i++, j++) {
193 /* always handle '/' first */
195 if (strchr(reserved, ch)) {
200 * decode it if not already done. do not decode reverse proxied URLs
201 * unless specifically forced
203 if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
204 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
207 ch = ap_proxy_hex2c(&x[i + 1]);
209 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
210 ap_proxy_c2hex(ch, &y[j]);
215 /* recode it, if necessary */
216 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
217 ap_proxy_c2hex(ch, &y[j]);
229 * Parses network-location.
230 * urlp on input the URL; on output the path, after the leading /
231 * user NULL if no user/password permitted
232 * password holder for password
233 * host holder for host
234 * port port number; only set if one is supplied.
236 * Returns an error string.
238 PROXY_DECLARE(char *)
239 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
240 char **passwordp, char **hostp, apr_port_t *port)
242 char *addr, *scope_id, *strp, *host, *url = *urlp;
243 char *user = NULL, *password = NULL;
247 if (url[0] != '/' || url[1] != '/') {
248 return "Malformed URL";
251 url = strchr(host, '/');
256 *(url++) = '\0'; /* skip seperating '/' */
259 /* find _last_ '@' since it might occur in user/password part */
260 strp = strrchr(host, '@');
268 strp = strchr(user, ':');
271 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
272 if (password == NULL) {
273 return "Bad %-escape in URL (password)";
277 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
279 return "Bad %-escape in URL (username)";
285 if (passwordp != NULL) {
286 *passwordp = password;
290 * Parse the host string to separate host portion from optional port.
291 * Perform range checking on port.
293 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
294 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
295 return "Invalid host/port";
297 if (tmp_port != 0) { /* only update caller's port if port was specified */
301 ap_str_tolower(addr); /* DNS names are case-insensitive */
310 * If the date is a valid RFC 850 date or asctime() date, then it
311 * is converted to the RFC 1123 format.
313 PROXY_DECLARE(const char *)
314 ap_proxy_date_canon(apr_pool_t *p, const char *date)
319 apr_time_t time = apr_date_parse_http(date);
324 ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
325 rv = apr_rfc822_date(ndate, time);
326 if (rv != APR_SUCCESS) {
333 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
335 request_rec *rp = apr_pcalloc(r->pool, sizeof(*r));
338 rp->status = HTTP_OK;
340 rp->headers_in = apr_table_make(r->pool, 50);
341 rp->subprocess_env = apr_table_make(r->pool, 50);
342 rp->headers_out = apr_table_make(r->pool, 12);
343 rp->err_headers_out = apr_table_make(r->pool, 5);
344 rp->notes = apr_table_make(r->pool, 5);
346 rp->server = r->server;
347 rp->proxyreq = r->proxyreq;
348 rp->request_time = r->request_time;
350 rp->output_filters = c->output_filters;
351 rp->input_filters = c->input_filters;
352 rp->proto_output_filters = c->output_filters;
353 rp->proto_input_filters = c->input_filters;
355 rp->request_config = ap_create_request_config(r->pool);
356 proxy_run_create_req(r, rp);
363 * list is a comma-separated list of case-insensitive tokens, with
364 * optional whitespace around the tokens.
365 * The return returns 1 if the token val is found in the list, or 0
368 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
375 while (list != NULL) {
376 p = ap_strchr_c(list, ',');
381 } while (apr_isspace(*p));
387 while (i > 0 && apr_isspace(list[i - 1])) {
390 if (i == len && strncasecmp(list, val, len) == 0) {
399 * list is a comma-separated list of case-insensitive tokens, with
400 * optional whitespace around the tokens.
401 * if val appears on the list of tokens, it is removed from the list,
402 * and the new list is returned.
404 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
412 while (list != NULL) {
413 p = ap_strchr_c(list, ',');
418 } while (apr_isspace(*p));
424 while (i > 0 && apr_isspace(list[i - 1])) {
427 if (i == len && strncasecmp(list, val, len) == 0) {
432 new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
435 new = apr_pstrndup(pool, list, i);
444 * Converts 8 hex digits to a time integer
446 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
451 for (i = 0, j = 0; i < 8; i++) {
454 if (apr_isdigit(ch)) {
457 else if (apr_isupper(ch)) {
458 j |= ch - ('A' - 10);
461 j |= ch - ('a' - 10);
464 if (j == 0xffffffff) {
465 return -1; /* so that it works with 8-byte ints */
473 * Converts a time integer to 8 hex digits
475 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
480 for (i = 7; i >= 0; i--) {
484 y[i] = ch + ('A' - 10);
493 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
495 apr_table_setn(r->notes, "error-notes",
497 "The proxy server could not handle the request "
498 "<em><a href=\"", ap_escape_html(r->pool, r->uri),
499 "\">", ap_escape_html(r->pool, r->method),
501 ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
503 ap_escape_html(r->pool, message),
504 "</strong></p>", NULL));
506 /* Allow "error-notes" string to be printed by ap_send_error_response() */
507 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
509 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
510 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
511 "proxy: %s returned by %s", message, r->uri);
516 proxy_get_host_of_request(request_rec *r)
518 char *url, *user = NULL, *password = NULL, *err, *host;
521 if (r->hostname != NULL) {
525 /* Set url to the first char after "scheme://" */
526 if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
530 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
532 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
535 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", err);
540 return host; /* ought to return the port, too */
543 /* Return TRUE if addr represents an IP address (or an IP network address) */
544 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
546 const char *addr = This->name;
552 * if the address is given with an explicit netmask, use that
553 * Due to a deficiency in apr_inet_addr(), it is impossible to parse
554 * "partial" addresses (with less than 4 quads) correctly, i.e.
555 * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
556 * I therefore have to parse the IP address manually:
557 * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
558 * addr and mask were set by proxy_readmask()
563 * Parse IP addr manually, optionally allowing
564 * abbreviated net addresses like 192.168.
567 /* Iterate over up to 4 (dotted) quads. */
568 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
571 if (*addr == '/' && quads > 0) { /* netmask starts here. */
575 if (!apr_isdigit(*addr)) {
576 return 0; /* no digit at start of quad */
579 ip_addr[quads] = strtol(addr, &tmp, 0);
581 if (tmp == addr) { /* expected a digit, found something else */
585 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
592 if (*addr == '.' && quads != 3) {
593 ++addr; /* after the 4th quad, a dot would be illegal */
597 for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
598 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
601 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
606 bits = strtol(addr, &tmp, 0);
608 if (tmp == addr) { /* expected a digit, found something else */
614 if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
621 * Determine (i.e., "guess") netmask by counting the
622 * number of trailing .0's; reduce #quads appropriately
623 * (so that 192.168.0.0 is equivalent to 192.168.)
625 while (quads > 0 && ip_addr[quads - 1] == 0) {
629 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
634 /* every zero-byte counts as 8 zero-bits */
637 if (bits != 32) { /* no warning for fully qualified IP address */
638 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
639 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
640 inet_ntoa(This->addr), bits);
644 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
646 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
647 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
648 "Warning: NetMask and IP-Addr disagree in %s/%ld",
649 inet_ntoa(This->addr), bits);
650 This->addr.s_addr &= This->mask.s_addr;
651 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
652 " Set to %s/%ld", inet_ntoa(This->addr), bits);
656 This->matcher = proxy_match_ipaddr;
660 return (*addr == '\0'); /* okay iff we've parsed the whole string */
664 /* Return TRUE if addr represents an IP address (or an IP network address) */
665 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
668 struct in_addr addr, *ip;
669 const char *host = proxy_get_host_of_request(r);
671 if (host == NULL) { /* oops! */
675 memset(&addr, '\0', sizeof addr);
676 memset(ip_addr, '\0', sizeof ip_addr);
678 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
679 for (addr.s_addr = 0, i = 0; i < 4; ++i) {
680 /* ap_proxy_is_ipaddr() already confirmed that we have
681 * a valid octet in ip_addr[i]
683 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
686 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
688 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
689 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
690 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
691 "%s/", inet_ntoa(This->addr));
692 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
693 "%s", inet_ntoa(This->mask));
699 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
700 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
701 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
702 "%s/", inet_ntoa(This->addr));
703 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
704 "%s", inet_ntoa(This->mask));
709 struct apr_sockaddr_t *reqaddr;
711 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
714 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
715 "2)IP-NoMatch: hostname=%s msg=Host not found", host);
720 /* Try to deal with multiple IP addr's for a host */
721 /* FIXME: This needs to be able to deal with IPv6 */
723 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
724 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
726 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
727 "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
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));
737 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
738 "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
739 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
740 "%s/", inet_ntoa(This->addr));
741 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
742 "%s", inet_ntoa(This->mask));
745 reqaddr = reqaddr->next;
752 /* Return TRUE if addr represents a domain name */
753 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
755 char *addr = This->name;
758 /* Domain name must start with a '.' */
759 if (addr[0] != '.') {
763 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
764 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
769 if (addr[i] == ':') {
770 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
771 "@@@@ handle optional port in proxy_is_domainname()");
772 /* @@@@ handle optional port */
776 if (addr[i] != '\0') {
780 /* Strip trailing dots */
781 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
785 This->matcher = proxy_match_domainname;
789 /* Return TRUE if host "host" is in domain "domain" */
790 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
792 const char *host = proxy_get_host_of_request(r);
793 int d_len = strlen(This->name), h_len;
795 if (host == NULL) { /* some error was logged already */
799 h_len = strlen(host);
801 /* @@@ do this within the setup? */
802 /* Ignore trailing dots in domain comparison: */
803 while (d_len > 0 && This->name[d_len - 1] == '.') {
806 while (h_len > 0 && host[h_len - 1] == '.') {
810 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
813 /* Return TRUE if host represents a host name */
814 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
816 struct apr_sockaddr_t *addr;
817 char *host = This->name;
820 /* Host names must not start with a '.' */
821 if (host[0] == '.') {
824 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
825 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
827 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
831 This->hostaddr = addr;
833 /* Strip trailing dots */
834 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
838 This->matcher = proxy_match_hostname;
842 /* Return TRUE if host "host" is equal to host2 "host2" */
843 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
845 char *host = This->name;
846 const char *host2 = proxy_get_host_of_request(r);
850 if (host == NULL || host2 == NULL) {
851 return 0; /* oops! */
854 h2_len = strlen(host2);
855 h1_len = strlen(host);
858 struct apr_sockaddr_t *addr = *This->hostaddr;
860 /* Try to deal with multiple IP addr's for a host */
862 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
868 /* Ignore trailing dots in host2 comparison: */
869 while (h2_len > 0 && host2[h2_len - 1] == '.') {
872 while (h1_len > 0 && host[h1_len - 1] == '.') {
875 return h1_len == h2_len
876 && strncasecmp(host, host2, h1_len) == 0;
879 /* Return TRUE if addr is to be matched as a word */
880 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
882 This->matcher = proxy_match_word;
886 /* Return TRUE if string "str2" occurs literally in "str1" */
887 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
889 const char *host = proxy_get_host_of_request(r);
890 return host != NULL && ap_strstr_c(host, This->name) != NULL;
893 /* checks whether a host in uri_addr matches proxyblock */
894 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
895 apr_sockaddr_t *uri_addr)
898 apr_sockaddr_t * src_uri_addr = uri_addr;
899 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
900 for (j = 0; j < conf->noproxies->nelts; j++) {
901 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
902 struct apr_sockaddr_t *conf_addr = npent[j].addr;
903 uri_addr = src_uri_addr;
904 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
905 "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
906 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
907 || npent[j].name[0] == '*') {
908 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
909 "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
910 return HTTP_FORBIDDEN;
913 uri_addr = src_uri_addr;
917 apr_sockaddr_ip_get(&conf_ip, conf_addr);
918 apr_sockaddr_ip_get(&uri_ip, uri_addr);
919 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
920 "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
921 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
922 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
923 "proxy: connect to remote machine %s blocked: IP %s matched", uri_addr->hostname, conf_ip);
924 return HTTP_FORBIDDEN;
926 uri_addr = uri_addr->next;
928 conf_addr = conf_addr->next;
934 /* set up the minimal filter set */
935 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
937 ap_add_input_filter("HTTP_IN", NULL, r, c);
942 * converts a series of buckets into a string
943 * XXX: BillS says this function performs essentially the same function as
944 * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
945 * instead? I think ap_proxy_string_read() will not work properly on non ASCII
946 * (EBCDIC) machines either.
948 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
949 char *buff, apr_size_t bufflen, int *eos)
958 /* start with an empty string */
962 /* loop through each brigade */
964 /* get brigade from network one line at a time */
965 if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
971 /* loop through each bucket */
973 if (*eos || APR_BRIGADE_EMPTY(bb)) {
974 /* The connection aborted or timed out */
975 return APR_ECONNABORTED;
977 e = APR_BRIGADE_FIRST(bb);
978 if (APR_BUCKET_IS_EOS(e)) {
982 if (APR_SUCCESS != (rv = apr_bucket_read(e,
983 (const char **)&response,
989 * is string LF terminated?
990 * XXX: This check can be made more efficient by simply checking
991 * if the last character in the 'response' buffer is an ASCII_LF.
992 * See ap_rgetline() for an example.
994 if (memchr(response, APR_ASCII_LF, len)) {
997 /* concat strings until buff is full - then throw the data away */
998 if (len > ((bufflen-1)-(pos-buff))) {
999 len = (bufflen-1)-(pos-buff);
1002 memcpy(pos, response, len);
1006 APR_BUCKET_REMOVE(e);
1007 apr_bucket_destroy(e);
1015 /* unmerge an element in the table */
1016 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
1018 apr_off_t offset = 0;
1019 apr_off_t count = 0;
1022 /* get the value to unmerge */
1023 const char *initial = apr_table_get(t, key);
1027 value = apr_pstrdup(p, initial);
1029 /* remove the value from the headers */
1030 apr_table_unset(t, key);
1032 /* find each comma */
1033 while (value[count]) {
1034 if (value[count] == ',') {
1036 apr_table_add(t, key, value + offset);
1041 apr_table_add(t, key, value + offset);
1044 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1045 proxy_dir_conf *conf, const char *url)
1047 proxy_req_conf *rconf;
1048 struct proxy_alias *ent;
1053 * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1054 * after the hostname
1056 if (r->proxyreq != PROXYREQ_REVERSE) {
1061 if (conf->interpolate_env == 1) {
1062 rconf = ap_get_module_config(r->request_config, &proxy_module);
1063 ent = (struct proxy_alias *)rconf->raliases->elts;
1066 ent = (struct proxy_alias *)conf->raliases->elts;
1068 for (i = 0; i < conf->raliases->nelts; i++) {
1069 proxy_server_conf *sconf = (proxy_server_conf *)
1070 ap_get_module_config(r->server->module_config, &proxy_module);
1071 proxy_balancer *balancer;
1074 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1075 "ppr: real: %s", real);
1077 * First check if mapping against a balancer and see
1078 * if we have such a entity. If so, then we need to
1079 * find the particulars of the actual worker which may
1080 * or may not be the right one... basically, we need
1081 * to find which member actually handled this request.
1083 if ((strncasecmp(real, "balancer:", 9) == 0) &&
1084 (balancer = ap_proxy_get_balancer(r->pool, sconf, real))) {
1086 proxy_worker *worker;
1087 worker = (proxy_worker *)balancer->workers->elts;
1088 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1089 "ppr: checking balancer: %s",
1091 for (n = 0; n < balancer->workers->nelts; n++) {
1093 u = apr_psprintf(r->pool, "%s://%s:%d/", worker->scheme,
1094 worker->hostname, worker->port);
1097 u = apr_psprintf(r->pool, "%s://%s/", worker->scheme,
1100 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1101 "ppr: matching member (%s) and URL (%s)",
1105 if (l1 >= l2 && strncasecmp(u, url, l2) == 0) {
1106 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1107 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1108 "ppr: matched member (%s)", u);
1109 return ap_construct_url(r->pool, u, r);
1116 if (l1 >= l2 && strncasecmp(real, url, l2) == 0) {
1117 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1118 return ap_construct_url(r->pool, u, r);
1126 * Cookies are a bit trickier to match: we've got two substrings to worry
1127 * about, and we can't just find them with strstr 'cos of case. Regexp
1128 * matching would be an easy fix, but for better consistency with all the
1129 * other matches we'll refrain and use apr_strmatch to find path=/domain=
1130 * and stick to plain strings for the config values.
1132 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1133 proxy_dir_conf *conf, const char *str)
1135 proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1137 struct proxy_alias *ent;
1138 size_t len = strlen(str);
1139 const char *newpath = NULL;
1140 const char *newdomain = NULL;
1142 const char *domainp;
1143 const char *pathe = NULL;
1144 const char *domaine = NULL;
1145 size_t l1, l2, poffs = 0, doffs = 0;
1151 if (r->proxyreq != PROXYREQ_REVERSE) {
1156 * Find the match and replacement, but save replacing until we've done
1157 * both path and domain so we know the new strlen
1159 if ((pathp = apr_strmatch(conf->cookie_path_str, str, len)) != NULL) {
1161 poffs = pathp - str;
1162 pathe = ap_strchr_c(pathp, ';');
1163 l1 = pathe ? (pathe - pathp) : strlen(pathp);
1164 pathe = pathp + l1 ;
1165 if (conf->interpolate_env == 1) {
1166 ent = (struct proxy_alias *)rconf->cookie_paths->elts;
1169 ent = (struct proxy_alias *)conf->cookie_paths->elts;
1171 for (i = 0; i < conf->cookie_paths->nelts; i++) {
1172 l2 = strlen(ent[i].fake);
1173 if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1174 newpath = ent[i].real;
1175 pdiff = strlen(newpath) - l1;
1181 if ((domainp = apr_strmatch(conf->cookie_domain_str, str, len)) != NULL) {
1183 doffs = domainp - str;
1184 domaine = ap_strchr_c(domainp, ';');
1185 l1 = domaine ? (domaine - domainp) : strlen(domainp);
1186 domaine = domainp + l1;
1187 if (conf->interpolate_env == 1) {
1188 ent = (struct proxy_alias *)rconf->cookie_domains->elts;
1191 ent = (struct proxy_alias *)conf->cookie_domains->elts;
1193 for (i = 0; i < conf->cookie_domains->nelts; i++) {
1194 l2 = strlen(ent[i].fake);
1195 if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1196 newdomain = ent[i].real;
1197 ddiff = strlen(newdomain) - l1;
1204 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1205 l1 = strlen(newpath);
1207 l2 = strlen(newdomain);
1208 if (doffs > poffs) {
1209 memcpy(ret, str, poffs);
1210 memcpy(ret + poffs, newpath, l1);
1211 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1212 memcpy(ret + doffs + pdiff, newdomain, l2);
1213 strcpy(ret + doffs + pdiff + l2, domaine);
1216 memcpy(ret, str, doffs) ;
1217 memcpy(ret + doffs, newdomain, l2);
1218 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1219 memcpy(ret + poffs + ddiff, newpath, l1);
1220 strcpy(ret + poffs + ddiff + l1, pathe);
1224 memcpy(ret, str, poffs);
1225 memcpy(ret + poffs, newpath, l1);
1226 strcpy(ret + poffs + l1, pathe);
1231 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1232 l2 = strlen(newdomain);
1233 memcpy(ret, str, doffs);
1234 memcpy(ret + doffs, newdomain, l2);
1235 strcpy(ret + doffs+l2, domaine);
1238 ret = (char *)str; /* no change */
1245 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1246 proxy_server_conf *conf,
1249 proxy_balancer *balancer;
1250 char *c, *uri = apr_pstrdup(p, url);
1253 c = strchr(uri, ':');
1254 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1257 /* remove path from uri */
1258 if ((c = strchr(c + 3, '/'))) {
1261 balancer = (proxy_balancer *)conf->balancers->elts;
1262 for (i = 0; i < conf->balancers->nelts; i++) {
1263 if (strcasecmp(balancer->name, uri) == 0) {
1271 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1273 proxy_server_conf *conf,
1276 char *c, *q, *uri = apr_pstrdup(p, url);
1277 proxy_balancer_method *lbmethod;
1279 c = strchr(uri, ':');
1280 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1281 return "Bad syntax for a balancer name";
1282 /* remove path from uri */
1283 if ((q = strchr(c + 3, '/')))
1286 ap_str_tolower(uri);
1287 *balancer = apr_array_push(conf->balancers);
1288 memset(*balancer, 0, sizeof(proxy_balancer));
1291 * NOTE: The default method is byrequests, which we assume
1294 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1296 return "Can't find 'byrequests' lb method";
1299 (*balancer)->name = uri;
1300 (*balancer)->lbmethod = lbmethod;
1301 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker));
1302 /* XXX Is this a right place to create mutex */
1304 if (apr_thread_mutex_create(&((*balancer)->mutex),
1305 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1306 /* XXX: Do we need to log something here */
1307 return "can not create thread mutex";
1314 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1315 proxy_server_conf *conf,
1318 proxy_worker *worker;
1319 proxy_worker *max_worker = NULL;
1323 int worker_name_length;
1328 c = ap_strchr_c(url, ':');
1329 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1333 url_copy = apr_pstrdup(p, url);
1334 url_length = strlen(url);
1337 * We need to find the start of the path and
1338 * therefore we know the length of the scheme://hostname/
1339 * part to we can force-lowercase everything up to
1340 * the start of the path.
1342 c = ap_strchr_c(c+3, '/');
1345 pathstart = url_copy + (c - url);
1347 ap_str_tolower(url_copy);
1348 min_match = strlen(url_copy);
1352 ap_str_tolower(url_copy);
1353 min_match = strlen(url_copy);
1356 worker = (proxy_worker *)conf->workers->elts;
1359 * Do a "longest match" on the worker name to find the worker that
1360 * fits best to the URL, but keep in mind that we must have at least
1361 * a minimum matching of length min_match such that
1362 * scheme://hostname[:port] matches between worker and url.
1364 for (i = 0; i < conf->workers->nelts; i++) {
1365 if ( ((worker_name_length = strlen(worker->name)) <= url_length)
1366 && (worker_name_length >= min_match)
1367 && (worker_name_length > max_match)
1368 && (strncmp(url_copy, worker->name, worker_name_length) == 0) ) {
1369 max_worker = worker;
1370 max_match = worker_name_length;
1378 static apr_status_t conn_pool_cleanup(void *theworker)
1380 proxy_worker *worker = (proxy_worker *)theworker;
1381 if (worker->cp->res) {
1382 worker->cp->pool = NULL;
1388 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1391 proxy_conn_pool *cp;
1394 * Create a connection pool's subpool.
1395 * This pool is used for connection recycling.
1396 * Once the worker is added it is never removed but
1397 * it can be disabled.
1399 apr_pool_create(&pool, p);
1400 apr_pool_tag(pool, "proxy_worker_cp");
1402 * Alloc from the same pool as worker.
1403 * proxy_conn_pool is permanently attached to the worker.
1405 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1410 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1412 proxy_server_conf *conf,
1418 rv = apr_uri_parse(p, url, &uri);
1420 if (rv != APR_SUCCESS) {
1421 return "Unable to parse URL";
1423 if (!uri.hostname || !uri.scheme) {
1424 return "URL must be absolute!";
1427 ap_str_tolower(uri.hostname);
1428 ap_str_tolower(uri.scheme);
1429 *worker = apr_array_push(conf->workers);
1430 memset(*worker, 0, sizeof(proxy_worker));
1431 (*worker)->name = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1432 (*worker)->scheme = uri.scheme;
1433 (*worker)->hostname = uri.hostname;
1434 (*worker)->port = uri.port;
1435 (*worker)->id = proxy_lb_workers;
1436 (*worker)->flush_packets = flush_off;
1437 (*worker)->flush_wait = PROXY_FLUSH_WAIT;
1438 /* Increase the total worker count */
1440 init_conn_pool(p, *worker);
1442 if (apr_thread_mutex_create(&((*worker)->mutex),
1443 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1444 /* XXX: Do we need to log something here */
1445 return "can not create thread mutex";
1452 PROXY_DECLARE(proxy_worker *) ap_proxy_create_worker(apr_pool_t *p)
1455 proxy_worker *worker;
1456 worker = (proxy_worker *)apr_pcalloc(p, sizeof(proxy_worker));
1457 worker->id = proxy_lb_workers;
1458 /* Increase the total worker count */
1460 init_conn_pool(p, worker);
1466 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer,
1467 proxy_worker *worker)
1469 proxy_worker *runtime;
1471 runtime = apr_array_push(balancer->workers);
1472 memcpy(runtime, worker, sizeof(proxy_worker));
1473 runtime->id = proxy_lb_workers;
1474 /* Increase the total runtime count */
1479 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1480 proxy_balancer **balancer,
1482 proxy_server_conf *conf, char **url)
1486 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1487 if (access_status == DECLINED && *balancer == NULL) {
1488 *worker = ap_proxy_get_worker(r->pool, conf, *url);
1490 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1491 "proxy: %s: found worker %s for %s",
1492 (*worker)->scheme, (*worker)->name, *url);
1497 else if (r->proxyreq == PROXYREQ_PROXY) {
1498 if (conf->forward) {
1499 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1500 "proxy: *: found forward proxy worker for %s",
1503 *worker = conf->forward;
1507 else if (r->proxyreq == PROXYREQ_REVERSE) {
1508 if (conf->reverse) {
1509 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1510 "proxy: *: found reverse proxy worker for %s",
1513 *worker = conf->reverse;
1518 else if (access_status == DECLINED && *balancer != NULL) {
1519 /* All the workers are busy */
1520 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1521 "proxy: all workers are busy. Unable to serve %s",
1523 access_status = HTTP_SERVICE_UNAVAILABLE;
1525 return access_status;
1528 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1529 proxy_balancer *balancer,
1531 proxy_server_conf *conf)
1533 int access_status = OK;
1535 access_status = proxy_run_post_request(worker, balancer, r, conf);
1536 if (access_status == DECLINED) {
1537 access_status = OK; /* no post_request handler available */
1538 /* TODO: recycle direct worker */
1542 return access_status;
1546 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1547 const char *proxy_function,
1548 apr_sockaddr_t *backend_addr,
1549 const char *backend_name,
1550 proxy_server_conf *conf,
1558 while (backend_addr && !connected) {
1559 if ((rv = apr_socket_create(newsock, backend_addr->family,
1560 SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1561 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1562 ap_log_error(APLOG_MARK, loglevel, rv, s,
1563 "proxy: %s: error creating fam %d socket for target %s",
1565 backend_addr->family,
1568 * this could be an IPv6 address from the DNS but the
1569 * local machine won't give us an IPv6 socket; hopefully the
1570 * DNS returned an additional address to try
1572 backend_addr = backend_addr->next;
1576 #if !defined(TPF) && !defined(BEOS)
1577 if (conf->recv_buffer_size > 0 &&
1578 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1579 conf->recv_buffer_size))) {
1580 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1581 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1582 "ProxyReceiveBufferSize, using default");
1586 rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
1587 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1588 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1589 "apr_socket_opt_set(APR_TCP_NODELAY): "
1593 /* Set a timeout on the socket */
1594 if (conf->timeout_set == 1) {
1595 apr_socket_timeout_set(*newsock, conf->timeout);
1598 apr_socket_timeout_set(*newsock, s->timeout);
1601 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1602 "proxy: %s: fam %d socket created to connect to %s",
1603 proxy_function, backend_addr->family, backend_name);
1605 /* make the connection out of the socket */
1606 rv = apr_socket_connect(*newsock, backend_addr);
1608 /* if an error occurred, loop round and try again */
1609 if (rv != APR_SUCCESS) {
1610 apr_socket_close(*newsock);
1611 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1612 ap_log_error(APLOG_MARK, loglevel, rv, s,
1613 "proxy: %s: attempt to connect to %pI (%s) failed",
1617 backend_addr = backend_addr->next;
1622 return connected ? 0 : 1;
1625 static apr_status_t connection_cleanup(void *theconn)
1627 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1628 proxy_worker *worker = conn->worker;
1629 apr_bucket_brigade *bb;
1634 * If the connection pool is NULL the worker
1635 * cleanup has been run. Just return.
1642 /* Sanity check: Did we already return the pooled connection? */
1643 if (conn->inreslist) {
1644 ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool,
1645 "proxy: Pooled connection 0x%pp for worker %s has been"
1646 " already returned to the connection pool.", conn,
1653 if (conn->need_flush && r && (r->bytes_sent || r->eos_sent)) {
1655 * We need to ensure that buckets that may have been buffered in the
1656 * network filters get flushed to the network. This is needed since
1657 * these buckets have been created with the bucket allocator of the
1658 * backend connection. This allocator either gets destroyed if
1659 * conn->close is set or the worker address is not reusable which
1660 * causes the connection to the backend to be closed or it will be used
1661 * again by another frontend connection that wants to recycle the
1662 * backend connection.
1663 * In this case we could run into nasty race conditions (e.g. if the
1664 * next user of the backend connection destroys the allocator before we
1665 * sent the buckets to the network).
1667 * Remark 1: Only do this if buckets where sent down the chain before
1668 * that could still be buffered in the network filter. This is the case
1669 * if we have sent an EOS bucket or if we actually sent buckets with
1670 * data down the chain. In all other cases we either have not sent any
1671 * buckets at all down the chain or we only sent meta buckets that are
1672 * not EOS buckets down the chain. The only meta bucket that remains in
1673 * this case is the flush bucket which would have removed all possibly
1674 * buffered buckets in the network filter.
1675 * If we sent a flush bucket in the case where not ANY buckets were
1676 * sent down the chain, we break error handling which happens AFTER us.
1678 * Remark 2: Doing a setaside does not help here as the buckets remain
1679 * created by the wrong allocator in this case.
1681 * Remark 3: Yes, this creates a possible performance penalty in the case
1682 * of pipelined requests as we may send only a small amount of data over
1686 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1689 * If we have already sent an EOS bucket send directly to the
1690 * connection based filters. We just want to flush the buckets
1691 * if something hasn't been sent to the network yet.
1693 ap_fflush(c->output_filters, bb);
1696 ap_fflush(r->output_filters, bb);
1698 apr_brigade_destroy(bb);
1700 conn->need_flush = 0;
1703 /* determine if the connection need to be closed */
1704 if (conn->close || !worker->is_address_reusable || worker->disablereuse) {
1705 apr_pool_t *p = conn->pool;
1707 conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1709 conn->worker = worker;
1710 apr_pool_create(&(conn->scpool), p);
1711 apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1714 if (worker->hmax && worker->cp->res) {
1715 conn->inreslist = 1;
1716 apr_reslist_release(worker->cp->res, (void *)conn);
1721 worker->cp->conn = conn;
1724 /* Always return the SUCCESS */
1728 static void socket_cleanup(proxy_conn_rec *conn)
1731 conn->connection = NULL;
1732 apr_pool_clear(conn->scpool);
1735 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1738 apr_bucket_brigade *bb;
1742 * If we have an existing SSL connection it might be possible that the
1743 * server sent some SSL message we have not read so far (e.g. a SSL
1744 * shutdown message if the server closed the keepalive connection while
1745 * the connection was held unused in our pool).
1746 * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1747 * processed. We don't expect any data to be in the returned brigade.
1749 if (conn->sock && conn->connection) {
1750 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1751 rv = ap_get_brigade(conn->connection->input_filters, bb,
1752 AP_MODE_READBYTES, APR_NONBLOCK_READ,
1754 if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1755 socket_cleanup(conn);
1757 if (!APR_BRIGADE_EMPTY(bb)) {
1760 rv = apr_brigade_length(bb, 0, &len);
1761 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r,
1762 "proxy: SSL cleanup brigade contained %"
1763 APR_OFF_T_FMT " bytes of data.", len);
1765 apr_brigade_destroy(bb);
1770 /* reslist constructor */
1771 static apr_status_t connection_constructor(void **resource, void *params,
1776 proxy_conn_rec *conn;
1777 proxy_worker *worker = (proxy_worker *)params;
1780 * Create the subpool for each connection
1781 * This keeps the memory consumption constant
1782 * when disconnecting from backend.
1784 apr_pool_create(&ctx, pool);
1785 apr_pool_tag(ctx, "proxy_conn_pool");
1787 * Create another subpool that manages the data for the
1788 * socket and the connection member of the proxy_conn_rec struct as we
1789 * destroy this data more frequently than other data in the proxy_conn_rec
1790 * struct like hostname and addr (at least in the case where we have
1791 * keepalive connections that timed out).
1793 apr_pool_create(&scpool, ctx);
1794 apr_pool_tag(scpool, "proxy_conn_scpool");
1795 conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1798 conn->scpool = scpool;
1799 conn->worker = worker;
1801 conn->inreslist = 1;
1808 #if APR_HAS_THREADS /* only needed when threads are used */
1809 /* reslist destructor */
1810 static apr_status_t connection_destructor(void *resource, void *params,
1813 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1815 /* Destroy the pool only if not called from reslist_destroy */
1816 if (conn->worker->cp->pool) {
1817 apr_pool_destroy(conn->pool);
1825 * ap_proxy_initialize_worker_share() concerns itself
1826 * with initializing those parts of worker which
1827 * are, or could be, shared. Basically worker->s
1829 PROXY_DECLARE(void) ap_proxy_initialize_worker_share(proxy_server_conf *conf,
1830 proxy_worker *worker,
1833 proxy_worker_stat *score = NULL;
1835 if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1836 /* The worker share is already initialized */
1837 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1838 "proxy: worker %s already initialized",
1842 /* Get scoreboard slot */
1843 if (ap_scoreboard_image) {
1844 score = (proxy_worker_stat *) ap_get_scoreboard_lb(worker->id);
1846 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1847 "proxy: ap_get_scoreboard_lb(%d) failed in child %" APR_PID_T_FMT " for worker %s",
1848 worker->id, getpid(), worker->name);
1851 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1852 "proxy: grabbed scoreboard slot %d in child %" APR_PID_T_FMT " for worker %s",
1853 worker->id, getpid(), worker->name);
1857 score = (proxy_worker_stat *) apr_pcalloc(conf->pool, sizeof(proxy_worker_stat));
1858 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1859 "proxy: initialized plain memory in child %" APR_PID_T_FMT " for worker %s",
1860 getpid(), worker->name);
1864 * recheck to see if we've already been here. Possible
1865 * if proxy is using scoreboard to hold shared stats
1867 if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1868 /* The worker share is already initialized */
1869 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1870 "proxy: worker %s already initialized",
1874 if (worker->route) {
1875 strcpy(worker->s->route, worker->route);
1878 *worker->s->route = '\0';
1880 if (worker->redirect) {
1881 strcpy(worker->s->redirect, worker->redirect);
1884 *worker->s->redirect = '\0';
1887 worker->s->status |= (worker->status | PROXY_WORKER_INITIALIZED);
1891 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s)
1899 if (worker->status & PROXY_WORKER_INITIALIZED) {
1900 /* The worker is already initialized */
1904 /* Set default parameters */
1905 if (!worker->retry_set) {
1906 worker->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1908 /* By default address is reusable unless DisableReuse is set */
1909 if (worker->disablereuse) {
1910 worker->is_address_reusable = 0;
1913 worker->is_address_reusable = 1;
1917 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1918 if (mpm_threads > 1) {
1919 /* Set hard max to no more then mpm_threads */
1920 if (worker->hmax == 0 || worker->hmax > mpm_threads) {
1921 worker->hmax = mpm_threads;
1923 if (worker->smax == 0 || worker->smax > worker->hmax) {
1924 worker->smax = worker->hmax;
1926 /* Set min to be lower then smax */
1927 if (worker->min > worker->smax) {
1928 worker->min = worker->smax;
1932 /* This will supress the apr_reslist creation */
1933 worker->min = worker->smax = worker->hmax = 0;
1936 rv = apr_reslist_create(&(worker->cp->res),
1937 worker->min, worker->smax,
1938 worker->hmax, worker->ttl,
1939 connection_constructor, connection_destructor,
1940 worker, worker->cp->pool);
1942 apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1944 apr_pool_cleanup_null);
1946 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1947 "proxy: initialized worker %d in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1948 worker->id, getpid(), worker->hostname, worker->min,
1949 worker->hmax, worker->smax);
1951 #if (APR_MAJOR_VERSION > 0)
1952 /* Set the acquire timeout */
1953 if (rv == APR_SUCCESS && worker->acquire_set) {
1954 apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1963 rv = connection_constructor(&conn, worker, worker->cp->pool);
1964 worker->cp->conn = conn;
1966 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1967 "proxy: initialized single connection worker %d in child %" APR_PID_T_FMT " for (%s)",
1968 worker->id, getpid(), worker->hostname);
1970 if (rv == APR_SUCCESS) {
1971 worker->status |= (PROXY_WORKER_INITIALIZED);
1976 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1977 proxy_worker *worker,
1980 if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1981 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1982 "proxy: %s: retrying the worker for (%s)",
1983 proxy_function, worker->hostname);
1984 if (apr_time_now() > worker->s->error_time + worker->retry) {
1985 ++worker->s->retries;
1986 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1987 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1988 "proxy: %s: worker for (%s) has been marked for retry",
1989 proxy_function, worker->hostname);
2001 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
2002 proxy_conn_rec **conn,
2003 proxy_worker *worker,
2008 if (!PROXY_WORKER_IS_USABLE(worker)) {
2009 /* Retry the worker */
2010 ap_proxy_retry_worker(proxy_function, worker, s);
2012 if (!PROXY_WORKER_IS_USABLE(worker)) {
2013 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2014 "proxy: %s: disabled connection for (%s)",
2015 proxy_function, worker->hostname);
2016 return HTTP_SERVICE_UNAVAILABLE;
2020 if (worker->hmax && worker->cp->res) {
2021 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2026 /* create the new connection if the previous was destroyed */
2027 if (!worker->cp->conn) {
2028 connection_constructor((void **)conn, worker, worker->cp->pool);
2031 *conn = worker->cp->conn;
2032 worker->cp->conn = NULL;
2037 if (rv != APR_SUCCESS) {
2038 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2039 "proxy: %s: failed to acquire connection for (%s)",
2040 proxy_function, worker->hostname);
2041 return HTTP_SERVICE_UNAVAILABLE;
2043 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2044 "proxy: %s: has acquired connection for (%s)",
2045 proxy_function, worker->hostname);
2047 (*conn)->worker = worker;
2050 (*conn)->inreslist = 0;
2056 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2057 proxy_conn_rec *conn,
2060 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2061 "proxy: %s: has released connection for (%s)",
2062 proxy_function, conn->worker->hostname);
2063 connection_cleanup(conn);
2069 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2070 proxy_server_conf *conf,
2071 proxy_worker *worker,
2072 proxy_conn_rec *conn,
2075 const char *proxyname,
2076 apr_port_t proxyport,
2077 char *server_portstr,
2078 int server_portstr_size)
2081 apr_status_t err = APR_SUCCESS;
2082 apr_status_t uerr = APR_SUCCESS;
2087 * Break up the URL to determine the host to connect to
2090 /* we break the URL into host, port, uri */
2091 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2092 return ap_proxyerror(r, HTTP_BAD_REQUEST,
2093 apr_pstrcat(p,"URI cannot be parsed: ", *url,
2097 uri->port = apr_uri_port_of_scheme(uri->scheme);
2100 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2101 "proxy: connecting %s to %s:%d", *url, uri->hostname,
2105 * allocate these out of the specified connection pool
2106 * The scheme handler decides if this is permanent or
2107 * short living pool.
2109 /* are we connecting directly, or via a proxy? */
2111 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2112 uri->query ? uri->query : "",
2113 uri->fragment ? "#" : "",
2114 uri->fragment ? uri->fragment : "", NULL);
2117 * Make sure that we pick the the correct and valid worker.
2118 * If a single keepalive connection triggers different workers,
2119 * then we have a problem (we don't select the correct one).
2120 * Do an expensive check in this case, where we compare the
2121 * the hostnames associated between the two.
2123 * TODO: Handle this much better...
2125 if (!conn->hostname || !worker->is_address_reusable ||
2126 worker->disablereuse ||
2127 (r->connection->keepalives &&
2128 (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2129 (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2131 conn->hostname = apr_pstrdup(conn->pool, proxyname);
2132 conn->port = proxyport;
2135 conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2136 conn->port = uri->port;
2138 socket_cleanup(conn);
2139 err = apr_sockaddr_info_get(&(conn->addr),
2140 conn->hostname, APR_UNSPEC,
2144 else if (!worker->cp->addr) {
2145 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2146 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
2148 return HTTP_INTERNAL_SERVER_ERROR;
2152 * Worker can have the single constant backend adress.
2153 * The single DNS lookup is used once per worker.
2154 * If dynamic change is needed then set the addr to NULL
2155 * inside dynamic config to force the lookup.
2157 err = apr_sockaddr_info_get(&(worker->cp->addr),
2158 conn->hostname, APR_UNSPEC,
2161 conn->addr = worker->cp->addr;
2162 if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2163 ap_log_error(APLOG_MARK, APLOG_ERR, uerr, r->server,
2168 conn->addr = worker->cp->addr;
2171 if (err != APR_SUCCESS) {
2172 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2173 apr_pstrcat(p, "DNS lookup failure for: ",
2174 conn->hostname, NULL));
2177 /* Get the server port for the Via headers */
2179 server_port = ap_get_server_port(r);
2180 if (ap_is_default_port(server_port, r)) {
2181 strcpy(server_portstr,"");
2184 apr_snprintf(server_portstr, server_portstr_size, ":%d",
2188 /* check if ProxyBlock directive on this host */
2189 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2190 return ap_proxyerror(r, HTTP_FORBIDDEN,
2191 "Connect to remote machine blocked");
2193 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2194 "proxy: connected %s to %s:%d", *url, conn->hostname,
2199 #define USE_ALTERNATE_IS_CONNECTED 1
2201 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2202 #define APR_MSG_PEEK MSG_PEEK
2205 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2206 static int is_socket_connected(apr_socket_t *socket)
2208 apr_pollfd_t pfds[1];
2209 apr_status_t status;
2212 pfds[0].reqevents = APR_POLLIN;
2213 pfds[0].desc_type = APR_POLL_SOCKET;
2214 pfds[0].desc.s = socket;
2217 status = apr_poll(&pfds[0], 1, &nfds, 0);
2218 } while (APR_STATUS_IS_EINTR(status));
2220 if (status == APR_SUCCESS && nfds == 1 &&
2221 pfds[0].rtnevents == APR_POLLIN) {
2222 apr_sockaddr_t unused;
2225 /* The socket might be closed in which case
2226 * the poll will return POLLIN.
2227 * If there is no data available the socket
2230 status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2232 if (status == APR_SUCCESS && len)
2237 else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2244 static int is_socket_connected(apr_socket_t *sock)
2247 apr_size_t buffer_len = 1;
2248 char test_buffer[1];
2249 apr_status_t socket_status;
2250 apr_interval_time_t current_timeout;
2253 apr_socket_timeout_get(sock, ¤t_timeout);
2254 /* set no timeout */
2255 apr_socket_timeout_set(sock, 0);
2256 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2257 /* put back old timeout */
2258 apr_socket_timeout_set(sock, current_timeout);
2259 if (APR_STATUS_IS_EOF(socket_status)
2260 || APR_STATUS_IS_ECONNRESET(socket_status)) {
2267 #endif /* USE_ALTERNATE_IS_CONNECTED */
2269 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2270 proxy_conn_rec *conn,
2271 proxy_worker *worker,
2277 apr_sockaddr_t *backend_addr = conn->addr;
2278 apr_socket_t *newsock;
2279 void *sconf = s->module_config;
2280 proxy_server_conf *conf =
2281 (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2284 if (!(connected = is_socket_connected(conn->sock))) {
2285 socket_cleanup(conn);
2286 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2287 "proxy: %s: backend socket is disconnected.",
2291 while (backend_addr && !connected) {
2292 if ((rv = apr_socket_create(&newsock, backend_addr->family,
2293 SOCK_STREAM, APR_PROTO_TCP,
2294 conn->scpool)) != APR_SUCCESS) {
2295 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2296 ap_log_error(APLOG_MARK, loglevel, rv, s,
2297 "proxy: %s: error creating fam %d socket for target %s",
2299 backend_addr->family,
2302 * this could be an IPv6 address from the DNS but the
2303 * local machine won't give us an IPv6 socket; hopefully the
2304 * DNS returned an additional address to try
2306 backend_addr = backend_addr->next;
2309 conn->connection = NULL;
2311 #if !defined(TPF) && !defined(BEOS)
2312 if (worker->recv_buffer_size > 0 &&
2313 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2314 worker->recv_buffer_size))) {
2315 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2316 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2317 "ProxyReceiveBufferSize, using default");
2321 rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2322 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2323 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2324 "apr_socket_opt_set(APR_TCP_NODELAY): "
2328 /* Set a timeout for connecting to the backend on the socket */
2329 if (worker->conn_timeout_set) {
2330 apr_socket_timeout_set(newsock, worker->conn_timeout);
2332 else if (worker->timeout_set == 1) {
2333 apr_socket_timeout_set(newsock, worker->timeout);
2335 else if (conf->timeout_set == 1) {
2336 apr_socket_timeout_set(newsock, conf->timeout);
2339 apr_socket_timeout_set(newsock, s->timeout);
2341 /* Set a keepalive option */
2342 if (worker->keepalive) {
2343 if ((rv = apr_socket_opt_set(newsock,
2344 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2345 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2346 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2350 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2351 "proxy: %s: fam %d socket created to connect to %s",
2352 proxy_function, backend_addr->family, worker->hostname);
2354 /* make the connection out of the socket */
2355 rv = apr_socket_connect(newsock, backend_addr);
2357 /* if an error occurred, loop round and try again */
2358 if (rv != APR_SUCCESS) {
2359 apr_socket_close(newsock);
2360 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2361 ap_log_error(APLOG_MARK, loglevel, rv, s,
2362 "proxy: %s: attempt to connect to %pI (%s) failed",
2366 backend_addr = backend_addr->next;
2370 /* Set a timeout on the socket */
2371 if (worker->timeout_set == 1) {
2372 apr_socket_timeout_set(newsock, worker->timeout);
2374 else if (conf->timeout_set == 1) {
2375 apr_socket_timeout_set(newsock, conf->timeout);
2378 apr_socket_timeout_set(newsock, s->timeout);
2381 conn->sock = newsock;
2385 * Put the entire worker to error state if
2386 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2387 * Altrough some connections may be alive
2388 * no further connections to the worker could be made
2390 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2391 !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2392 worker->s->status |= PROXY_WORKER_IN_ERROR;
2393 worker->s->error_time = apr_time_now();
2394 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2395 "ap_proxy_connect_backend disabling worker for (%s)",
2399 worker->s->error_time = 0;
2400 worker->s->retries = 0;
2402 return connected ? OK : DECLINED;
2405 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2406 proxy_conn_rec *conn,
2410 apr_sockaddr_t *backend_addr = conn->addr;
2412 apr_interval_time_t current_timeout;
2413 apr_bucket_alloc_t *bucket_alloc;
2415 if (conn->connection) {
2420 * We need to flush the buckets before we return the connection to the
2421 * connection pool. See comment in connection_cleanup for why this is
2424 conn->need_flush = 1;
2425 bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2427 * The socket is now open, create a new backend server connection
2429 conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2433 if (!conn->connection) {
2435 * the peer reset the connection already; ap_run_create_connection()
2438 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2439 s, "proxy: %s: an error occurred creating a "
2440 "new connection to %pI (%s)", proxy_function,
2441 backend_addr, conn->hostname);
2442 /* XXX: Will be closed when proxy_conn is closed */
2443 socket_cleanup(conn);
2444 return HTTP_INTERNAL_SERVER_ERROR;
2447 /* For ssl connection to backend */
2449 if (!ap_proxy_ssl_enable(conn->connection)) {
2450 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2451 s, "proxy: %s: failed to enable ssl support "
2452 "for %pI (%s)", proxy_function,
2453 backend_addr, conn->hostname);
2454 return HTTP_INTERNAL_SERVER_ERROR;
2458 /* TODO: See if this will break FTP */
2459 ap_proxy_ssl_disable(conn->connection);
2462 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2463 "proxy: %s: connection complete to %pI (%s)",
2464 proxy_function, backend_addr, conn->hostname);
2467 * save the timeout of the socket because core_pre_connection
2468 * will set it to base_server->timeout
2469 * (core TimeOut directive).
2471 apr_socket_timeout_get(conn->sock, ¤t_timeout);
2472 /* set up the connection filters */
2473 rc = ap_run_pre_connection(conn->connection, conn->sock);
2474 if (rc != OK && rc != DONE) {
2475 conn->connection->aborted = 1;
2476 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2477 "proxy: %s: pre_connection setup failed (%d)",
2478 proxy_function, rc);
2481 apr_socket_timeout_set(conn->sock, current_timeout);
2486 int ap_proxy_lb_workers(void)
2489 * Since we can't resize the scoreboard when reconfiguring, we
2490 * have to impose a limit on the number of workers, we are
2491 * able to reconfigure to.
2493 if (!lb_workers_limit)
2494 lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2495 return lb_workers_limit;
2498 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2499 apr_bucket_brigade *brigade)
2502 conn_rec *c = r->connection;
2506 * If this is a subrequest, then prevent also caching of the main
2510 r->main->no_cache = 1;
2511 e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2513 APR_BRIGADE_INSERT_TAIL(brigade, e);
2514 e = apr_bucket_eos_create(c->bucket_alloc);
2515 APR_BRIGADE_INSERT_TAIL(brigade, e);