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