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