]> granicus.if.org Git - apache/blob - modules/proxy/proxy_util.c
mod_proxy: Make sure we populate the client IP from the peer IP for proxy
[apache] / modules / proxy / proxy_util.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /* Utility routines for Apache proxy */
18 #include "mod_proxy.h"
19 #include "ap_mpm.h"
20 #include "scoreboard.h"
21 #include "apr_version.h"
22 #include "apr_hash.h"
23 #include "proxy_util.h"
24
25 #if APR_HAVE_UNISTD_H
26 #include <unistd.h>         /* for getpid() */
27 #endif
28
29 #if (APR_MAJOR_VERSION < 1)
30 #undef apr_socket_create
31 #define apr_socket_create apr_socket_create_ex
32 #endif
33
34 APLOG_USE_MODULE(proxy);
35
36 /*
37  * Opaque structure containing target server info when
38  * using a forward proxy.
39  * Up to now only used in combination with HTTP CONNECT.
40  */
41 typedef struct {
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 */
46 } forward_info;
47
48 /* Keep synced with mod_proxy.h! */
49 static struct wstat {
50     unsigned int bit;
51     char flag;
52     const char *name;
53 } wstat_tbl[] = {
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 "},
63     {0x0, '\0', NULL}
64 };
65
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;
71
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);
76
77 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
78                                    (request_rec *r, request_rec *pr), (r, pr),
79                                    OK, DECLINED)
80
81 PROXY_DECLARE(apr_status_t) ap_proxy_strncpy(char *dst, const char *src, size_t dlen)
82 {
83     if ((strlen(src)+1) > dlen) {
84         /* APR_ENOSPACE would be better */
85         return APR_EGENERAL;
86     }
87     else {
88         apr_cpystrn(dst, src, dlen);
89     }
90     return APR_SUCCESS;
91 }
92
93 /* already called in the knowledge that the characters are hex digits */
94 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
95 {
96     int i;
97
98 #if !APR_CHARSET_EBCDIC
99     int ch = x[0];
100
101     if (apr_isdigit(ch)) {
102         i = ch - '0';
103     }
104     else if (apr_isupper(ch)) {
105         i = ch - ('A' - 10);
106     }
107     else {
108         i = ch - ('a' - 10);
109     }
110     i <<= 4;
111
112     ch = x[1];
113     if (apr_isdigit(ch)) {
114         i += ch - '0';
115     }
116     else if (apr_isupper(ch)) {
117         i += ch - ('A' - 10);
118     }
119     else {
120         i += ch - ('a' - 10);
121     }
122     return i;
123 #else /*APR_CHARSET_EBCDIC*/
124     /*
125      * we assume that the hex value refers to an ASCII character
126      * so convert to EBCDIC so that it makes sense locally;
127      *
128      * example:
129      *
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
134      * 0x40
135      */
136     char buf[1];
137
138     if (1 == sscanf(x, "%2x", &i)) {
139         buf[0] = i & 0xFF;
140         ap_xlate_proto_from_ascii(buf, 1);
141         return buf[0];
142     }
143     else {
144         return 0;
145     }
146 #endif /*APR_CHARSET_EBCDIC*/
147 }
148
149 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
150 {
151 #if !APR_CHARSET_EBCDIC
152     int i;
153
154     x[0] = '%';
155     i = (ch & 0xF0) >> 4;
156     if (i >= 10) {
157         x[1] = ('A' - 10) + i;
158     }
159     else {
160         x[1] = '0' + i;
161     }
162
163     i = ch & 0x0F;
164     if (i >= 10) {
165         x[2] = ('A' - 10) + i;
166     }
167     else {
168         x[2] = '0' + i;
169     }
170 #else /*APR_CHARSET_EBCDIC*/
171     static const char ntoa[] = { "0123456789ABCDEF" };
172     char buf[1];
173
174     ch &= 0xFF;
175
176     buf[0] = ch;
177     ap_xlate_proto_to_ascii(buf, 1);
178
179     x[0] = '%';
180     x[1] = ntoa[(buf[0] >> 4) & 0x0F];
181     x[2] = ntoa[buf[0] & 0x0F];
182     x[3] = '\0';
183 #endif /*APR_CHARSET_EBCDIC*/
184 }
185
186 /*
187  * canonicalise a URL-encoded string
188  */
189
190 /*
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.
195  */
196 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
197                                        enum enctype t, int forcedec,
198                                        int proxyreq)
199 {
200     int i, j, ch;
201     char *y;
202     char *allowed;  /* characters which should not be encoded */
203     char *reserved; /* characters which much not be en/de-coded */
204
205 /*
206  * N.B. in addition to :@&=, this allows ';' in an http path
207  * and '?' in an ftp path -- this may be revised
208  *
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.)
212  */
213     if (t == enc_path) {
214         allowed = "~$-_.+!*'(),;:@&=";
215     }
216     else if (t == enc_search) {
217         allowed = "$-_.!*'(),;:@&=";
218     }
219     else if (t == enc_user) {
220         allowed = "$-_.+!*'(),;@&=";
221     }
222     else if (t == enc_fpath) {
223         allowed = "$-_.+!*'(),?:@&=";
224     }
225     else {            /* if (t == enc_parm) */
226         allowed = "$-_.+!*'(),?/:@&=";
227     }
228
229     if (t == enc_path) {
230         reserved = "/";
231     }
232     else if (t == enc_search) {
233         reserved = "+";
234     }
235     else {
236         reserved = "";
237     }
238
239     y = apr_palloc(p, 3 * len + 1);
240
241     for (i = 0, j = 0; i < len; i++, j++) {
242 /* always handle '/' first */
243         ch = x[i];
244         if (strchr(reserved, ch)) {
245             y[j] = ch;
246             continue;
247         }
248 /*
249  * decode it if not already done. do not decode reverse proxied URLs
250  * unless specifically forced
251  */
252         if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
253             if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
254                 return NULL;
255             }
256             ch = ap_proxy_hex2c(&x[i + 1]);
257             i += 2;
258             if (ch != 0 && strchr(reserved, ch)) {  /* keep it encoded */
259                 ap_proxy_c2hex(ch, &y[j]);
260                 j += 2;
261                 continue;
262             }
263         }
264 /* recode it, if necessary */
265         if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
266             ap_proxy_c2hex(ch, &y[j]);
267             j += 2;
268         }
269         else {
270             y[j] = ch;
271         }
272     }
273     y[j] = '\0';
274     return y;
275 }
276
277 /*
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.
284  *
285  * Returns an error string.
286  */
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)
290 {
291     char *addr, *scope_id, *strp, *host, *url = *urlp;
292     char *user = NULL, *password = NULL;
293     apr_port_t tmp_port;
294     apr_status_t rv;
295
296     if (url[0] != '/' || url[1] != '/') {
297         return "Malformed URL";
298     }
299     host = url + 2;
300     url = strchr(host, '/');
301     if (url == NULL) {
302         url = "";
303     }
304     else {
305         *(url++) = '\0';    /* skip seperating '/' */
306     }
307
308     /* find _last_ '@' since it might occur in user/password part */
309     strp = strrchr(host, '@');
310
311     if (strp != NULL) {
312         *strp = '\0';
313         user = host;
314         host = strp + 1;
315
316 /* find password */
317         strp = strchr(user, ':');
318         if (strp != NULL) {
319             *strp = '\0';
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)";
323             }
324         }
325
326         user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
327         if (user == NULL) {
328             return "Bad %-escape in URL (username)";
329         }
330     }
331     if (userp != NULL) {
332         *userp = user;
333     }
334     if (passwordp != NULL) {
335         *passwordp = password;
336     }
337
338     /*
339      * Parse the host string to separate host portion from optional port.
340      * Perform range checking on port.
341      */
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";
345     }
346     if (tmp_port != 0) { /* only update caller's port if port was specified */
347         *port = tmp_port;
348     }
349
350     ap_str_tolower(addr); /* DNS names are case-insensitive */
351
352     *urlp = url;
353     *hostp = addr;
354
355     return NULL;
356 }
357
358 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
359 {
360     apr_pool_t *pool;
361     request_rec *rp;
362
363     apr_pool_create(&pool, c->pool);
364
365     rp = apr_pcalloc(pool, sizeof(*r));
366
367     rp->pool            = pool;
368     rp->status          = HTTP_OK;
369
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);
375
376     rp->server = r->server;
377     rp->log = r->log;
378     rp->proxyreq = r->proxyreq;
379     rp->request_time = r->request_time;
380     rp->connection      = c;
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;
387
388     rp->request_config  = ap_create_request_config(pool);
389     proxy_run_create_req(r, rp);
390
391     return rp;
392 }
393
394 /*
395  * Converts 8 hex digits to a time integer
396  */
397 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
398 {
399     int i, ch;
400     unsigned int j;
401
402     for (i = 0, j = 0; i < 8; i++) {
403         ch = x[i];
404         j <<= 4;
405         if (apr_isdigit(ch)) {
406             j |= ch - '0';
407         }
408         else if (apr_isupper(ch)) {
409             j |= ch - ('A' - 10);
410         }
411         else {
412             j |= ch - ('a' - 10);
413         }
414     }
415     if (j == 0xffffffff) {
416         return -1;      /* so that it works with 8-byte ints */
417     }
418     else {
419         return j;
420     }
421 }
422
423 /*
424  * Converts a time integer to 8 hex digits
425  */
426 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
427 {
428     int i, ch;
429     unsigned int j = t;
430
431     for (i = 7; i >= 0; i--) {
432         ch = j & 0xF;
433         j >>= 4;
434         if (ch >= 10) {
435             y[i] = ch + ('A' - 10);
436         }
437         else {
438             y[i] = ch + '0';
439         }
440     }
441     y[8] = '\0';
442 }
443
444 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
445 {
446     const char *uri = ap_escape_html(r->pool, r->uri);
447     apr_table_setn(r->notes, "error-notes",
448         apr_pstrcat(r->pool,
449             "The proxy server could not handle the request <em><a href=\"",
450             uri, "\">", ap_escape_html(r->pool, r->method), "&nbsp;", uri,
451             "</a></em>.<p>\n"
452             "Reason: <strong>", ap_escape_html(r->pool, message),
453             "</strong></p>",
454             NULL));
455
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, "*"));
458
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,
461                   r->uri);
462     return statuscode;
463 }
464
465 static const char *
466      proxy_get_host_of_request(request_rec *r)
467 {
468     char *url, *user = NULL, *password = NULL, *err, *host;
469     apr_port_t port;
470
471     if (r->hostname != NULL) {
472         return r->hostname;
473     }
474
475     /* Set url to the first char after "scheme://" */
476     if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
477         return NULL;
478     }
479
480     url = apr_pstrdup(r->pool, &url[1]);    /* make it point to "//", which is what proxy_canon_netloc expects */
481
482     err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
483
484     if (err != NULL) {
485         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00899) "%s", err);
486     }
487
488     r->hostname = host;
489
490     return host;        /* ought to return the port, too */
491 }
492
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)
495 {
496     const char *addr = This->name;
497     long ip_addr[4];
498     int i, quads;
499     long bits;
500
501     /*
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()
509      * return 1;
510      */
511
512     /*
513      * Parse IP addr manually, optionally allowing
514      * abbreviated net addresses like 192.168.
515      */
516
517     /* Iterate over up to 4 (dotted) quads. */
518     for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
519         char *tmp;
520
521         if (*addr == '/' && quads > 0) {  /* netmask starts here. */
522             break;
523         }
524
525         if (!apr_isdigit(*addr)) {
526             return 0;       /* no digit at start of quad */
527         }
528
529         ip_addr[quads] = strtol(addr, &tmp, 0);
530
531         if (tmp == addr) {  /* expected a digit, found something else */
532             return 0;
533         }
534
535         if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
536             /* invalid octet */
537             return 0;
538         }
539
540         addr = tmp;
541
542         if (*addr == '.' && quads != 3) {
543             ++addr;     /* after the 4th quad, a dot would be illegal */
544         }
545     }
546
547     for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
548         This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
549     }
550
551     if (addr[0] == '/' && apr_isdigit(addr[1])) {   /* net mask follows: */
552         char *tmp;
553
554         ++addr;
555
556         bits = strtol(addr, &tmp, 0);
557
558         if (tmp == addr) {   /* expected a digit, found something else */
559             return 0;
560         }
561
562         addr = tmp;
563
564         if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
565             return 0;
566         }
567
568     }
569     else {
570         /*
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.)
574          */
575         while (quads > 0 && ip_addr[quads - 1] == 0) {
576             --quads;
577         }
578
579         /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
580         if (quads < 1) {
581             return 0;
582         }
583
584         /* every zero-byte counts as 8 zero-bits */
585         bits = 8 * quads;
586
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);
591         }
592     }
593
594     This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
595
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);
603     }
604
605     if (*addr == '\0') {
606         This->matcher = proxy_match_ipaddr;
607         return 1;
608     }
609     else {
610         return (*addr == '\0'); /* okay iff we've parsed the whole string */
611     }
612 }
613
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)
616 {
617     int i, ip_addr[4];
618     struct in_addr addr, *ip;
619     const char *host = proxy_get_host_of_request(r);
620
621     if (host == NULL) {   /* oops! */
622        return 0;
623     }
624
625     memset(&addr, '\0', sizeof addr);
626     memset(ip_addr, '\0', sizeof ip_addr);
627
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]
632              */
633             addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
634         }
635
636         if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
637 #if DEBUGGING
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));
644 #endif
645             return 1;
646         }
647 #if DEBUGGING
648         else {
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));
655         }
656 #endif
657     }
658     else {
659         struct apr_sockaddr_t *reqaddr;
660
661         if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
662             != APR_SUCCESS) {
663 #if DEBUGGING
664             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, APLOGNO(00909)
665              "2)IP-NoMatch: hostname=%s msg=Host not found", host);
666 #endif
667             return 0;
668         }
669
670         /* Try to deal with multiple IP addr's for a host */
671         /* FIXME: This needs to be able to deal with IPv6 */
672         while (reqaddr) {
673             ip = (struct in_addr *) reqaddr->ipaddr_ptr;
674             if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
675 #if DEBUGGING
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));
682 #endif
683                 return 1;
684             }
685 #if DEBUGGING
686             else {
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));
693             }
694 #endif
695             reqaddr = reqaddr->next;
696         }
697     }
698
699     return 0;
700 }
701
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)
704 {
705     char *addr = This->name;
706     int i;
707
708     /* Domain name must start with a '.' */
709     if (addr[0] != '.') {
710         return 0;
711     }
712
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) {
715         continue;
716     }
717
718 #if 0
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 */
723     }
724 #endif
725
726     if (addr[i] != '\0') {
727         return 0;
728     }
729
730     /* Strip trailing dots */
731     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
732         addr[i] = '\0';
733     }
734
735     This->matcher = proxy_match_domainname;
736     return 1;
737 }
738
739 /* Return TRUE if host "host" is in domain "domain" */
740 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
741 {
742     const char *host = proxy_get_host_of_request(r);
743     int d_len = strlen(This->name), h_len;
744
745     if (host == NULL) {      /* some error was logged already */
746         return 0;
747     }
748
749     h_len = strlen(host);
750
751     /* @@@ do this within the setup? */
752     /* Ignore trailing dots in domain comparison: */
753     while (d_len > 0 && This->name[d_len - 1] == '.') {
754         --d_len;
755     }
756     while (h_len > 0 && host[h_len - 1] == '.') {
757         --h_len;
758     }
759     return h_len > d_len
760         && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
761 }
762
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)
765 {
766     struct apr_sockaddr_t *addr;
767     char *host = This->name;
768     int i;
769
770     /* Host names must not start with a '.' */
771     if (host[0] == '.') {
772         return 0;
773     }
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);
776
777     if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
778         return 0;
779     }
780
781     This->hostaddr = addr;
782
783     /* Strip trailing dots */
784     for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
785         host[i] = '\0';
786     }
787
788     This->matcher = proxy_match_hostname;
789     return 1;
790 }
791
792 /* Return TRUE if host "host" is equal to host2 "host2" */
793 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
794 {
795     char *host = This->name;
796     const char *host2 = proxy_get_host_of_request(r);
797     int h2_len;
798     int h1_len;
799
800     if (host == NULL || host2 == NULL) {
801         return 0; /* oops! */
802     }
803
804     h2_len = strlen(host2);
805     h1_len = strlen(host);
806
807 #if 0
808     struct apr_sockaddr_t *addr = *This->hostaddr;
809
810     /* Try to deal with multiple IP addr's for a host */
811     while (addr) {
812         if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
813             return 1;
814         addr = addr->next;
815     }
816 #endif
817
818     /* Ignore trailing dots in host2 comparison: */
819     while (h2_len > 0 && host2[h2_len - 1] == '.') {
820         --h2_len;
821     }
822     while (h1_len > 0 && host[h1_len - 1] == '.') {
823         --h1_len;
824     }
825     return h1_len == h2_len
826         && strncasecmp(host, host2, h1_len) == 0;
827 }
828
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)
831 {
832     This->matcher = proxy_match_word;
833     return 1;
834 }
835
836 /* Return TRUE if string "str2" occurs literally in "str1" */
837 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
838 {
839     const char *host = proxy_get_host_of_request(r);
840     return host != NULL && ap_strstr_c(host, This->name) != NULL;
841 }
842
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)
846 {
847     int j;
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;
863         }
864         while (conf_addr) {
865             uri_addr = src_uri_addr;
866             while (uri_addr) {
867                 char *conf_ip;
868                 char *uri_ip;
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,
873                               uri_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;
879                 }
880                 uri_addr = uri_addr->next;
881             }
882             conf_addr = conf_addr->next;
883         }
884     }
885     return OK;
886 }
887
888 /* set up the minimal filter set */
889 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
890 {
891     ap_add_input_filter("HTTP_IN", NULL, r, c);
892     return OK;
893 }
894
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)
897 {
898     apr_off_t offset = 0;
899     apr_off_t count = 0;
900     char *value = NULL;
901
902     /* get the value to unmerge */
903     const char *initial = apr_table_get(t, key);
904     if (!initial) {
905         return;
906     }
907     value = apr_pstrdup(p, initial);
908
909     /* remove the value from the headers */
910     apr_table_unset(t, key);
911
912     /* find each comma */
913     while (value[count]) {
914         if (value[count] == ',') {
915             value[count] = 0;
916             apr_table_add(t, key, value + offset);
917             offset = count + 1;
918         }
919         count++;
920     }
921     apr_table_add(t, key, value + offset);
922 }
923
924 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
925                               proxy_dir_conf *conf, const char *url)
926 {
927     proxy_req_conf *rconf;
928     struct proxy_alias *ent;
929     int i, l1, l2;
930     char *u;
931
932     /*
933      * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
934      * after the hostname
935      * XXX FIXME: Ensure the /uri component is a case sensitive match
936      */
937     if (r->proxyreq != PROXYREQ_REVERSE) {
938         return url;
939     }
940
941     l1 = strlen(url);
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;
945     }
946     else {
947         ent = (struct proxy_alias *)conf->raliases->elts;
948     }
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;
954         /*
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.
960          */
961         if (ap_proxy_valid_balancer_name((char *)real, 0) &&
962             (balancer = ap_proxy_get_balancer(r->pool, sconf, real, 1))) {
963             int n, l3 = 0;
964             proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
965             const char *urlpart = ap_strchr_c(real, '/');
966             if (urlpart) {
967                 if (!urlpart[1])
968                     urlpart = NULL;
969                 else
970                     l3 = strlen(urlpart);
971             }
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
976              */
977             for (n = 0; n < balancer->workers->nelts; n++) {
978                 l2 = strlen((*worker)->s->name);
979                 if (urlpart) {
980                     /* urlpart (l3) assuredly starts with its own '/' */
981                     if ((*worker)->s->name[l2 - 1] == '/')
982                         --l2;
983                     if (l1 >= l2 + l3
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],
987                                         NULL);
988                         return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
989                     }
990                 }
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);
994                 }
995                 worker++;
996             }
997         }
998         else {
999             const char *part = url;
1000             l2 = strlen(real);
1001             if (real[0] == '/') {
1002                 part = ap_strstr_c(url, "://");
1003                 if (part) {
1004                     part = ap_strchr_c(part+3, '/');
1005                     if (part) {
1006                         l1 = strlen(part);
1007                     }
1008                     else {
1009                         part = url;
1010                     }
1011                 }
1012                 else {
1013                     part = url;
1014                 }
1015             }
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);
1019             }
1020         }
1021     }
1022
1023     return url;
1024 }
1025
1026 /*
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.
1032  */
1033 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1034                               proxy_dir_conf *conf, const char *str)
1035 {
1036     proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1037                                                  &proxy_module);
1038     struct proxy_alias *ent;
1039     size_t len = strlen(str);
1040     const char *newpath = NULL;
1041     const char *newdomain = NULL;
1042     const char *pathp;
1043     const char *domainp;
1044     const char *pathe = NULL;
1045     const char *domaine = NULL;
1046     size_t l1, l2, poffs = 0, doffs = 0;
1047     int i;
1048     int ddiff = 0;
1049     int pdiff = 0;
1050     char *ret;
1051
1052     if (r->proxyreq != PROXYREQ_REVERSE) {
1053         return str;
1054     }
1055
1056    /*
1057     * Find the match and replacement, but save replacing until we've done
1058     * both path and domain so we know the new strlen
1059     */
1060     if ((pathp = apr_strmatch(ap_proxy_strmatch_path, str, len)) != NULL) {
1061         pathp += 5;
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;
1068         }
1069         else {
1070             ent = (struct proxy_alias *)conf->cookie_paths->elts;
1071         }
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;
1077                 break;
1078             }
1079         }
1080     }
1081
1082     if ((domainp = apr_strmatch(ap_proxy_strmatch_domain, str, len)) != NULL) {
1083         domainp += 7;
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;
1090         }
1091         else {
1092             ent = (struct proxy_alias *)conf->cookie_domains->elts;
1093         }
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;
1099                 break;
1100             }
1101         }
1102     }
1103
1104     if (newpath) {
1105         ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1106         l1 = strlen(newpath);
1107         if (newdomain) {
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);
1115             }
1116             else {
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);
1122             }
1123         }
1124         else {
1125             memcpy(ret, str, poffs);
1126             memcpy(ret + poffs, newpath, l1);
1127             strcpy(ret + poffs + l1, pathe);
1128         }
1129     }
1130     else {
1131         if (newdomain) {
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);
1137         }
1138         else {
1139             ret = (char *)str; /* no change */
1140         }
1141     }
1142
1143     return ret;
1144 }
1145
1146 /*
1147  * BALANCER related...
1148  */
1149
1150 /*
1151  * verifies that the balancer name conforms to standards.
1152  */
1153 PROXY_DECLARE(int) ap_proxy_valid_balancer_name(char *name, int i)
1154 {
1155     if (!i)
1156         i = sizeof(BALANCER_PREFIX)-1;
1157     return (!strncasecmp(name, BALANCER_PREFIX, i));
1158 }
1159
1160
1161 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1162                                                       proxy_server_conf *conf,
1163                                                       const char *url,
1164                                                       int care)
1165 {
1166     proxy_balancer *balancer;
1167     char *c, *uri = apr_pstrdup(p, url);
1168     int i;
1169     proxy_hashes hash;
1170
1171     ap_str_tolower(uri);
1172     c = strchr(uri, ':');
1173     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1174         return NULL;
1175     }
1176     /* remove path from uri */
1177     if ((c = strchr(c + 3, '/'))) {
1178         *c = '\0';
1179     }
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) {
1186                 return balancer;
1187             }
1188         }
1189         balancer++;
1190     }
1191     return NULL;
1192 }
1193
1194
1195 PROXY_DECLARE(char *) ap_proxy_update_balancer(apr_pool_t *p,
1196                                                 proxy_balancer *balancer,
1197                                                 const char *url)
1198 {
1199     apr_uri_t puri;
1200     if (apr_uri_parse(p, url, &puri) != APR_SUCCESS) {
1201         return apr_psprintf(p, "unable to parse: %s", url);
1202     }
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);
1206     }
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);
1210     }
1211     return NULL;
1212 }
1213
1214 PROXY_DECLARE(char *) ap_proxy_define_balancer(apr_pool_t *p,
1215                                                proxy_balancer **balancer,
1216                                                proxy_server_conf *conf,
1217                                                const char *url,
1218                                                const char *alias,
1219                                                int do_malloc)
1220 {
1221     char nonce[APR_UUID_FORMATTED_LENGTH + 1];
1222     proxy_balancer_method *lbmethod;
1223     apr_uuid_t uuid;
1224     proxy_balancer_shared *bshared;
1225     char *c, *q, *uri = apr_pstrdup(p, url);
1226     const char *sname;
1227
1228     /* We should never get here without a valid BALANCER_PREFIX... */
1229
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, '/')))
1235         *q = '\0';
1236
1237     ap_str_tolower(uri);
1238     *balancer = apr_array_push(conf->balancers);
1239     memset(*balancer, 0, sizeof(proxy_balancer));
1240
1241     /*
1242      * NOTE: The default method is byrequests, which we assume
1243      * exists!
1244      */
1245     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1246     if (!lbmethod) {
1247         return "Can't find 'byrequests' lb method";
1248     }
1249
1250     (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1251     (*balancer)->gmutex = NULL;
1252     (*balancer)->tmutex = NULL;
1253     (*balancer)->lbmethod = lbmethod;
1254
1255     if (do_malloc)
1256         bshared = ap_malloc(sizeof(proxy_balancer_shared));
1257     else
1258         bshared = apr_palloc(p, sizeof(proxy_balancer_shared));
1259
1260     memset(bshared, 0, sizeof(proxy_balancer_shared));
1261
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);
1266     }
1267     ap_pstr2_alnum(p, bshared->name + sizeof(BALANCER_PREFIX) - 1,
1268                    &sname);
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);
1272     }
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;
1276
1277     /* Retrieve a UUID and store the nonce for the lifetime of
1278      * the process. */
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);
1283     }
1284
1285     (*balancer)->s = bshared;
1286     (*balancer)->sconf = conf;
1287
1288     return ap_proxy_update_balancer(p, *balancer, alias);
1289 }
1290
1291 /*
1292  * Create an already defined balancer and free up memory.
1293  */
1294 PROXY_DECLARE(apr_status_t) ap_proxy_share_balancer(proxy_balancer *balancer,
1295                                                     proxy_balancer_shared *shm,
1296                                                     int i)
1297 {
1298     proxy_balancer_method *lbmethod;
1299     if (!shm || !balancer->s)
1300         return APR_EINVAL;
1301
1302     memcpy(shm, balancer->s, sizeof(proxy_balancer_shared));
1303     if (balancer->s->was_malloced)
1304         free(balancer->s);
1305     balancer->s = shm;
1306     balancer->s->index = i;
1307     /* the below should always succeed */
1308     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, balancer->s->lbpname, "0");
1309     if (lbmethod)
1310         balancer->lbmethod = lbmethod;
1311     return APR_SUCCESS;
1312 }
1313
1314 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_balancer(proxy_balancer *balancer, server_rec *s, apr_pool_t *p)
1315 {
1316     apr_status_t rv = APR_SUCCESS;
1317     ap_slotmem_provider_t *storage = balancer->storage;
1318     apr_size_t size;
1319     unsigned int num;
1320
1321     if (!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;
1325     }
1326     /*
1327      * for each balancer we need to init the global
1328      * mutex and then attach to the shared worker shm
1329      */
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;
1334     }
1335
1336     /* Re-open the mutex for the child. */
1337     rv = apr_global_mutex_child_init(&(balancer->gmutex),
1338                                      apr_global_mutex_lockfile(balancer->gmutex),
1339                                      p);
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",
1343                      balancer->s->name);
1344         return rv;
1345     }
1346
1347     /* now attach */
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;
1352     }
1353     if (balancer->lbmethod && balancer->lbmethod->reset)
1354         balancer->lbmethod->reset(balancer, s);
1355
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");
1361             return rv;
1362         }
1363     }
1364     return APR_SUCCESS;
1365 }
1366
1367 /*
1368  * CONNECTION related...
1369  */
1370
1371 static apr_status_t conn_pool_cleanup(void *theworker)
1372 {
1373     proxy_worker *worker = (proxy_worker *)theworker;
1374     if (worker->cp->res) {
1375         worker->cp->pool = NULL;
1376     }
1377     return APR_SUCCESS;
1378 }
1379
1380 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1381 {
1382     apr_pool_t *pool;
1383     proxy_conn_pool *cp;
1384
1385     /*
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.
1390      */
1391     apr_pool_create(&pool, p);
1392     apr_pool_tag(pool, "proxy_worker_cp");
1393     /*
1394      * Alloc from the same pool as worker.
1395      * proxy_conn_pool is permanently attached to the worker.
1396      */
1397     cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1398     cp->pool = pool;
1399     worker->cp = cp;
1400 }
1401
1402 static apr_status_t connection_cleanup(void *theconn)
1403 {
1404     proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1405     proxy_worker *worker = conn->worker;
1406
1407     /*
1408      * If the connection pool is NULL the worker
1409      * cleanup has been run. Just return.
1410      */
1411     if (!worker->cp) {
1412         return APR_SUCCESS;
1413     }
1414
1415     if (conn->r) {
1416         apr_pool_destroy(conn->r->pool);
1417         conn->r = NULL;
1418     }
1419
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,
1425                       worker->s->name);
1426         return APR_SUCCESS;
1427     }
1428
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;
1432         apr_pool_clear(p);
1433         conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1434         conn->pool = p;
1435         conn->worker = worker;
1436         apr_pool_create(&(conn->scpool), p);
1437         apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1438     }
1439
1440     if (worker->s->hmax && worker->cp->res) {
1441         conn->inreslist = 1;
1442         apr_reslist_release(worker->cp->res, (void *)conn);
1443     }
1444     else
1445     {
1446         worker->cp->conn = conn;
1447     }
1448
1449     /* Always return the SUCCESS */
1450     return APR_SUCCESS;
1451 }
1452
1453 static void socket_cleanup(proxy_conn_rec *conn)
1454 {
1455     conn->sock = NULL;
1456     conn->connection = NULL;
1457     apr_pool_clear(conn->scpool);
1458 }
1459
1460 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1461                                                             request_rec *r)
1462 {
1463     apr_bucket_brigade *bb;
1464     apr_status_t rv;
1465
1466     /*
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.
1473      */
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,
1478                             HUGE_STRING_LEN);
1479         if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1480             socket_cleanup(conn);
1481         }
1482         if (!APR_BRIGADE_EMPTY(bb)) {
1483             apr_off_t len;
1484
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);
1489         }
1490         apr_brigade_destroy(bb);
1491     }
1492     return APR_SUCCESS;
1493 }
1494
1495 /* reslist constructor */
1496 static apr_status_t connection_constructor(void **resource, void *params,
1497                                            apr_pool_t *pool)
1498 {
1499     apr_pool_t *ctx;
1500     apr_pool_t *scpool;
1501     proxy_conn_rec *conn;
1502     proxy_worker *worker = (proxy_worker *)params;
1503
1504     /*
1505      * Create the subpool for each connection
1506      * This keeps the memory consumption constant
1507      * when disconnecting from backend.
1508      */
1509     apr_pool_create(&ctx, pool);
1510     apr_pool_tag(ctx, "proxy_conn_pool");
1511     /*
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).
1517      */
1518     apr_pool_create(&scpool, ctx);
1519     apr_pool_tag(scpool, "proxy_conn_scpool");
1520     conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1521
1522     conn->pool   = ctx;
1523     conn->scpool = scpool;
1524     conn->worker = worker;
1525     conn->inreslist = 1;
1526     *resource = conn;
1527
1528     return APR_SUCCESS;
1529 }
1530
1531 /* reslist destructor */
1532 static apr_status_t connection_destructor(void *resource, void *params,
1533                                           apr_pool_t *pool)
1534 {
1535     proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1536
1537     /* Destroy the pool only if not called from reslist_destroy */
1538     if (conn->worker->cp->pool) {
1539         apr_pool_destroy(conn->pool);
1540     }
1541
1542     return APR_SUCCESS;
1543 }
1544
1545 /*
1546  * WORKER related...
1547  */
1548
1549 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1550                                                   proxy_balancer *balancer,
1551                                                   proxy_server_conf *conf,
1552                                                   const char *url)
1553 {
1554     proxy_worker *worker;
1555     proxy_worker *max_worker = NULL;
1556     int max_match = 0;
1557     int url_length;
1558     int min_match;
1559     int worker_name_length;
1560     const char *c;
1561     char *url_copy;
1562     int i;
1563
1564     c = ap_strchr_c(url, ':');
1565     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1566         return NULL;
1567     }
1568
1569     url_length = strlen(url);
1570     url_copy = apr_pstrmemdup(p, url, url_length);
1571
1572     /*
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.
1577      */
1578     c = ap_strchr_c(c+3, '/');
1579     if (c) {
1580         char *pathstart;
1581         pathstart = url_copy + (c - url);
1582         *pathstart = '\0';
1583         ap_str_tolower(url_copy);
1584         min_match = strlen(url_copy);
1585         *pathstart = '/';
1586     }
1587     else {
1588         ap_str_tolower(url_copy);
1589         min_match = strlen(url_copy);
1590     }
1591     /*
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.
1596      */
1597
1598     if (balancer) {
1599         proxy_worker **workers = (proxy_worker **)balancer->workers->elts;
1600         for (i = 0; i < balancer->workers->nelts; i++, workers++) {
1601             worker = *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;
1608             }
1609
1610         }
1611     } else {
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;
1620             }
1621         }
1622     }
1623
1624     return max_worker;
1625 }
1626
1627 /*
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.
1633  */
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,
1638                                              const char *url,
1639                                              int do_malloc)
1640 {
1641     int rv;
1642     apr_uri_t uri;
1643     proxy_worker_shared *wshared;
1644     char *ptr;
1645
1646     rv = apr_uri_parse(p, url, &uri);
1647
1648     if (rv != APR_SUCCESS) {
1649         return "Unable to parse URL";
1650     }
1651     if (!uri.hostname || !uri.scheme) {
1652         return "URL must be absolute!";
1653     }
1654
1655     ap_str_tolower(uri.hostname);
1656     ap_str_tolower(uri.scheme);
1657     /*
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:
1661      *
1662      *      ProxyPass / http://www.example.com
1663      *
1664      * in which case the worker goes in the conf slot.
1665      */
1666     if (balancer) {
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();
1674     } else if (conf) {
1675         *worker = apr_array_push(conf->workers);
1676     } else {
1677         /* we need to allocate space here */
1678         *worker = apr_palloc(p, sizeof(proxy_worker));
1679     }
1680
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. */
1685     if (do_malloc)
1686         wshared = ap_malloc(sizeof(proxy_worker_shared));  /* will be freed ap_proxy_share_worker */
1687     else
1688         wshared = apr_palloc(p, sizeof(proxy_worker_shared));
1689
1690     memset(wshared, 0, sizeof(proxy_worker_shared));
1691
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);
1695     }
1696     if (PROXY_STRNCPY(wshared->scheme, uri.scheme) != APR_SUCCESS) {
1697         return apr_psprintf(p, "worker scheme (%s) too long", uri.scheme);
1698     }
1699     if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) {
1700         return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
1701     }
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;
1707     wshared->smax = -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);
1711
1712     (*worker)->hash = wshared->hash;
1713     (*worker)->context = NULL;
1714     (*worker)->cp = NULL;
1715     (*worker)->balancer = balancer;
1716     (*worker)->s = wshared;
1717
1718     return NULL;
1719 }
1720
1721 /*
1722  * Create an already defined worker and free up memory
1723  */
1724 PROXY_DECLARE(apr_status_t) ap_proxy_share_worker(proxy_worker *worker, proxy_worker_shared *shm,
1725                                                   int i)
1726 {
1727     if (!shm || !worker->s)
1728         return APR_EINVAL;
1729
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 */
1733     worker->s = shm;
1734     worker->s->index = i;
1735     return APR_SUCCESS;
1736 }
1737
1738 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1739 {
1740     apr_status_t rv = APR_SUCCESS;
1741     int mpm_threads;
1742
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);
1747     }
1748     else {
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);
1754         }
1755         /* By default address is reusable unless DisableReuse is set */
1756         if (worker->s->disablereuse) {
1757             worker->s->is_address_reusable = 0;
1758         }
1759         else {
1760             worker->s->is_address_reusable = 1;
1761         }
1762
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;
1768             }
1769             if (worker->s->smax == -1 || worker->s->smax > worker->s->hmax) {
1770                 worker->s->smax = worker->s->hmax;
1771             }
1772             /* Set min to be lower then smax */
1773             if (worker->s->min > worker->s->smax) {
1774                 worker->s->min = worker->s->smax;
1775             }
1776         }
1777         else {
1778             /* This will supress the apr_reslist creation */
1779             worker->s->min = worker->s->smax = worker->s->hmax = 0;
1780         }
1781     }
1782
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);
1787     }
1788     else {
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");
1797                 return rv;
1798             }
1799         }
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;
1806         }
1807
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);
1814
1815             apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1816                                       conn_pool_cleanup,
1817                                       apr_pool_cleanup_null);
1818
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);
1823
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);
1827             }
1828
1829         }
1830         else {
1831             void *conn;
1832
1833             rv = connection_constructor(&conn, worker, worker->cp->pool);
1834             worker->cp->conn = conn;
1835
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);
1839         }
1840     }
1841     if (rv == APR_SUCCESS) {
1842         worker->s->status |= (PROXY_WORKER_INITIALIZED);
1843         worker->local_status |= (PROXY_WORKER_INITIALIZED);
1844     }
1845     return rv;
1846 }
1847
1848 static int ap_proxy_retry_worker(const char *proxy_function, proxy_worker *worker,
1849         server_rec *s)
1850 {
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);
1858             return OK;
1859         }
1860         else {
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);
1864             return DECLINED;
1865         }
1866     }
1867     else {
1868         return OK;
1869     }
1870 }
1871
1872 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1873                                         proxy_balancer **balancer,
1874                                         request_rec *r,
1875                                         proxy_server_conf *conf, char **url)
1876 {
1877     int access_status;
1878
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);
1882         if (*worker) {
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);
1886
1887             *balancer = NULL;
1888             access_status = OK;
1889         }
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);
1894                 *balancer = NULL;
1895                 *worker = conf->forward;
1896                 access_status = OK;
1897                 /*
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.
1901                  */
1902                 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
1903             }
1904         }
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);
1909                 *balancer = NULL;
1910                 *worker = conf->reverse;
1911                 access_status = OK;
1912                 /*
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.
1916                  */
1917                 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
1918             }
1919         }
1920     }
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;
1926     }
1927     return access_status;
1928 }
1929
1930 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1931                                          proxy_balancer *balancer,
1932                                          request_rec *r,
1933                                          proxy_server_conf *conf)
1934 {
1935     int access_status = OK;
1936     if (balancer) {
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 */
1941         }
1942     }
1943
1944     return access_status;
1945 }
1946
1947 /* DEPRECATED */
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,
1953                                                request_rec *r)
1954 {
1955     apr_status_t rv;
1956     int connected = 0;
1957     int loglevel;
1958
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);
1966             /*
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
1970              */
1971             backend_addr = backend_addr->next;
1972             continue;
1973         }
1974
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");
1981         }
1982
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): "
1987                           "Failed to set");
1988         }
1989
1990         /* Set a timeout on the socket */
1991         if (conf->timeout_set) {
1992             apr_socket_timeout_set(*newsock, conf->timeout);
1993         }
1994         else {
1995             apr_socket_timeout_set(*newsock, r->server->timeout);
1996         }
1997
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);
2001
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",
2007                               proxy_function);
2008             }
2009         }
2010
2011         /* make the connection out of the socket */
2012         rv = apr_socket_connect(*newsock, backend_addr);
2013
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;
2022             continue;
2023         }
2024         connected = 1;
2025     }
2026     return connected ? 0 : 1;
2027 }
2028
2029 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
2030                                                proxy_conn_rec **conn,
2031                                                proxy_worker *worker,
2032                                                server_rec *s)
2033 {
2034     apr_status_t rv;
2035
2036     if (!PROXY_WORKER_IS_USABLE(worker)) {
2037         /* Retry the worker */
2038         ap_proxy_retry_worker(proxy_function, worker, s);
2039
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;
2045         }
2046     }
2047
2048     if (worker->s->hmax && worker->cp->res) {
2049         rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2050     }
2051     else {
2052         /* create the new connection if the previous was destroyed */
2053         if (!worker->cp->conn) {
2054             connection_constructor((void **)conn, worker, worker->cp->pool);
2055         }
2056         else {
2057             *conn = worker->cp->conn;
2058             worker->cp->conn = NULL;
2059         }
2060         rv = APR_SUCCESS;
2061     }
2062
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;
2068     }
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);
2072
2073     (*conn)->worker = worker;
2074     (*conn)->close  = 0;
2075     (*conn)->inreslist = 0;
2076
2077     return OK;
2078 }
2079
2080 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2081                                                proxy_conn_rec *conn,
2082                                                server_rec *s)
2083 {
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);
2088
2089     return OK;
2090 }
2091
2092 PROXY_DECLARE(int)
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,
2097                               apr_uri_t *uri,
2098                               char **url,
2099                               const char *proxyname,
2100                               apr_port_t proxyport,
2101                               char *server_portstr,
2102                               int server_portstr_size)
2103 {
2104     int server_port;
2105     apr_status_t err = APR_SUCCESS;
2106     apr_status_t uerr = APR_SUCCESS;
2107
2108     /*
2109      * Break up the URL to determine the host to connect to
2110      */
2111
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,
2116                                          NULL));
2117     }
2118     if (!uri->port) {
2119         uri->port = apr_uri_port_of_scheme(uri->scheme);
2120     }
2121
2122     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00944)
2123                  "connecting %s to %s:%d", *url, uri->hostname, uri->port);
2124
2125     /*
2126      * allocate these out of the specified connection pool
2127      * The scheme handler decides if this is permanent or
2128      * short living pool.
2129      */
2130     /* are we connecting directly, or via a proxy? */
2131     if (!proxyname) {
2132         *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2133                            uri->query ? uri->query : "",
2134                            uri->fragment ? "#" : "",
2135                            uri->fragment ? uri->fragment : "", NULL);
2136     }
2137     /*
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.
2143      *
2144      * TODO: Handle this much better...
2145      */
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) ) ) {
2151         if (proxyname) {
2152             conn->hostname = apr_pstrdup(conn->pool, proxyname);
2153             conn->port = proxyport;
2154             /*
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.
2159              */
2160             if (conn->is_ssl) {
2161                 const char *proxy_auth;
2162
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.
2173                  */
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);
2180                 }
2181             }
2182         }
2183         else {
2184             conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2185             conn->port = uri->port;
2186         }
2187         socket_cleanup(conn);
2188         err = apr_sockaddr_info_get(&(conn->addr),
2189                                     conn->hostname, APR_UNSPEC,
2190                                     conn->port, 0,
2191                                     conn->pool);
2192     }
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;
2197         }
2198
2199         /*
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.
2204          */
2205         err = apr_sockaddr_info_get(&(worker->cp->addr),
2206                                     conn->hostname, APR_UNSPEC,
2207                                     conn->port, 0,
2208                                     worker->cp->pool);
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");
2212         }
2213     }
2214     else {
2215         conn->addr = worker->cp->addr;
2216     }
2217     /* Close a possible existing socket if we are told to do so */
2218     if (conn->close) {
2219         socket_cleanup(conn);
2220         conn->close = 0;
2221     }
2222
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));
2227     }
2228
2229     /* Get the server port for the Via headers */
2230     {
2231         server_port = ap_get_server_port(r);
2232         if (ap_is_default_port(server_port, r)) {
2233             strcpy(server_portstr,"");
2234         }
2235         else {
2236             apr_snprintf(server_portstr, server_portstr_size, ":%d",
2237                          server_port);
2238         }
2239     }
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");
2244     }
2245     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00947)
2246                  "connected %s to %s:%d", *url, conn->hostname, conn->port);
2247     return OK;
2248 }
2249
2250 #define USE_ALTERNATE_IS_CONNECTED 1
2251
2252 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2253 #define APR_MSG_PEEK MSG_PEEK
2254 #endif
2255
2256 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2257 static int is_socket_connected(apr_socket_t *socket)
2258 {
2259     apr_pollfd_t pfds[1];
2260     apr_status_t status;
2261     apr_int32_t  nfds;
2262
2263     pfds[0].reqevents = APR_POLLIN;
2264     pfds[0].desc_type = APR_POLL_SOCKET;
2265     pfds[0].desc.s = socket;
2266
2267     do {
2268         status = apr_poll(&pfds[0], 1, &nfds, 0);
2269     } while (APR_STATUS_IS_EINTR(status));
2270
2271     if (status == APR_SUCCESS && nfds == 1 &&
2272         pfds[0].rtnevents == APR_POLLIN) {
2273         apr_sockaddr_t unused;
2274         apr_size_t len = 1;
2275         char buf[1];
2276         /* The socket might be closed in which case
2277          * the poll will return POLLIN.
2278          * If there is no data available the socket
2279          * is closed.
2280          */
2281         status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2282                                      &buf[0], &len);
2283         if (status == APR_SUCCESS && len)
2284             return 1;
2285         else
2286             return 0;
2287     }
2288     else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2289         return 1;
2290     }
2291     return 0;
2292
2293 }
2294 #else
2295 static int is_socket_connected(apr_socket_t *sock)
2296
2297 {
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;
2302
2303     /* save timeout */
2304     apr_socket_timeout_get(sock, &current_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)) {
2312         return 0;
2313     }
2314     else {
2315         return 1;
2316     }
2317 }
2318 #endif /* USE_ALTERNATE_IS_CONNECTED */
2319
2320
2321 /*
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".
2325  */
2326 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2327                                       server_rec *s)
2328 {
2329     int status;
2330     apr_size_t nbytes;
2331     apr_size_t left;
2332     int complete = 0;
2333     char buffer[HUGE_STRING_LEN];
2334     char drain_buffer[HUGE_STRING_LEN];
2335     forward_info *forward = (forward_info *)backend->forward;
2336     int len = 0;
2337
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);
2352     }
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);
2358
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 */
2362     do {
2363         nbytes = left;
2364         status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2365         len += nbytes;
2366         left -= nbytes;
2367         buffer[len] = '\0';
2368         if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2369             complete = 1;
2370             break;
2371         }
2372     } while (status == APR_SUCCESS && left > 0);
2373     /* Drain what's left */
2374     if (!complete) {
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) {
2381                 break;
2382             }
2383         }
2384     }
2385
2386     /* Check for HTTP_OK response status */
2387     if (status == APR_SUCCESS) {
2388         int major, minor;
2389         /* Only scan for three character status code */
2390         char code_str[4];
2391
2392         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00949)
2393                      "send_http_connect: response from the forward proxy: %s",
2394                      buffer);
2395
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;
2401             }
2402             else {
2403                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00950)
2404                              "send_http_connect: the forward proxy returned code is '%s'",
2405                              code_str);
2406             status = APR_INCOMPLETE;
2407             }
2408         }
2409     }
2410
2411     return(status);
2412 }
2413
2414
2415 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2416                                             proxy_conn_rec *conn,
2417                                             proxy_worker *worker,
2418                                             server_rec *s)
2419 {
2420     apr_status_t rv;
2421     int connected = 0;
2422     int loglevel;
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);
2430
2431     if (conn->sock) {
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.",
2436                          proxy_function);
2437         }
2438     }
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",
2446                          proxy_function,
2447                          backend_addr->family,
2448                          worker->s->hostname);
2449             /*
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
2453              */
2454             backend_addr = backend_addr->next;
2455             continue;
2456         }
2457         conn->connection = NULL;
2458
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");
2465         }
2466
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): "
2471                           "Failed to set");
2472         }
2473
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);
2477         }
2478         else if (worker->s->timeout_set) {
2479             apr_socket_timeout_set(newsock, worker->s->timeout);
2480         }
2481         else if (conf->timeout_set) {
2482             apr_socket_timeout_set(newsock, conf->timeout);
2483         }
2484         else {
2485              apr_socket_timeout_set(newsock, s->timeout);
2486         }
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"
2493                              " Keepalive");
2494             }
2495         }
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);
2499
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",
2508                     proxy_function);
2509             }
2510         }
2511
2512         /* make the connection out of the socket */
2513         rv = apr_socket_connect(newsock, backend_addr);
2514
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",
2521                          proxy_function,
2522                          backend_addr,
2523                          worker->s->hostname);
2524             backend_addr = backend_addr->next;
2525             continue;
2526         }
2527
2528         /* Set a timeout on the socket */
2529         if (worker->s->timeout_set) {
2530             apr_socket_timeout_set(newsock, worker->s->timeout);
2531         }
2532         else if (conf->timeout_set) {
2533             apr_socket_timeout_set(newsock, conf->timeout);
2534         }
2535         else {
2536              apr_socket_timeout_set(newsock, s->timeout);
2537         }
2538
2539         conn->sock = newsock;
2540
2541         if (conn->forward) {
2542             forward_info *forward = (forward_info *)conn->forward;
2543             /*
2544              * For HTTP CONNECT we need to prepend CONNECT request before
2545              * sending our actual HTTPS requests.
2546              */
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) {
2551                     conn->sock = NULL;
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",
2557                                  proxy_function,
2558                                  forward->target_host, forward->target_port,
2559                                  backend_addr, worker->s->hostname);
2560                     backend_addr = backend_addr->next;
2561                     continue;
2562                 }
2563             }
2564         }
2565
2566         connected    = 1;
2567     }
2568     /*
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
2573      */
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 %"
2580             APR_TIME_T_FMT "s",
2581             worker->s->hostname, apr_time_sec(worker->s->retry));
2582     }
2583     else {
2584         if (worker->s->retries) {
2585             /*
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
2589              */
2590         }
2591         worker->s->error_time = 0;
2592         worker->s->retries = 0;
2593     }
2594     return connected ? OK : DECLINED;
2595 }
2596
2597 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2598                                               proxy_conn_rec *conn,
2599                                               conn_rec *c,
2600                                               server_rec *s)
2601 {
2602     apr_sockaddr_t *backend_addr = conn->addr;
2603     int rc;
2604     apr_interval_time_t current_timeout;
2605     apr_bucket_alloc_t *bucket_alloc;
2606
2607     if (conn->connection) {
2608         return OK;
2609     }
2610
2611     bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2612     /*
2613      * The socket is now open, create a new backend server connection
2614      */
2615     conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2616                                                 0, NULL,
2617                                                 bucket_alloc);
2618
2619     if (!conn->connection) {
2620         /*
2621          * the peer reset the connection already; ap_run_create_connection()
2622          * closed the socket
2623          */
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;
2631     }
2632
2633     /* For ssl connection to backend */
2634     if (conn->is_ssl) {
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;
2641         }
2642     }
2643     else {
2644         /* TODO: See if this will break FTP */
2645         ap_proxy_ssl_disable(conn->connection);
2646     }
2647
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);
2651
2652     /*
2653      * save the timeout of the socket because core_pre_connection
2654      * will set it to base_server->timeout
2655      * (core TimeOut directive).
2656      */
2657     apr_socket_timeout_get(conn->sock, &current_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);
2665         return rc;
2666     }
2667     apr_socket_timeout_set(conn->sock, current_timeout);
2668
2669     return OK;
2670 }
2671
2672 int ap_proxy_lb_workers(void)
2673 {
2674     /*
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.
2678      */
2679     if (!lb_workers_limit)
2680         lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2681     return lb_workers_limit;
2682 }
2683
2684 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2685                                            apr_bucket_brigade *brigade)
2686 {
2687     apr_bucket *e;
2688     conn_rec *c = r->connection;
2689
2690     r->no_cache = 1;
2691     /*
2692      * If this is a subrequest, then prevent also caching of the main
2693      * request.
2694      */
2695     if (r->main)
2696         r->main->no_cache = 1;
2697     e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2698                                c->bucket_alloc);
2699     APR_BRIGADE_INSERT_TAIL(brigade, e);
2700     e = apr_bucket_eos_create(c->bucket_alloc);
2701     APR_BRIGADE_INSERT_TAIL(brigade, e);
2702 }
2703
2704 /*
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
2709  * collisions.
2710  */
2711 PROXY_DECLARE(unsigned int)
2712 ap_proxy_hashfunc(const char *str, proxy_hash_t method)
2713 {
2714     if (method == PROXY_HASHFUNC_APR) {
2715         apr_ssize_t slen = strlen(str);
2716         return apr_hashfunc_default(str, &slen);
2717     }
2718     else if (method == PROXY_HASHFUNC_FNV) {
2719         /* FNV model */
2720         unsigned int hash;
2721         const unsigned int fnv_prime = 0x811C9DC5;
2722         for (hash = 0; *str; str++) {
2723             hash *= fnv_prime;
2724             hash ^= (*str);
2725         }
2726         return hash;
2727     }
2728     else { /* method == PROXY_HASHFUNC_DEFAULT */
2729         /* SDBM model */
2730         unsigned int hash;
2731         for (hash = 0; *str; str++) {
2732             hash = (*str) + (hash << 6) + (hash << 16) - hash;
2733         }
2734         return hash;
2735     }
2736 }
2737
2738 PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w)
2739 {
2740     unsigned int *status = &w->s->status;
2741     char flag = toupper(c);
2742     struct wstat *pwt = wstat_tbl;
2743     while (pwt->bit) {
2744         if (flag == pwt->flag) {
2745             if (set)
2746                 *status |= pwt->bit;
2747             else
2748                 *status &= ~(pwt->bit);
2749             return APR_SUCCESS;
2750         }
2751         pwt++;
2752     }
2753     return APR_EINVAL;
2754 }
2755
2756 PROXY_DECLARE(char *) ap_proxy_parse_wstatus(apr_pool_t *p, proxy_worker *w)
2757 {
2758     char *ret = "";
2759     unsigned int status = w->s->status;
2760     struct wstat *pwt = wstat_tbl;
2761     while (pwt->bit) {
2762         if (status & pwt->bit)
2763             ret = apr_pstrcat(p, ret, pwt->name, NULL);
2764         pwt++;
2765     }
2766     if (PROXY_WORKER_IS_USABLE(w))
2767         ret = apr_pstrcat(p, ret, "Ok ", NULL);
2768     return ret;
2769 }
2770
2771 PROXY_DECLARE(apr_status_t) ap_proxy_sync_balancer(proxy_balancer *b, server_rec *s,
2772                                                     proxy_server_conf *conf)
2773 {
2774     proxy_worker **workers;
2775     int i;
2776     int index;
2777     proxy_worker_shared *shm;
2778     proxy_balancer_method *lbmethod;
2779     ap_slotmem_provider_t *storage = b->storage;
2780
2781     if (b->s->wupdated <= b->wupdated)
2782         return APR_SUCCESS;
2783     /* balancer sync */
2784     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, b->s->lbpname, "0");
2785     if (lbmethod) {
2786         b->lbmethod = lbmethod;
2787     }
2788     /* worker sync */
2789
2790     /*
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
2795      * which is int.
2796      */
2797     for (index = 0; index < b->max_workers; index++) {
2798         int found;
2799         apr_status_t rv;
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;
2803         }
2804         /* account for possible "holes" in the slotmem
2805          * (eg: slots 0-2 are used, but 3 isn't, but 4-5 is)
2806          */
2807         if (!shm->hash.def || !shm->hash.fnv)
2808             continue;
2809         found = 0;
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) {
2814                 found = 1;
2815                 break;
2816             }
2817         }
2818         if (!found) {
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");
2830                 return rv;
2831             }
2832         }
2833     }
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;
2838     }
2839     b->wupdated = b->s->wupdated;
2840     return APR_SUCCESS;
2841 }
2842
2843 void proxy_util_register_hooks(apr_pool_t *p)
2844 {
2845     APR_REGISTER_OPTIONAL_FN(ap_proxy_retry_worker);
2846 }