]> granicus.if.org Git - apache/blob - modules/proxy/proxy_util.c
b3c5cb4e61d070607bb3169ebdddced6bf651b8f
[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
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 /*
33  * Opaque structure containing target server info when
34  * using a forward proxy.
35  * Up to now only used in combination with HTTP CONNECT.
36  */
37 typedef struct {
38     int          use_http_connect; /* Use SSL Tunneling via HTTP CONNECT */
39     const char   *target_host;     /* Target hostname */
40     apr_port_t   target_port;      /* Target port */
41     const char   *proxy_auth;      /* Proxy authorization */
42 } forward_info;
43
44 /* Global balancer counter */
45 int PROXY_DECLARE_DATA proxy_lb_workers = 0;
46 static int lb_workers_limit = 0;
47
48 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r);
49 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r);
50 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r);
51 static int proxy_match_word(struct dirconn_entry *This, request_rec *r);
52
53 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, create_req,
54                                    (request_rec *r, request_rec *pr), (r, pr),
55                                    OK, DECLINED)
56
57 /* already called in the knowledge that the characters are hex digits */
58 PROXY_DECLARE(int) ap_proxy_hex2c(const char *x)
59 {
60     int i, ch;
61
62 #if !APR_CHARSET_EBCDIC
63     ch = x[0];
64     if (apr_isdigit(ch)) {
65         i = ch - '0';
66     }
67     else if (apr_isupper(ch)) {
68         i = ch - ('A' - 10);
69     }
70     else {
71         i = ch - ('a' - 10);
72     }
73     i <<= 4;
74
75     ch = x[1];
76     if (apr_isdigit(ch)) {
77         i += ch - '0';
78     }
79     else if (apr_isupper(ch)) {
80         i += ch - ('A' - 10);
81     }
82     else {
83         i += ch - ('a' - 10);
84     }
85     return i;
86 #else /*APR_CHARSET_EBCDIC*/
87     /*
88      * we assume that the hex value refers to an ASCII character
89      * so convert to EBCDIC so that it makes sense locally;
90      *
91      * example:
92      *
93      * client specifies %20 in URL to refer to a space char;
94      * at this point we're called with EBCDIC "20"; after turning
95      * EBCDIC "20" into binary 0x20, we then need to assume that 0x20
96      * represents an ASCII char and convert 0x20 to EBCDIC, yielding
97      * 0x40
98      */
99     char buf[1];
100
101     if (1 == sscanf(x, "%2x", &i)) {
102         buf[0] = i & 0xFF;
103         ap_xlate_proto_from_ascii(buf, 1);
104         return buf[0];
105     }
106     else {
107         return 0;
108     }
109 #endif /*APR_CHARSET_EBCDIC*/
110 }
111
112 PROXY_DECLARE(void) ap_proxy_c2hex(int ch, char *x)
113 {
114 #if !APR_CHARSET_EBCDIC
115     int i;
116
117     x[0] = '%';
118     i = (ch & 0xF0) >> 4;
119     if (i >= 10) {
120         x[1] = ('A' - 10) + i;
121     }
122     else {
123         x[1] = '0' + i;
124     }
125
126     i = ch & 0x0F;
127     if (i >= 10) {
128         x[2] = ('A' - 10) + i;
129     }
130     else {
131         x[2] = '0' + i;
132     }
133 #else /*APR_CHARSET_EBCDIC*/
134     static const char ntoa[] = { "0123456789ABCDEF" };
135     char buf[1];
136
137     ch &= 0xFF;
138
139     buf[0] = ch;
140     ap_xlate_proto_to_ascii(buf, 1);
141
142     x[0] = '%';
143     x[1] = ntoa[(buf[0] >> 4) & 0x0F];
144     x[2] = ntoa[buf[0] & 0x0F];
145     x[3] = '\0';
146 #endif /*APR_CHARSET_EBCDIC*/
147 }
148
149 /*
150  * canonicalise a URL-encoded string
151  */
152
153 /*
154  * Convert a URL-encoded string to canonical form.
155  * It decodes characters which need not be encoded,
156  * and encodes those which must be encoded, and does not touch
157  * those which must not be touched.
158  */
159 PROXY_DECLARE(char *)ap_proxy_canonenc(apr_pool_t *p, const char *x, int len,
160                                        enum enctype t, int forcedec,
161                                        int proxyreq)
162 {
163     int i, j, ch;
164     char *y;
165     char *allowed;  /* characters which should not be encoded */
166     char *reserved; /* characters which much not be en/de-coded */
167
168 /*
169  * N.B. in addition to :@&=, this allows ';' in an http path
170  * and '?' in an ftp path -- this may be revised
171  *
172  * Also, it makes a '+' character in a search string reserved, as
173  * it may be form-encoded. (Although RFC 1738 doesn't allow this -
174  * it only permits ; / ? : @ = & as reserved chars.)
175  */
176     if (t == enc_path) {
177         allowed = "~$-_.+!*'(),;:@&=";
178     }
179     else if (t == enc_search) {
180         allowed = "$-_.!*'(),;:@&=";
181     }
182     else if (t == enc_user) {
183         allowed = "$-_.+!*'(),;@&=";
184     }
185     else if (t == enc_fpath) {
186         allowed = "$-_.+!*'(),?:@&=";
187     }
188     else {            /* if (t == enc_parm) */
189         allowed = "$-_.+!*'(),?/:@&=";
190     }
191
192     if (t == enc_path) {
193         reserved = "/";
194     }
195     else if (t == enc_search) {
196         reserved = "+";
197     }
198     else {
199         reserved = "";
200     }
201
202     y = apr_palloc(p, 3 * len + 1);
203
204     for (i = 0, j = 0; i < len; i++, j++) {
205 /* always handle '/' first */
206         ch = x[i];
207         if (strchr(reserved, ch)) {
208             y[j] = ch;
209             continue;
210         }
211 /*
212  * decode it if not already done. do not decode reverse proxied URLs
213  * unless specifically forced
214  */
215         if ((forcedec || (proxyreq && proxyreq != PROXYREQ_REVERSE)) && ch == '%') {
216             if (!apr_isxdigit(x[i + 1]) || !apr_isxdigit(x[i + 2])) {
217                 return NULL;
218             }
219             ch = ap_proxy_hex2c(&x[i + 1]);
220             i += 2;
221             if (ch != 0 && strchr(reserved, ch)) {  /* keep it encoded */
222                 ap_proxy_c2hex(ch, &y[j]);
223                 j += 2;
224                 continue;
225             }
226         }
227 /* recode it, if necessary */
228         if (!apr_isalnum(ch) && !strchr(allowed, ch)) {
229             ap_proxy_c2hex(ch, &y[j]);
230             j += 2;
231         }
232         else {
233             y[j] = ch;
234         }
235     }
236     y[j] = '\0';
237     return y;
238 }
239
240 /*
241  * Parses network-location.
242  *    urlp           on input the URL; on output the path, after the leading /
243  *    user           NULL if no user/password permitted
244  *    password       holder for password
245  *    host           holder for host
246  *    port           port number; only set if one is supplied.
247  *
248  * Returns an error string.
249  */
250 PROXY_DECLARE(char *)
251      ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
252             char **passwordp, char **hostp, apr_port_t *port)
253 {
254     char *addr, *scope_id, *strp, *host, *url = *urlp;
255     char *user = NULL, *password = NULL;
256     apr_port_t tmp_port;
257     apr_status_t rv;
258
259     if (url[0] != '/' || url[1] != '/') {
260         return "Malformed URL";
261     }
262     host = url + 2;
263     url = strchr(host, '/');
264     if (url == NULL) {
265         url = "";
266     }
267     else {
268         *(url++) = '\0';    /* skip seperating '/' */
269     }
270
271     /* find _last_ '@' since it might occur in user/password part */
272     strp = strrchr(host, '@');
273
274     if (strp != NULL) {
275         *strp = '\0';
276         user = host;
277         host = strp + 1;
278
279 /* find password */
280         strp = strchr(user, ':');
281         if (strp != NULL) {
282             *strp = '\0';
283             password = ap_proxy_canonenc(p, strp + 1, strlen(strp + 1), enc_user, 1, 0);
284             if (password == NULL) {
285                 return "Bad %-escape in URL (password)";
286             }
287         }
288
289         user = ap_proxy_canonenc(p, user, strlen(user), enc_user, 1, 0);
290         if (user == NULL) {
291             return "Bad %-escape in URL (username)";
292         }
293     }
294     if (userp != NULL) {
295         *userp = user;
296     }
297     if (passwordp != NULL) {
298         *passwordp = password;
299     }
300
301     /*
302      * Parse the host string to separate host portion from optional port.
303      * Perform range checking on port.
304      */
305     rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
306     if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
307         return "Invalid host/port";
308     }
309     if (tmp_port != 0) { /* only update caller's port if port was specified */
310         *port = tmp_port;
311     }
312
313     ap_str_tolower(addr); /* DNS names are case-insensitive */
314
315     *urlp = url;
316     *hostp = addr;
317
318     return NULL;
319 }
320
321 /*
322  * If the date is a valid RFC 850 date or asctime() date, then it
323  * is converted to the RFC 1123 format.
324  */
325 PROXY_DECLARE(const char *)
326      ap_proxy_date_canon(apr_pool_t *p, const char *date)
327 {
328     apr_status_t rv;
329     char* ndate;
330
331     apr_time_t time = apr_date_parse_http(date);
332     if (!time) {
333         return date;
334     }
335
336     ndate = apr_palloc(p, APR_RFC822_DATE_LEN);
337     rv = apr_rfc822_date(ndate, time);
338     if (rv != APR_SUCCESS) {
339         return date;
340     }
341
342     return ndate;
343 }
344
345 PROXY_DECLARE(request_rec *)ap_proxy_make_fake_req(conn_rec *c, request_rec *r)
346 {
347     request_rec *rp = apr_pcalloc(r->pool, sizeof(*r));
348
349     rp->pool            = r->pool;
350     rp->status          = HTTP_OK;
351
352     rp->headers_in      = apr_table_make(r->pool, 50);
353     rp->subprocess_env  = apr_table_make(r->pool, 50);
354     rp->headers_out     = apr_table_make(r->pool, 12);
355     rp->err_headers_out = apr_table_make(r->pool, 5);
356     rp->notes           = apr_table_make(r->pool, 5);
357
358     rp->server = r->server;
359     rp->proxyreq = r->proxyreq;
360     rp->request_time = r->request_time;
361     rp->connection      = c;
362     rp->output_filters  = c->output_filters;
363     rp->input_filters   = c->input_filters;
364     rp->proto_output_filters  = c->output_filters;
365     rp->proto_input_filters   = c->input_filters;
366
367     rp->request_config  = ap_create_request_config(r->pool);
368     proxy_run_create_req(r, rp);
369
370     return rp;
371 }
372
373
374 /*
375  * list is a comma-separated list of case-insensitive tokens, with
376  * optional whitespace around the tokens.
377  * The return returns 1 if the token val is found in the list, or 0
378  * otherwise.
379  */
380 PROXY_DECLARE(int) ap_proxy_liststr(const char *list, const char *val)
381 {
382     int len, i;
383     const char *p;
384
385     len = strlen(val);
386
387     while (list != NULL) {
388         p = ap_strchr_c(list, ',');
389         if (p != NULL) {
390             i = p - list;
391             do {
392                 p++;
393             } while (apr_isspace(*p));
394         }
395         else {
396             i = strlen(list);
397         }
398
399         while (i > 0 && apr_isspace(list[i - 1])) {
400             i--;
401         }
402         if (i == len && strncasecmp(list, val, len) == 0) {
403             return 1;
404         }
405         list = p;
406     }
407     return 0;
408 }
409
410 /*
411  * list is a comma-separated list of case-insensitive tokens, with
412  * optional whitespace around the tokens.
413  * if val appears on the list of tokens, it is removed from the list,
414  * and the new list is returned.
415  */
416 PROXY_DECLARE(char *)ap_proxy_removestr(apr_pool_t *pool, const char *list, const char *val)
417 {
418     int len, i;
419     const char *p;
420     char *new = NULL;
421
422     len = strlen(val);
423
424     while (list != NULL) {
425         p = ap_strchr_c(list, ',');
426         if (p != NULL) {
427             i = p - list;
428             do {
429                 p++;
430             } while (apr_isspace(*p));
431         }
432         else {
433             i = strlen(list);
434         }
435
436         while (i > 0 && apr_isspace(list[i - 1])) {
437             i--;
438         }
439         if (i == len && strncasecmp(list, val, len) == 0) {
440             /* do nothing */
441         }
442         else {
443             if (new) {
444                 new = apr_pstrcat(pool, new, ",", apr_pstrndup(pool, list, i), NULL);
445             }
446             else {
447                 new = apr_pstrndup(pool, list, i);
448             }
449         }
450         list = p;
451     }
452     return new;
453 }
454
455 /*
456  * Converts 8 hex digits to a time integer
457  */
458 PROXY_DECLARE(int) ap_proxy_hex2sec(const char *x)
459 {
460     int i, ch;
461     unsigned int j;
462
463     for (i = 0, j = 0; i < 8; i++) {
464         ch = x[i];
465         j <<= 4;
466         if (apr_isdigit(ch)) {
467             j |= ch - '0';
468         }
469         else if (apr_isupper(ch)) {
470             j |= ch - ('A' - 10);
471         }
472         else {
473             j |= ch - ('a' - 10);
474         }
475     }
476     if (j == 0xffffffff) {
477         return -1;      /* so that it works with 8-byte ints */
478     }
479     else {
480         return j;
481     }
482 }
483
484 /*
485  * Converts a time integer to 8 hex digits
486  */
487 PROXY_DECLARE(void) ap_proxy_sec2hex(int t, char *y)
488 {
489     int i, ch;
490     unsigned int j = t;
491
492     for (i = 7; i >= 0; i--) {
493         ch = j & 0xF;
494         j >>= 4;
495         if (ch >= 10) {
496             y[i] = ch + ('A' - 10);
497         }
498         else {
499             y[i] = ch + '0';
500         }
501     }
502     y[8] = '\0';
503 }
504
505 PROXY_DECLARE(int) ap_proxyerror(request_rec *r, int statuscode, const char *message)
506 {
507     apr_table_setn(r->notes, "error-notes",
508     apr_pstrcat(r->pool,
509         "The proxy server could not handle the request "
510         "<em><a href=\"", ap_escape_html(r->pool, r->uri),
511         "\">", ap_escape_html(r->pool, r->method),
512         "&nbsp;",
513         ap_escape_html(r->pool, r->uri), "</a></em>.<p>\n"
514         "Reason: <strong>",
515         ap_escape_html(r->pool, message),
516         "</strong></p>", NULL));
517
518     /* Allow "error-notes" string to be printed by ap_send_error_response() */
519     apr_table_setn(r->notes, "verbose-error-to", apr_pstrdup(r->pool, "*"));
520
521     r->status_line = apr_psprintf(r->pool, "%3.3u Proxy Error", statuscode);
522     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
523              "proxy: %s returned by %s", message, r->uri);
524     return statuscode;
525 }
526
527 static const char *
528      proxy_get_host_of_request(request_rec *r)
529 {
530     char *url, *user = NULL, *password = NULL, *err, *host;
531     apr_port_t port;
532
533     if (r->hostname != NULL) {
534         return r->hostname;
535     }
536
537     /* Set url to the first char after "scheme://" */
538     if ((url = strchr(r->uri, ':')) == NULL || url[1] != '/' || url[2] != '/') {
539         return NULL;
540     }
541
542     url = apr_pstrdup(r->pool, &url[1]);    /* make it point to "//", which is what proxy_canon_netloc expects */
543
544     err = ap_proxy_canon_netloc(r->pool, &url, &user, &password, &host, &port);
545
546     if (err != NULL) {
547         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", err);
548     }
549
550     r->hostname = host;
551
552     return host;        /* ought to return the port, too */
553 }
554
555 /* Return TRUE if addr represents an IP address (or an IP network address) */
556 PROXY_DECLARE(int) ap_proxy_is_ipaddr(struct dirconn_entry *This, apr_pool_t *p)
557 {
558     const char *addr = This->name;
559     long ip_addr[4];
560     int i, quads;
561     long bits;
562
563     /*
564      * if the address is given with an explicit netmask, use that
565      * Due to a deficiency in apr_inet_addr(), it is impossible to parse
566      * "partial" addresses (with less than 4 quads) correctly, i.e.
567      * 192.168.123 is parsed as 192.168.0.123, which is not what I want.
568      * I therefore have to parse the IP address manually:
569      * if (proxy_readmask(This->name, &This->addr.s_addr, &This->mask.s_addr) == 0)
570      * addr and mask were set by proxy_readmask()
571      * return 1;
572      */
573
574     /*
575      * Parse IP addr manually, optionally allowing
576      * abbreviated net addresses like 192.168.
577      */
578
579     /* Iterate over up to 4 (dotted) quads. */
580     for (quads = 0; quads < 4 && *addr != '\0'; ++quads) {
581         char *tmp;
582
583         if (*addr == '/' && quads > 0) {  /* netmask starts here. */
584             break;
585         }
586
587         if (!apr_isdigit(*addr)) {
588             return 0;       /* no digit at start of quad */
589         }
590
591         ip_addr[quads] = strtol(addr, &tmp, 0);
592
593         if (tmp == addr) {  /* expected a digit, found something else */
594             return 0;
595         }
596
597         if (ip_addr[quads] < 0 || ip_addr[quads] > 255) {
598             /* invalid octet */
599             return 0;
600         }
601
602         addr = tmp;
603
604         if (*addr == '.' && quads != 3) {
605             ++addr;     /* after the 4th quad, a dot would be illegal */
606         }
607     }
608
609     for (This->addr.s_addr = 0, i = 0; i < quads; ++i) {
610         This->addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
611     }
612
613     if (addr[0] == '/' && apr_isdigit(addr[1])) {   /* net mask follows: */
614         char *tmp;
615
616         ++addr;
617
618         bits = strtol(addr, &tmp, 0);
619
620         if (tmp == addr) {   /* expected a digit, found something else */
621             return 0;
622         }
623
624         addr = tmp;
625
626         if (bits < 0 || bits > 32) { /* netmask must be between 0 and 32 */
627             return 0;
628         }
629
630     }
631     else {
632         /*
633          * Determine (i.e., "guess") netmask by counting the
634          * number of trailing .0's; reduce #quads appropriately
635          * (so that 192.168.0.0 is equivalent to 192.168.)
636          */
637         while (quads > 0 && ip_addr[quads - 1] == 0) {
638             --quads;
639         }
640
641         /* "IP Address should be given in dotted-quad form, optionally followed by a netmask (e.g., 192.168.111.0/24)"; */
642         if (quads < 1) {
643             return 0;
644         }
645
646         /* every zero-byte counts as 8 zero-bits */
647         bits = 8 * quads;
648
649         if (bits != 32) {     /* no warning for fully qualified IP address */
650             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
651                          "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
652                          inet_ntoa(This->addr), bits);
653         }
654     }
655
656     This->mask.s_addr = htonl(APR_INADDR_NONE << (32 - bits));
657
658     if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
659         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
660                      "Warning: NetMask and IP-Addr disagree in %s/%ld",
661                      inet_ntoa(This->addr), bits);
662         This->addr.s_addr &= This->mask.s_addr;
663         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
664                      "         Set to %s/%ld", inet_ntoa(This->addr), bits);
665     }
666
667     if (*addr == '\0') {
668         This->matcher = proxy_match_ipaddr;
669         return 1;
670     }
671     else {
672         return (*addr == '\0'); /* okay iff we've parsed the whole string */
673     }
674 }
675
676 /* Return TRUE if addr represents an IP address (or an IP network address) */
677 static int proxy_match_ipaddr(struct dirconn_entry *This, request_rec *r)
678 {
679     int i, ip_addr[4];
680     struct in_addr addr, *ip;
681     const char *host = proxy_get_host_of_request(r);
682
683     if (host == NULL) {   /* oops! */
684        return 0;
685     }
686
687     memset(&addr, '\0', sizeof addr);
688     memset(ip_addr, '\0', sizeof ip_addr);
689
690     if (4 == sscanf(host, "%d.%d.%d.%d", &ip_addr[0], &ip_addr[1], &ip_addr[2], &ip_addr[3])) {
691         for (addr.s_addr = 0, i = 0; i < 4; ++i) {
692             /* ap_proxy_is_ipaddr() already confirmed that we have
693              * a valid octet in ip_addr[i]
694              */
695             addr.s_addr |= htonl(ip_addr[i] << (24 - 8 * i));
696         }
697
698         if (This->addr.s_addr == (addr.s_addr & This->mask.s_addr)) {
699 #if DEBUGGING
700             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
701                          "1)IP-Match: %s[%s] <-> ", host, inet_ntoa(addr));
702             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
703                          "%s/", inet_ntoa(This->addr));
704             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
705                          "%s", inet_ntoa(This->mask));
706 #endif
707             return 1;
708         }
709 #if DEBUGGING
710         else {
711             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
712                          "1)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(addr));
713             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
714                          "%s/", inet_ntoa(This->addr));
715             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
716                          "%s", inet_ntoa(This->mask));
717         }
718 #endif
719     }
720     else {
721         struct apr_sockaddr_t *reqaddr;
722
723         if (apr_sockaddr_info_get(&reqaddr, host, APR_UNSPEC, 0, 0, r->pool)
724             != APR_SUCCESS) {
725 #if DEBUGGING
726             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
727              "2)IP-NoMatch: hostname=%s msg=Host not found", host);
728 #endif
729             return 0;
730         }
731
732         /* Try to deal with multiple IP addr's for a host */
733         /* FIXME: This needs to be able to deal with IPv6 */
734         while (reqaddr) {
735             ip = (struct in_addr *) reqaddr->ipaddr_ptr;
736             if (This->addr.s_addr == (ip->s_addr & This->mask.s_addr)) {
737 #if DEBUGGING
738                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
739                              "3)IP-Match: %s[%s] <-> ", host, inet_ntoa(*ip));
740                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
741                              "%s/", inet_ntoa(This->addr));
742                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
743                              "%s", inet_ntoa(This->mask));
744 #endif
745                 return 1;
746             }
747 #if DEBUGGING
748             else {
749                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
750                              "3)IP-NoMatch: %s[%s] <-> ", host, inet_ntoa(*ip));
751                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
752                              "%s/", inet_ntoa(This->addr));
753                 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
754                              "%s", inet_ntoa(This->mask));
755             }
756 #endif
757             reqaddr = reqaddr->next;
758         }
759     }
760
761     return 0;
762 }
763
764 /* Return TRUE if addr represents a domain name */
765 PROXY_DECLARE(int) ap_proxy_is_domainname(struct dirconn_entry *This, apr_pool_t *p)
766 {
767     char *addr = This->name;
768     int i;
769
770     /* Domain name must start with a '.' */
771     if (addr[0] != '.') {
772         return 0;
773     }
774
775     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
776     for (i = 0; apr_isalnum(addr[i]) || addr[i] == '-' || addr[i] == '.'; ++i) {
777         continue;
778     }
779
780 #if 0
781     if (addr[i] == ':') {
782     ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
783                      "@@@@ handle optional port in proxy_is_domainname()");
784     /* @@@@ handle optional port */
785     }
786 #endif
787
788     if (addr[i] != '\0') {
789         return 0;
790     }
791
792     /* Strip trailing dots */
793     for (i = strlen(addr) - 1; i > 0 && addr[i] == '.'; --i) {
794         addr[i] = '\0';
795     }
796
797     This->matcher = proxy_match_domainname;
798     return 1;
799 }
800
801 /* Return TRUE if host "host" is in domain "domain" */
802 static int proxy_match_domainname(struct dirconn_entry *This, request_rec *r)
803 {
804     const char *host = proxy_get_host_of_request(r);
805     int d_len = strlen(This->name), h_len;
806
807     if (host == NULL) {      /* some error was logged already */
808         return 0;
809     }
810
811     h_len = strlen(host);
812
813     /* @@@ do this within the setup? */
814     /* Ignore trailing dots in domain comparison: */
815     while (d_len > 0 && This->name[d_len - 1] == '.') {
816         --d_len;
817     }
818     while (h_len > 0 && host[h_len - 1] == '.') {
819         --h_len;
820     }
821     return h_len > d_len
822         && strncasecmp(&host[h_len - d_len], This->name, d_len) == 0;
823 }
824
825 /* Return TRUE if host represents a host name */
826 PROXY_DECLARE(int) ap_proxy_is_hostname(struct dirconn_entry *This, apr_pool_t *p)
827 {
828     struct apr_sockaddr_t *addr;
829     char *host = This->name;
830     int i;
831
832     /* Host names must not start with a '.' */
833     if (host[0] == '.') {
834         return 0;
835     }
836     /* rfc1035 says DNS names must consist of "[-a-zA-Z0-9]" and '.' */
837     for (i = 0; apr_isalnum(host[i]) || host[i] == '-' || host[i] == '.'; ++i);
838
839     if (host[i] != '\0' || apr_sockaddr_info_get(&addr, host, APR_UNSPEC, 0, 0, p) != APR_SUCCESS) {
840         return 0;
841     }
842
843     This->hostaddr = addr;
844
845     /* Strip trailing dots */
846     for (i = strlen(host) - 1; i > 0 && host[i] == '.'; --i) {
847         host[i] = '\0';
848     }
849
850     This->matcher = proxy_match_hostname;
851     return 1;
852 }
853
854 /* Return TRUE if host "host" is equal to host2 "host2" */
855 static int proxy_match_hostname(struct dirconn_entry *This, request_rec *r)
856 {
857     char *host = This->name;
858     const char *host2 = proxy_get_host_of_request(r);
859     int h2_len;
860     int h1_len;
861
862     if (host == NULL || host2 == NULL) {
863         return 0; /* oops! */
864     }
865
866     h2_len = strlen(host2);
867     h1_len = strlen(host);
868
869 #if 0
870     struct apr_sockaddr_t *addr = *This->hostaddr;
871
872     /* Try to deal with multiple IP addr's for a host */
873     while (addr) {
874         if (addr->ipaddr_ptr == ? ? ? ? ? ? ? ? ? ? ? ? ?)
875             return 1;
876         addr = addr->next;
877     }
878 #endif
879
880     /* Ignore trailing dots in host2 comparison: */
881     while (h2_len > 0 && host2[h2_len - 1] == '.') {
882         --h2_len;
883     }
884     while (h1_len > 0 && host[h1_len - 1] == '.') {
885         --h1_len;
886     }
887     return h1_len == h2_len
888         && strncasecmp(host, host2, h1_len) == 0;
889 }
890
891 /* Return TRUE if addr is to be matched as a word */
892 PROXY_DECLARE(int) ap_proxy_is_word(struct dirconn_entry *This, apr_pool_t *p)
893 {
894     This->matcher = proxy_match_word;
895     return 1;
896 }
897
898 /* Return TRUE if string "str2" occurs literally in "str1" */
899 static int proxy_match_word(struct dirconn_entry *This, request_rec *r)
900 {
901     const char *host = proxy_get_host_of_request(r);
902     return host != NULL && ap_strstr_c(host, This->name) != NULL;
903 }
904
905 /* checks whether a host in uri_addr matches proxyblock */
906 PROXY_DECLARE(int) ap_proxy_checkproxyblock(request_rec *r, proxy_server_conf *conf,
907                              apr_sockaddr_t *uri_addr)
908 {
909     int j;
910     apr_sockaddr_t * src_uri_addr = uri_addr;
911     /* XXX FIXME: conf->noproxies->elts is part of an opaque structure */
912     for (j = 0; j < conf->noproxies->nelts; j++) {
913         struct noproxy_entry *npent = (struct noproxy_entry *) conf->noproxies->elts;
914         struct apr_sockaddr_t *conf_addr = npent[j].addr;
915         uri_addr = src_uri_addr;
916         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
917                      "proxy: checking remote machine [%s] against [%s]", uri_addr->hostname, npent[j].name);
918         if ((npent[j].name && ap_strstr_c(uri_addr->hostname, npent[j].name))
919             || npent[j].name[0] == '*') {
920             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
921                          "proxy: connect to remote machine %s blocked: name %s matched", uri_addr->hostname, npent[j].name);
922             return HTTP_FORBIDDEN;
923         }
924         while (conf_addr) {
925             uri_addr = src_uri_addr;
926             while (uri_addr) {
927                 char *conf_ip;
928                 char *uri_ip;
929                 apr_sockaddr_ip_get(&conf_ip, conf_addr);
930                 apr_sockaddr_ip_get(&uri_ip, uri_addr);
931                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
932                              "proxy: ProxyBlock comparing %s and %s", conf_ip, uri_ip);
933                 if (!apr_strnatcasecmp(conf_ip, uri_ip)) {
934                     ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
935                                  "proxy: connect to remote machine %s blocked: 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 ((strncasecmp(real, "balancer://", 11) == 0) &&
1094             (balancer = ap_proxy_get_balancer(r->pool, sconf, real))) {
1095             int n, l3 = 0;
1096             proxy_worker **worker = (proxy_worker **)balancer->workers->elts;
1097             const char *urlpart = ap_strchr_c(real + 11, '/');
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)->name);
1111                 if (urlpart) {
1112                     /* urlpart (l3) assuredly starts with its own '/' */
1113                     if ((*worker)->name[l2 - 1] == '/')
1114                         --l2;
1115                     if (l1 >= l2 + l3 
1116                             && strncasecmp((*worker)->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_construct_url(r->pool, u, r);
1121                     }
1122                 }
1123                 else if (l1 >= l2 && strncasecmp((*worker)->name, url, l2) == 0) {
1124                     u = apr_pstrcat(r->pool, ent[i].fake, &url[l2], NULL);
1125                     return 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_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(conf->cookie_path_str, 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(conf->cookie_domain_str, 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 PROXY_DECLARE(proxy_balancer *) ap_proxy_get_balancer(apr_pool_t *p,
1279                                                       proxy_server_conf *conf,
1280                                                       const char *url)
1281 {
1282     proxy_balancer *balancer;
1283     char *c, *uri = apr_pstrdup(p, url);
1284     int i;
1285
1286     c = strchr(uri, ':');
1287     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1288        return NULL;
1289     }
1290     /* remove path from uri */
1291     if ((c = strchr(c + 3, '/'))) {
1292         *c = '\0';
1293     }
1294     balancer = (proxy_balancer *)conf->balancers->elts;
1295     for (i = 0; i < conf->balancers->nelts; i++) {
1296         if (strcasecmp(balancer->name, uri) == 0) {
1297             return balancer;
1298         }
1299         balancer++;
1300     }
1301     return NULL;
1302 }
1303
1304 PROXY_DECLARE(const char *) ap_proxy_add_balancer(proxy_balancer **balancer,
1305                                                   apr_pool_t *p,
1306                                                   proxy_server_conf *conf,
1307                                                   const char *url)
1308 {
1309     char *c, *q, *uri = apr_pstrdup(p, url);
1310     proxy_balancer_method *lbmethod;
1311
1312     c = strchr(uri, ':');
1313     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0')
1314        return "Bad syntax for a balancer name";
1315     /* remove path from uri */
1316     if ((q = strchr(c + 3, '/')))
1317         *q = '\0';
1318
1319     ap_str_tolower(uri);
1320     *balancer = apr_array_push(conf->balancers);
1321     memset(*balancer, 0, sizeof(proxy_balancer));
1322
1323     /*
1324      * NOTE: The default method is byrequests, which we assume
1325      * exists!
1326      */
1327     lbmethod = ap_lookup_provider(PROXY_LBMETHOD, "byrequests", "0");
1328     if (!lbmethod) {
1329         return "Can't find 'byrequests' lb method";
1330     }
1331
1332     (*balancer)->name = uri;
1333     (*balancer)->lbmethod = lbmethod;
1334     (*balancer)->workers = apr_array_make(p, 5, sizeof(proxy_worker *));
1335     /* XXX Is this a right place to create mutex */
1336 #if APR_HAS_THREADS
1337     if (apr_thread_mutex_create(&((*balancer)->mutex),
1338                 APR_THREAD_MUTEX_DEFAULT, p) != APR_SUCCESS) {
1339         /* XXX: Do we need to log something here */
1340         return "can not create thread mutex";
1341     }
1342 #endif
1343
1344     return NULL;
1345 }
1346
1347 PROXY_DECLARE(proxy_worker *) ap_proxy_get_worker(apr_pool_t *p,
1348                                                   proxy_server_conf *conf,
1349                                                   const char *url)
1350 {
1351     proxy_worker *worker;
1352     proxy_worker *max_worker = NULL;
1353     int max_match = 0;
1354     int url_length;
1355     int min_match;
1356     int worker_name_length;
1357     const char *c;
1358     char *url_copy;
1359     int i;
1360
1361     c = ap_strchr_c(url, ':');
1362     if (c == NULL || c[1] != '/' || c[2] != '/' || c[3] == '\0') {
1363        return NULL;
1364     }
1365
1366     url_copy = apr_pstrdup(p, url);
1367     url_length = strlen(url);
1368
1369     /*
1370      * We need to find the start of the path and
1371      * therefore we know the length of the scheme://hostname/
1372      * part to we can force-lowercase everything up to
1373      * the start of the path.
1374      */
1375     c = ap_strchr_c(c+3, '/');
1376     if (c) {
1377         char *pathstart;
1378         pathstart = url_copy + (c - url);
1379         *pathstart = '\0';
1380         ap_str_tolower(url_copy);
1381         min_match = strlen(url_copy);
1382         *pathstart = '/';
1383     }
1384     else {
1385         ap_str_tolower(url_copy);
1386         min_match = strlen(url_copy);
1387     }
1388
1389     worker = (proxy_worker *)conf->workers->elts;
1390
1391     /*
1392      * Do a "longest match" on the worker name to find the worker that
1393      * fits best to the URL, but keep in mind that we must have at least
1394      * a minimum matching of length min_match such that
1395      * scheme://hostname[:port] matches between worker and url.
1396      */
1397     for (i = 0; i < conf->workers->nelts; i++) {
1398         if ( ((worker_name_length = strlen(worker->name)) <= url_length)
1399            && (worker_name_length >= min_match)
1400            && (worker_name_length > max_match)
1401            && (strncmp(url_copy, worker->name, worker_name_length) == 0) ) {
1402             max_worker = worker;
1403             max_match = worker_name_length;
1404         }
1405         worker++;
1406     }
1407     return max_worker;
1408 }
1409
1410 #if APR_HAS_THREADS
1411 static apr_status_t conn_pool_cleanup(void *theworker)
1412 {
1413     proxy_worker *worker = (proxy_worker *)theworker;
1414     if (worker->cp->res) {
1415         worker->cp->pool = NULL;
1416     }
1417     return APR_SUCCESS;
1418 }
1419 #endif
1420
1421 static void init_conn_pool(apr_pool_t *p, proxy_worker *worker)
1422 {
1423     apr_pool_t *pool;
1424     proxy_conn_pool *cp;
1425
1426     /*
1427      * Create a connection pool's subpool.
1428      * This pool is used for connection recycling.
1429      * Once the worker is added it is never removed but
1430      * it can be disabled.
1431      */
1432     apr_pool_create(&pool, p);
1433     apr_pool_tag(pool, "proxy_worker_cp");
1434     /*
1435      * Alloc from the same pool as worker.
1436      * proxy_conn_pool is permanently attached to the worker.
1437      */
1438     cp = (proxy_conn_pool *)apr_pcalloc(p, sizeof(proxy_conn_pool));
1439     cp->pool = pool;
1440     worker->cp = cp;
1441 }
1442
1443 PROXY_DECLARE(const char *) ap_proxy_add_worker(proxy_worker **worker,
1444                                                 apr_pool_t *p,
1445                                                 proxy_server_conf *conf,
1446                                                 const char *url)
1447 {
1448     int rv;
1449     apr_uri_t uri;
1450
1451     rv = apr_uri_parse(p, url, &uri);
1452
1453     if (rv != APR_SUCCESS) {
1454         return "Unable to parse URL";
1455     }
1456     if (!uri.hostname || !uri.scheme) {
1457         return "URL must be absolute!";
1458     }
1459
1460     ap_str_tolower(uri.hostname);
1461     ap_str_tolower(uri.scheme);
1462     *worker = apr_array_push(conf->workers);
1463     memset(*worker, 0, sizeof(proxy_worker));
1464     (*worker)->name = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD);
1465     (*worker)->scheme = uri.scheme;
1466     (*worker)->hostname = uri.hostname;
1467     (*worker)->port = uri.port;
1468     (*worker)->id   = proxy_lb_workers;
1469     (*worker)->flush_packets = flush_off;
1470     (*worker)->flush_wait = PROXY_FLUSH_WAIT;
1471     (*worker)->smax = -1;
1472     /* Increase the total worker count */
1473     proxy_lb_workers++;
1474     (*worker)->cp = NULL;
1475     (*worker)->mutex = NULL;
1476
1477     return NULL;
1478 }
1479
1480 PROXY_DECLARE(proxy_worker *) ap_proxy_create_worker(apr_pool_t *p)
1481 {
1482
1483     proxy_worker *worker;
1484     worker = (proxy_worker *)apr_pcalloc(p, sizeof(proxy_worker));
1485     worker->id = proxy_lb_workers;
1486     worker->smax = -1;
1487     /* Increase the total worker count */
1488     proxy_lb_workers++;
1489     worker->cp = NULL;
1490     worker->mutex = NULL;
1491
1492     return worker;
1493 }
1494
1495 PROXY_DECLARE(void)
1496 ap_proxy_add_worker_to_balancer(apr_pool_t *pool, proxy_balancer *balancer,
1497                                 proxy_worker *worker)
1498 {
1499     proxy_worker **runtime;
1500
1501     runtime = apr_array_push(balancer->workers);
1502     *runtime = worker;
1503     (*runtime)->id = proxy_lb_workers;
1504     /* Increase the total runtime count */
1505     proxy_lb_workers++;
1506
1507 }
1508
1509 PROXY_DECLARE(int) ap_proxy_pre_request(proxy_worker **worker,
1510                                         proxy_balancer **balancer,
1511                                         request_rec *r,
1512                                         proxy_server_conf *conf, char **url)
1513 {
1514     int access_status;
1515
1516     access_status = proxy_run_pre_request(worker, balancer, r, conf, url);
1517     if (access_status == DECLINED && *balancer == NULL) {
1518         *worker = ap_proxy_get_worker(r->pool, conf, *url);
1519         if (*worker) {
1520             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1521                           "proxy: %s: found worker %s for %s",
1522                            (*worker)->scheme, (*worker)->name, *url);
1523
1524             *balancer = NULL;
1525             access_status = OK;
1526         }
1527         else if (r->proxyreq == PROXYREQ_PROXY) {
1528             if (conf->forward) {
1529                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1530                               "proxy: *: found forward proxy worker for %s",
1531                                *url);
1532                 *balancer = NULL;
1533                 *worker = conf->forward;
1534                 access_status = OK;
1535             }
1536         }
1537         else if (r->proxyreq == PROXYREQ_REVERSE) {
1538             if (conf->reverse) {
1539                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1540                               "proxy: *: found reverse proxy worker for %s",
1541                                *url);
1542                 *balancer = NULL;
1543                 *worker = conf->reverse;
1544                 access_status = OK;
1545             }
1546         }
1547     }
1548     else if (access_status == DECLINED && *balancer != NULL) {
1549         /* All the workers are busy */
1550         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1551           "proxy: all workers are busy.  Unable to serve %s",
1552           *url);
1553         access_status = HTTP_SERVICE_UNAVAILABLE;
1554     }
1555     return access_status;
1556 }
1557
1558 PROXY_DECLARE(int) ap_proxy_post_request(proxy_worker *worker,
1559                                          proxy_balancer *balancer,
1560                                          request_rec *r,
1561                                          proxy_server_conf *conf)
1562 {
1563     int access_status = OK;
1564     if (balancer) {
1565         access_status = proxy_run_post_request(worker, balancer, r, conf);
1566         if (access_status == DECLINED) {
1567             access_status = OK; /* no post_request handler available */
1568             /* TODO: recycle direct worker */
1569         }
1570     }
1571
1572     return access_status;
1573 }
1574
1575 /* DEPRECATED */
1576 PROXY_DECLARE(int) ap_proxy_connect_to_backend(apr_socket_t **newsock,
1577                                                const char *proxy_function,
1578                                                apr_sockaddr_t *backend_addr,
1579                                                const char *backend_name,
1580                                                proxy_server_conf *conf,
1581                                                server_rec *s,
1582                                                apr_pool_t *p)
1583 {
1584     apr_status_t rv;
1585     int connected = 0;
1586     int loglevel;
1587
1588     while (backend_addr && !connected) {
1589         if ((rv = apr_socket_create(newsock, backend_addr->family,
1590                                     SOCK_STREAM, 0, p)) != APR_SUCCESS) {
1591             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1592             ap_log_error(APLOG_MARK, loglevel, rv, s,
1593                          "proxy: %s: error creating fam %d socket for target %s",
1594                          proxy_function,
1595                          backend_addr->family,
1596                          backend_name);
1597             /*
1598              * this could be an IPv6 address from the DNS but the
1599              * local machine won't give us an IPv6 socket; hopefully the
1600              * DNS returned an additional address to try
1601              */
1602             backend_addr = backend_addr->next;
1603             continue;
1604         }
1605
1606         if (conf->recv_buffer_size > 0 &&
1607             (rv = apr_socket_opt_set(*newsock, APR_SO_RCVBUF,
1608                                      conf->recv_buffer_size))) {
1609             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1610                          "apr_socket_opt_set(SO_RCVBUF): Failed to set "
1611                          "ProxyReceiveBufferSize, using default");
1612         }
1613
1614         rv = apr_socket_opt_set(*newsock, APR_TCP_NODELAY, 1);
1615         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1616              ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
1617                           "apr_socket_opt_set(APR_TCP_NODELAY): "
1618                           "Failed to set");
1619         }
1620
1621         /* Set a timeout on the socket */
1622         if (conf->timeout_set == 1) {
1623             apr_socket_timeout_set(*newsock, conf->timeout);
1624         }
1625         else {
1626              apr_socket_timeout_set(*newsock, s->timeout);
1627         }
1628
1629         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1630                      "proxy: %s: fam %d socket created to connect to %s",
1631                      proxy_function, backend_addr->family, backend_name);
1632
1633         /* make the connection out of the socket */
1634         rv = apr_socket_connect(*newsock, backend_addr);
1635
1636         /* if an error occurred, loop round and try again */
1637         if (rv != APR_SUCCESS) {
1638             apr_socket_close(*newsock);
1639             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
1640             ap_log_error(APLOG_MARK, loglevel, rv, s,
1641                          "proxy: %s: attempt to connect to %pI (%s) failed",
1642                          proxy_function,
1643                          backend_addr,
1644                          backend_name);
1645             backend_addr = backend_addr->next;
1646             continue;
1647         }
1648         connected = 1;
1649     }
1650     return connected ? 0 : 1;
1651 }
1652
1653 static apr_status_t connection_cleanup(void *theconn)
1654 {
1655     proxy_conn_rec *conn = (proxy_conn_rec *)theconn;
1656     proxy_worker *worker = conn->worker;
1657
1658     /*
1659      * If the connection pool is NULL the worker
1660      * cleanup has been run. Just return.
1661      */
1662     if (!worker->cp) {
1663         return APR_SUCCESS;
1664     }
1665
1666 #if APR_HAS_THREADS
1667     /* Sanity check: Did we already return the pooled connection? */
1668     if (conn->inreslist) {
1669         ap_log_perror(APLOG_MARK, APLOG_ERR, 0, conn->pool,
1670                       "proxy: Pooled connection 0x%pp for worker %s has been"
1671                       " already returned to the connection pool.", conn,
1672                       worker->name);
1673         return APR_SUCCESS;
1674     }
1675 #endif
1676
1677     /* determine if the connection need to be closed */
1678     if (conn->close || !worker->is_address_reusable || worker->disablereuse) {
1679         apr_pool_t *p = conn->pool;
1680         apr_pool_clear(p);
1681         conn = apr_pcalloc(p, sizeof(proxy_conn_rec));
1682         conn->pool = p;
1683         conn->worker = worker;
1684         apr_pool_create(&(conn->scpool), p);
1685         apr_pool_tag(conn->scpool, "proxy_conn_scpool");
1686     }
1687 #if APR_HAS_THREADS
1688     if (worker->hmax && worker->cp->res) {
1689         conn->inreslist = 1;
1690         apr_reslist_release(worker->cp->res, (void *)conn);
1691     }
1692     else
1693 #endif
1694     {
1695         worker->cp->conn = conn;
1696     }
1697
1698     /* Always return the SUCCESS */
1699     return APR_SUCCESS;
1700 }
1701
1702 static void socket_cleanup(proxy_conn_rec *conn)
1703 {
1704     conn->sock = NULL;
1705     conn->connection = NULL;
1706     apr_pool_clear(conn->scpool);
1707 }
1708
1709 PROXY_DECLARE(apr_status_t) ap_proxy_ssl_connection_cleanup(proxy_conn_rec *conn,
1710                                                             request_rec *r)
1711 {
1712     apr_bucket_brigade *bb;
1713     apr_status_t rv;
1714
1715     /*
1716      * If we have an existing SSL connection it might be possible that the
1717      * server sent some SSL message we have not read so far (e.g. a SSL
1718      * shutdown message if the server closed the keepalive connection while
1719      * the connection was held unused in our pool).
1720      * So ensure that if present (=> APR_NONBLOCK_READ) it is read and
1721      * processed. We don't expect any data to be in the returned brigade.
1722      */
1723     if (conn->sock && conn->connection) {
1724         bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1725         rv = ap_get_brigade(conn->connection->input_filters, bb,
1726                             AP_MODE_READBYTES, APR_NONBLOCK_READ,
1727                             HUGE_STRING_LEN);
1728         if ((rv != APR_SUCCESS) && !APR_STATUS_IS_EAGAIN(rv)) {
1729             socket_cleanup(conn);
1730         }
1731         if (!APR_BRIGADE_EMPTY(bb)) {
1732             apr_off_t len;
1733
1734             rv = apr_brigade_length(bb, 0, &len);
1735             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r,
1736                           "proxy: SSL cleanup brigade contained %"
1737                           APR_OFF_T_FMT " bytes of data.", len);
1738         }
1739         apr_brigade_destroy(bb);
1740     }
1741     return APR_SUCCESS;
1742 }
1743
1744 /* reslist constructor */
1745 static apr_status_t connection_constructor(void **resource, void *params,
1746                                            apr_pool_t *pool)
1747 {
1748     apr_pool_t *ctx;
1749     apr_pool_t *scpool;
1750     proxy_conn_rec *conn;
1751     proxy_worker *worker = (proxy_worker *)params;
1752
1753     /*
1754      * Create the subpool for each connection
1755      * This keeps the memory consumption constant
1756      * when disconnecting from backend.
1757      */
1758     apr_pool_create(&ctx, pool);
1759     apr_pool_tag(ctx, "proxy_conn_pool");
1760     /*
1761      * Create another subpool that manages the data for the
1762      * socket and the connection member of the proxy_conn_rec struct as we
1763      * destroy this data more frequently than other data in the proxy_conn_rec
1764      * struct like hostname and addr (at least in the case where we have
1765      * keepalive connections that timed out).
1766      */
1767     apr_pool_create(&scpool, ctx);
1768     apr_pool_tag(scpool, "proxy_conn_scpool");
1769     conn = apr_pcalloc(ctx, sizeof(proxy_conn_rec));
1770
1771     conn->pool   = ctx;
1772     conn->scpool = scpool;
1773     conn->worker = worker;
1774 #if APR_HAS_THREADS
1775     conn->inreslist = 1;
1776 #endif
1777     *resource = conn;
1778
1779     return APR_SUCCESS;
1780 }
1781
1782 #if APR_HAS_THREADS /* only needed when threads are used */
1783 /* reslist destructor */
1784 static apr_status_t connection_destructor(void *resource, void *params,
1785                                           apr_pool_t *pool)
1786 {
1787     proxy_conn_rec *conn = (proxy_conn_rec *)resource;
1788
1789     /* Destroy the pool only if not called from reslist_destroy */
1790     if (conn->worker->cp->pool) {
1791         apr_pool_destroy(conn->pool);
1792     }
1793
1794     return APR_SUCCESS;
1795 }
1796 #endif
1797
1798 /*
1799  * ap_proxy_initialize_worker_share() concerns itself
1800  * with initializing those parts of worker which
1801  * are, or could be, shared. Basically worker->s
1802  */
1803 PROXY_DECLARE(void) ap_proxy_initialize_worker_share(proxy_server_conf *conf,
1804                                                      proxy_worker *worker,
1805                                                      server_rec *s)
1806 {
1807     proxy_worker_stat *score = NULL;
1808
1809     if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1810         /* The worker share is already initialized */
1811         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1812               "proxy: worker %s already initialized",
1813               worker->name);
1814         return;
1815     }
1816     if (!worker->s) {
1817         /* Get scoreboard slot */
1818         if (ap_scoreboard_image) {
1819             score = (proxy_worker_stat *) ap_get_scoreboard_lb(worker->id);
1820             if (!score) {
1821                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
1822                       "proxy: ap_get_scoreboard_lb(%d) failed in child %" APR_PID_T_FMT " for worker %s",
1823                       worker->id, getpid(), worker->name);
1824             }
1825             else {
1826                  ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1827                       "proxy: grabbed scoreboard slot %d in child %" APR_PID_T_FMT " for worker %s",
1828                       worker->id, getpid(), worker->name);
1829             }
1830         }
1831         if (!score) {
1832             score = (proxy_worker_stat *) apr_pcalloc(conf->pool, sizeof(proxy_worker_stat));
1833             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1834                   "proxy: initialized plain memory in child %" APR_PID_T_FMT " for worker %s",
1835                   getpid(), worker->name);
1836         }
1837         worker->s = score;
1838         /*
1839          * recheck to see if we've already been here. Possible
1840          * if proxy is using scoreboard to hold shared stats
1841          */
1842         if (PROXY_WORKER_IS_INITIALIZED(worker)) {
1843             /* The worker share is already initialized */
1844             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1845                   "proxy: worker %s already initialized",
1846                   worker->name);
1847             return;
1848         }
1849     }
1850     if (worker->route) {
1851         strcpy(worker->s->route, worker->route);
1852     }
1853     else {
1854         *worker->s->route = '\0';
1855     }
1856     if (worker->redirect) {
1857         strcpy(worker->s->redirect, worker->redirect);
1858     }
1859     else {
1860         *worker->s->redirect = '\0';
1861     }
1862
1863     worker->s->status |= (worker->status | PROXY_WORKER_INITIALIZED);
1864
1865 }
1866
1867 PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, server_rec *s, apr_pool_t *p)
1868 {
1869     apr_status_t rv;
1870
1871 #if APR_HAS_THREADS
1872     int mpm_threads;
1873 #endif
1874
1875     if (worker->status & PROXY_WORKER_INITIALIZED) {
1876         /* The worker is already initialized */
1877         return APR_SUCCESS;
1878     }
1879
1880     /* Set default parameters */
1881     if (!worker->retry_set) {
1882         worker->retry = apr_time_from_sec(PROXY_WORKER_DEFAULT_RETRY);
1883     }
1884     /* By default address is reusable unless DisableReuse is set */
1885     if (worker->disablereuse) {
1886         worker->is_address_reusable = 0;
1887     }
1888     else {
1889         worker->is_address_reusable = 1;
1890     }
1891
1892     if (worker->cp == NULL)
1893         init_conn_pool(p, worker);
1894     if (worker->cp == NULL) {
1895         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1896             "can not create connection pool");
1897         return APR_EGENERAL;
1898     } 
1899
1900 #if APR_HAS_THREADS
1901     if (worker->mutex == NULL) {
1902         rv = apr_thread_mutex_create(&(worker->mutex), APR_THREAD_MUTEX_DEFAULT, p);
1903         if (rv != APR_SUCCESS) {
1904             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1905                 "can not create thread mutex");
1906             return rv;
1907         }
1908     }
1909
1910     ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
1911     if (mpm_threads > 1) {
1912         /* Set hard max to no more then mpm_threads */
1913         if (worker->hmax == 0 || worker->hmax > mpm_threads) {
1914             worker->hmax = mpm_threads;
1915         }
1916         if (worker->smax == -1 || worker->smax > worker->hmax) {
1917             worker->smax = worker->hmax;
1918         }
1919         /* Set min to be lower then smax */
1920         if (worker->min > worker->smax) {
1921             worker->min = worker->smax;
1922         }
1923     }
1924     else {
1925         /* This will supress the apr_reslist creation */
1926         worker->min = worker->smax = worker->hmax = 0;
1927     }
1928     if (worker->hmax) {
1929         rv = apr_reslist_create(&(worker->cp->res),
1930                                 worker->min, worker->smax,
1931                                 worker->hmax, worker->ttl,
1932                                 connection_constructor, connection_destructor,
1933                                 worker, worker->cp->pool);
1934
1935         apr_pool_cleanup_register(worker->cp->pool, (void *)worker,
1936                                   conn_pool_cleanup,
1937                                   apr_pool_cleanup_null);
1938
1939         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1940             "proxy: initialized worker %d in child %" APR_PID_T_FMT " for (%s) min=%d max=%d smax=%d",
1941              worker->id, getpid(), worker->hostname, worker->min,
1942              worker->hmax, worker->smax);
1943
1944 #if (APR_MAJOR_VERSION > 0)
1945         /* Set the acquire timeout */
1946         if (rv == APR_SUCCESS && worker->acquire_set) {
1947             apr_reslist_timeout_set(worker->cp->res, worker->acquire);
1948         }
1949 #endif
1950     }
1951     else
1952 #endif
1953     {
1954         void *conn;
1955
1956         rv = connection_constructor(&conn, worker, worker->cp->pool);
1957         worker->cp->conn = conn;
1958
1959         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1960              "proxy: initialized single connection worker %d in child %" APR_PID_T_FMT " for (%s)",
1961              worker->id, getpid(), worker->hostname);
1962     }
1963     if (rv == APR_SUCCESS) {
1964         worker->status |= (PROXY_WORKER_INITIALIZED);
1965     }
1966     return rv;
1967 }
1968
1969 PROXY_DECLARE(int) ap_proxy_retry_worker(const char *proxy_function,
1970                                          proxy_worker *worker,
1971                                          server_rec *s)
1972 {
1973     if (worker->s->status & PROXY_WORKER_IN_ERROR) {
1974         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1975                     "proxy: %s: retrying the worker for (%s)",
1976                      proxy_function, worker->hostname);
1977         if (apr_time_now() > worker->s->error_time + worker->retry) {
1978             ++worker->s->retries;
1979             worker->s->status &= ~PROXY_WORKER_IN_ERROR;
1980             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1981                          "proxy: %s: worker for (%s) has been marked for retry",
1982                          proxy_function, worker->hostname);
1983             return OK;
1984         }
1985         else {
1986             return DECLINED;
1987         }
1988     }
1989     else {
1990         return OK;
1991     }
1992 }
1993
1994 PROXY_DECLARE(int) ap_proxy_acquire_connection(const char *proxy_function,
1995                                                proxy_conn_rec **conn,
1996                                                proxy_worker *worker,
1997                                                server_rec *s)
1998 {
1999     apr_status_t rv;
2000
2001     if (!PROXY_WORKER_IS_USABLE(worker)) {
2002         /* Retry the worker */
2003         ap_proxy_retry_worker(proxy_function, worker, s);
2004
2005         if (!PROXY_WORKER_IS_USABLE(worker)) {
2006             ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2007                          "proxy: %s: disabled connection for (%s)",
2008                          proxy_function, worker->hostname);
2009             return HTTP_SERVICE_UNAVAILABLE;
2010         }
2011     }
2012 #if APR_HAS_THREADS
2013     if (worker->hmax && worker->cp->res) {
2014         rv = apr_reslist_acquire(worker->cp->res, (void **)conn);
2015     }
2016     else
2017 #endif
2018     {
2019         /* create the new connection if the previous was destroyed */
2020         if (!worker->cp->conn) {
2021             connection_constructor((void **)conn, worker, worker->cp->pool);
2022         }
2023         else {
2024             *conn = worker->cp->conn;
2025             worker->cp->conn = NULL;
2026         }
2027         rv = APR_SUCCESS;
2028     }
2029
2030     if (rv != APR_SUCCESS) {
2031         ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2032                      "proxy: %s: failed to acquire connection for (%s)",
2033                      proxy_function, worker->hostname);
2034         return HTTP_SERVICE_UNAVAILABLE;
2035     }
2036     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2037                  "proxy: %s: has acquired connection for (%s)",
2038                  proxy_function, worker->hostname);
2039
2040     (*conn)->worker = worker;
2041     (*conn)->close  = 0;
2042 #if APR_HAS_THREADS
2043     (*conn)->inreslist = 0;
2044 #endif
2045
2046     return OK;
2047 }
2048
2049 PROXY_DECLARE(int) ap_proxy_release_connection(const char *proxy_function,
2050                                                proxy_conn_rec *conn,
2051                                                server_rec *s)
2052 {
2053     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2054                  "proxy: %s: has released connection for (%s)",
2055                  proxy_function, conn->worker->hostname);
2056     connection_cleanup(conn);
2057
2058     return OK;
2059 }
2060
2061 PROXY_DECLARE(int)
2062 ap_proxy_determine_connection(apr_pool_t *p, request_rec *r,
2063                               proxy_server_conf *conf,
2064                               proxy_worker *worker,
2065                               proxy_conn_rec *conn,
2066                               apr_uri_t *uri,
2067                               char **url,
2068                               const char *proxyname,
2069                               apr_port_t proxyport,
2070                               char *server_portstr,
2071                               int server_portstr_size)
2072 {
2073     int server_port;
2074     apr_status_t err = APR_SUCCESS;
2075     apr_status_t uerr = APR_SUCCESS;
2076
2077     /*
2078      * Break up the URL to determine the host to connect to
2079      */
2080
2081     /* we break the URL into host, port, uri */
2082     if (APR_SUCCESS != apr_uri_parse(p, *url, uri)) {
2083         return ap_proxyerror(r, HTTP_BAD_REQUEST,
2084                              apr_pstrcat(p,"URI cannot be parsed: ", *url,
2085                                          NULL));
2086     }
2087     if (!uri->port) {
2088         uri->port = apr_uri_port_of_scheme(uri->scheme);
2089     }
2090
2091     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2092                  "proxy: connecting %s to %s:%d", *url, uri->hostname,
2093                  uri->port);
2094
2095     /*
2096      * allocate these out of the specified connection pool
2097      * The scheme handler decides if this is permanent or
2098      * short living pool.
2099      */
2100     /* are we connecting directly, or via a proxy? */
2101     if (!proxyname) {
2102         *url = apr_pstrcat(p, uri->path, uri->query ? "?" : "",
2103                            uri->query ? uri->query : "",
2104                            uri->fragment ? "#" : "",
2105                            uri->fragment ? uri->fragment : "", NULL);
2106     }
2107     /*
2108      * Make sure that we pick the the correct and valid worker.
2109      * If a single keepalive connection triggers different workers,
2110      * then we have a problem (we don't select the correct one).
2111      * Do an expensive check in this case, where we compare the
2112      * the hostnames associated between the two.
2113      *
2114      * TODO: Handle this much better...
2115      */
2116     if (!conn->hostname || !worker->is_address_reusable || 
2117          worker->disablereuse ||
2118          (r->connection->keepalives &&
2119          (r->proxyreq == PROXYREQ_PROXY || r->proxyreq == PROXYREQ_REVERSE) &&
2120          (strcasecmp(conn->hostname, uri->hostname) != 0) ) ) {
2121         if (proxyname) {
2122             conn->hostname = apr_pstrdup(conn->pool, proxyname);
2123             conn->port = proxyport;
2124             /*
2125              * If we have a forward proxy and the protocol is HTTPS,
2126              * then we need to prepend a HTTP CONNECT request before
2127              * sending our actual HTTPS requests.
2128              * Save our real backend data for using it later during HTTP CONNECT.
2129              */
2130             if (conn->is_ssl) {
2131                 const char *proxy_auth;
2132
2133                 forward_info *forward = apr_pcalloc(conn->pool, sizeof(forward_info));
2134                 conn->forward = forward;
2135                 forward->use_http_connect = 1;
2136                 forward->target_host = apr_pstrdup(conn->pool, uri->hostname);
2137                 forward->target_port = uri->port;
2138                 /* Do we want to pass Proxy-Authorization along?
2139                  * If we haven't used it, then YES
2140                  * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
2141                  * So let's make it configurable by env.
2142                  * The logic here is the same used in mod_proxy_http.
2143                  */
2144                 proxy_auth = apr_table_get(r->headers_in, "Proxy-Authorization");
2145                 if (proxy_auth != NULL &&
2146                     proxy_auth[0] != '\0' &&
2147                     r->user == NULL && /* we haven't yet authenticated */
2148                     apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
2149                     forward->proxy_auth = apr_pstrdup(conn->pool, proxy_auth);
2150                 }
2151             }
2152         }
2153         else {
2154             conn->hostname = apr_pstrdup(conn->pool, uri->hostname);
2155             conn->port = uri->port;
2156         }
2157         socket_cleanup(conn);
2158         err = apr_sockaddr_info_get(&(conn->addr),
2159                                     conn->hostname, APR_UNSPEC,
2160                                     conn->port, 0,
2161                                     conn->pool);
2162     }
2163     else if (!worker->cp->addr) {
2164         if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
2165             ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
2166                          "proxy: lock");
2167             return HTTP_INTERNAL_SERVER_ERROR;
2168         }
2169
2170         /*
2171          * Worker can have the single constant backend adress.
2172          * The single DNS lookup is used once per worker.
2173          * If dynamic change is needed then set the addr to NULL
2174          * inside dynamic config to force the lookup.
2175          */
2176         err = apr_sockaddr_info_get(&(worker->cp->addr),
2177                                     conn->hostname, APR_UNSPEC,
2178                                     conn->port, 0,
2179                                     worker->cp->pool);
2180         conn->addr = worker->cp->addr;
2181         if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
2182             ap_log_error(APLOG_MARK, APLOG_ERR, uerr, r->server,
2183                          "proxy: unlock");
2184         }
2185     }
2186     else {
2187         conn->addr = worker->cp->addr;
2188     }
2189     /* Close a possible existing socket if we are told to do so */
2190     if (conn->close) {
2191         socket_cleanup(conn);
2192         conn->close = 0;
2193     }
2194
2195     if (err != APR_SUCCESS) {
2196         return ap_proxyerror(r, HTTP_BAD_GATEWAY,
2197                              apr_pstrcat(p, "DNS lookup failure for: ",
2198                                          conn->hostname, NULL));
2199     }
2200
2201     /* Get the server port for the Via headers */
2202     {
2203         server_port = ap_get_server_port(r);
2204         if (ap_is_default_port(server_port, r)) {
2205             strcpy(server_portstr,"");
2206         }
2207         else {
2208             apr_snprintf(server_portstr, server_portstr_size, ":%d",
2209                          server_port);
2210         }
2211     }
2212     /* check if ProxyBlock directive on this host */
2213     if (OK != ap_proxy_checkproxyblock(r, conf, conn->addr)) {
2214         return ap_proxyerror(r, HTTP_FORBIDDEN,
2215                              "Connect to remote machine blocked");
2216     }
2217     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
2218                  "proxy: connected %s to %s:%d", *url, conn->hostname,
2219                  conn->port);
2220     return OK;
2221 }
2222
2223 #define USE_ALTERNATE_IS_CONNECTED 1
2224
2225 #if !defined(APR_MSG_PEEK) && defined(MSG_PEEK)
2226 #define APR_MSG_PEEK MSG_PEEK
2227 #endif
2228
2229 #if USE_ALTERNATE_IS_CONNECTED && defined(APR_MSG_PEEK)
2230 static int is_socket_connected(apr_socket_t *socket)
2231 {
2232     apr_pollfd_t pfds[1];
2233     apr_status_t status;
2234     apr_int32_t  nfds;
2235
2236     pfds[0].reqevents = APR_POLLIN;
2237     pfds[0].desc_type = APR_POLL_SOCKET;
2238     pfds[0].desc.s = socket;
2239
2240     do {
2241         status = apr_poll(&pfds[0], 1, &nfds, 0);
2242     } while (APR_STATUS_IS_EINTR(status));
2243
2244     if (status == APR_SUCCESS && nfds == 1 &&
2245         pfds[0].rtnevents == APR_POLLIN) {
2246         apr_sockaddr_t unused;
2247         apr_size_t len = 1;
2248         char buf[1];
2249         /* The socket might be closed in which case
2250          * the poll will return POLLIN.
2251          * If there is no data available the socket
2252          * is closed.
2253          */
2254         status = apr_socket_recvfrom(&unused, socket, APR_MSG_PEEK,
2255                                      &buf[0], &len);
2256         if (status == APR_SUCCESS && len)
2257             return 1;
2258         else
2259             return 0;
2260     }
2261     else if (APR_STATUS_IS_EAGAIN(status) || APR_STATUS_IS_TIMEUP(status)) {
2262         return 1;
2263     }
2264     return 0;
2265
2266 }
2267 #else
2268 static int is_socket_connected(apr_socket_t *sock)
2269
2270 {
2271     apr_size_t buffer_len = 1;
2272     char test_buffer[1];
2273     apr_status_t socket_status;
2274     apr_interval_time_t current_timeout;
2275
2276     /* save timeout */
2277     apr_socket_timeout_get(sock, &current_timeout);
2278     /* set no timeout */
2279     apr_socket_timeout_set(sock, 0);
2280     socket_status = apr_socket_recv(sock, test_buffer, &buffer_len);
2281     /* put back old timeout */
2282     apr_socket_timeout_set(sock, current_timeout);
2283     if (APR_STATUS_IS_EOF(socket_status)
2284         || APR_STATUS_IS_ECONNRESET(socket_status)) {
2285         return 0;
2286     }
2287     else {
2288         return 1;
2289     }
2290 }
2291 #endif /* USE_ALTERNATE_IS_CONNECTED */
2292
2293
2294 /*
2295  * Send a HTTP CONNECT request to a forward proxy.
2296  * The proxy is given by "backend", the target server
2297  * is contained in the "forward" member of "backend".
2298  */
2299 static apr_status_t send_http_connect(proxy_conn_rec *backend,
2300                                       server_rec *s)
2301 {
2302     int status;
2303     apr_size_t nbytes;
2304     apr_size_t left;
2305     int complete = 0;
2306     char buffer[HUGE_STRING_LEN];
2307     char drain_buffer[HUGE_STRING_LEN];
2308     forward_info *forward = (forward_info *)backend->forward;
2309     int len = 0;
2310
2311     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2312                  "proxy: CONNECT: sending the CONNECT request for %s:%d "
2313                  "to the remote proxy %pI (%s)",
2314                  forward->target_host, forward->target_port,
2315                  backend->addr, backend->hostname);
2316     /* Create the CONNECT request */
2317     nbytes = apr_snprintf(buffer, sizeof(buffer),
2318                           "CONNECT %s:%d HTTP/1.0" CRLF,
2319                           forward->target_host, forward->target_port);
2320     /* Add proxy authorization from the initial request if necessary */
2321     if (forward->proxy_auth != NULL) {
2322         nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2323                                "Proxy-Authorization: %s" CRLF,
2324                                forward->proxy_auth);
2325     }
2326     /* Set a reasonable agent and send everything */
2327     nbytes += apr_snprintf(buffer + nbytes, sizeof(buffer) - nbytes,
2328                            "Proxy-agent: %s" CRLF CRLF,
2329                            ap_get_server_banner());
2330     apr_socket_send(backend->sock, buffer, &nbytes);
2331
2332     /* Receive the whole CONNECT response */
2333     left = sizeof(buffer) - 1;
2334     /* Read until we find the end of the headers or run out of buffer */
2335     do {
2336         nbytes = left;
2337         status = apr_socket_recv(backend->sock, buffer + len, &nbytes);
2338         len += nbytes;
2339         left -= nbytes;
2340         buffer[len] = '\0';
2341         if (strstr(buffer + len - nbytes, "\r\n\r\n") != NULL) {
2342             complete = 1;
2343             break;
2344         }
2345     } while (status == APR_SUCCESS && left > 0);
2346     /* Drain what's left */
2347     if (!complete) {
2348         nbytes = sizeof(drain_buffer) - 1;
2349         while (status == APR_SUCCESS && nbytes) {
2350             status = apr_socket_recv(backend->sock, drain_buffer, &nbytes);
2351             buffer[nbytes] = '\0';
2352             nbytes = sizeof(drain_buffer) - 1;
2353             if (strstr(drain_buffer, "\r\n\r\n") != NULL) {
2354                 complete = 1;
2355                 break;
2356             }
2357         }
2358     }
2359
2360     /* Check for HTTP_OK response status */
2361     if (status == APR_SUCCESS) {
2362         int major, minor;
2363         /* Only scan for three character status code */
2364         char code_str[4];
2365
2366         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2367                      "send_http_connect: response from the forward proxy: %s",
2368                      buffer);
2369
2370         /* Extract the returned code */
2371         if (sscanf(buffer, "HTTP/%u.%u %3s", &major, &minor, code_str) == 3) {
2372             status = atoi(code_str);
2373             if (status == HTTP_OK) {
2374                 status = APR_SUCCESS;
2375             }
2376             else {
2377                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2378                              "send_http_connect: the forward proxy returned code is '%s'",
2379                              code_str);
2380             status = APR_INCOMPLETE;
2381             }
2382         }
2383     }
2384
2385     return(status);
2386 }
2387
2388
2389 PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function,
2390                                             proxy_conn_rec *conn,
2391                                             proxy_worker *worker,
2392                                             server_rec *s)
2393 {
2394     apr_status_t rv;
2395     int connected = 0;
2396     int loglevel;
2397     apr_sockaddr_t *backend_addr = conn->addr;
2398     apr_socket_t *newsock;
2399     void *sconf = s->module_config;
2400     proxy_server_conf *conf =
2401         (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
2402
2403     if (conn->sock) {
2404         if (!(connected = is_socket_connected(conn->sock))) {
2405             socket_cleanup(conn);
2406             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2407                          "proxy: %s: backend socket is disconnected.",
2408                          proxy_function);
2409         }
2410     }
2411     while (backend_addr && !connected) {
2412         if ((rv = apr_socket_create(&newsock, backend_addr->family,
2413                                 SOCK_STREAM, APR_PROTO_TCP,
2414                                 conn->scpool)) != APR_SUCCESS) {
2415             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2416             ap_log_error(APLOG_MARK, loglevel, rv, s,
2417                          "proxy: %s: error creating fam %d socket for target %s",
2418                          proxy_function,
2419                          backend_addr->family,
2420                          worker->hostname);
2421             /*
2422              * this could be an IPv6 address from the DNS but the
2423              * local machine won't give us an IPv6 socket; hopefully the
2424              * DNS returned an additional address to try
2425              */
2426             backend_addr = backend_addr->next;
2427             continue;
2428         }
2429         conn->connection = NULL;
2430
2431         if (worker->recv_buffer_size > 0 &&
2432             (rv = apr_socket_opt_set(newsock, APR_SO_RCVBUF,
2433                                      worker->recv_buffer_size))) {
2434             ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2435                          "apr_socket_opt_set(SO_RCVBUF): Failed to set "
2436                          "ProxyReceiveBufferSize, using default");
2437         }
2438
2439         rv = apr_socket_opt_set(newsock, APR_TCP_NODELAY, 1);
2440         if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
2441              ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2442                           "apr_socket_opt_set(APR_TCP_NODELAY): "
2443                           "Failed to set");
2444         }
2445
2446         /* Set a timeout for connecting to the backend on the socket */
2447         if (worker->conn_timeout_set) {
2448             apr_socket_timeout_set(newsock, worker->conn_timeout);
2449         }
2450         else if (worker->timeout_set == 1) {
2451             apr_socket_timeout_set(newsock, worker->timeout);
2452         }
2453         else if (conf->timeout_set == 1) {
2454             apr_socket_timeout_set(newsock, conf->timeout);
2455         }
2456         else {
2457              apr_socket_timeout_set(newsock, s->timeout);
2458         }
2459         /* Set a keepalive option */
2460         if (worker->keepalive) {
2461             if ((rv = apr_socket_opt_set(newsock,
2462                             APR_SO_KEEPALIVE, 1)) != APR_SUCCESS) {
2463                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
2464                              "apr_socket_opt_set(SO_KEEPALIVE): Failed to set"
2465                              " Keepalive");
2466             }
2467         }
2468         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2469                      "proxy: %s: fam %d socket created to connect to %s",
2470                      proxy_function, backend_addr->family, worker->hostname);
2471
2472         /* make the connection out of the socket */
2473         rv = apr_socket_connect(newsock, backend_addr);
2474
2475         /* if an error occurred, loop round and try again */
2476         if (rv != APR_SUCCESS) {
2477             apr_socket_close(newsock);
2478             loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2479             ap_log_error(APLOG_MARK, loglevel, rv, s,
2480                          "proxy: %s: attempt to connect to %pI (%s) failed",
2481                          proxy_function,
2482                          backend_addr,
2483                          worker->hostname);
2484             backend_addr = backend_addr->next;
2485             continue;
2486         }
2487
2488         /* Set a timeout on the socket */
2489         if (worker->timeout_set == 1) {
2490             apr_socket_timeout_set(newsock, worker->timeout);
2491         }
2492         else if (conf->timeout_set == 1) {
2493             apr_socket_timeout_set(newsock, conf->timeout);
2494         }
2495         else {
2496              apr_socket_timeout_set(newsock, s->timeout);
2497         }
2498
2499         conn->sock = newsock;
2500
2501         if (conn->forward) {
2502             forward_info *forward = (forward_info *)conn->forward;
2503             /*
2504              * For HTTP CONNECT we need to prepend CONNECT request before
2505              * sending our actual HTTPS requests.
2506              */
2507             if (forward->use_http_connect) {
2508                 rv = send_http_connect(conn, s);
2509                 /* If an error occurred, loop round and try again */
2510                 if (rv != APR_SUCCESS) {
2511                     conn->sock = NULL;
2512                     apr_socket_close(newsock);
2513                     loglevel = backend_addr->next ? APLOG_DEBUG : APLOG_ERR;
2514                     ap_log_error(APLOG_MARK, loglevel, rv, s,
2515                                  "proxy: %s: attempt to connect to %s:%d "
2516                                  "via http CONNECT through %pI (%s) failed",
2517                                  proxy_function,
2518                                  forward->target_host, forward->target_port,
2519                                  backend_addr, worker->hostname);
2520                     backend_addr = backend_addr->next;
2521                     continue;
2522                 }
2523             }
2524         }
2525
2526         connected    = 1;
2527     }
2528     /*
2529      * Put the entire worker to error state if
2530      * the PROXY_WORKER_IGNORE_ERRORS flag is not set.
2531      * Altrough some connections may be alive
2532      * no further connections to the worker could be made
2533      */
2534     if (!connected && PROXY_WORKER_IS_USABLE(worker) &&
2535         !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) {
2536         worker->s->status |= PROXY_WORKER_IN_ERROR;
2537         worker->s->error_time = apr_time_now();
2538         ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
2539             "ap_proxy_connect_backend disabling worker for (%s)",
2540             worker->hostname);
2541     }
2542     else {
2543         if (worker->s->retries) {
2544             /*
2545              * A worker came back. So here is where we need to
2546              * either reset all params to initial conditions or
2547              * apply some sort of aging
2548              */
2549         }
2550         worker->s->error_time = 0;
2551         worker->s->retries = 0;
2552     }
2553     return connected ? OK : DECLINED;
2554 }
2555
2556 PROXY_DECLARE(int) ap_proxy_connection_create(const char *proxy_function,
2557                                               proxy_conn_rec *conn,
2558                                               conn_rec *c,
2559                                               server_rec *s)
2560 {
2561     apr_sockaddr_t *backend_addr = conn->addr;
2562     int rc;
2563     apr_interval_time_t current_timeout;
2564     apr_bucket_alloc_t *bucket_alloc;
2565
2566     if (conn->connection) {
2567         return OK;
2568     }
2569
2570     bucket_alloc = apr_bucket_alloc_create(conn->scpool);
2571     /*
2572      * The socket is now open, create a new backend server connection
2573      */
2574     conn->connection = ap_run_create_connection(conn->scpool, s, conn->sock,
2575                                                 0, NULL,
2576                                                 bucket_alloc);
2577
2578     if (!conn->connection) {
2579         /*
2580          * the peer reset the connection already; ap_run_create_connection()
2581          * closed the socket
2582          */
2583         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
2584                      s, "proxy: %s: an error occurred creating a "
2585                      "new connection to %pI (%s)", proxy_function,
2586                      backend_addr, conn->hostname);
2587         /* XXX: Will be closed when proxy_conn is closed */
2588         socket_cleanup(conn);
2589         return HTTP_INTERNAL_SERVER_ERROR;
2590     }
2591
2592     /* For ssl connection to backend */
2593     if (conn->is_ssl) {
2594         if (!ap_proxy_ssl_enable(conn->connection)) {
2595             ap_log_error(APLOG_MARK, APLOG_ERR, 0,
2596                          s, "proxy: %s: failed to enable ssl support "
2597                          "for %pI (%s)", proxy_function,
2598                          backend_addr, conn->hostname);
2599             return HTTP_INTERNAL_SERVER_ERROR;
2600         }
2601     }
2602     else {
2603         /* TODO: See if this will break FTP */
2604         ap_proxy_ssl_disable(conn->connection);
2605     }
2606
2607     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2608                  "proxy: %s: connection complete to %pI (%s)",
2609                  proxy_function, backend_addr, conn->hostname);
2610
2611     /*
2612      * save the timeout of the socket because core_pre_connection
2613      * will set it to base_server->timeout
2614      * (core TimeOut directive).
2615      */
2616     apr_socket_timeout_get(conn->sock, &current_timeout);
2617     /* set up the connection filters */
2618     rc = ap_run_pre_connection(conn->connection, conn->sock);
2619     if (rc != OK && rc != DONE) {
2620         conn->connection->aborted = 1;
2621         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
2622                      "proxy: %s: pre_connection setup failed (%d)",
2623                      proxy_function, rc);
2624         return rc;
2625     }
2626     apr_socket_timeout_set(conn->sock, current_timeout);
2627
2628     return OK;
2629 }
2630
2631 int ap_proxy_lb_workers(void)
2632 {
2633     /*
2634      * Since we can't resize the scoreboard when reconfiguring, we
2635      * have to impose a limit on the number of workers, we are
2636      * able to reconfigure to.
2637      */
2638     if (!lb_workers_limit)
2639         lb_workers_limit = proxy_lb_workers + PROXY_DYNAMIC_BALANCER_LIMIT;
2640     return lb_workers_limit;
2641 }
2642
2643 PROXY_DECLARE(void) ap_proxy_backend_broke(request_rec *r,
2644                                            apr_bucket_brigade *brigade)
2645 {
2646     apr_bucket *e;
2647     conn_rec *c = r->connection;
2648
2649     r->no_cache = 1;
2650     /*
2651      * If this is a subrequest, then prevent also caching of the main
2652      * request.
2653      */
2654     if (r->main)
2655         r->main->no_cache = 1;
2656     e = ap_bucket_error_create(HTTP_BAD_GATEWAY, NULL, c->pool,
2657                                c->bucket_alloc);
2658     APR_BRIGADE_INSERT_TAIL(brigade, e);
2659     e = apr_bucket_eos_create(c->bucket_alloc);
2660     APR_BRIGADE_INSERT_TAIL(brigade, e);
2661 }
2662
2663 /*
2664  * Transform buckets from one bucket allocator to another one by creating a
2665  * transient bucket for each data bucket and let it use the data read from
2666  * the old bucket. Metabuckets are transformed by just recreating them.
2667  * Attention: Currently only the following bucket types are handled:
2668  *
2669  * All data buckets
2670  * FLUSH
2671  * EOS
2672  *
2673  * If an other bucket type is found its type is logged as a debug message
2674  * and APR_EGENERAL is returned.
2675  */
2676 PROXY_DECLARE(apr_status_t)
2677 ap_proxy_buckets_lifetime_transform(request_rec *r, apr_bucket_brigade *from,
2678                                     apr_bucket_brigade *to)
2679 {
2680     apr_bucket *e;
2681     apr_bucket *new;
2682     const char *data;
2683     apr_size_t bytes;
2684     apr_status_t rv = APR_SUCCESS;
2685
2686     apr_brigade_cleanup(to);
2687     for (e = APR_BRIGADE_FIRST(from);
2688          e != APR_BRIGADE_SENTINEL(from);
2689          e = APR_BUCKET_NEXT(e)) {
2690         if (!APR_BUCKET_IS_METADATA(e)) {
2691             apr_bucket_read(e, &data, &bytes, APR_BLOCK_READ);
2692             new = apr_bucket_transient_create(data, bytes, r->connection->bucket_alloc);
2693             APR_BRIGADE_INSERT_TAIL(to, new);
2694         }
2695         else if (APR_BUCKET_IS_FLUSH(e)) {
2696             new = apr_bucket_flush_create(r->connection->bucket_alloc);
2697             APR_BRIGADE_INSERT_TAIL(to, new);
2698         }
2699         else if (APR_BUCKET_IS_EOS(e)) {
2700             new = apr_bucket_eos_create(r->connection->bucket_alloc);
2701             APR_BRIGADE_INSERT_TAIL(to, new);
2702         }
2703         else {
2704             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2705                           "proxy: Unhandled bucket type of type %s in"
2706                           " ap_proxy_buckets_lifetime_transform", e->type->name);
2707             rv = APR_EGENERAL;
2708         }
2709     }
2710     return rv;
2711 }