use new cf_log_info.
[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 static rbtree_t *realms_byname = NULL;
36
37 static rbtree_t *home_servers_byaddr = NULL;
38 static rbtree_t *home_servers_byname = NULL;
39
40 static rbtree_t *home_pools_byname = NULL;
41
42 typedef struct realm_config_t {
43         CONF_SECTION    *cs;
44         int             dead_time;
45         int             retry_count;
46         int             retry_delay;
47         int             fallback;
48         int             wake_all_if_all_dead;
49 } realm_config_t;
50
51 static realm_config_t *realm_config = NULL;
52
53 /*
54  *  Map the proxy server configuration parameters to variables.
55  */
56 static const CONF_PARSER proxy_config[] = {
57         { "retry_delay",  PW_TYPE_INTEGER,
58           offsetof(realm_config_t, retry_delay),
59           NULL, Stringify(RETRY_DELAY) },
60
61         { "retry_count",  PW_TYPE_INTEGER,
62           offsetof(realm_config_t, retry_count),
63           NULL, Stringify(RETRY_COUNT) },
64
65         { "default_fallback", PW_TYPE_BOOLEAN,
66           offsetof(realm_config_t, fallback),
67           NULL, "no" },
68
69         { "dead_time",    PW_TYPE_INTEGER, 
70           offsetof(realm_config_t, dead_time),
71           NULL, Stringify(DEAD_TIME) },
72
73         { "wake_all_if_all_dead", PW_TYPE_BOOLEAN,
74           offsetof(realm_config_t, wake_all_if_all_dead),
75           NULL, "no" },
76
77         { NULL, -1, 0, NULL, NULL }
78 };
79
80 static int realm_name_cmp(const void *one, const void *two)
81 {
82         const REALM *a = one;
83         const REALM *b = two;
84
85         return strcasecmp(a->name, b->name);
86 }
87
88
89 static int home_server_name_cmp(const void *one, const void *two)
90 {
91         const home_server *a = one;
92         const home_server *b = two;
93
94         if (a->type < b->type) return -1;
95         if (a->type > b->type) return +1;
96
97         return strcasecmp(a->name, b->name);
98 }
99
100 static int home_server_addr_cmp(const void *one, const void *two)
101 {
102         const home_server *a = one;
103         const home_server *b = two;
104
105         if (a->port < b->port) return -1;
106         if (a->port > b->port) return +1;
107
108         return fr_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
109 }
110
111
112 static int home_pool_name_cmp(const void *one, const void *two)
113 {
114         const home_pool_t *a = one;
115         const home_pool_t *b = two;
116
117         if (a->server_type < b->server_type) return -1;
118         if (a->server_type > b->server_type) return +1;
119
120         return strcasecmp(a->name, b->name);
121 }
122
123
124 /*
125  *      Xlat for %{home_server:foo}
126  */
127 static size_t xlat_home_server(UNUSED void *instance, REQUEST *request,
128                                char *fmt, char *out, size_t outlen,
129                                UNUSED RADIUS_ESCAPE_STRING func)
130 {
131         const char *value = NULL;
132         CONF_PAIR *cp;
133
134         if (!fmt || !out || (outlen < 1)) return 0;
135
136         if (!request || !request->home_server) {
137                 *out = '\0';
138                 return 0;
139         }
140
141         cp = cf_pair_find(request->home_server->cs, fmt);
142         if (!cp || !(value = cf_pair_value(cp))) {
143                 *out = '\0';
144                 return 0;
145         }
146         
147         strlcpy(out, value, outlen);
148
149         return strlen(out);
150 }
151
152
153 /*
154  *      Xlat for %{home_server_pool:foo}
155  */
156 static size_t xlat_server_pool(UNUSED void *instance, REQUEST *request,
157                                char *fmt, char *out, size_t outlen,
158                                UNUSED RADIUS_ESCAPE_STRING func)
159 {
160         const char *value = NULL;
161         CONF_PAIR *cp;
162
163         if (!fmt || !out || (outlen < 1)) return 0;
164
165         if (!request || !request->home_pool) {
166                 *out = '\0';
167                 return 0;
168         }
169
170         cp = cf_pair_find(request->home_pool->cs, fmt);
171         if (!cp || !(value = cf_pair_value(cp))) {
172                 *out = '\0';
173                 return 0;
174         }
175         
176         strlcpy(out, value, outlen);
177
178         return strlen(out);
179 }
180
181
182 void realms_free(void)
183 {
184         rbtree_free(home_servers_byname);
185         home_servers_byname = NULL;
186
187         rbtree_free(home_servers_byaddr);
188         home_servers_byaddr = NULL;
189
190         rbtree_free(home_pools_byname);
191         home_pools_byname = NULL;
192
193         rbtree_free(realms_byname);
194         realms_byname = NULL;
195 }
196
197
198 static struct in_addr hs_ip4addr;
199 static struct in6_addr hs_ip6addr;
200 static char *hs_type = NULL;
201 static char *hs_check = NULL;
202
203 static CONF_PARSER home_server_config[] = {
204         { "ipaddr",  PW_TYPE_IPADDR,
205           0, &hs_ip4addr,  NULL },
206         { "ipv6addr",  PW_TYPE_IPV6ADDR,
207           0, &hs_ip6addr, NULL },
208
209         { "port", PW_TYPE_INTEGER,
210           offsetof(home_server,port), NULL,   "0" },
211
212         { "type",  PW_TYPE_STRING_PTR,
213           0, &hs_type, NULL },
214
215         { "secret",  PW_TYPE_STRING_PTR,
216           offsetof(home_server,secret), NULL,  NULL},
217
218         { "response_window", PW_TYPE_INTEGER,
219           offsetof(home_server,response_window), NULL,   "30" },
220         { "max_outstanding", PW_TYPE_INTEGER,
221           offsetof(home_server,max_outstanding), NULL,   "65536" },
222
223         { "zombie_period", PW_TYPE_INTEGER,
224           offsetof(home_server,zombie_period), NULL,   "40" },
225         { "status_check", PW_TYPE_STRING_PTR,
226           0, &hs_check,   "none" },
227         { "ping_check", PW_TYPE_STRING_PTR,
228           0, &hs_check,   "none" },
229
230         { "ping_interval", PW_TYPE_INTEGER,
231           offsetof(home_server,ping_interval), NULL,   "30" },
232         { "check_interval", PW_TYPE_INTEGER,
233           offsetof(home_server,ping_interval), NULL,   "30" },
234         { "num_answers_to_alive", PW_TYPE_INTEGER,
235           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
236         { "num_pings_to_alive", PW_TYPE_INTEGER,
237           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
238         { "revive_interval", PW_TYPE_INTEGER,
239           offsetof(home_server,revive_interval), NULL,   "300" },
240         { "status_check_timeout", PW_TYPE_INTEGER,
241           offsetof(home_server,ping_timeout), NULL,   "4" },
242
243         { "username",  PW_TYPE_STRING_PTR,
244           offsetof(home_server,ping_user_name), NULL,  NULL},
245         { "password",  PW_TYPE_STRING_PTR,
246           offsetof(home_server,ping_user_password), NULL,  NULL},
247
248         { NULL, -1, 0, NULL, NULL }             /* end the list */
249
250 };
251
252
253 static int home_server_add(CONF_SECTION *cs, int type)
254 {
255         const char *name2;
256         home_server *home;
257         int dual = FALSE;
258
259         name2 = cf_section_name1(cs);
260         if (!name2 || (strcasecmp(name2, "home_server") != 0)) {
261                 cf_log_err(cf_sectiontoitem(cs),
262                            "Section is not a home_server.");
263                 return 0;
264         }
265
266         name2 = cf_section_name2(cs);
267         if (!name2) {
268                 cf_log_err(cf_sectiontoitem(cs),
269                            "Home server section is missing a name.");
270                 return 0;
271         }
272
273         home = rad_malloc(sizeof(*home));
274         memset(home, 0, sizeof(*home));
275
276         home->name = name2;
277         home->cs = cs;
278
279         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
280         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
281         cf_section_parse(cs, home, home_server_config);
282
283         if (!cf_pair_find(cs, "ipaddr") &&
284             !cf_pair_find(cs, "ipv6addr")) {
285                 cf_log_err(cf_sectiontoitem(cs),
286                            "No IPv4 or IPv6 address defined for home server %s.",
287                            name2);
288                 free(home);
289                 free(hs_type);
290                 hs_type = NULL;
291                 free(hs_check);
292                 hs_check = NULL;
293                 return 0;
294         }
295
296         /*
297          *      Figure out which one to use.
298          */
299         if (cf_pair_find(cs, "ipaddr")) {
300                 home->ipaddr.af = AF_INET;
301                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
302
303         } else if (cf_pair_find(cs, "ipv6addr")) {
304                 home->ipaddr.af = AF_INET6;
305                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
306
307         } else {
308                 cf_log_err(cf_sectiontoitem(cs),
309                            "Internal sanity check failed for home server %s.",
310                            name2);
311                 free(home);
312                 free(hs_type);
313                 hs_type = NULL;
314                 free(hs_check);
315                 hs_check = NULL;
316                 return 0;
317         }
318
319         if (!home->port || (home->port > 65535)) {
320                 cf_log_err(cf_sectiontoitem(cs),
321                            "No port, or invalid port defined for home server %s.",
322                            name2);
323                 free(home);
324                 free(hs_type);
325                 hs_type = NULL;
326                 free(hs_check);
327                 hs_check = NULL;
328                 return 0;
329         }
330
331         if (0) {
332                 cf_log_err(cf_sectiontoitem(cs),
333                            "Fatal error!  Home server %s is ourselves!",
334                            name2);
335                 free(home);
336                 free(hs_type);
337                 hs_type = NULL;
338                 free(hs_check);
339                 hs_check = NULL;
340                 return 0;
341         }
342
343         if (!hs_type) {
344                 cf_log_err(cf_sectiontoitem(cs),
345                            "Fatal error!  Home server %s has no type defined!",
346                            name2);
347                 free(home);
348                 free(hs_type);
349                 hs_type = NULL;
350                 free(hs_check);
351                 hs_check = NULL;
352                 return 0;
353         }
354
355         if (strcasecmp(hs_type, "auth") == 0) {
356                 home->type = HOME_TYPE_AUTH;
357                 if (type != home->type) {
358                         cf_log_err(cf_sectiontoitem(cs),
359                                    "Server pool of \"acct\" servers cannot include home server %s of type \"auth\"",
360                                    name2);
361                         free(home);
362                         return 0;
363                 }
364
365         } else if (strcasecmp(hs_type, "acct") == 0) {
366                 home->type = HOME_TYPE_ACCT;
367                 if (type != home->type) {
368                         cf_log_err(cf_sectiontoitem(cs),
369                                    "Server pool of \"auth\" servers cannot include home server %s of type \"acct\"",
370                                    name2);
371                         free(home);
372                         return 0;
373                 }
374
375         } else if (strcasecmp(hs_type, "auth+acct") == 0) {
376                 home->type = HOME_TYPE_AUTH;
377                 dual = TRUE;
378
379         } else {
380                 cf_log_err(cf_sectiontoitem(cs),
381                            "Invalid type \"%s\" for home server %s.",
382                            hs_type, name2);
383                 free(home);
384                 free(hs_type);
385                 hs_type = NULL;
386                 free(hs_check);
387                 hs_check = NULL;
388                 return 0;
389         }
390         free(hs_type);
391         hs_type = NULL;
392
393         if (!home->secret) {
394                 cf_log_err(cf_sectiontoitem(cs),
395                            "No shared secret defined for home server %s.",
396                            name2);
397                 free(home);
398                 return 0;
399         }
400
401         if (!hs_check || (strcasecmp(hs_check, "none") == 0)) {
402                 home->ping_check = HOME_PING_CHECK_NONE;
403
404         } else if (strcasecmp(hs_check, "status-server") == 0) {
405                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
406
407         } else if (strcasecmp(hs_check, "request") == 0) {
408                 home->ping_check = HOME_PING_CHECK_REQUEST;
409
410         } else {
411                 cf_log_err(cf_sectiontoitem(cs),
412                            "Invalid ping_check \"%s\" for home server %s.",
413                            hs_check, name2);
414                 free(home);
415                 free(hs_check);
416                 hs_check = NULL;
417                 return 0;
418         }
419         free(hs_check);
420         hs_check = NULL;
421
422         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
423             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
424                 if (!home->ping_user_name) {
425                         cf_log_err(cf_sectiontoitem(cs), "You must supply a user name to enable ping checks");
426                         free(home);
427                         return 0;
428                 }
429
430                 if ((home->type == HOME_TYPE_AUTH) &&
431                     !home->ping_user_password) {
432                         cf_log_err(cf_sectiontoitem(cs), "You must supply a password to enable ping checks");
433                         free(home);
434                         return 0;
435                 }
436         }
437
438         if (rbtree_finddata(home_servers_byaddr, home)) {
439                 DEBUG2("Ignoring duplicate home server %s.", name2);
440                 return 1;
441         }
442
443         if (!rbtree_insert(home_servers_byname, home)) {
444                 cf_log_err(cf_sectiontoitem(cs),
445                            "Internal error adding home server %s.",
446                            name2);
447                 free(home);
448                 return 0;
449         }
450
451         if (!rbtree_insert(home_servers_byaddr, home)) {
452                 rbtree_deletebydata(home_servers_byname, home);
453                 cf_log_err(cf_sectiontoitem(cs),
454                            "Internal error adding home server %s.",
455                            name2);
456                 free(home);
457                 return 0;
458         }
459
460         if (home->response_window < 5) home->response_window = 5;
461         if (home->response_window > 60) home->response_window = 60;
462
463         if (home->max_outstanding < 8) home->max_outstanding = 8;
464         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
465
466         if (home->ping_interval < 6) home->ping_interval = 6;
467         if (home->ping_interval > 120) home->ping_interval = 120;
468
469         if (home->zombie_period < 20) home->zombie_period = 20;
470         if (home->zombie_period > 120) home->zombie_period = 120;
471
472         if (home->zombie_period < home->response_window) {
473                 home->zombie_period = home->response_window;
474         }
475
476         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
477         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
478
479         if (home->ping_timeout < 3) home->ping_timeout = 3;
480         if (home->ping_timeout > 10) home->ping_timeout = 10;
481
482         if (home->revive_interval < 60) home->revive_interval = 60;
483         if (home->revive_interval > 3600) home->revive_interval = 3600;
484
485         if (dual) {
486                 home_server *home2 = rad_malloc(sizeof(*home2));
487
488                 memcpy(home2, home, sizeof(*home2));
489
490                 home2->type = HOME_TYPE_ACCT;
491                 home2->port++;
492                 home2->ping_user_password = NULL;
493                 home2->cs = cs;
494
495                 if (!rbtree_insert(home_servers_byname, home2)) {
496                         cf_log_err(cf_sectiontoitem(cs),
497                                    "Internal error adding home server %s.",
498                                    name2);
499                         free(home2);
500                         return 0;
501                 }
502                 
503                 if (!rbtree_insert(home_servers_byaddr, home2)) {
504                         rbtree_deletebydata(home_servers_byname, home2);
505                         cf_log_err(cf_sectiontoitem(cs),
506                                    "Internal error adding home server %s.",
507                                    name2);
508                         free(home2);
509                         return 0;
510                 }
511         }
512
513         return 1;
514 }
515
516
517 static home_pool_t *server_pool_alloc(const char *name, home_pool_type_t type,
518                                       int server_type, int num_home_servers)
519 {
520         home_pool_t *pool;
521
522         pool = rad_malloc(sizeof(*pool) + (sizeof(pool->servers[0]) *
523                                            num_home_servers));
524         if (!pool) return NULL; /* just for pairanoia */
525         
526         memset(pool, 0, sizeof(*pool) + (sizeof(pool->servers[0]) *
527                                          num_home_servers));
528
529         pool->name = name;
530         pool->type = type;
531         pool->server_type = server_type;
532         pool->num_home_servers = num_home_servers;
533
534         return pool;
535 }
536
537
538 static int server_pool_add(realm_config_t *rc,
539                            CONF_SECTION *cs, int server_type, int do_print)
540 {
541         const char *name2;
542         home_pool_t *pool = NULL;
543         const char *value;
544         CONF_PAIR *cp;
545         int num_home_servers;
546
547         name2 = cf_section_name1(cs);
548         if (!name2 || ((strcasecmp(name2, "server_pool") != 0) &&
549                        (strcasecmp(name2, "home_server_pool") != 0))) {
550                 cf_log_err(cf_sectiontoitem(cs),
551                            "Section is not a home_server_pool.");
552                 return 0;
553         }
554
555         name2 = cf_section_name2(cs);
556         if (!name2) {
557                 cf_log_err(cf_sectiontoitem(cs),
558                            "Server pool section is missing a name.");
559                 return 0;
560         }
561
562         /*
563          *      Count the home servers and initalize them.
564          */
565         num_home_servers = 0;
566         for (cp = cf_pair_find(cs, "home_server");
567              cp != NULL;
568              cp = cf_pair_find_next(cs, cp, "home_server")) {
569                 home_server myhome, *home;
570                 CONF_SECTION *server_cs;
571
572                 num_home_servers++;
573
574                 value = cf_pair_value(cp);
575                 if (!value) {
576                         cf_log_err(cf_pairtoitem(cp),
577                                    "No value given for home_server.");
578                         return 0;;
579                 }
580
581                 myhome.name = value;
582                 myhome.type = server_type;
583                 home = rbtree_finddata(home_servers_byname, &myhome);
584                 if (home) continue;
585
586                 server_cs = cf_section_sub_find_name2(rc->cs,
587                                                       "home_server",
588                                                       value);
589                 if (!server_cs) {
590                         cf_log_err(cf_pairtoitem(cp),
591                                    "Unknown home_server \"%s\".",
592                                    value);
593                         return 0;
594                 }
595
596                 if (!home_server_add(server_cs, server_type)) {
597                         return 0;
598                 }
599
600                 home = rbtree_finddata(home_servers_byname, &myhome);
601                 if (!home) {
602                         radlog(L_ERR, "Internal sanity check failed %d",
603                                __LINE__);
604                         return 0;
605                 }
606         }
607
608         if (num_home_servers == 0) {
609                 cf_log_err(cf_sectiontoitem(cs),
610                            "No home servers defined in pool %s",
611                            name2);
612                 goto error;
613         }
614
615         pool = server_pool_alloc(name2, HOME_POOL_FAIL_OVER, server_type,
616                                  num_home_servers);
617         pool->cs = cs;
618
619         if (do_print) cf_log_info(cs, " home_server_pool %s {", name2);
620
621         cp = cf_pair_find(cs, "type");
622         if (cp) {
623                 static FR_NAME_NUMBER pool_types[] = {
624                         { "load-balance", HOME_POOL_LOAD_BALANCE },
625                         { "fail-over", HOME_POOL_FAIL_OVER },
626                         { "round_robin", HOME_POOL_LOAD_BALANCE },
627                         { "fail_over", HOME_POOL_FAIL_OVER },
628                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
629                         { "client-port-balance", HOME_POOL_CLIENT_PORT_BALANCE },
630                         { "keyed-balance", HOME_POOL_KEYED_BALANCE },
631                         { NULL, 0 }
632                 };
633
634                 value = cf_pair_value(cp);
635                 if (!value) {
636                         cf_log_err(cf_pairtoitem(cp),
637                                    "No value given for type.");
638                         goto error;
639                 }
640
641                 pool->type = fr_str2int(pool_types, value, 0);
642                 if (!pool->type) {
643                         cf_log_err(cf_pairtoitem(cp),
644                                    "Unknown type \"%s\".",
645                                    value);
646                         goto error;
647                 }
648
649                 if (do_print) cf_log_info(cs, "\ttype = %s", value);
650         }
651
652         cp = cf_pair_find(cs, "virtual_server");
653         if (cp) {
654                 pool->virtual_server = cf_pair_value(cp);
655                 if (do_print && pool->virtual_server) {
656                         cf_log_info(cs, "\tvirtual_server = %s", pool->virtual_server);
657                 }
658
659                 if (!cf_section_sub_find_name2(rc->cs, "server",
660                                                pool->virtual_server)) {
661                         cf_log_err(cf_pairtoitem(cp), "No such server %s",
662                                    pool->virtual_server);
663                         goto error;
664                 }
665
666         }
667
668         num_home_servers = 0;
669         for (cp = cf_pair_find(cs, "home_server");
670              cp != NULL;
671              cp = cf_pair_find_next(cs, cp, "home_server")) {
672                 home_server myhome, *home;
673
674                 value = cf_pair_value(cp);
675                 if (!value) {
676                         cf_log_err(cf_pairtoitem(cp),
677                                    "No value given for home_server.");
678                         goto error;
679                 }
680
681                 myhome.name = value;
682                 myhome.type = server_type;
683
684                 home = rbtree_finddata(home_servers_byname, &myhome);
685                 if (!home) {
686                         DEBUG2("Internal sanity check failed");
687                         goto error;
688                 }
689
690                 if (0) {
691                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
692                         continue;
693                 }
694
695                 if (do_print) cf_log_info(cs, "\thome_server = %s", home->name);
696                 pool->servers[num_home_servers++] = home;
697         } /* loop over home_server's */
698
699         if (!rbtree_insert(home_pools_byname, pool)) {
700                 rad_assert("Internal sanity check failed");
701                 goto error;
702         }
703
704         if (do_print) cf_log_info(cs, " }");
705
706         rad_assert(pool->server_type != 0);
707
708         return 1;
709
710  error:
711         if (do_print) cf_log_info(cs, " }");
712         free(pool);
713         return 0;
714 }
715
716
717 static int old_server_add(realm_config_t *rc, CONF_SECTION *cs,
718                           const char *realm,
719                           const char *name, const char *secret,
720                           home_pool_type_t ldflag, home_pool_t **pool_p,
721                           int type)
722 {
723         int i, insert_point, num_home_servers;
724         home_server myhome, *home;
725         home_pool_t mypool, *pool;
726         CONF_SECTION *subcs;
727
728         /*
729          *      LOCAL realms get sanity checked, and nothing else happens.
730          */
731         if (strcmp(name, "LOCAL") == 0) {
732                 if (*pool_p) {
733                         cf_log_err(cf_sectiontoitem(cs), "Realm \"%s\" cannot be both LOCAL and remote", name);
734                         return 0;
735                 }
736                 return 1;
737         }
738
739         mypool.name = realm;
740         mypool.server_type = type;
741         pool = rbtree_finddata(home_pools_byname, &mypool);
742         if (pool) {
743                 if (pool->type != ldflag) {
744                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent ldflag for server pool \"%s\"", name);
745                         return 0;
746                 }
747
748                 if (pool->server_type != type) {
749                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent home server type for server pool \"%s\"", name);
750                         return 0;
751                 }
752         }
753
754         myhome.name = name;
755         myhome.type = type;
756         home = rbtree_finddata(home_servers_byname, &myhome);
757         if (home) {
758                 if (strcmp(home->secret, secret) != 0) {
759                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent shared secret for home server \"%s\"", name);
760                         return 0;
761                 }
762
763                 if (home->type != type) {
764                         cf_log_err(cf_sectiontoitem(cs), "Inconsistent type for home server \"%s\"", name);
765                         return 0;
766                 }
767
768                 /*
769                  *      See if the home server is already listed
770                  *      in the pool.  If so, do nothing else.
771                  */
772                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
773                         if (pool->servers[i] == home) {
774                                 return 1;
775                         }
776                 }
777         }
778
779         /*
780          *      If we do have a pool, check that there is room to
781          *      insert the home server we've found, or the one that we
782          *      create here.
783          *
784          *      Note that we insert it into the LAST available
785          *      position, in order to maintain the same order as in
786          *      the configuration files.
787          */
788         insert_point = -1;
789         if (pool) {
790                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
791                         if (pool->servers[i]) break;
792
793                         if (!pool->servers[i]) {
794                                 insert_point = i;
795                         }
796                 }
797
798                 if (insert_point < 0) {
799                         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);
800                         return 0;
801                 }
802         }
803
804         /*
805          *      No home server, allocate one.
806          */
807         if (!home) {
808                 const char *p;
809                 char *q;
810
811                 home = rad_malloc(sizeof(*home));
812                 memset(home, 0, sizeof(*home));
813
814                 home->name = name;
815                 home->hostname = name;
816                 home->type = type;
817                 home->secret = secret;
818                 home->cs = cs;
819
820                 p = strchr(name, ':');
821                 if (!p) {
822                         if (type == HOME_TYPE_AUTH) {
823                                 home->port = PW_AUTH_UDP_PORT;
824                         } else {
825                                 home->port = PW_ACCT_UDP_PORT;
826                         }
827
828                         p = name;
829                         q = NULL;
830
831                 } else if (p == name) {
832                                 cf_log_err(cf_sectiontoitem(cs),
833                                            "Invalid hostname %s.",
834                                            name);
835                                 free(home);
836                                 return 0;
837
838                 } else {
839                         home->port = atoi(p + 1);
840                         if ((home->port == 0) || (home->port > 65535)) {
841                                 cf_log_err(cf_sectiontoitem(cs),
842                                            "Invalid port %s.",
843                                            p + 1);
844                                 free(home);
845                                 return 0;
846                         }
847
848                         q = rad_malloc((p - name) + 1);
849                         memcpy(q, name, (p - name));
850                         q[p - name] = '\0';
851                         p = q;
852                 }
853
854                 if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
855                         cf_log_err(cf_sectiontoitem(cs),
856                                    "Failed looking up hostname %s.",
857                                    p);
858                         free(home);
859                         free(q);
860                         return 0;
861                 }
862                 free(q);
863
864                 /*
865                  *      Use the old-style configuration.
866                  */
867                 home->max_outstanding = 65535*16;
868                 home->zombie_period = rc->retry_delay * rc->retry_count;
869                 if (home->zombie_period == 0) home->zombie_period =30;
870                 home->response_window = home->zombie_period - 1;
871
872                 home->ping_check = HOME_PING_CHECK_NONE;
873
874                 home->revive_interval = rc->dead_time;
875
876                 if (rbtree_finddata(home_servers_byaddr, home)) {
877                         cf_log_err(cf_sectiontoitem(cs), "Home server %s has the same IP address and/or port as another home server.", name);
878                         free(home);
879                         return 0;
880                 }
881
882                 if (!rbtree_insert(home_servers_byname, home)) {
883                         cf_log_err(cf_sectiontoitem(cs), "Internal error adding home server %s.", name);
884                         free(home);
885                         return 0;
886                 }
887
888                 if (!rbtree_insert(home_servers_byaddr, home)) {
889                         rbtree_deletebydata(home_servers_byname, home);
890                         cf_log_err(cf_sectiontoitem(cs), "Internal error adding home server %s.", name);
891                         free(home);
892                         return 0;
893                 }
894         }
895
896         /*
897          *      We now have a home server, see if we can insert it
898          *      into pre-existing pool.
899          */
900         if (insert_point >= 0) {
901                 rad_assert(pool != NULL);
902                 pool->servers[insert_point] = home;
903                 return 1;
904         }
905
906         rad_assert(pool == NULL);
907         rad_assert(home != NULL);
908
909         /*
910          *      Count the old-style realms of this name.
911          */
912         num_home_servers = 0;
913         for (subcs = cf_section_find_next(cs, NULL, "realm");
914              subcs != NULL;
915              subcs = cf_section_find_next(cs, subcs, "realm")) {
916                 const char *this = cf_section_name2(subcs);
917
918                 if (!this || (strcmp(this, realm) != 0)) continue;
919                 num_home_servers++;
920         }
921
922         if (num_home_servers == 0) {
923                 cf_log_err(cf_sectiontoitem(cs), "Internal error counting pools for home server %s.", name);
924                 free(home);
925                 return 0;
926         }
927
928         pool = server_pool_alloc(realm, ldflag, type, num_home_servers);
929         pool->cs = cs;
930
931         pool->servers[0] = home;
932
933         if (!rbtree_insert(home_pools_byname, pool)) {
934                 rad_assert("Internal sanity check failed");
935                 return 0;
936         }
937
938         *pool_p = pool;
939
940         return 1;
941 }
942
943 static int old_realm_config(realm_config_t *rc, CONF_SECTION *cs, REALM *r)
944 {
945         const char *host;
946         const char *secret = NULL;
947         home_pool_type_t ldflag;
948         CONF_PAIR *cp;
949
950         cp = cf_pair_find(cs, "ldflag");
951         ldflag = HOME_POOL_FAIL_OVER;
952         if (cp) {
953                 host = cf_pair_value(cp);
954                 if (!host) {
955                         cf_log_err(cf_pairtoitem(cp), "No value specified for ldflag");
956                         return 0;
957                 }
958
959                 if (strcasecmp(host, "fail_over") == 0) {
960                         cf_log_info(cs, "\tldflag = fail_over");
961                         
962                 } else if (strcasecmp(host, "round_robin") == 0) {
963                         ldflag = HOME_POOL_LOAD_BALANCE;
964                         cf_log_info(cs, "\tldflag = round_robin");
965                         
966                 } else {
967                         cf_log_err(cf_sectiontoitem(cs), "Unknown value \"%s\" for ldflag", host);
968                         return 0;
969                 }
970         } /* else don't print it. */
971
972         /*
973          *      Allow old-style if it doesn't exist, or if it exists and
974          *      it's LOCAL.
975          */
976         cp = cf_pair_find(cs, "authhost");
977         if (cp) {
978                 host = cf_pair_value(cp);
979                 if (!host) {
980                         cf_log_err(cf_pairtoitem(cp), "No value specified for authhost");
981                         return 0;
982                 }
983
984                 if (strcmp(host, "LOCAL") != 0) {
985                         cp = cf_pair_find(cs, "secret");
986                         if (!cp) {
987                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
988                                 return 0;
989                         }
990
991                         secret = cf_pair_value(cp);
992                         if (!secret) {
993                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
994                                 return 0;
995                         }
996                 }
997                         
998                 cf_log_info(cs, "\tauthhost = %s",  host);
999
1000                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1001                                     &r->auth_pool, HOME_TYPE_AUTH)) {
1002                         return 0;
1003                 }
1004         }
1005
1006         cp = cf_pair_find(cs, "accthost");
1007         if (cp) {
1008                 host = cf_pair_value(cp);
1009                 if (!host) {
1010                         cf_log_err(cf_pairtoitem(cp), "No value specified for accthost");
1011                         return 0;
1012                 }
1013
1014                 /*
1015                  *      Don't look for a secret again if it was found
1016                  *      above.
1017                  */
1018                 if ((strcmp(host, "LOCAL") != 0) && !secret) {
1019                         cp = cf_pair_find(cs, "secret");
1020                         if (!cp) {
1021                                 cf_log_err(cf_sectiontoitem(cs), "No shared secret supplied for realm: %s", r->name);
1022                                 return 0;
1023                         }
1024                         
1025                         secret = cf_pair_value(cp);
1026                         if (!secret) {
1027                                 cf_log_err(cf_pairtoitem(cp), "No value specified for secret");
1028                                 return 0;
1029                         }
1030                 }
1031                 
1032                 cf_log_info(cs, "\taccthost = %s", host);
1033
1034                 if (!old_server_add(rc, cs, r->name, host, secret, ldflag,
1035                                     &r->acct_pool, HOME_TYPE_ACCT)) {
1036                         return 0;
1037                 }
1038         }
1039
1040         if (secret) cf_log_info(cs, "\tsecret = %s", secret);
1041
1042         return 1;
1043
1044 }
1045
1046
1047 static int add_pool_to_realm(realm_config_t *rc, CONF_SECTION *cs,
1048                              const char *name, home_pool_t **dest,
1049                              int server_type, int do_print)
1050 {
1051         home_pool_t mypool, *pool;
1052
1053         mypool.name = name;
1054         mypool.server_type = server_type;
1055
1056         pool = rbtree_finddata(home_pools_byname, &mypool);
1057         if (!pool) {
1058                 CONF_SECTION *pool_cs;
1059
1060                 pool_cs = cf_section_sub_find_name2(rc->cs,
1061                                                     "home_server_pool",
1062                                                     name);
1063                 if (!pool_cs) {
1064                         pool_cs = cf_section_sub_find_name2(rc->cs,
1065                                                             "server_pool",
1066                                                             name);
1067                 }
1068                 if (!pool_cs) {
1069                         cf_log_err(cf_sectiontoitem(cs), "Failed to find home_server_pool \"%s\"", name);
1070                         return 0;
1071                 }
1072
1073                 if (!server_pool_add(rc, pool_cs, server_type, do_print)) {
1074                         return 0;
1075                 }
1076
1077                 pool = rbtree_finddata(home_pools_byname, &mypool);
1078                 if (!pool) {
1079                         radlog(L_ERR, "Internal sanity check failed in add_pool_to_realm");
1080                         return 0;
1081                 }
1082         }
1083
1084         if (pool->server_type != server_type) {
1085                 cf_log_err(cf_sectiontoitem(cs), "Incompatible home_server_pool \"%s\" (mixed auth_pool / acct_pool)", name);
1086                 return 0;
1087         }
1088
1089         *dest = pool;
1090
1091         return 1;
1092 }
1093
1094 static int realm_add(realm_config_t *rc, CONF_SECTION *cs)
1095 {
1096         const char *name2;
1097         REALM *r = NULL;
1098         CONF_PAIR *cp;
1099         home_pool_t *auth_pool, *acct_pool;
1100         const char *auth_pool_name, *acct_pool_name;
1101
1102         name2 = cf_section_name1(cs);
1103         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
1104                 cf_log_err(cf_sectiontoitem(cs), "Section is not a realm.");
1105                 return 0;
1106         }
1107
1108         name2 = cf_section_name2(cs);
1109         if (!name2) {
1110                 cf_log_err(cf_sectiontoitem(cs), "Realm section is missing the realm name.");
1111                 return 0;
1112         }
1113
1114         auth_pool = acct_pool = NULL;
1115         auth_pool_name = acct_pool_name = NULL;
1116
1117         /*
1118          *      Prefer new configuration to old one.
1119          */
1120         cp = cf_pair_find(cs, "pool");
1121         if (cp) auth_pool_name = cf_pair_value(cp);
1122         if (cp && auth_pool_name) {
1123                 acct_pool_name = auth_pool_name;
1124                 if (!add_pool_to_realm(rc, cs,
1125                                        auth_pool_name, &auth_pool,
1126                                        HOME_TYPE_AUTH, 1)) {
1127                         return 0;
1128                 }
1129                 if (!add_pool_to_realm(rc, cs,
1130                                        auth_pool_name, &acct_pool,
1131                                        HOME_TYPE_ACCT, 0)) {
1132                         return 0;
1133                 }
1134         }
1135
1136         cp = cf_pair_find(cs, "auth_pool");
1137         if (cp) auth_pool_name = cf_pair_value(cp);
1138         if (cp && auth_pool_name) {
1139                 if (auth_pool) {
1140                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"auth_pool\" at the same time.");
1141                         return 0;
1142                 }
1143                 if (!add_pool_to_realm(rc, cs,
1144                                        auth_pool_name, &auth_pool,
1145                                        HOME_TYPE_AUTH, 1)) {
1146                         return 0;
1147                 }
1148         }
1149
1150         cp = cf_pair_find(cs, "acct_pool");
1151         if (cp) acct_pool_name = cf_pair_value(cp);
1152         if (cp && acct_pool_name) {
1153                 int do_print = TRUE;
1154
1155                 if (acct_pool) {
1156                         cf_log_err(cf_sectiontoitem(cs), "Cannot use \"pool\" and \"acct_pool\" at the same time.");
1157                         return 0;
1158                 }
1159
1160                 if (!auth_pool ||
1161                     (strcmp(auth_pool_name, acct_pool_name) != 0)) {
1162                         do_print = TRUE;
1163                 }
1164
1165                 if (!add_pool_to_realm(rc, cs,
1166                                        acct_pool_name, &acct_pool,
1167                                        HOME_TYPE_ACCT, do_print)) {
1168                         return 0;
1169                 }
1170         }
1171
1172         cf_log_info(cs, " realm %s {", name2);
1173
1174         /*
1175          *      The realm MAY already exist if it's an old-style realm.
1176          *      In that case, merge the old-style realm with this one.
1177          */
1178         r = realm_find(name2);
1179         if (r) {
1180                 if (cf_pair_find(cs, "auth_pool") ||
1181                     cf_pair_find(cs, "acct_pool")) {
1182                         cf_log_err(cf_sectiontoitem(cs), "Duplicate realm \"%s\"", name2);
1183                         goto error;
1184                 }
1185
1186                 if (!old_realm_config(rc, cs, r)) {
1187                         goto error;
1188                 }
1189
1190                 cf_log_info(cs, " } # realm %s", name2);
1191                 return 1;
1192         }
1193
1194         r = rad_malloc(sizeof(*r));
1195         memset(r, 0, sizeof(*r));
1196
1197         r->name = name2;
1198         r->auth_pool = auth_pool;
1199         r->acct_pool = acct_pool;
1200         r->striprealm = 1;
1201
1202         if (auth_pool_name &&
1203             (auth_pool_name == acct_pool_name)) { /* yes, ptr comparison */
1204                 cf_log_info(cs, "\tpool = %s", auth_pool_name);
1205         } else {
1206                 if (auth_pool_name) cf_log_info(cs, "\tauth_pool = %s", auth_pool_name);
1207                 if (acct_pool_name) cf_log_info(cs, "\tacct_pool = %s", acct_pool_name);
1208         }
1209
1210         cp = cf_pair_find(cs, "nostrip");
1211         if (cp && (cf_pair_value(cp) == NULL)) {
1212                 r->striprealm = 0;
1213                 cf_log_info(cs, "\tnostrip");
1214         }
1215
1216         /*
1217          *      We're a new-style realm.  Complain if we see the old
1218          *      directives.
1219          */
1220         if (r->auth_pool || r->acct_pool) {
1221                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
1222                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
1223                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
1224                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
1225                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
1226                 }
1227
1228
1229                 /*
1230                  *      The realm MAY be an old-style realm, as there
1231                  *      was no auth_pool or acct_pool.  Double-check
1232                  *      it, just to be safe.
1233                  */
1234         } else if (!old_realm_config(rc, cs, r)) {
1235                 goto error;
1236         }
1237
1238         if (!rbtree_insert(realms_byname, r)) {
1239                 rad_assert("Internal sanity check failed");
1240                 goto error;
1241         }
1242
1243         cf_log_info(cs, " }");
1244
1245         return 1;
1246
1247  error:
1248         cf_log_info(cs, " } # realm %s", name2);
1249         free(r);
1250         return 0;
1251 }
1252
1253
1254 int realms_init(CONF_SECTION *config)
1255 {
1256         CONF_SECTION *cs;
1257         realm_config_t *rc, *old_rc;
1258
1259         if (realms_byname) return 1;
1260
1261         realms_byname = rbtree_create(realm_name_cmp, free, 0);
1262         if (!realms_byname) {
1263                 realms_free();
1264                 return 0;
1265         }
1266
1267         home_servers_byaddr = rbtree_create(home_server_addr_cmp, free, 0);
1268         if (!home_servers_byaddr) {
1269                 realms_free();
1270                 return 0;
1271         }
1272
1273         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
1274         if (!home_servers_byname) {
1275                 realms_free();
1276                 return 0;
1277         }
1278
1279         home_pools_byname = rbtree_create(home_pool_name_cmp, free, 0);
1280         if (!home_pools_byname) {
1281                 realms_free();
1282                 return 0;
1283         }
1284
1285         rc = rad_malloc(sizeof(*rc));
1286         memset(rc, 0, sizeof(*rc));
1287         rc->cs = config;
1288
1289         cs = cf_subsection_find_next(config, NULL, "proxy");
1290         if (cs) {
1291                 cf_section_parse(cs, rc, proxy_config);
1292         } else {
1293                 rc->dead_time = DEAD_TIME;
1294                 rc->retry_count = RETRY_COUNT;
1295                 rc->retry_delay = RETRY_DELAY;
1296                 rc->fallback = 0;
1297                 rc->wake_all_if_all_dead= 0;
1298         }
1299
1300         for (cs = cf_subsection_find_next(config, NULL, "realm");
1301              cs != NULL;
1302              cs = cf_subsection_find_next(config, cs, "realm")) {
1303                 if (!realm_add(rc, cs)) {
1304                         free(rc);
1305                         realms_free();
1306                         return 0;
1307                 }
1308         }
1309
1310         xlat_register("home_server", xlat_home_server, NULL);
1311         xlat_register("home_server_pool", xlat_server_pool, NULL);
1312
1313         /*
1314          *      Swap pointers atomically.
1315          */
1316         old_rc = realm_config;
1317         realm_config = rc;
1318         free(old_rc);
1319
1320         return 1;
1321 }
1322
1323
1324 /*
1325  *      Find a realm in the REALM list.
1326  */
1327 REALM *realm_find(const char *name)
1328 {
1329         REALM myrealm;
1330
1331         if (!name) name = "NULL";
1332
1333         myrealm.name = name;
1334         return rbtree_finddata(realms_byname, &myrealm);
1335 }
1336
1337
1338 home_server *home_server_ldb(const char *realmname,
1339                              home_pool_t *pool, REQUEST *request)
1340 {
1341         int             start;
1342         int             count;
1343         home_server     *found = NULL;
1344         VALUE_PAIR      *vp;
1345
1346         start = 0;
1347
1348         /*
1349          *      Determine how to pick choose the home server.
1350          */
1351         switch (pool->type) {
1352                 uint32_t hash;
1353
1354                 /*
1355                  *      For load-balancing by client IP address, we
1356                  *      pick a home server by hashing the client IP.
1357                  *
1358                  *      This isn't as even a load distribution as
1359                  *      tracking the State attribute, but it's better
1360                  *      than nothing.
1361                  */
1362         case HOME_POOL_CLIENT_BALANCE:
1363                 switch (request->packet->src_ipaddr.af) {
1364                 case AF_INET:
1365                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1366                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1367                         break;
1368                 case AF_INET6:
1369                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1370                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1371                         break;
1372                 default:
1373                         hash = 0;
1374                         break;
1375                 }
1376                 start = hash % pool->num_home_servers;
1377                 break;
1378
1379         case HOME_POOL_CLIENT_PORT_BALANCE:
1380                 switch (request->packet->src_ipaddr.af) {
1381                 case AF_INET:
1382                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1383                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1384                         break;
1385                 case AF_INET6:
1386                         hash = fr_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1387                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1388                         break;
1389                 default:
1390                         hash = 0;
1391                         break;
1392                 }
1393                 fr_hash_update(&request->packet->src_port,
1394                                  sizeof(request->packet->src_port), hash);
1395                 start = hash % pool->num_home_servers;
1396                 break;
1397
1398         case HOME_POOL_KEYED_BALANCE:
1399                 if ((vp = pairfind(request->config_items, PW_LOAD_BALANCE_KEY)) != NULL) {
1400                         hash = fr_hash(vp->vp_strvalue, vp->length);
1401                         start = hash % pool->num_home_servers;
1402                         break;
1403                 }
1404                 /* FALL-THROUGH */
1405                                 
1406         case HOME_POOL_LOAD_BALANCE:
1407                 found = pool->servers[0];
1408
1409         default:
1410                 start = 0;
1411                 break;
1412         }
1413
1414         /*
1415          *      Starting with the home server we chose, loop through
1416          *      all home servers.  If the current one is dead, skip
1417          *      it.  If it is too busy, skip it.
1418          *
1419          *      Otherwise, use it.
1420          */
1421         for (count = 0; count < pool->num_home_servers; count++) {
1422                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
1423
1424                 if (home->state == HOME_STATE_IS_DEAD) {
1425                         continue;
1426                 }
1427
1428                 /*
1429                  *      This home server is too busy.  Choose another one.
1430                  */
1431                 if (home->currently_outstanding >= home->max_outstanding) {
1432                         continue;
1433                 }
1434
1435                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
1436                         return home;
1437                 }
1438
1439                 DEBUG3("PROXY %s %d\t%s %d",
1440                        found->name, found->currently_outstanding,
1441                        home->name, home->currently_outstanding);
1442
1443                 /*
1444                  *      Prefer this server if it's less busy than the
1445                  *      one we previously found.
1446                  */
1447                 if (home->currently_outstanding < found->currently_outstanding) {
1448                         DEBUG3("Choosing %s: It's less busy than %s",
1449                                home->name, found->name);
1450                         found = home;
1451                         continue;
1452                 }
1453
1454                 /*
1455                  *      Ignore servers which are busier than the one
1456                  *      we found.
1457                  */
1458                 if (home->currently_outstanding > found->currently_outstanding) {
1459                         DEBUG3("Skipping %s: It's busier than %s",
1460                                home->name, found->name);
1461                         continue;
1462                 }
1463
1464                 if (home->total_requests_sent < found->total_requests_sent) {
1465                         DEBUG3("Choosing %s: It's been less busy than %s",
1466                                home->name, found->name);
1467                         found = home;
1468                         continue;
1469                 }
1470
1471                 if (home->total_requests_sent > found->total_requests_sent) {
1472                         DEBUG3("Skipping %s: It's been busier than %s",
1473                                home->name, found->name);
1474                         continue;
1475                 }
1476
1477                 /*
1478                  *      From the list of servers which have the same
1479                  *      load, choose one at random.
1480                  */
1481                 if (((count + 1) * (fr_rand() & 0xffff)) < (uint32_t) 0x10000) {
1482                         found = home;
1483                 }
1484
1485         } /* loop over the home servers */
1486
1487         if (found) return found;
1488
1489         /*
1490          *      No live match found, and no fallback to the "DEFAULT"
1491          *      realm.  We fix this by blindly marking all servers as
1492          *      "live".  But only do it for ones that don't support
1493          *      "pings", as they will be marked live when they
1494          *      actually are live.
1495          */
1496         if (!realm_config->fallback &&
1497             realm_config->wake_all_if_all_dead) {
1498                 home_server *lb = NULL;
1499
1500                 for (count = 0; count < pool->num_home_servers; count++) {
1501                         home_server *home = pool->servers[count];
1502
1503                         if ((home->state == HOME_STATE_IS_DEAD) &&
1504                             (home->ping_check == HOME_PING_CHECK_NONE)) {
1505                                 home->state = HOME_STATE_ALIVE;
1506                                 if (!lb) lb = home;
1507                         }
1508                 }
1509
1510                 if (lb) return lb;
1511         }
1512
1513         /*
1514          *      Still nothing.  Look up the DEFAULT realm, but only
1515          *      if we weren't looking up the NULL or DEFAULT realms.
1516          */
1517         if (realm_config->fallback &&
1518             realmname &&
1519             (strcmp(realmname, "NULL") != 0) &&
1520             (strcmp(realmname, "DEFAULT") != 0)) {
1521                 REALM *rd = realm_find("DEFAULT");
1522
1523                 if (!rd) return NULL;
1524
1525                 pool = NULL;
1526                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1527                         pool = rd->auth_pool;
1528
1529                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1530                         pool = rd->acct_pool;
1531                 }
1532                 if (!pool) return NULL;
1533
1534                 DEBUG2("  Realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
1535                 return home_server_ldb(rd->name, pool, request);
1536         }
1537
1538         /*
1539          *      Still haven't found anything.  Oh well.
1540          */
1541         return NULL;
1542 }
1543
1544
1545 home_server *home_server_find(fr_ipaddr_t *ipaddr, int port)
1546 {
1547         home_server myhome;
1548
1549         myhome.ipaddr = *ipaddr;
1550         myhome.port = port;
1551
1552         return rbtree_finddata(home_servers_byaddr, &myhome);
1553 }