rad_panic never returns
[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                 static LRAD_NAME_NUMBER pool_types[] = {
448                         { "load-balance", HOME_POOL_LOAD_BALANCE },
449                         { "fail-over", HOME_POOL_FAIL_OVER },
450                         { "round_robin", HOME_POOL_LOAD_BALANCE },
451                         { "fail_over", HOME_POOL_FAIL_OVER },
452                         { "client-balance", HOME_POOL_CLIENT_BALANCE },
453                         { NULL, 0 }
454                 };
455
456                 value = cf_pair_value(cp);
457                 if (!value) {
458                         radlog(L_ERR, "%s[%d]: No value given for type.",
459                                filename, cf_pair_lineno(cp));
460                         free(pool);
461                         return 0;
462                 }
463
464                 pool->type = lrad_str2int(pool_types, value, 0);
465                 if (!pool->type) {
466                         radlog(L_ERR, "%s[%d]: Unknown type \"%s\".",
467                                filename, cf_pair_lineno(cp), value);
468                         free(pool);
469                         return 0;
470                 }
471
472                 DEBUG2(" server_pool %s: type = %s", name2, value);
473         }
474
475         for (cp = cf_pair_find(cs, "home_server");
476              cp != NULL;
477              cp = cf_pair_find_next(cs, cp, "home_server")) {
478                 home_server myhome, *home;
479
480                 value = cf_pair_value(cp);
481                 if (!value) {
482                         radlog(L_ERR, "%s[%d]: No value given for home_server.",
483                                filename, cf_pair_lineno(cp));
484                         free(pool);
485                         return 0;
486                 }
487
488                 myhome.name = value;
489
490                 home = rbtree_finddata(home_servers_byname, &myhome);
491                 if (!home) {
492                         CONF_SECTION *server_cs;
493
494                         server_cs = cf_section_sub_find_name2(NULL,
495                                                               "home_server",
496                                                               value);
497                         if (!server_cs) {
498                                 radlog(L_ERR, "%s[%d]: Unknown home_server \"%s\".",
499                                        filename, cf_pair_lineno(cp), value);
500                                 free(pool);
501                                 return 0;
502                         }
503                         
504                         if (!home_server_add(filename, server_cs)) {
505                                 free(pool);
506                                 return 0;
507                         }
508
509                         home = rbtree_finddata(home_servers_byname, &myhome);
510                         if (!home) {
511                                 rad_assert("Internal sanity check failed");
512                                 return 0;
513                         }
514                 }
515
516                 if (!pool->server_type) {
517                         rad_assert(home->type != 0);
518                         pool->server_type = home->type;
519
520                 } else if (pool->server_type != home->type) {
521                         radlog(L_ERR, "%s[%d]: Home server \"%s\" is not of the same type as previous servers in server pool %s",
522                                filename, cf_pair_lineno(cp), value, pool->name);
523                         free(pool);
524                         return 0;
525                 }
526
527                 if (0) {
528                         DEBUG2("Warning: Duplicate home server %s in server pool %s", home->name, pool->name);
529                         continue;
530                 }
531
532                 DEBUG2(" server_pool %s: home_server = %s", name2, home->name);
533                 pool->servers[pool->num_home_servers] = home;
534                 pool->num_home_servers++;
535
536         } /* loop over home_server's */
537
538         if (!rbtree_insert(home_pools_byname, pool)) {
539                 rad_assert("Internal sanity check failed");
540                 return 0;
541         }
542
543         rad_assert(pool->server_type != 0);
544         
545         return 1;
546 }
547
548
549 static int old_server_add(const char *filename, int lineno,
550                           const char *name, const char *secret,
551                           home_pool_type_t ldflag, home_pool_t **pool_p,
552                           int type)
553 {
554         int i, insert_point, num_home_servers;
555         home_server myhome, *home;
556         home_pool_t mypool, *pool;
557         CONF_SECTION *cs;
558
559         /*
560          *      LOCAL realms get sanity checked, and nothing else happens.
561          */
562         if (strcmp(name, "LOCAL") == 0) {
563                 if (*pool_p) {
564                         radlog(L_ERR, "%s[%d]: Realm \"%s\" cannot be both LOCAL and remote", filename, lineno, name);
565                         return 0;
566                 }
567                 return 1;
568         }
569
570         mypool.name = name;
571         pool = rbtree_finddata(home_pools_byname, &mypool);
572         if (pool) {
573                 if (pool->type != ldflag) {
574                         radlog(L_ERR, "%s[%d]: Inconsistent ldflag for server pool \"%s\"", filename, lineno, name);
575                         return 0;
576                 }
577
578                 if (pool->server_type != type) {
579                         radlog(L_ERR, "%s[%d]: Inconsistent home server type for server pool \"%s\"", filename, lineno, name);
580                         return 0;
581                 }
582         }
583
584         myhome.name = name;
585         home = rbtree_finddata(home_servers_byname, &myhome);
586         if (home) {
587                 if (strcmp(home->secret, secret) != 0) {
588                         radlog(L_ERR, "%s[%d]: Inconsistent shared secret for home server \"%s\"", filename, lineno, name);
589                         return 0;
590                 }
591
592                 if (home->type != type) {
593                         radlog(L_ERR, "%s[%d]: Inconsistent type for home server \"%s\"", filename, lineno, name);
594                         return 0;
595                 }
596                 
597                 /*
598                  *      See if the home server is already listed
599                  *      in the pool.  If so, do nothing else.
600                  */
601                 if (pool) for (i = 0; i < pool->num_home_servers; i++) {
602                         if (pool->servers[i] == home) {
603                                 return 1;
604                         }
605                 }
606         }
607
608         /*
609          *      If we do have a pool, check that there is room to
610          *      insert the home server we've found, or the one that we
611          *      create here.
612          *
613          *      Note that we insert it into the LAST available
614          *      position, in order to maintain the same order as in
615          *      the configuration files.
616          */
617         insert_point = -1;
618         if (pool) {
619                 for (i = pool->num_home_servers - 1; i >= 0; i--) {
620                         if (pool->servers[i]) break;
621
622                         if (!pool->servers[i]) {
623                                 insert_point = i;
624                         }
625                 }
626
627                 if (insert_point < 0) {
628                         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);
629                         return 0;
630                 }
631         }
632
633         /*
634          *      No home server, allocate one.
635          */
636         if (!home) {         
637                 const char *p;
638                 char *q;
639
640                 home = rad_malloc(sizeof(*home));
641                 memset(home, 0, sizeof(*home));
642
643                 home->name = name;
644                 home->hostname = name;
645                 home->type = type;
646                 home->secret = secret;
647
648                 p = strchr(name, ':');
649                 if (!p) {
650                         if (type == HOME_TYPE_AUTH) {
651                                 home->port = PW_AUTH_UDP_PORT;
652                         } else {
653                                 home->port = PW_ACCT_UDP_PORT;
654                         }
655
656                         p = name;
657                         q = NULL;
658
659                 } else if (p == name) {
660                                 radlog(L_ERR, "%s[%d]: Invalid hostname %s.",
661                                        filename, lineno, name);
662                                 free(home);
663                                 return 0;
664
665                 } else {
666                         home->port = atoi(p + 1);
667                         if ((home->port == 0) || (home->port > 65535)) {
668                                 radlog(L_ERR, "%s[%d]: Invalid port %s.",
669                                        filename, lineno, p + 1);
670                                 free(home);
671                                 return 0;
672                         }
673
674                         q = rad_malloc((p - name) + 1);
675                         memcpy(q, name, (p - name));
676                         q[p - name] = '\0';
677                         p = q;
678                 }
679
680                 if (ip_hton(p, AF_UNSPEC, &home->ipaddr) < 0) {
681                         radlog(L_ERR, "%s[%d]: Failed looking up hostname %s.",
682                                filename, lineno, p);
683                         free(home);
684                         free(q);
685                         return 0;
686                 }
687                 free(q);
688
689                 /*
690                  *      Use the old-style configuration.
691                  */
692                 home->max_outstanding = 65535*16;
693                 home->zombie_period = mainconfig.proxy_retry_delay * mainconfig.proxy_retry_count;
694                 if (home->zombie_period == 0) home->zombie_period =30;
695                 home->response_window = home->zombie_period - 1;
696
697                 home->ping_check = HOME_PING_CHECK_NONE;
698
699                 home->revive_interval = mainconfig.proxy_dead_time;
700
701                 if (rbtree_finddata(home_servers_byaddr, home)) {
702                         radlog(L_ERR, "%s[%d]: Home server %s has the same IP address as another home server.",
703                                filename, lineno, name);
704                         free(home);
705                         return 0;
706                 }
707
708                 if (!rbtree_insert(home_servers_byname, home)) {
709                         radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
710                                filename, lineno, name);
711                         free(home);
712                         return 0;
713                 }
714                 
715                 if (!rbtree_insert(home_servers_byaddr, home)) {
716                         rbtree_deletebydata(home_servers_byname, home);
717                         radlog(L_ERR, "%s[%d]: Internal error adding home server %s.",
718                                filename, lineno, name);
719                         free(home);
720                         return 0;
721                 }
722         }
723
724         /*
725          *      We now have a home server, see if we can insert it
726          *      into pre-existing pool.
727          */
728         if (insert_point >= 0) {
729                 rad_assert(pool != NULL);
730                 pool->servers[insert_point] = home;
731                 return 1;
732         }
733
734         rad_assert(pool == NULL);
735         rad_assert(home != NULL);
736
737         /*
738          *      Count the old-style realms of this name.
739          */
740         num_home_servers = 0;
741         for (cs = cf_section_sub_find_name2(mainconfig.config, "realm", name);
742              cs != NULL;
743              cs = cf_section_sub_find_name2(cs, "realm", name)) {
744                 num_home_servers++;
745         }
746
747
748         pool = rad_malloc(sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
749         memset(pool, 0, sizeof(*pool) + num_home_servers * sizeof(pool->servers[0]));
750
751         pool->name = name;
752         pool->type = ldflag;
753         pool->server_type = type;
754         pool->num_home_servers = num_home_servers;
755         pool->servers[0] = home;
756
757         if (!rbtree_insert(home_pools_byname, pool)) {
758                 rad_assert("Internal sanity check failed");
759                 return 0;
760         }
761
762         *pool_p = pool;
763
764         return 1;
765 }
766
767 static int old_realm_config(const char *filename, CONF_SECTION *cs, REALM *r)
768 {
769         char *host;
770         const char *secret;
771         home_pool_type_t ldflag;
772
773         secret = cf_section_value_find(cs, "secret");
774
775         host = cf_section_value_find(cs, "ldflag");
776         if (!host ||
777             (strcasecmp(host, "fail_over") == 0)) {
778                 ldflag = HOME_POOL_FAIL_OVER;
779                 DEBUG2("  realm %s: ldflag = fail_over", r->name);
780
781         } else if (strcasecmp(host, "round_robin") == 0) {
782                 ldflag = HOME_POOL_LOAD_BALANCE;
783                 DEBUG2("  realm %s: ldflag = round_robin", r->name);
784
785         } else {
786                 radlog(L_ERR, "%s[%d]: Unknown value \"%s\" for ldflag",
787                        filename, cf_section_lineno(cs), host);
788                 return 0;
789         }
790
791         /*
792          *      Allow old-style if it doesn't exist, or if it exists and
793          *      it's LOCAL.
794          */
795         if (((host = cf_section_value_find(cs, "authhost")) != NULL) &&
796             (strcmp(host, "LOCAL") != 0)) {
797                 if (!secret) {
798                         radlog(L_ERR, "%s[%d]: No shared secret supplied for realm: %s",
799                                filename, cf_section_lineno(cs), r->name);
800                         return 0;
801                 }
802
803                 DEBUG2("  realm %s: authhost = %s",  r->name, host);
804
805                 if (!old_server_add(filename, cf_section_lineno(cs),
806                                     host, secret, ldflag,
807                                     &r->auth_pool, HOME_TYPE_AUTH)) {
808                         return 0;
809                 }
810         }
811
812         if (((host = cf_section_value_find(cs, "accthost")) != NULL) &&
813             (strcmp(host, "LOCAL") != 0)) {
814                 if (!secret) {
815                         radlog(L_ERR, "%s[%d]: No shared secret supplied for realm: %s",
816                                filename, cf_section_lineno(cs), r->name);
817                         return 0;
818                 }
819
820                 DEBUG2("  realm %s: accthost = %s", r->name, host);
821
822                 if (!old_server_add(filename, cf_section_lineno(cs),
823                                     host, secret, ldflag,
824                                     &r->auth_pool, HOME_TYPE_ACCT)) {
825                         return 0;
826                 }
827         }
828
829         if (secret) DEBUG2("  realm %s: secret = %s", r->name, secret);
830
831         return 1;
832         
833 }
834
835
836 static int add_pool_to_realm(const char *filename, int lineno,
837                              const char *name, home_pool_t **dest,
838                              int server_type)
839 {
840         home_pool_t mypool, *pool;
841
842         mypool.name = name;
843         pool = rbtree_finddata(home_pools_byname, &mypool);
844         if (!pool) {
845                 CONF_SECTION *pool_cs;
846
847                 pool_cs = cf_section_sub_find_name2(NULL, "server_pool",
848                                                     name);
849                 if (!pool_cs) {
850                         radlog(L_ERR, "%s[%d]: Failed to find server_pool \"%s\"",
851                                filename, lineno, name);
852                         return 0;
853                 }
854
855                 if (!server_pool_add(filename, pool_cs)) {
856                         return 0;
857                 }
858                 
859                 pool = rbtree_finddata(home_pools_byname, &mypool);
860                 if (!pool) {
861                         rad_assert("Internal sanity check failed");
862                         return 0;
863                 }
864         }
865
866         if (pool->server_type != server_type) {
867                 radlog(L_ERR, "%s[%d]: Incompatible server_pool \"%s\" (mixed auth_pool / acct_pool)",
868                        filename, lineno, name);
869                 return 0;
870         }
871
872         *dest = pool;
873
874         return 1;
875 }
876
877 int realm_add(const char *filename, CONF_SECTION *cs)
878 {
879         const char *name2;
880         char *pool = NULL;
881         REALM *r;
882         CONF_PAIR *cp;
883
884         name2 = cf_section_name1(cs);
885         if (!name2 || (strcasecmp(name2, "realm") != 0)) {
886                 radlog(L_ERR, "%s[%d]: Section is not a realm.",
887                        filename, cf_section_lineno(cs));
888                 return 0;
889         }
890
891         name2 = cf_section_name2(cs);
892         if (!name2) {
893                 radlog(L_ERR, "%s[%d]: Realm section is missing the realm name.",
894                        filename, cf_section_lineno(cs));
895                 return 0;
896         }
897
898         /*
899          *      The realm MAY already exist if it's an old-style realm.
900          *      In that case, merge the old-style realm with this one.
901          */
902         r = realm_find(name2);
903         if (r) {
904                 if (cf_pair_find(cs, "auth_pool") ||
905                     cf_pair_find(cs, "acct_pool")) {
906                         radlog(L_ERR, "%s[%d]: Duplicate realm \"%s\"",
907                                filename, cf_section_lineno(cs), name2);
908                         return 0;
909                 }
910
911                 if (!old_realm_config(filename, cs, r)) {
912                         return 0;
913                 }
914
915                 return 1;
916         }
917
918         r = rad_malloc(sizeof(*r));
919         memset(r, 0, sizeof(*r));
920
921         r->name = name2;
922
923         /*
924          *      Prefer new configuration to old one.
925          */
926         cp = cf_pair_find(cs, "auth_pool");
927         if (cp) pool = cf_pair_value(cp);
928         if (cp && pool) {
929                 if (!add_pool_to_realm(filename, cf_pair_lineno(cp),
930                                        pool, &r->auth_pool, HOME_TYPE_AUTH)) {
931                         free(r);
932                         return 0;
933                 }
934                 DEBUG2(" realm %s: auth_pool = %s", name2, pool);
935         }
936
937         cp = cf_pair_find(cs, "acct_pool");
938         if (cp) pool = cf_pair_value(cp);
939         if (cp && pool) {
940                 if (!add_pool_to_realm(filename, cf_pair_lineno(cp),
941                                        pool, &r->acct_pool, HOME_TYPE_ACCT)) {
942                         free(r);
943                         return 0;
944                 }
945                 DEBUG2(" realm %s: acct_pool = %s", name2, pool);
946         }
947
948         r->striprealm = 1;
949         
950         if ((cf_section_value_find(cs, "nostrip")) != NULL) {
951                 r->striprealm = 0;
952                 DEBUG2(" realm %s: nostrip", name2);
953         }
954
955         /*
956          *      We're a new-style realm.  Complain if we see the old
957          *      directives.
958          */
959         if (r->auth_pool || r->acct_pool) {
960                 if (((cp = cf_pair_find(cs, "authhost")) != NULL) ||
961                     ((cp = cf_pair_find(cs, "accthost")) != NULL) ||
962                     ((cp = cf_pair_find(cs, "secret")) != NULL) ||
963                     ((cp = cf_pair_find(cs, "ldflag")) != NULL)) {
964                         DEBUG2("WARNING: Ignoring old-style configuration entry \"%s\" in realm \"%s\"", cf_pair_attr(cp), r->name);
965                 }
966
967
968                 /*
969                  *      The realm MAY be an old-style realm, as there
970                  *      was no auth_pool or acct_pool.  Double-check
971                  *      it, just to be safe.
972                  */
973         } else if (!old_realm_config(filename, cs, r)) {
974                 free(r);
975                 return 0;
976         }
977
978         if (!rbtree_insert(realms_byname, r)) {
979                 rad_assert("Internal sanity check failed");
980                 free(r);
981                 return 0;
982         }
983
984         return 1;
985 }
986
987
988 /*
989  *      Find a realm in the REALM list.
990  */
991 REALM *realm_find(const char *name)
992 {
993         REALM myrealm;
994
995         if (!name) name = "NULL";
996
997         myrealm.name = name;
998         return rbtree_finddata(realms_byname, &myrealm);
999 }
1000
1001
1002 home_server *home_server_ldb(const char *realmname,
1003                              home_pool_t *pool, REQUEST *request)
1004 {
1005         int             start;
1006         int             count;
1007
1008         start = 0;
1009
1010         /*
1011          *      Determine how to pick choose the home server.
1012          */
1013         switch (pool->type) {
1014                 uint32_t hash;
1015
1016                 /*
1017                  *      Load balancing.  Pick one at random.
1018                  */
1019         case HOME_POOL_LOAD_BALANCE:
1020                 hash = lrad_rand();
1021                 start = hash % pool->num_home_servers;
1022                 break;
1023
1024                 /*
1025                  *      For load-balancing by client IP address, we
1026                  *      pick a home server by hashing the client IP.
1027                  *
1028                  *      This isn't as even a load distribution as
1029                  *      tracking the State attribute, but it's better
1030                  *      than nothing.
1031                  */
1032         case HOME_POOL_CLIENT_BALANCE:
1033                 switch (request->packet->src_ipaddr.af) {
1034                 case AF_INET:
1035                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip4addr,
1036                                          sizeof(request->packet->src_ipaddr.ipaddr.ip4addr));
1037                         break;
1038                 case AF_INET6:
1039                         hash = lrad_hash(&request->packet->src_ipaddr.ipaddr.ip6addr,
1040                                          sizeof(request->packet->src_ipaddr.ipaddr.ip6addr));
1041                         break;
1042                 default:
1043                         hash = 0;
1044                         break;
1045                 }
1046                 start = hash % pool->num_home_servers;
1047                 break;
1048
1049         default:
1050                 start = 0;
1051                 break;
1052         }
1053
1054         /*
1055          *      Starting with the home server we chose, loop through
1056          *      all home servers.  If the current one is dead, skip
1057          *      it.  If it is too busy, skip it.
1058          *
1059          *      Otherwise, use it.
1060          */
1061         for (count = 0; count < pool->num_home_servers; count++) {
1062                 home_server *home = pool->servers[(start + count) % pool->num_home_servers];
1063
1064                 if (home->state == HOME_STATE_IS_DEAD) {
1065                         continue;
1066                 }
1067
1068                 /*
1069                  *      This home server is too busy.  Choose another one.
1070                  */
1071                 if (home->currently_outstanding >= home->max_outstanding) {
1072                         continue;
1073                 }
1074
1075                 return home;
1076         } /* loop over the home servers */
1077
1078         /*
1079          *      No live match found, and no fallback to the "DEFAULT"
1080          *      realm.  We fix this by blindly marking all servers as
1081          *      "live".  But only do it for ones that don't support
1082          *      "pings", as they will be marked live when they
1083          *      actually are live.
1084          */
1085         if (!mainconfig.proxy_fallback &&
1086             mainconfig.wake_all_if_all_dead) {
1087                 home_server *lb = NULL;
1088
1089                 for (count = 0; count < pool->num_home_servers; count++) {
1090                         home_server *home = pool->servers[count];
1091
1092                         if ((home->state == HOME_STATE_IS_DEAD) &&
1093                             (home->ping_check == HOME_PING_CHECK_NONE)) {
1094                                 home->state = HOME_STATE_ALIVE;
1095                                 if (!lb) lb = home;
1096                         }
1097                 }
1098
1099                 if (lb) return lb;
1100         }
1101
1102         /*
1103          *      Still nothing.  Look up the DEFAULT realm, but only
1104          *      if we weren't looking up the NULL or DEFAULT realms.
1105          */
1106         if (mainconfig.proxy_fallback &&
1107             realmname &&
1108             (strcmp(realmname, "NULL") != 0) &&
1109             (strcmp(realmname, "DEFAULT") != 0)) {
1110                 REALM *rd = realm_find("DEFAULT");
1111
1112                 if (!rd) return NULL;
1113
1114                 pool = NULL;
1115                 if (request->packet->code == PW_AUTHENTICATION_REQUEST) {
1116                         pool = rd->auth_pool;
1117                         
1118                 } else if (request->packet->code == PW_ACCOUNTING_REQUEST) {
1119                         pool = rd->acct_pool;
1120                 }
1121                 if (!pool) return NULL;
1122
1123                 DEBUG2("  Realm %s has no live home servers.  Falling back to the DEFAULT realm.", realmname);
1124                 return home_server_ldb(rd->name, pool, request);
1125         }
1126
1127         /*
1128          *      Still haven't found anything.  Oh well.
1129          */
1130         return NULL;
1131 }
1132
1133
1134 home_server *home_server_find(lrad_ipaddr_t *ipaddr, int port)
1135 {
1136         home_server myhome;
1137
1138         myhome.ipaddr = *ipaddr;
1139         myhome.port = port;
1140
1141         return rbtree_finddata(home_servers_byaddr, &myhome);
1142 }