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"
25 #include <unistd.h> /* for getpid() */
28 #if (APR_MAJOR_VERSION < 1)
29 #undef apr_socket_create
30 #define apr_socket_create apr_socket_create_ex
33 APLOG_USE_MODULE(proxy);
36 * Opaque structure containing target server info when
37 * using a forward proxy.
38 * Up to now only used in combination with HTTP CONNECT.
41 int use_http_connect; /* Use SSL Tunneling via HTTP CONNECT */
42 const char *target_host; /* Target hostname */
43 apr_port_t target_port; /* Target port */
44 const char *proxy_auth; /* Proxy authorization */
47 /* Keep synced with mod_proxy.h! */
53 {PROXY_WORKER_INITIALIZED, PROXY_WORKER_INITIALIZED_FLAG, "Init "},
54 {PROXY_WORKER_IGNORE_ERRORS, PROXY_WORKER_IGNORE_ERRORS_FLAG, "Ign "},
55 {PROXY_WORKER_DRAIN, PROXY_WORKER_DRAIN_FLAG, "Drn "},
56 {PROXY_WORKER_IN_SHUTDOWN, PROXY_WORKER_IN_SHUTDOWN_FLAG, "Shut "},
57 {PROXY_WORKER_DISABLED, PROXY_WORKER_DISABLED_FLAG, "Dis "},
58 {PROXY_WORKER_STOPPED, PROXY_WORKER_STOPPED_FLAG, "Stop "},
59 {PROXY_WORKER_IN_ERROR, PROXY_WORKER_IN_ERROR_FLAG, "Err "},
60 {PROXY_WORKER_HOT_STANDBY, PROXY_WORKER_HOT_STANDBY_FLAG, "Stby "},
61 {PROXY_WORKER_FREE, PROXY_WORKER_FREE_FLAG, "Free "},
65 /* Global balancer counter */
66 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
67 static int lb_workers_limit = 0;
68 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_path;
69 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_domain;
71 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
72 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
73 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
74 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
76 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
77 (request_rec *r, request_rec *pr), (r, pr),
80 PROXY_DECLARE(apr_status_t) ap_proxy_strncpy(char *dst, const char *src, size_t dlen)
82 if ((strlen(src)+1) > dlen) {
83 /* APR_ENOSPACE would be better */
87 apr_cpystrn(dst, src, dlen);
92 /* already called in the knowledge that the characters are hex digits */
93 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
97 #if !APR_CHARSET_EBCDIC
100 if (apr_isdigit(ch)) {
103 else if (apr_isupper(ch)) {
112 if (apr_isdigit(ch)) {
115 else if (apr_isupper(ch)) {
116 i += ch - ('A' - 10);
119 i += ch - ('a' - 10);
122 #else /*APR_CHARSET_EBCDIC*/
124 * we assume that the hex value refers to an ASCII character
125 * so convert to EBCDIC so that it makes sense locally;
129 * client specifies %20 in URL to refer to a space char;
130 * at this point we're called with EBCDIC "20"; after turning
131 * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
132 * represents an ASCII char and convert 0x20 to EBCDIC, yielding
137 if (1 == sscanf(x, "%2x", &i)) {
139 ap_xlate_proto_from_ascii(buf, 1);
145 #endif /*APR_CHARSET_EBCDIC*/
148 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
150 #if !APR_CHARSET_EBCDIC
154 i = (ch & 0xF0) >> 4;
156 x[1] = ('A' - 10) + i;
164 x[2] = ('A' - 10) + i;
169 #else /*APR_CHARSET_EBCDIC*/
170 static const char ntoa[] = { "0123456789ABCDEF" };
176 ap_xlate_proto_to_ascii(buf, 1);
179 x[1] = ntoa[(buf[0] >> 4) & 0x0F];
180 x[2] = ntoa[buf[0] & 0x0F];
182 #endif /*APR_CHARSET_EBCDIC*/
186 * canonicalise a URL-encoded string
190 * Convert a URL-encoded string to canonical form.
191 * It decodes characters which need not be encoded,
192 * and encodes those which must be encoded, and does not touch
193 * those which must not be touched.
195 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
196 enum enctype t, int forcedec,
201 char *allowed; /* characters which should not be encoded */
202 char *reserved; /* characters which much not be en/de-coded */
205 * N.B. in addition to :@&=, this allows ';' in an http path
206 * and '?' in an ftp path -- this may be revised
208 * Also, it makes a '+' character in a search string reserved, as
209 * it may be form-encoded. (Although RFC 1738 doesn't allow this -
210 * it only permits ; / ? : @ = & as reserved chars.)
213 allowed = "~$-_.+!*'(),;:@&=";
215 else if (t == enc_search) {
216 allowed = "$-_.!*'(),;:@&=";
218 else if (t == enc_user) {
219 allowed = "$-_.+!*'(),;@&=";
221 else if (t == enc_fpath) {
222 allowed = "$-_.+!*'(),?:@&=";
224 else { /* if (t == enc_parm) */
225 allowed = "$-_.+!*'(),?/:@&=";
231 else if (t == enc_search) {
238 y = apr_palloc(p, 3 * len + 1);
240 for (i = 0, j = 0; i < len; i++, j++) {
241 /* always handle '/' first */
243 if (strchr(reserved, ch)) {
248 * decode it if not already done. do not decode reverse proxied URLs
249 * unless specifically forced
251 if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
252 if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
255 ch = ap_proxy_hex2c(&x[i + 1]);
257 if (ch != 0 && strchr(reserved, ch)) { /* keep it encoded */
258 ap_proxy_c2hex(ch, &y[j]);
263 /* recode it, if necessary */
264 if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
265 ap_proxy_c2hex(ch, &y[j]);
277 * Parses network-location.
278 * urlp on input the URL; on output the path, after the leading /
279 * user NULL if no user/password permitted
280 * password holder for password
281 * host holder for host
282 * port port number; only set if one is supplied.
284 * Returns an error string.
286 PROXY_DECLARE(char *)
287 ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
288 char **passwordp, char **hostp, apr_port_t *port)
290 char *addr, *scope_id, *strp, *host, *url = *urlp;
291 char *user = NULL, *password = NULL;
295 if (url[0] != '/' || url[1] != '/') {
296 return "Malformed URL";
299 url = strchr(host, '/');
304 *(url++) = '\0'; /* skip seperating '/' */
307 /* find _last_ '@' since it might occur in user/password part */
308 strp = strrchr(host, '@');
316 strp = strchr(user, ':');
319 password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
320 if (password == NULL) {
321 return "Bad %-escape in URL (password)";
325 user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
327 return "Bad %-escape in URL (username)";
333 if (passwordp != NULL) {
334 *passwordp = password;
338 * Parse the host string to separate host portion from optional port.
339 * Perform range checking on port.
341 rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
342 if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
343 return "Invalid host/port";
345 if (tmp_port != 0) { /* only update caller's port if port was specified */
349 ap_str_tolower(addr); /* DNS names are case-insensitive */
358 * If the date is a valid RFC 850 date or asctime() date, then it
359 * is converted to the RFC 1123 format.
361 PROXY_DECLARE(const char *)
362 ap_proxy_date_canon(apr_pool_t *p, const char *date)
367 apr_time_t time = apr_date_parse_http(date);
372 ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
373 rv = apr_rfc822_date(ndate, time);
374 if (rv != APR_SUCCESS) {
381 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
386 apr_pool_create(&pool, c->pool);
388 rp = apr_pcalloc(pool, sizeof(*r));
391 rp->status = HTTP_OK;
393 rp->headers_in = apr_table_make(pool, 50);
394 rp->subprocess_env = apr_table_make(pool, 50);
395 rp->headers_out = apr_table_make(pool, 12);
396 rp->err_headers_out = apr_table_make(pool, 5);
397 rp->notes = apr_table_make(pool, 5);
399 rp->server = r->server;
401 rp->proxyreq = r->proxyreq;
402 rp->request_time = r->request_time;
404 rp->output_filters = c->output_filters;
405 rp->input_filters = c->input_filters;
406 rp->proto_output_filters = c->output_filters;
407 rp->proto_input_filters = c->input_filters;
409 rp->request_config = ap_create_request_config(pool);
410 proxy_run_create_req(r, rp);
417 * list is a comma-separated list of case-insensitive tokens, with
418 * optional whitespace around the tokens.
419 * The return returns 1 if the token val is found in the list, or 0
422 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
429 while (list != NULL) {
430 p = ap_strchr_c(list, ',');
435 } while (apr_isspace(*p));
441 while (i > 0 && apr_isspace(list[i - 1])) {
444 if (i == len && strncasecmp(list, val, len) == 0) {
453 * Converts 8 hex digits to a time integer
455 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
460 for (i = 0, j = 0; i < 8; i++) {
463 if (apr_isdigit(ch)) {
466 else if (apr_isupper(ch)) {
467 j |= ch - ('A' - 10);
470 j |= ch - ('a' - 10);
473 if (j == 0xffffffff) {
474 return -1; /* so that it works with 8-byte ints */
482 * Converts a time integer to 8 hex digits
484 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
489 for (i = 7; i >= 0; i--) {
493 y[i] = ch + ('A' - 10);
502 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
504 const char *uri = ap_escape_html(r->pool, r->uri);
505 apr_table_setn(r->notes, "error-notes",
507 "The proxy server could not handle the request <em><a href=\"",
508 uri, "\">", ap_escape_html(r->pool, r->method), " ", uri,
510 "Reason: <strong>", ap_escape_html(r->pool, message),
514 /* Allow "error-notes" string to be printed by ap_send_error_response() */
515 apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
517 r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
518 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s returned by %s", message,
524 proxy_get_host_of_request(request_rec *r)
526 char *url, *user = NULL, *password = NULL, *err, *host;
529 if (r->hostname != NULL) {
533 /* Set url to the first char after "scheme://" */
534 if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
538 url = apr_pstrdup(r->pool, &url[1]); /* make it point to "//", which is what proxy_canon_netloc expects */
540 err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
543 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", err);
548 return host; /* ought to return the port, too */
551 /* Return TRUE if addr represents an IP address (or an IP network address) */
552 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
554 const char *addr = This->name;
560 * if the address is given with an explicit netmask, use that
561 * Due to a deficiency in apr_inet_addr(), it is impossible to parse
562 * "partial" addresses (with less than 4 quads) correctly, i.e.
563 * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
564 * I therefore have to parse the IP address manually:
565 * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
566 * addr and mask were set by proxy_readmask()
571 * Parse IP addr manually, optionally allowing
572 * abbreviated net addresses like 192.168.
575 /* Iterate over up to 4 (dotted) quads. */
576 for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
579 if (*addr == '/' && quads > 0) { /* netmask starts here. */
583 if (!apr_isdigit(*addr)) {
584 return 0; /* no digit at start of quad */
587 ip_addr[quads] = strtol(addr, &tmp, 0);
589 if (tmp == addr) { /* expected a digit, found something else */
593 if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
600 if (*addr == '.' && quads != 3) {
601 ++addr; /* after the 4th quad, a dot would be illegal */
605 for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
606 This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
609 if (addr[0] == '/' && apr_isdigit(addr[1])) { /* net mask follows: */
614 bits = strtol(addr, &tmp, 0);
616 if (tmp == addr) { /* expected a digit, found something else */
622 if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
629 * Determine (i.e., "guess") netmask by counting the
630 * number of trailing .0's; reduce #quads appropriately
631 * (so that 192.168.0.0 is equivalent to 192.168.)
633 while (quads > 0 && ip_addr[quads - 1] == 0) {
637 /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
642 /* every zero-byte counts as 8 zero-bits */
645 if (bits != 32) { /* no warning for fully qualified IP address */
646 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
647 "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
648 inet_ntoa(This->addr), bits);
652 This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
654 if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
655 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
656 "Warning: NetMask and IP-Addr disagree in %s/%ld",
657 inet_ntoa(This->addr), bits);
658 This->addr.s_addr &= This->mask.s_addr;
659 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
660 " Set to %s/%ld", inet_ntoa(This->addr), bits);
664 This->matcher = proxy_match_ipaddr;
668 return (*addr == '\0'); /* okay iff we've parsed the whole string */
672 /* Return TRUE if addr represents an IP address (or an IP network address) */
673 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
676 struct in_addr addr, *ip;
677 const char *host = proxy_get_host_of_request(r);
679 if (host == NULL) { /* oops! */
683 memset(&addr, '\0', sizeof addr);
684 memset(ip_addr, '\0', sizeof ip_addr);
686 if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
687 for (addr.s_addr = 0, i = 0; i < 4; ++i) {
688 /* ap_proxy_is_ipaddr() already confirmed that we have
689 * a valid octet in ip_addr[i]
691 addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
694 if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
696 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
697 "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
698 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
699 "%s/", inet_ntoa(This->addr));
700 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701 "%s", inet_ntoa(This->mask));
707 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
708 "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
709 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
710 "%s/", inet_ntoa(This->addr));
711 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
712 "%s", inet_ntoa(This->mask));
717 struct apr_sockaddr_t *reqaddr;
719 if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
722 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
723 "2)IP-NoMatch: hostname=%s msg=Host not found", host);
728 /* Try to deal with multiple IP addr's for a host */
729 /* FIXME: This needs to be able to deal with IPv6 */
731 ip = (struct in_addr *) reqaddr->ipaddr_ptr;
732 if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
734 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
735 "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
736 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
737 "%s/", inet_ntoa(This->addr));
738 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
739 "%s", inet_ntoa(This->mask));
745 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
746 "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
747 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
748 "%s/", inet_ntoa(This->addr));
749 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
750 "%s", inet_ntoa(This->mask));
753 reqaddr = reqaddr->next;
760 /* Return TRUE if addr represents a domain name */
761 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
763 char *addr = This->name;
766 /* Domain name must start with a '.' */
767 if (addr[0] != '.') {
771 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
772 for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
777 if (addr[i] == ':') {
778 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
779 "@@@@ handle optional port in proxy_is_domainname()");
780 /* @@@@ handle optional port */
784 if (addr[i] != '\0') {
788 /* Strip trailing dots */
789 for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
793 This->matcher = proxy_match_domainname;
797 /* Return TRUE if host "host" is in domain "domain" */
798 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
800 const char *host = proxy_get_host_of_request(r);
801 int d_len = strlen(This->name), h_len;
803 if (host == NULL) { /* some error was logged already */
807 h_len = strlen(host);
809 /* @@@ do this within the setup? */
810 /* Ignore trailing dots in domain comparison: */
811 while (d_len > 0 && This->name[d_len - 1] == '.') {
814 while (h_len > 0 && host[h_len - 1] == '.') {
818 && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
821 /* Return TRUE if host represents a host name */
822 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
824 struct apr_sockaddr_t *addr;
825 char *host = This->name;
828 /* Host names must not start with a '.' */
829 if (host[0] == '.') {
832 /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
833 for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
835 if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
839 This->hostaddr = addr;
841 /* Strip trailing dots */
842 for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
846 This->matcher = proxy_match_hostname;
850 /* Return TRUE if host "host" is equal to host2 "host2" */
851 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
853 char *host = This->name;
854 const char *host2 = proxy_get_host_of_request(r);
858 if (host == NULL || host2 == NULL) {
859 return 0; /* oops! */
862 h2_len = strlen(host2);
863 h1_len = strlen(host);
866 struct apr_sockaddr_t *addr = *This->hostaddr;
868 /* Try to deal with multiple IP addr's for a host */
870 if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
876 /* Ignore trailing dots in host2 comparison: */
877 while (h2_len > 0 && host2[h2_len - 1] == '.') {
880 while (h1_len > 0 && host[h1_len - 1] == '.') {
883 return h1_len == h2_len
884 && strncasecmp(host, host2, h1_len) == 0;
887 /* Return TRUE if addr is to be matched as a word */
888 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
890 This->matcher = proxy_match_word;
894 /* Return TRUE if string "str2" occurs literally in "str1" */
895 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
897 const char *host = proxy_get_host_of_request(r);
898 return host != NULL && ap_strstr_c(host, This->name) != NULL;
901 /* checks whether a host in uri_addr matches proxyblock */
902 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
903 apr_sockaddr_t *uri_addr)
906 apr_sockaddr_t * src_uri_addr = uri_addr;
907 /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
908 for (j = 0; j < conf->noproxies->nelts; j++) {
909 struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
910 struct apr_sockaddr_t *conf_addr = npent[j].addr;
911 uri_addr = src_uri_addr;
912 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
913 "checking remote machine [%s] against [%s]",
914 uri_addr->hostname, npent[j].name);
915 if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
916 || npent[j].name[0] == '*') {
917 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
918 "connect to remote machine %s blocked: name %s "
919 "matched", uri_addr->hostname, npent[j].name);
920 return HTTP_FORBIDDEN;
923 uri_addr = src_uri_addr;
927 apr_sockaddr_ip_get(&conf_ip, conf_addr);
928 apr_sockaddr_ip_get(&uri_ip, uri_addr);
929 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
930 "ProxyBlock comparing %s and %s", conf_ip,
932 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
933 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
934 "connect to remote machine %s blocked: "
935 "IP %s matched", uri_addr->hostname, conf_ip);
936 return HTTP_FORBIDDEN;
938 uri_addr = uri_addr->next;
940 conf_addr = conf_addr->next;
946 /* set up the minimal filter set */
947 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
949 ap_add_input_filter("HTTP_IN", NULL, r, c);
954 * converts a series of buckets into a string
955 * XXX: BillS says this function performs essentially the same function as
956 * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
957 * instead? I think ap_proxy_string_read() will not work properly on non ASCII
958 * (EBCDIC) machines either.
960 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
961 char *buff, apr_size_t bufflen, int *eos)
970 /* start with an empty string */
974 /* loop through each brigade */
976 /* get brigade from network one line at a time */
977 if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
983 /* loop through each bucket */
985 if (*eos || APR_BRIGADE_EMPTY(bb)) {
986 /* The connection aborted or timed out */
987 return APR_ECONNABORTED;
989 e = APR_BRIGADE_FIRST(bb);
990 if (APR_BUCKET_IS_EOS(e)) {
994 if (APR_SUCCESS != (rv = apr_bucket_read(e,
995 (const char **)&response,
1001 * is string LF terminated?
1002 * XXX: This check can be made more efficient by simply checking
1003 * if the last character in the 'response' buffer is an ASCII_LF.
1004 * See ap_rgetline() for an example.
1006 if (memchr(response, APR_ASCII_LF, len)) {
1009 /* concat strings until buff is full - then throw the data away */
1010 if (len > ((bufflen-1)-(pos-buff))) {
1011 len = (bufflen-1)-(pos-buff);
1014 memcpy(pos, response, len);
1018 APR_BUCKET_REMOVE(e);
1019 apr_bucket_destroy(e);
1027 /* unmerge an element in the table */
1028 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
1030 apr_off_t offset = 0;
1031 apr_off_t count = 0;
1034 /* get the value to unmerge */
1035 const char *initial = apr_table_get(t, key);
1039 value = apr_pstrdup(p, initial);
1041 /* remove the value from the headers */
1042 apr_table_unset(t, key);
1044 /* find each comma */
1045 while (value[count]) {
1046 if (value[count] == ',') {
1048 apr_table_add(t, key, value + offset);
1053 apr_table_add(t, key, value + offset);
1056 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1057 proxy_dir_conf *conf, const char *url)
1059 proxy_req_conf *rconf;
1060 struct proxy_alias *ent;
1065 * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1066 * after the hostname
1067 * XXX FIXME: Ensure the /uri component is a case sensitive match
1069 if (r->proxyreq != PROXYREQ_REVERSE) {
1074 if (conf->interpolate_env == 1) {
1075 rconf = ap_get_module_config(r->request_config, &proxy_module);
1076 ent = (struct proxy_alias *)rconf->raliases->elts;
1079 ent = (struct proxy_alias *)conf->raliases->elts;
1081 for (i = 0; i < conf->raliases->nelts; i++) {
1082 proxy_server_conf *sconf = (proxy_server_conf *)
1083 ap_get_module_config(r->server->module_config, &proxy_module);
1084 proxy_balancer *balancer;
1085 const char *real = ent[i].real;
1087 * First check if mapping against a balancer and see
1088 * if we have such a entity. If so, then we need to
1089 * find the particulars of the actual worker which may
1090 * or may not be the right one... basically, we need
1091 * to find which member actually handled this request.
1093 if (ap_proxy_valid_balancer_name((char *)real, 0) &&
1094 (balancer = ap_proxy_get_balancer(r->pool, sconf, real, 1))) {
1096 proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
1097 const char *urlpart = ap_strchr_c(real, '/');
1102 l3 = strlen(urlpart);
1104 /* The balancer comparison is a bit trickier. Given the context
1105 * BalancerMember balancer://alias http://example.com/foo
1106 * ProxyPassReverse /bash balancer://alias/bar
1107 * translate url http://example.com/foo/bar/that to /bash/that
1109 for (n = 0; n < balancer->workers->nelts; n++) {
1110 l2 = strlen((*worker)->s->name);
1112 /* urlpart (l3) assuredly starts with its own '/' */
1113 if ((*worker)->s->name[l2 - 1] == '/')
1116 && strncasecmp((*worker)->s->name, url, l2) == 0
1117 && strncmp(urlpart, url + l2, l3) == 0) {
1118 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2 + l3],
1120 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1123 else if (l1 >= l2 && strncasecmp((*worker)->s->name, url, l2) == 0) {
1124 u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1125 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1131 const char *part = url;
1133 if (real[0] == '/') {
1134 part = ap_strstr_c(url, "://");
1136 part = ap_strchr_c(part+3, '/');
1148 if (l1 >= l2 && strncasecmp(real, part, l2) == 0) {
1149 u = apr_pstrcat(r->pool, ent[i].fake, &part[l2], NULL);
1150 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1159 * Cookies are a bit trickier to match: we've got two substrings to worry
1160 * about, and we can't just find them with strstr 'cos of case. Regexp
1161 * matching would be an easy fix, but for better consistency with all the
1162 * other matches we'll refrain and use apr_strmatch to find path=/domain=
1163 * and stick to plain strings for the config values.
1165 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1166 proxy_dir_conf *conf, const char *str)
1168 proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1170 struct proxy_alias *ent;
1171 size_t len = strlen(str);
1172 const char *newpath = NULL;
1173 const char *newdomain = NULL;
1175 const char *domainp;
1176 const char *pathe = NULL;
1177 const char *domaine = NULL;
1178 size_t l1, l2, poffs = 0, doffs = 0;
1184 if (r->proxyreq != PROXYREQ_REVERSE) {
1189 * Find the match and replacement, but save replacing until we've done
1190 * both path and domain so we know the new strlen
1192 if ((pathp = apr_strmatch(ap_proxy_strmatch_path, str, len)) != NULL) {
1194 poffs = pathp - str;
1195 pathe = ap_strchr_c(pathp, ';');
1196 l1 = pathe ? (pathe - pathp) : strlen(pathp);
1197 pathe = pathp + l1 ;
1198 if (conf->interpolate_env == 1) {
1199 ent = (struct proxy_alias *)rconf->cookie_paths->elts;
1202 ent = (struct proxy_alias *)conf->cookie_paths->elts;
1204 for (i = 0; i < conf->cookie_paths->nelts; i++) {
1205 l2 = strlen(ent[i].fake);
1206 if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1207 newpath = ent[i].real;
1208 pdiff = strlen(newpath) - l1;
1214 if ((domainp = apr_strmatch(ap_proxy_strmatch_domain, str, len)) != NULL) {
1216 doffs = domainp - str;
1217 domaine = ap_strchr_c(domainp, ';');
1218 l1 = domaine ? (domaine - domainp) : strlen(domainp);
1219 domaine = domainp + l1;
1220 if (conf->interpolate_env == 1) {
1221 ent = (struct proxy_alias *)rconf->cookie_domains->elts;
1224 ent = (struct proxy_alias *)conf->cookie_domains->elts;
1226 for (i = 0; i < conf->cookie_domains->nelts; i++) {
1227 l2 = strlen(ent[i].fake);
1228 if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1229 newdomain = ent[i].real;
1230 ddiff = strlen(newdomain) - l1;
1237 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1238 l1 = strlen(newpath);
1240 l2 = strlen(newdomain);
1241 if (doffs > poffs) {
1242 memcpy(ret, str, poffs);
1243 memcpy(ret + poffs, newpath, l1);
1244 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1245 memcpy(ret + doffs + pdiff, newdomain, l2);
1246 strcpy(ret + doffs + pdiff + l2, domaine);
1249 memcpy(ret, str, doffs) ;
1250 memcpy(ret + doffs, newdomain, l2);
1251 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1252 memcpy(ret + poffs + ddiff, newpath, l1);
1253 strcpy(ret + poffs + ddiff + l1, pathe);
1257 memcpy(ret, str, poffs);
1258 memcpy(ret + poffs, newpath, l1);
1259 strcpy(ret + poffs + l1, pathe);
1264 ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1265 l2 = strlen(newdomain);
1266 memcpy(ret, str, doffs);
1267 memcpy(ret + doffs, newdomain, l2);
1268 strcpy(ret + doffs+l2, domaine);
1271 ret = (char *)str; /* no change */
1279 * BALANCER related...
1283 * verifies that the balancer name conforms to standards.
1285 PROXY_DECLARE(int) ap_proxy_valid_balancer_name(char *name, int i)
1288 i = sizeof(BALANCER_PREFIX)-1;
1289 return (!strncasecmp(name, BALANCER_PREFIX, i));
1293 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1294 proxy_server_conf *conf,
1298 proxy_balancer *balancer;
1299 char *c, *uri = apr_pstrdup(p, url);
1303 c = strchr(uri, ':');
1304 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1307 /* remove path from uri */
1308 if ((c = strchr(c + 3, '/'))) {
1311 hash = ap_proxy_hashfunc(uri, PROXY_HASHFUNC_DEFAULT);
1312 balancer = (proxy_balancer *)conf->balancers->elts;
1313 for (i = 0; i < conf->balancers->nelts; i++) {
1314 if (balancer->hash == hash) {
1315 if (!care || !balancer->s->inactive) {
1325 PROXY_DECLARE(char *) ap_proxy_update_balancer(apr_pool_t *p,
1326 proxy_balancer *balancer,
1330 if (apr_uri_parse(p, url, &puri) != APR_SUCCESS) {
1331 return apr_psprintf(p, "unable to parse: %s", url);
1333 if (puri.path && PROXY_STRNCPY(balancer->s->vpath, puri.path) != APR_SUCCESS) {
1334 return apr_psprintf(p, "balancer %s front-end virtual-path (%s) too long",
1335 balancer->s->name, puri.path);
1337 if (puri.hostname && PROXY_STRNCPY(balancer->s->vhost, puri.hostname) != APR_SUCCESS) {
1338 return apr_psprintf(p, "balancer %s front-end vhost name (%s) too long",
1339 balancer->s->name, puri.hostname);
1344 PROXY_DECLARE(char *) ap_proxy_define_balancer(apr_pool_t *p,
1345 proxy_balancer **balancer,
1346 proxy_server_conf *conf,
1351 char nonce[APR_UUID_FORMATTED_LENGTH + 1];
1352 proxy_balancer_method *lbmethod;
1354 proxy_balancer_shared *bshared;
1355 char *c, *q, *uri = apr_pstrdup(p, url);
1358 /* We should never get here without a valid BALANCER_PREFIX... */
1360 c = strchr(uri, ':');
1361 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1362 return "Bad syntax for a balancer name";
1363 /* remove path from uri */
1364 if ((q = strchr(c + 3, '/')))
1367 ap_str_tolower(uri);
1368 *balancer = apr_array_push(conf->balancers);
1369 memset(*balancer, 0, sizeof(proxy_balancer));
1372 * NOTE: The default method is byrequests, which we assume
1375 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1377 return "Can't find 'byrequests' lb method";
1380 (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1381 (*balancer)->gmutex = NULL;
1382 (*balancer)->tmutex = NULL;
1383 (*balancer)->lbmethod = lbmethod;
1386 bshared = ap_malloc(sizeof(proxy_balancer_shared));
1388 bshared = apr_palloc(p, sizeof(proxy_balancer_shared));
1390 memset(bshared, 0, sizeof(proxy_balancer_shared));
1392 bshared->was_malloced = (do_malloc != 0);
1393 PROXY_STRNCPY(bshared->lbpname, "byrequests");
1394 if (PROXY_STRNCPY(bshared->name, uri) != APR_SUCCESS) {
1395 return apr_psprintf(p, "balancer name (%s) too long", uri);
1397 ap_pstr2_alnum(p, bshared->name + sizeof(BALANCER_PREFIX) - 1,
1399 sname = apr_pstrcat(p, conf->id, "_", sname, NULL);
1400 if (PROXY_STRNCPY(bshared->sname, sname) != APR_SUCCESS) {
1401 return apr_psprintf(p, "balancer safe-name (%s) too long", sname);
1403 bshared->hash = ap_proxy_hashfunc(bshared->name, PROXY_HASHFUNC_DEFAULT);
1404 (*balancer)->hash = bshared->hash;
1406 /* Retrieve a UUID and store the nonce for the lifetime of
1408 apr_uuid_get(&uuid);
1409 apr_uuid_format(nonce, &uuid);
1410 if (PROXY_STRNCPY(bshared->nonce, nonce) != APR_SUCCESS) {
1411 return apr_psprintf(p, "balancer nonce (%s) too long", nonce);
1414 (*balancer)->s = bshared;
1415 (*balancer)->sconf = conf;
1417 return ap_proxy_update_balancer(p, *balancer, alias);
1421 * Create an already defined balancer and free up memory.
1423 PROXY_DECLARE(apr_status_t) ap_proxy_share_balancer(proxy_balancer *balancer,
1424 proxy_balancer_shared *shm,
1427 proxy_balancer_method *lbmethod;
1428 if (!shm || !balancer->s)
1431 memcpy(shm, balancer->s, sizeof(proxy_balancer_shared));
1432 if (balancer->s->was_malloced)
1435 balancer->s->index = i;
1436 /* the below should always succeed */
1437 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, balancer->s->lbpname, "0");
1439 balancer->lbmethod = lbmethod;
1443 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_balancer(proxy_balancer *balancer, server_rec *s, apr_pool_t *p)
1445 apr_status_t rv = APR_SUCCESS;
1446 ap_slotmem_provider_t *storage = balancer->storage;
1451 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1452 "no provider for %s", balancer->s->name);
1453 return APR_EGENERAL;
1456 * for each balancer we need to init the global
1457 * mutex and then attach to the shared worker shm
1459 if (!balancer->gmutex) {
1460 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1461 "no mutex %s", balancer->s->name);
1462 return APR_EGENERAL;
1465 /* Re-open the mutex for the child. */
1466 rv = apr_global_mutex_child_init(&(balancer->gmutex),
1467 apr_global_mutex_lockfile(balancer->gmutex),
1469 if (rv != APR_SUCCESS) {
1470 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
1471 "Failed to reopen mutex %s in child",
1477 storage->attach(&(balancer->wslot), balancer->s->sname, &size, &num, p);
1478 if (!balancer->wslot) {
1479 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, "slotmem_attach failed");
1480 return APR_EGENERAL;
1482 if (balancer->lbmethod && balancer->lbmethod->reset)
1483 balancer->lbmethod->reset(balancer, s);
1485 if (balancer->tmutex == NULL) {
1486 rv = apr_thread_mutex_create(&(balancer->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1487 if (rv != APR_SUCCESS) {
1488 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1489 "can not create balancer thread mutex");
1497 * CONNECTION related...
1500 static apr_status_t conn_pool_cleanup(void *theworker)
1502 proxy_worker *worker = (proxy_worker *)theworker;
1503 if (worker->cp->res) {
1504 worker->cp->pool = NULL;
1509 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1512 proxy_conn_pool *cp;
1515 * Create a connection pool's subpool.
1516 * This pool is used for connection recycling.
1517 * Once the worker is added it is never removed but
1518 * it can be disabled.
1520 apr_pool_create(&pool, p);
1521 apr_pool_tag(pool, "proxy_worker_cp");
1523 * Alloc from the same pool as worker.
1524 * proxy_conn_pool is permanently attached to the worker.
1526 cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1531 static apr_status_t connection_cleanup(void *theconn)
1533 proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1534 proxy_worker *worker = conn->worker;
1537 * If the connection pool is NULL the worker
1538 * cleanup has been run. Just return.
1545 apr_pool_destroy(conn->r->pool);
1549 /* Sanity check: Did we already return the pooled connection? */
1550 if (conn->inreslist) {
1551 ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool,
1552 "Pooled connection 0x%pp for worker %s has been"
1553 " already returned to the connection pool.", conn,
1558 /* determine if the connection need to be closed */
1559 if (conn->close || !worker->s->is_address_reusable || worker->s->disablereuse) {
1560 apr_pool_t *p = conn->pool;
1562 conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1564 conn->worker = worker;
1565 apr_pool_create(&(conn->scpool), p);
1566 apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1569 if (worker->s->hmax && worker->cp->res) {
1570 conn->inreslist = 1;
1571 apr_reslist_release(worker->cp->res, (void *)conn);
1575 worker->cp->conn = conn;
1578 /* Always return the SUCCESS */
1582 static void socket_cleanup(proxy_conn_rec *conn)
1585 conn->connection = NULL;
1586 apr_pool_clear(conn->scpool);
1589 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1592 apr_bucket_brigade *bb;
1596 * If we have an existing SSL connection it might be possible that the
1597 * server sent some SSL message we have not read so far (e.g. an SSL
1598 * shutdown message if the server closed the keepalive connection while
1599 * the connection was held unused in our pool).
1600 * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1601 * processed. We don't expect any data to be in the returned brigade.
1603 if (conn->sock && conn->connection) {
1604 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1605 rv = ap_get_brigade(conn->connection->input_filters, bb,
1606 AP_MODE_READBYTES, APR_NONBLOCK_READ,
1608 if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1609 socket_cleanup(conn);
1611 if (!APR_BRIGADE_EMPTY(bb)) {
1614 rv = apr_brigade_length(bb, 0, &len);
1615 ap_log_rerror(APLOG_MARK, APLOG_TRACE3, rv, r,
1616 "SSL cleanup brigade contained %"
1617 APR_OFF_T_FMT " bytes of data.", len);
1619 apr_brigade_destroy(bb);
1624 /* reslist constructor */
1625 static apr_status_t connection_constructor(void **resource, void *params,
1630 proxy_conn_rec *conn;
1631 proxy_worker *worker = (proxy_worker *)params;
1634 * Create the subpool for each connection
1635 * This keeps the memory consumption constant
1636 * when disconnecting from backend.
1638 apr_pool_create(&ctx, pool);
1639 apr_pool_tag(ctx, "proxy_conn_pool");
1641 * Create another subpool that manages the data for the
1642 * socket and the connection member of the proxy_conn_rec struct as we
1643 * destroy this data more frequently than other data in the proxy_conn_rec
1644 * struct like hostname and addr (at least in the case where we have
1645 * keepalive connections that timed out).
1647 apr_pool_create(&scpool, ctx);
1648 apr_pool_tag(scpool, "proxy_conn_scpool");
1649 conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1652 conn->scpool = scpool;
1653 conn->worker = worker;
1654 conn->inreslist = 1;
1660 /* reslist destructor */
1661 static apr_status_t connection_destructor(void *resource, void *params,
1664 proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1666 /* Destroy the pool only if not called from reslist_destroy */
1667 if (conn->worker->cp->pool) {
1668 apr_pool_destroy(conn->pool);
1678 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1679 proxy_balancer *balancer,
1680 proxy_server_conf *conf,
1683 proxy_worker *worker;
1684 proxy_worker *max_worker = NULL;
1688 int worker_name_length;
1693 c = ap_strchr_c(url, ':');
1694 if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1698 url_length = strlen(url);
1699 url_copy = apr_pstrmemdup(p, url, url_length);
1702 * We need to find the start of the path and
1703 * therefore we know the length of the scheme://hostname/
1704 * part to we can force-lowercase everything up to
1705 * the start of the path.
1707 c = ap_strchr_c(c+3, '/');
1710 pathstart = url_copy + (c - url);
1712 ap_str_tolower(url_copy);
1713 min_match = strlen(url_copy);
1717 ap_str_tolower(url_copy);
1718 min_match = strlen(url_copy);
1721 * Do a "longest match" on the worker name to find the worker that
1722 * fits best to the URL, but keep in mind that we must have at least
1723 * a minimum matching of length min_match such that
1724 * scheme://hostname[:port] matches between worker and url.
1728 proxy_worker **workers = (proxy_worker **)balancer->workers->elts;
1729 for (i = 0; i < balancer->workers->nelts; i++, workers++) {
1731 if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1732 && (worker_name_length >= min_match)
1733 && (worker_name_length > max_match)
1734 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1735 max_worker = worker;
1736 max_match = worker_name_length;
1741 worker = (proxy_worker *)conf->workers->elts;
1742 for (i = 0; i < conf->workers->nelts; i++, worker++) {
1743 if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1744 && (worker_name_length >= min_match)
1745 && (worker_name_length > max_match)
1746 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1747 max_worker = worker;
1748 max_match = worker_name_length;
1757 * To create a worker from scratch first we define the
1758 * specifics of the worker; this is all local data.
1759 * We then allocate space for it if data needs to be
1760 * shared. This allows for dynamic addition during
1761 * config and runtime.
1763 PROXY_DECLARE(char *) ap_proxy_define_worker(apr_pool_t *p,
1764 proxy_worker **worker,
1765 proxy_balancer *balancer,
1766 proxy_server_conf *conf,
1772 proxy_worker_shared *wshared;
1775 rv = apr_uri_parse(p, url, &uri);
1777 if (rv != APR_SUCCESS) {
1778 return "Unable to parse URL";
1780 if (!uri.hostname || !uri.scheme) {
1781 return "URL must be absolute!";
1784 ap_str_tolower(uri.hostname);
1785 ap_str_tolower(uri.scheme);
1787 * Workers can be associated w/ balancers or on their
1788 * own; ie: the generic reverse-proxy or a worker
1789 * in a simple ProxyPass statement. eg:
1791 * ProxyPass / http://www.example.com
1793 * in which case the worker goes in the conf slot.
1796 proxy_worker **runtime;
1797 /* recall that we get a ptr to the ptr here */
1798 runtime = apr_array_push(balancer->workers);
1799 *worker = *runtime = apr_palloc(p, sizeof(proxy_worker)); /* right to left baby */
1800 /* we've updated the list of workers associated with
1801 * this balancer *locally* */
1802 balancer->wupdated = apr_time_now();
1804 *worker = apr_array_push(conf->workers);
1806 /* we need to allocate space here */
1807 *worker = apr_palloc(p, sizeof(proxy_worker));
1810 memset(*worker, 0, sizeof(proxy_worker));
1811 /* right here we just want to tuck away the worker info.
1812 * if called during config, we don't have shm setup yet,
1813 * so just note the info for later. */
1815 wshared = ap_malloc(sizeof(proxy_worker_shared)); /* will be freed ap_proxy_share_worker */
1817 wshared = apr_palloc(p, sizeof(proxy_worker_shared));
1819 memset(wshared, 0, sizeof(proxy_worker_shared));
1821 ptr = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1822 if (PROXY_STRNCPY(wshared->name, ptr) != APR_SUCCESS) {
1823 return apr_psprintf(p, "worker name (%s) too long", ptr);
1825 if (PROXY_STRNCPY(wshared->scheme, uri.scheme) != APR_SUCCESS) {
1826 return apr_psprintf(p, "worker scheme (%s) too long", uri.scheme);
1828 if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) {
1829 return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
1831 wshared->port = uri.port;
1832 wshared->flush_packets = flush_off;
1833 wshared->flush_wait = PROXY_FLUSH_WAIT;
1834 wshared->is_address_reusable = 1;
1835 wshared->lbfactor = 1;
1837 wshared->hash = ap_proxy_hashfunc(wshared->name, PROXY_HASHFUNC_DEFAULT);
1838 wshared->was_malloced = (do_malloc != 0);
1840 (*worker)->hash = wshared->hash;
1841 (*worker)->context = NULL;
1842 (*worker)->cp = NULL;
1843 (*worker)->balancer = balancer;
1844 (*worker)->s = wshared;
1850 * Create an already defined worker and free up memory
1852 PROXY_DECLARE(apr_status_t) ap_proxy_share_worker(proxy_worker *worker, proxy_worker_shared *shm,
1855 if (!shm || !worker->s)
1858 memcpy(shm, worker->s, sizeof(proxy_worker_shared));
1859 if (worker->s->was_malloced)
1860 free(worker->s); /* was malloced in ap_proxy_define_worker */
1862 worker->s->index = i;
1866 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1868 apr_status_t rv = APR_SUCCESS;
1871 if (worker->s->status & PROXY_WORKER_INITIALIZED) {
1872 /* The worker is already initialized */
1873 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1874 "worker %s shared already initialized", worker->s->name);
1877 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1878 "initializing worker %s shared", worker->s->name);
1879 /* Set default parameters */
1880 if (!worker->s->retry_set) {
1881 worker->s->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1883 /* By default address is reusable unless DisableReuse is set */
1884 if (worker->s->disablereuse) {
1885 worker->s->is_address_reusable = 0;
1888 worker->s->is_address_reusable = 1;
1891 ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1892 if (mpm_threads > 1) {
1893 /* Set hard max to no more then mpm_threads */
1894 if (worker->s->hmax == 0 || worker->s->hmax > mpm_threads) {
1895 worker->s->hmax = mpm_threads;
1897 if (worker->s->smax == -1 || worker->s->smax > worker->s->hmax) {
1898 worker->s->smax = worker->s->hmax;
1900 /* Set min to be lower then smax */
1901 if (worker->s->min > worker->s->smax) {
1902 worker->s->min = worker->s->smax;
1906 /* This will supress the apr_reslist creation */
1907 worker->s->min = worker->s->smax = worker->s->hmax = 0;
1911 /* What if local is init'ed and shm isn't?? Even possible? */
1912 if (worker->local_status & PROXY_WORKER_INITIALIZED) {
1913 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1914 "worker %s local already initialized", worker->s->name);
1917 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1918 "initializing worker %s local", worker->s->name);
1919 /* Now init local worker data */
1920 if (worker->tmutex == NULL) {
1921 rv = apr_thread_mutex_create(&(worker->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1922 if (rv != APR_SUCCESS) {
1923 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1924 "can not create worker thread mutex");
1928 if (worker->cp == NULL)
1929 init_conn_pool(p, worker);
1930 if (worker->cp == NULL) {
1931 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1932 "can not create connection pool");
1933 return APR_EGENERAL;
1936 if (worker->s->hmax) {
1937 rv = apr_reslist_create(&(worker->cp->res),
1938 worker->s->min, worker->s->smax,
1939 worker->s->hmax, worker->s->ttl,
1940 connection_constructor, connection_destructor,
1941 worker, worker->cp->pool);
1943 apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1945 apr_pool_cleanup_null);
1947 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1948 "initialized pool in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1949 getpid(), worker->s->hostname, worker->s->min,
1950 worker->s->hmax, worker->s->smax);
1952 /* Set the acquire timeout */
1953 if (rv == APR_SUCCESS && worker->s->acquire_set) {
1954 apr_reslist_timeout_set(worker->cp->res, worker->s->acquire);
1961 rv = connection_constructor(&conn, worker, worker->cp->pool);
1962 worker->cp->conn = conn;
1964 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1965 "initialized single connection worker in child %" APR_PID_T_FMT " for (%s)",
1966 getpid(), worker->s->hostname);
1969 if (rv == APR_SUCCESS) {
1970 worker->s->status |= (PROXY_WORKER_INITIALIZED);
1971 worker->local_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 if (apr_time_now() > worker->s->error_time + worker->s->retry) {
1982 ++worker->s->retries;
1983 worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1984 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1985 "%s: worker for (%s) has been marked for retry",
1986 proxy_function, worker->s->hostname);
1990 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1991 "%s: too soon to retry worker for (%s)",
1992 proxy_function, worker->s->hostname);
2001 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
2002 proxy_balancer **balancer,
2004 proxy_server_conf *conf, char **url)
2008 access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
2009 if (access_status == DECLINED && *balancer == NULL) {
2010 *worker = ap_proxy_get_worker(r->pool, NULL, conf, *url);
2012 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2013 "%s: found worker %s for %s",
2014 (*worker)->s->scheme, (*worker)->s->name, *url);
2019 else if (r->proxyreq == PROXYREQ_PROXY) {
2020 if (conf->forward) {
2021 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2022 "*: found forward proxy worker for %s", *url);
2024 *worker = conf->forward;
2027 * The forward worker does not keep connections alive, so
2028 * ensure that mod_proxy_http does the correct thing
2029 * regarding the Connection header in the request.
2031 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
2034 else if (r->proxyreq == PROXYREQ_REVERSE) {
2035 if (conf->reverse) {
2036 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2037 "*: found reverse proxy worker for %s", *url);
2039 *worker = conf->reverse;
2042 * The reverse worker does not keep connections alive, so
2043 * ensure that mod_proxy_http does the correct thing
2044 * regarding the Connection header in the request.
2046 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
2050 else if (access_status == DECLINED && *balancer != NULL) {
2051 /* All the workers are busy */
2052 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2053 "all workers are busy. Unable to serve %s", *url);
2054 access_status = HTTP_SERVICE_UNAVAILABLE;
2056 return access_status;
2059 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
2060 proxy_balancer *balancer,
2062 proxy_server_conf *conf)
2064 int access_status = OK;
2066 access_status = proxy_run_post_request(worker, balancer, r, conf);
2067 if (access_status == DECLINED) {
2068 access_status = OK; /* no post_request handler available */
2069 /* TODO: recycle direct worker */
2073 return access_status;
2077 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
2078 const char *proxy_function,
2079 apr_sockaddr_t *backend_addr,
2080 const char *backend_name,
2081 proxy_server_conf *conf,
2088 while (backend_addr && !connected) {
2089 if ((rv = apr_socket_create(newsock, backend_addr->family,
2090 SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
2091 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2092 ap_log_rerror(APLOG_MARK, loglevel, rv, r,
2093 "%s: error creating fam %d socket for target %s",
2094 proxy_function, backend_addr->family, backend_name);
2096 * this could be an IPv6 address from the DNS but the
2097 * local machine won't give us an IPv6 socket; hopefully the
2098 * DNS returned an additional address to try
2100 backend_addr = backend_addr->next;
2104 if (conf->recv_buffer_size > 0 &&
2105 (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
2106 conf->recv_buffer_size))) {
2107 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2108 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2109 "ProxyReceiveBufferSize, using default");
2112 rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
2113 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2114 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2115 "apr_socket_opt_set(APR_TCP_NODELAY): "
2119 /* Set a timeout on the socket */
2120 if (conf->timeout_set) {
2121 apr_socket_timeout_set(*newsock, conf->timeout);
2124 apr_socket_timeout_set(*newsock, r->server->timeout);
2127 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2128 "%s: fam %d socket created to connect to %s",
2129 proxy_function, backend_addr->family, backend_name);
2131 if (conf->source_address) {
2132 rv = apr_socket_bind(*newsock, conf->source_address);
2133 if (rv != APR_SUCCESS) {
2134 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2135 "%s: failed to bind socket to local address",
2140 /* make the connection out of the socket */
2141 rv = apr_socket_connect(*newsock, backend_addr);
2143 /* if an error occurred, loop round and try again */
2144 if (rv != APR_SUCCESS) {
2145 apr_socket_close(*newsock);
2146 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2147 ap_log_rerror(APLOG_MARK, loglevel, rv, r,
2148 "%s: attempt to connect to %pI (%s) failed",
2149 proxy_function, backend_addr, backend_name);
2150 backend_addr = backend_addr->next;
2155 return connected ? 0 : 1;
2158 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
2159 proxy_conn_rec **conn,
2160 proxy_worker *worker,
2165 if (!PROXY_WORKER_IS_USABLE(worker)) {
2166 /* Retry the worker */
2167 ap_proxy_retry_worker(proxy_function, worker, s);
2169 if (!PROXY_WORKER_IS_USABLE(worker)) {
2170 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2171 "%s: disabled connection for (%s)",
2172 proxy_function, worker->s->hostname);
2173 return HTTP_SERVICE_UNAVAILABLE;
2177 if (worker->s->hmax && worker->cp->res) {
2178 rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2181 /* create the new connection if the previous was destroyed */
2182 if (!worker->cp->conn) {
2183 connection_constructor((void **)conn, worker, worker->cp->pool);
2186 *conn = worker->cp->conn;
2187 worker->cp->conn = NULL;
2192 if (rv != APR_SUCCESS) {
2193 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2194 "%s: failed to acquire connection for (%s)",
2195 proxy_function, worker->s->hostname);
2196 return HTTP_SERVICE_UNAVAILABLE;
2198 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2199 "%s: has acquired connection for (%s)",
2200 proxy_function, worker->s->hostname);
2202 (*conn)->worker = worker;
2204 (*conn)->inreslist = 0;
2209 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2210 proxy_conn_rec *conn,
2213 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2214 "%s: has released connection for (%s)",
2215 proxy_function, conn->worker->s->hostname);
2216 connection_cleanup(conn);
2222 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2223 proxy_server_conf *conf,
2224 proxy_worker *worker,
2225 proxy_conn_rec *conn,
2228 const char *proxyname,
2229 apr_port_t proxyport,
2230 char *server_portstr,
2231 int server_portstr_size)
2234 apr_status_t err = APR_SUCCESS;
2235 apr_status_t uerr = APR_SUCCESS;
2238 * Break up the URL to determine the host to connect to
2241 /* we break the URL into host, port, uri */
2242 if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2243 return ap_proxyerror(r, HTTP_BAD_REQUEST,
2244 apr_pstrcat(p,"URI cannot be parsed: ", *url,
2248 uri->port = apr_uri_port_of_scheme(uri->scheme);
2251 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2252 "connecting %s to %s:%d", *url, uri->hostname, uri->port);
2255 * allocate these out of the specified connection pool
2256 * The scheme handler decides if this is permanent or
2257 * short living pool.
2259 /* are we connecting directly, or via a proxy? */
2261 *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2262 uri->query ? uri->query : "",
2263 uri->fragment ? "#" : "",
2264 uri->fragment ? uri->fragment : "", NULL);
2267 * Make sure that we pick the the correct and valid worker.
2268 * If a single keepalive connection triggers different workers,
2269 * then we have a problem (we don't select the correct one).
2270 * Do an expensive check in this case, where we compare the
2271 * the hostnames associated between the two.
2273 * TODO: Handle this much better...
2275 if (!conn->hostname || !worker->s->is_address_reusable ||
2276 worker->s->disablereuse ||
2277 (r->connection->keepalives &&
2278 (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2279 (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2281 conn->hostname = apr_pstrdup(conn->pool, proxyname);
2282 conn->port = proxyport;
2284 * If we have a forward proxy and the protocol is HTTPS,
2285 * then we need to prepend a HTTP CONNECT request before
2286 * sending our actual HTTPS requests.
2287 * Save our real backend data for using it later during HTTP CONNECT.
2290 const char *proxy_auth;
2292 forward_info *forward = apr_pcalloc(conn->pool, sizeof(forward_info));
2293 conn->forward = forward;
2294 forward->use_http_connect = 1;
2295 forward->target_host = apr_pstrdup(conn->pool, uri->hostname);
2296 forward->target_port = uri->port;
2297 /* Do we want to pass Proxy-Authorization along?
2298 * If we haven't used it, then YES
2299 * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
2300 * So let's make it configurable by env.
2301 * The logic here is the same used in mod_proxy_http.
2303 proxy_auth = apr_table_get(r->headers_in, "Proxy-Authorization");
2304 if (proxy_auth != NULL &&
2305 proxy_auth[0] != '\0' &&
2306 r->user == NULL && /* we haven't yet authenticated */
2307 apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
2308 forward->proxy_auth = apr_pstrdup(conn->pool, proxy_auth);
2313 conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2314 conn->port = uri->port;
2316 socket_cleanup(conn);
2317 err = apr_sockaddr_info_get(&(conn->addr),
2318 conn->hostname, APR_UNSPEC,
2322 else if (!worker->cp->addr) {
2323 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2324 ap_log_rerror(APLOG_MARK, APLOG_ERR, err, r, "lock");
2325 return HTTP_INTERNAL_SERVER_ERROR;
2329 * Worker can have the single constant backend adress.
2330 * The single DNS lookup is used once per worker.
2331 * If dynamic change is needed then set the addr to NULL
2332 * inside dynamic config to force the lookup.
2334 err = apr_sockaddr_info_get(&(worker->cp->addr),
2335 conn->hostname, APR_UNSPEC,
2338 conn->addr = worker->cp->addr;
2339 if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2340 ap_log_rerror(APLOG_MARK, APLOG_ERR, uerr, r, "unlock");
2344 conn->addr = worker->cp->addr;
2346 /* Close a possible existing socket if we are told to do so */
2348 socket_cleanup(conn);
2352 if (err != APR_SUCCESS) {
2353 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2354 apr_pstrcat(p, "DNS lookup failure for: ",
2355 conn->hostname, NULL));
2358 /* Get the server port for the Via headers */
2360 server_port = ap_get_server_port(r);
2361 if (ap_is_default_port(server_port, r)) {
2362 strcpy(server_portstr,"");
2365 apr_snprintf(server_portstr, server_portstr_size, ":%d",
2369 /* check if ProxyBlock directive on this host */
2370 if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2371 return ap_proxyerror(r, HTTP_FORBIDDEN,
2372 "Connect to remote machine blocked");
2374 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2375 "connected %s to %s:%d", *url, conn->hostname, conn->port);
2379 #define USE_ALTERNATE_IS_CONNECTED 1
2381 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2382 #define APR_MSG_PEEK MSG_PEEK
2385 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2386 static int is_socket_connected(apr_socket_t *socket)
2388 apr_pollfd_t pfds[1];
2389 apr_status_t status;
2392 pfds[0].reqevents = APR_POLLIN;
2393 pfds[0].desc_type = APR_POLL_SOCKET;
2394 pfds[0].desc.s = socket;
2397 status = apr_poll(&pfds[0], 1, &nfds, 0);
2398 } while (APR_STATUS_IS_EINTR(status));
2400 if (status == APR_SUCCESS && nfds == 1 &&
2401 pfds[0].rtnevents == APR_POLLIN) {
2402 apr_sockaddr_t unused;
2405 /* The socket might be closed in which case
2406 * the poll will return POLLIN.
2407 * If there is no data available the socket
2410 status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2412 if (status == APR_SUCCESS && len)
2417 else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2424 static int is_socket_connected(apr_socket_t *sock)
2427 apr_size_t buffer_len = 1;
2428 char test_buffer[1];
2429 apr_status_t socket_status;
2430 apr_interval_time_t current_timeout;
2433 apr_socket_timeout_get(sock, ¤t_timeout);
2434 /* set no timeout */
2435 apr_socket_timeout_set(sock, 0);
2436 socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2437 /* put back old timeout */
2438 apr_socket_timeout_set(sock, current_timeout);
2439 if (APR_STATUS_IS_EOF(socket_status)
2440 || APR_STATUS_IS_ECONNRESET(socket_status)) {
2447 #endif /* USE_ALTERNATE_IS_CONNECTED */
2451 * Send a HTTP CONNECT request to a forward proxy.
2452 * The proxy is given by "backend", the target server
2453 * is contained in the "forward" member of "backend".
2455 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2462 char buffer[HUGE_STRING_LEN];
2463 char drain_buffer[HUGE_STRING_LEN];
2464 forward_info *forward = (forward_info *)backend->forward;
2467 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2468 "CONNECT: sending the CONNECT request for %s:%d "
2469 "to the remote proxy %pI (%s)",
2470 forward->target_host, forward->target_port,
2471 backend->addr, backend->hostname);
2472 /* Create the CONNECT request */
2473 nbytes = apr_snprintf(buffer, sizeof(buffer),
2474 "CONNECT %s:%d HTTP/1.0" CRLF,
2475 forward->target_host, forward->target_port);
2476 /* Add proxy authorization from the initial request if necessary */
2477 if (forward->proxy_auth != NULL) {
2478 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2479 "Proxy-Authorization: %s" CRLF,
2480 forward->proxy_auth);
2482 /* Set a reasonable agent and send everything */
2483 nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2484 "Proxy-agent: %s" CRLF CRLF,
2485 ap_get_server_banner());
2486 apr_socket_send(backend->sock, buffer, &nbytes);
2488 /* Receive the whole CONNECT response */
2489 left = sizeof(buffer) - 1;
2490 /* Read until we find the end of the headers or run out of buffer */
2493 status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2497 if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2501 } while (status == APR_SUCCESS && left > 0);
2502 /* Drain what's left */
2504 nbytes = sizeof(drain_buffer) - 1;
2505 while (status == APR_SUCCESS && nbytes) {
2506 status = apr_socket_recv(backend->sock, drain_buffer, &nbytes);
2507 buffer[nbytes] = '\0';
2508 nbytes = sizeof(drain_buffer) - 1;
2509 if (strstr(drain_buffer, "\r\n\r\n") != NULL) {
2515 /* Check for HTTP_OK response status */
2516 if (status == APR_SUCCESS) {
2518 /* Only scan for three character status code */
2521 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2522 "send_http_connect: response from the forward proxy: %s",
2525 /* Extract the returned code */
2526 if (sscanf(buffer, "HTTP/%u.%u %3s", &major, &minor, code_str) == 3) {
2527 status = atoi(code_str);
2528 if (status == HTTP_OK) {
2529 status = APR_SUCCESS;
2532 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2533 "send_http_connect: the forward proxy returned code is '%s'",
2535 status = APR_INCOMPLETE;
2544 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2545 proxy_conn_rec *conn,
2546 proxy_worker *worker,
2552 apr_sockaddr_t *backend_addr = conn->addr;
2553 /* the local address to use for the outgoing connection */
2554 apr_sockaddr_t *local_addr;
2555 apr_socket_t *newsock;
2556 void *sconf = s->module_config;
2557 proxy_server_conf *conf =
2558 (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2561 if (!(connected = is_socket_connected(conn->sock))) {
2562 socket_cleanup(conn);
2563 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2564 "%s: backend socket is disconnected.",
2568 while (backend_addr && !connected) {
2569 if ((rv = apr_socket_create(&newsock, backend_addr->family,
2570 SOCK_STREAM, APR_PROTO_TCP,
2571 conn->scpool)) != APR_SUCCESS) {
2572 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2573 ap_log_error(APLOG_MARK, loglevel, rv, s,
2574 "%s: error creating fam %d socket for target %s",
2576 backend_addr->family,
2577 worker->s->hostname);
2579 * this could be an IPv6 address from the DNS but the
2580 * local machine won't give us an IPv6 socket; hopefully the
2581 * DNS returned an additional address to try
2583 backend_addr = backend_addr->next;
2586 conn->connection = NULL;
2588 if (worker->s->recv_buffer_size > 0 &&
2589 (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2590 worker->s->recv_buffer_size))) {
2591 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2592 "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2593 "ProxyReceiveBufferSize, using default");
2596 rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2597 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2598 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2599 "apr_socket_opt_set(APR_TCP_NODELAY): "
2603 /* Set a timeout for connecting to the backend on the socket */
2604 if (worker->s->conn_timeout_set) {
2605 apr_socket_timeout_set(newsock, worker->s->conn_timeout);
2607 else if (worker->s->timeout_set) {
2608 apr_socket_timeout_set(newsock, worker->s->timeout);
2610 else if (conf->timeout_set) {
2611 apr_socket_timeout_set(newsock, conf->timeout);
2614 apr_socket_timeout_set(newsock, s->timeout);
2616 /* Set a keepalive option */
2617 if (worker->s->keepalive) {
2618 if ((rv = apr_socket_opt_set(newsock,
2619 APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2620 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2621 "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2625 ap_log_error(APLOG_MARK, APLOG_TRACE2, 0, s,
2626 "%s: fam %d socket created to connect to %s",
2627 proxy_function, backend_addr->family, worker->s->hostname);
2629 if (conf->source_address_set) {
2630 local_addr = apr_pmemdup(conn->pool, conf->source_address,
2631 sizeof(apr_sockaddr_t));
2632 local_addr->pool = conn->pool;
2633 rv = apr_socket_bind(newsock, local_addr);
2634 if (rv != APR_SUCCESS) {
2635 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2636 "%s: failed to bind socket to local address",
2641 /* make the connection out of the socket */
2642 rv = apr_socket_connect(newsock, backend_addr);
2644 /* if an error occurred, loop round and try again */
2645 if (rv != APR_SUCCESS) {
2646 apr_socket_close(newsock);
2647 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2648 ap_log_error(APLOG_MARK, loglevel, rv, s,
2649 "%s: attempt to connect to %pI (%s) failed",
2652 worker->s->hostname);
2653 backend_addr = backend_addr->next;
2657 /* Set a timeout on the socket */
2658 if (worker->s->timeout_set) {
2659 apr_socket_timeout_set(newsock, worker->s->timeout);
2661 else if (conf->timeout_set) {
2662 apr_socket_timeout_set(newsock, conf->timeout);
2665 apr_socket_timeout_set(newsock, s->timeout);
2668 conn->sock = newsock;
2670 if (conn->forward) {
2671 forward_info *forward = (forward_info *)conn->forward;
2673 * For HTTP CONNECT we need to prepend CONNECT request before
2674 * sending our actual HTTPS requests.
2676 if (forward->use_http_connect) {
2677 rv = send_http_connect(conn, s);
2678 /* If an error occurred, loop round and try again */
2679 if (rv != APR_SUCCESS) {
2681 apr_socket_close(newsock);
2682 loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2683 ap_log_error(APLOG_MARK, loglevel, rv, s,
2684 "%s: attempt to connect to %s:%d "
2685 "via http CONNECT through %pI (%s) failed",
2687 forward->target_host, forward->target_port,
2688 backend_addr, worker->s->hostname);
2689 backend_addr = backend_addr->next;
2698 * Put the entire worker to error state if
2699 * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2700 * Altrough some connections may be alive
2701 * no further connections to the worker could be made
2703 if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2704 !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2705 worker->s->error_time = apr_time_now();
2706 worker->s->status |= PROXY_WORKER_IN_ERROR;
2707 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2708 "ap_proxy_connect_backend disabling worker for (%s) for %"
2710 worker->s->hostname, apr_time_sec(worker->s->retry));
2713 if (worker->s->retries) {
2715 * A worker came back. So here is where we need to
2716 * either reset all params to initial conditions or
2717 * apply some sort of aging
2720 worker->s->error_time = 0;
2721 worker->s->retries = 0;
2723 return connected ? OK : DECLINED;
2726 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2727 proxy_conn_rec *conn,
2731 apr_sockaddr_t *backend_addr = conn->addr;
2733 apr_interval_time_t current_timeout;
2734 apr_bucket_alloc_t *bucket_alloc;
2736 if (conn->connection) {
2740 bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2742 * The socket is now open, create a new backend server connection
2744 conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2748 if (!conn->connection) {
2750 * the peer reset the connection already; ap_run_create_connection()
2753 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2754 s, "%s: an error occurred creating a "
2755 "new connection to %pI (%s)", proxy_function,
2756 backend_addr, conn->hostname);
2757 /* XXX: Will be closed when proxy_conn is closed */
2758 socket_cleanup(conn);
2759 return HTTP_INTERNAL_SERVER_ERROR;
2762 /* For ssl connection to backend */
2764 if (!ap_proxy_ssl_enable(conn->connection)) {
2765 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2766 s, "%s: failed to enable ssl support "
2767 "for %pI (%s)", proxy_function,
2768 backend_addr, conn->hostname);
2769 return HTTP_INTERNAL_SERVER_ERROR;
2773 /* TODO: See if this will break FTP */
2774 ap_proxy_ssl_disable(conn->connection);
2777 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2778 "%s: connection complete to %pI (%s)",
2779 proxy_function, backend_addr, conn->hostname);
2782 * save the timeout of the socket because core_pre_connection
2783 * will set it to base_server->timeout
2784 * (core TimeOut directive).
2786 apr_socket_timeout_get(conn->sock, ¤t_timeout);
2787 /* set up the connection filters */
2788 rc = ap_run_pre_connection(conn->connection, conn->sock);
2789 if (rc != OK && rc != DONE) {
2790 conn->connection->aborted = 1;
2791 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2792 "%s: pre_connection setup failed (%d)",
2793 proxy_function, rc);
2796 apr_socket_timeout_set(conn->sock, current_timeout);
2801 int ap_proxy_lb_workers(void)
2804 * Since we can't resize the scoreboard when reconfiguring, we
2805 * have to impose a limit on the number of workers, we are
2806 * able to reconfigure to.
2808 if (!lb_workers_limit)
2809 lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2810 return lb_workers_limit;
2813 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2814 apr_bucket_brigade *brigade)
2817 conn_rec *c = r->connection;
2821 * If this is a subrequest, then prevent also caching of the main
2825 r->main->no_cache = 1;
2826 e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2828 APR_BRIGADE_INSERT_TAIL(brigade, e);
2829 e = apr_bucket_eos_create(c->bucket_alloc);
2830 APR_BRIGADE_INSERT_TAIL(brigade, e);
2834 * Transform buckets from one bucket allocator to another one by creating a
2835 * transient bucket for each data bucket and let it use the data read from
2836 * the old bucket. Metabuckets are transformed by just recreating them.
2837 * Attention: Currently only the following bucket types are handled:
2843 * If an other bucket type is found its type is logged as a debug message
2844 * and APR_EGENERAL is returned.
2846 PROXY_DECLARE(apr_status_t)
2847 ap_proxy_buckets_lifetime_transform(request_rec *r, apr_bucket_brigade *from,
2848 apr_bucket_brigade *to)
2854 apr_status_t rv = APR_SUCCESS;
2856 apr_brigade_cleanup(to);
2857 for (e = APR_BRIGADE_FIRST(from);
2858 e != APR_BRIGADE_SENTINEL(from);
2859 e = APR_BUCKET_NEXT(e)) {
2860 if (!APR_BUCKET_IS_METADATA(e)) {
2861 apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
2862 new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
2863 APR_BRIGADE_INSERT_TAIL(to, new);
2865 else if (APR_BUCKET_IS_FLUSH(e)) {
2866 new = apr_bucket_flush_create(r->connection->bucket_alloc);
2867 APR_BRIGADE_INSERT_TAIL(to, new);
2869 else if (APR_BUCKET_IS_EOS(e)) {
2870 new = apr_bucket_eos_create(r->connection->bucket_alloc);
2871 APR_BRIGADE_INSERT_TAIL(to, new);
2874 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2875 "Unhandled bucket type of type %s in"
2876 " ap_proxy_buckets_lifetime_transform", e->type->name);
2877 apr_bucket_delete(e);
2885 * Provide a string hashing function for the proxy.
2886 * We offer 2 methods: one is the APR model but we
2887 * also provide our own, based on either FNV or SDBM.
2888 * The reason is in case we want to use both to ensure no
2891 PROXY_DECLARE(unsigned int)
2892 ap_proxy_hashfunc(const char *str, proxy_hash_t method)
2894 if (method == PROXY_HASHFUNC_APR) {
2895 apr_ssize_t slen = strlen(str);
2896 return apr_hashfunc_default(str, &slen);
2898 else if (method == PROXY_HASHFUNC_FNV) {
2901 const unsigned int fnv_prime = 0x811C9DC5;
2902 for (hash = 0; *str; str++) {
2908 else { /* method == PROXY_HASHFUNC_DEFAULT */
2911 for (hash = 0; *str; str++) {
2912 hash = (*str) + (hash << 6) + (hash << 16) - hash;
2918 PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w)
2920 unsigned int *status = &w->s->status;
2921 char flag = toupper(c);
2922 struct wstat *pwt = wstat_tbl;
2924 if (flag == pwt->flag) {
2926 *status |= pwt->bit;
2928 *status &= ~(pwt->bit);
2936 PROXY_DECLARE(char *) ap_proxy_parse_wstatus(apr_pool_t *p, proxy_worker *w)
2939 unsigned int status = w->s->status;
2940 struct wstat *pwt = wstat_tbl;
2942 if (status & pwt->bit)
2943 ret = apr_pstrcat(p, ret, pwt->name, NULL);
2946 if (PROXY_WORKER_IS_USABLE(w))
2947 ret = apr_pstrcat(p, ret, "Ok ", NULL);
2951 PROXY_DECLARE(apr_status_t) ap_proxy_sync_balancer(proxy_balancer *b, server_rec *s,
2952 proxy_server_conf *conf)
2954 proxy_worker **workers;
2957 proxy_worker_shared *shm;
2958 proxy_balancer_method *lbmethod;
2959 ap_slotmem_provider_t *storage = b->storage;
2961 if (b->s->wupdated <= b->wupdated)
2964 lbmethod = ap_lookup_provider(PROXY_LBMETHOD, b->s->lbpname, "0");
2966 b->lbmethod = lbmethod;
2971 * Look thru the list of workers in shm
2972 * and see which one(s) we are lacking...
2973 * again, the cast to unsigned int is safe
2974 * since our upper limit is always max_workers
2977 for (index = 0; index < b->max_workers; index++) {
2980 if ((rv = storage->dptr(b->wslot, (unsigned int)index, (void *)&shm)) != APR_SUCCESS) {
2981 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "worker slotmem_dptr failed");
2982 return APR_EGENERAL;
2984 /* account for possible "holes" in the slotmem
2985 * (eg: slots 0-2 are used, but 3 isn't, but 4-5 is)
2990 workers = (proxy_worker **)b->workers->elts;
2991 for (i = 0; i < b->workers->nelts; i++, workers++) {
2992 proxy_worker *worker = *workers;
2993 if (worker->hash == shm->hash) {
2999 proxy_worker **runtime;
3000 runtime = apr_array_push(b->workers);
3001 *runtime = apr_palloc(conf->pool, sizeof(proxy_worker));
3002 (*runtime)->hash = shm->hash;
3003 (*runtime)->context = NULL;
3004 (*runtime)->cp = NULL;
3005 (*runtime)->balancer = b;
3006 (*runtime)->s = shm;
3007 (*runtime)->tmutex = NULL;
3008 if ((rv = ap_proxy_initialize_worker(*runtime, s, conf->pool)) != APR_SUCCESS) {
3009 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Cannot init worker");
3014 if (b->s->need_reset) {
3015 if (b->lbmethod && b->lbmethod->reset)
3016 b->lbmethod->reset(b, s);
3017 b->s->need_reset = 0;
3019 b->wupdated = b->s->wupdated;