Make home server coa config match raddb/proxy.conf
[freeradius.git] / src / main / realms.c
1 /*
2  * realms.c     Realm handling code
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2007  The FreeRADIUS server project
21  * Copyright 2007  Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 #include <sys/stat.h>
31
32 #include <ctype.h>
33 #include <fcntl.h>
34
35 #ifdef HAVE_REGEX_H
36 #include <regex.h>
37
38 /*
39  *  For POSIX Regular expressions.
40  *  (0) Means no extended regular expressions.
41  *  REG_EXTENDED means use extended regular expressions.
42  */
43 #ifndef REG_EXTENDED
44 #define REG_EXTENDED (0)
45 #endif
46
47 #ifndef REG_NOSUB
48 #define REG_NOSUB (0)
49 #endif
50
51 #ifndef REG_ICASE
52 #define REG_ICASE (0)
53 #endif
54 #endif
55
56 static rbtree_t *realms_byname = NULL;
57
58 #ifdef HAVE_REGEX_H
59 typedef struct realm_regex_t {
60         REALM   *realm;
61         struct realm_regex_t *next;
62 } realm_regex_t;
63
64 static realm_regex_t *realms_regex = NULL;
65
66 #endif /* HAVE_REGEX_H */
67
68 typedef struct realm_config_t {
69         CONF_SECTION    *cs;
70         int             dead_time;
71         int             retry_count;
72         int             retry_delay;
73         int             fallback;
74         int             wake_all_if_all_dead;
75 } realm_config_t;
76
77 static realm_config_t *realm_config = NULL;
78
79 #ifdef WITH_PROXY
80 static rbtree_t *home_servers_byaddr = NULL;
81 static rbtree_t *home_servers_byname = NULL;
82 #ifdef WITH_STATS
83 static int home_server_max_number = 0;
84 static rbtree_t *home_servers_bynumber = NULL;
85 #endif
86
87 static rbtree_t *home_pools_byname = NULL;
88
89 /*
90  *  Map the proxy server configuration parameters to variables.
91  */
92 static const CONF_PARSER proxy_config[] = {
93         { "retry_delay",  PW_TYPE_INTEGER,
94           offsetof(realm_config_t, retry_delay),
95           NULL, Stringify(RETRY_DELAY) },
96
97         { "retry_count",  PW_TYPE_INTEGER,
98           offsetof(realm_config_t, retry_count),
99           NULL, Stringify(RETRY_COUNT) },
100
101         { "default_fallback", PW_TYPE_BOOLEAN,
102           offsetof(realm_config_t, fallback),
103           NULL, "no" },
104
105         { "dead_time",    PW_TYPE_INTEGER, 
106           offsetof(realm_config_t, dead_time),
107           NULL, Stringify(DEAD_TIME) },
108
109         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN,
110           offsetof(realm_config_t, wake_all_if_all_dead),
111           NULL, "no" },
112
113         { NULL, -1, 0, NULL, NULL }
114 };
115 #endif
116
117 static int realm_name_cmp(const void *one, const void *two)
118 {
119         const REALM *a = one;
120         const REALM *b = two;
121
122         return strcasecmp(a->name, b->name);
123 }
124
125
126 #ifdef WITH_PROXY
127 static void home_server_free(void *data)
128 {
129         home_server *home = data;
130
131 #ifdef WITH_TLS
132         tls_server_conf_free(home->tls);
133         home->tls = NULL;
134 #endif
135
136         free(home);
137 }
138
139 static int home_server_name_cmp(const void *one, const void *two)
140 {
141         const home_server *a = one;
142         const home_server *b = two;
143
144         if (a->type < b->type) return -1;
145         if (a->type > b->type) return +1;
146
147         return strcasecmp(a->name, b->name);
148 }
149
150 static int home_server_addr_cmp(const void *one, const void *two)
151 {
152         const home_server *a = one;
153         const home_server *b = two;
154
155         if (a->server && !b->server) return -1;
156         if (!a->server && b->server) return +1;
157
158         if (a->server && b->server) {
159                 int rcode = a->type - b->type;
160                 if (rcode != 0) return rcode;
161                 return strcmp(a->server, b->server);
162         }
163
164 #ifdef WITH_TCP
165         if (a->proto < b->proto) return -1;
166         if (a->proto > b->proto) return +1;
167 #endif
168
169         if (a->port < b->port) return -1;
170         if (a->port > b->port) return +1;
171
172         return fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
173 }
174
175 #ifdef WITH_STATS
176 static int home_server_number_cmp(const void *one, const void *two)
177 {
178         const home_server *a = one;
179         const home_server *b = two;
180
181         return (a->number - b->number);
182 }
183 #endif
184
185 static int home_pool_name_cmp(const void *one, const void *two)
186 {
187         const home_pool_t *a = one;
188         const home_pool_t *b = two;
189
190         if (a->server_type < b->server_type) return -1;
191         if (a->server_type > b->server_type) return +1;
192
193         return strcasecmp(a->name, b->name);
194 }
195
196
197 static size_t xlat_cs(CONF_SECTION *cs, char *fmt, char *out, size_t outlen)
198
199 {
200         const char *value = NULL;
201
202         /*
203          *      Instance name
204          */
205         if (strcmp(fmt, "instance") == 0) {
206                 value = cf_section_name2(cs);
207                 if (!value) {
208                         *out = '\0';
209                         return 0;
210                 }
211         } else {
212                 CONF_PAIR *cp;
213
214                 cp = cf_pair_find(cs, fmt);
215                 if (!cp || !(value = cf_pair_value(cp))) {
216                         *out = '\0';
217                         return 0;
218                 }
219         }
220
221         strlcpy(out, value, outlen);
222
223         return strlen(out);
224 }
225
226
227 /*
228  *      Xlat for %{home_server:foo}
229  */
230 static size_t xlat_home_server(UNUSED void *instance, REQUEST *request,
231                                char *fmt, char *out, size_t outlen,
232                                UNUSED RADIUS_ESCAPE_STRING func)
233 {
234         if (!fmt || !out || (outlen < 1)) return 0;
235
236         if (!request || !request->home_server) {
237                 *out = '\0';
238                 return 0;
239         }
240
241         return xlat_cs(request->home_server->cs, fmt, out, outlen);
242 }
243
244
245 /*
246  *      Xlat for %{home_server_pool:foo}
247  */
248 static size_t xlat_server_pool(UNUSED void *instance, REQUEST *request,
249                                char *fmt, char *out, size_t outlen,
250                                UNUSED RADIUS_ESCAPE_STRING func)
251 {
252         if (!fmt || !out || (outlen < 1)) return 0;
253
254         if (!request || !request->home_pool) {
255                 *out = '\0';
256                 return 0;
257         }
258
259         return xlat_cs(request->home_pool->cs, fmt, out, outlen);
260 }
261 #endif
262
263 void realms_free(void)
264 {
265 #ifdef WITH_PROXY
266 #ifdef WITH_STATS
267         rbtree_free(home_servers_bynumber);
268         home_servers_bynumber = NULL;
269 #endif
270
271         rbtree_free(home_servers_byname);
272         home_servers_byname = NULL;
273
274         rbtree_free(home_servers_byaddr);
275         home_servers_byaddr = NULL;
276
277         rbtree_free(home_pools_byname);
278         home_pools_byname = NULL;
279 #endif
280
281         rbtree_free(realms_byname);
282         realms_byname = NULL;
283
284 #ifdef HAVE_REGEX_H
285         if (realms_regex) {
286                 realm_regex_t *this, *next;
287
288                 for (this = realms_regex; this != NULL; this = next) {
289                         next = this->next;
290                         free(this->realm);
291                         free(this);
292                 }
293                 realms_regex = NULL;
294         }
295 #endif
296
297         free(realm_config);
298         realm_config = NULL;
299 }
300
301
302 #ifdef WITH_PROXY
303 static CONF_PARSER limit_config[] = {
304         { "max_connections", PW_TYPE_INTEGER,
305           offsetof(home_server, max_connections), NULL,   "16" },
306
307         { "max_requests", PW_TYPE_INTEGER,
308           offsetof(home_server,max_requests), NULL,   "0" },
309
310         { "lifetime", PW_TYPE_INTEGER,
311           offsetof(home_server,lifetime), NULL,   "0" },
312
313         { "idle_timeout", PW_TYPE_INTEGER,
314           offsetof(home_server,idle_timeout), NULL,   "0" },
315
316         { NULL, -1, 0, NULL, NULL }             /* end the list */
317 };
318
319 static struct in_addr hs_ip4addr;
320 static struct in6_addr hs_ip6addr;
321 static char *hs_srcipaddr = NULL;
322 static char *hs_type = NULL;
323 static char *hs_check = NULL;
324 static char *hs_virtual_server = NULL;
325 #ifdef WITH_TCP
326 static char *hs_proto = NULL;
327 #endif
328
329 #ifdef WITH_COA
330 static CONF_PARSER home_server_coa[] = {
331         { "irt",  PW_TYPE_INTEGER,
332           offsetof(home_server, coa_irt), 0, Stringify(2) },
333         { "mrt",  PW_TYPE_INTEGER,
334           offsetof(home_server, coa_mrt), 0, Stringify(16) },
335         { "mrc",  PW_TYPE_INTEGER,
336           offsetof(home_server, coa_mrc), 0, Stringify(5) },
337         { "mrd",  PW_TYPE_INTEGER,
338           offsetof(home_server, coa_mrd), 0, Stringify(30) },
339
340         { NULL, -1, 0, NULL, NULL }             /* end the list */
341 };
342 #endif
343
344 static CONF_PARSER home_server_config[] = {
345         { "ipaddr",  PW_TYPE_IPADDR,
346           0, &hs_ip4addr,  NULL },
347         { "ipv6addr",  PW_TYPE_IPV6ADDR,
348           0, &hs_ip6addr, NULL },
349         { "virtual_server",  PW_TYPE_STRING_PTR,
350           0, &hs_virtual_server, NULL },
351
352         { "port", PW_TYPE_INTEGER,
353           offsetof(home_server,port), NULL,   "0" },
354
355         { "type",  PW_TYPE_STRING_PTR,
356           0, &hs_type, NULL },
357
358 #ifdef WITH_TCP
359         { "proto",  PW_TYPE_STRING_PTR,
360           0, &hs_proto, NULL },
361 #endif
362
363         { "secret",  PW_TYPE_STRING_PTR,
364           offsetof(home_server,secret), NULL,  NULL},
365
366         { "src_ipaddr",  PW_TYPE_STRING_PTR,
367           0, &hs_srcipaddr,  NULL },
368
369         { "response_window", PW_TYPE_INTEGER,
370           offsetof(home_server,response_window), NULL,   "30" },
371         { "no_response_fail", PW_TYPE_BOOLEAN,
372           offsetof(home_server,no_response_fail), NULL,   NULL },
373         { "max_outstanding", PW_TYPE_INTEGER,
374           offsetof(home_server,max_outstanding), NULL,   "65536" },
375         { "require_message_authenticator",  PW_TYPE_BOOLEAN,
376           offsetof(home_server, message_authenticator), 0, NULL },
377
378         { "zombie_period", PW_TYPE_INTEGER,
379           offsetof(home_server,zombie_period), NULL,   "40" },
380         { "status_check", PW_TYPE_STRING_PTR,
381           0, &hs_check,   "none" },
382         { "ping_check", PW_TYPE_STRING_PTR,
383           0, &hs_check,   NULL },
384
385         { "ping_interval", PW_TYPE_INTEGER,
386           offsetof(home_server,ping_interval), NULL,   "30" },
387         { "check_interval", PW_TYPE_INTEGER,
388           offsetof(home_server,ping_interval), NULL,   "30" },
389         { "num_answers_to_alive", PW_TYPE_INTEGER,
390           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
391         { "num_pings_to_alive", PW_TYPE_INTEGER,
392           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
393         { "revive_interval", PW_TYPE_INTEGER,
394           offsetof(home_server,revive_interval), NULL,   "300" },
395         { "status_check_timeout", PW_TYPE_INTEGER,
396           offsetof(home_server,ping_timeout), NULL,   "4" },
397
398         { "username",  PW_TYPE_STRING_PTR,
399           offsetof(home_server,ping_user_name), NULL,  NULL},
400         { "password",  PW_TYPE_STRING_PTR,
401           offsetof(home_server,ping_user_password), NULL,  NULL},
402
403 #ifdef WITH_STATS
404         { "historic_average_window", PW_TYPE_INTEGER,
405           offsetof(home_server,ema.window), NULL,  NULL },
406 #endif
407
408 #ifdef WITH_COA
409         {  "coa", PW_TYPE_SUBSECTION, 0, NULL, (const void *) home_server_coa },
410 #endif
411
412         { "limit", PW_TYPE_SUBSECTION, 0, NULL, (const void *) limit_config },
413
414         { NULL, -1, 0, NULL, NULL }             /* end the list */
415 };
416
417
418 static void null_free(UNUSED void *data)
419 {
420 }
421
422 static int home_server_add(realm_config_t *rc, CONF_SECTION *cs)
423 {
424         const char *name2;
425         home_server *home;
426         int dual = FALSE;
427         CONF_PAIR *cp;
428         CONF_SECTION *tls;
429
430         free(hs_virtual_server); /* used only for printing during parsing */
431         hs_virtual_server = NULL;
432
433         name2 = cf_section_name2(cs);
434         if (!name2) {
435                 cf_log_err(cf_sectiontoitem(cs),
436                            "Home server section is missing a name.");
437                 return 0;
438         }
439
440         home = rad_malloc(sizeof(*home));
441         memset(home, 0, sizeof(*home));
442
443         home->name = name2;
444         home->cs = cs;
445
446         /*
447          *      For zombie period calculations.  We want to count
448          *      zombies from the time when the server starts, instead
449          *      of from 1970.
450          */
451         home->last_packet = time(NULL);
452
453         /*
454          *      Authentication servers have a default "no_response_fail = 0".
455          *      Accounting servers have a default "no_response_fail = 1".
456          *
457          *      This is because authentication packets are retried, so
458          *      they can fail over to another home server.  Accounting
459          *      packets are not retried, so they cannot fail over, and
460          *      instead should be rejected immediately.
461          */
462         home->no_response_fail = 2;
463
464         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
465         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
466         if (cf_section_parse(cs, home, home_server_config) < 0) {
467                 goto error;
468         }
469
470         /*
471          *      Figure out which one to use.
472          */
473         if (cf_pair_find(cs, "ipaddr")) {
474                 home->ipaddr.af = AF_INET;
475                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
476
477         } else if (cf_pair_find(cs, "ipv6addr")) {
478                 home->ipaddr.af = AF_INET6;
479                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
480
481         } else if ((cp = cf_pair_find(cs, "virtual_server")) != NULL) {
482                 home->ipaddr.af = AF_UNSPEC;
483                 home->server = cf_pair_value(cp);
484                 if (!home->server) {
485                         cf_log_err(cf_sectiontoitem(cs),
486                                    "Invalid value for virtual_server");
487                         goto error;
488                 }
489
490                 if (!cf_section_sub_find_name2(rc->cs, "server", home->server)) {
491                   
492                         cf_log_err(cf_sectiontoitem(cs),
493                                    "No such server %s", home->server);
494                         goto error;
495                 }
496
497                 /*
498                  *      When CoA is used, the user has to specify the type
499                  *      of the home server, even when they point to
500                  *      virtual servers.
501                  */
502                 home->secret = strdup("");
503                 goto skip_port;
504
505         } else {
506                 cf_log_err(cf_sectiontoitem(cs),
507                            "No ipaddr, ipv6addr, or virtual_server defined for home server \"%s\".",
508                            name2);
509         error:
510                 free(home);
511                 free(hs_type);
512                 hs_type = NULL;
513                 free(hs_check);
514                 hs_check = NULL;
515                 free(hs_srcipaddr);
516                 hs_srcipaddr = NULL;
517 #ifdef WITH_TCP
518                 free(hs_proto);
519                 hs_proto = NULL;
520 #endif
521                 return 0;
522         }
523
524         if (!home->port || (home->port > 65535)) {
525                 cf_log_err(cf_sectiontoitem(cs),
526                            "No port, or invalid port defined for home server %s.",
527                            name2);
528                 goto error;
529         }
530
531         if (0) {
532                 cf_log_err(cf_sectiontoitem(cs),
533                            "Fatal error!  Home server %s is ourselves!",
534                            name2);
535                 goto error;
536         }
537
538         if (!home->secret) {
539                 cf_log_err(cf_sectiontoitem(cs),
540                            "No shared secret defined for home server %s.",
541                            name2);
542                 goto error;
543         }
544
545         /*
546          *      Use a reasonable default.
547          */
548  skip_port:
549         if (!hs_type) hs_type = strdup("auth+acct");
550
551         if (strcasecmp(hs_type, "auth") == 0) {
552                 home->type = HOME_TYPE_AUTH;
553                 if (home->no_response_fail == 2) home->no_response_fail = 0;
554
555         } else if (strcasecmp(hs_type, "acct") == 0) {
556                 home->type = HOME_TYPE_ACCT;
557                 if (home->no_response_fail == 2) home->no_response_fail = 1;
558
559         } else if (strcasecmp(hs_type, "auth+acct") == 0) {
560                 home->type = HOME_TYPE_AUTH;
561                 dual = TRUE;
562
563 #ifdef WITH_COA
564         } else if (strcasecmp(hs_type, "coa") == 0) {
565                 home->type = HOME_TYPE_COA;
566                 dual = FALSE;
567
568                 if (home->server != NULL) {
569                         cf_log_err(cf_sectiontoitem(cs),
570                                    "Home servers of type \"coa\" cannot point to a virtual server");
571                         goto error;
572                 }
573 #endif
574
575         } else {
576                 cf_log_err(cf_sectiontoitem(cs),
577                            "Invalid type \"%s\" for home server %s.",
578                            hs_type, name2);
579                 goto error;
580         }
581         free(hs_type);
582         hs_type = NULL;
583
584         if (!hs_check || (strcasecmp(hs_check, "none") == 0)) {
585                 home->ping_check = HOME_PING_CHECK_NONE;
586
587         } else if (strcasecmp(hs_check, "status-server") == 0) {
588                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
589
590         } else if (strcasecmp(hs_check, "request") == 0) {
591                 home->ping_check = HOME_PING_CHECK_REQUEST;
592
593         } else {
594                 cf_log_err(cf_sectiontoitem(cs),
595                            "Invalid ping_check \"%s\" for home server %s.",
596                            hs_check, name2);
597                 goto error;
598         }
599         free(hs_check);
600         hs_check = NULL;
601
602         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
603             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
604                 if (!home->ping_user_name) {
605                         cf_log_err(cf_sectiontoitem(cs), "You must supply a user name to enable ping checks");
606                         goto error;
607                 }
608
609                 if ((home->type == HOME_TYPE_AUTH) &&
610                     !home->ping_user_password) {
611                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable ping checks");
612                         goto error;
613                 }
614         }
615
616         home->proto = IPPROTO_UDP;
617 #ifdef WITH_TCP
618         if (hs_proto) {
619                 if (strcmp(hs_proto, "udp") == 0) {
620                         free(hs_proto);
621                         hs_proto = NULL;
622                         
623                 } else if (strcmp(hs_proto, "tcp") == 0) {
624                         free(hs_proto);
625                         hs_proto = NULL;
626                         home->proto = IPPROTO_TCP;
627                         
628                         if (home->ping_check == HOME_PING_CHECK_REQUEST) {
629                                 cf_log_err(cf_sectiontoitem(cs),
630                                            "Cannot use 'status_check = request' for home servers where 'proto = tcp'");
631                                 goto error;
632                         }
633
634                 } else {
635                         cf_log_err(cf_sectiontoitem(cs),
636                                    "Unknown proto \"%s\".", hs_proto);
637                         goto error;
638                 }
639         }
640 #endif
641
642         if (!home->server &&
643             rbtree_finddata(home_servers_byaddr, home)) {
644                 cf_log_err(cf_sectiontoitem(cs), "Duplicate home server");
645                 goto error;
646         }
647
648         /*
649          *      Check the TLS configuration.
650          */
651         tls = cf_section_sub_find(cs, "tls");
652
653         /*
654          *      If the home is a virtual server, don't look up source IP.
655          */
656         if (!home->server) {
657                 rad_assert(home->ipaddr.af != AF_UNSPEC);
658
659                 /*
660                  *      Otherwise look up the source IP using the same
661                  *      address family as the destination IP.
662                  */
663                 if (hs_srcipaddr) {
664                         if (ip_hton(hs_srcipaddr, home->ipaddr.af, &home->src_ipaddr) < 0) {
665                                 cf_log_err(cf_sectiontoitem(cs), "Failed parsing src_ipaddr");
666                                 goto error;
667                         }
668                         
669                 } else {
670                         /*
671                          *      Source isn't specified: Source is
672                          *      the correct address family, but all zeros.
673                          */
674                         memset(&home->src_ipaddr, 0, sizeof(home->src_ipaddr));
675                         home->src_ipaddr.af = home->ipaddr.af;
676                 }
677
678                 if (tls && (home->proto != IPPROTO_TCP)) {
679                         cf_log_err(cf_sectiontoitem(cs), "TLS transport is not available for UDP sockets.");
680                         goto error;
681                 }
682
683 #ifndef WITH_TLS
684                 cf_log_err(cf_sectiontoitem(cs), "TLS transport is not available in this executable.");
685                 goto error;
686 #else
687                 /*
688                  *      Parse the SSL client configuration.
689                  */
690                 if (tls) {
691                         home->tls = tls_client_conf_parse(tls);
692                         if (!home->tls) {
693                                 goto error;
694                         }
695                 }
696 #endif
697
698         } else if (tls) {
699                 cf_log_err(cf_sectiontoitem(cs), "Virtual home_servers cannot have a \"tls\" subsection");
700                 goto error;
701         }
702
703         /*
704          *      Make sure that this is set.
705          */
706         if (home->src_ipaddr.af == AF_UNSPEC) {
707                 home->src_ipaddr.af = home->ipaddr.af;
708         }
709
710         free(hs_srcipaddr);
711         hs_srcipaddr = NULL;
712
713         if (!rbtree_insert(home_servers_byname, home)) {
714                 cf_log_err(cf_sectiontoitem(cs),
715                            "Internal error %d adding home server %s.",
716                            __LINE__, name2);
717                 goto error;
718         }
719
720         if (!home->server &&
721             !rbtree_insert(home_servers_byaddr, home)) {
722                 rbtree_deletebydata(home_servers_byname, home);
723                 cf_log_err(cf_sectiontoitem(cs),
724                            "Internal error %d adding home server %s.",
725                            __LINE__, name2);
726                 goto error;
727         }
728
729 #ifdef WITH_STATS
730         home->number = home_server_max_number++;
731         if (!rbtree_insert(home_servers_bynumber, home)) {
732                 rbtree_deletebydata(home_servers_byname, home);
733                 if (home->ipaddr.af != AF_UNSPEC) {
734                         rbtree_deletebydata(home_servers_byname, home);
735                 }
736                 cf_log_err(cf_sectiontoitem(cs),
737                            "Internal error %d adding home server %s.",
738                            __LINE__, name2);
739                 goto error;
740         }
741 #endif
742
743         if (home->max_outstanding < 8) home->max_outstanding = 8;
744         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
745
746         if (home->ping_interval < 6) home->ping_interval = 6;
747         if (home->ping_interval > 120) home->ping_interval = 120;
748
749         if (home->response_window < 1) home->response_window = 1;
750         if (home->response_window > 60) home->response_window = 60;
751         if (home->response_window > mainconfig.max_request_time) home->response_window = mainconfig.max_request_time;
752
753         if (home->zombie_period < 1) home->zombie_period = 1;
754         if (home->zombie_period > 120) home->zombie_period = 120;
755
756         if (home->zombie_period < home->response_window) {
757                 home->zombie_period = home->response_window;
758         }
759
760         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
761         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
762
763         if (home->ping_timeout < 3) home->ping_timeout = 3;
764         if (home->ping_timeout > 10) home->ping_timeout = 10;
765
766         if (home->revive_interval < 60) home->revive_interval = 60;
767         if (home->revive_interval > 3600) home->revive_interval = 3600;
768
769 #ifdef WITH_COA
770         if (home->coa_irt < 1) home->coa_irt = 1;
771         if (home->coa_irt > 5) home->coa_irt = 5;
772
773         if (home->coa_mrc < 0) home->coa_mrc = 0;
774         if (home->coa_mrc > 20 ) home->coa_mrc = 20;
775
776         if (home->coa_mrt < 0) home->coa_mrt = 0;
777         if (home->coa_mrt > 30 ) home->coa_mrt = 30;
778
779         if (home->coa_mrd < 5) home->coa_mrd = 5;
780         if (home->coa_mrd > 60 ) home->coa_mrd = 60;
781 #endif
782
783         if (home->max_connections > 1024) home->max_connections = 1024;
784
785 #ifdef WITH_TCP
786         /*
787          *      UDP sockets can't be connection limited.
788          */
789         if (home->proto != IPPROTO_TCP) home->max_connections = 0;
790 #endif
791
792         if ((home->idle_timeout > 0) && (home->idle_timeout < 5))
793                 home->idle_timeout = 5;
794         if ((home->lifetime > 0) && (home->lifetime < 5))
795                 home->lifetime = 5;
796         if ((home->lifetime > 0) && (home->idle_timeout > home->lifetime))
797                 home->idle_timeout = 0;
798
799         if (dual) {
800                 home_server *home2 = rad_malloc(sizeof(*home2));
801
802                 memcpy(home2, home, sizeof(*home2));
803
804                 home2->type = HOME_TYPE_ACCT;
805                 home2->port++;
806                 home2->ping_user_password = NULL;
807                 home2->cs = cs;
808
809                 if (home->no_response_fail == 2) home->no_response_fail = 0;
810                 if (home2->no_response_fail == 2) home2->no_response_fail = 1;
811
812                 if (!rbtree_insert(home_servers_byname, home2)) {
813                         cf_log_err(cf_sectiontoitem(cs),
814                                    "Internal error %d adding home server %s.",
815                                    __LINE__, name2);
816                         free(home2);
817                         return 0;
818                 }
819                 
820                 if (!home->server &&
821                     !rbtree_insert(home_servers_byaddr, home2)) {
822                         rbtree_deletebydata(home_servers_byname, home2);
823                         cf_log_err(cf_sectiontoitem(cs),
824                                    "Internal error %d adding home server %s.",
825                                    __LINE__, name2);
826                         free(home2);
827                         return 0;
828                 }
829
830 #ifdef WITH_STATS
831                 home2->number = home_server_max_number++;
832                 if (!rbtree_insert(home_servers_bynumber, home2)) {
833                         rbtree_deletebydata(home_servers_byname, home2);
834                         if (!home2->server) {
835                                 rbtree_deletebydata(home_servers_byname, home2);
836                         }
837                         cf_log_err(cf_sectiontoitem(cs),
838                                    "Internal error %d adding home server %s.",
839                                    __LINE__, name2);
840                         free(home2);
841                         return 0;
842                 }
843 #endif
844         }
845
846         /*
847          *      Mark it as already processed
848          */
849         cf_data_add(cs, "home_server", null_free, null_free);
850
851         return 1;
852 }
853
854
855 static home_pool_t *server_pool_alloc(const char *name, home_pool_type_t type,
856                                       int server_type, int num_home_servers)
857 {
858         home_pool_t *pool;
859
860         pool = rad_malloc(sizeof(*pool) + (sizeof(pool->servers[0]) *
861                                            num_home_servers));
862         if (!pool) return NULL; /* just for pairanoia */
863         
864         memset(pool, 0, sizeof(*pool) + (sizeof(pool->servers[0]) *
865                                          num_home_servers));
866
867         pool->name = name;
868         pool->type = type;
869         pool->server_type = server_type;
870         pool->num_home_servers = num_home_servers;
871
872         return pool;
873 }
874
875 static int pool_check_home_server(realm_config_t *rc, CONF_PAIR *cp,
876                                   const char *name, int server_type,
877                                   home_server **phome)
878 {
879         home_server myhome, *home;
880         CONF_SECTION *server_cs;
881
882         if (!name) {
883                 cf_log_err(cf_pairtoitem(cp),
884                            "No value given for home_server.");
885                 return 0;
886         }
887
888         myhome.name = name;
889         myhome.type = server_type;
890         home = rbtree_finddata(home_servers_byname, &myhome);
891         if (home) {
892                 *phome = home;
893                 return 1;
894         }
895         
896         server_cs = cf_section_sub_find_name2(rc->cs, "home_server", name);
897         if (!server_cs) {
898                 cf_log_err(cf_pairtoitem(cp),
899                            "Unknown home_server \"%s\".", name);
900                 return 0;
901         }
902         
903         home = rbtree_finddata(home_servers_byname, &myhome);
904         if (!home) {
905                 cf_log_err(cf_pairtoitem(cp),
906                            "Internal error %d adding home server \"%s\".",
907                            __LINE__, name);
908                 return 0;
909         }
910
911         *phome = home;
912         return 1;
913 }
914
915
916 static int server_pool_add(realm_config_t *rc,
917                            CONF_SECTION *cs, int server_type, int do_print)
918 {
919         const char *name2;
920         home_pool_t *pool = NULL;
921         const char *value;
922         CONF_PAIR *cp;
923         int num_home_servers;
924         home_server *home;
925
926         name2 = cf_section_name1(cs);
927         if (!name2 || ((strcasecmp(name2, "server_pool") != 0) &&
928                        (strcasecmp(name2, "home_server_pool") != 0))) {
929                 cf_log_err(cf_sectiontoitem(cs),
930                            "Section is not a home_server_pool.");
931                 return 0;
932         }
933
934         name2 = cf_section_name2(cs);
935         if (!name2) {
936                 cf_log_err(cf_sectiontoitem(cs),
937                            "Server pool section is missing a name.");
938                 return 0;
939         }
940
941         /*
942          *      Count the home servers and initalize them.
943          */
944         num_home_servers = 0;
945         for (cp = cf_pair_find(cs, "home_server");
946              cp != NULL;
947              cp = cf_pair_find_next(cs, cp, "home_server")) {
948                 num_home_servers++;
949
950                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
951                                             server_type, &home)) {
952                         return 0;
953                 }
954         }
955
956         if (num_home_servers == 0) {
957                 cf_log_err(cf_sectiontoitem(cs),
958                            "No home servers defined in pool %s",
959                            name2);
960                 goto error;
961         }
962
963         pool = server_pool_alloc(name2, HOME_POOL_FAIL_OVER, server_type,
964                                  num_home_servers);
965         pool->cs = cs;
966
967
968         /*
969          *      Fallback servers must be defined, and must be
970          *      virtual servers.
971          */
972         cp = cf_pair_find(cs, "fallback");
973         if (cp) {
974 #ifdef WITH_COA
975                 if (server_type == HOME_TYPE_COA) {
976                         cf_log_err(cf_sectiontoitem(cs), "Home server pools of type \"coa\" cannot have a fallback virtual server.");
977                         goto error;
978                 }
979 #endif
980
981                 if (!pool_check_home_server(rc, cp, cf_pair_value(cp),
982                                             server_type, &pool->fallback)) {
983                         
984                         goto error;
985                 }
986
987                 if (!pool->fallback->server) {
988                         cf_log_err(cf_sectiontoitem(cs), "Fallback home_server %s does NOT contain a virtual_server directive.", pool->fallback->name);
989                         goto error;
990                 }
991         }
992
993         if (do_print) cf_log_info(cs, " home_server_pool %s {", name2);
994
995         cp = cf_pair_find(cs, "type");
996         if (cp) {
997                 static FR_NAME_NUMBER pool_types[] = {
998                         { "load-balance", HOME_POOL_LOAD_BALANCE },
999                         { "fail-over", HOME_POOL_FAIL_OVER },
1000                         { "round_robin", HOME_POOL_LOAD_BALANCE },
1001                         { "fail_over", HOME_POOL_FAIL_OVER },
1002                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
1003                         { "client-port-balance", HOME_POOL_CLIENT_PORT_BALANCE },
1004                         { "keyed-balance", HOME_POOL_KEYED_BALANCE },
1005                         { NULL, 0 }
1006                 };
1007
1008                 value = cf_pair_value(cp);
1009                 if (!value) {
1010                         cf_log_err(cf_pairtoitem(cp),
1011                                    "No value given for type.");
1012                         goto error;
1013                 }
1014
1015                 pool->type = fr_str2int(pool_types, value, 0);
1016                 if (!pool->type) {
1017                         cf_log_err(cf_pairtoitem(cp),
1018                                    "Unknown type \"%s\".",
1019                                    value);
1020                         goto error;
1021                 }
1022
1023                 if (do_print) cf_log_info(cs, "\ttype = %s", value);
1024         }
1025
1026         cp = cf_pair_find(cs, "virtual_server");
1027         if (cp) {
1028                 pool->virtual_server = cf_pair_value(cp);               
1029                 if (!pool->virtual_server) {
1030                         cf_log_err(cf_pairtoitem(cp), "No value given for virtual_server");
1031                         goto error;
1032                 }
1033
1034                 if (do_print) {
1035                         cf_log_info(cs, "\tvirtual_server = %s", pool->virtual_server);
1036                 }
1037
1038                 if (!cf_section_sub_find_name2(rc->cs, "server",
1039                                                pool->virtual_server)) {
1040                         cf_log_err(cf_pairtoitem(cp), "No such server %s",
1041                                    pool->virtual_server);
1042                         goto error;
1043                 }
1044
1045         }
1046
1047         num_home_servers = 0;
1048         for (cp = cf_pair_find(cs, "home_server");
1049              cp != NULL;
1050              cp = cf_pair_find_next(cs, cp, "home_server")) {
1051                 home_server myhome;
1052
1053                 value = cf_pair_value(cp);
1054
1055                 memset(&myhome, 0, sizeof(&myhome));
1056                 myhome.name = value;
1057                 myhome.type = server_type;
1058
1059                 home = rbtree_finddata(home_servers_byname, &myhome);
1060                 if (!home) {
1061                         DEBUG2("Internal sanity check failed");
1062                         goto error;
1063                 }
1064
1065                 if (0) {
1066                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
1067                         continue;
1068                 }
1069
1070                 if (do_print) cf_log_info(cs, "\thome_server = %s", home->name);
1071                 pool->servers[num_home_servers++] = home;
1072         } /* loop over home_server's */
1073
1074         if (pool->fallback && do_print) {
1075                 cf_log_info(cs, "\tfallback = %s", pool->fallback->name);
1076         }
1077
1078         if (!rbtree_insert(home_pools_byname, pool)) {
1079                 rad_assert("Internal sanity check failed");
1080                 goto error;
1081         }
1082
1083         if (do_print) cf_log_info(cs, " }");
1084
1085         cf_data_add(cs, "home_server_pool", pool, free);
1086
1087         rad_assert(pool->server_type != 0);
1088
1089         return 1;
1090
1091  error:
1092         if (do_print) cf_log_info(cs, " }");
1093         free(pool);
1094         return 0;
1095 }
1096 #endif
1097
1098 static int old_server_add(realm_config_t *rc, CONF_SECTION *cs,
1099                           const char *realm,
1100                           const char *name, const char *secret,
1101                           home_pool_type_t ldflag, home_pool_t **pool_p,
1102                           int type, const char *server)
1103 {
1104 #ifdef WITH_PROXY
1105         int i, insert_point, num_home_servers;
1106         home_server myhome, *home;
1107         home_pool_t mypool, *pool;
1108         CONF_SECTION *subcs;
1109 #else
1110         rc = rc;                /* -Wunused */
1111         realm = realm;
1112         secret = secret;
1113         ldflag = ldflag;
1114         type = type;
1115         server = server;
1116 #endif
1117
1118         /*
1119          *      LOCAL realms get sanity checked, and nothing else happens.
1120          */
1121         if (strcmp(name, "LOCAL") == 0) {
1122                 if (*pool_p) {
1123                         cf_log_err(cf_sectiontoitem(cs), "Realm \"%s\" cannot be both LOCAL and remote", name);
1124                         return 0;
1125                 }
1126                 return 1;
1127         }
1128
1129 #ifndef WITH_PROXY
1130         return 0;               /* Not proxying.  Can't do non-LOCAL realms */
1131
1132 #else
1133         mypool.name = realm;
1134         mypool.server_type = type;
1135         pool = rbtree_finddata(home_pools_byname, &mypool);
1136         if (pool) {
1137                 if (pool->type != ldflag) {
1138                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent ldflag for server pool \"%s\"", name);
1139                         return 0;
1140                 }
1141
1142                 if (pool->server_type != type) {
1143                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent home server type for server pool \"%s\"", name);
1144                         return 0;
1145                 }
1146         }
1147
1148         myhome.name = name;
1149         myhome.type = type;
1150         home = rbtree_finddata(home_servers_byname, &myhome);
1151         if (home) {
1152                 if (secret && (strcmp(home->secret, secret) != 0)) {
1153                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent shared secret for home server \"%s\"", name);
1154                         return 0;
1155                 }
1156
1157                 if (home->type != type) {
1158                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent type for home server \"%s\"", name);
1159                         return 0;
1160                 }
1161
1162                 /*
1163                  *      See if the home server is already listed
1164                  *      in the pool.  If so, do nothing else.
1165                  */
1166                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
1167                         if (pool->servers[i] == home) {
1168                                 return 1;
1169                         }
1170                 }
1171         }
1172
1173         /*
1174          *      If we do have a pool, check that there is room to
1175          *      insert the home server we've found, or the one that we
1176          *      create here.
1177          *
1178          *      Note that we insert it into the LAST available
1179          *      position, in order to maintain the same order as in
1180          *      the configuration files.
1181          */
1182         insert_point = -1;
1183         if (pool) {
1184                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
1185                         if (pool->servers[i]) break;
1186
1187                         if (!pool->servers[i]) {
1188                                 insert_point = i;
1189                         }
1190                 }
1191
1192                 if (insert_point < 0) {
1193                         cf_log_err(cf_sectiontoitem(cs), "No room in pool to add home server \"%s\".  Please update the realm configuration to use the new-style home servers and server pools.", name);
1194                         return 0;
1195                 }
1196         }
1197
1198         /*
1199          *      No home server, allocate one.
1200          */
1201         if (!home) {
1202                 const char *p;
1203                 char *q;
1204
1205                 home = rad_malloc(sizeof(*home));
1206                 memset(home, 0, sizeof(*home));
1207
1208                 home->name = name;
1209                 home->hostname = name;
1210                 home->type = type;
1211                 home->secret = secret;
1212                 home->cs = cs;
1213                 home->proto = IPPROTO_UDP;
1214
1215                 p = strchr(name, ':');
1216                 if (!p) {
1217                         if (type == HOME_TYPE_AUTH) {
1218                                 home->port = PW_AUTH_UDP_PORT;
1219                         } else {
1220                                 home->port = PW_ACCT_UDP_PORT;
1221                         }
1222
1223                         p = name;
1224                         q = NULL;
1225
1226                 } else if (p == name) {
1227                                 cf_log_err(cf_sectiontoitem(cs),
1228                                            "Invalid hostname %s.",
1229                                            name);
1230                                 free(home);
1231                                 return 0;
1232
1233                 } else {
1234                         home->port = atoi(p + 1);
1235                         if ((home->port == 0) || (home->port > 65535)) {
1236                                 cf_log_err(cf_sectiontoitem(cs),
1237                                            "Invalid port %s.",
1238                                            p + 1);
1239                                 free(home);
1240                                 return 0;
1241                         }
1242
1243                         q = rad_malloc((p - name) + 1);
1244                         memcpy(q, name, (p - name));
1245                         q[p - name] = '\0';
1246                         p = q;
1247                 }
1248
1249                 if (!server) {
1250                         if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
1251                                 cf_log_err(cf_sectiontoitem(cs),
1252                                            "Failed looking up hostname %s.",
1253                                            p);
1254                                 free(home);
1255                                 free(q);
1256                                 return 0;
1257                         }
1258                         home->src_ipaddr.af = home->ipaddr.af;
1259                 } else {
1260                         home->ipaddr.af = AF_UNSPEC;
1261                         home->server = server;
1262                 }
1263                 free(q);
1264
1265                 /*
1266                  *      Use the old-style configuration.
1267                  */
1268                 home->max_outstanding = 65535*16;
1269                 home->zombie_period = rc->retry_delay * rc->retry_count;
1270                 if (home->zombie_period == 0) home->zombie_period =30;
1271                 home->response_window = home->zombie_period - 1;
1272
1273                 home->ping_check = HOME_PING_CHECK_NONE;
1274
1275                 home->revive_interval = rc->dead_time;
1276
1277                 if (rbtree_finddata(home_servers_byaddr, home)) {
1278                         cf_log_err(cf_sectiontoitem(cs), "Home server %s has the same IP address and/or port as another home server.", name);
1279                         free(home);
1280                         return 0;
1281                 }
1282
1283                 if (!rbtree_insert(home_servers_byname, home)) {
1284                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1285                         free(home);
1286                         return 0;
1287                 }
1288
1289                 if (!rbtree_insert(home_servers_byaddr, home)) {
1290                         rbtree_deletebydata(home_servers_byname, home);
1291                         cf_log_err(cf_sectiontoitem(cs), "Internal error %d adding home server %s.", __LINE__, name);
1292                         free(home);
1293                         return 0;
1294                 }
1295
1296 #ifdef WITH_STATS
1297                 home->number = home_server_max_number++;
1298                 if (!rbtree_insert(home_servers_bynumber, home)) {
1299                         rbtree_deletebydata(home_servers_byname, home);
1300                         if (home->ipaddr.af != AF_UNSPEC) {
1301                                 rbtree_deletebydata(home_servers_byname, home);
1302                         }
1303                         cf_log_err(cf_sectiontoitem(cs),
1304                                    "Internal error %d adding home server %s.",
1305                                    __LINE__, name);
1306                         free(home);
1307                         return 0;
1308                 }
1309 #endif
1310         }
1311
1312         /*
1313          *      We now have a home server, see if we can insert it
1314          *      into pre-existing pool.
1315          */
1316         if (insert_point >= 0) {
1317                 rad_assert(pool != NULL);
1318                 pool->servers[insert_point] = home;
1319                 return 1;
1320         }
1321
1322         rad_assert(pool == NULL);
1323         rad_assert(home != NULL);
1324
1325         /*
1326          *      Count the old-style realms of this name.
1327          */
1328         num_home_servers = 0;
1329         for (subcs = cf_section_find_next(cs, NULL, "realm");
1330              subcs != NULL;
1331              subcs = cf_section_find_next(cs, subcs, "realm")) {
1332                 const char *this = cf_section_name2(subcs);
1333
1334                 if (!this || (strcmp(this, realm) != 0)) continue;
1335                 num_home_servers++;
1336         }
1337
1338         if (num_home_servers == 0) {
1339                 cf_log_err(cf_sectiontoitem(cs), "Internal error counting pools for home server %s.", name);
1340                 free(home);
1341                 return 0;
1342         }
1343
1344         pool = server_pool_alloc(realm, ldflag, type, num_home_servers);
1345         pool->cs = cs;
1346
1347         pool->servers[0] = home;
1348
1349         if (!rbtree_insert(home_pools_byname, pool)) {
1350                 rad_assert("Internal sanity check failed");
1351                 return 0;
1352         }
1353
1354         *pool_p = pool;
1355
1356         return 1;
1357 #endif
1358 }
1359
1360 static int old_realm_config(realm_config_t *rc, CONF_SECTION *cs, REALM *r)
1361 {
1362         const char *host;
1363         const char *secret = NULL;
1364         home_pool_type_t ldflag;
1365         CONF_PAIR *cp;
1366
1367         cp = cf_pair_find(cs, "ldflag");
1368         ldflag = HOME_POOL_FAIL_OVER;
1369         if (cp) {
1370                 host = cf_pair_value(cp);
1371                 if (!host) {
1372                         cf_log_err(cf_pairtoitem(cp), "No value specified for ldflag");
1373                         return 0;
1374                 }
1375
1376                 if (strcasecmp(host, "fail_over") == 0) {
1377                         cf_log_info(cs, "\tldflag = fail_over");
1378                         
1379                 } else if (strcasecmp(host, "round_robin") == 0) {
1380                         ldflag = HOME_POOL_LOAD_BALANCE;
1381                         cf_log_info(cs, "\tldflag = round_robin");
1382                         
1383                 } else {
1384                         cf_log_err(cf_sectiontoitem(cs), "Unknown value \"%s\" for ldflag", host);
1385                         return 0;
1386                 }
1387         } /* else don't print it. */
1388
1389         /*
1390          *      Allow old-style if it doesn't exist, or if it exists and
1391          *      it's LOCAL.
1392          */
1393         cp = cf_pair_find(cs, "authhost");
1394         if (cp) {
1395                 host = cf_pair_value(cp);
1396                 if (!host) {
1397                         cf_log_err(cf_pairtoitem(cp), "No value specified for authhost");
1398                         return 0;
1399                 }
1400
1401                 if (strcmp(host, "LOCAL") != 0) {
1402                         cp = cf_pair_find(cs, "secret");
1403                         if (!cp) {
1404                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1405                                 return 0;
1406                         }
1407
1408                         secret = cf_pair_value(cp);
1409                         if (!secret) {
1410                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1411                                 return 0;
1412                         }
1413                 }
1414                         
1415                 cf_log_info(cs, "\tauthhost = %s",  host);
1416
1417                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1418                                     &r->auth_pool, HOME_TYPE_AUTH, NULL)) {
1419                         return 0;
1420                 }
1421         }
1422
1423         cp = cf_pair_find(cs, "accthost");
1424         if (cp) {
1425                 host = cf_pair_value(cp);
1426                 if (!host) {
1427                         cf_log_err(cf_pairtoitem(cp), "No value specified for accthost");
1428                         return 0;
1429                 }
1430
1431                 /*
1432                  *      Don't look for a secret again if it was found
1433                  *      above.
1434                  */
1435                 if ((strcmp(host, "LOCAL") != 0) && !secret) {
1436                         cp = cf_pair_find(cs, "secret");
1437                         if (!cp) {
1438                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1439                                 return 0;
1440                         }
1441                         
1442                         secret = cf_pair_value(cp);
1443                         if (!secret) {
1444                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1445                                 return 0;
1446                         }
1447                 }
1448                 
1449                 cf_log_info(cs, "\taccthost = %s", host);
1450
1451                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1452                                     &r->acct_pool, HOME_TYPE_ACCT, NULL)) {
1453                         return 0;
1454                 }
1455         }
1456
1457         cp = cf_pair_find(cs, "virtual_server");
1458         if (cp) {
1459                 host = cf_pair_value(cp);
1460                 if (!host) {
1461                         cf_log_err(cf_pairtoitem(cp), "No value specified for virtual_server");
1462                         return 0;
1463                 }
1464
1465                 cf_log_info(cs, "\tvirtual_server = %s", host);
1466
1467                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1468                                     &r->auth_pool, HOME_TYPE_AUTH, host)) {
1469                         return 0;
1470                 }
1471                 if (!old_server_add(rc, cs, r->name, host, "", ldflag,
1472                                     &r->acct_pool, HOME_TYPE_ACCT, host)) {
1473                         return 0;
1474                 }
1475         }
1476
1477         if (secret) cf_log_info(cs, "\tsecret = %s", secret);
1478
1479         return 1;
1480
1481 }
1482
1483
1484 #ifdef WITH_PROXY
1485 static int add_pool_to_realm(realm_config_t *rc, CONF_SECTION *cs,
1486                              const char *name, home_pool_t **dest,
1487                              int server_type, int do_print)
1488 {
1489         home_pool_t mypool, *pool;
1490
1491         mypool.name = name;
1492         mypool.server_type = server_type;
1493
1494         pool = rbtree_finddata(home_pools_byname, &mypool);
1495         if (!pool) {
1496                 CONF_SECTION *pool_cs;
1497
1498                 pool_cs = cf_section_sub_find_name2(rc->cs,
1499                                                     "home_server_pool",
1500                                                     name);
1501                 if (!pool_cs) {
1502                         pool_cs = cf_section_sub_find_name2(rc->cs,
1503                                                             "server_pool",
1504                                                             name);
1505                 }
1506                 if (!pool_cs) {
1507                         cf_log_err(cf_sectiontoitem(cs), "Failed to find home_server_pool \"%s\"", name);
1508                         return 0;
1509                 }
1510
1511                 if (!server_pool_add(rc, pool_cs, server_type, do_print)) {
1512                         return 0;
1513                 }
1514
1515                 pool = rbtree_finddata(home_pools_byname, &mypool);
1516                 if (!pool) {
1517                         radlog(L_ERR, "Internal sanity check failed in add_pool_to_realm");
1518                         return 0;
1519                 }
1520         }
1521
1522         if (pool->server_type != server_type) {
1523                 cf_log_err(cf_sectiontoitem(cs), "Incompatible home_server_pool \"%s\" (mixed auth_pool / acct_pool)", name);
1524                 return 0;
1525         }
1526
1527         *dest = pool;
1528
1529         return 1;
1530 }
1531 #endif
1532
1533
1534 static int realm_add(realm_config_t *rc, CONF_SECTION *cs)
1535 {
1536         const char *name2;
1537         REALM *r = NULL;
1538         CONF_PAIR *cp;
1539 #ifdef WITH_PROXY
1540         home_pool_t *auth_pool, *acct_pool;
1541         const char *auth_pool_name, *acct_pool_name;
1542 #endif
1543
1544         name2 = cf_section_name1(cs);
1545         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
1546                 cf_log_err(cf_sectiontoitem(cs), "Section is not a realm.");
1547                 return 0;
1548         }
1549
1550         name2 = cf_section_name2(cs);
1551         if (!name2) {
1552                 cf_log_err(cf_sectiontoitem(cs), "Realm section is missing the realm name.");
1553                 return 0;
1554         }
1555
1556 #ifdef WITH_PROXY
1557         auth_pool = acct_pool = NULL;
1558         auth_pool_name = acct_pool_name = NULL;
1559
1560         /*
1561          *      Prefer new configuration to old one.
1562          */
1563         cp = cf_pair_find(cs, "pool");
1564         if (!cp) cp = cf_pair_find(cs, "home_server_pool");
1565         if (cp) auth_pool_name = cf_pair_value(cp);
1566         if (cp && auth_pool_name) {
1567                 acct_pool_name = auth_pool_name;
1568                 if (!add_pool_to_realm(rc, cs,
1569                                        auth_pool_name, &auth_pool,
1570                                        HOME_TYPE_AUTH, 1)) {
1571                         return 0;
1572                 }
1573                 if (!add_pool_to_realm(rc, cs,
1574                                        auth_pool_name, &acct_pool,
1575                                        HOME_TYPE_ACCT, 0)) {
1576                         return 0;
1577                 }
1578         }
1579
1580         cp = cf_pair_find(cs, "auth_pool");
1581         if (cp) auth_pool_name = cf_pair_value(cp);
1582         if (cp && auth_pool_name) {
1583                 if (auth_pool) {
1584                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"auth_pool\" at the same time.");
1585                         return 0;
1586                 }
1587                 if (!add_pool_to_realm(rc, cs,
1588                                        auth_pool_name, &auth_pool,
1589                                        HOME_TYPE_AUTH, 1)) {
1590                         return 0;
1591                 }
1592         }
1593
1594         cp = cf_pair_find(cs, "acct_pool");
1595         if (cp) acct_pool_name = cf_pair_value(cp);
1596         if (cp && acct_pool_name) {
1597                 int do_print = TRUE;
1598
1599                 if (acct_pool) {
1600                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"acct_pool\" at the same time.");
1601                         return 0;
1602                 }
1603
1604                 if (!auth_pool ||
1605                     (strcmp(auth_pool_name, acct_pool_name) != 0)) {
1606                         do_print = TRUE;
1607                 }
1608
1609                 if (!add_pool_to_realm(rc, cs,
1610                                        acct_pool_name, &acct_pool,
1611                                        HOME_TYPE_ACCT, do_print)) {
1612                         return 0;
1613                 }
1614         }
1615 #endif
1616
1617         cf_log_info(cs, " realm %s {", name2);
1618
1619 #ifdef WITH_PROXY
1620         /*
1621          *      The realm MAY already exist if it's an old-style realm.
1622          *      In that case, merge the old-style realm with this one.
1623          */
1624         r = realm_find2(name2);
1625         if (r && (strcmp(r->name, name2) == 0)) {
1626                 if (cf_pair_find(cs, "auth_pool") ||
1627                     cf_pair_find(cs, "acct_pool")) {
1628                         cf_log_err(cf_sectiontoitem(cs), "Duplicate realm \"%s\"", name2);
1629                         goto error;
1630                 }
1631
1632                 if (!old_realm_config(rc, cs, r)) {
1633                         goto error;
1634                 }
1635
1636                 cf_log_info(cs, " } # realm %s", name2);
1637                 return 1;
1638         }
1639 #endif
1640
1641 #ifdef HAVE_REGEX_H
1642         if (name2[0] == '~') {
1643                 int rcode;
1644                 regex_t reg;
1645                 
1646                 /*
1647                  *      Include substring matches.
1648                  */
1649                 rcode = regcomp(&reg, name2 + 1,
1650                                 REG_EXTENDED | REG_NOSUB | REG_ICASE);
1651                 if (rcode != 0) {
1652                         char buffer[256];
1653
1654                         regerror(rcode, &reg, buffer, sizeof(buffer));
1655
1656                         cf_log_err(cf_sectiontoitem(cs),
1657                                    "Invalid regex \"%s\": %s",
1658                                    name2 + 1, buffer);
1659                         goto error;
1660                 }
1661                 regfree(&reg);
1662         }
1663 #endif
1664
1665         r = rad_malloc(sizeof(*r));
1666         memset(r, 0, sizeof(*r));
1667
1668         r->name = name2;
1669         r->striprealm = 1;
1670 #ifdef WITH_PROXY
1671         r->auth_pool = auth_pool;
1672         r->acct_pool = acct_pool;
1673         
1674         if (auth_pool_name &&
1675             (auth_pool_name == acct_pool_name)) { /* yes, ptr comparison */
1676                 cf_log_info(cs, "\tpool = %s", auth_pool_name);
1677         } else {
1678                 if (auth_pool_name) cf_log_info(cs, "\tauth_pool = %s", auth_pool_name);
1679                 if (acct_pool_name) cf_log_info(cs, "\tacct_pool = %s", acct_pool_name);
1680         }
1681 #endif
1682
1683         cp = cf_pair_find(cs, "nostrip");
1684         if (cp && (cf_pair_value(cp) == NULL)) {
1685                 r->striprealm = 0;
1686                 cf_log_info(cs, "\tnostrip");
1687         }
1688
1689         /*
1690          *      We're a new-style realm.  Complain if we see the old
1691          *      directives.
1692          */
1693         if (r->auth_pool || r->acct_pool) {
1694                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
1695                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
1696                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
1697                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
1698                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
1699                 }
1700
1701
1702                 /*
1703                  *      The realm MAY be an old-style realm, as there
1704                  *      was no auth_pool or acct_pool.  Double-check
1705                  *      it, just to be safe.
1706                  */
1707         } else if (!old_realm_config(rc, cs, r)) {
1708                 goto error;
1709         }
1710
1711 #ifdef HAVE_REGEX_H
1712         /*
1713          *      It's a regex.  Add it to a separate list.
1714          */
1715         if (name2[0] == '~') {
1716                 realm_regex_t *rr, **last;
1717
1718                 rr = rad_malloc(sizeof(*rr));
1719                 
1720                 last = &realms_regex;
1721                 while (*last) last = &((*last)->next);  /* O(N^2)... sue me. */
1722
1723                 r->name = name2;
1724                 rr->realm = r;
1725                 rr->next = NULL;
1726
1727                 *last = rr;
1728
1729                 cf_log_info(cs, " }");
1730                 return 1;
1731         }
1732 #endif
1733
1734         if (!rbtree_insert(realms_byname, r)) {
1735                 rad_assert("Internal sanity check failed");
1736                 goto error;
1737         }
1738
1739         cf_log_info(cs, " }");
1740
1741         return 1;
1742
1743  error:
1744         cf_log_info(cs, " } # realm %s", name2);
1745         free(r);
1746         return 0;
1747 }
1748
1749 #ifdef WITH_COA
1750 static const FR_NAME_NUMBER home_server_types[] = {
1751         { "auth", HOME_TYPE_AUTH },
1752         { "auth+acct", HOME_TYPE_AUTH },
1753         { "acct", HOME_TYPE_ACCT },
1754         { "coa", HOME_TYPE_COA },
1755         { NULL, 0 }
1756 };
1757
1758 static int pool_peek_type(CONF_SECTION *config, CONF_SECTION *cs)
1759 {
1760         int home;
1761         const char *name, *type;
1762         CONF_PAIR *cp;
1763         CONF_SECTION *server_cs;
1764
1765         cp = cf_pair_find(cs, "home_server");
1766         if (!cp) {
1767                 cf_log_err(cf_sectiontoitem(cs), "Pool does not contain a \"home_server\" entry");
1768                 return HOME_TYPE_INVALID;
1769         }
1770
1771         name = cf_pair_value(cp);
1772         if (!name) {
1773                 cf_log_err(cf_pairtoitem(cp), "home_server entry does not reference a home server");
1774                 return HOME_TYPE_INVALID;
1775         }
1776
1777         server_cs = cf_section_sub_find_name2(config, "home_server", name);
1778         if (!server_cs) {
1779                 cf_log_err(cf_pairtoitem(cp), "home_server \"%s\" does not exist", name);
1780                 return HOME_TYPE_INVALID;
1781         }
1782
1783         cp = cf_pair_find(server_cs, "type");
1784         if (!cp) {
1785                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s does not contain a \"type\" entry", name);
1786                 return HOME_TYPE_INVALID;
1787         }
1788
1789         type = cf_pair_value(cp);
1790         if (!type) {
1791                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s contains an empty \"type\" entry", name);
1792                 return HOME_TYPE_INVALID;
1793         }
1794
1795         home = fr_str2int(home_server_types, type, HOME_TYPE_INVALID);
1796         if (home == HOME_TYPE_INVALID) {
1797                 cf_log_err(cf_sectiontoitem(server_cs), "home_server %s contains an invalid \"type\" entry of value \"%s\"", name, type);
1798                 return HOME_TYPE_INVALID;
1799         }
1800
1801         return home;            /* 'cause we miss it so much */
1802 }
1803 #endif
1804
1805 int realms_init(CONF_SECTION *config)
1806 {
1807         CONF_SECTION *cs;
1808         realm_config_t *rc, *old_rc;
1809
1810         if (realms_byname) return 1;
1811
1812         realms_byname = rbtree_create(realm_name_cmp, free, 0);
1813         if (!realms_byname) {
1814                 realms_free();
1815                 return 0;
1816         }
1817
1818 #ifdef WITH_PROXY
1819         home_servers_byaddr = rbtree_create(home_server_addr_cmp, home_server_free, 0);
1820         if (!home_servers_byaddr) {
1821                 realms_free();
1822                 return 0;
1823         }
1824
1825         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
1826         if (!home_servers_byname) {
1827                 realms_free();
1828                 return 0;
1829         }
1830
1831 #ifdef WITH_STATS
1832         home_servers_bynumber = rbtree_create(home_server_number_cmp, NULL, 0);
1833         if (!home_servers_bynumber) {
1834                 realms_free();
1835                 return 0;
1836         }
1837 #endif
1838
1839         home_pools_byname = rbtree_create(home_pool_name_cmp, NULL, 0);
1840         if (!home_pools_byname) {
1841                 realms_free();
1842                 return 0;
1843         }
1844 #endif
1845
1846         rc = rad_malloc(sizeof(*rc));
1847         memset(rc, 0, sizeof(*rc));
1848         rc->cs = config;
1849
1850 #ifdef WITH_PROXY
1851         cs = cf_subsection_find_next(config, NULL, "proxy");
1852         if (cs) {
1853                 cf_section_parse(cs, rc, proxy_config);
1854         } else {
1855                 rc->dead_time = DEAD_TIME;
1856                 rc->retry_count = RETRY_COUNT;
1857                 rc->retry_delay = RETRY_DELAY;
1858                 rc->fallback = 0;
1859                 rc->wake_all_if_all_dead= 0;
1860         }
1861
1862         for (cs = cf_subsection_find_next(config, NULL, "home_server");
1863              cs != NULL;
1864              cs = cf_subsection_find_next(config, cs, "home_server")) {
1865                 if (!home_server_add(rc, cs)) {
1866                         free(rc);
1867                         realms_free();
1868                         return 0;
1869                 }
1870         }
1871 #endif
1872
1873         for (cs = cf_subsection_find_next(config, NULL, "realm");
1874              cs != NULL;
1875              cs = cf_subsection_find_next(config, cs, "realm")) {
1876                 if (!realm_add(rc, cs)) {
1877                         free(rc);
1878                         realms_free();
1879                         return 0;
1880                 }
1881         }
1882
1883 #ifdef WITH_COA
1884         /*
1885          *      CoA pools aren't tied to realms.
1886          */
1887         for (cs = cf_subsection_find_next(config, NULL, "home_server_pool");
1888              cs != NULL;
1889              cs = cf_subsection_find_next(config, cs, "home_server_pool")) {
1890                 int type;
1891
1892                 /*
1893                  *      Pool was already loaded.
1894                  */
1895                 if (cf_data_find(cs, "home_server_pool")) continue;
1896
1897                 type = pool_peek_type(config, cs);
1898                 if (type == HOME_TYPE_INVALID) return 0;
1899
1900                 if (!server_pool_add(rc, cs, type, TRUE)) {
1901                         return 0;
1902                 }
1903         }
1904 #endif
1905
1906
1907 #ifdef WITH_PROXY
1908         xlat_register("home_server", xlat_home_server, NULL);
1909         xlat_register("home_server_pool", xlat_server_pool, NULL);
1910 #endif
1911
1912         /*
1913          *      Swap pointers atomically.
1914          */
1915         old_rc = realm_config;
1916         realm_config = rc;
1917         free(old_rc);
1918
1919         return 1;
1920 }
1921
1922 /*
1923  *      Find a realm where "name" might be the regex.
1924  */
1925 REALM *realm_find2(const char *name)
1926 {
1927         REALM myrealm;
1928         REALM *realm;
1929         
1930         if (!name) name = "NULL";
1931
1932         myrealm.name = name;
1933         realm = rbtree_finddata(realms_byname, &myrealm);
1934         if (realm) return realm;
1935
1936 #ifdef HAVE_REGEX_H
1937         if (realms_regex) {
1938                 realm_regex_t *this;
1939
1940                 for (this = realms_regex; this != NULL; this = this->next) {
1941                         if (strcmp(this->realm->name, name) == 0) {
1942                                 return this->realm;
1943                         }
1944                 }
1945         }
1946 #endif
1947
1948         /*
1949          *      Couldn't find a realm.  Look for DEFAULT.
1950          */
1951         myrealm.name = "DEFAULT";
1952         return rbtree_finddata(realms_byname, &myrealm);
1953 }
1954
1955
1956 /*
1957  *      Find a realm in the REALM list.
1958  */
1959 REALM *realm_find(const char *name)
1960 {
1961         REALM myrealm;
1962         REALM *realm;
1963         
1964         if (!name) name = "NULL";
1965
1966         myrealm.name = name;
1967         realm = rbtree_finddata(realms_byname, &myrealm);
1968         if (realm) return realm;
1969
1970 #ifdef HAVE_REGEX_H
1971         if (realms_regex) {
1972                 realm_regex_t *this;
1973
1974                 for (this = realms_regex; this != NULL; this = this->next) {
1975                         int compare;
1976                         regex_t reg;
1977
1978                         /*
1979                          *      Include substring matches.
1980                          */
1981                         if (regcomp(&reg, this->realm->name + 1,
1982                                     REG_EXTENDED | REG_NOSUB | REG_ICASE) != 0) {
1983                                 continue;
1984                         }
1985
1986                         compare = regexec(&reg, name, 0, NULL, 0);
1987                         regfree(&reg);
1988
1989                         if (compare == 0) return this->realm;
1990                 }
1991         }
1992 #endif
1993
1994         /*
1995          *      Couldn't find a realm.  Look for DEFAULT.
1996          */
1997         myrealm.name = "DEFAULT";
1998         return rbtree_finddata(realms_byname, &myrealm);
1999 }
2000
2001
2002 #ifdef WITH_PROXY
2003 home_server *home_server_ldb(const char *realmname,
2004                              home_pool_t *pool, REQUEST *request)
2005 {
2006         int             start;
2007         int             count;
2008         home_server     *found = NULL;
2009         home_server     *zombie = NULL;
2010         VALUE_PAIR      *vp;
2011
2012         /*
2013          *      Determine how to pick choose the home server.
2014          */
2015         switch (pool->type) {
2016                 uint32_t hash;
2017
2018                 /*
2019                  *      For load-balancing by client IP address, we
2020                  *      pick a home server by hashing the client IP.
2021                  *
2022                  *      This isn't as even a load distribution as
2023                  *      tracking the State attribute, but it's better
2024                  *      than nothing.
2025                  */
2026         case HOME_POOL_CLIENT_BALANCE:
2027                 switch (request->packet->src_ipaddr.af) {
2028                 case AF_INET:
2029                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
2030                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
2031                         break;
2032                 case AF_INET6:
2033                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
2034                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
2035                         break;
2036                 default:
2037                         hash = 0;
2038                         break;
2039                 }
2040                 start = hash % pool->num_home_servers;
2041                 break;
2042
2043         case HOME_POOL_CLIENT_PORT_BALANCE:
2044                 switch (request->packet->src_ipaddr.af) {
2045                 case AF_INET:
2046                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
2047                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
2048                         break;
2049                 case AF_INET6:
2050                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
2051                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
2052                         break;
2053                 default:
2054                         hash = 0;
2055                         break;
2056                 }
2057                 fr_hash_update(&request->packet->src_port,
2058                                  sizeof(request->packet->src_port), hash);
2059                 start = hash % pool->num_home_servers;
2060                 break;
2061
2062         case HOME_POOL_KEYED_BALANCE:
2063                 if ((vp = pairfind(request->config_items, PW_LOAD_BALANCE_KEY, 0)) != NULL) {
2064                         hash = fr_hash(vp->vp_strvalue, vp->length);
2065                         start = hash % pool->num_home_servers;
2066                         break;
2067                 }
2068                 /* FALL-THROUGH */
2069                                 
2070         case HOME_POOL_LOAD_BALANCE:
2071         case HOME_POOL_FAIL_OVER:
2072                 start = 0;
2073                 break;
2074
2075         default:                /* this shouldn't happen... */
2076                 start = 0;
2077                 break;
2078
2079         }
2080
2081         /*
2082          *      Starting with the home server we chose, loop through
2083          *      all home servers.  If the current one is dead, skip
2084          *      it.  If it is too busy, skip it.
2085          *
2086          *      Otherwise, use it.
2087          */
2088         for (count = 0; count < pool->num_home_servers; count++) {
2089                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
2090
2091                 if (!home) continue;
2092
2093                 /*
2094                  *      Skip dead home servers.
2095                  */
2096                 if (home->state == HOME_STATE_IS_DEAD) {
2097                         continue;
2098                 }
2099
2100                 /*
2101                  *      This home server is too busy.  Choose another one.
2102                  */
2103                 if (home->currently_outstanding >= home->max_outstanding) {
2104                         continue;
2105                 }
2106
2107 #ifdef WITH_DETAIL
2108                 /*
2109                  *      We read the packet from a detail file, AND it
2110                  *      came from this server.  Don't re-proxy it
2111                  *      there.
2112                  */
2113                 if ((request->listener->type == RAD_LISTEN_DETAIL) &&
2114                     (request->packet->code == PW_ACCOUNTING_REQUEST) &&
2115                     (fr_ipaddr_cmp(&home->ipaddr, &request->packet->src_ipaddr) == 0)) {
2116                         continue;
2117                 }
2118 #endif
2119
2120                 /*
2121                  *      It's zombie, so we remember the first zombie
2122                  *      we find, but we don't mark it as a "live"
2123                  *      server.
2124                  */
2125                 if (home->state == HOME_STATE_ZOMBIE) {
2126                         if (!zombie) zombie = home;
2127                         continue;
2128                 }
2129
2130                 /*
2131                  *      We've found the first "live" one.  Use that.
2132                  */
2133                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
2134                         found = home;
2135                         break;
2136                 }
2137
2138                 /*
2139                  *      Otherwise we're doing some kind of load balancing.
2140                  *      If we haven't found one yet, pick this one.
2141                  */
2142                 if (!found) {
2143                         found = home;
2144                         continue;
2145                 }
2146
2147                 RDEBUG3("PROXY %s %d\t%s %d",
2148                        found->name, found->currently_outstanding,
2149                        home->name, home->currently_outstanding);
2150
2151                 /*
2152                  *      Prefer this server if it's less busy than the
2153                  *      one we had previously found.
2154                  */
2155                 if (home->currently_outstanding < found->currently_outstanding) {
2156                         RDEBUG3("PROXY Choosing %s: It's less busy than %s",
2157                                home->name, found->name);
2158                         found = home;
2159                         continue;
2160                 }
2161
2162                 /*
2163                  *      Ignore servers which are busier than the one
2164                  *      we found.
2165                  */
2166                 if (home->currently_outstanding > found->currently_outstanding) {
2167                         RDEBUG3("PROXY Skipping %s: It's busier than %s",
2168                                home->name, found->name);
2169                         continue;
2170                 }
2171
2172                 /*
2173                  *      From the list of servers which have the same
2174                  *      load, choose one at random.
2175                  */
2176                 if (((count + 1) * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
2177                         found = home;
2178                 }
2179         } /* loop over the home servers */
2180
2181         /*
2182          *      We have no live servers, BUT we have a zombie.  Use
2183          *      the zombie as a last resort.
2184          */
2185         if (!found && zombie) {
2186                 found = zombie;
2187                 zombie = NULL;
2188         }
2189
2190         /*
2191          *      There's a fallback if they're all dead.
2192          */
2193         if (!found && pool->fallback) {
2194                 found = pool->fallback;
2195
2196                 if (pool->in_fallback) goto update_and_return;
2197
2198                 pool->in_fallback = TRUE;
2199                 
2200                 /*
2201                  *      Run the trigger once an hour saying that
2202                  *      they're all dead.
2203                  */
2204                 if ((pool->time_all_dead + 3600) < request->timestamp) {
2205                         pool->time_all_dead = request->timestamp;
2206                         exec_trigger(request, pool->cs, "home_server_pool.fallback");
2207                 }
2208         }
2209
2210         if (found) {
2211         update_and_return:
2212                 if ((found != pool->fallback) && pool->in_fallback) {
2213                         pool->in_fallback = FALSE;
2214                         exec_trigger(request, pool->cs, "home_server_pool.normal");
2215                 }
2216
2217                 /*
2218                  *      Allocate the proxy packet, only if it wasn't
2219                  *      already allocated by a module.  This check is
2220                  *      mainly to support the proxying of EAP-TTLS and
2221                  *      EAP-PEAP tunneled requests.
2222                  *
2223                  *      In those cases, the EAP module creates a
2224                  *      "fake" request, and recursively passes it
2225                  *      through the authentication stage of the
2226                  *      server.  The module then checks if the request
2227                  *      was supposed to be proxied, and if so, creates
2228                  *      a proxy packet from the TUNNELED request, and
2229                  *      not from the EAP request outside of the
2230                  *      tunnel.
2231                  *
2232                  *      The proxy then works like normal, except that
2233                  *      the response packet is "eaten" by the EAP
2234                  *      module, and encapsulated into an EAP packet.
2235                  */
2236                 if (!request->proxy) {
2237                         if ((request->proxy = rad_alloc(TRUE)) == NULL) {
2238                                 radlog(L_ERR|L_CONS, "no memory");
2239                                 exit(1);
2240                         }
2241                         
2242                         /*
2243                          *      Copy the request, then look up name
2244                          *      and plain-text password in the copy.
2245                          *
2246                          *      Note that the User-Name attribute is
2247                          *      the *original* as sent over by the
2248                          *      client.  The Stripped-User-Name
2249                          *      attribute is the one hacked through
2250                          *      the 'hints' file.
2251                          */
2252                         request->proxy->vps =  paircopy(request->packet->vps);
2253                 }
2254
2255                 /*
2256                  *      Update the various fields as appropriate.
2257                  */
2258                 request->proxy->src_ipaddr = found->src_ipaddr;
2259                 request->proxy->src_port = 0;
2260                 request->proxy->dst_ipaddr = found->ipaddr;
2261                 request->proxy->dst_port = found->port;
2262                 request->home_server = found;
2263
2264                 /*
2265                  *      We're supposed to add a Message-Authenticator
2266                  *      if it doesn't exist, and it doesn't exist.
2267                  */
2268                 if (found->message_authenticator &&
2269                     (request->packet->code == PW_AUTHENTICATION_REQUEST) &&
2270                     !pairfind(request->proxy->vps, PW_MESSAGE_AUTHENTICATOR, 0)) {
2271                         radius_pairmake(request, &request->proxy->vps,
2272                                         "Message-Authenticator", "0x00",
2273                                         T_OP_SET);
2274                 }
2275
2276                 return found;
2277         }
2278
2279         /*
2280          *      No live match found, and no fallback to the "DEFAULT"
2281          *      realm.  We fix this by blindly marking all servers as
2282          *      "live".  But only do it for ones that don't support
2283          *      "pings", as they will be marked live when they
2284          *      actually are live.
2285          */
2286         if (!realm_config->fallback &&
2287             realm_config->wake_all_if_all_dead) {
2288                 for (count = 0; count < pool->num_home_servers; count++) {
2289                         home_server *home = pool->servers[count];
2290
2291                         if (!home) continue;
2292
2293                         if ((home->state == HOME_STATE_IS_DEAD) &&
2294                             (home->ping_check == HOME_PING_CHECK_NONE)) {
2295                                 home->state = HOME_STATE_ALIVE;
2296                                 if (!found) found = home;
2297                         }
2298                 }
2299
2300                 if (found) goto update_and_return;
2301         }
2302
2303         /*
2304          *      Still nothing.  Look up the DEFAULT realm, but only
2305          *      if we weren't looking up the NULL or DEFAULT realms.
2306          */
2307         if (realm_config->fallback &&
2308             realmname &&
2309             (strcmp(realmname, "NULL") != 0) &&
2310             (strcmp(realmname, "DEFAULT") != 0)) {
2311                 REALM *rd = realm_find("DEFAULT");
2312
2313                 if (!rd) return NULL;
2314
2315                 pool = NULL;
2316                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
2317                         pool = rd->auth_pool;
2318
2319                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
2320                         pool = rd->acct_pool;
2321                 }
2322                 if (!pool) return NULL;
2323
2324                 RDEBUG2("PROXY - realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
2325                 return home_server_ldb(rd->name, pool, request);
2326         }
2327
2328         /*
2329          *      Still haven't found anything.  Oh well.
2330          */
2331         return NULL;
2332 }
2333
2334
2335 home_server *home_server_find(fr_ipaddr_t *ipaddr, int port, int proto)
2336 {
2337         home_server myhome;
2338
2339         memset(&myhome, 0, sizeof(myhome));
2340         myhome.ipaddr = *ipaddr;
2341         myhome.port = port;
2342 #ifdef WITH_TCP
2343         myhome.proto = proto;
2344 #else
2345         myhome.proto = IPPROTO_UDP;
2346 #endif
2347         myhome.server = NULL;   /* we're not called for internal proxying */
2348
2349         return rbtree_finddata(home_servers_byaddr, &myhome);
2350 }
2351
2352 #ifdef WITH_COA
2353 home_server *home_server_byname(const char *name, int type)
2354 {
2355         home_server myhome;
2356
2357         memset(&myhome, 0, sizeof(myhome));
2358         myhome.type = type;
2359         myhome.name = name;
2360
2361         return rbtree_finddata(home_servers_byname, &myhome);
2362 }
2363 #endif
2364
2365 #ifdef WITH_STATS
2366 home_server *home_server_bynumber(int number)
2367 {
2368         home_server myhome;
2369
2370         memset(&myhome, 0, sizeof(myhome));
2371         myhome.number = number;
2372         myhome.server = NULL;   /* we're not called for internal proxying */
2373
2374         return rbtree_finddata(home_servers_bynumber, &myhome);
2375 }
2376 #endif
2377
2378 home_pool_t *home_pool_byname(const char *name, int type)
2379 {
2380         home_pool_t mypool;
2381         
2382         memset(&mypool, 0, sizeof(mypool));
2383         mypool.name = name;
2384         mypool.server_type = type;
2385         return rbtree_finddata(home_pools_byname, &mypool);
2386 }
2387
2388 #endif