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"
23 #include "proxy_util.h"
26 #include <unistd.h> /* for getpid() */
29 #if (APR_MAJOR_VERSION < 1)
30 #undef apr_socket_create
31 #define apr_socket_create apr_socket_create_ex
34 APLOG_USE_MODULE(proxy);
37 * Opaque structure containing target server info when
38 * using a forward proxy.
39 * Up to now only used in combination with HTTP CONNECT.
42 int use_http_connect; /* Use SSL Tunneling via HTTP CONNECT */
43 const char *target_host; /* Target hostname */
44 apr_port_t target_port; /* Target port */
45 const char *proxy_auth; /* Proxy authorization */
48 /* Keep synced with mod_proxy.h! */
54 {PROXY_WORKER_INITIALIZED, PROXY_WORKER_INITIALIZED_FLAG, "Init "},
55 {PROXY_WORKER_IGNORE_ERRORS, PROXY_WORKER_IGNORE_ERRORS_FLAG, "Ign "},
56 {PROXY_WORKER_DRAIN, PROXY_WORKER_DRAIN_FLAG, "Drn "},
57 {PROXY_WORKER_IN_SHUTDOWN, PROXY_WORKER_IN_SHUTDOWN_FLAG, "Shut "},
58 {PROXY_WORKER_DISABLED, PROXY_WORKER_DISABLED_FLAG, "Dis "},
59 {PROXY_WORKER_STOPPED, PROXY_WORKER_STOPPED_FLAG, "Stop "},
60 {PROXY_WORKER_IN_ERROR, PROXY_WORKER_IN_ERROR_FLAG, "Err "},
61 {PROXY_WORKER_HOT_STANDBY, PROXY_WORKER_HOT_STANDBY_FLAG, "Stby "},
62 {PROXY_WORKER_FREE, PROXY_WORKER_FREE_FLAG, "Free "},
66 /* Global balancer counter */
67 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
68 static int lb_workers_limit = 0;
69 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_path;
70 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_domain;
72 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
73 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
74 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
75 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
77 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
78 (request_rec *r, request_rec *pr), (r, pr),
81 PROXY_DECLARE(apr_status_t) ap_proxy_strncpy(char *dst, const char *src, size_t dlen)
83 if ((strlen(src)+1) > dlen) {
84 /* APR_ENOSPACE would be better */
88 apr_cpystrn(dst, src, dlen);
93 /* already called in the knowledge that the characters are hex digits */
94 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
98 #if !APR_CHARSET_EBCDIC
101 if (apr_isdigit(ch)) {
104 else if (apr_isupper(ch)) {
113 if (apr_isdigit(ch)) {
116 else if (apr_isupper(ch)) {
117 i += ch - ('A' - 10);
120 i += ch - ('a' - 10);
123 #else /*APR_CHARSET_EBCDIC*/
125 * we assume that the hex value refers to an ASCII character
126 * so convert to EBCDIC so that it makes sense locally;
130 * client specifies %20 in URL to refer to a space char;
131 * at this point we're called with EBCDIC "20"; after turning
132 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
133 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
138 if (1 == sscanf(x, "%2x", &i)) {
140 ap_xlate_proto_from_ascii(buf, 1);
146 #endif /*APR_CHARSET_EBCDIC*/
149 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
151 #if !APR_CHARSET_EBCDIC
155 i = (ch & 0xF0) >> 4;
157 x[1] = ('A' - 10) + i;
165 x[2] = ('A' - 10) + i;
170 #else /*APR_CHARSET_EBCDIC*/
171 static const char ntoa[] = { "0123456789ABCDEF" };
177 ap_xlate_proto_to_ascii(buf, 1);
180 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
181 x[2] = ntoa[buf[0] & 0x0F];
183 #endif /*APR_CHARSET_EBCDIC*/
187 * canonicalise a URL-encoded string
191 * Convert a URL-encoded string to canonical form.
192 * It decodes characters which need not be encoded,
193 * and encodes those which must be encoded, and does not touch
194 * those which must not be touched.
196 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
197 enum enctype t, int forcedec,
202 char *allowed; /* characters which should not be encoded */
203 char *reserved; /* characters which much not be en/de-coded */
206 * N.B. in addition to :@&=, this allows ';' in an http path
207 * and '?' in an ftp path -- this may be revised
209 * Also, it makes a '+' character in a search string reserved, as
210 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
211 * it only permits ; / ? : @ = & as reserved chars.)
214 allowed = "~$-_.+!*'(),;:@&=";
216 else if (t == enc_search) {
217 allowed = "$-_.!*'(),;:@&=";
219 else if (t == enc_user) {
220 allowed = "$-_.+!*'(),;@&=";
222 else if (t == enc_fpath) {
223 allowed = "$-_.+!*'(),?:@&=";
225 else { /* if (t == enc_parm) */
226 allowed = "$-_.+!*'(),?/:@&=";
232 else if (t == enc_search) {
239 y = apr_palloc(p, 3 * len + 1);
241 for (i = 0, j = 0; i < len; i++, j++) {
242 /* always handle '/' first */
244 if (strchr(reserved, ch)) {
249 * decode it if not already done. do not decode reverse proxied URLs
250 * unless specifically forced
252 if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
253 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
256 ch = ap_proxy_hex2c(&x[i + 1]);
258 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
259 ap_proxy_c2hex(ch, &y[j]);
264 /* recode it, if necessary */
265 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
266 ap_proxy_c2hex(ch, &y[j]);
278 * Parses network-location.
279 * urlp on input the URL; on output the path, after the leading /
280 * user NULL if no user/password permitted
281 * password holder for password
282 * host holder for host
283 * port port number; only set if one is supplied.
285 * Returns an error string.
287 PROXY_DECLARE(char *)
288 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
289 char **passwordp, char **hostp, apr_port_t *port)
291 char *addr, *scope_id, *strp, *host, *url = *urlp;
292 char *user = NULL, *password = NULL;
296 if (url[0] != '/' || url[1] != '/') {
297 return "Malformed URL";
300 url = strchr(host, '/');
305 *(url++) = '\0'; /* skip seperating '/' */
308 /* find _last_ '@' since it might occur in user/password part */
309 strp = strrchr(host, '@');
317 strp = strchr(user, ':');
320 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
321 if (password == NULL) {
322 return "Bad %-escape in URL (password)";
326 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
328 return "Bad %-escape in URL (username)";
334 if (passwordp != NULL) {
335 *passwordp = password;
339 * Parse the host string to separate host portion from optional port.
340 * Perform range checking on port.
342 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
343 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
344 return "Invalid host/port";
346 if (tmp_port != 0) { /* only update caller's port if port was specified */
350 ap_str_tolower(addr); /* DNS names are case-insensitive */
358 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
363 apr_pool_create(&pool, c->pool);
365 rp = apr_pcalloc(pool, sizeof(*r));
368 rp->status = HTTP_OK;
370 rp->headers_in = apr_table_make(pool, 50);
371 rp->subprocess_env = apr_table_make(pool, 50);
372 rp->headers_out = apr_table_make(pool, 12);
373 rp->err_headers_out = apr_table_make(pool, 5);
374 rp->notes = apr_table_make(pool, 5);
376 rp->server = r->server;
378 rp->proxyreq = r->proxyreq;
379 rp->request_time = r->request_time;
381 rp->output_filters = c->output_filters;
382 rp->input_filters = c->input_filters;
383 rp->proto_output_filters = c->output_filters;
384 rp->proto_input_filters = c->input_filters;
385 rp->client_ip = c->peer_ip;
386 rp->client_addr = c->peer_addr;
388 rp->request_config = ap_create_request_config(pool);
389 proxy_run_create_req(r, rp);
395 * Converts 8 hex digits to a time integer
397 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
402 for (i = 0, j = 0; i < 8; i++) {
405 if (apr_isdigit(ch)) {
408 else if (apr_isupper(ch)) {
409 j |= ch - ('A' - 10);
412 j |= ch - ('a' - 10);
415 if (j == 0xffffffff) {
416 return -1; /* so that it works with 8-byte ints */
424 * Converts a time integer to 8 hex digits
426 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
431 for (i = 7; i >= 0; i--) {
435 y[i] = ch + ('A' - 10);
444 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
446 const char *uri = ap_escape_html(r->pool, r->uri);
447 apr_table_setn(r->notes, "error-notes",
449 "The proxy server could not handle the request <em><a href=\"",
450 uri, "\">", ap_escape_html(r->pool, r->method), " ", uri,
452 "Reason: <strong>", ap_escape_html(r->pool, message),
456 /* Allow "error-notes" string to be printed by ap_send_error_response() */
457 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
459 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
460 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00898) "%s returned by %s", message,
466 proxy_get_host_of_request(request_rec *r)
468 char *url, *user = NULL, *password = NULL, *err, *host;
471 if (r->hostname != NULL) {
475 /* Set url to the first char after "scheme://" */
476 if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
480 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
482 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
485 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00899) "%s", err);
490 return host; /* ought to return the port, too */
493 /* Return TRUE if addr represents an IP address (or an IP network address) */
494 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
496 const char *addr = This->name;
502 * if the address is given with an explicit netmask, use that
503 * Due to a deficiency in apr_inet_addr(), it is impossible to parse
504 * "partial" addresses (with less than 4 quads) correctly, i.e.
505 * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
506 * I therefore have to parse the IP address manually:
507 * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
508 * addr and mask were set by proxy_readmask()
513 * Parse IP addr manually, optionally allowing
514 * abbreviated net addresses like 192.168.
517 /* Iterate over up to 4 (dotted) quads. */
518 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
521 if (*addr == '/' && quads > 0) { /* netmask starts here. */
525 if (!apr_isdigit(*addr)) {
526 return 0; /* no digit at start of quad */
529 ip_addr[quads] = strtol(addr, &tmp, 0);
531 if (tmp == addr) { /* expected a digit, found something else */
535 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
542 if (*addr == '.' && quads != 3) {
543 ++addr; /* after the 4th quad, a dot would be illegal */
547 for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
548 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
551 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
556 bits = strtol(addr, &tmp, 0);
558 if (tmp == addr) { /* expected a digit, found something else */
564 if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
571 * Determine (i.e., "guess") netmask by counting the
572 * number of trailing .0's; reduce #quads appropriately
573 * (so that 192.168.0.0 is equivalent to 192.168.)
575 while (quads > 0 && ip_addr[quads - 1] == 0) {
579 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
584 /* every zero-byte counts as 8 zero-bits */
587 if (bits != 32) { /* no warning for fully qualified IP address */
588 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00900)
589 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
590 inet_ntoa(This->addr), bits);
594 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
596 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
597 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00901)
598 "Warning: NetMask and IP-Addr disagree in %s/%ld",
599 inet_ntoa(This->addr), bits);
600 This->addr.s_addr &= This->mask.s_addr;
601 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00902)
602 " Set to %s/%ld", inet_ntoa(This->addr), bits);
606 This->matcher = proxy_match_ipaddr;
610 return (*addr == '\0'); /* okay iff we've parsed the whole string */
614 /* Return TRUE if addr represents an IP address (or an IP network address) */
615 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
618 struct in_addr addr, *ip;
619 const char *host = proxy_get_host_of_request(r);
621 if (host == NULL) { /* oops! */
625 memset(&addr, '\0', sizeof addr);
626 memset(ip_addr, '\0', sizeof ip_addr);
628 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
629 for (addr.s_addr = 0, i = 0; i < 4; ++i) {
630 /* ap_proxy_is_ipaddr() already confirmed that we have
631 * a valid octet in ip_addr[i]
633 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
636 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
638 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00903)
639 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
640 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00904)
641 "%s/", inet_ntoa(This->addr));
642 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00905)
643 "%s", inet_ntoa(This->mask));
649 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00906)
650 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
651 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00907)
652 "%s/", inet_ntoa(This->addr));
653 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00908)
654 "%s", inet_ntoa(This->mask));
659 struct apr_sockaddr_t *reqaddr;
661 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
664 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00909)
665 "2)IP-NoMatch: hostname=%s msg=Host not found", host);
670 /* Try to deal with multiple IP addr's for a host */
671 /* FIXME: This needs to be able to deal with IPv6 */
673 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
674 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
676 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00910)
677 "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
678 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00911)
679 "%s/", inet_ntoa(This->addr));
680 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00912)
681 "%s", inet_ntoa(This->mask));
687 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00913)
688 "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
689 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00914)
690 "%s/", inet_ntoa(This->addr));
691 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00915)
692 "%s", inet_ntoa(This->mask));
695 reqaddr = reqaddr->next;
702 /* Return TRUE if addr represents a domain name */
703 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
705 char *addr = This->name;
708 /* Domain name must start with a '.' */
709 if (addr[0] != '.') {
713 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
714 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
719 if (addr[i] == ':') {
720 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
721 "@@@@ handle optional port in proxy_is_domainname()");
722 /* @@@@ handle optional port */
726 if (addr[i] != '\0') {
730 /* Strip trailing dots */
731 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
735 This->matcher = proxy_match_domainname;
739 /* Return TRUE if host "host" is in domain "domain" */
740 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
742 const char *host = proxy_get_host_of_request(r);
743 int d_len = strlen(This->name), h_len;
745 if (host == NULL) { /* some error was logged already */
749 h_len = strlen(host);
751 /* @@@ do this within the setup? */
752 /* Ignore trailing dots in domain comparison: */
753 while (d_len > 0 && This->name[d_len - 1] == '.') {
756 while (h_len > 0 && host[h_len - 1] == '.') {
760 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
763 /* Return TRUE if host represents a host name */
764 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
766 struct apr_sockaddr_t *addr;
767 char *host = This->name;
770 /* Host names must not start with a '.' */
771 if (host[0] == '.') {
774 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
775 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
777 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
781 This->hostaddr = addr;
783 /* Strip trailing dots */
784 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
788 This->matcher = proxy_match_hostname;
792 /* Return TRUE if host "host" is equal to host2 "host2" */
793 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
795 char *host = This->name;
796 const char *host2 = proxy_get_host_of_request(r);
800 if (host == NULL || host2 == NULL) {
801 return 0; /* oops! */
804 h2_len = strlen(host2);
805 h1_len = strlen(host);
808 struct apr_sockaddr_t *addr = *This->hostaddr;
810 /* Try to deal with multiple IP addr's for a host */
812 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
818 /* Ignore trailing dots in host2 comparison: */
819 while (h2_len > 0 && host2[h2_len - 1] == '.') {
822 while (h1_len > 0 && host[h1_len - 1] == '.') {
825 return h1_len == h2_len
826 && strncasecmp(host, host2, h1_len) == 0;
829 /* Return TRUE if addr is to be matched as a word */
830 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
832 This->matcher = proxy_match_word;
836 /* Return TRUE if string "str2" occurs literally in "str1" */
837 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
839 const char *host = proxy_get_host_of_request(r);
840 return host != NULL && ap_strstr_c(host, This->name) != NULL;
843 /* checks whether a host in uri_addr matches proxyblock */
844 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
845 apr_sockaddr_t *uri_addr)
848 apr_sockaddr_t * src_uri_addr = uri_addr;
849 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
850 for (j = 0; j < conf->noproxies->nelts; j++) {
851 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
852 struct apr_sockaddr_t *conf_addr = npent[j].addr;
853 uri_addr = src_uri_addr;
854 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
855 "checking remote machine [%s] against [%s]",
856 uri_addr->hostname, npent[j].name);
857 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
858 || npent[j].name[0] == '*') {
859 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(00916)
860 "connect to remote machine %s blocked: name %s "
861 "matched", uri_addr->hostname, npent[j].name);
862 return HTTP_FORBIDDEN;
865 uri_addr = src_uri_addr;
869 apr_sockaddr_ip_get(&conf_ip, conf_addr);
870 apr_sockaddr_ip_get(&uri_ip, uri_addr);
871 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
872 "ProxyBlock comparing %s and %s", conf_ip,
874 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
875 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(00917)
876 "connect to remote machine %s blocked: "
877 "IP %s matched", uri_addr->hostname, conf_ip);
878 return HTTP_FORBIDDEN;
880 uri_addr = uri_addr->next;
882 conf_addr = conf_addr->next;
888 /* set up the minimal filter set */
889 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
891 ap_add_input_filter("HTTP_IN", NULL, r, c);
895 /* unmerge an element in the table */
896 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
898 apr_off_t offset = 0;
902 /* get the value to unmerge */
903 const char *initial = apr_table_get(t, key);
907 value = apr_pstrdup(p, initial);
909 /* remove the value from the headers */
910 apr_table_unset(t, key);
912 /* find each comma */
913 while (value[count]) {
914 if (value[count] == ',') {
916 apr_table_add(t, key, value + offset);
921 apr_table_add(t, key, value + offset);
924 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
925 proxy_dir_conf *conf, const char *url)
927 proxy_req_conf *rconf;
928 struct proxy_alias *ent;
933 * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
935 * XXX FIXME: Ensure the /uri component is a case sensitive match
937 if (r->proxyreq != PROXYREQ_REVERSE) {
942 if (conf->interpolate_env == 1) {
943 rconf = ap_get_module_config(r->request_config, &proxy_module);
944 ent = (struct proxy_alias *)rconf->raliases->elts;
947 ent = (struct proxy_alias *)conf->raliases->elts;
949 for (i = 0; i < conf->raliases->nelts; i++) {
950 proxy_server_conf *sconf = (proxy_server_conf *)
951 ap_get_module_config(r->server->module_config, &proxy_module);
952 proxy_balancer *balancer;
953 const char *real = ent[i].real;
955 * First check if mapping against a balancer and see
956 * if we have such a entity. If so, then we need to
957 * find the particulars of the actual worker which may
958 * or may not be the right one... basically, we need
959 * to find which member actually handled this request.
961 if (ap_proxy_valid_balancer_name((char *)real, 0) &&
962 (balancer = ap_proxy_get_balancer(r->pool, sconf, real, 1))) {
964 proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
965 const char *urlpart = ap_strchr_c(real, '/');
970 l3 = strlen(urlpart);
972 /* The balancer comparison is a bit trickier. Given the context
973 * BalancerMember balancer://alias http://example.com/foo
974 * ProxyPassReverse /bash balancer://alias/bar
975 * translate url http://example.com/foo/bar/that to /bash/that
977 for (n = 0; n < balancer->workers->nelts; n++) {
978 l2 = strlen((*worker)->s->name);
980 /* urlpart (l3) assuredly starts with its own '/' */
981 if ((*worker)->s->name[l2 - 1] == '/')
984 && strncasecmp((*worker)->s->name, url, l2) == 0
985 && strncmp(urlpart, url + l2, l3) == 0) {
986 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2 + l3],
988 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
991 else if (l1 >= l2 && strncasecmp((*worker)->s->name, url, l2) == 0) {
992 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
993 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
999 const char *part = url;
1001 if (real[0] == '/') {
1002 part = ap_strstr_c(url, "://");
1004 part = ap_strchr_c(part+3, '/');
1016 if (l1 >= l2 && strncasecmp(real, part, l2) == 0) {
1017 u = apr_pstrcat(r->pool, ent[i].fake, &part[l2], NULL);
1018 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1027 * Cookies are a bit trickier to match: we've got two substrings to worry
1028 * about, and we can't just find them with strstr 'cos of case. Regexp
1029 * matching would be an easy fix, but for better consistency with all the
1030 * other matches we'll refrain and use apr_strmatch to find path=/domain=
1031 * and stick to plain strings for the config values.
1033 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1034 proxy_dir_conf *conf, const char *str)
1036 proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1038 struct proxy_alias *ent;
1039 size_t len = strlen(str);
1040 const char *newpath = NULL;
1041 const char *newdomain = NULL;
1043 const char *domainp;
1044 const char *pathe = NULL;
1045 const char *domaine = NULL;
1046 size_t l1, l2, poffs = 0, doffs = 0;
1052 if (r->proxyreq != PROXYREQ_REVERSE) {
1057 * Find the match and replacement, but save replacing until we've done
1058 * both path and domain so we know the new strlen
1060 if ((pathp = apr_strmatch(ap_proxy_strmatch_path, str, len)) != NULL) {
1062 poffs = pathp - str;
1063 pathe = ap_strchr_c(pathp, ';');
1064 l1 = pathe ? (pathe - pathp) : strlen(pathp);
1065 pathe = pathp + l1 ;
1066 if (conf->interpolate_env == 1) {
1067 ent = (struct proxy_alias *)rconf->cookie_paths->elts;
1070 ent = (struct proxy_alias *)conf->cookie_paths->elts;
1072 for (i = 0; i < conf->cookie_paths->nelts; i++) {
1073 l2 = strlen(ent[i].fake);
1074 if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1075 newpath = ent[i].real;
1076 pdiff = strlen(newpath) - l1;
1082 if ((domainp = apr_strmatch(ap_proxy_strmatch_domain, str, len)) != NULL) {
1084 doffs = domainp - str;
1085 domaine = ap_strchr_c(domainp, ';');
1086 l1 = domaine ? (domaine - domainp) : strlen(domainp);
1087 domaine = domainp + l1;
1088 if (conf->interpolate_env == 1) {
1089 ent = (struct proxy_alias *)rconf->cookie_domains->elts;
1092 ent = (struct proxy_alias *)conf->cookie_domains->elts;
1094 for (i = 0; i < conf->cookie_domains->nelts; i++) {
1095 l2 = strlen(ent[i].fake);
1096 if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1097 newdomain = ent[i].real;
1098 ddiff = strlen(newdomain) - l1;
1105 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1106 l1 = strlen(newpath);
1108 l2 = strlen(newdomain);
1109 if (doffs > poffs) {
1110 memcpy(ret, str, poffs);
1111 memcpy(ret + poffs, newpath, l1);
1112 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1113 memcpy(ret + doffs + pdiff, newdomain, l2);
1114 strcpy(ret + doffs + pdiff + l2, domaine);
1117 memcpy(ret, str, doffs) ;
1118 memcpy(ret + doffs, newdomain, l2);
1119 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1120 memcpy(ret + poffs + ddiff, newpath, l1);
1121 strcpy(ret + poffs + ddiff + l1, pathe);
1125 memcpy(ret, str, poffs);
1126 memcpy(ret + poffs, newpath, l1);
1127 strcpy(ret + poffs + l1, pathe);
1132 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1133 l2 = strlen(newdomain);
1134 memcpy(ret, str, doffs);
1135 memcpy(ret + doffs, newdomain, l2);
1136 strcpy(ret + doffs+l2, domaine);
1139 ret = (char *)str; /* no change */
1147 * BALANCER related...
1151 * verifies that the balancer name conforms to standards.
1153 PROXY_DECLARE(int) ap_proxy_valid_balancer_name(char *name, int i)
1156 i = sizeof(BALANCER_PREFIX)-1;
1157 return (!strncasecmp(name, BALANCER_PREFIX, i));
1161 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1162 proxy_server_conf *conf,
1166 proxy_balancer *balancer;
1167 char *c, *uri = apr_pstrdup(p, url);
1171 ap_str_tolower(uri);
1172 c = strchr(uri, ':');
1173 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1176 /* remove path from uri */
1177 if ((c = strchr(c + 3, '/'))) {
1180 hash.def = ap_proxy_hashfunc(uri, PROXY_HASHFUNC_DEFAULT);
1181 hash.fnv = ap_proxy_hashfunc(uri, PROXY_HASHFUNC_FNV);
1182 balancer = (proxy_balancer *)conf->balancers->elts;
1183 for (i = 0; i < conf->balancers->nelts; i++) {
1184 if (balancer->hash.def == hash.def && balancer->hash.fnv == hash.fnv) {
1185 if (!care || !balancer->s->inactive) {
1195 PROXY_DECLARE(char *) ap_proxy_update_balancer(apr_pool_t *p,
1196 proxy_balancer *balancer,
1200 if (apr_uri_parse(p, url, &puri) != APR_SUCCESS) {
1201 return apr_psprintf(p, "unable to parse: %s", url);
1203 if (puri.path && PROXY_STRNCPY(balancer->s->vpath, puri.path) != APR_SUCCESS) {
1204 return apr_psprintf(p, "balancer %s front-end virtual-path (%s) too long",
1205 balancer->s->name, puri.path);
1207 if (puri.hostname && PROXY_STRNCPY(balancer->s->vhost, puri.hostname) != APR_SUCCESS) {
1208 return apr_psprintf(p, "balancer %s front-end vhost name (%s) too long",
1209 balancer->s->name, puri.hostname);
1214 PROXY_DECLARE(char *) ap_proxy_define_balancer(apr_pool_t *p,
1215 proxy_balancer **balancer,
1216 proxy_server_conf *conf,
1221 char nonce[APR_UUID_FORMATTED_LENGTH + 1];
1222 proxy_balancer_method *lbmethod;
1224 proxy_balancer_shared *bshared;
1225 char *c, *q, *uri = apr_pstrdup(p, url);
1228 /* We should never get here without a valid BALANCER_PREFIX... */
1230 c = strchr(uri, ':');
1231 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1232 return "Bad syntax for a balancer name";
1233 /* remove path from uri */
1234 if ((q = strchr(c + 3, '/')))
1237 ap_str_tolower(uri);
1238 *balancer = apr_array_push(conf->balancers);
1239 memset(*balancer, 0, sizeof(proxy_balancer));
1242 * NOTE: The default method is byrequests, which we assume
1245 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1247 return "Can't find 'byrequests' lb method";
1250 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1251 (*balancer)->gmutex = NULL;
1252 (*balancer)->tmutex = NULL;
1253 (*balancer)->lbmethod = lbmethod;
1256 bshared = ap_malloc(sizeof(proxy_balancer_shared));
1258 bshared = apr_palloc(p, sizeof(proxy_balancer_shared));
1260 memset(bshared, 0, sizeof(proxy_balancer_shared));
1262 bshared->was_malloced = (do_malloc != 0);
1263 PROXY_STRNCPY(bshared->lbpname, "byrequests");
1264 if (PROXY_STRNCPY(bshared->name, uri) != APR_SUCCESS) {
1265 return apr_psprintf(p, "balancer name (%s) too long", uri);
1267 ap_pstr2_alnum(p, bshared->name + sizeof(BALANCER_PREFIX) - 1,
1269 sname = apr_pstrcat(p, conf->id, "_", sname, NULL);
1270 if (PROXY_STRNCPY(bshared->sname, sname) != APR_SUCCESS) {
1271 return apr_psprintf(p, "balancer safe-name (%s) too long", sname);
1273 bshared->hash.def = ap_proxy_hashfunc(bshared->name, PROXY_HASHFUNC_DEFAULT);
1274 bshared->hash.fnv = ap_proxy_hashfunc(bshared->name, PROXY_HASHFUNC_FNV);
1275 (*balancer)->hash = bshared->hash;
1277 /* Retrieve a UUID and store the nonce for the lifetime of
1279 apr_uuid_get(&uuid);
1280 apr_uuid_format(nonce, &uuid);
1281 if (PROXY_STRNCPY(bshared->nonce, nonce) != APR_SUCCESS) {
1282 return apr_psprintf(p, "balancer nonce (%s) too long", nonce);
1285 (*balancer)->s = bshared;
1286 (*balancer)->sconf = conf;
1288 return ap_proxy_update_balancer(p, *balancer, alias);
1292 * Create an already defined balancer and free up memory.
1294 PROXY_DECLARE(apr_status_t) ap_proxy_share_balancer(proxy_balancer *balancer,
1295 proxy_balancer_shared *shm,
1298 proxy_balancer_method *lbmethod;
1299 if (!shm || !balancer->s)
1302 memcpy(shm, balancer->s, sizeof(proxy_balancer_shared));
1303 if (balancer->s->was_malloced)
1306 balancer->s->index = i;
1307 /* the below should always succeed */
1308 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, balancer->s->lbpname, "0");
1310 balancer->lbmethod = lbmethod;
1314 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_balancer(proxy_balancer *balancer, server_rec *s, apr_pool_t *p)
1316 apr_status_t rv = APR_SUCCESS;
1317 ap_slotmem_provider_t *storage = balancer->storage;
1322 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, APLOGNO(00918)
1323 "no provider for %s", balancer->s->name);
1324 return APR_EGENERAL;
1327 * for each balancer we need to init the global
1328 * mutex and then attach to the shared worker shm
1330 if (!balancer->gmutex) {
1331 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, APLOGNO(00919)
1332 "no mutex %s", balancer->s->name);
1333 return APR_EGENERAL;
1336 /* Re-open the mutex for the child. */
1337 rv = apr_global_mutex_child_init(&(balancer->gmutex),
1338 apr_global_mutex_lockfile(balancer->gmutex),
1340 if (rv != APR_SUCCESS) {
1341 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(00920)
1342 "Failed to reopen mutex %s in child",
1348 storage->attach(&(balancer->wslot), balancer->s->sname, &size, &num, p);
1349 if (!balancer->wslot) {
1350 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, APLOGNO(00921) "slotmem_attach failed");
1351 return APR_EGENERAL;
1353 if (balancer->lbmethod && balancer->lbmethod->reset)
1354 balancer->lbmethod->reset(balancer, s);
1356 if (balancer->tmutex == NULL) {
1357 rv = apr_thread_mutex_create(&(balancer->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1358 if (rv != APR_SUCCESS) {
1359 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, APLOGNO(00922)
1360 "can not create balancer thread mutex");
1368 * CONNECTION related...
1371 static apr_status_t conn_pool_cleanup(void *theworker)
1373 proxy_worker *worker = (proxy_worker *)theworker;
1374 if (worker->cp->res) {
1375 worker->cp->pool = NULL;
1380 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1383 proxy_conn_pool *cp;
1386 * Create a connection pool's subpool.
1387 * This pool is used for connection recycling.
1388 * Once the worker is added it is never removed but
1389 * it can be disabled.
1391 apr_pool_create(&pool, p);
1392 apr_pool_tag(pool, "proxy_worker_cp");
1394 * Alloc from the same pool as worker.
1395 * proxy_conn_pool is permanently attached to the worker.
1397 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1402 static apr_status_t connection_cleanup(void *theconn)
1404 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1405 proxy_worker *worker = conn->worker;
1408 * If the connection pool is NULL the worker
1409 * cleanup has been run. Just return.
1416 apr_pool_destroy(conn->r->pool);
1420 /* Sanity check: Did we already return the pooled connection? */
1421 if (conn->inreslist) {
1422 ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool, APLOGNO(00923)
1423 "Pooled connection 0x%pp for worker %s has been"
1424 " already returned to the connection pool.", conn,
1429 /* determine if the connection need to be closed */
1430 if (conn->close || !worker->s->is_address_reusable || worker->s->disablereuse) {
1431 apr_pool_t *p = conn->pool;
1433 conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1435 conn->worker = worker;
1436 apr_pool_create(&(conn->scpool), p);
1437 apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1440 if (worker->s->hmax && worker->cp->res) {
1441 conn->inreslist = 1;
1442 apr_reslist_release(worker->cp->res, (void *)conn);
1446 worker->cp->conn = conn;
1449 /* Always return the SUCCESS */
1453 static void socket_cleanup(proxy_conn_rec *conn)
1456 conn->connection = NULL;
1457 apr_pool_clear(conn->scpool);
1460 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1463 apr_bucket_brigade *bb;
1467 * If we have an existing SSL connection it might be possible that the
1468 * server sent some SSL message we have not read so far (e.g. an SSL
1469 * shutdown message if the server closed the keepalive connection while
1470 * the connection was held unused in our pool).
1471 * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1472 * processed. We don't expect any data to be in the returned brigade.
1474 if (conn->sock && conn->connection) {
1475 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1476 rv = ap_get_brigade(conn->connection->input_filters, bb,
1477 AP_MODE_READBYTES, APR_NONBLOCK_READ,
1479 if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1480 socket_cleanup(conn);
1482 if (!APR_BRIGADE_EMPTY(bb)) {
1485 rv = apr_brigade_length(bb, 0, &len);
1486 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, rv, r,
1487 "SSL cleanup brigade contained %"
1488 APR_OFF_T_FMT " bytes of data.", len);
1490 apr_brigade_destroy(bb);
1495 /* reslist constructor */
1496 static apr_status_t connection_constructor(void **resource, void *params,
1501 proxy_conn_rec *conn;
1502 proxy_worker *worker = (proxy_worker *)params;
1505 * Create the subpool for each connection
1506 * This keeps the memory consumption constant
1507 * when disconnecting from backend.
1509 apr_pool_create(&ctx, pool);
1510 apr_pool_tag(ctx, "proxy_conn_pool");
1512 * Create another subpool that manages the data for the
1513 * socket and the connection member of the proxy_conn_rec struct as we
1514 * destroy this data more frequently than other data in the proxy_conn_rec
1515 * struct like hostname and addr (at least in the case where we have
1516 * keepalive connections that timed out).
1518 apr_pool_create(&scpool, ctx);
1519 apr_pool_tag(scpool, "proxy_conn_scpool");
1520 conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1523 conn->scpool = scpool;
1524 conn->worker = worker;
1525 conn->inreslist = 1;
1531 /* reslist destructor */
1532 static apr_status_t connection_destructor(void *resource, void *params,
1535 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1537 /* Destroy the pool only if not called from reslist_destroy */
1538 if (conn->worker->cp->pool) {
1539 apr_pool_destroy(conn->pool);
1549 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1550 proxy_balancer *balancer,
1551 proxy_server_conf *conf,
1554 proxy_worker *worker;
1555 proxy_worker *max_worker = NULL;
1559 int worker_name_length;
1564 c = ap_strchr_c(url, ':');
1565 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1569 url_length = strlen(url);
1570 url_copy = apr_pstrmemdup(p, url, url_length);
1573 * We need to find the start of the path and
1574 * therefore we know the length of the scheme://hostname/
1575 * part to we can force-lowercase everything up to
1576 * the start of the path.
1578 c = ap_strchr_c(c+3, '/');
1581 pathstart = url_copy + (c - url);
1583 ap_str_tolower(url_copy);
1584 min_match = strlen(url_copy);
1588 ap_str_tolower(url_copy);
1589 min_match = strlen(url_copy);
1592 * Do a "longest match" on the worker name to find the worker that
1593 * fits best to the URL, but keep in mind that we must have at least
1594 * a minimum matching of length min_match such that
1595 * scheme://hostname[:port] matches between worker and url.
1599 proxy_worker **workers = (proxy_worker **)balancer->workers->elts;
1600 for (i = 0; i < balancer->workers->nelts; i++, workers++) {
1602 if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1603 && (worker_name_length >= min_match)
1604 && (worker_name_length > max_match)
1605 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1606 max_worker = worker;
1607 max_match = worker_name_length;
1612 worker = (proxy_worker *)conf->workers->elts;
1613 for (i = 0; i < conf->workers->nelts; i++, worker++) {
1614 if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1615 && (worker_name_length >= min_match)
1616 && (worker_name_length > max_match)
1617 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1618 max_worker = worker;
1619 max_match = worker_name_length;
1628 * To create a worker from scratch first we define the
1629 * specifics of the worker; this is all local data.
1630 * We then allocate space for it if data needs to be
1631 * shared. This allows for dynamic addition during
1632 * config and runtime.
1634 PROXY_DECLARE(char *) ap_proxy_define_worker(apr_pool_t *p,
1635 proxy_worker **worker,
1636 proxy_balancer *balancer,
1637 proxy_server_conf *conf,
1643 proxy_worker_shared *wshared;
1646 rv = apr_uri_parse(p, url, &uri);
1648 if (rv != APR_SUCCESS) {
1649 return "Unable to parse URL";
1651 if (!uri.hostname || !uri.scheme) {
1652 return "URL must be absolute!";
1655 ap_str_tolower(uri.hostname);
1656 ap_str_tolower(uri.scheme);
1658 * Workers can be associated w/ balancers or on their
1659 * own; ie: the generic reverse-proxy or a worker
1660 * in a simple ProxyPass statement. eg:
1662 * ProxyPass / http://www.example.com
1664 * in which case the worker goes in the conf slot.
1667 proxy_worker **runtime;
1668 /* recall that we get a ptr to the ptr here */
1669 runtime = apr_array_push(balancer->workers);
1670 *worker = *runtime = apr_palloc(p, sizeof(proxy_worker)); /* right to left baby */
1671 /* we've updated the list of workers associated with
1672 * this balancer *locally* */
1673 balancer->wupdated = apr_time_now();
1675 *worker = apr_array_push(conf->workers);
1677 /* we need to allocate space here */
1678 *worker = apr_palloc(p, sizeof(proxy_worker));
1681 memset(*worker, 0, sizeof(proxy_worker));
1682 /* right here we just want to tuck away the worker info.
1683 * if called during config, we don't have shm setup yet,
1684 * so just note the info for later. */
1686 wshared = ap_malloc(sizeof(proxy_worker_shared)); /* will be freed ap_proxy_share_worker */
1688 wshared = apr_palloc(p, sizeof(proxy_worker_shared));
1690 memset(wshared, 0, sizeof(proxy_worker_shared));
1692 ptr = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1693 if (PROXY_STRNCPY(wshared->name, ptr) != APR_SUCCESS) {
1694 return apr_psprintf(p, "worker name (%s) too long", ptr);
1696 if (PROXY_STRNCPY(wshared->scheme, uri.scheme) != APR_SUCCESS) {
1697 return apr_psprintf(p, "worker scheme (%s) too long", uri.scheme);
1699 if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) {
1700 return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
1702 wshared->port = uri.port;
1703 wshared->flush_packets = flush_off;
1704 wshared->flush_wait = PROXY_FLUSH_WAIT;
1705 wshared->is_address_reusable = 1;
1706 wshared->lbfactor = 1;
1708 wshared->hash.def = ap_proxy_hashfunc(wshared->name, PROXY_HASHFUNC_DEFAULT);
1709 wshared->hash.fnv = ap_proxy_hashfunc(wshared->name, PROXY_HASHFUNC_FNV);
1710 wshared->was_malloced = (do_malloc != 0);
1712 (*worker)->hash = wshared->hash;
1713 (*worker)->context = NULL;
1714 (*worker)->cp = NULL;
1715 (*worker)->balancer = balancer;
1716 (*worker)->s = wshared;
1722 * Create an already defined worker and free up memory
1724 PROXY_DECLARE(apr_status_t) ap_proxy_share_worker(proxy_worker *worker, proxy_worker_shared *shm,
1727 if (!shm || !worker->s)
1730 memcpy(shm, worker->s, sizeof(proxy_worker_shared));
1731 if (worker->s->was_malloced)
1732 free(worker->s); /* was malloced in ap_proxy_define_worker */
1734 worker->s->index = i;
1738 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1740 apr_status_t rv = APR_SUCCESS;
1743 if (worker->s->status & PROXY_WORKER_INITIALIZED) {
1744 /* The worker is already initialized */
1745 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00924)
1746 "worker %s shared already initialized", worker->s->name);
1749 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00925)
1750 "initializing worker %s shared", worker->s->name);
1751 /* Set default parameters */
1752 if (!worker->s->retry_set) {
1753 worker->s->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1755 /* By default address is reusable unless DisableReuse is set */
1756 if (worker->s->disablereuse) {
1757 worker->s->is_address_reusable = 0;
1760 worker->s->is_address_reusable = 1;
1763 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1764 if (mpm_threads > 1) {
1765 /* Set hard max to no more then mpm_threads */
1766 if (worker->s->hmax == 0 || worker->s->hmax > mpm_threads) {
1767 worker->s->hmax = mpm_threads;
1769 if (worker->s->smax == -1 || worker->s->smax > worker->s->hmax) {
1770 worker->s->smax = worker->s->hmax;
1772 /* Set min to be lower then smax */
1773 if (worker->s->min > worker->s->smax) {
1774 worker->s->min = worker->s->smax;
1778 /* This will supress the apr_reslist creation */
1779 worker->s->min = worker->s->smax = worker->s->hmax = 0;
1783 /* What if local is init'ed and shm isn't?? Even possible? */
1784 if (worker->local_status & PROXY_WORKER_INITIALIZED) {
1785 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00926)
1786 "worker %s local already initialized", worker->s->name);
1789 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00927)
1790 "initializing worker %s local", worker->s->name);
1791 /* Now init local worker data */
1792 if (worker->tmutex == NULL) {
1793 rv = apr_thread_mutex_create(&(worker->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1794 if (rv != APR_SUCCESS) {
1795 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00928)
1796 "can not create worker thread mutex");
1800 if (worker->cp == NULL)
1801 init_conn_pool(p, worker);
1802 if (worker->cp == NULL) {
1803 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00929)
1804 "can not create connection pool");
1805 return APR_EGENERAL;
1808 if (worker->s->hmax) {
1809 rv = apr_reslist_create(&(worker->cp->res),
1810 worker->s->min, worker->s->smax,
1811 worker->s->hmax, worker->s->ttl,
1812 connection_constructor, connection_destructor,
1813 worker, worker->cp->pool);
1815 apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1817 apr_pool_cleanup_null);
1819 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00930)
1820 "initialized pool in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1821 getpid(), worker->s->hostname, worker->s->min,
1822 worker->s->hmax, worker->s->smax);
1824 /* Set the acquire timeout */
1825 if (rv == APR_SUCCESS && worker->s->acquire_set) {
1826 apr_reslist_timeout_set(worker->cp->res, worker->s->acquire);
1833 rv = connection_constructor(&conn, worker, worker->cp->pool);
1834 worker->cp->conn = conn;
1836 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00931)
1837 "initialized single connection worker in child %" APR_PID_T_FMT " for (%s)",
1838 getpid(), worker->s->hostname);
1841 if (rv == APR_SUCCESS) {
1842 worker->s->status |= (PROXY_WORKER_INITIALIZED);
1843 worker->local_status |= (PROXY_WORKER_INITIALIZED);
1848 static int ap_proxy_retry_worker(const char *proxy_function, proxy_worker *worker,
1851 if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1852 if (apr_time_now() > worker->s->error_time + worker->s->retry) {
1853 ++worker->s->retries;
1854 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1855 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00932)
1856 "%s: worker for (%s) has been marked for retry",
1857 proxy_function, worker->s->hostname);
1861 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00933)
1862 "%s: too soon to retry worker for (%s)",
1863 proxy_function, worker->s->hostname);
1872 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1873 proxy_balancer **balancer,
1875 proxy_server_conf *conf, char **url)
1879 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1880 if (access_status == DECLINED && *balancer == NULL) {
1881 *worker = ap_proxy_get_worker(r->pool, NULL, conf, *url);
1883 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1884 "%s: found worker %s for %s",
1885 (*worker)->s->scheme, (*worker)->s->name, *url);
1890 else if (r->proxyreq == PROXYREQ_PROXY) {
1891 if (conf->forward) {
1892 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1893 "*: found forward proxy worker for %s", *url);
1895 *worker = conf->forward;
1898 * The forward worker does not keep connections alive, so
1899 * ensure that mod_proxy_http does the correct thing
1900 * regarding the Connection header in the request.
1902 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
1905 else if (r->proxyreq == PROXYREQ_REVERSE) {
1906 if (conf->reverse) {
1907 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1908 "*: found reverse proxy worker for %s", *url);
1910 *worker = conf->reverse;
1913 * The reverse worker does not keep connections alive, so
1914 * ensure that mod_proxy_http does the correct thing
1915 * regarding the Connection header in the request.
1917 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
1921 else if (access_status == DECLINED && *balancer != NULL) {
1922 /* All the workers are busy */
1923 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00934)
1924 "all workers are busy. Unable to serve %s", *url);
1925 access_status = HTTP_SERVICE_UNAVAILABLE;
1927 return access_status;
1930 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1931 proxy_balancer *balancer,
1933 proxy_server_conf *conf)
1935 int access_status = OK;
1937 access_status = proxy_run_post_request(worker, balancer, r, conf);
1938 if (access_status == DECLINED) {
1939 access_status = OK; /* no post_request handler available */
1940 /* TODO: recycle direct worker */
1944 return access_status;
1948 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1949 const char *proxy_function,
1950 apr_sockaddr_t *backend_addr,
1951 const char *backend_name,
1952 proxy_server_conf *conf,
1959 while (backend_addr && !connected) {
1960 if ((rv = apr_socket_create(newsock, backend_addr->family,
1961 SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1962 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1963 ap_log_rerror(APLOG_MARK, loglevel, rv, r, APLOGNO(00935)
1964 "%s: error creating fam %d socket for target %s",
1965 proxy_function, backend_addr->family, backend_name);
1967 * this could be an IPv6 address from the DNS but the
1968 * local machine won't give us an IPv6 socket; hopefully the
1969 * DNS returned an additional address to try
1971 backend_addr = backend_addr->next;
1975 if (conf->recv_buffer_size > 0 &&
1976 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1977 conf->recv_buffer_size))) {
1978 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00936)
1979 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1980 "ProxyReceiveBufferSize, using default");
1983 rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
1984 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1985 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00937)
1986 "apr_socket_opt_set(APR_TCP_NODELAY): "
1990 /* Set a timeout on the socket */
1991 if (conf->timeout_set) {
1992 apr_socket_timeout_set(*newsock, conf->timeout);
1995 apr_socket_timeout_set(*newsock, r->server->timeout);
1998 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
1999 "%s: fam %d socket created to connect to %s",
2000 proxy_function, backend_addr->family, backend_name);
2002 if (conf->source_address) {
2003 rv = apr_socket_bind(*newsock, conf->source_address);
2004 if (rv != APR_SUCCESS) {
2005 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00938)
2006 "%s: failed to bind socket to local address",
2011 /* make the connection out of the socket */
2012 rv = apr_socket_connect(*newsock, backend_addr);
2014 /* if an error occurred, loop round and try again */
2015 if (rv != APR_SUCCESS) {
2016 apr_socket_close(*newsock);
2017 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2018 ap_log_rerror(APLOG_MARK, loglevel, rv, r, APLOGNO(00939)
2019 "%s: attempt to connect to %pI (%s) failed",
2020 proxy_function, backend_addr, backend_name);
2021 backend_addr = backend_addr->next;
2026 return connected ? 0 : 1;
2029 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
2030 proxy_conn_rec **conn,
2031 proxy_worker *worker,
2036 if (!PROXY_WORKER_IS_USABLE(worker)) {
2037 /* Retry the worker */
2038 ap_proxy_retry_worker(proxy_function, worker, s);
2040 if (!PROXY_WORKER_IS_USABLE(worker)) {
2041 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00940)
2042 "%s: disabled connection for (%s)",
2043 proxy_function, worker->s->hostname);
2044 return HTTP_SERVICE_UNAVAILABLE;
2048 if (worker->s->hmax && worker->cp->res) {
2049 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2052 /* create the new connection if the previous was destroyed */
2053 if (!worker->cp->conn) {
2054 connection_constructor((void **)conn, worker, worker->cp->pool);
2057 *conn = worker->cp->conn;
2058 worker->cp->conn = NULL;
2063 if (rv != APR_SUCCESS) {
2064 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00941)
2065 "%s: failed to acquire connection for (%s)",
2066 proxy_function, worker->s->hostname);
2067 return HTTP_SERVICE_UNAVAILABLE;
2069 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00942)
2070 "%s: has acquired connection for (%s)",
2071 proxy_function, worker->s->hostname);
2073 (*conn)->worker = worker;
2075 (*conn)->inreslist = 0;
2080 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2081 proxy_conn_rec *conn,
2084 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00943)
2085 "%s: has released connection for (%s)",
2086 proxy_function, conn->worker->s->hostname);
2087 connection_cleanup(conn);
2093 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2094 proxy_server_conf *conf,
2095 proxy_worker *worker,
2096 proxy_conn_rec *conn,
2099 const char *proxyname,
2100 apr_port_t proxyport,
2101 char *server_portstr,
2102 int server_portstr_size)
2105 apr_status_t err = APR_SUCCESS;
2106 apr_status_t uerr = APR_SUCCESS;
2109 * Break up the URL to determine the host to connect to
2112 /* we break the URL into host, port, uri */
2113 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2114 return ap_proxyerror(r, HTTP_BAD_REQUEST,
2115 apr_pstrcat(p,"URI cannot be parsed: ", *url,
2119 uri->port = apr_uri_port_of_scheme(uri->scheme);
2122 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00944)
2123 "connecting %s to %s:%d", *url, uri->hostname, uri->port);
2126 * allocate these out of the specified connection pool
2127 * The scheme handler decides if this is permanent or
2128 * short living pool.
2130 /* are we connecting directly, or via a proxy? */
2132 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2133 uri->query ? uri->query : "",
2134 uri->fragment ? "#" : "",
2135 uri->fragment ? uri->fragment : "", NULL);
2138 * Make sure that we pick the the correct and valid worker.
2139 * If a single keepalive connection triggers different workers,
2140 * then we have a problem (we don't select the correct one).
2141 * Do an expensive check in this case, where we compare the
2142 * the hostnames associated between the two.
2144 * TODO: Handle this much better...
2146 if (!conn->hostname || !worker->s->is_address_reusable ||
2147 worker->s->disablereuse ||
2148 (r->connection->keepalives &&
2149 (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2150 (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2152 conn->hostname = apr_pstrdup(conn->pool, proxyname);
2153 conn->port = proxyport;
2155 * If we have a forward proxy and the protocol is HTTPS,
2156 * then we need to prepend a HTTP CONNECT request before
2157 * sending our actual HTTPS requests.
2158 * Save our real backend data for using it later during HTTP CONNECT.
2161 const char *proxy_auth;
2163 forward_info *forward = apr_pcalloc(conn->pool, sizeof(forward_info));
2164 conn->forward = forward;
2165 forward->use_http_connect = 1;
2166 forward->target_host = apr_pstrdup(conn->pool, uri->hostname);
2167 forward->target_port = uri->port;
2168 /* Do we want to pass Proxy-Authorization along?
2169 * If we haven't used it, then YES
2170 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
2171 * So let's make it configurable by env.
2172 * The logic here is the same used in mod_proxy_http.
2174 proxy_auth = apr_table_get(r->headers_in, "Proxy-Authorization");
2175 if (proxy_auth != NULL &&
2176 proxy_auth[0] != '\0' &&
2177 r->user == NULL && /* we haven't yet authenticated */
2178 apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
2179 forward->proxy_auth = apr_pstrdup(conn->pool, proxy_auth);
2184 conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2185 conn->port = uri->port;
2187 socket_cleanup(conn);
2188 err = apr_sockaddr_info_get(&(conn->addr),
2189 conn->hostname, APR_UNSPEC,
2193 else if (!worker->cp->addr) {
2194 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2195 ap_log_rerror(APLOG_MARK, APLOG_ERR, err, r, APLOGNO(00945) "lock");
2196 return HTTP_INTERNAL_SERVER_ERROR;
2200 * Worker can have the single constant backend adress.
2201 * The single DNS lookup is used once per worker.
2202 * If dynamic change is needed then set the addr to NULL
2203 * inside dynamic config to force the lookup.
2205 err = apr_sockaddr_info_get(&(worker->cp->addr),
2206 conn->hostname, APR_UNSPEC,
2209 conn->addr = worker->cp->addr;
2210 if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2211 ap_log_rerror(APLOG_MARK, APLOG_ERR, uerr, r, APLOGNO(00946) "unlock");
2215 conn->addr = worker->cp->addr;
2217 /* Close a possible existing socket if we are told to do so */
2219 socket_cleanup(conn);
2223 if (err != APR_SUCCESS) {
2224 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2225 apr_pstrcat(p, "DNS lookup failure for: ",
2226 conn->hostname, NULL));
2229 /* Get the server port for the Via headers */
2231 server_port = ap_get_server_port(r);
2232 if (ap_is_default_port(server_port, r)) {
2233 strcpy(server_portstr,"");
2236 apr_snprintf(server_portstr, server_portstr_size, ":%d",
2240 /* check if ProxyBlock directive on this host */
2241 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2242 return ap_proxyerror(r, HTTP_FORBIDDEN,
2243 "Connect to remote machine blocked");
2245 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00947)
2246 "connected %s to %s:%d", *url, conn->hostname, conn->port);
2250 #define USE_ALTERNATE_IS_CONNECTED 1
2252 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2253 #define APR_MSG_PEEK MSG_PEEK
2256 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2257 static int is_socket_connected(apr_socket_t *socket)
2259 apr_pollfd_t pfds[1];
2260 apr_status_t status;
2263 pfds[0].reqevents = APR_POLLIN;
2264 pfds[0].desc_type = APR_POLL_SOCKET;
2265 pfds[0].desc.s = socket;
2268 status = apr_poll(&pfds[0], 1, &nfds, 0);
2269 } while (APR_STATUS_IS_EINTR(status));
2271 if (status == APR_SUCCESS && nfds == 1 &&
2272 pfds[0].rtnevents == APR_POLLIN) {
2273 apr_sockaddr_t unused;
2276 /* The socket might be closed in which case
2277 * the poll will return POLLIN.
2278 * If there is no data available the socket
2281 status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2283 if (status == APR_SUCCESS && len)
2288 else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2295 static int is_socket_connected(apr_socket_t *sock)
2298 apr_size_t buffer_len = 1;
2299 char test_buffer[1];
2300 apr_status_t socket_status;
2301 apr_interval_time_t current_timeout;
2304 apr_socket_timeout_get(sock, ¤t_timeout);
2305 /* set no timeout */
2306 apr_socket_timeout_set(sock, 0);
2307 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2308 /* put back old timeout */
2309 apr_socket_timeout_set(sock, current_timeout);
2310 if (APR_STATUS_IS_EOF(socket_status)
2311 || APR_STATUS_IS_ECONNRESET(socket_status)) {
2318 #endif /* USE_ALTERNATE_IS_CONNECTED */
2322 * Send a HTTP CONNECT request to a forward proxy.
2323 * The proxy is given by "backend", the target server
2324 * is contained in the "forward" member of "backend".
2326 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2333 char buffer[HUGE_STRING_LEN];
2334 char drain_buffer[HUGE_STRING_LEN];
2335 forward_info *forward = (forward_info *)backend->forward;
2338 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00948)
2339 "CONNECT: sending the CONNECT request for %s:%d "
2340 "to the remote proxy %pI (%s)",
2341 forward->target_host, forward->target_port,
2342 backend->addr, backend->hostname);
2343 /* Create the CONNECT request */
2344 nbytes = apr_snprintf(buffer, sizeof(buffer),
2345 "CONNECT %s:%d HTTP/1.0" CRLF,
2346 forward->target_host, forward->target_port);
2347 /* Add proxy authorization from the initial request if necessary */
2348 if (forward->proxy_auth != NULL) {
2349 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2350 "Proxy-Authorization: %s" CRLF,
2351 forward->proxy_auth);
2353 /* Set a reasonable agent and send everything */
2354 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2355 "Proxy-agent: %s" CRLF CRLF,
2356 ap_get_server_banner());
2357 apr_socket_send(backend->sock, buffer, &nbytes);
2359 /* Receive the whole CONNECT response */
2360 left = sizeof(buffer) - 1;
2361 /* Read until we find the end of the headers or run out of buffer */
2364 status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2368 if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2372 } while (status == APR_SUCCESS && left > 0);
2373 /* Drain what's left */
2375 nbytes = sizeof(drain_buffer) - 1;
2376 while (status == APR_SUCCESS && nbytes) {
2377 status = apr_socket_recv(backend->sock, drain_buffer, &nbytes);
2378 buffer[nbytes] = '\0';
2379 nbytes = sizeof(drain_buffer) - 1;
2380 if (strstr(drain_buffer, "\r\n\r\n") != NULL) {
2386 /* Check for HTTP_OK response status */
2387 if (status == APR_SUCCESS) {
2389 /* Only scan for three character status code */
2392 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00949)
2393 "send_http_connect: response from the forward proxy: %s",
2396 /* Extract the returned code */
2397 if (sscanf(buffer, "HTTP/%u.%u %3s", &major, &minor, code_str) == 3) {
2398 status = atoi(code_str);
2399 if (status == HTTP_OK) {
2400 status = APR_SUCCESS;
2403 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00950)
2404 "send_http_connect: the forward proxy returned code is '%s'",
2406 status = APR_INCOMPLETE;
2415 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2416 proxy_conn_rec *conn,
2417 proxy_worker *worker,
2423 apr_sockaddr_t *backend_addr = conn->addr;
2424 /* the local address to use for the outgoing connection */
2425 apr_sockaddr_t *local_addr;
2426 apr_socket_t *newsock;
2427 void *sconf = s->module_config;
2428 proxy_server_conf *conf =
2429 (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2432 if (!(connected = is_socket_connected(conn->sock))) {
2433 socket_cleanup(conn);
2434 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00951)
2435 "%s: backend socket is disconnected.",
2439 while (backend_addr && !connected) {
2440 if ((rv = apr_socket_create(&newsock, backend_addr->family,
2441 SOCK_STREAM, APR_PROTO_TCP,
2442 conn->scpool)) != APR_SUCCESS) {
2443 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2444 ap_log_error(APLOG_MARK, loglevel, rv, s, APLOGNO(00952)
2445 "%s: error creating fam %d socket for target %s",
2447 backend_addr->family,
2448 worker->s->hostname);
2450 * this could be an IPv6 address from the DNS but the
2451 * local machine won't give us an IPv6 socket; hopefully the
2452 * DNS returned an additional address to try
2454 backend_addr = backend_addr->next;
2457 conn->connection = NULL;
2459 if (worker->s->recv_buffer_size > 0 &&
2460 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2461 worker->s->recv_buffer_size))) {
2462 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00953)
2463 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2464 "ProxyReceiveBufferSize, using default");
2467 rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2468 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2469 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00954)
2470 "apr_socket_opt_set(APR_TCP_NODELAY): "
2474 /* Set a timeout for connecting to the backend on the socket */
2475 if (worker->s->conn_timeout_set) {
2476 apr_socket_timeout_set(newsock, worker->s->conn_timeout);
2478 else if (worker->s->timeout_set) {
2479 apr_socket_timeout_set(newsock, worker->s->timeout);
2481 else if (conf->timeout_set) {
2482 apr_socket_timeout_set(newsock, conf->timeout);
2485 apr_socket_timeout_set(newsock, s->timeout);
2487 /* Set a keepalive option */
2488 if (worker->s->keepalive) {
2489 if ((rv = apr_socket_opt_set(newsock,
2490 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2491 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00955)
2492 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2496 ap_log_error(APLOG_MARK, APLOG_TRACE2, 0, s,
2497 "%s: fam %d socket created to connect to %s",
2498 proxy_function, backend_addr->family, worker->s->hostname);
2500 if (conf->source_address_set) {
2501 local_addr = apr_pmemdup(conn->pool, conf->source_address,
2502 sizeof(apr_sockaddr_t));
2503 local_addr->pool = conn->pool;
2504 rv = apr_socket_bind(newsock, local_addr);
2505 if (rv != APR_SUCCESS) {
2506 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, APLOGNO(00956)
2507 "%s: failed to bind socket to local address",
2512 /* make the connection out of the socket */
2513 rv = apr_socket_connect(newsock, backend_addr);
2515 /* if an error occurred, loop round and try again */
2516 if (rv != APR_SUCCESS) {
2517 apr_socket_close(newsock);
2518 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2519 ap_log_error(APLOG_MARK, loglevel, rv, s, APLOGNO(00957)
2520 "%s: attempt to connect to %pI (%s) failed",
2523 worker->s->hostname);
2524 backend_addr = backend_addr->next;
2528 /* Set a timeout on the socket */
2529 if (worker->s->timeout_set) {
2530 apr_socket_timeout_set(newsock, worker->s->timeout);
2532 else if (conf->timeout_set) {
2533 apr_socket_timeout_set(newsock, conf->timeout);
2536 apr_socket_timeout_set(newsock, s->timeout);
2539 conn->sock = newsock;
2541 if (conn->forward) {
2542 forward_info *forward = (forward_info *)conn->forward;
2544 * For HTTP CONNECT we need to prepend CONNECT request before
2545 * sending our actual HTTPS requests.
2547 if (forward->use_http_connect) {
2548 rv = send_http_connect(conn, s);
2549 /* If an error occurred, loop round and try again */
2550 if (rv != APR_SUCCESS) {
2552 apr_socket_close(newsock);
2553 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2554 ap_log_error(APLOG_MARK, loglevel, rv, s, APLOGNO(00958)
2555 "%s: attempt to connect to %s:%d "
2556 "via http CONNECT through %pI (%s) failed",
2558 forward->target_host, forward->target_port,
2559 backend_addr, worker->s->hostname);
2560 backend_addr = backend_addr->next;
2569 * Put the entire worker to error state if
2570 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2571 * Altrough some connections may be alive
2572 * no further connections to the worker could be made
2574 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2575 !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2576 worker->s->error_time = apr_time_now();
2577 worker->s->status |= PROXY_WORKER_IN_ERROR;
2578 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00959)
2579 "ap_proxy_connect_backend disabling worker for (%s) for %"
2581 worker->s->hostname, apr_time_sec(worker->s->retry));
2584 if (worker->s->retries) {
2586 * A worker came back. So here is where we need to
2587 * either reset all params to initial conditions or
2588 * apply some sort of aging
2591 worker->s->error_time = 0;
2592 worker->s->retries = 0;
2594 return connected ? OK : DECLINED;
2597 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2598 proxy_conn_rec *conn,
2602 apr_sockaddr_t *backend_addr = conn->addr;
2604 apr_interval_time_t current_timeout;
2605 apr_bucket_alloc_t *bucket_alloc;
2607 if (conn->connection) {
2611 bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2613 * The socket is now open, create a new backend server connection
2615 conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2619 if (!conn->connection) {
2621 * the peer reset the connection already; ap_run_create_connection()
2624 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2625 s, APLOGNO(00960) "%s: an error occurred creating a "
2626 "new connection to %pI (%s)", proxy_function,
2627 backend_addr, conn->hostname);
2628 /* XXX: Will be closed when proxy_conn is closed */
2629 socket_cleanup(conn);
2630 return HTTP_INTERNAL_SERVER_ERROR;
2633 /* For ssl connection to backend */
2635 if (!ap_proxy_ssl_enable(conn->connection)) {
2636 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2637 s, APLOGNO(00961) "%s: failed to enable ssl support "
2638 "for %pI (%s)", proxy_function,
2639 backend_addr, conn->hostname);
2640 return HTTP_INTERNAL_SERVER_ERROR;
2644 /* TODO: See if this will break FTP */
2645 ap_proxy_ssl_disable(conn->connection);
2648 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00962)
2649 "%s: connection complete to %pI (%s)",
2650 proxy_function, backend_addr, conn->hostname);
2653 * save the timeout of the socket because core_pre_connection
2654 * will set it to base_server->timeout
2655 * (core TimeOut directive).
2657 apr_socket_timeout_get(conn->sock, ¤t_timeout);
2658 /* set up the connection filters */
2659 rc = ap_run_pre_connection(conn->connection, conn->sock);
2660 if (rc != OK && rc != DONE) {
2661 conn->connection->aborted = 1;
2662 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00963)
2663 "%s: pre_connection setup failed (%d)",
2664 proxy_function, rc);
2667 apr_socket_timeout_set(conn->sock, current_timeout);
2672 int ap_proxy_lb_workers(void)
2675 * Since we can't resize the scoreboard when reconfiguring, we
2676 * have to impose a limit on the number of workers, we are
2677 * able to reconfigure to.
2679 if (!lb_workers_limit)
2680 lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2681 return lb_workers_limit;
2684 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2685 apr_bucket_brigade *brigade)
2688 conn_rec *c = r->connection;
2692 * If this is a subrequest, then prevent also caching of the main
2696 r->main->no_cache = 1;
2697 e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2699 APR_BRIGADE_INSERT_TAIL(brigade, e);
2700 e = apr_bucket_eos_create(c->bucket_alloc);
2701 APR_BRIGADE_INSERT_TAIL(brigade, e);
2705 * Provide a string hashing function for the proxy.
2706 * We offer 2 methods: one is the APR model but we
2707 * also provide our own, based on either FNV or SDBM.
2708 * The reason is in case we want to use both to ensure no
2711 PROXY_DECLARE(unsigned int)
2712 ap_proxy_hashfunc(const char *str, proxy_hash_t method)
2714 if (method == PROXY_HASHFUNC_APR) {
2715 apr_ssize_t slen = strlen(str);
2716 return apr_hashfunc_default(str, &slen);
2718 else if (method == PROXY_HASHFUNC_FNV) {
2721 const unsigned int fnv_prime = 0x811C9DC5;
2722 for (hash = 0; *str; str++) {
2728 else { /* method == PROXY_HASHFUNC_DEFAULT */
2731 for (hash = 0; *str; str++) {
2732 hash = (*str) + (hash << 6) + (hash << 16) - hash;
2738 PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w)
2740 unsigned int *status = &w->s->status;
2741 char flag = toupper(c);
2742 struct wstat *pwt = wstat_tbl;
2744 if (flag == pwt->flag) {
2746 *status |= pwt->bit;
2748 *status &= ~(pwt->bit);
2756 PROXY_DECLARE(char *) ap_proxy_parse_wstatus(apr_pool_t *p, proxy_worker *w)
2759 unsigned int status = w->s->status;
2760 struct wstat *pwt = wstat_tbl;
2762 if (status & pwt->bit)
2763 ret = apr_pstrcat(p, ret, pwt->name, NULL);
2766 if (PROXY_WORKER_IS_USABLE(w))
2767 ret = apr_pstrcat(p, ret, "Ok ", NULL);
2771 PROXY_DECLARE(apr_status_t) ap_proxy_sync_balancer(proxy_balancer *b, server_rec *s,
2772 proxy_server_conf *conf)
2774 proxy_worker **workers;
2777 proxy_worker_shared *shm;
2778 proxy_balancer_method *lbmethod;
2779 ap_slotmem_provider_t *storage = b->storage;
2781 if (b->s->wupdated <= b->wupdated)
2784 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, b->s->lbpname, "0");
2786 b->lbmethod = lbmethod;
2791 * Look thru the list of workers in shm
2792 * and see which one(s) we are lacking...
2793 * again, the cast to unsigned int is safe
2794 * since our upper limit is always max_workers
2797 for (index = 0; index < b->max_workers; index++) {
2800 if ((rv = storage->dptr(b->wslot, (unsigned int)index, (void *)&shm)) != APR_SUCCESS) {
2801 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, APLOGNO(00965) "worker slotmem_dptr failed");
2802 return APR_EGENERAL;
2804 /* account for possible "holes" in the slotmem
2805 * (eg: slots 0-2 are used, but 3 isn't, but 4-5 is)
2807 if (!shm->hash.def || !shm->hash.fnv)
2810 workers = (proxy_worker **)b->workers->elts;
2811 for (i = 0; i < b->workers->nelts; i++, workers++) {
2812 proxy_worker *worker = *workers;
2813 if (worker->hash.def == shm->hash.def && worker->hash.fnv == shm->hash.fnv) {
2819 proxy_worker **runtime;
2820 runtime = apr_array_push(b->workers);
2821 *runtime = apr_palloc(conf->pool, sizeof(proxy_worker));
2822 (*runtime)->hash = shm->hash;
2823 (*runtime)->context = NULL;
2824 (*runtime)->cp = NULL;
2825 (*runtime)->balancer = b;
2826 (*runtime)->s = shm;
2827 (*runtime)->tmutex = NULL;
2828 if ((rv = ap_proxy_initialize_worker(*runtime, s, conf->pool)) != APR_SUCCESS) {
2829 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, APLOGNO(00966) "Cannot init worker");
2834 if (b->s->need_reset) {
2835 if (b->lbmethod && b->lbmethod->reset)
2836 b->lbmethod->reset(b, s);
2837 b->s->need_reset = 0;
2839 b->wupdated = b->s->wupdated;
2843 void proxy_util_register_hooks(apr_pool_t *p)
2845 APR_REGISTER_OPTIONAL_FN(ap_proxy_retry_worker);