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