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