]> granicus.if.org Git - apache/blob - modules/proxy/proxy_util.c
d8c45e5210bdfea79956beec2b143661910133f6
[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
24 #if APR_HAVE_UNISTD_H
25 #include <unistd.h>         /* for getpid() */
26 #endif
27
28 #if (APR_MAJOR_VERSION < 1)
29 #undef apr_socket_create
30 #define apr_socket_create apr_socket_create_ex
31 #endif
32
33 APLOG_USE_MODULE(proxy);
34
35 /*
36  * Opaque structure containing target server info when
37  * using a forward proxy.
38  * Up to now only used in combination with HTTP CONNECT.
39  */
40 typedef struct {
41     int          use_http_connect; /* Use SSL Tunneling via HTTP CONNECT */
42     const char   *target_host;     /* Target hostname */
43     apr_port_t   target_port;      /* Target port */
44     const char   *proxy_auth;      /* Proxy authorization */
45 } forward_info;
46
47 /* Keep synced with mod_proxy.h! */
48 static struct wstat {
49     unsigned int bit;
50     char flag;
51     const char *name;
52 } wstat_tbl[] = {
53     {PROXY_WORKER_INITIALIZED,   PROXY_WORKER_INITIALIZED_FLAG,   "Init "},
54     {PROXY_WORKER_IGNORE_ERRORS, PROXY_WORKER_IGNORE_ERRORS_FLAG, "Ign "},
55     {PROXY_WORKER_DRAIN,         PROXY_WORKER_DRAIN_FLAG,         "Drn "},
56     {PROXY_WORKER_IN_SHUTDOWN,   PROXY_WORKER_IN_SHUTDOWN_FLAG,   "Shut "},
57     {PROXY_WORKER_DISABLED,      PROXY_WORKER_DISABLED_FLAG,      "Dis "},
58     {PROXY_WORKER_STOPPED,       PROXY_WORKER_STOPPED_FLAG,       "Stop "},
59     {PROXY_WORKER_IN_ERROR,      PROXY_WORKER_IN_ERROR_FLAG,      "Err "},
60     {PROXY_WORKER_HOT_STANDBY,   PROXY_WORKER_HOT_STANDBY_FLAG,   "Stby "},
61     {PROXY_WORKER_FREE,          PROXY_WORKER_FREE_FLAG,          "Free "},
62     {0x0, '\0', NULL}
63 };
64
65 /* Global balancer counter */
66 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
67 static int lb_workers_limit = 0;
68 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_path;
69 const apr_strmatch_pattern PROXY_DECLARE_DATA *ap_proxy_strmatch_domain;
70
71 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
72 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
73 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
74 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
75
76 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
77                                    (request_rec *r, request_rec *pr), (r, pr),
78                                    OK, DECLINED)
79
80 PROXY_DECLARE(apr_status_t) ap_proxy_strncpy(char *dst, const char *src, size_t dlen)
81 {
82     if ((strlen(src)+1) > dlen) {
83         /* APR_ENOSPACE would be better */
84         return APR_EGENERAL;
85     }
86     else {
87         apr_cpystrn(dst, src, dlen);
88     }
89     return APR_SUCCESS;
90 }
91
92 /* already called in the knowledge that the characters are hex digits */
93 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
94 {
95     int i;
96
97 #if !APR_CHARSET_EBCDIC
98     int ch = x[0];
99
100     if (apr_isdigit(ch)) {
101         i = ch - '0';
102     }
103     else if (apr_isupper(ch)) {
104         i = ch - ('A' - 10);
105     }
106     else {
107         i = ch - ('a' - 10);
108     }
109     i <<= 4;
110
111     ch = x[1];
112     if (apr_isdigit(ch)) {
113         i += ch - '0';
114     }
115     else if (apr_isupper(ch)) {
116         i += ch - ('A' - 10);
117     }
118     else {
119         i += ch - ('a' - 10);
120     }
121     return i;
122 #else /*APR_CHARSET_EBCDIC*/
123     /*
124      * we assume that the hex value refers to an ASCII character
125      * so convert to EBCDIC so that it makes sense locally;
126      *
127      * example:
128      *
129      * client specifies %20 in URL to refer to a space char;
130      * at this point we're called with EBCDIC "20"; after turning
131      * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
132      * represents an ASCII char and convert 0x20 to EBCDIC, yielding
133      * 0x40
134      */
135     char buf[1];
136
137     if (1 == sscanf(x, "%2x", &i)) {
138         buf[0] = i & 0xFF;
139         ap_xlate_proto_from_ascii(buf, 1);
140         return buf[0];
141     }
142     else {
143         return 0;
144     }
145 #endif /*APR_CHARSET_EBCDIC*/
146 }
147
148 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
149 {
150 #if !APR_CHARSET_EBCDIC
151     int i;
152
153     x[0] = '%';
154     i = (ch & 0xF0) >> 4;
155     if (i >= 10) {
156         x[1] = ('A' - 10) + i;
157     }
158     else {
159         x[1] = '0' + i;
160     }
161
162     i = ch & 0x0F;
163     if (i >= 10) {
164         x[2] = ('A' - 10) + i;
165     }
166     else {
167         x[2] = '0' + i;
168     }
169 #else /*APR_CHARSET_EBCDIC*/
170     static const char ntoa[] = { "0123456789ABCDEF" };
171     char buf[1];
172
173     ch &= 0xFF;
174
175     buf[0] = ch;
176     ap_xlate_proto_to_ascii(buf, 1);
177
178     x[0] = '%';
179     x[1] = ntoa[(buf[0] >> 4) & 0x0F];
180     x[2] = ntoa[buf[0] & 0x0F];
181     x[3] = '\0';
182 #endif /*APR_CHARSET_EBCDIC*/
183 }
184
185 /*
186  * canonicalise a URL-encoded string
187  */
188
189 /*
190  * Convert a URL-encoded string to canonical form.
191  * It decodes characters which need not be encoded,
192  * and encodes those which must be encoded, and does not touch
193  * those which must not be touched.
194  */
195 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
196                                        enum enctype t, int forcedec,
197                                        int proxyreq)
198 {
199     int i, j, ch;
200     char *y;
201     char *allowed;  /* characters which should not be encoded */
202     char *reserved; /* characters which much not be en/de-coded */
203
204 /*
205  * N.B. in addition to :@&=, this allows ';' in an http path
206  * and '?' in an ftp path -- this may be revised
207  *
208  * Also, it makes a '+' character in a search string reserved, as
209  * it may be form-encoded. (Although RFC 1738 doesn't allow this -
210  * it only permits ; / ? : @ = & as reserved chars.)
211  */
212     if (t == enc_path) {
213         allowed = "~$-_.+!*'(),;:@&=";
214     }
215     else if (t == enc_search) {
216         allowed = "$-_.!*'(),;:@&=";
217     }
218     else if (t == enc_user) {
219         allowed = "$-_.+!*'(),;@&=";
220     }
221     else if (t == enc_fpath) {
222         allowed = "$-_.+!*'(),?:@&=";
223     }
224     else {            /* if (t == enc_parm) */
225         allowed = "$-_.+!*'(),?/:@&=";
226     }
227
228     if (t == enc_path) {
229         reserved = "/";
230     }
231     else if (t == enc_search) {
232         reserved = "+";
233     }
234     else {
235         reserved = "";
236     }
237
238     y = apr_palloc(p, 3 * len + 1);
239
240     for (i = 0, j = 0; i < len; i++, j++) {
241 /* always handle '/' first */
242         ch = x[i];
243         if (strchr(reserved, ch)) {
244             y[j] = ch;
245             continue;
246         }
247 /*
248  * decode it if not already done. do not decode reverse proxied URLs
249  * unless specifically forced
250  */
251         if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
252             if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
253                 return NULL;
254             }
255             ch = ap_proxy_hex2c(&x[i + 1]);
256             i += 2;
257             if (ch != 0 && strchr(reserved, ch)) {  /* keep it encoded */
258                 ap_proxy_c2hex(ch, &y[j]);
259                 j += 2;
260                 continue;
261             }
262         }
263 /* recode it, if necessary */
264         if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
265             ap_proxy_c2hex(ch, &y[j]);
266             j += 2;
267         }
268         else {
269             y[j] = ch;
270         }
271     }
272     y[j] = '\0';
273     return y;
274 }
275
276 /*
277  * Parses network-location.
278  *    urlp           on input the URL; on output the path, after the leading /
279  *    user           NULL if no user/password permitted
280  *    password       holder for password
281  *    host           holder for host
282  *    port           port number; only set if one is supplied.
283  *
284  * Returns an error string.
285  */
286 PROXY_DECLARE(char *)
287      ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
288             char **passwordp, char **hostp, apr_port_t *port)
289 {
290     char *addr, *scope_id, *strp, *host, *url = *urlp;
291     char *user = NULL, *password = NULL;
292     apr_port_t tmp_port;
293     apr_status_t rv;
294
295     if (url[0] != '/' || url[1] != '/') {
296         return "Malformed URL";
297     }
298     host = url + 2;
299     url = strchr(host, '/');
300     if (url == NULL) {
301         url = "";
302     }
303     else {
304         *(url++) = '\0';    /* skip seperating '/' */
305     }
306
307     /* find _last_ '@' since it might occur in user/password part */
308     strp = strrchr(host, '@');
309
310     if (strp != NULL) {
311         *strp = '\0';
312         user = host;
313         host = strp + 1;
314
315 /* find password */
316         strp = strchr(user, ':');
317         if (strp != NULL) {
318             *strp = '\0';
319             password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
320             if (password == NULL) {
321                 return "Bad %-escape in URL (password)";
322             }
323         }
324
325         user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
326         if (user == NULL) {
327             return "Bad %-escape in URL (username)";
328         }
329     }
330     if (userp != NULL) {
331         *userp = user;
332     }
333     if (passwordp != NULL) {
334         *passwordp = password;
335     }
336
337     /*
338      * Parse the host string to separate host portion from optional port.
339      * Perform range checking on port.
340      */
341     rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
342     if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
343         return "Invalid host/port";
344     }
345     if (tmp_port != 0) { /* only update caller's port if port was specified */
346         *port = tmp_port;
347     }
348
349     ap_str_tolower(addr); /* DNS names are case-insensitive */
350
351     *urlp = url;
352     *hostp = addr;
353
354     return NULL;
355 }
356
357 /*
358  * If the date is a valid RFC 850 date or asctime() date, then it
359  * is converted to the RFC 1123 format.
360  */
361 PROXY_DECLARE(const char *)
362      ap_proxy_date_canon(apr_pool_t *p, const char *date)
363 {
364     apr_status_t rv;
365     char* ndate;
366
367     apr_time_t time = apr_date_parse_http(date);
368     if (!time) {
369         return date;
370     }
371
372     ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
373     rv = apr_rfc822_date(ndate, time);
374     if (rv != APR_SUCCESS) {
375         return date;
376     }
377
378     return ndate;
379 }
380
381 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
382 {
383     apr_pool_t *pool;
384     request_rec *rp;
385
386     apr_pool_create(&pool, c->pool);
387
388     rp = apr_pcalloc(pool, sizeof(*r));
389
390     rp->pool            = pool;
391     rp->status          = HTTP_OK;
392
393     rp->headers_in      = apr_table_make(pool, 50);
394     rp->subprocess_env  = apr_table_make(pool, 50);
395     rp->headers_out     = apr_table_make(pool, 12);
396     rp->err_headers_out = apr_table_make(pool, 5);
397     rp->notes           = apr_table_make(pool, 5);
398
399     rp->server = r->server;
400     rp->log = r->log;
401     rp->proxyreq = r->proxyreq;
402     rp->request_time = r->request_time;
403     rp->connection      = c;
404     rp->output_filters  = c->output_filters;
405     rp->input_filters   = c->input_filters;
406     rp->proto_output_filters  = c->output_filters;
407     rp->proto_input_filters   = c->input_filters;
408
409     rp->request_config  = ap_create_request_config(pool);
410     proxy_run_create_req(r, rp);
411
412     return rp;
413 }
414
415
416 /*
417  * list is a comma-separated list of case-insensitive tokens, with
418  * optional whitespace around the tokens.
419  * The return returns 1 if the token val is found in the list, or 0
420  * otherwise.
421  */
422 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
423 {
424     int len, i;
425     const char *p;
426
427     len = strlen(val);
428
429     while (list != NULL) {
430         p = ap_strchr_c(list, ',');
431         if (p != NULL) {
432             i = p - list;
433             do {
434                 p++;
435             } while (apr_isspace(*p));
436         }
437         else {
438             i = strlen(list);
439         }
440
441         while (i > 0 && apr_isspace(list[i - 1])) {
442             i--;
443         }
444         if (i == len && strncasecmp(list, val, len) == 0) {
445             return 1;
446         }
447         list = p;
448     }
449     return 0;
450 }
451
452 /*
453  * Converts 8 hex digits to a time integer
454  */
455 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
456 {
457     int i, ch;
458     unsigned int j;
459
460     for (i = 0, j = 0; i < 8; i++) {
461         ch = x[i];
462         j <<= 4;
463         if (apr_isdigit(ch)) {
464             j |= ch - '0';
465         }
466         else if (apr_isupper(ch)) {
467             j |= ch - ('A' - 10);
468         }
469         else {
470             j |= ch - ('a' - 10);
471         }
472     }
473     if (j == 0xffffffff) {
474         return -1;      /* so that it works with 8-byte ints */
475     }
476     else {
477         return j;
478     }
479 }
480
481 /*
482  * Converts a time integer to 8 hex digits
483  */
484 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
485 {
486     int i, ch;
487     unsigned int j = t;
488
489     for (i = 7; i >= 0; i--) {
490         ch = j & 0xF;
491         j >>= 4;
492         if (ch >= 10) {
493             y[i] = ch + ('A' - 10);
494         }
495         else {
496             y[i] = ch + '0';
497         }
498     }
499     y[8] = '\0';
500 }
501
502 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
503 {
504     const char *uri = ap_escape_html(r->pool, r->uri);
505     apr_table_setn(r->notes, "error-notes",
506         apr_pstrcat(r->pool,
507             "The proxy server could not handle the request <em><a href=\"",
508             uri, "\">", ap_escape_html(r->pool, r->method), "&nbsp;", uri,
509             "</a></em>.<p>\n"
510             "Reason: <strong>", ap_escape_html(r->pool, message),
511             "</strong></p>",
512             NULL));
513
514     /* Allow "error-notes" string to be printed by ap_send_error_response() */
515     apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
516
517     r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
518     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s returned by %s", message,
519                   r->uri);
520     return statuscode;
521 }
522
523 static const char *
524      proxy_get_host_of_request(request_rec *r)
525 {
526     char *url, *user = NULL, *password = NULL, *err, *host;
527     apr_port_t port;
528
529     if (r->hostname != NULL) {
530         return r->hostname;
531     }
532
533     /* Set url to the first char after "scheme://" */
534     if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
535         return NULL;
536     }
537
538     url = apr_pstrdup(r->pool, &url[1]);    /* make it point to "//", which is what proxy_canon_netloc expects */
539
540     err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
541
542     if (err != NULL) {
543         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", err);
544     }
545
546     r->hostname = host;
547
548     return host;        /* ought to return the port, too */
549 }
550
551 /* Return TRUE if addr represents an IP address (or an IP network address) */
552 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
553 {
554     const char *addr = This->name;
555     long ip_addr[4];
556     int i, quads;
557     long bits;
558
559     /*
560      * if the address is given with an explicit netmask, use that
561      * Due to a deficiency in apr_inet_addr(), it is impossible to parse
562      * "partial" addresses (with less than 4 quads) correctly, i.e.
563      * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
564      * I therefore have to parse the IP address manually:
565      * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
566      * addr and mask were set by proxy_readmask()
567      * return 1;
568      */
569
570     /*
571      * Parse IP addr manually, optionally allowing
572      * abbreviated net addresses like 192.168.
573      */
574
575     /* Iterate over up to 4 (dotted) quads. */
576     for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
577         char *tmp;
578
579         if (*addr == '/' && quads > 0) {  /* netmask starts here. */
580             break;
581         }
582
583         if (!apr_isdigit(*addr)) {
584             return 0;       /* no digit at start of quad */
585         }
586
587         ip_addr[quads] = strtol(addr, &tmp, 0);
588
589         if (tmp == addr) {  /* expected a digit, found something else */
590             return 0;
591         }
592
593         if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
594             /* invalid octet */
595             return 0;
596         }
597
598         addr = tmp;
599
600         if (*addr == '.' && quads != 3) {
601             ++addr;     /* after the 4th quad, a dot would be illegal */
602         }
603     }
604
605     for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
606         This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
607     }
608
609     if (addr[0] == '/' && apr_isdigit(addr[1])) {   /* net mask follows: */
610         char *tmp;
611
612         ++addr;
613
614         bits = strtol(addr, &tmp, 0);
615
616         if (tmp == addr) {   /* expected a digit, found something else */
617             return 0;
618         }
619
620         addr = tmp;
621
622         if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
623             return 0;
624         }
625
626     }
627     else {
628         /*
629          * Determine (i.e., "guess") netmask by counting the
630          * number of trailing .0's; reduce #quads appropriately
631          * (so that 192.168.0.0 is equivalent to 192.168.)
632          */
633         while (quads > 0 && ip_addr[quads - 1] == 0) {
634             --quads;
635         }
636
637         /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
638         if (quads < 1) {
639             return 0;
640         }
641
642         /* every zero-byte counts as 8 zero-bits */
643         bits = 8 * quads;
644
645         if (bits != 32) {     /* no warning for fully qualified IP address */
646             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
647                          "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
648                          inet_ntoa(This->addr), bits);
649         }
650     }
651
652     This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
653
654     if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
655         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
656                      "Warning: NetMask and IP-Addr disagree in %s/%ld",
657                      inet_ntoa(This->addr), bits);
658         This->addr.s_addr &= This->mask.s_addr;
659         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
660                      "         Set to %s/%ld", inet_ntoa(This->addr), bits);
661     }
662
663     if (*addr == '\0') {
664         This->matcher = proxy_match_ipaddr;
665         return 1;
666     }
667     else {
668         return (*addr == '\0'); /* okay iff we've parsed the whole string */
669     }
670 }
671
672 /* Return TRUE if addr represents an IP address (or an IP network address) */
673 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
674 {
675     int i, ip_addr[4];
676     struct in_addr addr, *ip;
677     const char *host = proxy_get_host_of_request(r);
678
679     if (host == NULL) {   /* oops! */
680        return 0;
681     }
682
683     memset(&addr, '\0', sizeof addr);
684     memset(ip_addr, '\0', sizeof ip_addr);
685
686     if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
687         for (addr.s_addr = 0, i = 0; i < 4; ++i) {
688             /* ap_proxy_is_ipaddr() already confirmed that we have
689              * a valid octet in ip_addr[i]
690              */
691             addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
692         }
693
694         if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
695 #if DEBUGGING
696             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
697                          "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
698             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
699                          "%s/", inet_ntoa(This->addr));
700             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701                          "%s", inet_ntoa(This->mask));
702 #endif
703             return 1;
704         }
705 #if DEBUGGING
706         else {
707             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
708                          "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
709             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
710                          "%s/", inet_ntoa(This->addr));
711             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
712                          "%s", inet_ntoa(This->mask));
713         }
714 #endif
715     }
716     else {
717         struct apr_sockaddr_t *reqaddr;
718
719         if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
720             != APR_SUCCESS) {
721 #if DEBUGGING
722             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
723              "2)IP-NoMatch: hostname=%s msg=Host not found", host);
724 #endif
725             return 0;
726         }
727
728         /* Try to deal with multiple IP addr's for a host */
729         /* FIXME: This needs to be able to deal with IPv6 */
730         while (reqaddr) {
731             ip = (struct in_addr *) reqaddr->ipaddr_ptr;
732             if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
733 #if DEBUGGING
734                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
735                              "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
736                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
737                              "%s/", inet_ntoa(This->addr));
738                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
739                              "%s", inet_ntoa(This->mask));
740 #endif
741                 return 1;
742             }
743 #if DEBUGGING
744             else {
745                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
746                              "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
747                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
748                              "%s/", inet_ntoa(This->addr));
749                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
750                              "%s", inet_ntoa(This->mask));
751             }
752 #endif
753             reqaddr = reqaddr->next;
754         }
755     }
756
757     return 0;
758 }
759
760 /* Return TRUE if addr represents a domain name */
761 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
762 {
763     char *addr = This->name;
764     int i;
765
766     /* Domain name must start with a '.' */
767     if (addr[0] != '.') {
768         return 0;
769     }
770
771     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
772     for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
773         continue;
774     }
775
776 #if 0
777     if (addr[i] == ':') {
778     ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
779                      "@@@@ handle optional port in proxy_is_domainname()");
780     /* @@@@ handle optional port */
781     }
782 #endif
783
784     if (addr[i] != '\0') {
785         return 0;
786     }
787
788     /* Strip trailing dots */
789     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
790         addr[i] = '\0';
791     }
792
793     This->matcher = proxy_match_domainname;
794     return 1;
795 }
796
797 /* Return TRUE if host "host" is in domain "domain" */
798 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
799 {
800     const char *host = proxy_get_host_of_request(r);
801     int d_len = strlen(This->name), h_len;
802
803     if (host == NULL) {      /* some error was logged already */
804         return 0;
805     }
806
807     h_len = strlen(host);
808
809     /* @@@ do this within the setup? */
810     /* Ignore trailing dots in domain comparison: */
811     while (d_len > 0 && This->name[d_len - 1] == '.') {
812         --d_len;
813     }
814     while (h_len > 0 && host[h_len - 1] == '.') {
815         --h_len;
816     }
817     return h_len > d_len
818         && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
819 }
820
821 /* Return TRUE if host represents a host name */
822 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
823 {
824     struct apr_sockaddr_t *addr;
825     char *host = This->name;
826     int i;
827
828     /* Host names must not start with a '.' */
829     if (host[0] == '.') {
830         return 0;
831     }
832     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
833     for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
834
835     if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
836         return 0;
837     }
838
839     This->hostaddr = addr;
840
841     /* Strip trailing dots */
842     for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
843         host[i] = '\0';
844     }
845
846     This->matcher = proxy_match_hostname;
847     return 1;
848 }
849
850 /* Return TRUE if host "host" is equal to host2 "host2" */
851 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
852 {
853     char *host = This->name;
854     const char *host2 = proxy_get_host_of_request(r);
855     int h2_len;
856     int h1_len;
857
858     if (host == NULL || host2 == NULL) {
859         return 0; /* oops! */
860     }
861
862     h2_len = strlen(host2);
863     h1_len = strlen(host);
864
865 #if 0
866     struct apr_sockaddr_t *addr = *This->hostaddr;
867
868     /* Try to deal with multiple IP addr's for a host */
869     while (addr) {
870         if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
871             return 1;
872         addr = addr->next;
873     }
874 #endif
875
876     /* Ignore trailing dots in host2 comparison: */
877     while (h2_len > 0 && host2[h2_len - 1] == '.') {
878         --h2_len;
879     }
880     while (h1_len > 0 && host[h1_len - 1] == '.') {
881         --h1_len;
882     }
883     return h1_len == h2_len
884         && strncasecmp(host, host2, h1_len) == 0;
885 }
886
887 /* Return TRUE if addr is to be matched as a word */
888 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
889 {
890     This->matcher = proxy_match_word;
891     return 1;
892 }
893
894 /* Return TRUE if string "str2" occurs literally in "str1" */
895 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
896 {
897     const char *host = proxy_get_host_of_request(r);
898     return host != NULL && ap_strstr_c(host, This->name) != NULL;
899 }
900
901 /* checks whether a host in uri_addr matches proxyblock */
902 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
903                              apr_sockaddr_t *uri_addr)
904 {
905     int j;
906     apr_sockaddr_t * src_uri_addr = uri_addr;
907     /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
908     for (j = 0; j < conf->noproxies->nelts; j++) {
909         struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
910         struct apr_sockaddr_t *conf_addr = npent[j].addr;
911         uri_addr = src_uri_addr;
912         ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
913                       "checking remote machine [%s] against [%s]",
914                       uri_addr->hostname, npent[j].name);
915         if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
916             || npent[j].name[0] == '*') {
917             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
918                           "connect to remote machine %s blocked: name %s "
919                           "matched", uri_addr->hostname, npent[j].name);
920             return HTTP_FORBIDDEN;
921         }
922         while (conf_addr) {
923             uri_addr = src_uri_addr;
924             while (uri_addr) {
925                 char *conf_ip;
926                 char *uri_ip;
927                 apr_sockaddr_ip_get(&conf_ip, conf_addr);
928                 apr_sockaddr_ip_get(&uri_ip, uri_addr);
929                 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
930                               "ProxyBlock comparing %s and %s", conf_ip,
931                               uri_ip);
932                 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
933                     ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
934                                  "connect to remote machine %s blocked: "
935                                  "IP %s matched", uri_addr->hostname, conf_ip);
936                     return HTTP_FORBIDDEN;
937                 }
938                 uri_addr = uri_addr->next;
939             }
940             conf_addr = conf_addr->next;
941         }
942     }
943     return OK;
944 }
945
946 /* set up the minimal filter set */
947 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
948 {
949     ap_add_input_filter("HTTP_IN", NULL, r, c);
950     return OK;
951 }
952
953 /*
954  * converts a series of buckets into a string
955  * XXX: BillS says this function performs essentially the same function as
956  * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
957  * instead? I think ap_proxy_string_read() will not work properly on non ASCII
958  * (EBCDIC) machines either.
959  */
960 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
961                                                  char *buff, apr_size_t bufflen, int *eos)
962 {
963     apr_bucket *e;
964     apr_status_t rv;
965     char *pos = buff;
966     char *response;
967     int found = 0;
968     apr_size_t len;
969
970     /* start with an empty string */
971     buff[0] = 0;
972     *eos = 0;
973
974     /* loop through each brigade */
975     while (!found) {
976         /* get brigade from network one line at a time */
977         if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
978                                                 AP_MODE_GETLINE,
979                                                 APR_BLOCK_READ,
980                                                 0))) {
981             return rv;
982         }
983         /* loop through each bucket */
984         while (!found) {
985             if (*eos || APR_BRIGADE_EMPTY(bb)) {
986                 /* The connection aborted or timed out */
987                 return APR_ECONNABORTED;
988             }
989             e = APR_BRIGADE_FIRST(bb);
990             if (APR_BUCKET_IS_EOS(e)) {
991                 *eos = 1;
992             }
993             else {
994                 if (APR_SUCCESS != (rv = apr_bucket_read(e,
995                                                          (const char **)&response,
996                                                          &len,
997                                                          APR_BLOCK_READ))) {
998                     return rv;
999                 }
1000                 /*
1001                  * is string LF terminated?
1002                  * XXX: This check can be made more efficient by simply checking
1003                  * if the last character in the 'response' buffer is an ASCII_LF.
1004                  * See ap_rgetline() for an example.
1005                  */
1006                 if (memchr(response, APR_ASCII_LF, len)) {
1007                     found = 1;
1008                 }
1009                 /* concat strings until buff is full - then throw the data away */
1010                 if (len > ((bufflen-1)-(pos-buff))) {
1011                     len = (bufflen-1)-(pos-buff);
1012                 }
1013                 if (len > 0) {
1014                     memcpy(pos, response, len);
1015                     pos += len;
1016                 }
1017             }
1018             APR_BUCKET_REMOVE(e);
1019             apr_bucket_destroy(e);
1020         }
1021         *pos = '\0';
1022     }
1023
1024     return APR_SUCCESS;
1025 }
1026
1027 /* unmerge an element in the table */
1028 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
1029 {
1030     apr_off_t offset = 0;
1031     apr_off_t count = 0;
1032     char *value = NULL;
1033
1034     /* get the value to unmerge */
1035     const char *initial = apr_table_get(t, key);
1036     if (!initial) {
1037         return;
1038     }
1039     value = apr_pstrdup(p, initial);
1040
1041     /* remove the value from the headers */
1042     apr_table_unset(t, key);
1043
1044     /* find each comma */
1045     while (value[count]) {
1046         if (value[count] == ',') {
1047             value[count] = 0;
1048             apr_table_add(t, key, value + offset);
1049             offset = count + 1;
1050         }
1051         count++;
1052     }
1053     apr_table_add(t, key, value + offset);
1054 }
1055
1056 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1057                               proxy_dir_conf *conf, const char *url)
1058 {
1059     proxy_req_conf *rconf;
1060     struct proxy_alias *ent;
1061     int i, l1, l2;
1062     char *u;
1063
1064     /*
1065      * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1066      * after the hostname
1067      * XXX FIXME: Ensure the /uri component is a case sensitive match
1068      */
1069     if (r->proxyreq != PROXYREQ_REVERSE) {
1070         return url;
1071     }
1072
1073     l1 = strlen(url);
1074     if (conf->interpolate_env == 1) {
1075         rconf = ap_get_module_config(r->request_config, &proxy_module);
1076         ent = (struct proxy_alias *)rconf->raliases->elts;
1077     }
1078     else {
1079         ent = (struct proxy_alias *)conf->raliases->elts;
1080     }
1081     for (i = 0; i < conf->raliases->nelts; i++) {
1082         proxy_server_conf *sconf = (proxy_server_conf *)
1083             ap_get_module_config(r->server->module_config, &proxy_module);
1084         proxy_balancer *balancer;
1085         const char *real = ent[i].real;
1086         /*
1087          * First check if mapping against a balancer and see
1088          * if we have such a entity. If so, then we need to
1089          * find the particulars of the actual worker which may
1090          * or may not be the right one... basically, we need
1091          * to find which member actually handled this request.
1092          */
1093         if (ap_proxy_valid_balancer_name((char *)real, 0) &&
1094             (balancer = ap_proxy_get_balancer(r->pool, sconf, real, 1))) {
1095             int n, l3 = 0;
1096             proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
1097             const char *urlpart = ap_strchr_c(real, '/');
1098             if (urlpart) {
1099                 if (!urlpart[1])
1100                     urlpart = NULL;
1101                 else
1102                     l3 = strlen(urlpart);
1103             }
1104             /* The balancer comparison is a bit trickier.  Given the context
1105              *   BalancerMember balancer://alias http://example.com/foo
1106              *   ProxyPassReverse /bash balancer://alias/bar
1107              * translate url http://example.com/foo/bar/that to /bash/that
1108              */
1109             for (n = 0; n < balancer->workers->nelts; n++) {
1110                 l2 = strlen((*worker)->s->name);
1111                 if (urlpart) {
1112                     /* urlpart (l3) assuredly starts with its own '/' */
1113                     if ((*worker)->s->name[l2 - 1] == '/')
1114                         --l2;
1115                     if (l1 >= l2 + l3
1116                             && strncasecmp((*worker)->s->name, url, l2) == 0
1117                             && strncmp(urlpart, url + l2, l3) == 0) {
1118                         u = apr_pstrcat(r->pool, ent[i].fake, &url[l2 + l3],
1119                                         NULL);
1120                         return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1121                     }
1122                 }
1123                 else if (l1 >= l2 && strncasecmp((*worker)->s->name, url, l2) == 0) {
1124                     u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1125                     return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1126                 }
1127                 worker++;
1128             }
1129         }
1130         else {
1131             const char *part = url;
1132             l2 = strlen(real);
1133             if (real[0] == '/') {
1134                 part = ap_strstr_c(url, "://");
1135                 if (part) {
1136                     part = ap_strchr_c(part+3, '/');
1137                     if (part) {
1138                         l1 = strlen(part);
1139                     }
1140                     else {
1141                         part = url;
1142                     }
1143                 }
1144                 else {
1145                     part = url;
1146                 }
1147             }
1148             if (l1 >= l2 && strncasecmp(real, part, l2) == 0) {
1149                 u = apr_pstrcat(r->pool, ent[i].fake, &part[l2], NULL);
1150                 return ap_is_url(u) ? u : ap_construct_url(r->pool, u, r);
1151             }
1152         }
1153     }
1154
1155     return url;
1156 }
1157
1158 /*
1159  * Cookies are a bit trickier to match: we've got two substrings to worry
1160  * about, and we can't just find them with strstr 'cos of case.  Regexp
1161  * matching would be an easy fix, but for better consistency with all the
1162  * other matches we'll refrain and use apr_strmatch to find path=/domain=
1163  * and stick to plain strings for the config values.
1164  */
1165 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1166                               proxy_dir_conf *conf, const char *str)
1167 {
1168     proxy_req_conf *rconf = ap_get_module_config(r->request_config,
1169                                                  &proxy_module);
1170     struct proxy_alias *ent;
1171     size_t len = strlen(str);
1172     const char *newpath = NULL;
1173     const char *newdomain = NULL;
1174     const char *pathp;
1175     const char *domainp;
1176     const char *pathe = NULL;
1177     const char *domaine = NULL;
1178     size_t l1, l2, poffs = 0, doffs = 0;
1179     int i;
1180     int ddiff = 0;
1181     int pdiff = 0;
1182     char *ret;
1183
1184     if (r->proxyreq != PROXYREQ_REVERSE) {
1185         return str;
1186     }
1187
1188    /*
1189     * Find the match and replacement, but save replacing until we've done
1190     * both path and domain so we know the new strlen
1191     */
1192     if ((pathp = apr_strmatch(ap_proxy_strmatch_path, str, len)) != NULL) {
1193         pathp += 5;
1194         poffs = pathp - str;
1195         pathe = ap_strchr_c(pathp, ';');
1196         l1 = pathe ? (pathe - pathp) : strlen(pathp);
1197         pathe = pathp + l1 ;
1198         if (conf->interpolate_env == 1) {
1199             ent = (struct proxy_alias *)rconf->cookie_paths->elts;
1200         }
1201         else {
1202             ent = (struct proxy_alias *)conf->cookie_paths->elts;
1203         }
1204         for (i = 0; i < conf->cookie_paths->nelts; i++) {
1205             l2 = strlen(ent[i].fake);
1206             if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1207                 newpath = ent[i].real;
1208                 pdiff = strlen(newpath) - l1;
1209                 break;
1210             }
1211         }
1212     }
1213
1214     if ((domainp = apr_strmatch(ap_proxy_strmatch_domain, str, len)) != NULL) {
1215         domainp += 7;
1216         doffs = domainp - str;
1217         domaine = ap_strchr_c(domainp, ';');
1218         l1 = domaine ? (domaine - domainp) : strlen(domainp);
1219         domaine = domainp + l1;
1220         if (conf->interpolate_env == 1) {
1221             ent = (struct proxy_alias *)rconf->cookie_domains->elts;
1222         }
1223         else {
1224             ent = (struct proxy_alias *)conf->cookie_domains->elts;
1225         }
1226         for (i = 0; i < conf->cookie_domains->nelts; i++) {
1227             l2 = strlen(ent[i].fake);
1228             if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1229                 newdomain = ent[i].real;
1230                 ddiff = strlen(newdomain) - l1;
1231                 break;
1232             }
1233         }
1234     }
1235
1236     if (newpath) {
1237         ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1238         l1 = strlen(newpath);
1239         if (newdomain) {
1240             l2 = strlen(newdomain);
1241             if (doffs > poffs) {
1242                 memcpy(ret, str, poffs);
1243                 memcpy(ret + poffs, newpath, l1);
1244                 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1245                 memcpy(ret + doffs + pdiff, newdomain, l2);
1246                 strcpy(ret + doffs + pdiff + l2, domaine);
1247             }
1248             else {
1249                 memcpy(ret, str, doffs) ;
1250                 memcpy(ret + doffs, newdomain, l2);
1251                 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1252                 memcpy(ret + poffs + ddiff, newpath, l1);
1253                 strcpy(ret + poffs + ddiff + l1, pathe);
1254             }
1255         }
1256         else {
1257             memcpy(ret, str, poffs);
1258             memcpy(ret + poffs, newpath, l1);
1259             strcpy(ret + poffs + l1, pathe);
1260         }
1261     }
1262     else {
1263         if (newdomain) {
1264             ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1265             l2 = strlen(newdomain);
1266             memcpy(ret, str, doffs);
1267             memcpy(ret + doffs, newdomain, l2);
1268             strcpy(ret + doffs+l2, domaine);
1269         }
1270         else {
1271             ret = (char *)str; /* no change */
1272         }
1273     }
1274
1275     return ret;
1276 }
1277
1278 /*
1279  * BALANCER related...
1280  */
1281
1282 /*
1283  * verifies that the balancer name conforms to standards.
1284  */
1285 PROXY_DECLARE(int) ap_proxy_valid_balancer_name(char *name, int i)
1286 {
1287     if (!i)
1288         i = sizeof(BALANCER_PREFIX)-1;
1289     return (!strncasecmp(name, BALANCER_PREFIX, i));
1290 }
1291
1292
1293 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1294                                                       proxy_server_conf *conf,
1295                                                       const char *url,
1296                                                       int care)
1297 {
1298     proxy_balancer *balancer;
1299     char *c, *uri = apr_pstrdup(p, url);
1300     int i;
1301     unsigned int hash;
1302
1303     c = strchr(uri, ':');
1304     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1305         return NULL;
1306     }
1307     /* remove path from uri */
1308     if ((c = strchr(c + 3, '/'))) {
1309         *c = '\0';
1310     }
1311     hash = ap_proxy_hashfunc(uri, PROXY_HASHFUNC_DEFAULT);
1312     balancer = (proxy_balancer *)conf->balancers->elts;
1313     for (i = 0; i < conf->balancers->nelts; i++) {
1314         if (balancer->hash == hash) {
1315             if (!care || !balancer->s->inactive) {
1316                 return balancer;
1317             }
1318         }
1319         balancer++;
1320     }
1321     return NULL;
1322 }
1323
1324
1325 PROXY_DECLARE(char *) ap_proxy_update_balancer(apr_pool_t *p,
1326                                                 proxy_balancer *balancer,
1327                                                 const char *url)
1328 {
1329     apr_uri_t puri;
1330     if (apr_uri_parse(p, url, &puri) != APR_SUCCESS) {
1331         return apr_psprintf(p, "unable to parse: %s", url);
1332     }
1333     if (puri.path && PROXY_STRNCPY(balancer->s->vpath, puri.path) != APR_SUCCESS) {
1334         return apr_psprintf(p, "balancer %s front-end virtual-path (%s) too long",
1335                             balancer->s->name, puri.path);
1336     }
1337     if (puri.hostname && PROXY_STRNCPY(balancer->s->vhost, puri.hostname) != APR_SUCCESS) {
1338         return apr_psprintf(p, "balancer %s front-end vhost name (%s) too long",
1339                             balancer->s->name, puri.hostname);
1340     }
1341     return NULL;
1342 }
1343
1344 PROXY_DECLARE(char *) ap_proxy_define_balancer(apr_pool_t *p,
1345                                                proxy_balancer **balancer,
1346                                                proxy_server_conf *conf,
1347                                                const char *url,
1348                                                const char *alias,
1349                                                int do_malloc)
1350 {
1351     char nonce[APR_UUID_FORMATTED_LENGTH + 1];
1352     proxy_balancer_method *lbmethod;
1353     apr_uuid_t uuid;
1354     proxy_balancer_shared *bshared;
1355     char *c, *q, *uri = apr_pstrdup(p, url);
1356     const char *sname;
1357
1358     /* We should never get here without a valid BALANCER_PREFIX... */
1359
1360     c = strchr(uri, ':');
1361     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1362         return "Bad syntax for a balancer name";
1363     /* remove path from uri */
1364     if ((q = strchr(c + 3, '/')))
1365         *q = '\0';
1366
1367     ap_str_tolower(uri);
1368     *balancer = apr_array_push(conf->balancers);
1369     memset(*balancer, 0, sizeof(proxy_balancer));
1370
1371     /*
1372      * NOTE: The default method is byrequests, which we assume
1373      * exists!
1374      */
1375     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1376     if (!lbmethod) {
1377         return "Can't find 'byrequests' lb method";
1378     }
1379
1380     (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1381     (*balancer)->gmutex = NULL;
1382     (*balancer)->tmutex = NULL;
1383     (*balancer)->lbmethod = lbmethod;
1384
1385     if (do_malloc)
1386         bshared = ap_malloc(sizeof(proxy_balancer_shared));
1387     else
1388         bshared = apr_palloc(p, sizeof(proxy_balancer_shared));
1389
1390     memset(bshared, 0, sizeof(proxy_balancer_shared));
1391
1392     bshared->was_malloced = (do_malloc != 0);
1393     PROXY_STRNCPY(bshared->lbpname, "byrequests");
1394     if (PROXY_STRNCPY(bshared->name, uri) != APR_SUCCESS) {
1395         return apr_psprintf(p, "balancer name (%s) too long", uri);
1396     }
1397     ap_pstr2_alnum(p, bshared->name + sizeof(BALANCER_PREFIX) - 1,
1398                    &sname);
1399     sname = apr_pstrcat(p, conf->id, "_", sname, NULL);
1400     if (PROXY_STRNCPY(bshared->sname, sname) != APR_SUCCESS) {
1401         return apr_psprintf(p, "balancer safe-name (%s) too long", sname);
1402     }
1403     bshared->hash = ap_proxy_hashfunc(bshared->name, PROXY_HASHFUNC_DEFAULT);    
1404     (*balancer)->hash = bshared->hash;
1405
1406     /* Retrieve a UUID and store the nonce for the lifetime of
1407      * the process. */
1408     apr_uuid_get(&uuid);
1409     apr_uuid_format(nonce, &uuid);
1410     if (PROXY_STRNCPY(bshared->nonce, nonce) != APR_SUCCESS) {
1411         return apr_psprintf(p, "balancer nonce (%s) too long", nonce);
1412     }
1413
1414     (*balancer)->s = bshared;
1415     (*balancer)->sconf = conf;
1416
1417     return ap_proxy_update_balancer(p, *balancer, alias);
1418 }
1419
1420 /*
1421  * Create an already defined balancer and free up memory.
1422  */
1423 PROXY_DECLARE(apr_status_t) ap_proxy_share_balancer(proxy_balancer *balancer,
1424                                                     proxy_balancer_shared *shm,
1425                                                     int i)
1426 {
1427     proxy_balancer_method *lbmethod;
1428     if (!shm || !balancer->s)
1429         return APR_EINVAL;
1430
1431     memcpy(shm, balancer->s, sizeof(proxy_balancer_shared));
1432     if (balancer->s->was_malloced)
1433         free(balancer->s);
1434     balancer->s = shm;
1435     balancer->s->index = i;
1436     /* the below should always succeed */
1437     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, balancer->s->lbpname, "0");
1438     if (lbmethod)
1439         balancer->lbmethod = lbmethod;
1440     return APR_SUCCESS;
1441 }
1442
1443 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_balancer(proxy_balancer *balancer, server_rec *s, apr_pool_t *p)
1444 {
1445     apr_status_t rv = APR_SUCCESS;
1446     ap_slotmem_provider_t *storage = balancer->storage;
1447     apr_size_t size;
1448     unsigned int num;
1449
1450     if (!storage) {
1451         ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1452                      "no provider for %s", balancer->s->name);
1453         return APR_EGENERAL;
1454     }
1455     /*
1456      * for each balancer we need to init the global
1457      * mutex and then attach to the shared worker shm
1458      */
1459     if (!balancer->gmutex) {
1460         ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1461                      "no mutex %s", balancer->s->name);
1462         return APR_EGENERAL;
1463     }
1464
1465     /* Re-open the mutex for the child. */
1466     rv = apr_global_mutex_child_init(&(balancer->gmutex),
1467                                      apr_global_mutex_lockfile(balancer->gmutex),
1468                                      p);
1469     if (rv != APR_SUCCESS) {
1470         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
1471                      "Failed to reopen mutex %s in child",
1472                      balancer->s->name);
1473         return rv;
1474     }
1475
1476     /* now attach */
1477     storage->attach(&(balancer->wslot), balancer->s->sname, &size, &num, p);
1478     if (!balancer->wslot) {
1479         ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, "slotmem_attach failed");
1480         return APR_EGENERAL;
1481     }
1482     if (balancer->lbmethod && balancer->lbmethod->reset)
1483         balancer->lbmethod->reset(balancer, s);
1484
1485     if (balancer->tmutex == NULL) {
1486         rv = apr_thread_mutex_create(&(balancer->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1487         if (rv != APR_SUCCESS) {
1488             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s,
1489                          "can not create balancer thread mutex");
1490             return rv;
1491         }
1492     }
1493     return APR_SUCCESS;
1494 }
1495
1496 /*
1497  * CONNECTION related...
1498  */
1499
1500 static apr_status_t conn_pool_cleanup(void *theworker)
1501 {
1502     proxy_worker *worker = (proxy_worker *)theworker;
1503     if (worker->cp->res) {
1504         worker->cp->pool = NULL;
1505     }
1506     return APR_SUCCESS;
1507 }
1508
1509 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1510 {
1511     apr_pool_t *pool;
1512     proxy_conn_pool *cp;
1513
1514     /*
1515      * Create a connection pool's subpool.
1516      * This pool is used for connection recycling.
1517      * Once the worker is added it is never removed but
1518      * it can be disabled.
1519      */
1520     apr_pool_create(&pool, p);
1521     apr_pool_tag(pool, "proxy_worker_cp");
1522     /*
1523      * Alloc from the same pool as worker.
1524      * proxy_conn_pool is permanently attached to the worker.
1525      */
1526     cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1527     cp->pool = pool;
1528     worker->cp = cp;
1529 }
1530
1531 static apr_status_t connection_cleanup(void *theconn)
1532 {
1533     proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1534     proxy_worker *worker = conn->worker;
1535
1536     /*
1537      * If the connection pool is NULL the worker
1538      * cleanup has been run. Just return.
1539      */
1540     if (!worker->cp) {
1541         return APR_SUCCESS;
1542     }
1543
1544     if (conn->r) {
1545         apr_pool_destroy(conn->r->pool);
1546         conn->r = NULL;
1547     }
1548
1549     /* Sanity check: Did we already return the pooled connection? */
1550     if (conn->inreslist) {
1551         ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool,
1552                       "Pooled connection 0x%pp for worker %s has been"
1553                       " already returned to the connection pool.", conn,
1554                       worker->s->name);
1555         return APR_SUCCESS;
1556     }
1557
1558     /* determine if the connection need to be closed */
1559     if (conn->close || !worker->s->is_address_reusable || worker->s->disablereuse) {
1560         apr_pool_t *p = conn->pool;
1561         apr_pool_clear(p);
1562         conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1563         conn->pool = p;
1564         conn->worker = worker;
1565         apr_pool_create(&(conn->scpool), p);
1566         apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1567     }
1568
1569     if (worker->s->hmax && worker->cp->res) {
1570         conn->inreslist = 1;
1571         apr_reslist_release(worker->cp->res, (void *)conn);
1572     }
1573     else
1574     {
1575         worker->cp->conn = conn;
1576     }
1577
1578     /* Always return the SUCCESS */
1579     return APR_SUCCESS;
1580 }
1581
1582 static void socket_cleanup(proxy_conn_rec *conn)
1583 {
1584     conn->sock = NULL;
1585     conn->connection = NULL;
1586     apr_pool_clear(conn->scpool);
1587 }
1588
1589 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1590                                                             request_rec *r)
1591 {
1592     apr_bucket_brigade *bb;
1593     apr_status_t rv;
1594
1595     /*
1596      * If we have an existing SSL connection it might be possible that the
1597      * server sent some SSL message we have not read so far (e.g. an SSL
1598      * shutdown message if the server closed the keepalive connection while
1599      * the connection was held unused in our pool).
1600      * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1601      * processed. We don't expect any data to be in the returned brigade.
1602      */
1603     if (conn->sock && conn->connection) {
1604         bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1605         rv = ap_get_brigade(conn->connection->input_filters, bb,
1606                             AP_MODE_READBYTES, APR_NONBLOCK_READ,
1607                             HUGE_STRING_LEN);
1608         if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1609             socket_cleanup(conn);
1610         }
1611         if (!APR_BRIGADE_EMPTY(bb)) {
1612             apr_off_t len;
1613
1614             rv = apr_brigade_length(bb, 0, &len);
1615             ap_log_rerror(APLOG_MARK, APLOG_TRACE3, rv, r,
1616                           "SSL cleanup brigade contained %"
1617                           APR_OFF_T_FMT " bytes of data.", len);
1618         }
1619         apr_brigade_destroy(bb);
1620     }
1621     return APR_SUCCESS;
1622 }
1623
1624 /* reslist constructor */
1625 static apr_status_t connection_constructor(void **resource, void *params,
1626                                            apr_pool_t *pool)
1627 {
1628     apr_pool_t *ctx;
1629     apr_pool_t *scpool;
1630     proxy_conn_rec *conn;
1631     proxy_worker *worker = (proxy_worker *)params;
1632
1633     /*
1634      * Create the subpool for each connection
1635      * This keeps the memory consumption constant
1636      * when disconnecting from backend.
1637      */
1638     apr_pool_create(&ctx, pool);
1639     apr_pool_tag(ctx, "proxy_conn_pool");
1640     /*
1641      * Create another subpool that manages the data for the
1642      * socket and the connection member of the proxy_conn_rec struct as we
1643      * destroy this data more frequently than other data in the proxy_conn_rec
1644      * struct like hostname and addr (at least in the case where we have
1645      * keepalive connections that timed out).
1646      */
1647     apr_pool_create(&scpool, ctx);
1648     apr_pool_tag(scpool, "proxy_conn_scpool");
1649     conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1650
1651     conn->pool   = ctx;
1652     conn->scpool = scpool;
1653     conn->worker = worker;
1654     conn->inreslist = 1;
1655     *resource = conn;
1656
1657     return APR_SUCCESS;
1658 }
1659
1660 /* reslist destructor */
1661 static apr_status_t connection_destructor(void *resource, void *params,
1662                                           apr_pool_t *pool)
1663 {
1664     proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1665
1666     /* Destroy the pool only if not called from reslist_destroy */
1667     if (conn->worker->cp->pool) {
1668         apr_pool_destroy(conn->pool);
1669     }
1670
1671     return APR_SUCCESS;
1672 }
1673
1674 /*
1675  * WORKER related...
1676  */
1677
1678 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1679                                                   proxy_balancer *balancer,
1680                                                   proxy_server_conf *conf,
1681                                                   const char *url)
1682 {
1683     proxy_worker *worker;
1684     proxy_worker *max_worker = NULL;
1685     int max_match = 0;
1686     int url_length;
1687     int min_match;
1688     int worker_name_length;
1689     const char *c;
1690     char *url_copy;
1691     int i;
1692
1693     c = ap_strchr_c(url, ':');
1694     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1695         return NULL;
1696     }
1697
1698     url_length = strlen(url);
1699     url_copy = apr_pstrmemdup(p, url, url_length);
1700
1701     /*
1702      * We need to find the start of the path and
1703      * therefore we know the length of the scheme://hostname/
1704      * part to we can force-lowercase everything up to
1705      * the start of the path.
1706      */
1707     c = ap_strchr_c(c+3, '/');
1708     if (c) {
1709         char *pathstart;
1710         pathstart = url_copy + (c - url);
1711         *pathstart = '\0';
1712         ap_str_tolower(url_copy);
1713         min_match = strlen(url_copy);
1714         *pathstart = '/';
1715     }
1716     else {
1717         ap_str_tolower(url_copy);
1718         min_match = strlen(url_copy);
1719     }
1720     /*
1721      * Do a "longest match" on the worker name to find the worker that
1722      * fits best to the URL, but keep in mind that we must have at least
1723      * a minimum matching of length min_match such that
1724      * scheme://hostname[:port] matches between worker and url.
1725      */
1726
1727     if (balancer) {
1728         proxy_worker **workers = (proxy_worker **)balancer->workers->elts;
1729         for (i = 0; i < balancer->workers->nelts; i++, workers++) {
1730             worker = *workers;
1731             if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1732                 && (worker_name_length >= min_match)
1733                 && (worker_name_length > max_match)
1734                 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1735                 max_worker = worker;
1736                 max_match = worker_name_length;
1737             }
1738
1739         }
1740     } else {
1741         worker = (proxy_worker *)conf->workers->elts;
1742         for (i = 0; i < conf->workers->nelts; i++, worker++) {
1743             if ( ((worker_name_length = strlen(worker->s->name)) <= url_length)
1744                 && (worker_name_length >= min_match)
1745                 && (worker_name_length > max_match)
1746                 && (strncmp(url_copy, worker->s->name, worker_name_length) == 0) ) {
1747                 max_worker = worker;
1748                 max_match = worker_name_length;
1749             }
1750         }
1751     }
1752
1753     return max_worker;
1754 }
1755
1756 /*
1757  * To create a worker from scratch first we define the
1758  * specifics of the worker; this is all local data.
1759  * We then allocate space for it if data needs to be
1760  * shared. This allows for dynamic addition during
1761  * config and runtime.
1762  */
1763 PROXY_DECLARE(char *) ap_proxy_define_worker(apr_pool_t *p,
1764                                              proxy_worker **worker,
1765                                              proxy_balancer *balancer,
1766                                              proxy_server_conf *conf,
1767                                              const char *url,
1768                                              int do_malloc)
1769 {
1770     int rv;
1771     apr_uri_t uri;
1772     proxy_worker_shared *wshared;
1773     char *ptr;
1774
1775     rv = apr_uri_parse(p, url, &uri);
1776
1777     if (rv != APR_SUCCESS) {
1778         return "Unable to parse URL";
1779     }
1780     if (!uri.hostname || !uri.scheme) {
1781         return "URL must be absolute!";
1782     }
1783
1784     ap_str_tolower(uri.hostname);
1785     ap_str_tolower(uri.scheme);
1786     /*
1787      * Workers can be associated w/ balancers or on their
1788      * own; ie: the generic reverse-proxy or a worker
1789      * in a simple ProxyPass statement. eg:
1790      *
1791      *      ProxyPass / http://www.example.com
1792      *
1793      * in which case the worker goes in the conf slot.
1794      */
1795     if (balancer) {
1796         proxy_worker **runtime;
1797         /* recall that we get a ptr to the ptr here */
1798         runtime = apr_array_push(balancer->workers);
1799         *worker = *runtime = apr_palloc(p, sizeof(proxy_worker));   /* right to left baby */
1800         /* we've updated the list of workers associated with
1801          * this balancer *locally* */
1802         balancer->wupdated = apr_time_now();
1803     } else if (conf) {
1804         *worker = apr_array_push(conf->workers);
1805     } else {
1806         /* we need to allocate space here */
1807         *worker = apr_palloc(p, sizeof(proxy_worker));
1808     }
1809
1810     memset(*worker, 0, sizeof(proxy_worker));
1811     /* right here we just want to tuck away the worker info.
1812      * if called during config, we don't have shm setup yet,
1813      * so just note the info for later. */
1814     if (do_malloc)
1815         wshared = ap_malloc(sizeof(proxy_worker_shared));  /* will be freed ap_proxy_share_worker */
1816     else
1817         wshared = apr_palloc(p, sizeof(proxy_worker_shared));
1818
1819     memset(wshared, 0, sizeof(proxy_worker_shared));
1820
1821     ptr = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1822     if (PROXY_STRNCPY(wshared->name, ptr) != APR_SUCCESS) {
1823         return apr_psprintf(p, "worker name (%s) too long", ptr);
1824     }
1825     if (PROXY_STRNCPY(wshared->scheme, uri.scheme) != APR_SUCCESS) {
1826         return apr_psprintf(p, "worker scheme (%s) too long", uri.scheme);
1827     }
1828     if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) {
1829         return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname);
1830     }
1831     wshared->port = uri.port;
1832     wshared->flush_packets = flush_off;
1833     wshared->flush_wait = PROXY_FLUSH_WAIT;
1834     wshared->is_address_reusable = 1;
1835     wshared->lbfactor = 1;
1836     wshared->smax = -1;
1837     wshared->hash = ap_proxy_hashfunc(wshared->name, PROXY_HASHFUNC_DEFAULT);
1838     wshared->was_malloced = (do_malloc != 0);
1839
1840     (*worker)->hash = wshared->hash;
1841     (*worker)->context = NULL;
1842     (*worker)->cp = NULL;
1843     (*worker)->balancer = balancer;
1844     (*worker)->s = wshared;
1845
1846     return NULL;
1847 }
1848
1849 /*
1850  * Create an already defined worker and free up memory
1851  */
1852 PROXY_DECLARE(apr_status_t) ap_proxy_share_worker(proxy_worker *worker, proxy_worker_shared *shm,
1853                                                   int i)
1854 {
1855     if (!shm || !worker->s)
1856         return APR_EINVAL;
1857
1858     memcpy(shm, worker->s, sizeof(proxy_worker_shared));
1859     if (worker->s->was_malloced)
1860         free(worker->s); /* was malloced in ap_proxy_define_worker */
1861     worker->s = shm;
1862     worker->s->index = i;
1863     return APR_SUCCESS;
1864 }
1865
1866 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1867 {
1868     apr_status_t rv = APR_SUCCESS;
1869     int mpm_threads;
1870
1871     if (worker->s->status & PROXY_WORKER_INITIALIZED) {
1872         /* The worker is already initialized */
1873         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1874                      "worker %s shared already initialized", worker->s->name);
1875     }
1876     else {
1877         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1878                      "initializing worker %s shared", worker->s->name);
1879         /* Set default parameters */
1880         if (!worker->s->retry_set) {
1881             worker->s->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1882         }
1883         /* By default address is reusable unless DisableReuse is set */
1884         if (worker->s->disablereuse) {
1885             worker->s->is_address_reusable = 0;
1886         }
1887         else {
1888             worker->s->is_address_reusable = 1;
1889         }
1890
1891         ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1892         if (mpm_threads > 1) {
1893             /* Set hard max to no more then mpm_threads */
1894             if (worker->s->hmax == 0 || worker->s->hmax > mpm_threads) {
1895                 worker->s->hmax = mpm_threads;
1896             }
1897             if (worker->s->smax == -1 || worker->s->smax > worker->s->hmax) {
1898                 worker->s->smax = worker->s->hmax;
1899             }
1900             /* Set min to be lower then smax */
1901             if (worker->s->min > worker->s->smax) {
1902                 worker->s->min = worker->s->smax;
1903             }
1904         }
1905         else {
1906             /* This will supress the apr_reslist creation */
1907             worker->s->min = worker->s->smax = worker->s->hmax = 0;
1908         }
1909     }
1910
1911     /* What if local is init'ed and shm isn't?? Even possible? */
1912     if (worker->local_status & PROXY_WORKER_INITIALIZED) {
1913         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1914                      "worker %s local already initialized", worker->s->name);
1915     }
1916     else {
1917         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1918                      "initializing worker %s local", worker->s->name);
1919         /* Now init local worker data */
1920         if (worker->tmutex == NULL) {
1921             rv = apr_thread_mutex_create(&(worker->tmutex), APR_THREAD_MUTEX_DEFAULT, p);
1922             if (rv != APR_SUCCESS) {
1923                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1924                              "can not create worker thread mutex");
1925                 return rv;
1926             }
1927         }
1928         if (worker->cp == NULL)
1929             init_conn_pool(p, worker);
1930         if (worker->cp == NULL) {
1931             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1932                          "can not create connection pool");
1933             return APR_EGENERAL;
1934         }
1935
1936         if (worker->s->hmax) {
1937             rv = apr_reslist_create(&(worker->cp->res),
1938                                     worker->s->min, worker->s->smax,
1939                                     worker->s->hmax, worker->s->ttl,
1940                                     connection_constructor, connection_destructor,
1941                                     worker, worker->cp->pool);
1942
1943             apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1944                                       conn_pool_cleanup,
1945                                       apr_pool_cleanup_null);
1946
1947             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1948                 "initialized pool in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1949                  getpid(), worker->s->hostname, worker->s->min,
1950                  worker->s->hmax, worker->s->smax);
1951
1952             /* Set the acquire timeout */
1953             if (rv == APR_SUCCESS && worker->s->acquire_set) {
1954                 apr_reslist_timeout_set(worker->cp->res, worker->s->acquire);
1955             }
1956
1957         }
1958         else {
1959             void *conn;
1960
1961             rv = connection_constructor(&conn, worker, worker->cp->pool);
1962             worker->cp->conn = conn;
1963
1964             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1965                  "initialized single connection worker in child %" APR_PID_T_FMT " for (%s)",
1966                  getpid(), worker->s->hostname);
1967         }
1968     }
1969     if (rv == APR_SUCCESS) {
1970         worker->s->status |= (PROXY_WORKER_INITIALIZED);
1971         worker->local_status |= (PROXY_WORKER_INITIALIZED);
1972     }
1973     return rv;
1974 }
1975
1976 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1977                                          proxy_worker *worker,
1978                                          server_rec *s)
1979 {
1980     if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1981         if (apr_time_now() > worker->s->error_time + worker->s->retry) {
1982             ++worker->s->retries;
1983             worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1984             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1985                          "%s: worker for (%s) has been marked for retry",
1986                          proxy_function, worker->s->hostname);
1987             return OK;
1988         }
1989         else {
1990             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1991                          "%s: too soon to retry worker for (%s)",
1992                          proxy_function, worker->s->hostname);
1993             return DECLINED;
1994         }
1995     }
1996     else {
1997         return OK;
1998     }
1999 }
2000
2001 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
2002                                         proxy_balancer **balancer,
2003                                         request_rec *r,
2004                                         proxy_server_conf *conf, char **url)
2005 {
2006     int access_status;
2007
2008     access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
2009     if (access_status == DECLINED && *balancer == NULL) {
2010         *worker = ap_proxy_get_worker(r->pool, NULL, conf, *url);
2011         if (*worker) {
2012             ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2013                           "%s: found worker %s for %s",
2014                           (*worker)->s->scheme, (*worker)->s->name, *url);
2015
2016             *balancer = NULL;
2017             access_status = OK;
2018         }
2019         else if (r->proxyreq == PROXYREQ_PROXY) {
2020             if (conf->forward) {
2021                 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2022                               "*: found forward proxy worker for %s", *url);
2023                 *balancer = NULL;
2024                 *worker = conf->forward;
2025                 access_status = OK;
2026                 /*
2027                  * The forward worker does not keep connections alive, so
2028                  * ensure that mod_proxy_http does the correct thing
2029                  * regarding the Connection header in the request.
2030                  */
2031                 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
2032             }
2033         }
2034         else if (r->proxyreq == PROXYREQ_REVERSE) {
2035             if (conf->reverse) {
2036                 ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2037                               "*: found reverse proxy worker for %s", *url);
2038                 *balancer = NULL;
2039                 *worker = conf->reverse;
2040                 access_status = OK;
2041                 /*
2042                  * The reverse worker does not keep connections alive, so
2043                  * ensure that mod_proxy_http does the correct thing
2044                  * regarding the Connection header in the request.
2045                  */
2046                 apr_table_setn(r->subprocess_env, "proxy-nokeepalive", "1");
2047             }
2048         }
2049     }
2050     else if (access_status == DECLINED && *balancer != NULL) {
2051         /* All the workers are busy */
2052         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2053                       "all workers are busy.  Unable to serve %s", *url);
2054         access_status = HTTP_SERVICE_UNAVAILABLE;
2055     }
2056     return access_status;
2057 }
2058
2059 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
2060                                          proxy_balancer *balancer,
2061                                          request_rec *r,
2062                                          proxy_server_conf *conf)
2063 {
2064     int access_status = OK;
2065     if (balancer) {
2066         access_status = proxy_run_post_request(worker, balancer, r, conf);
2067         if (access_status == DECLINED) {
2068             access_status = OK; /* no post_request handler available */
2069             /* TODO: recycle direct worker */
2070         }
2071     }
2072
2073     return access_status;
2074 }
2075
2076 /* DEPRECATED */
2077 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
2078                                                const char *proxy_function,
2079                                                apr_sockaddr_t *backend_addr,
2080                                                const char *backend_name,
2081                                                proxy_server_conf *conf,
2082                                                request_rec *r)
2083 {
2084     apr_status_t rv;
2085     int connected = 0;
2086     int loglevel;
2087
2088     while (backend_addr && !connected) {
2089         if ((rv = apr_socket_create(newsock, backend_addr->family,
2090                                     SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
2091             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2092             ap_log_rerror(APLOG_MARK, loglevel, rv, r,
2093                           "%s: error creating fam %d socket for target %s",
2094                           proxy_function, backend_addr->family, backend_name);
2095             /*
2096              * this could be an IPv6 address from the DNS but the
2097              * local machine won't give us an IPv6 socket; hopefully the
2098              * DNS returned an additional address to try
2099              */
2100             backend_addr = backend_addr->next;
2101             continue;
2102         }
2103
2104         if (conf->recv_buffer_size > 0 &&
2105             (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
2106                                      conf->recv_buffer_size))) {
2107             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2108                           "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2109                           "ProxyReceiveBufferSize, using default");
2110         }
2111
2112         rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
2113         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2114             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2115                           "apr_socket_opt_set(APR_TCP_NODELAY): "
2116                           "Failed to set");
2117         }
2118
2119         /* Set a timeout on the socket */
2120         if (conf->timeout_set) {
2121             apr_socket_timeout_set(*newsock, conf->timeout);
2122         }
2123         else {
2124             apr_socket_timeout_set(*newsock, r->server->timeout);
2125         }
2126
2127         ap_log_rerror(APLOG_MARK, APLOG_TRACE2, 0, r,
2128                       "%s: fam %d socket created to connect to %s",
2129                       proxy_function, backend_addr->family, backend_name);
2130
2131         if (conf->source_address) {
2132             rv = apr_socket_bind(*newsock, conf->source_address);
2133             if (rv != APR_SUCCESS) {
2134                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
2135                               "%s: failed to bind socket to local address",
2136                               proxy_function);
2137             }
2138         }
2139
2140         /* make the connection out of the socket */
2141         rv = apr_socket_connect(*newsock, backend_addr);
2142
2143         /* if an error occurred, loop round and try again */
2144         if (rv != APR_SUCCESS) {
2145             apr_socket_close(*newsock);
2146             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2147             ap_log_rerror(APLOG_MARK, loglevel, rv, r,
2148                           "%s: attempt to connect to %pI (%s) failed",
2149                           proxy_function, backend_addr, backend_name);
2150             backend_addr = backend_addr->next;
2151             continue;
2152         }
2153         connected = 1;
2154     }
2155     return connected ? 0 : 1;
2156 }
2157
2158 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
2159                                                proxy_conn_rec **conn,
2160                                                proxy_worker *worker,
2161                                                server_rec *s)
2162 {
2163     apr_status_t rv;
2164
2165     if (!PROXY_WORKER_IS_USABLE(worker)) {
2166         /* Retry the worker */
2167         ap_proxy_retry_worker(proxy_function, worker, s);
2168
2169         if (!PROXY_WORKER_IS_USABLE(worker)) {
2170             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2171                          "%s: disabled connection for (%s)",
2172                          proxy_function, worker->s->hostname);
2173             return HTTP_SERVICE_UNAVAILABLE;
2174         }
2175     }
2176
2177     if (worker->s->hmax && worker->cp->res) {
2178         rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2179     }
2180     else {
2181         /* create the new connection if the previous was destroyed */
2182         if (!worker->cp->conn) {
2183             connection_constructor((void **)conn, worker, worker->cp->pool);
2184         }
2185         else {
2186             *conn = worker->cp->conn;
2187             worker->cp->conn = NULL;
2188         }
2189         rv = APR_SUCCESS;
2190     }
2191
2192     if (rv != APR_SUCCESS) {
2193         ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2194                      "%s: failed to acquire connection for (%s)",
2195                      proxy_function, worker->s->hostname);
2196         return HTTP_SERVICE_UNAVAILABLE;
2197     }
2198     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2199                  "%s: has acquired connection for (%s)",
2200                  proxy_function, worker->s->hostname);
2201
2202     (*conn)->worker = worker;
2203     (*conn)->close  = 0;
2204     (*conn)->inreslist = 0;
2205
2206     return OK;
2207 }
2208
2209 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2210                                                proxy_conn_rec *conn,
2211                                                server_rec *s)
2212 {
2213     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2214                 "%s: has released connection for (%s)",
2215                 proxy_function, conn->worker->s->hostname);
2216     connection_cleanup(conn);
2217
2218     return OK;
2219 }
2220
2221 PROXY_DECLARE(int)
2222 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2223                               proxy_server_conf *conf,
2224                               proxy_worker *worker,
2225                               proxy_conn_rec *conn,
2226                               apr_uri_t *uri,
2227                               char **url,
2228                               const char *proxyname,
2229                               apr_port_t proxyport,
2230                               char *server_portstr,
2231                               int server_portstr_size)
2232 {
2233     int server_port;
2234     apr_status_t err = APR_SUCCESS;
2235     apr_status_t uerr = APR_SUCCESS;
2236
2237     /*
2238      * Break up the URL to determine the host to connect to
2239      */
2240
2241     /* we break the URL into host, port, uri */
2242     if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2243         return ap_proxyerror(r, HTTP_BAD_REQUEST,
2244                              apr_pstrcat(p,"URI cannot be parsed: ", *url,
2245                                          NULL));
2246     }
2247     if (!uri->port) {
2248         uri->port = apr_uri_port_of_scheme(uri->scheme);
2249     }
2250
2251     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2252                  "connecting %s to %s:%d", *url, uri->hostname, uri->port);
2253
2254     /*
2255      * allocate these out of the specified connection pool
2256      * The scheme handler decides if this is permanent or
2257      * short living pool.
2258      */
2259     /* are we connecting directly, or via a proxy? */
2260     if (!proxyname) {
2261         *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2262                            uri->query ? uri->query : "",
2263                            uri->fragment ? "#" : "",
2264                            uri->fragment ? uri->fragment : "", NULL);
2265     }
2266     /*
2267      * Make sure that we pick the the correct and valid worker.
2268      * If a single keepalive connection triggers different workers,
2269      * then we have a problem (we don't select the correct one).
2270      * Do an expensive check in this case, where we compare the
2271      * the hostnames associated between the two.
2272      *
2273      * TODO: Handle this much better...
2274      */
2275     if (!conn->hostname || !worker->s->is_address_reusable ||
2276          worker->s->disablereuse ||
2277          (r->connection->keepalives &&
2278          (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2279          (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2280         if (proxyname) {
2281             conn->hostname = apr_pstrdup(conn->pool, proxyname);
2282             conn->port = proxyport;
2283             /*
2284              * If we have a forward proxy and the protocol is HTTPS,
2285              * then we need to prepend a HTTP CONNECT request before
2286              * sending our actual HTTPS requests.
2287              * Save our real backend data for using it later during HTTP CONNECT.
2288              */
2289             if (conn->is_ssl) {
2290                 const char *proxy_auth;
2291
2292                 forward_info *forward = apr_pcalloc(conn->pool, sizeof(forward_info));
2293                 conn->forward = forward;
2294                 forward->use_http_connect = 1;
2295                 forward->target_host = apr_pstrdup(conn->pool, uri->hostname);
2296                 forward->target_port = uri->port;
2297                 /* Do we want to pass Proxy-Authorization along?
2298                  * If we haven't used it, then YES
2299                  * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
2300                  * So let's make it configurable by env.
2301                  * The logic here is the same used in mod_proxy_http.
2302                  */
2303                 proxy_auth = apr_table_get(r->headers_in, "Proxy-Authorization");
2304                 if (proxy_auth != NULL &&
2305                     proxy_auth[0] != '\0' &&
2306                     r->user == NULL && /* we haven't yet authenticated */
2307                     apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
2308                     forward->proxy_auth = apr_pstrdup(conn->pool, proxy_auth);
2309                 }
2310             }
2311         }
2312         else {
2313             conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2314             conn->port = uri->port;
2315         }
2316         socket_cleanup(conn);
2317         err = apr_sockaddr_info_get(&(conn->addr),
2318                                     conn->hostname, APR_UNSPEC,
2319                                     conn->port, 0,
2320                                     conn->pool);
2321     }
2322     else if (!worker->cp->addr) {
2323         if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2324             ap_log_rerror(APLOG_MARK, APLOG_ERR, err, r, "lock");
2325             return HTTP_INTERNAL_SERVER_ERROR;
2326         }
2327
2328         /*
2329          * Worker can have the single constant backend adress.
2330          * The single DNS lookup is used once per worker.
2331          * If dynamic change is needed then set the addr to NULL
2332          * inside dynamic config to force the lookup.
2333          */
2334         err = apr_sockaddr_info_get(&(worker->cp->addr),
2335                                     conn->hostname, APR_UNSPEC,
2336                                     conn->port, 0,
2337                                     worker->cp->pool);
2338         conn->addr = worker->cp->addr;
2339         if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2340             ap_log_rerror(APLOG_MARK, APLOG_ERR, uerr, r, "unlock");
2341         }
2342     }
2343     else {
2344         conn->addr = worker->cp->addr;
2345     }
2346     /* Close a possible existing socket if we are told to do so */
2347     if (conn->close) {
2348         socket_cleanup(conn);
2349         conn->close = 0;
2350     }
2351
2352     if (err != APR_SUCCESS) {
2353         return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2354                              apr_pstrcat(p, "DNS lookup failure for: ",
2355                                          conn->hostname, NULL));
2356     }
2357
2358     /* Get the server port for the Via headers */
2359     {
2360         server_port = ap_get_server_port(r);
2361         if (ap_is_default_port(server_port, r)) {
2362             strcpy(server_portstr,"");
2363         }
2364         else {
2365             apr_snprintf(server_portstr, server_portstr_size, ":%d",
2366                          server_port);
2367         }
2368     }
2369     /* check if ProxyBlock directive on this host */
2370     if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2371         return ap_proxyerror(r, HTTP_FORBIDDEN,
2372                              "Connect to remote machine blocked");
2373     }
2374     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2375                  "connected %s to %s:%d", *url, conn->hostname, conn->port);
2376     return OK;
2377 }
2378
2379 #define USE_ALTERNATE_IS_CONNECTED 1
2380
2381 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2382 #define APR_MSG_PEEK MSG_PEEK
2383 #endif
2384
2385 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2386 static int is_socket_connected(apr_socket_t *socket)
2387 {
2388     apr_pollfd_t pfds[1];
2389     apr_status_t status;
2390     apr_int32_t  nfds;
2391
2392     pfds[0].reqevents = APR_POLLIN;
2393     pfds[0].desc_type = APR_POLL_SOCKET;
2394     pfds[0].desc.s = socket;
2395
2396     do {
2397         status = apr_poll(&pfds[0], 1, &nfds, 0);
2398     } while (APR_STATUS_IS_EINTR(status));
2399
2400     if (status == APR_SUCCESS && nfds == 1 &&
2401         pfds[0].rtnevents == APR_POLLIN) {
2402         apr_sockaddr_t unused;
2403         apr_size_t len = 1;
2404         char buf[1];
2405         /* The socket might be closed in which case
2406          * the poll will return POLLIN.
2407          * If there is no data available the socket
2408          * is closed.
2409          */
2410         status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2411                                      &buf[0], &len);
2412         if (status == APR_SUCCESS && len)
2413             return 1;
2414         else
2415             return 0;
2416     }
2417     else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2418         return 1;
2419     }
2420     return 0;
2421
2422 }
2423 #else
2424 static int is_socket_connected(apr_socket_t *sock)
2425
2426 {
2427     apr_size_t buffer_len = 1;
2428     char test_buffer[1];
2429     apr_status_t socket_status;
2430     apr_interval_time_t current_timeout;
2431
2432     /* save timeout */
2433     apr_socket_timeout_get(sock, &current_timeout);
2434     /* set no timeout */
2435     apr_socket_timeout_set(sock, 0);
2436     socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2437     /* put back old timeout */
2438     apr_socket_timeout_set(sock, current_timeout);
2439     if (APR_STATUS_IS_EOF(socket_status)
2440         || APR_STATUS_IS_ECONNRESET(socket_status)) {
2441         return 0;
2442     }
2443     else {
2444         return 1;
2445     }
2446 }
2447 #endif /* USE_ALTERNATE_IS_CONNECTED */
2448
2449
2450 /*
2451  * Send a HTTP CONNECT request to a forward proxy.
2452  * The proxy is given by "backend", the target server
2453  * is contained in the "forward" member of "backend".
2454  */
2455 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2456                                       server_rec *s)
2457 {
2458     int status;
2459     apr_size_t nbytes;
2460     apr_size_t left;
2461     int complete = 0;
2462     char buffer[HUGE_STRING_LEN];
2463     char drain_buffer[HUGE_STRING_LEN];
2464     forward_info *forward = (forward_info *)backend->forward;
2465     int len = 0;
2466
2467     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2468                  "CONNECT: sending the CONNECT request for %s:%d "
2469                  "to the remote proxy %pI (%s)",
2470                  forward->target_host, forward->target_port,
2471                  backend->addr, backend->hostname);
2472     /* Create the CONNECT request */
2473     nbytes = apr_snprintf(buffer, sizeof(buffer),
2474                           "CONNECT %s:%d HTTP/1.0" CRLF,
2475                           forward->target_host, forward->target_port);
2476     /* Add proxy authorization from the initial request if necessary */
2477     if (forward->proxy_auth != NULL) {
2478         nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2479                                "Proxy-Authorization: %s" CRLF,
2480                                forward->proxy_auth);
2481     }
2482     /* Set a reasonable agent and send everything */
2483     nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2484                            "Proxy-agent: %s" CRLF CRLF,
2485                            ap_get_server_banner());
2486     apr_socket_send(backend->sock, buffer, &nbytes);
2487
2488     /* Receive the whole CONNECT response */
2489     left = sizeof(buffer) - 1;
2490     /* Read until we find the end of the headers or run out of buffer */
2491     do {
2492         nbytes = left;
2493         status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2494         len += nbytes;
2495         left -= nbytes;
2496         buffer[len] = '\0';
2497         if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2498             complete = 1;
2499             break;
2500         }
2501     } while (status == APR_SUCCESS && left > 0);
2502     /* Drain what's left */
2503     if (!complete) {
2504         nbytes = sizeof(drain_buffer) - 1;
2505         while (status == APR_SUCCESS && nbytes) {
2506             status = apr_socket_recv(backend->sock, drain_buffer, &nbytes);
2507             buffer[nbytes] = '\0';
2508             nbytes = sizeof(drain_buffer) - 1;
2509             if (strstr(drain_buffer, "\r\n\r\n") != NULL) {
2510                 break;
2511             }
2512         }
2513     }
2514
2515     /* Check for HTTP_OK response status */
2516     if (status == APR_SUCCESS) {
2517         int major, minor;
2518         /* Only scan for three character status code */
2519         char code_str[4];
2520
2521         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2522                      "send_http_connect: response from the forward proxy: %s",
2523                      buffer);
2524
2525         /* Extract the returned code */
2526         if (sscanf(buffer, "HTTP/%u.%u %3s", &major, &minor, code_str) == 3) {
2527             status = atoi(code_str);
2528             if (status == HTTP_OK) {
2529                 status = APR_SUCCESS;
2530             }
2531             else {
2532                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2533                              "send_http_connect: the forward proxy returned code is '%s'",
2534                              code_str);
2535             status = APR_INCOMPLETE;
2536             }
2537         }
2538     }
2539
2540     return(status);
2541 }
2542
2543
2544 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2545                                             proxy_conn_rec *conn,
2546                                             proxy_worker *worker,
2547                                             server_rec *s)
2548 {
2549     apr_status_t rv;
2550     int connected = 0;
2551     int loglevel;
2552     apr_sockaddr_t *backend_addr = conn->addr;
2553     /* the local address to use for the outgoing connection */
2554     apr_sockaddr_t *local_addr;
2555     apr_socket_t *newsock;
2556     void *sconf = s->module_config;
2557     proxy_server_conf *conf =
2558         (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2559
2560     if (conn->sock) {
2561         if (!(connected = is_socket_connected(conn->sock))) {
2562             socket_cleanup(conn);
2563             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2564                          "%s: backend socket is disconnected.",
2565                          proxy_function);
2566         }
2567     }
2568     while (backend_addr && !connected) {
2569         if ((rv = apr_socket_create(&newsock, backend_addr->family,
2570                                 SOCK_STREAM, APR_PROTO_TCP,
2571                                 conn->scpool)) != APR_SUCCESS) {
2572             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2573             ap_log_error(APLOG_MARK, loglevel, rv, s,
2574                          "%s: error creating fam %d socket for target %s",
2575                          proxy_function,
2576                          backend_addr->family,
2577                          worker->s->hostname);
2578             /*
2579              * this could be an IPv6 address from the DNS but the
2580              * local machine won't give us an IPv6 socket; hopefully the
2581              * DNS returned an additional address to try
2582              */
2583             backend_addr = backend_addr->next;
2584             continue;
2585         }
2586         conn->connection = NULL;
2587
2588         if (worker->s->recv_buffer_size > 0 &&
2589             (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2590                                      worker->s->recv_buffer_size))) {
2591             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2592                          "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2593                          "ProxyReceiveBufferSize, using default");
2594         }
2595
2596         rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2597         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2598              ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2599                           "apr_socket_opt_set(APR_TCP_NODELAY): "
2600                           "Failed to set");
2601         }
2602
2603         /* Set a timeout for connecting to the backend on the socket */
2604         if (worker->s->conn_timeout_set) {
2605             apr_socket_timeout_set(newsock, worker->s->conn_timeout);
2606         }
2607         else if (worker->s->timeout_set) {
2608             apr_socket_timeout_set(newsock, worker->s->timeout);
2609         }
2610         else if (conf->timeout_set) {
2611             apr_socket_timeout_set(newsock, conf->timeout);
2612         }
2613         else {
2614              apr_socket_timeout_set(newsock, s->timeout);
2615         }
2616         /* Set a keepalive option */
2617         if (worker->s->keepalive) {
2618             if ((rv = apr_socket_opt_set(newsock,
2619                             APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2620                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2621                              "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2622                              " Keepalive");
2623             }
2624         }
2625         ap_log_error(APLOG_MARK, APLOG_TRACE2, 0, s,
2626                      "%s: fam %d socket created to connect to %s",
2627                      proxy_function, backend_addr->family, worker->s->hostname);
2628
2629         if (conf->source_address_set) {
2630             local_addr = apr_pmemdup(conn->pool, conf->source_address,
2631                                      sizeof(apr_sockaddr_t));
2632             local_addr->pool = conn->pool;
2633             rv = apr_socket_bind(newsock, local_addr);
2634             if (rv != APR_SUCCESS) {
2635                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2636                     "%s: failed to bind socket to local address",
2637                     proxy_function);
2638             }
2639         }
2640
2641         /* make the connection out of the socket */
2642         rv = apr_socket_connect(newsock, backend_addr);
2643
2644         /* if an error occurred, loop round and try again */
2645         if (rv != APR_SUCCESS) {
2646             apr_socket_close(newsock);
2647             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2648             ap_log_error(APLOG_MARK, loglevel, rv, s,
2649                          "%s: attempt to connect to %pI (%s) failed",
2650                          proxy_function,
2651                          backend_addr,
2652                          worker->s->hostname);
2653             backend_addr = backend_addr->next;
2654             continue;
2655         }
2656
2657         /* Set a timeout on the socket */
2658         if (worker->s->timeout_set) {
2659             apr_socket_timeout_set(newsock, worker->s->timeout);
2660         }
2661         else if (conf->timeout_set) {
2662             apr_socket_timeout_set(newsock, conf->timeout);
2663         }
2664         else {
2665              apr_socket_timeout_set(newsock, s->timeout);
2666         }
2667
2668         conn->sock = newsock;
2669
2670         if (conn->forward) {
2671             forward_info *forward = (forward_info *)conn->forward;
2672             /*
2673              * For HTTP CONNECT we need to prepend CONNECT request before
2674              * sending our actual HTTPS requests.
2675              */
2676             if (forward->use_http_connect) {
2677                 rv = send_http_connect(conn, s);
2678                 /* If an error occurred, loop round and try again */
2679                 if (rv != APR_SUCCESS) {
2680                     conn->sock = NULL;
2681                     apr_socket_close(newsock);
2682                     loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2683                     ap_log_error(APLOG_MARK, loglevel, rv, s,
2684                                  "%s: attempt to connect to %s:%d "
2685                                  "via http CONNECT through %pI (%s) failed",
2686                                  proxy_function,
2687                                  forward->target_host, forward->target_port,
2688                                  backend_addr, worker->s->hostname);
2689                     backend_addr = backend_addr->next;
2690                     continue;
2691                 }
2692             }
2693         }
2694
2695         connected    = 1;
2696     }
2697     /*
2698      * Put the entire worker to error state if
2699      * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2700      * Altrough some connections may be alive
2701      * no further connections to the worker could be made
2702      */
2703     if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2704         !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2705         worker->s->error_time = apr_time_now();
2706         worker->s->status |= PROXY_WORKER_IN_ERROR;
2707         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2708             "ap_proxy_connect_backend disabling worker for (%s) for %"
2709             APR_TIME_T_FMT "s",
2710             worker->s->hostname, apr_time_sec(worker->s->retry));
2711     }
2712     else {
2713         if (worker->s->retries) {
2714             /*
2715              * A worker came back. So here is where we need to
2716              * either reset all params to initial conditions or
2717              * apply some sort of aging
2718              */
2719         }
2720         worker->s->error_time = 0;
2721         worker->s->retries = 0;
2722     }
2723     return connected ? OK : DECLINED;
2724 }
2725
2726 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2727                                               proxy_conn_rec *conn,
2728                                               conn_rec *c,
2729                                               server_rec *s)
2730 {
2731     apr_sockaddr_t *backend_addr = conn->addr;
2732     int rc;
2733     apr_interval_time_t current_timeout;
2734     apr_bucket_alloc_t *bucket_alloc;
2735
2736     if (conn->connection) {
2737         return OK;
2738     }
2739
2740     bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2741     /*
2742      * The socket is now open, create a new backend server connection
2743      */
2744     conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2745                                                 0, NULL,
2746                                                 bucket_alloc);
2747
2748     if (!conn->connection) {
2749         /*
2750          * the peer reset the connection already; ap_run_create_connection()
2751          * closed the socket
2752          */
2753         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2754                      s, "%s: an error occurred creating a "
2755                      "new connection to %pI (%s)", proxy_function,
2756                      backend_addr, conn->hostname);
2757         /* XXX: Will be closed when proxy_conn is closed */
2758         socket_cleanup(conn);
2759         return HTTP_INTERNAL_SERVER_ERROR;
2760     }
2761
2762     /* For ssl connection to backend */
2763     if (conn->is_ssl) {
2764         if (!ap_proxy_ssl_enable(conn->connection)) {
2765             ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2766                          s, "%s: failed to enable ssl support "
2767                          "for %pI (%s)", proxy_function,
2768                          backend_addr, conn->hostname);
2769             return HTTP_INTERNAL_SERVER_ERROR;
2770         }
2771     }
2772     else {
2773         /* TODO: See if this will break FTP */
2774         ap_proxy_ssl_disable(conn->connection);
2775     }
2776
2777     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2778                  "%s: connection complete to %pI (%s)",
2779                  proxy_function, backend_addr, conn->hostname);
2780
2781     /*
2782      * save the timeout of the socket because core_pre_connection
2783      * will set it to base_server->timeout
2784      * (core TimeOut directive).
2785      */
2786     apr_socket_timeout_get(conn->sock, &current_timeout);
2787     /* set up the connection filters */
2788     rc = ap_run_pre_connection(conn->connection, conn->sock);
2789     if (rc != OK && rc != DONE) {
2790         conn->connection->aborted = 1;
2791         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2792                      "%s: pre_connection setup failed (%d)",
2793                      proxy_function, rc);
2794         return rc;
2795     }
2796     apr_socket_timeout_set(conn->sock, current_timeout);
2797
2798     return OK;
2799 }
2800
2801 int ap_proxy_lb_workers(void)
2802 {
2803     /*
2804      * Since we can't resize the scoreboard when reconfiguring, we
2805      * have to impose a limit on the number of workers, we are
2806      * able to reconfigure to.
2807      */
2808     if (!lb_workers_limit)
2809         lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2810     return lb_workers_limit;
2811 }
2812
2813 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2814                                            apr_bucket_brigade *brigade)
2815 {
2816     apr_bucket *e;
2817     conn_rec *c = r->connection;
2818
2819     r->no_cache = 1;
2820     /*
2821      * If this is a subrequest, then prevent also caching of the main
2822      * request.
2823      */
2824     if (r->main)
2825         r->main->no_cache = 1;
2826     e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2827                                c->bucket_alloc);
2828     APR_BRIGADE_INSERT_TAIL(brigade, e);
2829     e = apr_bucket_eos_create(c->bucket_alloc);
2830     APR_BRIGADE_INSERT_TAIL(brigade, e);
2831 }
2832
2833 /*
2834  * Transform buckets from one bucket allocator to another one by creating a
2835  * transient bucket for each data bucket and let it use the data read from
2836  * the old bucket. Metabuckets are transformed by just recreating them.
2837  * Attention: Currently only the following bucket types are handled:
2838  *
2839  * All data buckets
2840  * FLUSH
2841  * EOS
2842  *
2843  * If an other bucket type is found its type is logged as a debug message
2844  * and APR_EGENERAL is returned.
2845  */
2846 PROXY_DECLARE(apr_status_t)
2847 ap_proxy_buckets_lifetime_transform(request_rec *r, apr_bucket_brigade *from,
2848                                     apr_bucket_brigade *to)
2849 {
2850     apr_bucket *e;
2851     apr_bucket *new;
2852     const char *data;
2853     apr_size_t bytes;
2854     apr_status_t rv = APR_SUCCESS;
2855
2856     apr_brigade_cleanup(to);
2857     for (e = APR_BRIGADE_FIRST(from);
2858          e != APR_BRIGADE_SENTINEL(from);
2859          e = APR_BUCKET_NEXT(e)) {
2860         if (!APR_BUCKET_IS_METADATA(e)) {
2861             apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
2862             new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
2863             APR_BRIGADE_INSERT_TAIL(to, new);
2864         }
2865         else if (APR_BUCKET_IS_FLUSH(e)) {
2866             new = apr_bucket_flush_create(r->connection->bucket_alloc);
2867             APR_BRIGADE_INSERT_TAIL(to, new);
2868         }
2869         else if (APR_BUCKET_IS_EOS(e)) {
2870             new = apr_bucket_eos_create(r->connection->bucket_alloc);
2871             APR_BRIGADE_INSERT_TAIL(to, new);
2872         }
2873         else {
2874             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2875                           "Unhandled bucket type of type %s in"
2876                           " ap_proxy_buckets_lifetime_transform", e->type->name);
2877             apr_bucket_delete(e);
2878             rv = APR_EGENERAL;
2879         }
2880     }
2881     return rv;
2882 }
2883
2884 /*
2885  * Provide a string hashing function for the proxy.
2886  * We offer 2 methods: one is the APR model but we
2887  * also provide our own, based on either FNV or SDBM.
2888  * The reason is in case we want to use both to ensure no
2889  * collisions.
2890  */
2891 PROXY_DECLARE(unsigned int)
2892 ap_proxy_hashfunc(const char *str, proxy_hash_t method)
2893 {
2894     if (method == PROXY_HASHFUNC_APR) {
2895         apr_ssize_t slen = strlen(str);
2896         return apr_hashfunc_default(str, &slen);
2897     }
2898     else if (method == PROXY_HASHFUNC_FNV) {
2899         /* FNV model */
2900         unsigned int hash;
2901         const unsigned int fnv_prime = 0x811C9DC5;
2902         for (hash = 0; *str; str++) {
2903             hash *= fnv_prime;
2904             hash ^= (*str);
2905         }
2906         return hash;
2907     }
2908     else { /* method == PROXY_HASHFUNC_DEFAULT */
2909         /* SDBM model */
2910         unsigned int hash;
2911         for (hash = 0; *str; str++) {
2912             hash = (*str) + (hash << 6) + (hash << 16) - hash;
2913         }
2914         return hash;
2915     }
2916 }
2917
2918 PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w)
2919 {
2920     unsigned int *status = &w->s->status;
2921     char flag = toupper(c);
2922     struct wstat *pwt = wstat_tbl;
2923     while (pwt->bit) {
2924         if (flag == pwt->flag) {
2925             if (set)
2926                 *status |= pwt->bit;
2927             else
2928                 *status &= ~(pwt->bit);
2929             return APR_SUCCESS;
2930         }
2931         pwt++;
2932     }
2933     return APR_EINVAL;
2934 }
2935
2936 PROXY_DECLARE(char *) ap_proxy_parse_wstatus(apr_pool_t *p, proxy_worker *w)
2937 {
2938     char *ret = "";
2939     unsigned int status = w->s->status;
2940     struct wstat *pwt = wstat_tbl;
2941     while (pwt->bit) {
2942         if (status & pwt->bit)
2943             ret = apr_pstrcat(p, ret, pwt->name, NULL);
2944         pwt++;
2945     }
2946     if (PROXY_WORKER_IS_USABLE(w))
2947         ret = apr_pstrcat(p, ret, "Ok ", NULL);
2948     return ret;
2949 }
2950
2951 PROXY_DECLARE(apr_status_t) ap_proxy_sync_balancer(proxy_balancer *b, server_rec *s,
2952                                                     proxy_server_conf *conf)
2953 {
2954     proxy_worker **workers;
2955     int i;
2956     int index;
2957     proxy_worker_shared *shm;
2958     proxy_balancer_method *lbmethod;
2959     ap_slotmem_provider_t *storage = b->storage;
2960
2961     if (b->s->wupdated <= b->wupdated)
2962         return APR_SUCCESS;
2963     /* balancer sync */
2964     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, b->s->lbpname, "0");
2965     if (lbmethod) {
2966         b->lbmethod = lbmethod;
2967     }
2968     /* worker sync */
2969
2970     /*
2971      * Look thru the list of workers in shm
2972      * and see which one(s) we are lacking...
2973      * again, the cast to unsigned int is safe
2974      * since our upper limit is always max_workers
2975      * which is int.
2976      */
2977     for (index = 0; index < b->max_workers; index++) {
2978         int found;
2979         apr_status_t rv;
2980         if ((rv = storage->dptr(b->wslot, (unsigned int)index, (void *)&shm)) != APR_SUCCESS) {
2981             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "worker slotmem_dptr failed");
2982             return APR_EGENERAL;
2983         }
2984         /* account for possible "holes" in the slotmem
2985          * (eg: slots 0-2 are used, but 3 isn't, but 4-5 is)
2986          */
2987         if (!shm->hash)
2988             continue;
2989         found = 0;
2990         workers = (proxy_worker **)b->workers->elts;
2991         for (i = 0; i < b->workers->nelts; i++, workers++) {
2992             proxy_worker *worker = *workers;
2993             if (worker->hash == shm->hash) {
2994                 found = 1;
2995                 break;
2996             }
2997         }
2998         if (!found) {
2999             proxy_worker **runtime;
3000             runtime = apr_array_push(b->workers);
3001             *runtime = apr_palloc(conf->pool, sizeof(proxy_worker));
3002             (*runtime)->hash = shm->hash;
3003             (*runtime)->context = NULL;
3004             (*runtime)->cp = NULL;
3005             (*runtime)->balancer = b;
3006             (*runtime)->s = shm;
3007             (*runtime)->tmutex = NULL;
3008             if ((rv = ap_proxy_initialize_worker(*runtime, s, conf->pool)) != APR_SUCCESS) {
3009                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Cannot init worker");
3010                 return rv;
3011             }
3012         }
3013     }
3014     if (b->s->need_reset) {
3015         if (b->lbmethod && b->lbmethod->reset)
3016             b->lbmethod->reset(b, s);
3017         b->s->need_reset = 0;
3018     }
3019     b->wupdated = b->s->wupdated;
3020     return APR_SUCCESS;
3021 }
3022