Use "currently_outstanding" metric for load-balance. i.e. we choose
[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 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24
25 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/rad_assert.h>
30
31 #include <sys/stat.h>
32
33 #include <ctype.h>
34 #include <fcntl.h>
35
36 static rbtree_t *realms_byname = NULL;
37
38 static rbtree_t *home_servers_byaddr = NULL;
39 static rbtree_t *home_servers_byname = NULL;
40
41 static rbtree_t *home_pools_byname = NULL;
42
43 static int realm_name_cmp(const void *one, const void *two)
44 {
45         const REALM *a = one;
46         const REALM *b = two;
47
48         return strcasecmp(a->name, b->name);
49 }
50
51
52 static int home_server_name_cmp(const void *one, const void *two)
53 {
54         const home_server *a = one;
55         const home_server *b = two;
56
57         return strcasecmp(a->name, b->name);
58 }
59
60 static int home_server_addr_cmp(const void *one, const void *two)
61 {
62         const home_server *a = one;
63         const home_server *b = two;
64
65         if (a->port < b->port) return -1;
66         if (a->port > b->port) return +1;
67
68         return lrad_ipaddr_cmp(&a->ipaddr, &b->ipaddr);
69 }
70
71
72 static int home_pool_name_cmp(const void *one, const void *two)
73 {
74         const home_pool_t *a = one;
75         const home_pool_t *b = two;
76
77         return strcasecmp(a->name, b->name);
78 }
79
80
81 void realms_free(void)
82 {
83         rbtree_free(home_servers_byname);
84         home_servers_byname = NULL;
85
86         rbtree_free(home_servers_byaddr);
87         home_servers_byaddr = NULL;
88
89         rbtree_free(home_pools_byname);
90         home_pools_byname = NULL;
91
92         rbtree_free(realms_byname);
93         realms_byname = NULL;
94 }
95
96
97 int realms_init(const char *filename)
98 {
99         CONF_SECTION *cs;
100
101         if (realms_byname) return 1;
102
103         realms_byname = rbtree_create(realm_name_cmp, free, 0);
104         if (!realms_byname) {
105                 realms_free();
106                 return 0;
107         }
108
109         home_servers_byaddr = rbtree_create(home_server_addr_cmp, free, 0);
110         if (!home_servers_byaddr) {
111                 realms_free();
112                 return 0;
113         }
114
115         home_servers_byname = rbtree_create(home_server_name_cmp, NULL, 0);
116         if (!home_servers_byname) {
117                 realms_free();
118                 return 0;
119         }
120
121         home_pools_byname = rbtree_create(home_pool_name_cmp, free, 0);
122         if (!home_pools_byname) {
123                 realms_free();
124                 return 0;
125         }
126
127         for (cs = cf_subsection_find_next(mainconfig.config, NULL, "realm");
128              cs != NULL;
129              cs = cf_subsection_find_next(mainconfig.config, cs, "realm")) {
130                 if (!realm_add(filename, cs)) {
131                         realms_free();
132                         return 0;
133                 }
134         }
135
136         return 1;
137 }
138
139 static struct in_addr hs_ip4addr;
140 static struct in6_addr hs_ip6addr;
141 static char *hs_type = NULL;
142 static char *hs_check = NULL;
143
144 static CONF_PARSER home_server_config[] = {
145         { "ipaddr",  PW_TYPE_IPADDR,
146           0, &hs_ip4addr,  NULL },
147         { "ipv6addr",  PW_TYPE_IPV6ADDR,
148           0, &hs_ip6addr, NULL },
149
150         { "hostname",  PW_TYPE_STRING_PTR,
151           offsetof(home_server,hostname), NULL,  NULL},
152         { "port", PW_TYPE_INTEGER,
153           offsetof(home_server,port), NULL,   "0" },
154
155         { "type",  PW_TYPE_STRING_PTR,
156           0, &hs_type, NULL },
157
158         { "secret",  PW_TYPE_STRING_PTR,
159           offsetof(home_server,secret), NULL,  NULL},
160
161         { "response_window", PW_TYPE_INTEGER,
162           offsetof(home_server,response_window), NULL,   "30" },
163         { "max_outstanding", PW_TYPE_INTEGER,
164           offsetof(home_server,max_outstanding), NULL,   "65536" },
165
166         { "zombie_period", PW_TYPE_INTEGER,
167           offsetof(home_server,zombie_period), NULL,   "40" },
168         { "status_check", PW_TYPE_STRING_PTR,
169           0, &hs_check,   "none" },
170         { "ping_check", PW_TYPE_STRING_PTR,
171           0, &hs_check,   "none" },
172
173         { "ping_interval", PW_TYPE_INTEGER,
174           offsetof(home_server,ping_interval), NULL,   "30" },
175         { "check_interval", PW_TYPE_INTEGER,
176           offsetof(home_server,ping_interval), NULL,   "30" },
177         { "num_answers_to_alive", PW_TYPE_INTEGER,
178           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
179         { "num_pings_to_alive", PW_TYPE_INTEGER,
180           offsetof(home_server,num_pings_to_alive), NULL,   "3" },
181         { "revive_interval", PW_TYPE_INTEGER,
182           offsetof(home_server,revive_interval), NULL,   "300" },
183         { "status_check_timeout", PW_TYPE_INTEGER,
184           offsetof(home_server,ping_timeout), NULL,   "4" },
185
186         { "username",  PW_TYPE_STRING_PTR,
187           offsetof(home_server,ping_user_name), NULL,  NULL},
188         { "password",  PW_TYPE_STRING_PTR,
189           offsetof(home_server,ping_user_password), NULL,  NULL},
190         
191         { NULL, -1, 0, NULL, NULL }             /* end the list */
192
193 };
194
195
196 static int home_server_add(const char *filename, CONF_SECTION *cs)
197 {
198         const char *name2;
199         home_server *home;
200
201         name2 = cf_section_name1(cs);
202         if (!name2 || (strcasecmp(name2, "home_server") != 0)) {
203                 radlog(L_ERR, "%s[%d]: Section is not a home_server.",
204                        filename, cf_section_lineno(cs));
205                 return 0;
206         }
207
208         name2 = cf_section_name2(cs);
209         if (!name2) {
210                 radlog(L_ERR, "%s[%d]: Home server section is missing a name.",
211                        filename, cf_section_lineno(cs));
212                 return 0;
213         }
214
215         home = rad_malloc(sizeof(*home));
216         memset(home, 0, sizeof(*home));
217
218         home->name = name2;
219         
220         memset(&hs_ip4addr, 0, sizeof(hs_ip4addr));
221         memset(&hs_ip6addr, 0, sizeof(hs_ip6addr));
222         cf_section_parse(cs, home, home_server_config);
223
224         if (!home->hostname && (htonl(hs_ip4addr.s_addr) == INADDR_NONE) &&
225             IN6_IS_ADDR_UNSPECIFIED(&hs_ip6addr)) {
226                 radlog(L_ERR, "%s[%d]: No hostname, IPv4 address, or IPv6 address defined for home server %s.",
227                        filename, cf_section_lineno(cs), name2);
228                 free(home);
229                 free(hs_type);
230                 hs_type = NULL;
231                 free(hs_check);
232                 hs_check = NULL;
233                 return 0;
234         }
235
236         /*
237          *      FIXME: Parse home->hostname!
238          *
239          *      Right now, only ipaddr && ip6addr are used.
240          *      The old-style parsing still allows hostnames.
241          */
242         if (htonl(hs_ip4addr.s_addr) != INADDR_NONE) {
243                 home->ipaddr.af = AF_INET;
244                 home->ipaddr.ipaddr.ip4addr = hs_ip4addr;
245
246         } else if (!IN6_IS_ADDR_UNSPECIFIED(&hs_ip6addr)) {
247                 home->ipaddr.af = AF_INET6;
248                 home->ipaddr.ipaddr.ip6addr = hs_ip6addr;
249
250         } else {
251                 radlog(L_ERR, "%s[%d]: FIXME: parse hostname for home server %s.",
252                        filename, cf_section_lineno(cs), name2);
253                 free(home);
254                 free(hs_type);
255                 hs_type = NULL;
256                 free(hs_check);
257                 hs_check = NULL;
258                 return 0;
259         }
260
261         if (!home->port || (home->port > 65535)) {
262                 radlog(L_ERR, "%s[%d]: No port, or invalid port defined for home server %s.",
263                        filename, cf_section_lineno(cs), name2);
264                 free(home);
265                 free(hs_type);
266                 hs_type = NULL;
267                 free(hs_check);
268                 hs_check = NULL;
269                 return 0;
270         }
271
272         if (0) {
273                 radlog(L_ERR, "%s[%d]: Fatal error!  Home server %s is ourselves!",
274                        filename, cf_section_lineno(cs), name2);
275                 free(home);
276                 free(hs_type);
277                 hs_type = NULL;
278                 free(hs_check);
279                 hs_check = NULL;
280                 return 0;
281         }
282
283         if (strcasecmp(hs_type, "auth") == 0) {
284                 home->type = HOME_TYPE_AUTH;
285
286         } else if (strcasecmp(hs_type, "acct") == 0) {
287                 home->type = HOME_TYPE_ACCT;
288
289         } else {
290                 radlog(L_ERR, "%s[%d]: Invalid type \"%s\" for home server %s.",
291                        filename, cf_section_lineno(cs), hs_type, name2);
292                 free(home);
293                 free(hs_type);
294                 hs_type = NULL;
295                 free(hs_check);
296                 hs_check = NULL;
297                 return 0;
298         }
299         free(hs_type);
300         hs_type = NULL;
301
302         if (!home->secret) {
303                 radlog(L_ERR, "%s[%d]: No shared secret defined for home server %s.",
304                        filename, cf_section_lineno(cs), name2);
305                 free(home);
306                 return 0;
307         }
308
309         if (strcasecmp(hs_check, "none") == 0) {
310                 home->ping_check = HOME_PING_CHECK_NONE;
311
312         } else if (strcasecmp(hs_check, "status-server") == 0) {
313                 home->ping_check = HOME_PING_CHECK_STATUS_SERVER;
314
315         } else if (strcasecmp(hs_check, "request") == 0) {
316                 home->ping_check = HOME_PING_CHECK_REQUEST;
317
318         } else {
319                 radlog(L_ERR, "%s[%d]: Invalid ping_check \"%s\" for home server %s.",
320                        filename, cf_section_lineno(cs), hs_check, name2);
321                 free(home);
322                 free(hs_check);
323                 hs_check = NULL;
324                 return 0;
325         }
326         free(hs_check);
327         hs_check = NULL;
328
329         if ((home->ping_check != HOME_PING_CHECK_NONE) &&
330             (home->ping_check != HOME_PING_CHECK_STATUS_SERVER)) {
331                 if (!home->ping_user_name) {
332                         radlog(L_INFO, "%s[%d]: You must supply a user name to enable ping checks",
333                                filename, cf_section_lineno(cs));
334                         free(home);
335                         return 0;
336                 }
337
338                 if ((home->type == HOME_TYPE_AUTH) && 
339                     !home->ping_user_password) {        
340                         radlog(L_INFO, "%s[%d]: You must supply a password to enable ping checks",
341                                filename, cf_section_lineno(cs));
342                         free(home);
343                         return 0;
344                 }
345         }
346
347         if (rbtree_finddata(home_servers_byaddr, home)) {
348                 radlog(L_INFO, "%s[%d]: Ignoring duplicate home server %s.",
349                        filename, cf_section_lineno(cs), name2);
350                 return 1;
351         }
352
353         if (!rbtree_insert(home_servers_byname, home)) {
354                 radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
355                        filename, cf_section_lineno(cs), name2);
356                 free(home);
357                 return 0;
358         }
359
360         if (!rbtree_insert(home_servers_byaddr, home)) {
361                 rbtree_deletebydata(home_servers_byname, home);
362                 radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
363                        filename, cf_section_lineno(cs), name2);
364                 free(home);
365                 return 0;
366         }
367
368         if (home->response_window < 5) home->response_window = 5;
369         if (home->response_window > 60) home->response_window = 60;
370
371         if (home->max_outstanding < 8) home->max_outstanding = 8;
372         if (home->max_outstanding > 65536*16) home->max_outstanding = 65536*16;
373
374         if (home->ping_interval < 6) home->ping_interval = 6;
375         if (home->ping_interval > 120) home->ping_interval = 120;
376
377         if (home->zombie_period < 20) home->zombie_period = 20;
378         if (home->zombie_period > 120) home->zombie_period = 120;
379
380         if (home->zombie_period < home->response_window) {
381                 home->zombie_period = home->response_window;
382         }
383
384         if (home->num_pings_to_alive < 3) home->num_pings_to_alive = 3;
385         if (home->num_pings_to_alive > 10) home->num_pings_to_alive = 10;
386
387         if (home->ping_timeout < 3) home->ping_timeout = 3;
388         if (home->ping_timeout > 10) home->ping_timeout = 10;
389
390         if (home->revive_interval < 60) home->revive_interval = 60;
391         if (home->revive_interval > 3600) home->revive_interval = 3600;
392
393         return 1;
394 }
395
396
397 static int server_pool_add(const char *filename, CONF_SECTION *cs)
398 {
399         const char *name2;
400         home_pool_t *pool = NULL;
401         const char *value;
402         CONF_PAIR *cp;
403         int num_home_servers;
404
405         name2 = cf_section_name1(cs);
406         if (!name2 || (strcasecmp(name2, "server_pool") != 0)) {
407                 radlog(L_ERR, "%s[%d]: Section is not a server_pool.",
408                        filename, cf_section_lineno(cs));
409                 return 0;
410         }
411
412         name2 = cf_section_name2(cs);
413         if (!name2) {
414                 radlog(L_ERR, "%s[%d]: Server pool section is missing a name.",
415                        filename, cf_section_lineno(cs));
416                 return 0;
417         }
418
419         /*
420          *      Count the home servers and initalize them.
421          */
422         num_home_servers = 0;
423         for (cp = cf_pair_find(cs, "home_server");
424              cp != NULL;
425              cp = cf_pair_find_next(cs, cp, "home_server")) {
426                 home_server myhome, *home;
427                 CONF_SECTION *server_cs;
428
429                 num_home_servers++;
430
431                 value = cf_pair_value(cp);
432                 if (!value) {
433                         radlog(L_ERR, "%s[%d]: No value given for home_server.",
434                                filename, cf_pair_lineno(cp));
435                         return 0;;
436                 }
437
438                 myhome.name = value;
439                 home = rbtree_finddata(home_servers_byname, &myhome);
440                 if (home) continue;
441
442                 server_cs = cf_section_sub_find_name2(NULL,
443                                                       "home_server",
444                                                       value);
445                 if (!server_cs) {
446                         radlog(L_ERR, "%s[%d]: Unknown home_server \"%s\".",
447                                filename, cf_pair_lineno(cp), value);
448                         return 0;
449                 }
450                         
451                 if (!home_server_add(filename, server_cs)) {
452                         return 0;
453                 }
454
455                 home = rbtree_finddata(home_servers_byname, &myhome);
456                 if (!home) {
457                         rad_assert("Internal sanity check failed");
458                         return 0;
459                 }
460         }
461
462         if (num_home_servers == 0) {
463                 radlog(L_ERR, "%s[%d]: No home servers defined in pool %s",
464                        filename, cf_section_lineno(cs), name2);
465                 goto error;
466         }
467
468         pool = rad_malloc(sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
469         memset(pool, 0, sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
470
471         pool->type = HOME_POOL_FAIL_OVER;
472         pool->name = name2;
473
474         DEBUG2(" server_pool %s {", name2);
475
476         cp = cf_pair_find(cs, "type");
477         if (cp) {
478                 static LRAD_NAME_NUMBER pool_types[] = {
479                         { "load-balance", HOME_POOL_LOAD_BALANCE },
480                         { "fail-over", HOME_POOL_FAIL_OVER },
481                         { "round_robin", HOME_POOL_LOAD_BALANCE },
482                         { "fail_over", HOME_POOL_FAIL_OVER },
483                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
484                         { NULL, 0 }
485                 };
486
487                 value = cf_pair_value(cp);
488                 if (!value) {
489                         radlog(L_ERR, "%s[%d]: No value given for type.",
490                                filename, cf_pair_lineno(cp));
491                         goto error;
492                 }
493
494                 pool->type = lrad_str2int(pool_types, value, 0);
495                 if (!pool->type) {
496                         radlog(L_ERR, "%s[%d]: Unknown type \"%s\".",
497                                filename, cf_pair_lineno(cp), value);
498                         goto error;
499                 }
500
501                 DEBUG2("\ttype = %s", name2, value);
502         }
503
504         for (cp = cf_pair_find(cs, "home_server");
505              cp != NULL;
506              cp = cf_pair_find_next(cs, cp, "home_server")) {
507                 home_server myhome, *home;
508
509                 value = cf_pair_value(cp);
510                 if (!value) {
511                         radlog(L_ERR, "%s[%d]: No value given for home_server.",
512                                filename, cf_pair_lineno(cp));
513                         goto error;
514                 }
515
516                 myhome.name = value;
517
518                 home = rbtree_finddata(home_servers_byname, &myhome);
519                 if (!home) {
520                         DEBUG2("Internal sanity check failed");
521                         goto error;
522                 }
523
524                 if (!pool->server_type) {
525                         rad_assert(home->type != 0);
526                         pool->server_type = home->type;
527
528                 } else if (pool->server_type != home->type) {
529                         radlog(L_ERR, "%s[%d]: Home server \"%s\" is not of the same type as previous servers in server pool %s",
530                                filename, cf_pair_lineno(cp), value, pool->name);
531                         goto error;
532                 }
533
534                 if (0) {
535                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
536                         continue;
537                 }
538
539                 DEBUG2("\thome_server = %s", home->name);
540                 pool->servers[pool->num_home_servers] = home;
541                 pool->num_home_servers++;
542         } /* loop over home_server's */
543
544         if (!rbtree_insert(home_pools_byname, pool)) {
545                 rad_assert("Internal sanity check failed");
546                 goto error;
547         }
548
549         DEBUG2(" }");
550
551         rad_assert(pool->server_type != 0);
552         
553         return 1;
554
555  error:
556         DEBUG2(" }");
557         free(pool);
558         return 0;
559 }
560
561
562 static int old_server_add(const char *filename, int lineno, const char *realm,
563                           const char *name, const char *secret,
564                           home_pool_type_t ldflag, home_pool_t **pool_p,
565                           int type)
566 {
567         int i, insert_point, num_home_servers;
568         home_server myhome, *home;
569         home_pool_t mypool, *pool;
570         CONF_SECTION *cs;
571
572         /*
573          *      LOCAL realms get sanity checked, and nothing else happens.
574          */
575         if (strcmp(name, "LOCAL") == 0) {
576                 if (*pool_p) {
577                         radlog(L_ERR, "%s[%d]: Realm \"%s\" cannot be both LOCAL and remote", filename, lineno, name);
578                         return 0;
579                 }
580                 return 1;
581         }
582
583         mypool.name = realm;
584         pool = rbtree_finddata(home_pools_byname, &mypool);
585         if (pool) {
586                 if (pool->type != ldflag) {
587                         radlog(L_ERR, "%s[%d]: Inconsistent ldflag for server pool \"%s\"", filename, lineno, name);
588                         return 0;
589                 }
590
591                 if (pool->server_type != type) {
592                         radlog(L_ERR, "%s[%d]: Inconsistent home server type for server pool \"%s\"", filename, lineno, name);
593                         return 0;
594                 }
595         }
596
597         myhome.name = name;
598         home = rbtree_finddata(home_servers_byname, &myhome);
599         if (home) {
600                 if (strcmp(home->secret, secret) != 0) {
601                         radlog(L_ERR, "%s[%d]: Inconsistent shared secret for home server \"%s\"", filename, lineno, name);
602                         return 0;
603                 }
604
605                 if (home->type != type) {
606                         radlog(L_ERR, "%s[%d]: Inconsistent type for home server \"%s\"", filename, lineno, name);
607                         return 0;
608                 }
609                 
610                 /*
611                  *      See if the home server is already listed
612                  *      in the pool.  If so, do nothing else.
613                  */
614                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
615                         if (pool->servers[i] == home) {
616                                 return 1;
617                         }
618                 }
619         }
620
621         /*
622          *      If we do have a pool, check that there is room to
623          *      insert the home server we've found, or the one that we
624          *      create here.
625          *
626          *      Note that we insert it into the LAST available
627          *      position, in order to maintain the same order as in
628          *      the configuration files.
629          */
630         insert_point = -1;
631         if (pool) {
632                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
633                         if (pool->servers[i]) break;
634
635                         if (!pool->servers[i]) {
636                                 insert_point = i;
637                         }
638                 }
639
640                 if (insert_point < 0) {
641                         radlog(L_ERR, "%s[%d]: No room in pool to add home server \"%s\".  Please update the realm configuration to use the new-style home servers and server pools.", filename, lineno, name);
642                         return 0;
643                 }
644         }
645
646         /*
647          *      No home server, allocate one.
648          */
649         if (!home) {         
650                 const char *p;
651                 char *q;
652
653                 home = rad_malloc(sizeof(*home));
654                 memset(home, 0, sizeof(*home));
655
656                 home->name = name;
657                 home->hostname = name;
658                 home->type = type;
659                 home->secret = secret;
660
661                 p = strchr(name, ':');
662                 if (!p) {
663                         if (type == HOME_TYPE_AUTH) {
664                                 home->port = PW_AUTH_UDP_PORT;
665                         } else {
666                                 home->port = PW_ACCT_UDP_PORT;
667                         }
668
669                         p = name;
670                         q = NULL;
671
672                 } else if (p == name) {
673                                 radlog(L_ERR, "%s[%d]: Invalid hostname %s.",
674                                        filename, lineno, name);
675                                 free(home);
676                                 return 0;
677
678                 } else {
679                         home->port = atoi(p + 1);
680                         if ((home->port == 0) || (home->port > 65535)) {
681                                 radlog(L_ERR, "%s[%d]: Invalid port %s.",
682                                        filename, lineno, p + 1);
683                                 free(home);
684                                 return 0;
685                         }
686
687                         q = rad_malloc((p - name) + 1);
688                         memcpy(q, name, (p - name));
689                         q[p - name] = '\0';
690                         p = q;
691                 }
692
693                 if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
694                         radlog(L_ERR, "%s[%d]: Failed looking up hostname %s.",
695                                filename, lineno, p);
696                         free(home);
697                         free(q);
698                         return 0;
699                 }
700                 free(q);
701
702                 /*
703                  *      Use the old-style configuration.
704                  */
705                 home->max_outstanding = 65535*16;
706                 home->zombie_period = mainconfig.proxy_retry_delay * mainconfig.proxy_retry_count;
707                 if (home->zombie_period == 0) home->zombie_period =30;
708                 home->response_window = home->zombie_period - 1;
709
710                 home->ping_check = HOME_PING_CHECK_NONE;
711
712                 home->revive_interval = mainconfig.proxy_dead_time;
713
714                 if (rbtree_finddata(home_servers_byaddr, home)) {
715                         radlog(L_ERR, "%s[%d]: Home server %s has the same IP address as another home server.",
716                                filename, lineno, name);
717                         free(home);
718                         return 0;
719                 }
720
721                 if (!rbtree_insert(home_servers_byname, home)) {
722                         radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
723                                filename, lineno, name);
724                         free(home);
725                         return 0;
726                 }
727                 
728                 if (!rbtree_insert(home_servers_byaddr, home)) {
729                         rbtree_deletebydata(home_servers_byname, home);
730                         radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
731                                filename, lineno, name);
732                         free(home);
733                         return 0;
734                 }
735         }
736
737         /*
738          *      We now have a home server, see if we can insert it
739          *      into pre-existing pool.
740          */
741         if (insert_point >= 0) {
742                 rad_assert(pool != NULL);
743                 pool->servers[insert_point] = home;
744                 return 1;
745         }
746
747         rad_assert(pool == NULL);
748         rad_assert(home != NULL);
749
750         /*
751          *      Count the old-style realms of this name.
752          */
753         num_home_servers = 0;
754         for (cs = cf_section_sub_find_name2(mainconfig.config, "realm", realm);
755              cs != NULL;
756              cs = cf_section_sub_find_name2(cs, "realm", realm)) {
757                 num_home_servers++;
758         }
759
760         pool = rad_malloc(sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
761         memset(pool, 0, sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
762
763         pool->name = realm;
764         pool->type = ldflag;
765         pool->server_type = type;
766         pool->num_home_servers = num_home_servers;
767         pool->servers[0] = home;
768
769         if (!rbtree_insert(home_pools_byname, pool)) {
770                 rad_assert("Internal sanity check failed");
771                 return 0;
772         }
773
774         *pool_p = pool;
775
776         return 1;
777 }
778
779 static int old_realm_config(const char *filename, CONF_SECTION *cs, REALM *r)
780 {
781         char *host;
782         const char *secret;
783         home_pool_type_t ldflag;
784
785         secret = cf_section_value_find(cs, "secret");
786
787         host = cf_section_value_find(cs, "ldflag");
788         if (!host ||
789             (strcasecmp(host, "fail_over") == 0)) {
790                 ldflag = HOME_POOL_FAIL_OVER;
791                 DEBUG2("\tldflag = fail_over");
792
793         } else if (strcasecmp(host, "round_robin") == 0) {
794                 ldflag = HOME_POOL_LOAD_BALANCE;
795                 DEBUG2("\tldflag = round_robin");
796
797         } else {
798                 radlog(L_ERR, "%s[%d]: Unknown value \"%s\" for ldflag",
799                        filename, cf_section_lineno(cs), host);
800                 return 0;
801         }
802
803         /*
804          *      Allow old-style if it doesn't exist, or if it exists and
805          *      it's LOCAL.
806          */
807         if (((host = cf_section_value_find(cs, "authhost")) != NULL) &&
808             (strcmp(host, "LOCAL") != 0)) {
809                 if (!secret) {
810                         radlog(L_ERR, "%s[%d]: No shared secret supplied for realm: %s",
811                                filename, cf_section_lineno(cs), r->name);
812                         return 0;
813                 }
814
815                 DEBUG2("\tauthhost = %s",  host);
816
817                 if (!old_server_add(filename, cf_section_lineno(cs),
818                                     r->name, host, secret, ldflag,
819                                     &r->auth_pool, HOME_TYPE_AUTH)) {
820                         return 0;
821                 }
822         }
823
824         if (((host = cf_section_value_find(cs, "accthost")) != NULL) &&
825             (strcmp(host, "LOCAL") != 0)) {
826                 if (!secret) {
827                         radlog(L_ERR, "%s[%d]: No shared secret supplied for realm: %s",
828                                filename, cf_section_lineno(cs), r->name);
829                         return 0;
830                 }
831
832                 DEBUG2("\taccthost = %s", host);
833
834                 if (!old_server_add(filename, cf_section_lineno(cs),
835                                     r->name, host, secret, ldflag,
836                                     &r->acct_pool, HOME_TYPE_ACCT)) {
837                         return 0;
838                 }
839         }
840
841         if (secret) DEBUG2("\tsecret = %s", secret);
842
843         return 1;
844         
845 }
846
847
848 static int add_pool_to_realm(const char *filename, int lineno,
849                              const char *name, home_pool_t **dest,
850                              int server_type)
851 {
852         home_pool_t mypool, *pool;
853
854         mypool.name = name;
855         pool = rbtree_finddata(home_pools_byname, &mypool);
856         if (!pool) {
857                 CONF_SECTION *pool_cs;
858
859                 pool_cs = cf_section_sub_find_name2(NULL, "server_pool",
860                                                     name);
861                 if (!pool_cs) {
862                         radlog(L_ERR, "%s[%d]: Failed to find server_pool \"%s\"",
863                                filename, lineno, name);
864                         return 0;
865                 }
866
867                 if (!server_pool_add(filename, pool_cs)) {
868                         return 0;
869                 }
870                 
871                 pool = rbtree_finddata(home_pools_byname, &mypool);
872                 if (!pool) {
873                         rad_assert("Internal sanity check failed");
874                         return 0;
875                 }
876         }
877
878         if (pool->server_type != server_type) {
879                 radlog(L_ERR, "%s[%d]: Incompatible server_pool \"%s\" (mixed auth_pool / acct_pool)",
880                        filename, lineno, name);
881                 return 0;
882         }
883
884         *dest = pool;
885
886         return 1;
887 }
888
889 int realm_add(const char *filename, CONF_SECTION *cs)
890 {
891         const char *name2;
892         REALM *r = NULL;
893         CONF_PAIR *cp;
894         home_pool_t *auth_pool, *acct_pool;
895         const char *auth_pool_name, *acct_pool_name;
896
897         name2 = cf_section_name1(cs);
898         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
899                 radlog(L_ERR, "%s[%d]: Section is not a realm.",
900                        filename, cf_section_lineno(cs));
901                 return 0;
902         }
903
904         name2 = cf_section_name2(cs);
905         if (!name2) {
906                 radlog(L_ERR, "%s[%d]: Realm section is missing the realm name.",
907                        filename, cf_section_lineno(cs));
908                 return 0;
909         }
910
911         auth_pool = acct_pool = NULL;
912         auth_pool_name = acct_pool_name = NULL;
913
914         /*
915          *      Prefer new configuration to old one.
916          */
917         cp = cf_pair_find(cs, "auth_pool");
918         if (cp) auth_pool_name = cf_pair_value(cp);
919         if (cp && auth_pool_name) {
920                 if (!add_pool_to_realm(filename, cf_pair_lineno(cp),
921                                        auth_pool_name, &auth_pool,
922                                        HOME_TYPE_AUTH)) {
923                         return 0;
924                 }
925         }
926
927         cp = cf_pair_find(cs, "acct_pool");
928         if (cp) acct_pool_name = cf_pair_value(cp);
929         if (cp && acct_pool_name) {
930                 if (!add_pool_to_realm(filename, cf_pair_lineno(cp),
931                                        acct_pool_name, &acct_pool,
932                                        HOME_TYPE_ACCT)) {
933                         return 0;
934                 }
935         }
936
937         DEBUG2(" realm %s {", name2);
938
939         /*
940          *      The realm MAY already exist if it's an old-style realm.
941          *      In that case, merge the old-style realm with this one.
942          */
943         r = realm_find(name2);
944         if (r) {
945                 if (cf_pair_find(cs, "auth_pool") ||
946                     cf_pair_find(cs, "acct_pool")) {
947                         radlog(L_ERR, "%s[%d]: Duplicate realm \"%s\"",
948                                filename, cf_section_lineno(cs), name2);
949                         goto error;
950                 }
951
952                 if (!old_realm_config(filename, cs, r)) {
953                         goto error;
954                 }
955
956                 DEBUG2(" } # realm %s", name2);
957                 return 1;
958         }
959
960         r = rad_malloc(sizeof(*r));
961         memset(r, 0, sizeof(*r));
962
963         r->name = name2;
964         r->auth_pool = auth_pool;
965         r->acct_pool = acct_pool;
966         r->striprealm = 1;
967
968         if (auth_pool_name) DEBUG2("\tauth_pool = %s", auth_pool_name);
969         if (acct_pool_name) DEBUG2("\tacct_pool = %s", acct_pool_name);
970         
971         if ((cf_section_value_find(cs, "nostrip")) != NULL) {
972                 r->striprealm = 0;
973                 DEBUG2("\tnostrip", name2);
974         }
975
976         /*
977          *      We're a new-style realm.  Complain if we see the old
978          *      directives.
979          */
980         if (r->auth_pool || r->acct_pool) {
981                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
982                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
983                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
984                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
985                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
986                 }
987
988
989                 /*
990                  *      The realm MAY be an old-style realm, as there
991                  *      was no auth_pool or acct_pool.  Double-check
992                  *      it, just to be safe.
993                  */
994         } else if (!old_realm_config(filename, cs, r)) {
995                 goto error;
996         }
997
998         if (!rbtree_insert(realms_byname, r)) {
999                 rad_assert("Internal sanity check failed");
1000                 goto error;
1001         }
1002
1003         DEBUG2(" }");
1004
1005         return 1;
1006
1007  error:
1008         DEBUG2(" } # realm %s", name2);
1009         free(r);
1010         return 0;
1011 }
1012
1013
1014 /*
1015  *      Find a realm in the REALM list.
1016  */
1017 REALM *realm_find(const char *name)
1018 {
1019         REALM myrealm;
1020
1021         if (!name) name = "NULL";
1022
1023         myrealm.name = name;
1024         return rbtree_finddata(realms_byname, &myrealm);
1025 }
1026
1027
1028 home_server *home_server_ldb(const char *realmname,
1029                              home_pool_t *pool, REQUEST *request)
1030 {
1031         int             start;
1032         int             count;
1033         home_server     *found = NULL;
1034
1035         start = 0;
1036
1037         /*
1038          *      Determine how to pick choose the home server.
1039          */
1040         switch (pool->type) {
1041                 uint32_t hash;
1042
1043                 /*
1044                  *      For load-balancing by client IP address, we
1045                  *      pick a home server by hashing the client IP.
1046                  *
1047                  *      This isn't as even a load distribution as
1048                  *      tracking the State attribute, but it's better
1049                  *      than nothing.
1050                  */
1051         case HOME_POOL_CLIENT_BALANCE:
1052                 switch (request->packet->src_ipaddr.af) {
1053                 case AF_INET:
1054                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1055                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1056                         break;
1057                 case AF_INET6:
1058                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1059                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1060                         break;
1061                 default:
1062                         hash = 0;
1063                         break;
1064                 }
1065                 start = hash % pool->num_home_servers;
1066                 break;
1067
1068         case HOME_POOL_LOAD_BALANCE:
1069                 found = pool->servers[0];
1070
1071         default:
1072                 start = 0;
1073                 break;
1074         }
1075
1076         /*
1077          *      Starting with the home server we chose, loop through
1078          *      all home servers.  If the current one is dead, skip
1079          *      it.  If it is too busy, skip it.
1080          *
1081          *      Otherwise, use it.
1082          */
1083         for (count = 0; count < pool->num_home_servers; count++) {
1084                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
1085
1086                 if (home->state == HOME_STATE_IS_DEAD) {
1087                         continue;
1088                 }
1089
1090                 /*
1091                  *      This home server is too busy.  Choose another one.
1092                  */
1093                 if (home->currently_outstanding >= home->max_outstanding) {
1094                         continue;
1095                 }
1096
1097                 if (pool->type != HOME_POOL_LOAD_BALANCE) {
1098                         return home;
1099                 }
1100
1101                 DEBUG3("PROXY %s %d\t%s %d",
1102                        found->name, found->currently_outstanding,
1103                        home->name, home->currently_outstanding);
1104
1105                 /*
1106                  *      Prefer this server if it's less busy than the
1107                  *      one we previously found.
1108                  */
1109                 if (home->currently_outstanding < found->currently_outstanding) {
1110                         DEBUG3("Choosing %s: It's less busy than %s",
1111                                home->name, found->name);
1112                         found = home;
1113                         continue;
1114                 }
1115
1116                 /*
1117                  *      Ignore servers which are busier than the one
1118                  *      we found.
1119                  */
1120                 if (home->currently_outstanding > found->currently_outstanding) {
1121                         DEBUG3("Skipping %s: It's busier than %s",
1122                                home->name, found->name);
1123                         continue;
1124                 }
1125
1126                 /*
1127                  *      From the list of servers which have the same
1128                  *      load, choose one at random.
1129                  */
1130                 if (((count + 1) * (lrad_rand() & 0xffff)) < (uint32_t) 0x10000) {
1131                         found = home;
1132                 }
1133
1134         } /* loop over the home servers */
1135
1136         if (found) return found;
1137
1138         /*
1139          *      No live match found, and no fallback to the "DEFAULT"
1140          *      realm.  We fix this by blindly marking all servers as
1141          *      "live".  But only do it for ones that don't support
1142          *      "pings", as they will be marked live when they
1143          *      actually are live.
1144          */
1145         if (!mainconfig.proxy_fallback &&
1146             mainconfig.wake_all_if_all_dead) {
1147                 home_server *lb = NULL;
1148
1149                 for (count = 0; count < pool->num_home_servers; count++) {
1150                         home_server *home = pool->servers[count];
1151
1152                         if ((home->state == HOME_STATE_IS_DEAD) &&
1153                             (home->ping_check == HOME_PING_CHECK_NONE)) {
1154                                 home->state = HOME_STATE_ALIVE;
1155                                 if (!lb) lb = home;
1156                         }
1157                 }
1158
1159                 if (lb) return lb;
1160         }
1161
1162         /*
1163          *      Still nothing.  Look up the DEFAULT realm, but only
1164          *      if we weren't looking up the NULL or DEFAULT realms.
1165          */
1166         if (mainconfig.proxy_fallback &&
1167             realmname &&
1168             (strcmp(realmname, "NULL") != 0) &&
1169             (strcmp(realmname, "DEFAULT") != 0)) {
1170                 REALM *rd = realm_find("DEFAULT");
1171
1172                 if (!rd) return NULL;
1173
1174                 pool = NULL;
1175                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1176                         pool = rd->auth_pool;
1177                         
1178                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1179                         pool = rd->acct_pool;
1180                 }
1181                 if (!pool) return NULL;
1182
1183                 DEBUG2("  Realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
1184                 return home_server_ldb(rd->name, pool, request);
1185         }
1186
1187         /*
1188          *      Still haven't found anything.  Oh well.
1189          */
1190         return NULL;
1191 }
1192
1193
1194 home_server *home_server_find(lrad_ipaddr_t *ipaddr, int port)
1195 {
1196         home_server myhome;
1197
1198         myhome.ipaddr = *ipaddr;
1199         myhome.port = port;
1200
1201         return rbtree_finddata(home_servers_byaddr, &myhome);
1202 }