]> granicus.if.org Git - apache/blob - modules/proxy/proxy_util.c
I wondered why I never saw the scoreboard init entry; now I know.
[apache] / modules / proxy / proxy_util.c
1 /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
2  * applicable.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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
23 #if APR_HAVE_UNISTD_H
24 #include <unistd.h>         /* for getpid() */
25 #endif
26
27 #if (APR_MAJOR_VERSION < 1)
28 #undef apr_socket_create
29 #define apr_socket_create apr_socket_create_ex
30 #endif
31
32 /* Global balancer counter */
33 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
34 static int lb_workers_limit = 0;
35
36 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
37 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
38 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
39 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
40
41 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
42                                    (request_rec *r, request_rec *pr), (r, pr),
43                                    OK, DECLINED)
44
45 /* already called in the knowledge that the characters are hex digits */
46 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
47 {
48     int i, ch;
49
50 #if !APR_CHARSET_EBCDIC
51     ch = x[0];
52     if (apr_isdigit(ch))
53     i = ch - '0';
54     else if (apr_isupper(ch))
55     i = ch - ('A' - 10);
56     else
57     i = ch - ('a' - 10);
58     i <<= 4;
59
60     ch = x[1];
61     if (apr_isdigit(ch))
62     i += ch - '0';
63     else if (apr_isupper(ch))
64     i += ch - ('A' - 10);
65     else
66     i += ch - ('a' - 10);
67     return i;
68 #else /*APR_CHARSET_EBCDIC*/
69     /*
70      * we assume that the hex value refers to an ASCII character
71      * so convert to EBCDIC so that it makes sense locally;
72      *
73      * example:
74      *
75      * client specifies %20 in URL to refer to a space char;
76      * at this point we're called with EBCDIC "20"; after turning
77      * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
78      * represents an ASCII char and convert 0x20 to EBCDIC, yielding
79      * 0x40
80      */
81     char buf[1];
82
83     if (1 == sscanf(x, "%2x", &i)) {
84         buf[0] = i & 0xFF;
85         ap_xlate_proto_from_ascii(buf, 1);
86         return buf[0];
87     }
88     else {
89         return 0;
90     }
91 #endif /*APR_CHARSET_EBCDIC*/
92 }
93
94 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
95 {
96 #if !APR_CHARSET_EBCDIC
97     int i;
98
99     x[0] = '%';
100     i = (ch & 0xF0) >> 4;
101     if (i >= 10)
102     x[1] = ('A' - 10) + i;
103     else
104     x[1] = '0' + i;
105
106     i = ch & 0x0F;
107     if (i >= 10)
108     x[2] = ('A' - 10) + i;
109     else
110     x[2] = '0' + i;
111 #else /*APR_CHARSET_EBCDIC*/
112     static const char ntoa[] = { "0123456789ABCDEF" };
113     char buf[1];
114
115     ch &= 0xFF;
116
117     buf[0] = ch;
118     ap_xlate_proto_to_ascii(buf, 1);
119
120     x[0] = '%';
121     x[1] = ntoa[(buf[0] >> 4) & 0x0F];
122     x[2] = ntoa[buf[0] & 0x0F];
123     x[3] = '\0';
124 #endif /*APR_CHARSET_EBCDIC*/
125 }
126
127 /*
128  * canonicalise a URL-encoded string
129  */
130
131 /*
132  * Convert a URL-encoded string to canonical form.
133  * It decodes characters which need not be encoded,
134  * and encodes those which must be encoded, and does not touch
135  * those which must not be touched.
136  */
137 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len, enum enctype t,
138     int forcedec, int proxyreq)
139 {
140     int i, j, ch;
141     char *y;
142     char *allowed;  /* characters which should not be encoded */
143     char *reserved; /* characters which much not be en/de-coded */
144
145 /*
146  * N.B. in addition to :@&=, this allows ';' in an http path
147  * and '?' in an ftp path -- this may be revised
148  *
149  * Also, it makes a '+' character in a search string reserved, as
150  * it may be form-encoded. (Although RFC 1738 doesn't allow this -
151  * it only permits ; / ? : @ = & as reserved chars.)
152  */
153     if (t == enc_path)
154     allowed = "$-_.+!*'(),;:@&=";
155     else if (t == enc_search)
156     allowed = "$-_.!*'(),;:@&=";
157     else if (t == enc_user)
158     allowed = "$-_.+!*'(),;@&=";
159     else if (t == enc_fpath)
160     allowed = "$-_.+!*'(),?:@&=";
161     else            /* if (t == enc_parm) */
162     allowed = "$-_.+!*'(),?/:@&=";
163
164     if (t == enc_path)
165     reserved = "/";
166     else if (t == enc_search)
167     reserved = "+";
168     else
169     reserved = "";
170
171     y = apr_palloc(p, 3 * len + 1);
172
173     for (i = 0, j = 0; i < len; i++, j++) {
174 /* always handle '/' first */
175     ch = x[i];
176     if (strchr(reserved, ch)) {
177         y[j] = ch;
178         continue;
179     }
180 /*
181  * decode it if not already done. do not decode reverse proxied URLs
182  * unless specifically forced
183  */
184     if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
185         if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2]))
186         return NULL;
187         ch = ap_proxy_hex2c(&x[i + 1]);
188         i += 2;
189         if (ch != 0 && strchr(reserved, ch)) {  /* keep it encoded */
190         ap_proxy_c2hex(ch, &y[j]);
191         j += 2;
192         continue;
193         }
194     }
195 /* recode it, if necessary */
196     if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
197         ap_proxy_c2hex(ch, &y[j]);
198         j += 2;
199     }
200     else
201         y[j] = ch;
202     }
203     y[j] = '\0';
204     return y;
205 }
206
207 /*
208  * Parses network-location.
209  *    urlp           on input the URL; on output the path, after the leading /
210  *    user           NULL if no user/password permitted
211  *    password       holder for password
212  *    host           holder for host
213  *    port           port number; only set if one is supplied.
214  *
215  * Returns an error string.
216  */
217 PROXY_DECLARE(char *)
218      ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
219             char **passwordp, char **hostp, apr_port_t *port)
220 {
221     char *addr, *scope_id, *strp, *host, *url = *urlp;
222     char *user = NULL, *password = NULL;
223     apr_port_t tmp_port;
224     apr_status_t rv;
225
226     if (url[0] != '/' || url[1] != '/')
227     return "Malformed URL";
228     host = url + 2;
229     url = strchr(host, '/');
230     if (url == NULL)
231     url = "";
232     else
233     *(url++) = '\0';    /* skip seperating '/' */
234
235     /* find _last_ '@' since it might occur in user/password part */
236     strp = strrchr(host, '@');
237
238     if (strp != NULL) {
239     *strp = '\0';
240     user = host;
241     host = strp + 1;
242
243 /* find password */
244     strp = strchr(user, ':');
245     if (strp != NULL) {
246         *strp = '\0';
247         password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
248         if (password == NULL)
249         return "Bad %-escape in URL (password)";
250     }
251
252     user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
253     if (user == NULL)
254         return "Bad %-escape in URL (username)";
255     }
256     if (userp != NULL) {
257     *userp = user;
258     }
259     if (passwordp != NULL) {
260     *passwordp = password;
261     }
262
263     /*
264      * Parse the host string to separate host portion from optional port.
265      * Perform range checking on port.
266      */
267     rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
268     if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
269         return "Invalid host/port";
270     }
271     if (tmp_port != 0) { /* only update caller's port if port was specified */
272         *port = tmp_port;
273     }
274
275     ap_str_tolower(addr); /* DNS names are case-insensitive */
276
277     *urlp = url;
278     *hostp = addr;
279
280     return NULL;
281 }
282
283 static const char * const lwday[7] =
284 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
285
286 /*
287  * If the date is a valid RFC 850 date or asctime() date, then it
288  * is converted to the RFC 1123 format, otherwise it is not modified.
289  * This routine is not very fast at doing conversions, as it uses
290  * sscanf and sprintf. However, if the date is already correctly
291  * formatted, then it exits very quickly.
292  */
293 PROXY_DECLARE(const char *)
294      ap_proxy_date_canon(apr_pool_t *p, const char *x1)
295 {
296     char *x = apr_pstrdup(p, x1);
297     int wk, mday, year, hour, min, sec, mon;
298     char *q, month[4], zone[4], week[4];
299
300     q = strchr(x, ',');
301     /* check for RFC 850 date */
302     if (q != NULL && q - x > 3 && q[1] == ' ') {
303     *q = '\0';
304     for (wk = 0; wk < 7; wk++)
305         if (strcmp(x, lwday[wk]) == 0)
306         break;
307     *q = ',';
308     if (wk == 7)
309         return x;       /* not a valid date */
310     if (q[4] != '-' || q[8] != '-' || q[11] != ' ' || q[14] != ':' ||
311         q[17] != ':' || strcmp(&q[20], " GMT") != 0)
312         return x;
313     if (sscanf(q + 2, "%u-%3s-%u %u:%u:%u %3s", &mday, month, &year,
314            &hour, &min, &sec, zone) != 7)
315         return x;
316     if (year < 70)
317         year += 2000;
318     else
319         year += 1900;
320     }
321     else {
322 /* check for acstime() date */
323     if (x[3] != ' ' || x[7] != ' ' || x[10] != ' ' || x[13] != ':' ||
324         x[16] != ':' || x[19] != ' ' || x[24] != '\0')
325         return x;
326     if (sscanf(x, "%3s %3s %u %u:%u:%u %u", week, month, &mday, &hour,
327            &min, &sec, &year) != 7)
328         return x;
329     for (wk = 0; wk < 7; wk++)
330         if (strcmp(week, apr_day_snames[wk]) == 0)
331         break;
332     if (wk == 7)
333         return x;
334     }
335
336 /* check date */
337     for (mon = 0; mon < 12; mon++)
338     if (strcmp(month, apr_month_snames[mon]) == 0)
339         break;
340     if (mon == 12)
341     return x;
342
343     q = apr_palloc(p, 30);
344     apr_snprintf(q, 30, "%s, %.2d %s %d %.2d:%.2d:%.2d GMT", apr_day_snames[wk],
345        mday, apr_month_snames[mon], year, hour, min, sec);
346     return q;
347 }
348
349 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
350 {
351     request_rec *rp = apr_pcalloc(c->pool, sizeof(*r));
352
353     rp->pool            = c->pool;
354     rp->status          = HTTP_OK;
355
356     rp->headers_in      = apr_table_make(c->pool, 50);
357     rp->subprocess_env  = apr_table_make(c->pool, 50);
358     rp->headers_out     = apr_table_make(c->pool, 12);
359     rp->err_headers_out = apr_table_make(c->pool, 5);
360     rp->notes           = apr_table_make(c->pool, 5);
361
362     rp->server = r->server;
363     rp->proxyreq = r->proxyreq;
364     rp->request_time = r->request_time;
365     rp->connection      = c;
366     rp->output_filters  = c->output_filters;
367     rp->input_filters   = c->input_filters;
368     rp->proto_output_filters  = c->output_filters;
369     rp->proto_input_filters   = c->input_filters;
370
371     rp->request_config  = ap_create_request_config(c->pool);
372     proxy_run_create_req(r, rp);
373
374     return rp;
375 }
376
377
378 /*
379  * list is a comma-separated list of case-insensitive tokens, with
380  * optional whitespace around the tokens.
381  * The return returns 1 if the token val is found in the list, or 0
382  * otherwise.
383  */
384 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
385 {
386     int len, i;
387     const char *p;
388
389     len = strlen(val);
390
391     while (list != NULL) {
392     p = ap_strchr_c(list, ',');
393     if (p != NULL) {
394         i = p - list;
395         do
396         p++;
397         while (apr_isspace(*p));
398     }
399     else
400         i = strlen(list);
401
402     while (i > 0 && apr_isspace(list[i - 1]))
403         i--;
404     if (i == len && strncasecmp(list, val, len) == 0)
405         return 1;
406     list = p;
407     }
408     return 0;
409 }
410
411 /*
412  * list is a comma-separated list of case-insensitive tokens, with
413  * optional whitespace around the tokens.
414  * if val appears on the list of tokens, it is removed from the list,
415  * and the new list is returned.
416  */
417 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
418 {
419     int len, i;
420     const char *p;
421     char *new = NULL;
422
423     len = strlen(val);
424
425     while (list != NULL) {
426     p = ap_strchr_c(list, ',');
427     if (p != NULL) {
428         i = p - list;
429         do
430         p++;
431         while (apr_isspace(*p));
432     }
433     else
434         i = strlen(list);
435
436     while (i > 0 && apr_isspace(list[i - 1]))
437         i--;
438     if (i == len && strncasecmp(list, val, len) == 0) {
439         /* do nothing */
440     }
441     else {
442         if (new)
443         new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
444         else
445         new = apr_pstrndup(pool, list, i);
446     }
447     list = p;
448     }
449     return new;
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     else if (apr_isupper(ch))
466         j |= ch - ('A' - 10);
467     else
468         j |= ch - ('a' - 10);
469     }
470     if (j == 0xffffffff)
471     return -1;      /* so that it works with 8-byte ints */
472     else
473     return j;
474 }
475
476 /*
477  * Converts a time integer to 8 hex digits
478  */
479 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
480 {
481     int i, ch;
482     unsigned int j = t;
483
484     for (i = 7; i >= 0; i--) {
485     ch = j & 0xF;
486     j >>= 4;
487     if (ch >= 10)
488         y[i] = ch + ('A' - 10);
489     else
490         y[i] = ch + '0';
491     }
492     y[8] = '\0';
493 }
494
495 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
496 {
497     apr_table_setn(r->notes, "error-notes",
498     apr_pstrcat(r->pool,
499         "The proxy server could not handle the request "
500         "<em><a href=\"", ap_escape_uri(r->pool, r->uri),
501         "\">", ap_escape_html(r->pool, r->method),
502         "&nbsp;",
503         ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
504         "Reason: <strong>",
505         ap_escape_html(r->pool, message),
506         "</strong></p>", NULL));
507
508     /* Allow "error-notes" string to be printed by ap_send_error_response() */
509     apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
510
511     r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
512     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
513              "proxy: %s returned by %s", message, r->uri);
514     return statuscode;
515 }
516
517 static const char *
518      proxy_get_host_of_request(request_rec *r)
519 {
520     char *url, *user = NULL, *password = NULL, *err, *host;
521     apr_port_t port;
522
523     if (r->hostname != NULL)
524     return r->hostname;
525
526     /* Set url to the first char after "scheme://" */
527     if ((url = strchr(r->uri, ':')) == NULL
528     || url[1] != '/' || url[2] != '/')
529     return NULL;
530
531     url = apr_pstrdup(r->pool, &url[1]);    /* make it point to "//", which is what proxy_canon_netloc expects */
532
533     err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
534
535     if (err != NULL)
536     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
537              "%s", err);
538
539     r->hostname = host;
540
541     return host;        /* ought to return the port, too */
542 }
543
544 /* Return TRUE if addr represents an IP address (or an IP network address) */
545 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
546 {
547     const char *addr = This->name;
548     long ip_addr[4];
549     int i, quads;
550     long bits;
551
552     /*
553      * if the address is given with an explicit netmask, use that
554      * Due to a deficiency in apr_inet_addr(), it is impossible to parse
555      * "partial" addresses (with less than 4 quads) correctly, i.e.
556      * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
557      * I therefore have to parse the IP address manually:
558      * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
559      * addr and mask were set by proxy_readmask()
560      * return 1;
561      */
562
563     /*
564      * Parse IP addr manually, optionally allowing
565      * abbreviated net addresses like 192.168.
566      */
567
568     /* Iterate over up to 4 (dotted) quads. */
569     for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
570     char *tmp;
571
572     if (*addr == '/' && quads > 0)  /* netmask starts here. */
573         break;
574
575     if (!apr_isdigit(*addr))
576         return 0;       /* no digit at start of quad */
577
578     ip_addr[quads] = strtol(addr, &tmp, 0);
579
580     if (tmp == addr)    /* expected a digit, found something else */
581         return 0;
582
583     if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
584         /* invalid octet */
585         return 0;
586     }
587
588     addr = tmp;
589
590     if (*addr == '.' && quads != 3)
591         ++addr;     /* after the 4th quad, a dot would be illegal */
592     }
593
594     for (This->addr.s_addr = 0, i = 0; i < quads; ++i)
595     This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
596
597     if (addr[0] == '/' && apr_isdigit(addr[1])) {   /* net mask follows: */
598     char *tmp;
599
600     ++addr;
601
602     bits = strtol(addr, &tmp, 0);
603
604     if (tmp == addr)    /* expected a digit, found something else */
605         return 0;
606
607     addr = tmp;
608
609     if (bits < 0 || bits > 32)  /* netmask must be between 0 and 32 */
610         return 0;
611
612     }
613     else {
614     /*
615      * Determine (i.e., "guess") netmask by counting the
616      * number of trailing .0's; reduce #quads appropriately
617      * (so that 192.168.0.0 is equivalent to 192.168.)
618      */
619     while (quads > 0 && ip_addr[quads - 1] == 0)
620         --quads;
621
622     /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
623     if (quads < 1)
624         return 0;
625
626     /* every zero-byte counts as 8 zero-bits */
627     bits = 8 * quads;
628
629     if (bits != 32)     /* no warning for fully qualified IP address */
630             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
631           "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
632          inet_ntoa(This->addr), bits);
633     }
634
635     This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
636
637     if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
638         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
639         "Warning: NetMask and IP-Addr disagree in %s/%ld",
640         inet_ntoa(This->addr), bits);
641     This->addr.s_addr &= This->mask.s_addr;
642         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
643         "         Set to %s/%ld",
644         inet_ntoa(This->addr), bits);
645     }
646
647     if (*addr == '\0') {
648     This->matcher = proxy_match_ipaddr;
649     return 1;
650     }
651     else
652     return (*addr == '\0'); /* okay iff we've parsed the whole string */
653 }
654
655 /* Return TRUE if addr represents an IP address (or an IP network address) */
656 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
657 {
658     int i, ip_addr[4];
659     struct in_addr addr, *ip;
660     const char *host = proxy_get_host_of_request(r);
661
662     if (host == NULL)   /* oops! */
663        return 0;
664
665     memset(&addr, '\0', sizeof addr);
666     memset(ip_addr, '\0', sizeof ip_addr);
667
668     if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
669     for (addr.s_addr = 0, i = 0; i < 4; ++i)
670         addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
671
672     if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
673 #if DEBUGGING
674         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
675                          "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
676         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
677                          "%s/", inet_ntoa(This->addr));
678         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
679                          "%s", inet_ntoa(This->mask));
680 #endif
681         return 1;
682     }
683 #if DEBUGGING
684     else {
685         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
686                          "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
687         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
688                          "%s/", inet_ntoa(This->addr));
689         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
690                          "%s", inet_ntoa(This->mask));
691     }
692 #endif
693     }
694     else {
695     struct apr_sockaddr_t *reqaddr;
696
697         if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
698         != APR_SUCCESS) {
699 #if DEBUGGING
700         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701              "2)IP-NoMatch: hostname=%s msg=Host not found",
702              host);
703 #endif
704         return 0;
705     }
706
707     /* Try to deal with multiple IP addr's for a host */
708     /* FIXME: This needs to be able to deal with IPv6 */
709     while (reqaddr) {
710         ip = (struct in_addr *) reqaddr->ipaddr_ptr;
711         if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
712 #if DEBUGGING
713         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
714                  "3)IP-Match: %s[%s] <-> ", host,
715                  inet_ntoa(*ip));
716         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
717                  "%s/", inet_ntoa(This->addr));
718         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
719                  "%s", inet_ntoa(This->mask));
720 #endif
721         return 1;
722         }
723 #if DEBUGGING
724         else {
725                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
726                  "3)IP-NoMatch: %s[%s] <-> ", host,
727                  inet_ntoa(*ip));
728                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
729                  "%s/", inet_ntoa(This->addr));
730                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
731                  "%s", inet_ntoa(This->mask));
732         }
733 #endif
734         reqaddr = reqaddr->next;
735     }
736     }
737
738     return 0;
739 }
740
741 /* Return TRUE if addr represents a domain name */
742 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
743 {
744     char *addr = This->name;
745     int i;
746
747     /* Domain name must start with a '.' */
748     if (addr[0] != '.')
749         return 0;
750
751     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
752     for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i)
753         continue;
754
755 #if 0
756     if (addr[i] == ':') {
757     ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
758                      "@@@@ handle optional port in proxy_is_domainname()");
759     /* @@@@ handle optional port */
760     }
761 #endif
762
763     if (addr[i] != '\0')
764         return 0;
765
766     /* Strip trailing dots */
767     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i)
768         addr[i] = '\0';
769
770     This->matcher = proxy_match_domainname;
771     return 1;
772 }
773
774 /* Return TRUE if host "host" is in domain "domain" */
775 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
776 {
777     const char *host = proxy_get_host_of_request(r);
778     int d_len = strlen(This->name), h_len;
779
780     if (host == NULL)       /* some error was logged already */
781         return 0;
782
783     h_len = strlen(host);
784
785     /* @@@ do this within the setup? */
786     /* Ignore trailing dots in domain comparison: */
787     while (d_len > 0 && This->name[d_len - 1] == '.')
788         --d_len;
789     while (h_len > 0 && host[h_len - 1] == '.')
790         --h_len;
791     return h_len > d_len
792         && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
793 }
794
795 /* Return TRUE if host represents a host name */
796 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
797 {
798     struct apr_sockaddr_t *addr;
799     char *host = This->name;
800     int i;
801
802     /* Host names must not start with a '.' */
803     if (host[0] == '.')
804         return 0;
805
806     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
807     for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
808
809     if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS)
810         return 0;
811
812     This->hostaddr = addr;
813
814     /* Strip trailing dots */
815     for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i)
816         host[i] = '\0';
817
818     This->matcher = proxy_match_hostname;
819     return 1;
820 }
821
822 /* Return TRUE if host "host" is equal to host2 "host2" */
823 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
824 {
825     char *host = This->name;
826     const char *host2 = proxy_get_host_of_request(r);
827     int h2_len;
828     int h1_len;
829
830     if (host == NULL || host2 == NULL)
831         return 0; /* oops! */
832
833     h2_len = strlen(host2);
834     h1_len = strlen(host);
835
836 #if 0
837     struct apr_sockaddr_t *addr = *This->hostaddr;
838
839     /* Try to deal with multiple IP addr's for a host */
840     while (addr) {
841         if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
842             return 1;
843         addr = addr->next;
844     }
845 #endif
846
847     /* Ignore trailing dots in host2 comparison: */
848     while (h2_len > 0 && host2[h2_len - 1] == '.')
849         --h2_len;
850     while (h1_len > 0 && host[h1_len - 1] == '.')
851         --h1_len;
852     return h1_len == h2_len
853         && strncasecmp(host, host2, h1_len) == 0;
854 }
855
856 /* Return TRUE if addr is to be matched as a word */
857 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
858 {
859     This->matcher = proxy_match_word;
860     return 1;
861 }
862
863 /* Return TRUE if string "str2" occurs literally in "str1" */
864 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
865 {
866     const char *host = proxy_get_host_of_request(r);
867     return host != NULL && ap_strstr_c(host, This->name) != NULL;
868 }
869
870 /* checks whether a host in uri_addr matches proxyblock */
871 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
872                              apr_sockaddr_t *uri_addr)
873 {
874     int j;
875     apr_sockaddr_t * src_uri_addr = uri_addr;
876     /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
877     for (j = 0; j < conf->noproxies->nelts; j++) {
878         struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
879         struct apr_sockaddr_t *conf_addr = npent[j].addr;
880         uri_addr = src_uri_addr;
881         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
882                      "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
883         if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
884             || npent[j].name[0] == '*') {
885             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
886                          "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
887             return HTTP_FORBIDDEN;
888         }
889         while (conf_addr) {
890             while (uri_addr) {
891                 char *conf_ip;
892                 char *uri_ip;
893                 apr_sockaddr_ip_get(&conf_ip, conf_addr);
894                 apr_sockaddr_ip_get(&uri_ip, uri_addr);
895                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
896                              "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
897                 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
898                     ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
899                                  "proxy: connect to remote machine %s blocked: IP %s matched", uri_addr->hostname, conf_ip);
900                     return HTTP_FORBIDDEN;
901                 }
902                 uri_addr = uri_addr->next;
903             }
904             conf_addr = conf_addr->next;
905         }
906     }
907     return OK;
908 }
909
910 /* set up the minimal filter set */
911 PROXY_DECLARE(int) ap_proxy_pre_http_request(conn_rec *c, request_rec *r)
912 {
913     ap_add_input_filter("HTTP_IN", NULL, r, c);
914     return OK;
915 }
916
917 /*
918  * converts a series of buckets into a string
919  * XXX: BillS says this function performs essentially the same function as
920  * ap_rgetline() in protocol.c. Deprecate this function and use ap_rgetline()
921  * instead? I think ap_proxy_string_read() will not work properly on non ASCII
922  * (EBCDIC) machines either.
923  */
924 PROXY_DECLARE(apr_status_t) ap_proxy_string_read(conn_rec *c, apr_bucket_brigade *bb,
925                                                  char *buff, apr_size_t bufflen, int *eos)
926 {
927     apr_bucket *e;
928     apr_status_t rv;
929     char *pos = buff;
930     char *response;
931     int found = 0;
932     apr_size_t len;
933
934     /* start with an empty string */
935     buff[0] = 0;
936     *eos = 0;
937
938     /* loop through each brigade */
939     while (!found) {
940         /* get brigade from network one line at a time */
941         if (APR_SUCCESS != (rv = ap_get_brigade(c->input_filters, bb,
942                                                 AP_MODE_GETLINE,
943                                                 APR_BLOCK_READ,
944                                                 0))) {
945             return rv;
946         }
947         /* loop through each bucket */
948         while (!found) {
949             if (*eos || APR_BRIGADE_EMPTY(bb)) {
950                 /* The connection aborted or timed out */
951                 return APR_ECONNABORTED;
952             }
953             e = APR_BRIGADE_FIRST(bb);
954             if (APR_BUCKET_IS_EOS(e)) {
955                 *eos = 1;
956             }
957             else {
958                 if (APR_SUCCESS != apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ)) {
959                     return rv;
960                 }
961                 /*
962                  * is string LF terminated?
963                  * XXX: This check can be made more efficient by simply checking
964                  * if the last character in the 'response' buffer is an ASCII_LF.
965                  * See ap_rgetline() for an example.
966                  */
967                 if (memchr(response, APR_ASCII_LF, len)) {
968                     found = 1;
969                 }
970                 /* concat strings until buff is full - then throw the data away */
971                 if (len > ((bufflen-1)-(pos-buff))) {
972                     len = (bufflen-1)-(pos-buff);
973                 }
974                 if (len > 0) {
975                     pos = apr_cpystrn(pos, response, len);
976                 }
977             }
978             APR_BUCKET_REMOVE(e);
979             apr_bucket_destroy(e);
980         }
981     }
982
983     return APR_SUCCESS;
984 }
985
986 /* unmerge an element in the table */
987 PROXY_DECLARE(void) ap_proxy_table_unmerge(apr_pool_t *p, apr_table_t *t, char *key)
988 {
989     apr_off_t offset = 0;
990     apr_off_t count = 0;
991     char *value = NULL;
992
993     /* get the value to unmerge */
994     const char *initial = apr_table_get(t, key);
995     if (!initial) {
996         return;
997     }
998     value = apr_pstrdup(p, initial);
999
1000     /* remove the value from the headers */
1001     apr_table_unset(t, key);
1002
1003     /* find each comma */
1004     while (value[count]) {
1005         if (value[count] == ',') {
1006             value[count] = 0;
1007             apr_table_add(t, key, value + offset);
1008             offset = count + 1;
1009         }
1010         count++;
1011     }
1012     apr_table_add(t, key, value + offset);
1013 }
1014
1015 PROXY_DECLARE(const char *) ap_proxy_location_reverse_map(request_rec *r,
1016                               proxy_dir_conf *conf, const char *url)
1017 {
1018     struct proxy_alias *ent;
1019     int i, l1, l2;
1020     char *u;
1021
1022     /*
1023      * XXX FIXME: Make sure this handled the ambiguous case of the :<PORT>
1024      * after the hostname
1025      */
1026
1027     l1 = strlen(url);
1028     ent = (struct proxy_alias *)conf->raliases->elts;
1029     for (i = 0; i < conf->raliases->nelts; i++) {
1030         l2 = strlen(ent[i].real);
1031         if (l1 >= l2 && strncasecmp(ent[i].real, url, l2) == 0) {
1032             u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1033             return ap_construct_url(r->pool, u, r);
1034         }
1035     }
1036
1037     return url;
1038 }
1039
1040 /*
1041  * Cookies are a bit trickier to match: we've got two substrings to worry
1042  * about, and we can't just find them with strstr 'cos of case.  Regexp
1043  * matching would be an easy fix, but for better consistency with all the
1044  * other matches we'll refrain and use apr_strmatch to find path=/domain=
1045  * and stick to plain strings for the config values.
1046  */
1047 PROXY_DECLARE(const char *) ap_proxy_cookie_reverse_map(request_rec *r,
1048                               proxy_dir_conf *conf, const char *str)
1049 {
1050     struct proxy_alias *ent;
1051     size_t len = strlen(str);
1052     const char *newpath = NULL;
1053     const char *newdomain = NULL;
1054     const char *pathp;
1055     const char *domainp;
1056     const char *pathe = NULL;
1057     const char *domaine = NULL;
1058     size_t l1, l2, poffs = 0, doffs = 0;
1059     int i;
1060     int ddiff = 0;
1061     int pdiff = 0;
1062     char *ret;
1063
1064    /*
1065     * Find the match and replacement, but save replacing until we've done
1066     * both path and domain so we know the new strlen
1067     */
1068     if ((pathp = apr_strmatch(conf->cookie_path_str, str, len)) != NULL) {
1069         pathp += 5;
1070         poffs = pathp - str;
1071         pathe = ap_strchr_c(pathp, ';');
1072         l1 = pathe ? (pathe - pathp) : strlen(pathp);
1073         pathe = pathp + l1 ;
1074         ent = (struct proxy_alias *)conf->cookie_paths->elts;
1075         for (i = 0; i < conf->cookie_paths->nelts; i++) {
1076             l2 = strlen(ent[i].fake);
1077             if (l1 >= l2 && strncmp(ent[i].fake, pathp, l2) == 0) {
1078                 newpath = ent[i].real;
1079                 pdiff = strlen(newpath) - l1;
1080                 break;
1081             }
1082         }
1083     }
1084
1085     if ((domainp = apr_strmatch(conf->cookie_domain_str, str, len)) != NULL) {
1086         domainp += 7;
1087         doffs = domainp - str;
1088         domaine = ap_strchr_c(domainp, ';');
1089         l1 = domaine ? (domaine - domainp) : strlen(domainp);
1090         domaine = domainp + l1;
1091         ent = (struct proxy_alias *)conf->cookie_domains->elts;
1092         for (i = 0; i < conf->cookie_domains->nelts; i++) {
1093             l2 = strlen(ent[i].fake);
1094             if (l1 >= l2 && strncasecmp(ent[i].fake, domainp, l2) == 0) {
1095                 newdomain = ent[i].real;
1096                 ddiff = strlen(newdomain) - l1;
1097                 break;
1098             }
1099         }
1100     }
1101
1102     if (newpath) {
1103         ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1104         l1 = strlen(newpath);
1105         if (newdomain) {
1106             l2 = strlen(newdomain);
1107             if (doffs > poffs) {
1108                 memcpy(ret, str, poffs);
1109                 memcpy(ret + poffs, newpath, l1);
1110                 memcpy(ret + poffs + l1, pathe, domainp - pathe);
1111                 memcpy(ret + doffs + pdiff, newdomain, l2);
1112                 strcpy(ret + doffs + pdiff + l2, domaine);
1113             }
1114             else {
1115                 memcpy(ret, str, doffs) ;
1116                 memcpy(ret + doffs, newdomain, l2);
1117                 memcpy(ret + doffs + l2, domaine, pathp - domaine);
1118                 memcpy(ret + poffs + ddiff, newpath, l1);
1119                 strcpy(ret + poffs + ddiff + l1, pathe);
1120             }
1121         }
1122         else {
1123             memcpy(ret, str, poffs);
1124             memcpy(ret + poffs, newpath, l1);
1125             strcpy(ret + poffs + l1, pathe);
1126         }
1127     }
1128     else {
1129         if (newdomain) {
1130             ret = apr_palloc(r->pool, len + pdiff + ddiff + 1);
1131             l2 = strlen(newdomain);
1132             memcpy(ret, str, doffs);
1133             memcpy(ret + doffs, newdomain, l2);
1134             strcpy(ret + doffs+l2, domaine);
1135         }
1136         else {
1137             ret = (char *)str; /* no change */
1138         }
1139     }
1140
1141     return ret;
1142 }
1143
1144 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1145                                                       proxy_server_conf *conf,
1146                                                       const char *url)
1147 {
1148     proxy_balancer *balancer;
1149     char *c, *uri = apr_pstrdup(p, url);
1150     int i;
1151
1152     c = strchr(uri, ':');
1153     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1154        return NULL;
1155     /* remove path from uri */
1156     if ((c = strchr(c + 3, '/')))
1157         *c = '\0';
1158     balancer = (proxy_balancer *)conf->balancers->elts;
1159     for (i = 0; i < conf->balancers->nelts; i++) {
1160         if (strcasecmp(balancer->name, uri) == 0)
1161             return balancer;
1162         balancer++;
1163     }
1164     return NULL;
1165 }
1166
1167 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1168                                                   apr_pool_t *p,
1169                                                   proxy_server_conf *conf,
1170                                                   const char *url)
1171 {
1172     char *c, *q, *uri = apr_pstrdup(p, url);
1173     proxy_balancer_method *lbmethod;
1174
1175     c = strchr(uri, ':');
1176     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1177        return "Bad syntax for a balancer name";
1178     /* remove path from uri */
1179     if ((q = strchr(c + 3, '/')))
1180         *q = '\0';
1181
1182     ap_str_tolower(uri);
1183     *balancer = apr_array_push(conf->balancers);
1184     memset(*balancer, 0, sizeof(proxy_balancer));
1185
1186     /*
1187      * NOTE: The default method is byrequests, which we assume
1188      * exists!
1189      */
1190     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1191     if (!lbmethod) {
1192         return "Can't find 'byrequests' lb method";
1193     }
1194
1195     (*balancer)->name = uri;
1196     (*balancer)->lbmethod = lbmethod;
1197     (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker));
1198     /* XXX Is this a right place to create mutex */
1199 #if APR_HAS_THREADS
1200     if (apr_thread_mutex_create(&((*balancer)->mutex),
1201                 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1202         /* XXX: Do we need to log something here */
1203         return "can not create thread mutex";
1204     }
1205 #endif
1206
1207     return NULL;
1208 }
1209
1210 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1211                                                   proxy_server_conf *conf,
1212                                                   const char *url)
1213 {
1214     proxy_worker *worker;
1215     proxy_worker *max_worker = NULL;
1216     int max_match = 0;
1217     int url_length;
1218     int worker_name_length;
1219     const char *c;
1220     char *url_copy;
1221     int i;
1222
1223     c = ap_strchr_c(url, ':');
1224     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1225        return NULL;
1226
1227     url_copy = apr_pstrdup(p, url);
1228     url_length = strlen(url);
1229
1230     /*
1231      * We need to find the start of the path and
1232      * therefore we know the length of the scheme://hostname/
1233      * part to we can force-lowercase everything up to
1234      * the start of the path.
1235      */
1236     c = ap_strchr_c(c+3, '/');
1237     if (c) {
1238         char *pathstart;
1239         pathstart = url_copy + (c - url);
1240         *pathstart = '\0';
1241         ap_str_tolower(url_copy);
1242         *pathstart = '/';
1243     } else {
1244         ap_str_tolower(url_copy);
1245     }
1246
1247     worker = (proxy_worker *)conf->workers->elts;
1248
1249     /*
1250      * Do a "longest match" on the worker name to find the worker that
1251      * fits best to the URL.
1252      */
1253     for (i = 0; i < conf->workers->nelts; i++) {
1254         if ( ((worker_name_length = strlen(worker->name)) <= url_length)
1255            && (worker_name_length > max_match)
1256            && (strncmp(url_copy, worker->name, worker_name_length) == 0) ) {
1257             max_worker = worker;
1258             max_match = worker_name_length;
1259         }
1260         worker++;
1261     }
1262     return max_worker;
1263 }
1264
1265 #if APR_HAS_THREADS
1266 static apr_status_t conn_pool_cleanup(void *theworker)
1267 {
1268     proxy_worker *worker = (proxy_worker *)theworker;
1269     if (worker->cp->res) {
1270         worker->cp->pool = NULL;
1271         apr_reslist_destroy(worker->cp->res);
1272     }
1273     return APR_SUCCESS;
1274 }
1275 #endif
1276
1277 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1278 {
1279     apr_pool_t *pool;
1280     proxy_conn_pool *cp;
1281
1282     /*
1283      * Create a connection pool's subpool.
1284      * This pool is used for connection recycling.
1285      * Once the worker is added it is never removed but
1286      * it can be disabled.
1287      */
1288     apr_pool_create(&pool, p);
1289     /*
1290      * Alloc from the same pool as worker.
1291      * proxy_conn_pool is permanently attached to the worker.
1292      */
1293     cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1294     cp->pool = pool;
1295     worker->cp = cp;
1296 }
1297
1298 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1299                                                 apr_pool_t *p,
1300                                                 proxy_server_conf *conf,
1301                                                 const char *url)
1302 {
1303     int rv;
1304     apr_uri_t uri;
1305
1306     rv = apr_uri_parse(p, url, &uri);
1307
1308     if (rv != APR_SUCCESS) {
1309         return "Unable to parse URL";
1310     }
1311
1312     ap_str_tolower(uri.hostname);
1313     ap_str_tolower(uri.scheme);
1314     *worker = apr_array_push(conf->workers);
1315     memset(*worker, 0, sizeof(proxy_worker));
1316     (*worker)->name = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1317     (*worker)->scheme = uri.scheme;
1318     (*worker)->hostname = uri.hostname;
1319     (*worker)->port = uri.port;
1320     (*worker)->id   = proxy_lb_workers;
1321     /* Increase the total worker count */
1322     proxy_lb_workers++;
1323     init_conn_pool(p, *worker);
1324 #if APR_HAS_THREADS
1325     if (apr_thread_mutex_create(&((*worker)->mutex),
1326                 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1327         /* XXX: Do we need to log something here */
1328         return "can not create thread mutex";
1329     }
1330 #endif
1331
1332     return NULL;
1333 }
1334
1335 PROXY_DECLARE(proxy_worker *) ap_proxy_create_worker(apr_pool_t *p)
1336 {
1337
1338     proxy_worker *worker;
1339     worker = (proxy_worker *)apr_pcalloc(p, sizeof(proxy_worker));
1340     worker->id = proxy_lb_workers;
1341     /* Increase the total worker count */
1342     proxy_lb_workers++;
1343     init_conn_pool(p, worker);
1344
1345     return worker;
1346 }
1347
1348 PROXY_DECLARE(void)
1349 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer,
1350                                 proxy_worker *worker)
1351 {
1352     proxy_worker *runtime;
1353
1354     runtime = apr_array_push(balancer->workers);
1355     memcpy(runtime, worker, sizeof(proxy_worker));
1356     runtime->id = proxy_lb_workers;
1357     /* Increase the total runtime count */
1358     proxy_lb_workers++;
1359
1360 }
1361
1362 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1363                                         proxy_balancer **balancer,
1364                                         request_rec *r,
1365                                         proxy_server_conf *conf, char **url)
1366 {
1367     int access_status;
1368
1369     access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1370     if (access_status == DECLINED && *balancer == NULL) {
1371         *worker = ap_proxy_get_worker(r->pool, conf, *url);
1372         if (*worker) {
1373             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1374                           "proxy: %s: found worker %s for %s",
1375                            (*worker)->scheme, (*worker)->name, *url);
1376
1377             *balancer = NULL;
1378             access_status = OK;
1379         }
1380         else if (r->proxyreq == PROXYREQ_PROXY) {
1381             if (conf->forward) {
1382                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1383                               "proxy: *: found forward proxy worker for %s",
1384                                *url);
1385                 *balancer = NULL;
1386                 *worker = conf->forward;
1387                 access_status = OK;
1388             }
1389         }
1390         else if (r->proxyreq == PROXYREQ_REVERSE) {
1391             if (conf->reverse) {
1392                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1393                               "proxy: *: found reverse proxy worker for %s",
1394                                *url);
1395                 *balancer = NULL;
1396                 *worker = conf->reverse;
1397                 access_status = OK;
1398             }
1399         }
1400     }
1401     else if (access_status == DECLINED && *balancer != NULL) {
1402         /* All the workers are busy */
1403         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1404           "proxy: all workers are busy.  Unable to serve %s",
1405           *url);
1406         access_status = HTTP_SERVICE_UNAVAILABLE;
1407     }
1408     return access_status;
1409 }
1410
1411 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1412                                          proxy_balancer *balancer,
1413                                          request_rec *r,
1414                                          proxy_server_conf *conf)
1415 {
1416     int access_status;
1417     if (balancer)
1418         access_status = proxy_run_post_request(worker, balancer, r, conf);
1419     else {
1420
1421
1422         access_status = OK;
1423     }
1424
1425     return access_status;
1426 }
1427
1428 /* DEPRECATED */
1429 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1430                                                const char *proxy_function,
1431                                                apr_sockaddr_t *backend_addr,
1432                                                const char *backend_name,
1433                                                proxy_server_conf *conf,
1434                                                server_rec *s,
1435                                                apr_pool_t *p)
1436 {
1437     apr_status_t rv;
1438     int connected = 0;
1439     int loglevel;
1440
1441     while (backend_addr && !connected) {
1442         if ((rv = apr_socket_create(newsock, backend_addr->family,
1443                                     SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1444             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1445             ap_log_error(APLOG_MARK, loglevel, rv, s,
1446                          "proxy: %s: error creating fam %d socket for target %s",
1447                          proxy_function,
1448                          backend_addr->family,
1449                          backend_name);
1450             /*
1451              * this could be an IPv6 address from the DNS but the
1452              * local machine won't give us an IPv6 socket; hopefully the
1453              * DNS returned an additional address to try
1454              */
1455             backend_addr = backend_addr->next;
1456             continue;
1457         }
1458
1459 #if !defined(TPF) && !defined(BEOS)
1460         if (conf->recv_buffer_size > 0 &&
1461             (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1462                                      conf->recv_buffer_size))) {
1463             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1464                          "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1465                          "ProxyReceiveBufferSize, using default");
1466         }
1467 #endif
1468
1469         /* Set a timeout on the socket */
1470         if (conf->timeout_set == 1) {
1471             apr_socket_timeout_set(*newsock, conf->timeout);
1472         }
1473         else {
1474              apr_socket_timeout_set(*newsock, s->timeout);
1475         }
1476
1477         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1478                      "proxy: %s: fam %d socket created to connect to %s",
1479                      proxy_function, backend_addr->family, backend_name);
1480
1481         /* make the connection out of the socket */
1482         rv = apr_socket_connect(*newsock, backend_addr);
1483
1484         /* if an error occurred, loop round and try again */
1485         if (rv != APR_SUCCESS) {
1486             apr_socket_close(*newsock);
1487             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1488             ap_log_error(APLOG_MARK, loglevel, rv, s,
1489                          "proxy: %s: attempt to connect to %pI (%s) failed",
1490                          proxy_function,
1491                          backend_addr,
1492                          backend_name);
1493             backend_addr = backend_addr->next;
1494             continue;
1495         }
1496         connected = 1;
1497     }
1498     return connected ? 0 : 1;
1499 }
1500
1501 static apr_status_t connection_cleanup(void *theconn)
1502 {
1503     proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1504     proxy_worker *worker = conn->worker;
1505
1506     /*
1507      * If the connection pool is NULL the worker
1508      * cleanup has been run. Just return.
1509      */
1510     if (!worker->cp)
1511         return APR_SUCCESS;
1512
1513     /* deterimine if the connection need to be closed */
1514     if (conn->close_on_recycle || conn->close) {
1515         apr_pool_t *p = conn->pool;
1516         apr_pool_clear(conn->pool);
1517         memset(conn, 0, sizeof(proxy_conn_rec));
1518         conn->pool = p;
1519         conn->worker = worker;
1520     }
1521 #if APR_HAS_THREADS
1522     if (worker->hmax && worker->cp->res) {
1523         apr_reslist_release(worker->cp->res, (void *)conn);
1524     }
1525     else
1526 #endif
1527     {
1528         worker->cp->conn = conn;
1529     }
1530
1531     /* Allways return the SUCCESS */
1532     return APR_SUCCESS;
1533 }
1534
1535 /* reslist constructor */
1536 static apr_status_t connection_constructor(void **resource, void *params,
1537                                            apr_pool_t *pool)
1538 {
1539     apr_pool_t *ctx;
1540     proxy_conn_rec *conn;
1541     proxy_worker *worker = (proxy_worker *)params;
1542
1543     /*
1544      * Create the subpool for each connection
1545      * This keeps the memory consumption constant
1546      * when disconnecting from backend.
1547      */
1548     apr_pool_create(&ctx, pool);
1549     conn = apr_pcalloc(pool, sizeof(proxy_conn_rec));
1550
1551     conn->pool   = ctx;
1552     conn->worker = worker;
1553     *resource = conn;
1554
1555     return APR_SUCCESS;
1556 }
1557
1558 #if APR_HAS_THREADS /* only needed when threads are used */
1559 /* reslist destructor */
1560 static apr_status_t connection_destructor(void *resource, void *params,
1561                                           apr_pool_t *pool)
1562 {
1563     proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1564
1565     /* Destroy the pool only if not called from reslist_destroy */
1566     if (conn->worker->cp->pool)
1567         apr_pool_destroy(conn->pool);
1568
1569     return APR_SUCCESS;
1570 }
1571 #endif
1572
1573 PROXY_DECLARE(void) ap_proxy_initialize_worker_share(proxy_server_conf *conf,
1574                                                      proxy_worker *worker,
1575                                                      server_rec *s)
1576 {
1577 #if PROXY_HAS_SCOREBOARD
1578     lb_score *score = NULL;
1579 #else
1580     void *score = NULL;
1581 #endif
1582
1583     if (worker->s && (worker->s->status & PROXY_WORKER_INITIALIZED)) {
1584         /* The worker share is already initialized */
1585         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1586               "proxy: worker %s already initialized",
1587               worker->name);
1588         return;
1589     }
1590 #if PROXY_HAS_SCOREBOARD
1591         /* Get scoreboard slot */
1592     if (ap_scoreboard_image) {
1593         score = ap_get_scoreboard_lb(worker->id);
1594         if (!score) {
1595             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1596                   "proxy: ap_get_scoreboard_lb(%d) failed for worker %s",
1597                   worker->id, worker->name);
1598         }
1599         else {
1600              ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1601                   "proxy: initialized scoreboard slot %d for worker %s",
1602                   worker->id, worker->name);
1603         }
1604     }
1605 #endif
1606     if (!score) {
1607         score = apr_pcalloc(conf->pool, sizeof(proxy_worker_stat));
1608         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1609               "proxy: initialized plain memory for worker %s",
1610               worker->name);
1611     }
1612     worker->s = (proxy_worker_stat *)score;
1613     if (worker->route)
1614         strcpy(worker->s->route, worker->route);
1615     else
1616         *worker->s->route = '\0';
1617     if (worker->redirect)
1618         strcpy(worker->s->redirect, worker->redirect);
1619     else
1620         *worker->s->redirect = '\0';
1621     /* Set default parameters */
1622     if (!worker->retry)
1623         worker->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1624     /* By default address is reusable */
1625     worker->is_address_reusable = 1;
1626
1627 }
1628
1629 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s)
1630 {
1631     apr_status_t rv;
1632
1633 #if APR_HAS_THREADS
1634     int mpm_threads;
1635 #endif
1636
1637     if (worker->s->status & PROXY_WORKER_INITIALIZED) {
1638         /* The worker is already initialized */
1639         return APR_SUCCESS;
1640     }
1641
1642 #if APR_HAS_THREADS
1643     ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1644     if (mpm_threads > 1) {
1645         /* Set hard max to no more then mpm_threads */
1646         if (worker->hmax == 0 || worker->hmax > mpm_threads)
1647             worker->hmax = mpm_threads;
1648         if (worker->smax == 0 || worker->smax > worker->hmax)
1649             worker->smax = worker->hmax;
1650         /* Set min to be lower then smax */
1651         if (worker->min > worker->smax)
1652             worker->min = worker->smax;
1653     }
1654     else {
1655         /* This will supress the apr_reslist creation */
1656         worker->min = worker->smax = worker->hmax = 0;
1657     }
1658     if (worker->hmax) {
1659         rv = apr_reslist_create(&(worker->cp->res),
1660                                 worker->min, worker->smax,
1661                                 worker->hmax, worker->ttl,
1662                                 connection_constructor, connection_destructor,
1663                                 worker, worker->cp->pool);
1664
1665         apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1666                                   conn_pool_cleanup,
1667                                   apr_pool_cleanup_null);
1668
1669         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1670             "proxy: initialized worker %d in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1671              worker->id, getpid(), worker->hostname, worker->min,
1672              worker->hmax, worker->smax);
1673
1674 #if (APR_MAJOR_VERSION > 0)
1675         /* Set the acquire timeout */
1676         if (rv == APR_SUCCESS && worker->acquire_set)
1677             apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1678 #endif
1679     }
1680     else
1681 #endif
1682     {
1683
1684         rv = connection_constructor((void **)&(worker->cp->conn), worker, worker->cp->pool);
1685         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1686              "proxy: initialized single connection worker %d in child %" APR_PID_T_FMT " for (%s)",
1687              worker->id, getpid(), worker->hostname);
1688     }
1689     if (rv == APR_SUCCESS)
1690         worker->s->status |= (worker->status | PROXY_WORKER_INITIALIZED);
1691     return rv;
1692 }
1693
1694 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1695                                          proxy_worker *worker,
1696                                          server_rec *s)
1697 {
1698     if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1699         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1700                     "proxy: %s: retrying the worker for (%s)",
1701                      proxy_function, worker->hostname);
1702         if (apr_time_now() > worker->s->error_time + worker->retry) {
1703             ++worker->s->retries;
1704             worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1705             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1706                          "proxy: %s: worker for (%s) has been marked for retry",
1707                          proxy_function, worker->hostname);
1708             return OK;
1709         }
1710         else
1711             return DECLINED;
1712     }
1713     else
1714         return OK;
1715 }
1716
1717 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
1718                                                proxy_conn_rec **conn,
1719                                                proxy_worker *worker,
1720                                                server_rec *s)
1721 {
1722     apr_status_t rv;
1723
1724     if (!PROXY_WORKER_IS_USABLE(worker)) {
1725         /* Retry the worker */
1726         ap_proxy_retry_worker(proxy_function, worker, s);
1727
1728         if (!PROXY_WORKER_IS_USABLE(worker)) {
1729             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1730                          "proxy: %s: disabled connection for (%s)",
1731                          proxy_function, worker->hostname);
1732             return HTTP_SERVICE_UNAVAILABLE;
1733         }
1734     }
1735 #if APR_HAS_THREADS
1736     if (worker->hmax && worker->cp->res) {
1737         rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
1738     }
1739     else
1740 #endif
1741     {
1742         /* create the new connection if the previous was destroyed */
1743         if (!worker->cp->conn)
1744             connection_constructor((void **)conn, worker, worker->cp->pool);
1745         else {
1746             *conn = worker->cp->conn;
1747             worker->cp->conn = NULL;
1748         }
1749         rv = APR_SUCCESS;
1750     }
1751
1752     if (rv != APR_SUCCESS) {
1753         ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1754                      "proxy: %s: failed to acquire connection for (%s)",
1755                      proxy_function, worker->hostname);
1756         return HTTP_SERVICE_UNAVAILABLE;
1757     }
1758     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1759                  "proxy: %s: has acquired connection for (%s)",
1760                  proxy_function, worker->hostname);
1761
1762     (*conn)->worker = worker;
1763     (*conn)->close  = 0;
1764     (*conn)->close_on_recycle = 0;
1765
1766     return OK;
1767 }
1768
1769 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
1770                                                proxy_conn_rec *conn,
1771                                                server_rec *s)
1772 {
1773     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1774                  "proxy: %s: has released connection for (%s)",
1775                  proxy_function, conn->worker->hostname);
1776     /* If there is a connection kill it's cleanup */
1777     if (conn->connection) {
1778         apr_pool_cleanup_kill(conn->connection->pool, conn, connection_cleanup);
1779         conn->connection = NULL;
1780     }
1781     connection_cleanup(conn);
1782
1783     return OK;
1784 }
1785
1786 PROXY_DECLARE(int)
1787 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
1788                               proxy_server_conf *conf,
1789                               proxy_worker *worker,
1790                               proxy_conn_rec *conn,
1791                               apr_uri_t *uri,
1792                               char **url,
1793                               const char *proxyname,
1794                               apr_port_t proxyport,
1795                               char *server_portstr,
1796                               int server_portstr_size)
1797 {
1798     int server_port;
1799     apr_status_t err = APR_SUCCESS;
1800
1801     /*
1802      * Break up the URL to determine the host to connect to
1803      */
1804
1805     /* we break the URL into host, port, uri */
1806     if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
1807         return ap_proxyerror(r, HTTP_BAD_REQUEST,
1808                              apr_pstrcat(p,"URI cannot be parsed: ", *url,
1809                                          NULL));
1810     }
1811     if (!uri->port) {
1812         uri->port = apr_uri_port_of_scheme(uri->scheme);
1813     }
1814
1815     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1816                  "proxy: connecting %s to %s:%d", *url, uri->hostname,
1817                  uri->port);
1818
1819     /*
1820      * allocate these out of the specified connection pool
1821      * The scheme handler decides if this is permanent or
1822      * short living pool.
1823      */
1824     /* are we connecting directly, or via a proxy? */
1825     if (!proxyname) {
1826         *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
1827                            uri->query ? uri->query : "",
1828                            uri->fragment ? "#" : "",
1829                            uri->fragment ? uri->fragment : "", NULL);
1830     }
1831     /*
1832      * Make sure that we pick the the correct and valid worker.
1833      * If a single keepalive connection triggers different workers,
1834      * then we have a problem (we don't select the correct one).
1835      * Do an expensive check in this case, where we compare the
1836      * the hostnames associated between the two.
1837      *
1838      * TODO: Handle this much better...
1839      */
1840     if (!conn->hostname || !worker->is_address_reusable ||   
1841          (r->connection->keepalives &&
1842          (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
1843          (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
1844         if (proxyname) {
1845             conn->hostname = apr_pstrdup(conn->pool, proxyname);
1846             conn->port = proxyport;
1847         } else {
1848             conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
1849             conn->port = uri->port;
1850         }
1851     }
1852     /*
1853      * TODO: add address cache for generic forward proxies.
1854      * At least level 0 -> compare with previous hostname:port
1855      */
1856     if (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE ||
1857         !worker->is_address_reusable) {
1858         /*
1859          * TODO: Check if the connection can be reused
1860          */
1861         if (conn->connection) {
1862             if (conn->sock) {
1863                 apr_socket_close(conn->sock);
1864                 conn->sock = NULL;
1865             }
1866             apr_pool_cleanup_kill(conn->connection->pool, conn, connection_cleanup);
1867             conn->connection = NULL;
1868         }
1869         err = apr_sockaddr_info_get(&(conn->addr),
1870                                     conn->hostname, APR_UNSPEC,
1871                                     conn->port, 0,
1872                                     conn->pool);
1873     }
1874     else if (!worker->cp->addr) {
1875         if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
1876             ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
1877                          "proxy: lock");
1878             return HTTP_INTERNAL_SERVER_ERROR;
1879         }
1880
1881         /*
1882          * Worker can have the single constant backend adress.
1883          * The single DNS lookup is used once per worker.
1884          * If dynamic change is needed then set the addr to NULL
1885          * inside dynamic config to force the lookup.
1886          */
1887         err = apr_sockaddr_info_get(&(worker->cp->addr),
1888                                     conn->hostname, APR_UNSPEC,
1889                                     conn->port, 0,
1890                                     worker->cp->pool);
1891         conn->addr = worker->cp->addr;
1892         PROXY_THREAD_UNLOCK(worker);
1893     }
1894     else
1895         conn->addr = worker->cp->addr;
1896
1897     if (err != APR_SUCCESS) {
1898         return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1899                              apr_pstrcat(p, "DNS lookup failure for: ",
1900                                          conn->hostname, NULL));
1901     }
1902
1903     /* Get the server port for the Via headers */
1904     {
1905         server_port = ap_get_server_port(r);
1906         if (ap_is_default_port(server_port, r)) {
1907             strcpy(server_portstr,"");
1908         } else {
1909             apr_snprintf(server_portstr, server_portstr_size, ":%d",
1910                          server_port);
1911         }
1912     }
1913     /* check if ProxyBlock directive on this host */
1914     if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
1915         return ap_proxyerror(r, HTTP_FORBIDDEN,
1916                              "Connect to remote machine blocked");
1917     }
1918     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1919                  "proxy: connected %s to %s:%d", *url, conn->hostname,
1920                  conn->port);
1921     return OK;
1922 }
1923
1924 static int is_socket_connected(apr_socket_t *sock)
1925
1926 {
1927     apr_size_t buffer_len = 1;
1928     char test_buffer[1];
1929     apr_status_t socket_status;
1930     apr_interval_time_t current_timeout;
1931
1932     /* save timeout */
1933     apr_socket_timeout_get(sock, &current_timeout);
1934     /* set no timeout */
1935     apr_socket_timeout_set(sock, 0);
1936     socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
1937     /* put back old timeout */
1938     apr_socket_timeout_set(sock, current_timeout);
1939     if (APR_STATUS_IS_EOF(socket_status))
1940         return 0;
1941     else
1942         return 1;
1943 }
1944
1945 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
1946                                             proxy_conn_rec *conn,
1947                                             proxy_worker *worker,
1948                                             server_rec *s)
1949 {
1950     apr_status_t rv;
1951     int connected = 0;
1952     int loglevel;
1953     apr_sockaddr_t *backend_addr = conn->addr;
1954     apr_socket_t *newsock;
1955
1956     if (conn->sock) {
1957         /*
1958          * This increases the connection pool size
1959          * but the number of dropped connections is
1960          * relatively small compared to connection lifetime
1961          */
1962         if (!(connected = is_socket_connected(conn->sock))) {
1963             apr_socket_close(conn->sock);
1964             conn->sock = NULL;
1965         }
1966     }
1967     while (backend_addr && !connected) {
1968         if ((rv = apr_socket_create(&newsock, backend_addr->family,
1969                                 SOCK_STREAM, APR_PROTO_TCP,
1970                                 conn->pool)) != APR_SUCCESS) {
1971             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1972             ap_log_error(APLOG_MARK, loglevel, rv, s,
1973                          "proxy: %s: error creating fam %d socket for target %s",
1974                          proxy_function,
1975                          backend_addr->family,
1976                          worker->hostname);
1977             /*
1978              * this could be an IPv6 address from the DNS but the
1979              * local machine won't give us an IPv6 socket; hopefully the
1980              * DNS returned an additional address to try
1981              */
1982             backend_addr = backend_addr->next;
1983             continue;
1984         }
1985
1986 #if !defined(TPF) && !defined(BEOS)
1987         if (worker->recv_buffer_size > 0 &&
1988             (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
1989                                      worker->recv_buffer_size))) {
1990             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1991                          "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1992                          "ProxyReceiveBufferSize, using default");
1993         }
1994 #endif
1995
1996         /* Set a timeout on the socket */
1997         if (worker->timeout_set == 1) {
1998             apr_socket_timeout_set(newsock, worker->timeout);
1999         }
2000         else {
2001              apr_socket_timeout_set(newsock, s->timeout);
2002         }
2003         /* Set a keepalive option */
2004         if (worker->keepalive) {
2005             if ((rv = apr_socket_opt_set(newsock,
2006                             APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2007                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2008                              "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2009                              " Keepalive");
2010             }
2011         }
2012         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2013                      "proxy: %s: fam %d socket created to connect to %s",
2014                      proxy_function, backend_addr->family, worker->hostname);
2015
2016         /* make the connection out of the socket */
2017         rv = apr_socket_connect(newsock, backend_addr);
2018
2019         /* if an error occurred, loop round and try again */
2020         if (rv != APR_SUCCESS) {
2021             apr_socket_close(newsock);
2022             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2023             ap_log_error(APLOG_MARK, loglevel, rv, s,
2024                          "proxy: %s: attempt to connect to %pI (%s) failed",
2025                          proxy_function,
2026                          backend_addr,
2027                          worker->hostname);
2028             backend_addr = backend_addr->next;
2029             continue;
2030         }
2031
2032         conn->sock   = newsock;
2033         connected    = 1;
2034     }
2035     /*
2036      * Put the entire worker to error state if
2037      * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2038      * Altrough some connections may be alive
2039      * no further connections to the worker could be made
2040      */
2041     if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2042         !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2043         worker->s->status |= PROXY_WORKER_IN_ERROR;
2044         worker->s->error_time = apr_time_now();
2045         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2046             "ap_proxy_connect_backend disabling worker for (%s)",
2047             worker->hostname);
2048     }
2049     else {
2050         worker->s->error_time = 0;
2051         worker->s->retries = 0;
2052     }
2053     return connected ? OK : DECLINED;
2054 }
2055
2056 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2057                                               proxy_conn_rec *conn,
2058                                               conn_rec *c,
2059                                               server_rec *s)
2060 {
2061     apr_sockaddr_t *backend_addr = conn->addr;
2062     int rc;
2063
2064     /*
2065      * The socket is now open, create a new backend server connection
2066      */
2067     conn->connection = ap_run_create_connection(c->pool, s, conn->sock,
2068                                                 c->id, c->sbh,
2069                                                 c->bucket_alloc);
2070
2071     if (!conn->connection) {
2072         /*
2073          * the peer reset the connection already; ap_run_create_connection()
2074          * closed the socket
2075          */
2076         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2077                      s, "proxy: %s: an error occurred creating a "
2078                      "new connection to %pI (%s)", proxy_function,
2079                      backend_addr, conn->hostname);
2080         /* XXX: Will be closed when proxy_conn is closed */
2081         apr_socket_close(conn->sock);
2082         conn->sock = NULL;
2083         return HTTP_INTERNAL_SERVER_ERROR;
2084     }
2085     /*
2086      * register the connection cleanup to client connection
2087      * so that the connection can be closed or reused
2088      */
2089     apr_pool_cleanup_register(c->pool, (void *)conn,
2090                               connection_cleanup,
2091                               apr_pool_cleanup_null);
2092
2093     /* For ssl connection to backend */
2094     if (conn->is_ssl) {
2095         if (!ap_proxy_ssl_enable(conn->connection)) {
2096             ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2097                          s, "proxy: %s: failed to enable ssl support "
2098                          "for %pI (%s)", proxy_function,
2099                          backend_addr, conn->hostname);
2100             return HTTP_INTERNAL_SERVER_ERROR;
2101         }
2102     }
2103     else {
2104         /* TODO: See if this will break FTP */
2105         ap_proxy_ssl_disable(conn->connection);
2106     }
2107
2108     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2109                  "proxy: %s: connection complete to %pI (%s)",
2110                  proxy_function, backend_addr, conn->hostname);
2111
2112     /* set up the connection filters */
2113     rc = ap_run_pre_connection(conn->connection, conn->sock);
2114     if (rc != OK && rc != DONE) {
2115         conn->connection->aborted = 1;
2116         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2117                      "proxy: %s: pre_connection setup failed (%d)",
2118                      proxy_function, rc);
2119         return rc;
2120     }
2121
2122     return OK;
2123 }
2124
2125 int ap_proxy_lb_workers(void)
2126 {
2127     /*
2128      * Since we can't resize the scoreboard when reconfiguring, we
2129      * have to impose a limit on the number of workers, we are
2130      * able to reconfigure to.
2131      */
2132     if (!lb_workers_limit)
2133     lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2134     return lb_workers_limit;
2135 }
2136
2137 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2138                                            apr_bucket_brigade *brigade)
2139 {
2140     apr_bucket *e;
2141     conn_rec *c = r->connection;
2142
2143     r->no_cache = 1;
2144     /*
2145      * If this is a subrequest, then prevent also caching of the main
2146      * request.
2147      */
2148     if (r->main)
2149         r->main->no_cache = 1;
2150     e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2151                                c->bucket_alloc);
2152     APR_BRIGADE_INSERT_TAIL(brigade, e);
2153     e = apr_bucket_eos_create(c->bucket_alloc);
2154     APR_BRIGADE_INSERT_TAIL(brigade, e);
2155 }